7257fc645d90e91a7909061ca012dd3771358ec5
[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] == '.') {
289         return;
290     }
291
292     if (strlen(name) > 8) {
293         saa_wbytes (strs, name, (long)(1+strlen(name)));
294         strslen += 1+strlen(name);
295     } else
296         pos = -1;
297
298     sym = saa_wstruct (syms);
299
300     sym->strpos = pos;
301     if (pos == -1)
302         strcpy (sym->name, name);
303     sym->is_global = !!is_global;
304     if (segment == NO_SEG)
305         sym->section = -1;      /* absolute symbol */
306     else {
307         int i;
308         sym->section = 0;
309         for (i=0; i<nsects; i++)
310             if (segment == sects[i]->index) {
311                 sym->section = i+1;
312                 break;
313             }
314         if (!sym->section)
315             sym->is_global = TRUE;
316     }
317     if (is_global == 2)
318         sym->value = offset;
319     else
320         sym->value = (sym->section == 0 ? 0 : offset);
321
322     /*
323      * define the references from external-symbol segment numbers
324      * to these symbol records.
325      */
326     if (sym->section == 0)
327         bsym = raa_write (bsym, segment, nsyms);
328
329     if (segment != NO_SEG)
330         symval = raa_write (symval, segment, sym->section ? 0 : sym->value);
331
332     nsyms++;
333 }
334
335 static long coff_add_reloc (struct Section *sect, long segment,
336                             int relative) {
337     struct Reloc *r;
338
339     r = *sect->tail = nasm_malloc(sizeof(struct Reloc));
340     sect->tail = &r->next;
341     r->next = NULL;
342
343     r->address = sect->len;
344     if (segment == NO_SEG)
345         r->symbol = 0, r->symbase = ABS_SYMBOL;
346     else {
347         int i;
348         r->symbase = REAL_SYMBOLS;
349         for (i=0; i<nsects; i++)
350             if (segment == sects[i]->index) {
351                 r->symbol = i*2;
352                 r->symbase = SECT_SYMBOLS;
353                 break;
354             }
355         if (r->symbase == REAL_SYMBOLS)
356             r->symbol = raa_read (bsym, segment);
357     }
358     r->relative = relative;
359
360     sect->nrelocs++;
361
362     /*
363      * Return the fixup for standard COFF common variables.
364      */
365     if (r->symbase == REAL_SYMBOLS && !win32)
366         return raa_read (symval, segment);
367     else
368         return 0;
369 }
370
371 static void coff_out (long segto, void *data, unsigned long type,
372                       long segment, long wrt) {
373     struct Section *s;
374     long realbytes = type & OUT_SIZMASK;
375     unsigned char mydata[4], *p;
376     int i;
377
378     if (wrt != NO_SEG) {
379         wrt = NO_SEG;                  /* continue to do _something_ */
380         error (ERR_NONFATAL, "WRT not supported by COFF output formats");
381     }
382
383     type &= OUT_TYPMASK;
384
385     /*
386      * handle absolute-assembly (structure definitions)
387      */
388     if (segto == NO_SEG) {
389         if (type != OUT_RESERVE)
390             error (ERR_NONFATAL, "attempt to assemble code in [ABSOLUTE]"
391                    " space");
392         return;
393     }
394
395     s = NULL;
396     for (i=0; i<nsects; i++)
397         if (segto == sects[i]->index) {
398             s = sects[i];
399             break;
400         }
401     if (!s) {
402         int tempint;                   /* ignored */
403         if (segto != coff_section_names (".text", 2, &tempint))
404             error (ERR_PANIC, "strange segment conditions in COFF driver");
405         else
406             s = sects[nsects-1];
407     }
408
409     if (!s->data && type != OUT_RESERVE) {
410         error(ERR_WARNING, "attempt to initialise memory in"
411               " BSS section `%s': ignored", s->name);
412         if (type == OUT_REL2ADR)
413             realbytes = 2;
414         else if (type == OUT_REL4ADR)
415             realbytes = 4;
416         s->len += realbytes;
417         return;
418     }
419
420     if (type == OUT_RESERVE) {
421         if (s->data) {
422             error(ERR_WARNING, "uninitialised space declared in"
423                   " non-BSS section `%s': zeroing", s->name);
424             coff_sect_write (s, NULL, realbytes);
425         } else
426             s->len += realbytes;
427     } else if (type == OUT_RAWDATA) {
428         if (segment != NO_SEG)
429             error(ERR_PANIC, "OUT_RAWDATA with other than NO_SEG");
430         coff_sect_write (s, data, realbytes);
431     } else if (type == OUT_ADDRESS) {
432         if (realbytes == 2 && (segment != NO_SEG || wrt != NO_SEG))
433             error(ERR_NONFATAL, "COFF format does not support 16-bit"
434                   " relocations");
435         else {
436             long fix = 0;
437             if (segment != NO_SEG || wrt != NO_SEG) {
438                 if (wrt != NO_SEG) {
439                     error(ERR_NONFATAL, "COFF format does not support"
440                           " WRT types");
441                 } else if (segment % 2) {
442                     error(ERR_NONFATAL, "COFF format does not support"
443                           " segment base references");
444                 } else
445                     fix = coff_add_reloc (s, segment, FALSE);
446             }
447             p = mydata;
448             WRITELONG (p, *(long *)data + fix);
449             coff_sect_write (s, mydata, realbytes);
450         }
451     } else if (type == OUT_REL2ADR) {
452         error(ERR_NONFATAL, "COFF format does not support 16-bit"
453               " relocations");
454     } else if (type == OUT_REL4ADR) {
455         if (segment == segto)
456             error(ERR_PANIC, "intra-segment OUT_REL4ADR");
457         else if (segment == NO_SEG && win32)
458             error(ERR_NONFATAL, "Win32 COFF does not correctly support"
459                   " relative references to absolute addresses");
460         else {
461             long fix = 0;
462             if (segment != NO_SEG && segment % 2) {
463                 error(ERR_NONFATAL, "COFF format does not support"
464                       " segment base references");
465             } else
466                 fix = coff_add_reloc (s, segment, TRUE);
467             p = mydata;
468             if (win32) {
469                 WRITELONG (p, *(long*)data + 4 - realbytes + fix);
470             } else {
471                 WRITELONG (p, *(long*)data-(realbytes + s->len) + fix);
472             }
473             coff_sect_write (s, mydata, 4L);
474         }
475     }
476 }
477
478 static void coff_sect_write (struct Section *sect,
479                              unsigned char *data, unsigned long len) {
480     saa_wbytes (sect->data, data, len);
481     sect->len += len;
482 }
483
484 static int coff_directives (char *directive, char *value, int pass) {
485     return 0;
486 }
487
488 static void coff_write (void) {
489     long pos, sympos, vsize;
490     int i;
491
492     /*
493      * Work out how big the file will get. Calculate the start of
494      * the `real' symbols at the same time.
495      */
496     pos = 0x14 + 0x28 * nsects;
497     initsym = 3;                       /* two for the file, one absolute */
498     for (i=0; i<nsects; i++) {
499         if (sects[i]->data) {
500             sects[i]->pos = pos;
501             pos += sects[i]->len;
502             sects[i]->relpos = pos;
503             pos += 10 * sects[i]->nrelocs;
504         } else
505             sects[i]->pos = sects[i]->relpos = 0L;
506         initsym += 2;                  /* two for each section */
507     }
508     sympos = pos;
509
510     /*
511      * Output the COFF header.
512      */
513     fwriteshort (0x14C, coffp);        /* MACHINE_i386 */
514     fwriteshort (nsects, coffp);       /* number of sections */
515     fwritelong (time(NULL), coffp);    /* time stamp */
516     fwritelong (sympos, coffp);
517     fwritelong (nsyms + initsym, coffp);
518     fwriteshort (0, coffp);            /* no optional header */
519     /* Flags: 32-bit, no line numbers. Win32 doesn't even bother with them. */
520     fwriteshort (win32 ? 0 : 0x104, coffp);
521
522     /*
523      * Output the section headers.
524      */
525     vsize = 0L;
526     for (i=0; i<nsects; i++) {
527         coff_section_header (sects[i]->name, vsize, sects[i]->len,
528                              sects[i]->pos, sects[i]->relpos,
529                              sects[i]->nrelocs, sects[i]->flags);
530         vsize += sects[i]->len;
531     }
532
533     /*
534      * Output the sections and their relocations.
535      */
536     for (i=0; i<nsects; i++)
537         if (sects[i]->data) {
538             saa_fpwrite (sects[i]->data, coffp);
539             coff_write_relocs (sects[i]);
540         }
541
542     /*
543      * Output the symbol and string tables.
544      */
545     coff_write_symbols();
546     fwritelong (strslen+4, coffp);     /* length includes length count */
547     saa_fpwrite (strs, coffp);
548 }
549
550 static void coff_section_header (char *name, long vsize,
551                                  long datalen, long datapos,
552                                  long relpos, int nrelocs, long flags) {
553     char padname[8];
554
555     memset (padname, 0, 8);
556     strncpy (padname, name, 8);
557     fwrite (padname, 8, 1, coffp);
558     fwritelong (vsize, coffp);
559     fwritelong (0L, coffp);            /* RVA/offset - we ignore */
560     fwritelong (datalen, coffp);
561     fwritelong (datapos, coffp);
562     fwritelong (relpos, coffp);
563     fwritelong (0L, coffp);            /* no line numbers - we don't do 'em */
564     fwriteshort (nrelocs, coffp);
565     fwriteshort (0, coffp);            /* again, no line numbers */
566     fwritelong (flags, coffp);
567 }
568
569 static void coff_write_relocs (struct Section *s) {
570     struct Reloc *r;
571
572     for (r = s->head; r; r = r->next) {
573         fwritelong (r->address, coffp);
574         fwritelong (r->symbol + (r->symbase == REAL_SYMBOLS ? initsym :
575                                  r->symbase == ABS_SYMBOL ? initsym-1 :
576                                  r->symbase == SECT_SYMBOLS ? 2 : 0), coffp);
577         /*
578          * Strange: Microsoft's COFF documentation says 0x03 for an
579          * absolute relocation, but both Visual C++ and DJGPP agree
580          * that in fact it's 0x06. I'll use 0x06 until someone
581          * argues.
582          */
583         fwriteshort (r->relative ? 0x14 : 0x06, coffp);
584     }
585 }
586
587 static void coff_symbol (char *name, long strpos, long value,
588                          int section, int type, int aux) {
589     char padname[8];
590
591     if (name) {
592         memset (padname, 0, 8);
593         strncpy (padname, name, 8);
594         fwrite (padname, 8, 1, coffp);
595     } else {
596         fwritelong (0L, coffp);
597         fwritelong (strpos, coffp);
598     }
599     fwritelong (value, coffp);
600     fwriteshort (section, coffp);
601     fwriteshort (0, coffp);
602     fputc (type, coffp);
603     fputc (aux, coffp);
604 }
605
606 static void coff_write_symbols (void) {
607     char filename[18];
608     int i;
609
610     /*
611      * The `.file' record, and the file name auxiliary record.
612      */
613     coff_symbol (".file", 0L, 0L, -2, 0x67, 1);
614     memset (filename, 0, 18);
615     strncpy (filename, coff_infile, 18);
616     fwrite (filename, 18, 1, coffp);
617
618     /*
619      * The section records, with their auxiliaries.
620      */
621     memset (filename, 0, 18);          /* useful zeroed buffer */
622
623     for (i=0; i<nsects; i++) {
624         coff_symbol (sects[i]->name, 0L, 0L, i+1, 3, 1);
625         fwritelong (sects[i]->len, coffp);
626         fwriteshort (sects[i]->nrelocs, coffp);
627         fwrite (filename, 12, 1, coffp);
628     }
629
630     /*
631      * The absolute symbol, for relative-to-absolute relocations.
632      */
633     coff_symbol (".absolut", 0L, 0L, -1, 3, 0);
634
635     /*
636      * The real symbols.
637      */
638     saa_rewind (syms);
639     for (i=0; i<nsyms; i++) {
640         struct Symbol *sym = saa_rstruct (syms);
641         coff_symbol (sym->strpos == -1 ? sym->name : NULL,
642                      sym->strpos, sym->value, sym->section,
643                      sym->is_global ? 2 : 3, 0);
644     }
645 }
646
647 static long coff_segbase (long segment) {
648     return segment;
649 }
650
651 static void coff_std_filename (char *inname, char *outname, efunc error) {
652     strcpy(coff_infile, inname);
653     standard_extension (inname, outname, ".o", error);
654 }
655
656 static void coff_win32_filename (char *inname, char *outname, efunc error) {
657     strcpy(coff_infile, inname);
658     standard_extension (inname, outname, ".obj", error);
659 }
660
661 #endif /* defined(OF_COFF) || defined(OF_WIN32) */
662
663 #ifdef OF_COFF
664
665 struct ofmt of_coff = {
666     "COFF (i386) object files (e.g. DJGPP for DOS)",
667     "coff",
668     coff_std_init,
669     coff_out,
670     coff_deflabel,
671     coff_section_names,
672     coff_segbase,
673     coff_directives,
674     coff_std_filename,
675     coff_cleanup
676 };
677
678 #endif
679
680 #ifdef OF_WIN32
681
682 struct ofmt of_win32 = {
683     "Microsoft Win32 (i386) object files",
684     "win32",
685     coff_win32_init,
686     coff_out,
687     coff_deflabel,
688     coff_section_names,
689     coff_segbase,
690     coff_directives,
691     coff_win32_filename,
692     coff_cleanup
693 };
694
695 #endif