Upgrade label functions to 64-bit
[platform/upstream/nasm.git] / output / outelf32.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 "compiler.h"
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <ctype.h>
16 #include <inttypes.h>
17
18 #include "nasm.h"
19 #include "nasmlib.h"
20 #include "stdscan.h"
21 #include "outform.h"
22
23 #ifdef OF_ELF32
24
25 /*
26  * Relocation types.
27  */
28 enum reloc_type {
29     R_386_32 = 1,               /* ordinary absolute relocation */
30     R_386_PC32 = 2,             /* PC-relative relocation */
31     R_386_GOT32 = 3,            /* an offset into GOT */
32     R_386_PLT32 = 4,            /* a PC-relative offset into PLT */
33     R_386_COPY = 5,             /* ??? */
34     R_386_GLOB_DAT = 6,         /* ??? */
35     R_386_JUMP_SLOT = 7,        /* ??? */
36     R_386_RELATIVE = 8,         /* ??? */
37     R_386_GOTOFF = 9,           /* an offset from GOT base */
38     R_386_GOTPC = 10,           /* a PC-relative offset _to_ GOT */
39     /* These are GNU extensions, but useful */
40     R_386_16 = 20,              /* A 16-bit absolute relocation */
41     R_386_PC16 = 21,            /* A 16-bit PC-relative relocation */
42     R_386_8 = 22,               /* An 8-bit absolute relocation */
43     R_386_PC8 = 23              /* An 8-bit PC-relative relocation */
44 };
45
46 struct Reloc {
47     struct Reloc *next;
48     int32_t address;               /* relative to _start_ of section */
49     int32_t symbol;                /*  symbol index */
50     int type;                   /* type of relocation */
51 };
52
53 struct Symbol {
54     int32_t strpos;                /* string table position of name */
55     int32_t section;               /* section ID of the symbol */
56     int type;                   /* symbol type */
57     int other;                     /* symbol visibility */
58     int32_t value;                 /* address, or COMMON variable align */
59     int32_t size;                  /* size of symbol */
60     int32_t globnum;               /* symbol table offset if global */
61     struct Symbol *next;        /* list of globals in each section */
62     struct Symbol *nextfwd;     /* list of unresolved-size symbols */
63     char *name;                 /* used temporarily if in above list */
64 };
65
66 #define SHT_PROGBITS 1
67 #define SHT_NOBITS 8
68
69 #define SHF_WRITE 1
70 #define SHF_ALLOC 2
71 #define SHF_EXECINSTR 4
72
73 struct Section {
74     struct SAA *data;
75     uint32_t len, size, nrelocs;
76     int32_t index;
77     int type;                   /* SHT_PROGBITS or SHT_NOBITS */
78     int align;                  /* alignment: power of two */
79     uint32_t flags;        /* section flags */
80     char *name;
81     struct SAA *rel;
82     int32_t rellen;
83     struct Reloc *head, **tail;
84     struct Symbol *gsyms;       /* global symbols in section */
85 };
86
87 #define SECT_DELTA 32
88 static struct Section **sects;
89 static int nsects, sectlen;
90
91 #define SHSTR_DELTA 256
92 static char *shstrtab;
93 static int shstrtablen, shstrtabsize;
94
95 static struct SAA *syms;
96 static uint32_t nlocals, nglobs;
97
98 static int32_t def_seg;
99
100 static struct RAA *bsym;
101
102 static struct SAA *strs;
103 static uint32_t strslen;
104
105 static FILE *elffp;
106 static efunc error;
107 static evalfunc evaluate;
108
109 static struct Symbol *fwds;
110
111 static char elf_module[FILENAME_MAX];
112
113 extern struct ofmt of_elf32;
114 extern struct ofmt of_elf;
115
116 #define SHN_ABS 0xFFF1
117 #define SHN_COMMON 0xFFF2
118 #define SHN_UNDEF 0
119
120 #define SYM_GLOBAL 0x10
121
122 #define STT_NOTYPE      0               /* Symbol type is unspecified */
123 #define STT_OBJECT      1               /* Symbol is a data object */
124 #define STT_FUNC        2               /* Symbol is a code object */
125 #define STT_SECTION     3               /* Symbol associated with a section */
126 #define STT_FILE        4               /* Symbol's name is file name */
127 #define STT_COMMON      5               /* Symbol is a common data object */
128 #define STT_TLS         6               /* Symbol is thread-local data object*/
129 #define STT_NUM         7               /* Number of defined types.  */
130
131 #define STV_DEFAULT 0
132 #define STV_INTERNAL 1
133 #define STV_HIDDEN 2
134 #define STV_PROTECTED 3
135
136 #define GLOBAL_TEMP_BASE 16     /* bigger than any constant sym id */
137
138 #define SEG_ALIGN 16            /* alignment of sections in file */
139 #define SEG_ALIGN_1 (SEG_ALIGN-1)
140
141 static const char align_str[SEG_ALIGN] = "";    /* ANSI will pad this with 0s */
142
143 #define ELF_MAX_SECTIONS 16     /* really 10, but let's play safe */
144 static struct ELF_SECTDATA {
145     void *data;
146     int32_t len;
147     bool is_saa;
148 } *elf_sects;
149 static int elf_nsect;
150 static int32_t elf_foffs;
151
152 static void elf_write(void);
153 static void elf_sect_write(struct Section *, const uint8_t *,
154                            uint32_t);
155 static void elf_section_header(int, int, int, void *, bool, int32_t, int, int,
156                                int, int);
157 static void elf_write_sections(void);
158 static struct SAA *elf_build_symtab(int32_t *, int32_t *);
159 static struct SAA *elf_build_reltab(int32_t *, struct Reloc *);
160 static void add_sectname(char *, char *);
161
162 /* this stuff is needed for the stabs debugging format */
163 #define N_SO 0x64               /* ID for main source file */
164 #define N_SOL 0x84              /* ID for sub-source file */
165 #define N_BINCL 0x82
166 #define N_EINCL 0xA2
167 #define N_SLINE 0x44
168 #define TY_STABSSYMLIN 0x40     /* ouch */
169
170 struct stabentry {
171     uint32_t n_strx;
172     uint8_t n_type;
173     uint8_t n_other;
174     uint16_t n_desc;
175     uint32_t n_value;
176 };
177
178 struct erel {
179     int offset, info;
180 };
181
182 struct symlininfo {
183     int offset;
184     int section;                /* section index */
185     char *name;                 /* shallow-copied pointer of section name */
186 };
187
188 struct linelist {
189     struct symlininfo info;
190     int line;
191     char *filename;
192     struct linelist *next;
193     struct linelist *last;
194 };
195
196 static struct linelist *stabslines = 0;
197 static int stabs_immcall = 0;
198 static int currentline = 0;
199 static int numlinestabs = 0;
200 static char *stabs_filename = 0;
201 static int symtabsection;
202 static uint8_t *stabbuf = 0, *stabstrbuf = 0, *stabrelbuf = 0;
203 static int stablen, stabstrlen, stabrellen;
204
205 static struct dfmt df_stabs;
206 static struct Symbol *lastsym;
207
208 void stabs32_init(struct ofmt *, void *, FILE *, efunc);
209 void stabs32_linenum(const char *filename, int32_t linenumber, int32_t);
210 void stabs32_deflabel(char *, int32_t, int64_t, int, char *);
211 void stabs32_directive(const char *, const char *);
212 void stabs32_typevalue(int32_t);
213 void stabs32_output(int, void *);
214 void stabs32_generate(void);
215 void stabs32_cleanup(void);
216
217 /* end of stabs debugging stuff */
218
219 /*
220  * Special section numbers which are used to define ELF special
221  * symbols, which can be used with WRT to provide PIC relocation
222  * types.
223  */
224 static int32_t elf_gotpc_sect, elf_gotoff_sect;
225 static int32_t elf_got_sect, elf_plt_sect;
226 static int32_t elf_sym_sect;
227
228 static void elf_init(FILE * fp, efunc errfunc, ldfunc ldef, evalfunc eval)
229 {
230     elffp = fp;
231     error = errfunc;
232     evaluate = eval;
233     (void)ldef;                 /* placate optimisers */
234     sects = NULL;
235     nsects = sectlen = 0;
236     syms = saa_init((int32_t)sizeof(struct Symbol));
237     nlocals = nglobs = 0;
238     bsym = raa_init();
239     strs = saa_init(1L);
240     saa_wbytes(strs, "\0", 1L);
241     saa_wbytes(strs, elf_module, (int32_t)(strlen(elf_module) + 1));
242     strslen = 2 + strlen(elf_module);
243     shstrtab = NULL;
244     shstrtablen = shstrtabsize = 0;;
245     add_sectname("", "");
246
247     fwds = NULL;
248
249     elf_gotpc_sect = seg_alloc();
250     ldef("..gotpc", elf_gotpc_sect + 1, 0L, NULL, false, false, &of_elf32,
251          error);
252     elf_gotoff_sect = seg_alloc();
253     ldef("..gotoff", elf_gotoff_sect + 1, 0L, NULL, false, false, &of_elf32,
254          error);
255     elf_got_sect = seg_alloc();
256     ldef("..got", elf_got_sect + 1, 0L, NULL, false, false, &of_elf32,
257          error);
258     elf_plt_sect = seg_alloc();
259     ldef("..plt", elf_plt_sect + 1, 0L, NULL, false, false, &of_elf32,
260          error);
261     elf_sym_sect = seg_alloc();
262     ldef("..sym", elf_sym_sect + 1, 0L, NULL, false, false, &of_elf32,
263          error);
264
265     def_seg = seg_alloc();
266 }
267
268 static void elf_cleanup(int debuginfo)
269 {
270     struct Reloc *r;
271     int i;
272
273     (void)debuginfo;
274
275     elf_write();
276     fclose(elffp);
277     for (i = 0; i < nsects; i++) {
278         if (sects[i]->type != SHT_NOBITS)
279             saa_free(sects[i]->data);
280         if (sects[i]->head)
281             saa_free(sects[i]->rel);
282         while (sects[i]->head) {
283             r = sects[i]->head;
284             sects[i]->head = sects[i]->head->next;
285             nasm_free(r);
286         }
287     }
288     nasm_free(sects);
289     saa_free(syms);
290     raa_free(bsym);
291     saa_free(strs);
292     if (of_elf32.current_dfmt) {
293         of_elf32.current_dfmt->cleanup();
294     }
295 }
296
297 static void add_sectname(char *firsthalf, char *secondhalf)
298 {
299     int len = strlen(firsthalf) + strlen(secondhalf);
300     while (shstrtablen + len + 1 > shstrtabsize)
301         shstrtab = nasm_realloc(shstrtab, (shstrtabsize += SHSTR_DELTA));
302     strcpy(shstrtab + shstrtablen, firsthalf);
303     strcat(shstrtab + shstrtablen, secondhalf);
304     shstrtablen += len + 1;
305 }
306
307 static int elf_make_section(char *name, int type, int flags, int align)
308 {
309     struct Section *s;
310
311     s = nasm_malloc(sizeof(*s));
312
313     if (type != SHT_NOBITS)
314         s->data = saa_init(1L);
315     s->head = NULL;
316     s->tail = &s->head;
317     s->len = s->size = 0;
318     s->nrelocs = 0;
319     if (!strcmp(name, ".text"))
320         s->index = def_seg;
321     else
322         s->index = seg_alloc();
323     add_sectname("", name);
324     s->name = nasm_malloc(1 + strlen(name));
325     strcpy(s->name, name);
326     s->type = type;
327     s->flags = flags;
328     s->align = align;
329     s->gsyms = NULL;
330
331     if (nsects >= sectlen)
332         sects =
333             nasm_realloc(sects, (sectlen += SECT_DELTA) * sizeof(*sects));
334     sects[nsects++] = s;
335
336     return nsects - 1;
337 }
338
339 static int32_t elf_section_names(char *name, int pass, int *bits)
340 {
341     char *p;
342     unsigned flags_and, flags_or;
343     int type, align, i;
344
345     /*
346      * Default is 32 bits.
347      */
348     if (!name) {
349         *bits = 32;
350         return def_seg;
351     }
352
353     p = name;
354     while (*p && !isspace(*p))
355         p++;
356     if (*p)
357         *p++ = '\0';
358     flags_and = flags_or = type = align = 0;
359
360     while (*p && isspace(*p))
361         p++;
362     while (*p) {
363         char *q = p;
364         while (*p && !isspace(*p))
365             p++;
366         if (*p)
367             *p++ = '\0';
368         while (*p && isspace(*p))
369             p++;
370
371         if (!nasm_strnicmp(q, "align=", 6)) {
372             align = atoi(q + 6);
373             if (align == 0)
374                 align = 1;
375             if ((align - 1) & align) {  /* means it's not a power of two */
376                 error(ERR_NONFATAL, "section alignment %d is not"
377                       " a power of two", align);
378                 align = 1;
379             }
380         } else if (!nasm_stricmp(q, "alloc")) {
381             flags_and |= SHF_ALLOC;
382             flags_or |= SHF_ALLOC;
383         } else if (!nasm_stricmp(q, "noalloc")) {
384             flags_and |= SHF_ALLOC;
385             flags_or &= ~SHF_ALLOC;
386         } else if (!nasm_stricmp(q, "exec")) {
387             flags_and |= SHF_EXECINSTR;
388             flags_or |= SHF_EXECINSTR;
389         } else if (!nasm_stricmp(q, "noexec")) {
390             flags_and |= SHF_EXECINSTR;
391             flags_or &= ~SHF_EXECINSTR;
392         } else if (!nasm_stricmp(q, "write")) {
393             flags_and |= SHF_WRITE;
394             flags_or |= SHF_WRITE;
395         } else if (!nasm_stricmp(q, "nowrite")) {
396             flags_and |= SHF_WRITE;
397             flags_or &= ~SHF_WRITE;
398         } else if (!nasm_stricmp(q, "progbits")) {
399             type = SHT_PROGBITS;
400         } else if (!nasm_stricmp(q, "nobits")) {
401             type = SHT_NOBITS;
402         }
403     }
404
405     if (!strcmp(name, ".comment") ||
406         !strcmp(name, ".shstrtab") ||
407         !strcmp(name, ".symtab") || !strcmp(name, ".strtab")) {
408         error(ERR_NONFATAL, "attempt to redefine reserved section"
409               "name `%s'", name);
410         return NO_SEG;
411     }
412
413     for (i = 0; i < nsects; i++)
414         if (!strcmp(name, sects[i]->name))
415             break;
416     if (i == nsects) {
417         if (!strcmp(name, ".text"))
418             i = elf_make_section(name, SHT_PROGBITS,
419                                  SHF_ALLOC | SHF_EXECINSTR, 16);
420         else if (!strcmp(name, ".rodata"))
421             i = elf_make_section(name, SHT_PROGBITS, SHF_ALLOC, 4);
422         else if (!strcmp(name, ".data"))
423             i = elf_make_section(name, SHT_PROGBITS,
424                                  SHF_ALLOC | SHF_WRITE, 4);
425         else if (!strcmp(name, ".bss"))
426             i = elf_make_section(name, SHT_NOBITS,
427                                  SHF_ALLOC | SHF_WRITE, 4);
428         else
429             i = elf_make_section(name, SHT_PROGBITS, SHF_ALLOC, 1);
430         if (type)
431             sects[i]->type = type;
432         if (align)
433             sects[i]->align = align;
434         sects[i]->flags &= ~flags_and;
435         sects[i]->flags |= flags_or;
436     } else if (pass == 1) {
437           if ((type && sects[i]->type != type)
438              || (align && sects[i]->align != align)
439              || (flags_and && ((sects[i]->flags & flags_and) != flags_or)))
440             error(ERR_WARNING, "section attributes ignored on"
441                   " redeclaration of section `%s'", name);
442     }
443
444     return sects[i]->index;
445 }
446
447 static void elf_deflabel(char *name, int32_t segment, int64_t offset,
448                          int is_global, char *special)
449 {
450     int pos = strslen;
451     struct Symbol *sym;
452     bool special_used = false;
453
454 #if defined(DEBUG) && DEBUG>2
455     fprintf(stderr,
456             " elf_deflabel: %s, seg=%ld, off=%ld, is_global=%d, %s\n",
457             name, segment, offset, is_global, special);
458 #endif
459     if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
460         /*
461          * This is a NASM special symbol. We never allow it into
462          * the ELF symbol table, even if it's a valid one. If it
463          * _isn't_ a valid one, we should barf immediately.
464          */
465         if (strcmp(name, "..gotpc") && strcmp(name, "..gotoff") &&
466             strcmp(name, "..got") && strcmp(name, "..plt") &&
467             strcmp(name, "..sym"))
468             error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
469         return;
470     }
471
472     if (is_global == 3) {
473         struct Symbol **s;
474         /*
475          * Fix up a forward-reference symbol size from the first
476          * pass.
477          */
478         for (s = &fwds; *s; s = &(*s)->nextfwd)
479             if (!strcmp((*s)->name, name)) {
480                 struct tokenval tokval;
481                 expr *e;
482                 char *p = special;
483
484                 while (*p && !isspace(*p))
485                     p++;
486                 while (*p && isspace(*p))
487                     p++;
488                 stdscan_reset();
489                 stdscan_bufptr = p;
490                 tokval.t_type = TOKEN_INVALID;
491                 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
492                 if (e) {
493                     if (!is_simple(e))
494                         error(ERR_NONFATAL, "cannot use relocatable"
495                               " expression as symbol size");
496                     else
497                         (*s)->size = reloc_value(e);
498                 }
499
500                 /*
501                  * Remove it from the list of unresolved sizes.
502                  */
503                 nasm_free((*s)->name);
504                 *s = (*s)->nextfwd;
505                 return;
506             }
507         return;                 /* it wasn't an important one */
508     }
509
510     saa_wbytes(strs, name, (int32_t)(1 + strlen(name)));
511     strslen += 1 + strlen(name);
512
513     lastsym = sym = saa_wstruct(syms);
514
515     sym->strpos = pos;
516     sym->type = is_global ? SYM_GLOBAL : 0;
517     sym->other = STV_DEFAULT;
518     sym->size = 0;
519     if (segment == NO_SEG)
520         sym->section = SHN_ABS;
521     else {
522         int i;
523         sym->section = SHN_UNDEF;
524         if (nsects == 0 && segment == def_seg) {
525             int tempint;
526             if (segment != elf_section_names(".text", 2, &tempint))
527                 error(ERR_PANIC,
528                       "strange segment conditions in ELF driver");
529             sym->section = nsects;
530         } else {
531             for (i = 0; i < nsects; i++)
532                 if (segment == sects[i]->index) {
533                     sym->section = i + 1;
534                     break;
535                 }
536         }
537     }
538
539     if (is_global == 2) {
540         sym->size = offset;
541         sym->value = 0;
542         sym->section = SHN_COMMON;
543         /*
544          * We have a common variable. Check the special text to see
545          * if it's a valid number and power of two; if so, store it
546          * as the alignment for the common variable.
547          */
548         if (special) {
549             bool err;
550             sym->value = readnum(special, &err);
551             if (err)
552                 error(ERR_NONFATAL, "alignment constraint `%s' is not a"
553                       " valid number", special);
554             else if ((sym->value | (sym->value - 1)) != 2 * sym->value - 1)
555                 error(ERR_NONFATAL, "alignment constraint `%s' is not a"
556                       " power of two", special);
557         }
558         special_used = true;
559     } else
560         sym->value = (sym->section == SHN_UNDEF ? 0 : offset);
561
562     if (sym->type == SYM_GLOBAL) {
563         /*
564          * If sym->section == SHN_ABS, then the first line of the
565          * else section would cause a core dump, because its a reference
566          * beyond the end of the section array.
567          * This behaviour is exhibited by this code:
568          *     GLOBAL crash_nasm
569          *     crash_nasm equ 0
570          * To avoid such a crash, such requests are silently discarded.
571          * This may not be the best solution.
572          */
573         if (sym->section == SHN_UNDEF || sym->section == SHN_COMMON) {
574             bsym = raa_write(bsym, segment, nglobs);
575         } else if (sym->section != SHN_ABS) {
576             /*
577              * This is a global symbol; so we must add it to the linked
578              * list of global symbols in its section. We'll push it on
579              * the beginning of the list, because it doesn't matter
580              * much which end we put it on and it's easier like this.
581              *
582              * In addition, we check the special text for symbol
583              * type and size information.
584              */
585             sym->next = sects[sym->section - 1]->gsyms;
586             sects[sym->section - 1]->gsyms = sym;
587
588             if (special) {
589                 int n = strcspn(special, " \t");
590
591                 if (!nasm_strnicmp(special, "function", n))
592                     sym->type |= STT_FUNC;
593                 else if (!nasm_strnicmp(special, "data", n) ||
594                          !nasm_strnicmp(special, "object", n))
595                     sym->type |= STT_OBJECT;
596                 else if (!nasm_strnicmp(special, "notype", n))
597                     sym->type |= STT_NOTYPE;
598                 else
599                     error(ERR_NONFATAL, "unrecognised symbol type `%.*s'",
600                           n, special);
601                 special += n;
602
603                 while (isspace(*special))
604                     ++special;
605                 if (*special) {
606                     n = strcspn(special, " \t");
607                     if (!nasm_strnicmp(special, "default", n))
608                         sym->other = STV_DEFAULT;
609                     else if (!nasm_strnicmp(special, "internal", n))
610                         sym->other = STV_INTERNAL;
611                     else if (!nasm_strnicmp(special, "hidden", n))
612                         sym->other = STV_HIDDEN;
613                     else if (!nasm_strnicmp(special, "protected", n))
614                         sym->other = STV_PROTECTED;
615                     else
616                         n = 0;
617                     special += n;
618                 }
619
620                 if (*special) {
621                     struct tokenval tokval;
622                     expr *e;
623                     int fwd = 0;
624                     char *saveme = stdscan_bufptr;      /* bugfix? fbk 8/10/00 */
625
626                     while (special[n] && isspace(special[n]))
627                         n++;
628                     /*
629                      * We have a size expression; attempt to
630                      * evaluate it.
631                      */
632                     stdscan_reset();
633                     stdscan_bufptr = special + n;
634                     tokval.t_type = TOKEN_INVALID;
635                     e = evaluate(stdscan, NULL, &tokval, &fwd, 0, error,
636                                  NULL);
637                     if (fwd) {
638                         sym->nextfwd = fwds;
639                         fwds = sym;
640                         sym->name = nasm_strdup(name);
641                     } else if (e) {
642                         if (!is_simple(e))
643                             error(ERR_NONFATAL, "cannot use relocatable"
644                                   " expression as symbol size");
645                         else
646                             sym->size = reloc_value(e);
647                     }
648                     stdscan_bufptr = saveme;    /* bugfix? fbk 8/10/00 */
649                 }
650                 special_used = true;
651             }
652         }
653         sym->globnum = nglobs;
654         nglobs++;
655     } else
656         nlocals++;
657
658     if (special && !special_used)
659         error(ERR_NONFATAL, "no special symbol features supported here");
660 }
661
662 static void elf_add_reloc(struct Section *sect, int32_t segment, int type)
663 {
664     struct Reloc *r;
665
666     r = *sect->tail = nasm_malloc(sizeof(struct Reloc));
667     sect->tail = &r->next;
668     r->next = NULL;
669
670     r->address = sect->len;
671     if (segment == NO_SEG)
672         r->symbol = 0;
673     else {
674         int i;
675         r->symbol = 0;
676         for (i = 0; i < nsects; i++)
677             if (segment == sects[i]->index)
678                 r->symbol = i + 2;
679         if (!r->symbol)
680             r->symbol = GLOBAL_TEMP_BASE + raa_read(bsym, segment);
681     }
682     r->type = type;
683
684     sect->nrelocs++;
685 }
686
687 /*
688  * This routine deals with ..got and ..sym relocations: the more
689  * complicated kinds. In shared-library writing, some relocations
690  * with respect to global symbols must refer to the precise symbol
691  * rather than referring to an offset from the base of the section
692  * _containing_ the symbol. Such relocations call to this routine,
693  * which searches the symbol list for the symbol in question.
694  *
695  * R_386_GOT32 references require the _exact_ symbol address to be
696  * used; R_386_32 references can be at an offset from the symbol.
697  * The boolean argument `exact' tells us this.
698  *
699  * Return value is the adjusted value of `addr', having become an
700  * offset from the symbol rather than the section. Should always be
701  * zero when returning from an exact call.
702  *
703  * Limitation: if you define two symbols at the same place,
704  * confusion will occur.
705  *
706  * Inefficiency: we search, currently, using a linked list which
707  * isn't even necessarily sorted.
708  */
709 static int32_t elf_add_gsym_reloc(struct Section *sect,
710                                int32_t segment, int32_t offset,
711                                int type, bool exact)
712 {
713     struct Reloc *r;
714     struct Section *s;
715     struct Symbol *sym, *sm;
716     int i;
717
718     /*
719      * First look up the segment/offset pair and find a global
720      * symbol corresponding to it. If it's not one of our segments,
721      * then it must be an external symbol, in which case we're fine
722      * doing a normal elf_add_reloc after first sanity-checking
723      * that the offset from the symbol is zero.
724      */
725     s = NULL;
726     for (i = 0; i < nsects; i++)
727         if (segment == sects[i]->index) {
728             s = sects[i];
729             break;
730         }
731     if (!s) {
732         if (exact && offset != 0)
733             error(ERR_NONFATAL, "unable to find a suitable global symbol"
734                   " for this reference");
735         else
736             elf_add_reloc(sect, segment, type);
737         return offset;
738     }
739
740     if (exact) {
741         /*
742          * Find a symbol pointing _exactly_ at this one.
743          */
744         for (sym = s->gsyms; sym; sym = sym->next)
745             if (sym->value == offset)
746                 break;
747     } else {
748         /*
749          * Find the nearest symbol below this one.
750          */
751         sym = NULL;
752         for (sm = s->gsyms; sm; sm = sm->next)
753             if (sm->value <= offset && (!sym || sm->value > sym->value))
754                 sym = sm;
755     }
756     if (!sym && exact) {
757         error(ERR_NONFATAL, "unable to find a suitable global symbol"
758               " for this reference");
759         return 0;
760     }
761
762     r = *sect->tail = nasm_malloc(sizeof(struct Reloc));
763     sect->tail = &r->next;
764     r->next = NULL;
765
766     r->address = sect->len;
767     r->symbol = GLOBAL_TEMP_BASE + sym->globnum;
768     r->type = type;
769
770     sect->nrelocs++;
771
772     return offset - sym->value;
773 }
774
775 static void elf_out(int32_t segto, const void *data, uint32_t type,
776                     int32_t segment, int32_t wrt)
777 {
778     struct Section *s;
779     int32_t realbytes = type & OUT_SIZMASK;
780     int32_t addr;
781     uint8_t mydata[4], *p;
782     int i;
783     static struct symlininfo sinfo;
784
785     type &= OUT_TYPMASK;
786
787     /*
788      * handle absolute-assembly (structure definitions)
789      */
790     if (segto == NO_SEG) {
791         if (type != OUT_RESERVE)
792             error(ERR_NONFATAL, "attempt to assemble code in [ABSOLUTE]"
793                   " space");
794         return;
795     }
796
797     s = NULL;
798     for (i = 0; i < nsects; i++)
799         if (segto == sects[i]->index) {
800             s = sects[i];
801             break;
802         }
803     if (!s) {
804         int tempint;            /* ignored */
805         if (segto != elf_section_names(".text", 2, &tempint))
806             error(ERR_PANIC, "strange segment conditions in ELF driver");
807         else {
808             s = sects[nsects - 1];
809             i = nsects - 1;
810         }
811     }
812
813     /* again some stabs debugging stuff */
814     if (of_elf32.current_dfmt) {
815         sinfo.offset = s->len;
816         sinfo.section = i;
817         sinfo.name = s->name;
818         of_elf32.current_dfmt->debug_output(TY_STABSSYMLIN, &sinfo);
819     }
820     /* end of debugging stuff */
821
822     if (s->type == SHT_NOBITS && type != OUT_RESERVE) {
823         error(ERR_WARNING, "attempt to initialize memory in"
824               " BSS section `%s': ignored", s->name);
825         if (type == OUT_REL2ADR)
826             realbytes = 2;
827         else if (type == OUT_REL4ADR)
828             realbytes = 4;
829         s->len += realbytes;
830         return;
831     }
832
833     if (type == OUT_RESERVE) {
834         if (s->type == SHT_PROGBITS) {
835             error(ERR_WARNING, "uninitialized space declared in"
836                   " non-BSS section `%s': zeroing", s->name);
837             elf_sect_write(s, NULL, realbytes);
838         } else
839             s->len += realbytes;
840     } else if (type == OUT_RAWDATA) {
841         if (segment != NO_SEG)
842             error(ERR_PANIC, "OUT_RAWDATA with other than NO_SEG");
843         elf_sect_write(s, data, realbytes);
844     } else if (type == OUT_ADDRESS) {
845         bool gnu16 = false;
846         addr = *(int32_t *)data;
847         if (segment != NO_SEG) {
848             if (segment % 2) {
849                 error(ERR_NONFATAL, "ELF format does not support"
850                       " segment base references");
851             } else {
852                 if (wrt == NO_SEG) {
853                     if (realbytes == 2) {
854                         gnu16 = true;
855                         elf_add_reloc(s, segment, R_386_16);
856                     } else {
857                         elf_add_reloc(s, segment, R_386_32);
858                     }
859                 } else if (wrt == elf_gotpc_sect + 1) {
860                     /*
861                      * The user will supply GOT relative to $$. ELF
862                      * will let us have GOT relative to $. So we
863                      * need to fix up the data item by $-$$.
864                      */
865                     addr += s->len;
866                     elf_add_reloc(s, segment, R_386_GOTPC);
867                 } else if (wrt == elf_gotoff_sect + 1) {
868                     elf_add_reloc(s, segment, R_386_GOTOFF);
869                 } else if (wrt == elf_got_sect + 1) {
870                     addr = elf_add_gsym_reloc(s, segment, addr,
871                                               R_386_GOT32, true);
872                 } else if (wrt == elf_sym_sect + 1) {
873                     if (realbytes == 2) {
874                         gnu16 = true;
875                         addr = elf_add_gsym_reloc(s, segment, addr,
876                                                   R_386_16, false);
877                     } else {
878                         addr = elf_add_gsym_reloc(s, segment, addr,
879                                                   R_386_32, false);
880                     }
881                 } else if (wrt == elf_plt_sect + 1) {
882                     error(ERR_NONFATAL, "ELF format cannot produce non-PC-"
883                           "relative PLT references");
884                 } else {
885                     error(ERR_NONFATAL, "ELF format does not support this"
886                           " use of WRT");
887                     wrt = NO_SEG;       /* we can at least _try_ to continue */
888                 }
889             }
890         }
891         p = mydata;
892         if (gnu16) {
893             error(ERR_WARNING | ERR_WARN_GNUELF,
894                   "16-bit relocations in ELF is a GNU extension");
895             WRITESHORT(p, addr);
896         } else {
897             if (realbytes != 4 && segment != NO_SEG) {
898                 error(ERR_NONFATAL,
899                       "Unsupported non-32-bit ELF relocation");
900             }
901             WRITELONG(p, addr);
902         }
903         elf_sect_write(s, mydata, realbytes);
904     } else if (type == OUT_REL2ADR) {
905         if (segment == segto)
906             error(ERR_PANIC, "intra-segment OUT_REL2ADR");
907         if (segment != NO_SEG && segment % 2) {
908             error(ERR_NONFATAL, "ELF format does not support"
909                   " segment base references");
910         } else {
911             if (wrt == NO_SEG) {
912                 error(ERR_WARNING | ERR_WARN_GNUELF,
913                       "16-bit relocations in ELF is a GNU extension");
914                 elf_add_reloc(s, segment, R_386_PC16);
915             } else {
916                 error(ERR_NONFATAL,
917                       "Unsupported non-32-bit ELF relocation");
918             }
919         }
920         p = mydata;
921         WRITESHORT(p, *(int32_t *)data - realbytes);
922         elf_sect_write(s, mydata, 2L);
923     } else if (type == OUT_REL4ADR) {
924         if (segment == segto)
925             error(ERR_PANIC, "intra-segment OUT_REL4ADR");
926         if (segment != NO_SEG && segment % 2) {
927             error(ERR_NONFATAL, "ELF format does not support"
928                   " segment base references");
929         } else {
930             if (wrt == NO_SEG) {
931                 elf_add_reloc(s, segment, R_386_PC32);
932             } else if (wrt == elf_plt_sect + 1) {
933                 elf_add_reloc(s, segment, R_386_PLT32);
934             } else if (wrt == elf_gotpc_sect + 1 ||
935                        wrt == elf_gotoff_sect + 1 ||
936                        wrt == elf_got_sect + 1) {
937                 error(ERR_NONFATAL, "ELF format cannot produce PC-"
938                       "relative GOT references");
939             } else {
940                 error(ERR_NONFATAL, "ELF format does not support this"
941                       " use of WRT");
942                 wrt = NO_SEG;   /* we can at least _try_ to continue */
943             }
944         }
945         p = mydata;
946         WRITELONG(p, *(int32_t *)data - realbytes);
947         elf_sect_write(s, mydata, 4L);
948     }
949 }
950
951 static void elf_write(void)
952 {
953     int nsections, align;
954     int scount;
955     char *p;
956     int commlen;
957     char comment[64];
958     int i;
959
960     struct SAA *symtab;
961     int32_t symtablen, symtablocal;
962
963     /*
964      * Work out how many sections we will have. We have SHN_UNDEF,
965      * then the flexible user sections, then the four fixed
966      * sections `.comment', `.shstrtab', `.symtab' and `.strtab',
967      * then optionally relocation sections for the user sections.
968      */
969     if (of_elf32.current_dfmt == &df_stabs)
970         nsections = 8;
971     else
972         nsections = 5;          /* SHN_UNDEF and the fixed ones */
973
974     add_sectname("", ".comment");
975     add_sectname("", ".shstrtab");
976     add_sectname("", ".symtab");
977     add_sectname("", ".strtab");
978     for (i = 0; i < nsects; i++) {
979         nsections++;            /* for the section itself */
980         if (sects[i]->head) {
981             nsections++;        /* for its relocations */
982             add_sectname(".rel", sects[i]->name);
983         }
984     }
985
986     if (of_elf32.current_dfmt == &df_stabs) {
987         /* in case the debug information is wanted, just add these three sections... */
988         add_sectname("", ".stab");
989         add_sectname("", ".stabstr");
990         add_sectname(".rel", ".stab");
991     }
992
993     /*
994      * Do the comment.
995      */
996     *comment = '\0';
997     commlen =
998         2 + sprintf(comment + 1, "The Netwide Assembler %s", NASM_VER);
999
1000     /*
1001      * Output the ELF header.
1002      */
1003     fwrite("\177ELF\1\1\1\0\0\0\0\0\0\0\0\0", 16, 1, elffp);
1004     fwriteint16_t(1, elffp);      /* ET_REL relocatable file */
1005     fwriteint16_t(3, elffp);      /* EM_386 processor ID */
1006     fwriteint32_t(1L, elffp);      /* EV_CURRENT file format version */
1007     fwriteint32_t(0L, elffp);      /* no entry point */
1008     fwriteint32_t(0L, elffp);      /* no program header table */
1009     fwriteint32_t(0x40L, elffp);   /* section headers straight after
1010                                  * ELF header plus alignment */
1011     fwriteint32_t(0L, elffp);      /* 386 defines no special flags */
1012     fwriteint16_t(0x34, elffp);   /* size of ELF header */
1013     fwriteint16_t(0, elffp);      /* no program header table, again */
1014     fwriteint16_t(0, elffp);      /* still no program header table */
1015     fwriteint16_t(0x28, elffp);   /* size of section header */
1016     fwriteint16_t(nsections, elffp);      /* number of sections */
1017     fwriteint16_t(nsects + 2, elffp);     /* string table section index for
1018                                          * section header table */
1019     fwriteint32_t(0L, elffp);      /* align to 0x40 bytes */
1020     fwriteint32_t(0L, elffp);
1021     fwriteint32_t(0L, elffp);
1022
1023     /*
1024      * Build the symbol table and relocation tables.
1025      */
1026     symtab = elf_build_symtab(&symtablen, &symtablocal);
1027     for (i = 0; i < nsects; i++)
1028         if (sects[i]->head)
1029             sects[i]->rel = elf_build_reltab(&sects[i]->rellen,
1030                                              sects[i]->head);
1031
1032     /*
1033      * Now output the section header table.
1034      */
1035
1036     elf_foffs = 0x40 + 0x28 * nsections;
1037     align = ((elf_foffs + SEG_ALIGN_1) & ~SEG_ALIGN_1) - elf_foffs;
1038     elf_foffs += align;
1039     elf_nsect = 0;
1040     elf_sects = nasm_malloc(sizeof(*elf_sects) * (2 * nsects + 10));
1041
1042     elf_section_header(0, 0, 0, NULL, false, 0L, 0, 0, 0, 0);   /* SHN_UNDEF */
1043     scount = 1;                 /* needed for the stabs debugging to track the symtable section */
1044     p = shstrtab + 1;
1045     for (i = 0; i < nsects; i++) {
1046         elf_section_header(p - shstrtab, sects[i]->type, sects[i]->flags,
1047                            (sects[i]->type == SHT_PROGBITS ?
1048                             sects[i]->data : NULL), true,
1049                            sects[i]->len, 0, 0, sects[i]->align, 0);
1050         p += strlen(p) + 1;
1051         scount++;               /* dito */
1052     }
1053     elf_section_header(p - shstrtab, 1, 0, comment, false, (int32_t)commlen, 0, 0, 1, 0);  /* .comment */
1054     scount++;                   /* dito */
1055     p += strlen(p) + 1;
1056     elf_section_header(p - shstrtab, 3, 0, shstrtab, false, (int32_t)shstrtablen, 0, 0, 1, 0);     /* .shstrtab */
1057     scount++;                   /* dito */
1058     p += strlen(p) + 1;
1059     elf_section_header(p - shstrtab, 2, 0, symtab, true, symtablen, nsects + 4, symtablocal, 4, 16);    /* .symtab */
1060     symtabsection = scount;     /* now we got the symtab section index in the ELF file */
1061     p += strlen(p) + 1;
1062     elf_section_header(p - shstrtab, 3, 0, strs, true, strslen, 0, 0, 1, 0);    /* .strtab */
1063     for (i = 0; i < nsects; i++)
1064         if (sects[i]->head) {
1065             p += strlen(p) + 1;
1066             elf_section_header(p - shstrtab, 9, 0, sects[i]->rel, true,
1067                                sects[i]->rellen, nsects + 3, i + 1, 4, 8);
1068         }
1069     if (of_elf32.current_dfmt == &df_stabs) {
1070         /* for debugging information, create the last three sections
1071            which are the .stab , .stabstr and .rel.stab sections respectively */
1072
1073         /* this function call creates the stab sections in memory */
1074         stabs32_generate();
1075
1076         if ((stabbuf) && (stabstrbuf) && (stabrelbuf)) {
1077             p += strlen(p) + 1;
1078             elf_section_header(p - shstrtab, 1, 0, stabbuf, false, stablen,
1079                                nsections - 2, 0, 4, 12);
1080
1081             p += strlen(p) + 1;
1082             elf_section_header(p - shstrtab, 3, 0, stabstrbuf, false,
1083                                stabstrlen, 0, 0, 4, 0);
1084
1085             p += strlen(p) + 1;
1086             /* link -> symtable  info -> section to refer to */
1087             elf_section_header(p - shstrtab, 9, 0, stabrelbuf, false,
1088                                stabrellen, symtabsection, nsections - 3, 4,
1089                                8);
1090         }
1091     }
1092     fwrite(align_str, align, 1, elffp);
1093
1094     /*
1095      * Now output the sections.
1096      */
1097     elf_write_sections();
1098
1099     nasm_free(elf_sects);
1100     saa_free(symtab);
1101 }
1102
1103 static struct SAA *elf_build_symtab(int32_t *len, int32_t *local)
1104 {
1105     struct SAA *s = saa_init(1L);
1106     struct Symbol *sym;
1107     uint8_t entry[16], *p;
1108     int i;
1109
1110     *len = *local = 0;
1111
1112     /*
1113      * First, an all-zeros entry, required by the ELF spec.
1114      */
1115     saa_wbytes(s, NULL, 16L);   /* null symbol table entry */
1116     *len += 16;
1117     (*local)++;
1118
1119     /*
1120      * Next, an entry for the file name.
1121      */
1122     p = entry;
1123     WRITELONG(p, 1);            /* we know it's 1st entry in strtab */
1124     WRITELONG(p, 0);            /* no value */
1125     WRITELONG(p, 0);            /* no size either */
1126     WRITESHORT(p, STT_FILE);    /* type FILE */
1127     WRITESHORT(p, SHN_ABS);
1128     saa_wbytes(s, entry, 16L);
1129     *len += 16;
1130     (*local)++;
1131
1132     /*
1133      * Now some standard symbols defining the segments, for relocation
1134      * purposes.
1135      */
1136     for (i = 1; i <= nsects; i++) {
1137         p = entry;
1138         WRITELONG(p, 0);        /* no symbol name */
1139         WRITELONG(p, 0);        /* offset zero */
1140         WRITELONG(p, 0);        /* size zero */
1141         WRITESHORT(p, STT_SECTION);       /* type, binding, and visibility */
1142         WRITESHORT(p, i);       /* section id */
1143         saa_wbytes(s, entry, 16L);
1144         *len += 16;
1145         (*local)++;
1146     }
1147
1148     /*
1149      * Now the other local symbols.
1150      */
1151     saa_rewind(syms);
1152     while ((sym = saa_rstruct(syms))) {
1153         if (sym->type & SYM_GLOBAL)
1154             continue;
1155         p = entry;
1156         WRITELONG(p, sym->strpos);
1157         WRITELONG(p, sym->value);
1158         WRITELONG(p, sym->size);
1159         WRITECHAR(p, sym->type);        /* type and binding */
1160         WRITECHAR(p, sym->other);       /* visibility */
1161         WRITESHORT(p, sym->section);
1162         saa_wbytes(s, entry, 16L);
1163         *len += 16;
1164         (*local)++;
1165     }
1166
1167     /*
1168      * Now the global symbols.
1169      */
1170     saa_rewind(syms);
1171     while ((sym = saa_rstruct(syms))) {
1172         if (!(sym->type & SYM_GLOBAL))
1173             continue;
1174         p = entry;
1175         WRITELONG(p, sym->strpos);
1176         WRITELONG(p, sym->value);
1177         WRITELONG(p, sym->size);
1178         WRITECHAR(p, sym->type);        /* type and binding */
1179         WRITECHAR(p, sym->other);       /* visibility */
1180         WRITESHORT(p, sym->section);
1181         saa_wbytes(s, entry, 16L);
1182         *len += 16;
1183     }
1184
1185     return s;
1186 }
1187
1188 static struct SAA *elf_build_reltab(int32_t *len, struct Reloc *r)
1189 {
1190     struct SAA *s;
1191     uint8_t *p, entry[8];
1192
1193     if (!r)
1194         return NULL;
1195
1196     s = saa_init(1L);
1197     *len = 0;
1198
1199     while (r) {
1200         int32_t sym = r->symbol;
1201
1202         if (sym >= GLOBAL_TEMP_BASE)
1203             sym += -GLOBAL_TEMP_BASE + (nsects + 2) + nlocals;
1204
1205         p = entry;
1206         WRITELONG(p, r->address);
1207         WRITELONG(p, (sym << 8) + r->type);
1208         saa_wbytes(s, entry, 8L);
1209         *len += 8;
1210
1211         r = r->next;
1212     }
1213
1214     return s;
1215 }
1216
1217 static void elf_section_header(int name, int type, int flags,
1218                                void *data, bool is_saa, int32_t datalen,
1219                                int link, int info, int align, int eltsize)
1220 {
1221     elf_sects[elf_nsect].data = data;
1222     elf_sects[elf_nsect].len = datalen;
1223     elf_sects[elf_nsect].is_saa = is_saa;
1224     elf_nsect++;
1225
1226     fwriteint32_t((int32_t)name, elffp);
1227     fwriteint32_t((int32_t)type, elffp);
1228     fwriteint32_t((int32_t)flags, elffp);
1229     fwriteint32_t(0L, elffp);      /* no address, ever, in object files */
1230     fwriteint32_t(type == 0 ? 0L : elf_foffs, elffp);
1231     fwriteint32_t(datalen, elffp);
1232     if (data)
1233         elf_foffs += (datalen + SEG_ALIGN_1) & ~SEG_ALIGN_1;
1234     fwriteint32_t((int32_t)link, elffp);
1235     fwriteint32_t((int32_t)info, elffp);
1236     fwriteint32_t((int32_t)align, elffp);
1237     fwriteint32_t((int32_t)eltsize, elffp);
1238 }
1239
1240 static void elf_write_sections(void)
1241 {
1242     int i;
1243     for (i = 0; i < elf_nsect; i++)
1244         if (elf_sects[i].data) {
1245             int32_t len = elf_sects[i].len;
1246             int32_t reallen = (len + SEG_ALIGN_1) & ~SEG_ALIGN_1;
1247             int32_t align = reallen - len;
1248             if (elf_sects[i].is_saa)
1249                 saa_fpwrite(elf_sects[i].data, elffp);
1250             else
1251                 fwrite(elf_sects[i].data, len, 1, elffp);
1252             fwrite(align_str, align, 1, elffp);
1253         }
1254 }
1255
1256 static void elf_sect_write(struct Section *sect,
1257                            const uint8_t *data, uint32_t len)
1258 {
1259     saa_wbytes(sect->data, data, len);
1260     sect->len += len;
1261 }
1262
1263 static int32_t elf_segbase(int32_t segment)
1264 {
1265     return segment;
1266 }
1267
1268 static int elf_directive(char *directive, char *value, int pass)
1269 {
1270     (void)directive;
1271     (void)value;
1272     (void)pass;
1273     return 0;
1274 }
1275
1276 static void elf_filename(char *inname, char *outname, efunc error)
1277 {
1278     strcpy(elf_module, inname);
1279     standard_extension(inname, outname, ".o", error);
1280 }
1281
1282 static const char *elf_stdmac[] = {
1283     "%define __SECT__ [section .text]",
1284     "%macro __NASM_CDecl__ 1",
1285     "%define $_%1 $%1",
1286     "%endmacro",
1287     NULL
1288 };
1289 static int elf_set_info(enum geninfo type, char **val)
1290 {
1291     (void)type;
1292     (void)val;
1293     return 0;
1294 }
1295
1296 static struct dfmt df_stabs = {
1297     "ELF32 (i386) stabs debug format for Linux",
1298     "stabs",
1299     stabs32_init,
1300     stabs32_linenum,
1301     stabs32_deflabel,
1302     stabs32_directive,
1303     stabs32_typevalue,
1304     stabs32_output,
1305     stabs32_cleanup
1306 };
1307
1308 struct dfmt *elf32_debugs_arr[2] = { &df_stabs, NULL };
1309
1310 struct ofmt of_elf32 = {
1311     "ELF32 (i386) object files (e.g. Linux)",
1312     "elf32",
1313     NULL,
1314     elf32_debugs_arr,
1315     &null_debug_form,
1316     elf_stdmac,
1317     elf_init,
1318     elf_set_info,
1319     elf_out,
1320     elf_deflabel,
1321     elf_section_names,
1322     elf_segbase,
1323     elf_directive,
1324     elf_filename,
1325     elf_cleanup
1326 };
1327
1328 struct ofmt of_elf = {
1329     "ELF (short name for ELF32) ",
1330     "elf",
1331     NULL,
1332     elf32_debugs_arr,
1333     &null_debug_form,
1334     elf_stdmac,
1335     elf_init,
1336     elf_set_info,
1337     elf_out,
1338     elf_deflabel,
1339     elf_section_names,
1340     elf_segbase,
1341     elf_directive,
1342     elf_filename,
1343     elf_cleanup
1344 };
1345 /* again, the stabs debugging stuff (code) */
1346
1347 void stabs32_init(struct ofmt *of, void *id, FILE * fp, efunc error)
1348 {
1349     (void)of;
1350     (void)id;
1351     (void)fp;
1352     (void)error;
1353 }
1354
1355 void stabs32_linenum(const char *filename, int32_t linenumber, int32_t segto)
1356 {
1357     (void)segto;
1358
1359     if (!stabs_filename) {
1360         stabs_filename = (char *)nasm_malloc(strlen(filename) + 1);
1361         strcpy(stabs_filename, filename);
1362     } else {
1363         if (strcmp(stabs_filename, filename)) {
1364             /* yep, a memory leak...this program is one-shot anyway, so who cares...
1365                in fact, this leak comes in quite handy to maintain a list of files
1366                encountered so far in the symbol lines... */
1367
1368             /* why not nasm_free(stabs_filename); we're done with the old one */
1369
1370             stabs_filename = (char *)nasm_malloc(strlen(filename) + 1);
1371             strcpy(stabs_filename, filename);
1372         }
1373     }
1374     stabs_immcall = 1;
1375     currentline = linenumber;
1376 }
1377
1378 void stabs32_deflabel(char *name, int32_t segment, int64_t offset, int is_global,
1379                     char *special)
1380 {
1381    (void)name;
1382    (void)segment;
1383    (void)offset;
1384    (void)is_global;
1385    (void)special;
1386 }
1387
1388 void stabs32_directive(const char *directive, const char *params)
1389 {
1390    (void)directive;
1391    (void)params;
1392 }
1393
1394 void stabs32_typevalue(int32_t type)
1395 {
1396     int32_t stype, ssize;
1397     switch (TYM_TYPE(type)) {
1398         case TY_LABEL:
1399             ssize = 0;
1400             stype = STT_NOTYPE;
1401             break;
1402         case TY_BYTE:
1403             ssize = 1;
1404             stype = STT_OBJECT;
1405             break;
1406         case TY_WORD:
1407             ssize = 2;
1408             stype = STT_OBJECT;
1409             break;
1410         case TY_DWORD:
1411             ssize = 4;
1412             stype = STT_OBJECT;
1413             break;
1414         case TY_FLOAT:
1415             ssize = 4;
1416             stype = STT_OBJECT;
1417             break;
1418         case TY_QWORD:
1419             ssize = 8;
1420             stype = STT_OBJECT;
1421             break;
1422         case TY_TBYTE:
1423             ssize = 10;
1424             stype = STT_OBJECT;
1425             break;
1426         case TY_OWORD:
1427             ssize = 8;
1428             stype = STT_OBJECT;
1429             break;
1430         case TY_COMMON:
1431             ssize = 0;
1432             stype = STT_COMMON;
1433             break;
1434         case TY_SEG:
1435             ssize = 0;
1436             stype = STT_SECTION;
1437             break;
1438         case TY_EXTERN:
1439             ssize = 0;
1440             stype = STT_NOTYPE;
1441             break;
1442         case TY_EQU:
1443             ssize = 0;
1444             stype = STT_NOTYPE;
1445             break;
1446         default:
1447             ssize = 0;
1448             stype = STT_NOTYPE;
1449             break;
1450     }
1451     if (stype == STT_OBJECT && !lastsym->type) {
1452         lastsym->size = ssize;
1453         lastsym->type = stype;
1454     }
1455 }
1456
1457 void stabs32_output(int type, void *param)
1458 {
1459     struct symlininfo *s;
1460     struct linelist *el;
1461     if (type == TY_STABSSYMLIN) {
1462         if (stabs_immcall) {
1463             s = (struct symlininfo *)param;
1464             if (!(sects[s->section]->flags & SHF_EXECINSTR))
1465                 return;         /* we are only interested in the text stuff */
1466             numlinestabs++;
1467             el = (struct linelist *)nasm_malloc(sizeof(struct linelist));
1468             el->info.offset = s->offset;
1469             el->info.section = s->section;
1470             el->info.name = s->name;
1471             el->line = currentline;
1472             el->filename = stabs_filename;
1473             el->next = 0;
1474             if (stabslines) {
1475                 stabslines->last->next = el;
1476                 stabslines->last = el;
1477             } else {
1478                 stabslines = el;
1479                 stabslines->last = el;
1480             }
1481         }
1482     }
1483     stabs_immcall = 0;
1484 }
1485
1486 #define WRITE_STAB(p,n_strx,n_type,n_other,n_desc,n_value) \
1487   do {\
1488     WRITELONG(p,n_strx); \
1489     WRITECHAR(p,n_type); \
1490     WRITECHAR(p,n_other); \
1491     WRITESHORT(p,n_desc); \
1492     WRITELONG(p,n_value); \
1493   } while (0)
1494
1495 /* for creating the .stab , .stabstr and .rel.stab sections in memory */
1496
1497 void stabs32_generate(void)
1498 {
1499     int i, numfiles, strsize, numstabs = 0, currfile, mainfileindex;
1500     uint8_t *sbuf, *ssbuf, *rbuf, *sptr, *rptr;
1501     char **allfiles;
1502     int *fileidx;
1503
1504     struct linelist *ptr;
1505
1506     ptr = stabslines;
1507
1508     allfiles = (char **)nasm_malloc(numlinestabs * sizeof(char *));
1509     for (i = 0; i < numlinestabs; i++)
1510         allfiles[i] = 0;
1511     numfiles = 0;
1512     while (ptr) {
1513         if (numfiles == 0) {
1514             allfiles[0] = ptr->filename;
1515             numfiles++;
1516         } else {
1517             for (i = 0; i < numfiles; i++) {
1518                 if (!strcmp(allfiles[i], ptr->filename))
1519                     break;
1520             }
1521             if (i >= numfiles) {
1522                 allfiles[i] = ptr->filename;
1523                 numfiles++;
1524             }
1525         }
1526         ptr = ptr->next;
1527     }
1528     strsize = 1;
1529     fileidx = (int *)nasm_malloc(numfiles * sizeof(int));
1530     for (i = 0; i < numfiles; i++) {
1531         fileidx[i] = strsize;
1532         strsize += strlen(allfiles[i]) + 1;
1533     }
1534     mainfileindex = 0;
1535     for (i = 0; i < numfiles; i++) {
1536         if (!strcmp(allfiles[i], elf_module)) {
1537             mainfileindex = i;
1538             break;
1539         }
1540     }
1541
1542     /* worst case size of the stab buffer would be:
1543        the sourcefiles changes each line, which would mean 1 SOL, 1 SYMLIN per line
1544      */
1545     sbuf =
1546         (uint8_t *)nasm_malloc((numlinestabs * 2 + 3) *
1547                                      sizeof(struct stabentry));
1548
1549     ssbuf = (uint8_t *)nasm_malloc(strsize);
1550
1551     rbuf = (uint8_t *)nasm_malloc(numlinestabs * 8 * (2 + 3));
1552     rptr = rbuf;
1553
1554     for (i = 0; i < numfiles; i++) {
1555         strcpy((char *)ssbuf + fileidx[i], allfiles[i]);
1556     }
1557     ssbuf[0] = 0;
1558
1559     stabstrlen = strsize;       /* set global variable for length of stab strings */
1560
1561     sptr = sbuf;
1562     ptr = stabslines;
1563     numstabs = 0;
1564
1565     if (ptr) {
1566         /* this is the first stab, its strx points to the filename of the
1567         the source-file, the n_desc field should be set to the number
1568         of remaining stabs
1569         */
1570         WRITE_STAB(sptr, fileidx[0], 0, 0, 0, strlen(allfiles[0] + 12));
1571
1572         /* this is the stab for the main source file */
1573         WRITE_STAB(sptr, fileidx[mainfileindex], N_SO, 0, 0, 0);
1574
1575         /* relocation table entry */
1576
1577         /* Since the symbol table has two entries before */
1578         /* the section symbols, the index in the info.section */
1579         /* member must be adjusted by adding 2 */
1580
1581         WRITELONG(rptr, (sptr - sbuf) - 4);
1582         WRITELONG(rptr, ((ptr->info.section + 2) << 8) | R_386_32);
1583
1584         numstabs++;
1585         currfile = mainfileindex;
1586     }
1587
1588     while (ptr) {
1589         if (strcmp(allfiles[currfile], ptr->filename)) {
1590             /* oops file has changed... */
1591             for (i = 0; i < numfiles; i++)
1592                 if (!strcmp(allfiles[i], ptr->filename))
1593                     break;
1594             currfile = i;
1595             WRITE_STAB(sptr, fileidx[currfile], N_SOL, 0, 0,
1596                        ptr->info.offset);
1597             numstabs++;
1598
1599             /* relocation table entry */
1600             WRITELONG(rptr, (sptr - sbuf) - 4);
1601             WRITELONG(rptr, ((ptr->info.section + 2) << 8) | R_386_32);
1602         }
1603
1604         WRITE_STAB(sptr, 0, N_SLINE, 0, ptr->line, ptr->info.offset);
1605         numstabs++;
1606
1607         /* relocation table entry */
1608
1609         WRITELONG(rptr, (sptr - sbuf) - 4);
1610         WRITELONG(rptr, ((ptr->info.section + 2) << 8) | R_386_32);
1611
1612         ptr = ptr->next;
1613
1614     }
1615
1616     ((struct stabentry *)sbuf)->n_desc = numstabs;
1617
1618     nasm_free(allfiles);
1619     nasm_free(fileidx);
1620
1621     stablen = (sptr - sbuf);
1622     stabrellen = (rptr - rbuf);
1623     stabrelbuf = rbuf;
1624     stabbuf = sbuf;
1625     stabstrbuf = ssbuf;
1626 }
1627
1628 void stabs32_cleanup(void)
1629 {
1630     struct linelist *ptr, *del;
1631     if (!stabslines)
1632         return;
1633     ptr = stabslines;
1634     while (ptr) {
1635         del = ptr;
1636         ptr = ptr->next;
1637         nasm_free(del);
1638     }
1639     if (stabbuf)
1640         nasm_free(stabbuf);
1641     if (stabrelbuf)
1642         nasm_free(stabrelbuf);
1643     if (stabstrbuf)
1644         nasm_free(stabstrbuf);
1645 }
1646
1647 #endif                          /* OF_ELF */