NASM 0.98.22
[platform/upstream/nasm.git] / outelf.c
1 /* outelf.c     output routines for the Netwide Assembler to produce
2  *              ELF32 (i386 of course) object file format
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
15 #include "nasm.h"
16 #include "nasmlib.h"
17 #include "outform.h"
18
19 #ifdef OF_ELF
20
21 /*
22  * Relocation types.
23  */
24 #define R_386_32 1                     /* ordinary absolute relocation */
25 #define R_386_PC32 2                   /* PC-relative relocation */
26 #define R_386_GOT32 3                  /* an offset into GOT */
27 #define R_386_PLT32 4                  /* a PC-relative offset into PLT */
28 #define R_386_GOTOFF 9                 /* an offset from GOT base */
29 #define R_386_GOTPC 10                 /* a PC-relative offset _to_ GOT */
30
31 struct Reloc {
32     struct Reloc *next;
33     long address;                      /* relative to _start_ of section */
34     long symbol;                       /* ELF symbol info thingy */
35     int type;                          /* type of relocation */
36 };
37
38 struct Symbol {
39     long strpos;                       /* string table position of name */
40     long section;                      /* section ID of the symbol */
41     int type;                          /* symbol type */
42     long value;                        /* address, or COMMON variable align */
43     long size;                         /* size of symbol */
44     long globnum;                      /* symbol table offset if global */
45     struct Symbol *next;               /* list of globals in each section */
46     struct Symbol *nextfwd;            /* list of unresolved-size symbols */
47     char *name;                        /* used temporarily if in above list */
48 };
49
50 #define SHT_PROGBITS 1
51 #define SHT_NOBITS 8
52
53 #define SHF_WRITE 1
54 #define SHF_ALLOC 2
55 #define SHF_EXECINSTR 4
56
57 struct Section {
58     struct SAA *data;
59     unsigned long len, size, nrelocs;
60     long index;
61     int type;                          /* SHT_PROGBITS or SHT_NOBITS */
62     int align;                         /* alignment: power of two */
63     unsigned long flags;               /* section flags */
64     char *name;
65     struct SAA *rel;
66     long rellen;
67     struct Reloc *head, **tail;
68     struct Symbol *gsyms;              /* global symbols in section */
69 };
70
71 #define SECT_DELTA 32
72 static struct Section **sects;
73 static int nsects, sectlen;
74
75 #define SHSTR_DELTA 256
76 static char *shstrtab;
77 static int shstrtablen, shstrtabsize;
78
79 static struct SAA *syms;
80 static unsigned long nlocals, nglobs;
81
82 static long def_seg;
83
84 static struct RAA *bsym;
85
86 static struct SAA *strs;
87 static unsigned long strslen;
88
89 static FILE *elffp;
90 static efunc error;
91 static evalfunc evaluate;
92
93 static struct Symbol *fwds;
94
95 static char elf_module[FILENAME_MAX];
96
97 extern struct ofmt of_elf;
98
99 #define SHN_ABS 0xFFF1
100 #define SHN_COMMON 0xFFF2
101 #define SHN_UNDEF 0
102
103 #define SYM_SECTION 0x04
104 #define SYM_GLOBAL 0x10
105 #define SYM_DATA 0x01
106 #define SYM_FUNCTION 0x02
107
108 #define GLOBAL_TEMP_BASE 15            /* bigger than any constant sym id */
109
110 #define SEG_ALIGN 16                   /* alignment of sections in file */
111 #define SEG_ALIGN_1 (SEG_ALIGN-1)
112
113 static const char align_str[SEG_ALIGN] = ""; /* ANSI will pad this with 0s */
114
115 #define ELF_MAX_SECTIONS 16            /* really 10, but let's play safe */
116 static struct ELF_SECTDATA {
117     void *data;
118     long len;
119     int is_saa;
120 } *elf_sects;
121 static int elf_nsect;
122 static long elf_foffs;
123
124 static void elf_write(void);
125 static void elf_sect_write(struct Section *, unsigned char *, unsigned long);
126 static void elf_section_header (int, int, int, void *, int, long,
127                                 int, int, int, int);
128 static void elf_write_sections (void);
129 static struct SAA *elf_build_symtab (long *, long *);
130 static struct SAA *elf_build_reltab (long *, struct Reloc *);
131 static void add_sectname (char *, char *);
132
133 /*
134  * Special section numbers which are used to define ELF special
135  * symbols, which can be used with WRT to provide PIC relocation
136  * types.
137  */
138 static long elf_gotpc_sect, elf_gotoff_sect;
139 static long elf_got_sect, elf_plt_sect;
140 static long elf_sym_sect;
141
142 static void elf_init(FILE *fp, efunc errfunc, ldfunc ldef, evalfunc eval) 
143 {
144     elffp = fp;
145     error = errfunc;
146     evaluate = eval;
147     (void) ldef;                       /* placate optimisers */
148     sects = NULL;
149     nsects = sectlen = 0;
150     syms = saa_init((long)sizeof(struct Symbol));
151     nlocals = nglobs = 0;
152     bsym = raa_init();
153     strs = saa_init(1L);
154     saa_wbytes (strs, "\0", 1L);
155     saa_wbytes (strs, elf_module, (long)(strlen(elf_module)+1));
156     strslen = 2+strlen(elf_module);
157     shstrtab = NULL;
158     shstrtablen = shstrtabsize = 0;;
159     add_sectname ("", "");
160
161     fwds = NULL;
162
163     elf_gotpc_sect = seg_alloc();
164     ldef("..gotpc", elf_gotpc_sect+1, 0L, NULL, FALSE, FALSE, &of_elf, error);
165     elf_gotoff_sect = seg_alloc();
166     ldef("..gotoff", elf_gotoff_sect+1, 0L, NULL, FALSE, FALSE,&of_elf,error);
167     elf_got_sect = seg_alloc();
168     ldef("..got", elf_got_sect+1, 0L, NULL, FALSE, FALSE, &of_elf, error);
169     elf_plt_sect = seg_alloc();
170     ldef("..plt", elf_plt_sect+1, 0L, NULL, FALSE, FALSE, &of_elf, error);
171     elf_sym_sect = seg_alloc();
172     ldef("..sym", elf_sym_sect+1, 0L, NULL, FALSE, FALSE, &of_elf, error);
173
174     def_seg = seg_alloc();
175 }
176
177 static void elf_cleanup(int debuginfo) 
178 {
179     struct Reloc *r;
180     int i;
181
182     (void) debuginfo;
183
184     elf_write();
185     fclose (elffp);
186     for (i=0; i<nsects; i++) {
187         if (sects[i]->type != SHT_NOBITS)
188             saa_free (sects[i]->data);
189         if (sects[i]->head)
190             saa_free (sects[i]->rel);
191         while (sects[i]->head) {
192             r = sects[i]->head;
193             sects[i]->head = sects[i]->head->next;
194             nasm_free (r);
195         }
196     }
197     nasm_free (sects);
198     saa_free (syms);
199     raa_free (bsym);
200     saa_free (strs);
201 }
202
203 static void add_sectname (char *firsthalf, char *secondhalf) 
204 {
205     int len = strlen(firsthalf)+strlen(secondhalf);
206     while (shstrtablen + len + 1 > shstrtabsize)
207         shstrtab = nasm_realloc (shstrtab, (shstrtabsize += SHSTR_DELTA));
208     strcpy (shstrtab+shstrtablen, firsthalf);
209     strcat (shstrtab+shstrtablen, secondhalf);
210     shstrtablen += len+1;
211 }
212
213 static int elf_make_section (char *name, int type, int flags, int align) 
214 {
215     struct Section *s;
216
217     s = nasm_malloc (sizeof(*s));
218
219     if (type != SHT_NOBITS)
220         s->data = saa_init (1L);
221     s->head = NULL;
222     s->tail = &s->head;
223     s->len = s->size = 0;
224     s->nrelocs = 0;
225     if (!strcmp(name, ".text"))
226         s->index = def_seg;
227     else
228         s->index = seg_alloc();
229     add_sectname ("", name);
230     s->name = nasm_malloc (1+strlen(name));
231     strcpy (s->name, name);
232     s->type = type;
233     s->flags = flags;
234     s->align = align;
235     s->gsyms = NULL;
236
237     if (nsects >= sectlen)
238         sects = nasm_realloc (sects, (sectlen += SECT_DELTA)*sizeof(*sects));
239     sects[nsects++] = s;
240
241     return nsects-1;
242 }
243
244 static long elf_section_names (char *name, int pass, int *bits) 
245 {
246     char *p;
247     int flags_and, flags_or, type, align, i;
248
249     /*
250      * Default is 32 bits.
251      */
252     if (!name) {
253         *bits = 32;
254         return def_seg;
255     }
256
257     p = name;
258     while (*p && !isspace(*p)) p++;
259     if (*p) *p++ = '\0';
260     flags_and = flags_or = type = align = 0;
261
262     while (*p && isspace(*p)) p++;
263     while (*p) {
264         char *q = p;
265         while (*p && !isspace(*p)) p++;
266         if (*p) *p++ = '\0';
267         while (*p && isspace(*p)) p++;
268         
269         if (!nasm_strnicmp(q, "align=", 6)) {
270             align = atoi(q+6);
271             if (align == 0)
272                 align = 1;
273             if ( (align-1) & align ) {   /* means it's not a power of two */
274                 error (ERR_NONFATAL, "section alignment %d is not"
275                        " a power of two", align);
276                 align = 1;
277             }
278         } else if (!nasm_stricmp(q, "alloc")) {
279             flags_and |= SHF_ALLOC;
280             flags_or |= SHF_ALLOC;
281         } else if (!nasm_stricmp(q, "noalloc")) {
282             flags_and |= SHF_ALLOC;
283             flags_or &= ~SHF_ALLOC;
284         } else if (!nasm_stricmp(q, "exec")) {
285             flags_and |= SHF_EXECINSTR;
286             flags_or |= SHF_EXECINSTR;
287         } else if (!nasm_stricmp(q, "noexec")) {
288             flags_and |= SHF_EXECINSTR;
289             flags_or &= ~SHF_EXECINSTR;
290         } else if (!nasm_stricmp(q, "write")) {
291             flags_and |= SHF_WRITE;
292             flags_or |= SHF_WRITE;
293         } else if (!nasm_stricmp(q, "nowrite")) {
294             flags_and |= SHF_WRITE;
295             flags_or &= ~SHF_WRITE;
296         } else if (!nasm_stricmp(q, "progbits")) {
297             type = SHT_PROGBITS;
298         } else if (!nasm_stricmp(q, "nobits")) {
299             type = SHT_NOBITS;
300         }
301     }
302
303     if (!strcmp(name, ".comment") ||
304         !strcmp(name, ".shstrtab") ||
305         !strcmp(name, ".symtab") ||
306         !strcmp(name, ".strtab")) {
307         error (ERR_NONFATAL, "attempt to redefine reserved section"
308                "name `%s'", name);
309         return NO_SEG;
310     }
311
312     for (i=0; i<nsects; i++)
313         if (!strcmp(name, sects[i]->name))
314             break;
315     if (i == nsects) {
316         if (!strcmp(name, ".text"))
317             i = elf_make_section (name, SHT_PROGBITS,
318                                   SHF_ALLOC | SHF_EXECINSTR, 16);
319         else if (!strcmp(name, ".data"))
320             i = elf_make_section (name, SHT_PROGBITS,
321                                   SHF_ALLOC | SHF_WRITE, 4);
322         else if (!strcmp(name, ".bss"))
323             i = elf_make_section (name, SHT_NOBITS,
324                                   SHF_ALLOC | SHF_WRITE, 4);
325         else
326             i = elf_make_section (name, SHT_PROGBITS, SHF_ALLOC, 1);
327         if (type)
328             sects[i]->type = type;
329         if (align)
330             sects[i]->align = align;
331         sects[i]->flags &= ~flags_and;
332         sects[i]->flags |= flags_or;
333     } else if (pass == 1) {
334         if (type || align || flags_and)
335             error (ERR_WARNING, "section attributes ignored on"
336                    " redeclaration of section `%s'", name);
337     }
338
339     return sects[i]->index;
340 }
341
342 static void elf_deflabel (char *name, long segment, long offset,
343                            int is_global, char *special) 
344 {
345     int pos = strslen;
346     struct Symbol *sym;
347     int special_used = FALSE;
348
349 #if defined(DEBUG) && DEBUG>2
350 fprintf(stderr, " elf_deflabel: %s, seg=%ld, off=%ld, is_global=%d, %s\n",
351       name, segment, offset, is_global, special);
352 #endif
353     if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
354         /*
355          * This is a NASM special symbol. We never allow it into
356          * the ELF symbol table, even if it's a valid one. If it
357          * _isn't_ a valid one, we should barf immediately.
358          */
359         if (strcmp(name, "..gotpc") && strcmp(name, "..gotoff") &&
360             strcmp(name, "..got") && strcmp(name, "..plt") &&
361             strcmp(name, "..sym"))
362             error (ERR_NONFATAL, "unrecognised special symbol `%s'", name);
363         return;
364     }
365
366     if (is_global == 3) {
367         struct Symbol **s;
368         /*
369          * Fix up a forward-reference symbol size from the first
370          * pass.
371          */
372         for (s = &fwds; *s; s = &(*s)->nextfwd)
373             if (!strcmp((*s)->name, name)) {
374                 struct tokenval tokval;
375                 expr *e;
376                 char *p = special;
377
378                 while (*p && !isspace(*p)) p++;
379                 while (*p && isspace(*p)) p++;
380                 stdscan_reset();
381                 stdscan_bufptr = p;
382                 tokval.t_type = TOKEN_INVALID;
383                 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
384                 if (e) {
385                     if (!is_simple(e))
386                         error (ERR_NONFATAL, "cannot use relocatable"
387                                " expression as symbol size");
388                     else
389                         (*s)->size = reloc_value(e);
390                 }
391
392                 /*
393                  * Remove it from the list of unresolved sizes.
394                  */
395                 nasm_free ((*s)->name);
396                 *s = (*s)->nextfwd;
397                 return;
398             }
399         return;                        /* it wasn't an important one */
400     }
401
402     saa_wbytes (strs, name, (long)(1+strlen(name)));
403     strslen += 1+strlen(name);
404
405     sym = saa_wstruct (syms);
406
407     sym->strpos = pos;
408     sym->type = is_global ? SYM_GLOBAL : 0;
409     sym->size = 0;
410     if (segment == NO_SEG)
411         sym->section = SHN_ABS;
412     else {
413         int i;
414         sym->section = SHN_UNDEF;
415         if (nsects == 0 && segment == def_seg) {
416             int tempint;
417             if (segment != elf_section_names (".text", 2, &tempint))
418                 error (ERR_PANIC, "strange segment conditions in ELF driver");
419             sym->section = nsects;
420         } else {
421             for (i=0; i<nsects; i++)
422                 if (segment == sects[i]->index) {
423                     sym->section = i+1;
424                     break;
425                 }
426         }
427     }
428
429     if (is_global == 2) {
430         sym->size = offset;
431         sym->value = 0;
432         sym->section = SHN_COMMON;
433         /*
434          * We have a common variable. Check the special text to see
435          * if it's a valid number and power of two; if so, store it
436          * as the alignment for the common variable.
437          */
438         if (special) {
439             int err;
440             sym->value = readnum (special, &err);
441             if (err)
442                 error(ERR_NONFATAL, "alignment constraint `%s' is not a"
443                       " valid number", special);
444             else if ( (sym->value | (sym->value-1)) != 2*sym->value - 1)
445                 error(ERR_NONFATAL, "alignment constraint `%s' is not a"
446                       " power of two", special);
447         }
448         special_used = TRUE;
449     } else
450         sym->value = (sym->section == SHN_UNDEF ? 0 : offset);
451
452     if (sym->type == SYM_GLOBAL) {
453         /*
454          * There's a problem here that needs fixing. 
455          * If sym->section == SHN_ABS, then the first line of the
456          * else section causes a core dump, because its a reference
457          * beyond the end of the section array.
458          * This behaviour is exhibited by this code:
459          *     GLOBAL crash_nasm
460          *     crash_nasm equ 0
461          *
462          * I'm not sure how to procede, because I haven't got the
463          * first clue about how ELF works, so I don't know what to
464          * do with it. Furthermore, I'm not sure what the rest of this
465          * section of code does. Help?
466          *
467          * For now, I'll see if doing absolutely nothing with it will
468          * work...
469          */
470         if (sym->section == SHN_UNDEF || sym->section == SHN_COMMON)
471         {
472             bsym = raa_write (bsym, segment, nglobs);
473         }
474         else if (sym->section != SHN_ABS) 
475         {
476             /*
477              * This is a global symbol; so we must add it to the linked
478              * list of global symbols in its section. We'll push it on
479              * the beginning of the list, because it doesn't matter
480              * much which end we put it on and it's easier like this.
481              *
482              * In addition, we check the special text for symbol
483              * type and size information.
484              */
485             sym->next = sects[sym->section-1]->gsyms;
486             sects[sym->section-1]->gsyms = sym;
487
488             if (special) {
489                 int n = strcspn(special, " ");
490
491                 if (!nasm_strnicmp(special, "function", n))
492                     sym->type |= SYM_FUNCTION;
493                 else if (!nasm_strnicmp(special, "data", n) ||
494                          !nasm_strnicmp(special, "object", n))
495                     sym->type |= SYM_DATA;
496                 else
497                     error(ERR_NONFATAL, "unrecognised symbol type `%.*s'",
498                           n, special);
499                 if (special[n]) {
500                     struct tokenval tokval;
501                     expr *e;
502                     int fwd = FALSE;
503                     char *saveme=stdscan_bufptr;   /* bugfix? fbk 8/10/00 */
504
505                     while (special[n] && isspace(special[n]))
506                         n++;
507                     /*
508                      * We have a size expression; attempt to
509                      * evaluate it.
510                      */
511                     stdscan_reset();
512                     stdscan_bufptr = special+n;
513                     tokval.t_type = TOKEN_INVALID;
514                     e = evaluate(stdscan, NULL, &tokval, &fwd, 0, error, NULL);
515                     if (fwd) {
516                         sym->nextfwd = fwds;
517                         fwds = sym;
518                         sym->name = nasm_strdup(name);
519                     } else if (e) {
520                         if (!is_simple(e))
521                             error (ERR_NONFATAL, "cannot use relocatable"
522                                    " expression as symbol size");
523                         else
524                             sym->size = reloc_value(e);
525                     }
526                     stdscan_bufptr=saveme;    /* bugfix? fbk 8/10/00 */
527                 }
528                 special_used = TRUE;
529             }
530         }
531         sym->globnum = nglobs;
532         nglobs++;
533     } else
534         nlocals++;
535
536     if (special && !special_used)
537         error(ERR_NONFATAL, "no special symbol features supported here");
538 }
539
540 static void elf_add_reloc (struct Section *sect, long segment,
541                            int type) 
542 {
543     struct Reloc *r;
544
545     r = *sect->tail = nasm_malloc(sizeof(struct Reloc));
546     sect->tail = &r->next;
547     r->next = NULL;
548
549     r->address = sect->len;
550     if (segment == NO_SEG)
551         r->symbol = 2;
552     else {
553         int i;
554         r->symbol = 0;
555         for (i=0; i<nsects; i++)
556             if (segment == sects[i]->index)
557                 r->symbol = i+3;
558         if (!r->symbol)
559             r->symbol = GLOBAL_TEMP_BASE + raa_read(bsym, segment);
560     }
561     r->type = type;
562
563     sect->nrelocs++;
564 }
565
566 /*
567  * This routine deals with ..got and ..sym relocations: the more
568  * complicated kinds. In shared-library writing, some relocations
569  * with respect to global symbols must refer to the precise symbol
570  * rather than referring to an offset from the base of the section
571  * _containing_ the symbol. Such relocations call to this routine,
572  * which searches the symbol list for the symbol in question.
573  *
574  * R_386_GOT32 references require the _exact_ symbol address to be
575  * used; R_386_32 references can be at an offset from the symbol.
576  * The boolean argument `exact' tells us this.
577  *
578  * Return value is the adjusted value of `addr', having become an
579  * offset from the symbol rather than the section. Should always be
580  * zero when returning from an exact call.
581  *
582  * Limitation: if you define two symbols at the same place,
583  * confusion will occur.
584  *
585  * Inefficiency: we search, currently, using a linked list which
586  * isn't even necessarily sorted.
587  */
588 static long elf_add_gsym_reloc (struct Section *sect,
589                                 long segment, long offset,
590                                 int type, int exact) 
591 {
592     struct Reloc *r;
593     struct Section *s;
594     struct Symbol *sym, *sm;
595     int i;
596
597     /*
598      * First look up the segment/offset pair and find a global
599      * symbol corresponding to it. If it's not one of our segments,
600      * then it must be an external symbol, in which case we're fine
601      * doing a normal elf_add_reloc after first sanity-checking
602      * that the offset from the symbol is zero.
603      */
604     s = NULL;
605     for (i=0; i<nsects; i++)
606         if (segment == sects[i]->index) {
607             s = sects[i];
608             break;
609         }
610     if (!s) {
611         if (exact && offset != 0)
612             error (ERR_NONFATAL, "unable to find a suitable global symbol"
613                    " for this reference");
614         else
615             elf_add_reloc (sect, segment, type);
616         return offset;
617     }
618
619     if (exact) {
620         /*
621          * Find a symbol pointing _exactly_ at this one.
622          */
623         for (sym = s->gsyms; sym; sym = sym->next)
624             if (sym->value == offset)
625                 break;
626     } else {
627         /*
628          * Find the nearest symbol below this one.
629          */
630         sym = NULL;
631         for (sm = s->gsyms; sm; sm = sm->next)
632             if (sm->value <= offset && (!sym || sm->value > sym->value))
633                 sym = sm;
634     }
635     if (!sym && exact) {
636         error (ERR_NONFATAL, "unable to find a suitable global symbol"
637                " for this reference");
638         return 0;
639     }
640
641     r = *sect->tail = nasm_malloc(sizeof(struct Reloc));
642     sect->tail = &r->next;
643     r->next = NULL;
644
645     r->address = sect->len;
646     r->symbol = GLOBAL_TEMP_BASE + sym->globnum;
647     r->type = type;
648
649     sect->nrelocs++;
650
651     return offset - sym->value;
652 }
653
654 static void elf_out (long segto, void *data, unsigned long type,
655                       long segment, long wrt) 
656 {
657     struct Section *s;
658     long realbytes = type & OUT_SIZMASK;
659     long addr;
660     unsigned char mydata[4], *p;
661     int i;
662
663     type &= OUT_TYPMASK;
664
665     /*
666      * handle absolute-assembly (structure definitions)
667      */
668     if (segto == NO_SEG) {
669         if (type != OUT_RESERVE)
670             error (ERR_NONFATAL, "attempt to assemble code in [ABSOLUTE]"
671                    " space");
672         return;
673     }
674
675     s = NULL;
676     for (i=0; i<nsects; i++)
677         if (segto == sects[i]->index) {
678             s = sects[i];
679             break;
680         }
681     if (!s) {
682         int tempint;                   /* ignored */
683         if (segto != elf_section_names (".text", 2, &tempint))
684             error (ERR_PANIC, "strange segment conditions in ELF driver");
685         else
686             s = sects[nsects-1];
687     }
688
689     if (s->type == SHT_NOBITS && type != OUT_RESERVE) {
690         error(ERR_WARNING, "attempt to initialise memory in"
691               " BSS section `%s': ignored", s->name);
692         if (type == OUT_REL2ADR)
693             realbytes = 2;
694         else if (type == OUT_REL4ADR)
695             realbytes = 4;
696         s->len += realbytes;
697         return;
698     }
699
700     if (type == OUT_RESERVE) {
701         if (s->type == SHT_PROGBITS) {
702             error(ERR_WARNING, "uninitialised space declared in"
703                   " non-BSS section `%s': zeroing", s->name);
704             elf_sect_write (s, NULL, realbytes);
705         } else
706             s->len += realbytes;
707     } else if (type == OUT_RAWDATA) {
708         if (segment != NO_SEG)
709             error(ERR_PANIC, "OUT_RAWDATA with other than NO_SEG");
710         elf_sect_write (s, data, realbytes);
711     } else if (type == OUT_ADDRESS) {
712         addr = *(long *)data;
713         if (segment != NO_SEG) {
714             if (segment % 2) {
715                 error(ERR_NONFATAL, "ELF format does not support"
716                       " segment base references");
717             } else {
718                 if (wrt == NO_SEG) {
719                     elf_add_reloc (s, segment, R_386_32);
720                 } else if (wrt == elf_gotpc_sect+1) {
721                     /*
722                      * The user will supply GOT relative to $$. ELF
723                      * will let us have GOT relative to $. So we
724                      * need to fix up the data item by $-$$.
725                      */
726                     addr += s->len;
727                     elf_add_reloc (s, segment, R_386_GOTPC);
728                 } else if (wrt == elf_gotoff_sect+1) {
729                     elf_add_reloc (s, segment, R_386_GOTOFF);
730                 } else if (wrt == elf_got_sect+1) {
731                     addr = elf_add_gsym_reloc (s, segment, addr,
732                                                R_386_GOT32, TRUE);
733                 } else if (wrt == elf_sym_sect+1) {
734                     addr = elf_add_gsym_reloc (s, segment, addr,
735                                                R_386_32, FALSE);
736                 } else if (wrt == elf_plt_sect+1) {
737                     error(ERR_NONFATAL, "ELF format cannot produce non-PC-"
738                           "relative PLT references");
739                 } else {
740                     error (ERR_NONFATAL, "ELF format does not support this"
741                            " use of WRT");
742                     wrt = NO_SEG;      /* we can at least _try_ to continue */
743                 }
744             }
745         }
746         p = mydata;
747         if (realbytes != 4 && segment != NO_SEG)
748             error (ERR_NONFATAL, "ELF format does not support non-32-bit"
749                    " relocations");
750         WRITELONG (p, addr);
751         elf_sect_write (s, mydata, realbytes);
752     } else if (type == OUT_REL2ADR) {
753         error (ERR_NONFATAL, "ELF format does not support 16-bit"
754                " relocations");
755     } else if (type == OUT_REL4ADR) {
756         if (segment == segto)
757             error(ERR_PANIC, "intra-segment OUT_REL4ADR");
758         if (segment != NO_SEG && segment % 2) {
759             error(ERR_NONFATAL, "ELF format does not support"
760                   " segment base references");
761         } else {
762             if (wrt == NO_SEG) {
763                 elf_add_reloc (s, segment, R_386_PC32);
764             } else if (wrt == elf_plt_sect+1) {
765                 elf_add_reloc (s, segment, R_386_PLT32);
766             } else if (wrt == elf_gotpc_sect+1 ||
767                        wrt == elf_gotoff_sect+1 ||
768                        wrt == elf_got_sect+1) {
769                 error(ERR_NONFATAL, "ELF format cannot produce PC-"
770                       "relative GOT references");
771             } else {
772                 error (ERR_NONFATAL, "ELF format does not support this"
773                        " use of WRT");
774                 wrt = NO_SEG;      /* we can at least _try_ to continue */
775             }
776         }
777         p = mydata;
778         WRITELONG (p, *(long*)data - realbytes);
779         elf_sect_write (s, mydata, 4L);
780     }
781 }
782
783 static void elf_write(void) 
784 {
785     int nsections, align;
786     char *p;
787     int commlen;
788     char comment[64];
789     int i;
790
791     struct SAA *symtab;
792     long symtablen, symtablocal;
793
794     /*
795      * Work out how many sections we will have. We have SHN_UNDEF,
796      * then the flexible user sections, then the four fixed
797      * sections `.comment', `.shstrtab', `.symtab' and `.strtab',
798      * then optionally relocation sections for the user sections.
799      */
800     nsections = 5;                     /* SHN_UNDEF and the fixed ones */
801     add_sectname ("", ".comment");
802     add_sectname ("", ".shstrtab");
803     add_sectname ("", ".symtab");
804     add_sectname ("", ".strtab");
805     for (i=0; i<nsects; i++) {
806         nsections++;                   /* for the section itself */
807         if (sects[i]->head) {
808             nsections++;               /* for its relocations */
809             add_sectname (".rel", sects[i]->name);
810         }
811     }
812
813     /*
814      * Do the comment.
815      */
816     *comment = '\0';
817     commlen = 2+sprintf(comment+1, "The Netwide Assembler %s", NASM_VER);
818
819     /*
820      * Output the ELF header.
821      */
822     fwrite ("\177ELF\1\1\1\0\0\0\0\0\0\0\0\0", 16, 1, elffp);
823     fwriteshort (1, elffp);            /* ET_REL relocatable file */
824     fwriteshort (3, elffp);            /* EM_386 processor ID */
825     fwritelong (1L, elffp);            /* EV_CURRENT file format version */
826     fwritelong (0L, elffp);            /* no entry point */
827     fwritelong (0L, elffp);            /* no program header table */
828     fwritelong (0x40L, elffp);         /* section headers straight after
829                                         * ELF header plus alignment */
830     fwritelong (0L, elffp);            /* 386 defines no special flags */
831     fwriteshort (0x34, elffp);         /* size of ELF header */
832     fwriteshort (0, elffp);            /* no program header table, again */
833     fwriteshort (0, elffp);            /* still no program header table */
834     fwriteshort (0x28, elffp);         /* size of section header */
835     fwriteshort (nsections, elffp);    /* number of sections */
836     fwriteshort (nsects+2, elffp);     /* string table section index for
837                                         * section header table */
838     fwritelong (0L, elffp);            /* align to 0x40 bytes */
839     fwritelong (0L, elffp);
840     fwritelong (0L, elffp);
841
842     /*
843      * Build the symbol table and relocation tables.
844      */
845     symtab = elf_build_symtab (&symtablen, &symtablocal);
846     for (i=0; i<nsects; i++)
847         if (sects[i]->head)
848             sects[i]->rel = elf_build_reltab (&sects[i]->rellen,
849                                               sects[i]->head);
850
851     /*
852      * Now output the section header table.
853      */
854
855     elf_foffs = 0x40 + 0x28 * nsections;
856     align = ((elf_foffs+SEG_ALIGN_1) & ~SEG_ALIGN_1) - elf_foffs;
857     elf_foffs += align;
858     elf_nsect = 0;
859     elf_sects = nasm_malloc(sizeof(*elf_sects) * (2 * nsects + 10));
860
861     elf_section_header (0, 0, 0, NULL, FALSE, 0L, 0, 0, 0, 0); /* SHN_UNDEF */
862     p = shstrtab+1;
863     for (i=0; i<nsects; i++) {
864         elf_section_header (p - shstrtab, sects[i]->type, sects[i]->flags,
865                             (sects[i]->type == SHT_PROGBITS ?
866                              sects[i]->data : NULL), TRUE,
867                             sects[i]->len, 0, 0, sects[i]->align, 0);
868         p += strlen(p)+1;
869     }
870     elf_section_header (p - shstrtab, 1, 0, comment, FALSE,
871                         (long)commlen, 0, 0, 1, 0);/* .comment */
872     p += strlen(p)+1;
873     elf_section_header (p - shstrtab, 3, 0, shstrtab, FALSE,
874                         (long)shstrtablen, 0, 0, 1, 0);/* .shstrtab */
875     p += strlen(p)+1;
876     elf_section_header (p - shstrtab, 2, 0, symtab, TRUE,
877                         symtablen, nsects+4, symtablocal, 4, 16);/* .symtab */
878     p += strlen(p)+1;
879     elf_section_header (p - shstrtab, 3, 0, strs, TRUE,
880                         strslen, 0, 0, 1, 0);       /* .strtab */
881     for (i=0; i<nsects; i++) if (sects[i]->head) {
882         p += strlen(p)+1;
883         elf_section_header (p - shstrtab, 9, 0, sects[i]->rel, TRUE,
884                             sects[i]->rellen, nsects+3, i+1, 4, 8);
885     }
886
887     fwrite (align_str, align, 1, elffp);
888
889     /*
890      * Now output the sections.
891      */
892     elf_write_sections();
893
894     nasm_free (elf_sects);
895     saa_free (symtab);
896 }
897
898 static struct SAA *elf_build_symtab (long *len, long *local) 
899 {
900     struct SAA *s = saa_init(1L);
901     struct Symbol *sym;
902     unsigned char entry[16], *p;
903     int i;
904
905     *len = *local = 0;
906
907     /*
908      * First, an all-zeros entry, required by the ELF spec.
909      */
910     saa_wbytes (s, NULL, 16L);         /* null symbol table entry */
911     *len += 16;
912     (*local)++;
913
914     /*
915      * Next, an entry for the file name.
916      */
917     p = entry;
918     WRITELONG (p, 1);                  /* we know it's 1st thing in strtab */
919     WRITELONG (p, 0);                  /* no value */
920     WRITELONG (p, 0);                  /* no size either */
921     WRITESHORT (p, 4);                 /* type FILE */
922     WRITESHORT (p, SHN_ABS);
923     saa_wbytes (s, entry, 16L);
924     *len += 16;
925     (*local)++;
926
927     /*
928      * Now some standard symbols defining the segments, for relocation
929      * purposes.
930      */
931     for (i = 1; i <= nsects+1; i++) {
932         p = entry;
933         WRITELONG (p, 0);              /* no symbol name */
934         WRITELONG (p, 0);              /* offset zero */
935         WRITELONG (p, 0);              /* size zero */
936         WRITESHORT (p, 3);             /* local section-type thing */
937         WRITESHORT (p, (i==1 ? SHN_ABS : i-1));   /* the section id */
938         saa_wbytes (s, entry, 16L);
939         *len += 16;
940         (*local)++;
941     }
942
943     /*
944      * Now the other local symbols.
945      */
946     saa_rewind (syms);
947     while ( (sym = saa_rstruct (syms)) ) {
948         if (sym->type & SYM_GLOBAL)
949             continue;
950         p = entry;
951         WRITELONG (p, sym->strpos);
952         WRITELONG (p, sym->value);
953         WRITELONG (p, sym->size);
954         WRITESHORT (p, sym->type);     /* local non-typed thing */
955         WRITESHORT (p, sym->section);
956         saa_wbytes (s, entry, 16L);
957         *len += 16;
958         (*local)++;
959     }
960
961     /*
962      * Now the global symbols.
963      */
964     saa_rewind (syms);
965     while ( (sym = saa_rstruct (syms)) ) {
966         if (!(sym->type & SYM_GLOBAL))
967             continue;
968         p = entry;
969         WRITELONG (p, sym->strpos);
970         WRITELONG (p, sym->value);
971         WRITELONG (p, sym->size);
972         WRITESHORT (p, sym->type);     /* global non-typed thing */
973         WRITESHORT (p, sym->section);
974         saa_wbytes (s, entry, 16L);
975         *len += 16;
976     }
977
978     return s;
979 }
980
981 static struct SAA *elf_build_reltab (long *len, struct Reloc *r) {
982     struct SAA *s;
983     unsigned char *p, entry[8];
984
985     if (!r)
986         return NULL;
987
988     s = saa_init(1L);
989     *len = 0;
990
991     while (r) {
992         long sym = r->symbol;
993
994         if (sym >= GLOBAL_TEMP_BASE)
995             sym += -GLOBAL_TEMP_BASE + (nsects+3) + nlocals;
996
997         p = entry;
998         WRITELONG (p, r->address);
999         WRITELONG (p, (sym << 8) + r->type);
1000         saa_wbytes (s, entry, 8L);
1001         *len += 8;
1002
1003         r = r->next;
1004     }
1005
1006     return s;
1007 }
1008
1009 static void elf_section_header (int name, int type, int flags,
1010                                 void *data, int is_saa, long datalen,
1011                                 int link, int info, int align, int eltsize) 
1012 {
1013     elf_sects[elf_nsect].data = data;
1014     elf_sects[elf_nsect].len = datalen;
1015     elf_sects[elf_nsect].is_saa = is_saa;
1016     elf_nsect++;
1017
1018     fwritelong ((long)name, elffp);
1019     fwritelong ((long)type, elffp);
1020     fwritelong ((long)flags, elffp);
1021     fwritelong (0L, elffp);            /* no address, ever, in object files */
1022     fwritelong (type == 0 ? 0L : elf_foffs, elffp);
1023     fwritelong (datalen, elffp);
1024     if (data)
1025         elf_foffs += (datalen+SEG_ALIGN_1) & ~SEG_ALIGN_1;
1026     fwritelong ((long)link, elffp);
1027     fwritelong ((long)info, elffp);
1028     fwritelong ((long)align, elffp);
1029     fwritelong ((long)eltsize, elffp);
1030 }
1031
1032 static void elf_write_sections (void) 
1033 {
1034     int i;
1035     for (i = 0; i < elf_nsect; i++)
1036         if (elf_sects[i].data) {
1037             long len = elf_sects[i].len;
1038             long reallen = (len+SEG_ALIGN_1) & ~SEG_ALIGN_1;
1039             long align = reallen - len;
1040             if (elf_sects[i].is_saa)
1041                 saa_fpwrite (elf_sects[i].data, elffp);
1042             else
1043                 fwrite (elf_sects[i].data, len, 1, elffp);
1044             fwrite (align_str, align, 1, elffp);
1045         }
1046 }
1047
1048 static void elf_sect_write (struct Section *sect,
1049                              unsigned char *data, unsigned long len) 
1050 {
1051     saa_wbytes (sect->data, data, len);
1052     sect->len += len;
1053 }
1054
1055 static long elf_segbase (long segment) 
1056 {
1057     return segment;
1058 }
1059
1060 static int elf_directive (char *directive, char *value, int pass) 
1061 {
1062     return 0;
1063 }
1064
1065 static void elf_filename (char *inname, char *outname, efunc error) 
1066 {
1067     strcpy(elf_module, inname);
1068     standard_extension (inname, outname, ".o", error);
1069 }
1070
1071 static char *elf_stdmac[] = {
1072     "%define __SECT__ [section .text]",
1073     "%macro __NASM_CDecl__ 1",
1074     "%define $_%1 $%1",
1075     "%endmacro",
1076     NULL
1077 };
1078 static int elf_set_info(enum geninfo type, char **val)
1079 {
1080     return 0;
1081 }
1082
1083 struct ofmt of_elf = {
1084     "ELF32 (i386) object files (e.g. Linux)",
1085     "elf",
1086     NULL,
1087     null_debug_arr,
1088     &null_debug_form,
1089     elf_stdmac,
1090     elf_init,
1091     elf_set_info,
1092     elf_out,
1093     elf_deflabel,
1094     elf_section_names,
1095     elf_segbase,
1096     elf_directive,
1097     elf_filename,
1098     elf_cleanup
1099 };
1100
1101 #endif /* OF_ELF */