out: Elf32, Elfx32, Elf64 -- Unify elf_init and elf_deflabel
[nasm.git] / output / outelf32.c
blob67c0907fab021107351f033b9a6859010afecae4
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2016 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
9 * conditions are met:
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * ----------------------------------------------------------------------- */
35 * outelf32.c output routines for the Netwide Assembler to produce
36 * ELF32 (i386 of course) object file format
39 #include "compiler.h"
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <ctype.h>
46 #include "nasm.h"
47 #include "nasmlib.h"
48 #include "saa.h"
49 #include "raa.h"
50 #include "stdscan.h"
51 #include "eval.h"
52 #include "output/outform.h"
53 #include "output/outlib.h"
54 #include "rbtree.h"
55 #include "ver.h"
57 #include "output/dwarf.h"
58 #include "output/stabs.h"
59 #include "output/outelf.h"
61 #ifdef OF_ELF32
63 #define SECT_DELTA 32
64 static struct elf_section **sects;
65 static int nsects, sectlen;
67 #define SHSTR_DELTA 256
68 static char *shstrtab;
69 static int shstrtablen, shstrtabsize;
71 static struct SAA *syms;
72 static uint32_t nlocals, nglobs, ndebugs; /* Symbol counts */
74 static int32_t def_seg;
76 static struct RAA *bsym;
78 static struct SAA *strs;
79 static uint32_t strslen;
81 static struct elf_symbol *fwds;
83 static char elf_module[FILENAME_MAX];
85 extern const struct ofmt of_elf32;
87 static struct ELF_SECTDATA {
88 void *data;
89 int64_t len;
90 bool is_saa;
91 } *elf_sects;
92 static int elf_nsect, nsections;
93 static int64_t elf_foffs;
95 static void elf_write(void);
96 static void elf_sect_write(struct elf_section *, const void *, size_t);
97 static void elf_sect_writeaddr(struct elf_section *, int64_t, size_t);
98 static void elf_section_header(int, int, uint64_t, void *, bool, uint64_t, int, int,
99 int, int);
100 static void elf_write_sections(void);
101 static struct SAA *elf_build_symtab(int32_t *, int32_t *);
102 static struct SAA *elf_build_reltab(uint64_t *, struct elf_reloc *);
103 static void add_sectname(char *, char *);
105 struct erel {
106 int offset, info;
109 struct symlininfo {
110 int offset;
111 int section; /* index into sects[] */
112 int segto; /* internal section number */
113 char *name; /* shallow-copied pointer of section name */
116 struct linelist {
117 struct linelist *next;
118 struct linelist *last;
119 struct symlininfo info;
120 char *filename;
121 int line;
124 struct sectlist {
125 struct SAA *psaa;
126 int section;
127 int line;
128 int offset;
129 int file;
130 struct sectlist *next;
131 struct sectlist *last;
134 /* common debug variables */
135 static int currentline = 1;
136 static int debug_immcall = 0;
138 /* stabs debug variables */
139 static struct linelist *stabslines = 0;
140 static int numlinestabs = 0;
141 static char *stabs_filename = 0;
142 static uint8_t *stabbuf = 0, *stabstrbuf = 0, *stabrelbuf = 0;
143 static int stablen, stabstrlen, stabrellen;
145 /* dwarf debug variables */
146 static struct linelist *dwarf_flist = 0, *dwarf_clist = 0, *dwarf_elist = 0;
147 static struct sectlist *dwarf_fsect = 0, *dwarf_csect = 0, *dwarf_esect = 0;
148 static int dwarf_numfiles = 0, dwarf_nsections;
149 static uint8_t *arangesbuf = 0, *arangesrelbuf = 0, *pubnamesbuf = 0, *infobuf = 0, *inforelbuf = 0,
150 *abbrevbuf = 0, *linebuf = 0, *linerelbuf = 0, *framebuf = 0, *locbuf = 0;
151 static int8_t line_base = -5, line_range = 14, opcode_base = 13;
152 static int arangeslen, arangesrellen, pubnameslen, infolen, inforellen,
153 abbrevlen, linelen, linerellen, framelen, loclen;
154 static int64_t dwarf_infosym, dwarf_abbrevsym, dwarf_linesym;
156 static const struct dfmt df_dwarf;
157 static const struct dfmt df_stabs;
158 static struct elf_symbol *lastsym;
160 /* common debugging routines */
161 static void debug_typevalue(int32_t);
163 /* stabs debugging routines */
164 static void stabs_linenum(const char *filename, int32_t linenumber, int32_t);
165 static void stabs_output(int, void *);
166 static void stabs_generate(void);
167 static void stabs_cleanup(void);
169 /* dwarf debugging routines */
170 static void dwarf_init(void);
171 static void dwarf_linenum(const char *filename, int32_t linenumber, int32_t);
172 static void dwarf_output(int, void *);
173 static void dwarf_generate(void);
174 static void dwarf_cleanup(void);
175 static void dwarf_findfile(const char *);
176 static void dwarf_findsect(const int);
179 * Special NASM section numbers which are used to define ELF special
180 * symbols.
182 static int32_t elf_gotpc_sect, elf_gotoff_sect;
183 static int32_t elf_got_sect, elf_plt_sect;
184 static int32_t elf_sym_sect, elf_gottpoff_sect, elf_tlsie_sect;
186 static void elf_init(void)
188 sects = NULL;
189 nsects = sectlen = 0;
190 syms = saa_init((int32_t)sizeof(struct elf_symbol));
191 nlocals = nglobs = ndebugs = 0;
192 bsym = raa_init();
193 strs = saa_init(1L);
194 saa_wbytes(strs, "\0", 1L);
195 saa_wbytes(strs, elf_module, strlen(elf_module)+1);
196 strslen = 2 + strlen(elf_module);
197 shstrtab = NULL;
198 shstrtablen = shstrtabsize = 0;;
199 add_sectname("", "");
201 fwds = NULL;
204 * FIXME: tlsie is Elf32 only and
205 * gottpoff is Elfx32|64 only.
208 elf_gotpc_sect = seg_alloc();
209 define_label("..gotpc", elf_gotpc_sect + 1, 0L, NULL, false, false);
210 elf_gotoff_sect = seg_alloc();
211 define_label("..gotoff", elf_gotoff_sect + 1, 0L, NULL, false, false);
212 elf_got_sect = seg_alloc();
213 define_label("..got", elf_got_sect + 1, 0L, NULL, false, false);
214 elf_plt_sect = seg_alloc();
215 define_label("..plt", elf_plt_sect + 1, 0L, NULL, false, false);
216 elf_sym_sect = seg_alloc();
217 define_label("..sym", elf_sym_sect + 1, 0L, NULL, false, false);
218 elf_gottpoff_sect = seg_alloc();
219 define_label("..gottpoff", elf_gottpoff_sect + 1, 0L, NULL, false, false);
220 elf_tlsie_sect = seg_alloc();
221 define_label("..tlsie", elf_tlsie_sect + 1, 0L, NULL, false, false);
223 def_seg = seg_alloc();
226 static void elf_cleanup(void)
228 struct elf_reloc *r;
229 int i;
231 elf_write();
232 for (i = 0; i < nsects; i++) {
233 if (sects[i]->type != SHT_NOBITS)
234 saa_free(sects[i]->data);
235 if (sects[i]->head)
236 saa_free(sects[i]->rel);
237 while (sects[i]->head) {
238 r = sects[i]->head;
239 sects[i]->head = sects[i]->head->next;
240 nasm_free(r);
243 nasm_free(sects);
244 saa_free(syms);
245 raa_free(bsym);
246 saa_free(strs);
247 dfmt->cleanup();
250 /* add entry to the elf .shstrtab section */
251 static void add_sectname(char *firsthalf, char *secondhalf)
253 int len = strlen(firsthalf) + strlen(secondhalf);
254 while (shstrtablen + len + 1 > shstrtabsize)
255 shstrtab = nasm_realloc(shstrtab, (shstrtabsize += SHSTR_DELTA));
256 strcpy(shstrtab + shstrtablen, firsthalf);
257 strcat(shstrtab + shstrtablen, secondhalf);
258 shstrtablen += len + 1;
261 static int elf_make_section(char *name, int type, int flags, int align)
263 struct elf_section *s;
265 s = nasm_zalloc(sizeof(*s));
267 if (type != SHT_NOBITS)
268 s->data = saa_init(1L);
269 s->tail = &s->head;
270 if (!strcmp(name, ".text"))
271 s->index = def_seg;
272 else
273 s->index = seg_alloc();
274 add_sectname("", name);
276 s->name = nasm_strdup(name);
277 s->type = type;
278 s->flags = flags;
279 s->align = align;
281 if (nsects >= sectlen)
282 sects = nasm_realloc(sects, (sectlen += SECT_DELTA) * sizeof(*sects));
283 sects[nsects++] = s;
285 return nsects - 1;
288 static int32_t elf_section_names(char *name, int pass, int *bits)
290 char *p;
291 uint32_t flags, flags_and, flags_or;
292 uint64_t align;
293 int type, i;
295 if (!name) {
296 *bits = ofmt->maxbits;
297 return def_seg;
300 p = nasm_skip_word(name);
301 if (*p)
302 *p++ = '\0';
303 flags_and = flags_or = type = align = 0;
305 elf_section_attrib(name, p, pass, &flags_and,
306 &flags_or, &align, &type);
308 if (!strcmp(name, ".shstrtab") ||
309 !strcmp(name, ".symtab") ||
310 !strcmp(name, ".strtab")) {
311 nasm_error(ERR_NONFATAL, "attempt to redefine reserved section"
312 "name `%s'", name);
313 return NO_SEG;
316 for (i = 0; i < nsects; i++)
317 if (!strcmp(name, sects[i]->name))
318 break;
319 if (i == nsects) {
320 const struct elf_known_section *ks = elf_known_sections;
322 while (ks->name) {
323 if (!strcmp(name, ks->name))
324 break;
325 ks++;
328 type = type ? type : ks->type;
329 align = align ? align : ks->align;
330 flags = (ks->flags & ~flags_and) | flags_or;
332 i = elf_make_section(name, type, flags, align);
333 } else if (pass == 1) {
334 if ((type && sects[i]->type != type)
335 || (align && sects[i]->align != align)
336 || (flags_and && ((sects[i]->flags & flags_and) != flags_or)))
337 nasm_error(ERR_WARNING, "incompatible section attributes ignored on"
338 " redeclaration of section `%s'", name);
341 return sects[i]->index;
344 static void elf_deflabel(char *name, int32_t segment, int64_t offset,
345 int is_global, char *special)
347 int pos = strslen;
348 struct elf_symbol *sym;
349 bool special_used = false;
351 #if defined(DEBUG) && DEBUG>2
352 nasm_error(ERR_DEBUG,
353 " elf_deflabel: %s, seg=%"PRIx32", off=%"PRIx64", is_global=%d, %s\n",
354 name, segment, offset, is_global, special);
355 #endif
356 if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
358 * This is a NASM special symbol. We never allow it into
359 * the ELF symbol table, even if it's a valid one. If it
360 * _isn't_ a valid one, we should barf immediately.
362 * FIXME: tlsie is Elf32 only, and gottpoff is Elfx32|64 only.
364 if (strcmp(name, "..gotpc") && strcmp(name, "..gotoff") &&
365 strcmp(name, "..got") && strcmp(name, "..plt") &&
366 strcmp(name, "..sym") && strcmp(name, "..gottpoff") &&
367 strcmp(name, "..tlsie"))
368 nasm_error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
369 return;
372 if (is_global == 3) {
373 struct elf_symbol **s;
375 * Fix up a forward-reference symbol size from the first
376 * pass.
378 for (s = &fwds; *s; s = &(*s)->nextfwd)
379 if (!strcmp((*s)->name, name)) {
380 struct tokenval tokval;
381 expr *e;
382 char *p = nasm_skip_spaces(nasm_skip_word(special));
384 stdscan_reset();
385 stdscan_set(p);
386 tokval.t_type = TOKEN_INVALID;
387 e = evaluate(stdscan, NULL, &tokval, NULL, 1, NULL);
388 if (e) {
389 if (!is_simple(e))
390 nasm_error(ERR_NONFATAL, "cannot use relocatable"
391 " expression as symbol size");
392 else
393 (*s)->size = reloc_value(e);
397 * Remove it from the list of unresolved sizes.
399 nasm_free((*s)->name);
400 *s = (*s)->nextfwd;
401 return;
403 return; /* it wasn't an important one */
406 saa_wbytes(strs, name, (int32_t)(1 + strlen(name)));
407 strslen += 1 + strlen(name);
409 lastsym = sym = saa_wstruct(syms);
411 memset(&sym->symv, 0, sizeof(struct rbtree));
413 sym->strpos = pos;
414 sym->type = is_global ? SYM_GLOBAL : SYM_LOCAL;
415 sym->other = STV_DEFAULT;
416 sym->size = 0;
417 if (segment == NO_SEG)
418 sym->section = SHN_ABS;
419 else {
420 int i;
421 sym->section = SHN_UNDEF;
422 if (segment == def_seg) {
423 /* we have to be sure at least text section is there */
424 int tempint;
425 if (segment != elf_section_names(".text", 2, &tempint))
426 nasm_panic(0, "strange segment conditions in ELF driver");
428 for (i = 0; i < nsects; i++) {
429 if (segment == sects[i]->index) {
430 sym->section = i + 1;
431 break;
436 if (is_global == 2) {
437 sym->size = offset;
438 sym->symv.key = 0;
439 sym->section = SHN_COMMON;
441 * We have a common variable. Check the special text to see
442 * if it's a valid number and power of two; if so, store it
443 * as the alignment for the common variable.
445 if (special) {
446 bool err;
447 sym->symv.key = readnum(special, &err);
448 if (err)
449 nasm_error(ERR_NONFATAL, "alignment constraint `%s' is not a"
450 " valid number", special);
451 else if ((sym->symv.key | (sym->symv.key - 1)) != 2 * sym->symv.key - 1)
452 nasm_error(ERR_NONFATAL, "alignment constraint `%s' is not a"
453 " power of two", special);
455 special_used = true;
456 } else
457 sym->symv.key = (sym->section == SHN_UNDEF ? 0 : offset);
459 if (sym->type == SYM_GLOBAL) {
461 * If sym->section == SHN_ABS, then the first line of the
462 * else section would cause a core dump, because its a reference
463 * beyond the end of the section array.
464 * This behaviour is exhibited by this code:
465 * GLOBAL crash_nasm
466 * crash_nasm equ 0
467 * To avoid such a crash, such requests are silently discarded.
468 * This may not be the best solution.
470 if (sym->section == SHN_UNDEF || sym->section == SHN_COMMON) {
471 bsym = raa_write(bsym, segment, nglobs);
472 } else if (sym->section != SHN_ABS) {
474 * This is a global symbol; so we must add it to the rbtree
475 * of global symbols in its section.
477 * In addition, we check the special text for symbol
478 * type and size information.
480 sects[sym->section-1]->gsyms =
481 rb_insert(sects[sym->section-1]->gsyms, &sym->symv);
483 if (special) {
484 int n = strcspn(special, " \t");
486 if (!nasm_strnicmp(special, "function", n))
487 sym->type |= STT_FUNC;
488 else if (!nasm_strnicmp(special, "data", n) ||
489 !nasm_strnicmp(special, "object", n))
490 sym->type |= STT_OBJECT;
491 else if (!nasm_strnicmp(special, "notype", n))
492 sym->type |= STT_NOTYPE;
493 else
494 nasm_error(ERR_NONFATAL, "unrecognised symbol type `%.*s'",
495 n, special);
496 special += n;
498 special = nasm_skip_spaces(special);
499 if (*special) {
500 n = strcspn(special, " \t");
501 if (!nasm_strnicmp(special, "default", n))
502 sym->other = STV_DEFAULT;
503 else if (!nasm_strnicmp(special, "internal", n))
504 sym->other = STV_INTERNAL;
505 else if (!nasm_strnicmp(special, "hidden", n))
506 sym->other = STV_HIDDEN;
507 else if (!nasm_strnicmp(special, "protected", n))
508 sym->other = STV_PROTECTED;
509 else
510 n = 0;
511 special += n;
514 if (*special) {
515 struct tokenval tokval;
516 expr *e;
517 int fwd = 0;
518 char *saveme = stdscan_get();
520 while (special[n] && nasm_isspace(special[n]))
521 n++;
523 * We have a size expression; attempt to
524 * evaluate it.
526 stdscan_reset();
527 stdscan_set(special + n);
528 tokval.t_type = TOKEN_INVALID;
529 e = evaluate(stdscan, NULL, &tokval, &fwd, 0, NULL);
530 if (fwd) {
531 sym->nextfwd = fwds;
532 fwds = sym;
533 sym->name = nasm_strdup(name);
534 } else if (e) {
535 if (!is_simple(e))
536 nasm_error(ERR_NONFATAL, "cannot use relocatable"
537 " expression as symbol size");
538 else
539 sym->size = reloc_value(e);
541 stdscan_set(saveme);
543 special_used = true;
546 * If TLS segment, mark symbol accordingly.
548 if (sects[sym->section - 1]->flags & SHF_TLS) {
549 sym->type &= 0xf0;
550 sym->type |= STT_TLS;
553 sym->globnum = nglobs;
554 nglobs++;
555 } else
556 nlocals++;
558 if (special && !special_used)
559 nasm_error(ERR_NONFATAL, "no special symbol features supported here");
562 static void elf_add_reloc(struct elf_section *sect, int32_t segment,
563 int64_t offset, int type)
565 struct elf_reloc *r;
567 r = *sect->tail = nasm_zalloc(sizeof(struct elf_reloc));
568 sect->tail = &r->next;
570 r->address = sect->len;
571 r->offset = offset;
573 if (segment != NO_SEG) {
574 int i;
575 for (i = 0; i < nsects; i++)
576 if (segment == sects[i]->index)
577 r->symbol = i + 2;
578 if (!r->symbol)
579 r->symbol = GLOBAL_TEMP_BASE + raa_read(bsym, segment);
581 r->type = type;
583 sect->nrelocs++;
587 * This routine deals with ..got and ..sym relocations: the more
588 * complicated kinds. In shared-library writing, some relocations
589 * with respect to global symbols must refer to the precise symbol
590 * rather than referring to an offset from the base of the section
591 * _containing_ the symbol. Such relocations call to this routine,
592 * which searches the symbol list for the symbol in question.
594 * R_386_GOT32 references require the _exact_ symbol address to be
595 * used; R_386_32 references can be at an offset from the symbol.
596 * The boolean argument `exact' tells us this.
598 * Return value is the adjusted value of `addr', having become an
599 * offset from the symbol rather than the section. Should always be
600 * zero when returning from an exact call.
602 * Limitation: if you define two symbols at the same place,
603 * confusion will occur.
605 * Inefficiency: we search, currently, using a linked list which
606 * isn't even necessarily sorted.
608 static int32_t elf_add_gsym_reloc(struct elf_section *sect,
609 int32_t segment, uint32_t offset,
610 int type, bool exact)
612 struct elf_reloc *r;
613 struct elf_section *s;
614 struct elf_symbol *sym;
615 struct rbtree *srb;
616 int i;
619 * First look up the segment/offset pair and find a global
620 * symbol corresponding to it. If it's not one of our segments,
621 * then it must be an external symbol, in which case we're fine
622 * doing a normal elf_add_reloc after first sanity-checking
623 * that the offset from the symbol is zero.
625 s = NULL;
626 for (i = 0; i < nsects; i++)
627 if (segment == sects[i]->index) {
628 s = sects[i];
629 break;
632 if (!s) {
633 if (exact && offset)
634 nasm_error(ERR_NONFATAL, "unable to find a suitable global symbol"
635 " for this reference");
636 else
637 elf_add_reloc(sect, segment, 0, type);
638 return offset;
641 srb = rb_search(s->gsyms, offset);
642 if (!srb || (exact && srb->key != offset)) {
643 nasm_error(ERR_NONFATAL, "unable to find a suitable global symbol"
644 " for this reference");
645 return 0;
647 sym = container_of(srb, struct elf_symbol, symv);
649 r = *sect->tail = nasm_malloc(sizeof(struct elf_reloc));
650 sect->tail = &r->next;
652 r->next = NULL;
653 r->address = sect->len;
654 r->symbol = GLOBAL_TEMP_BASE + sym->globnum;
655 r->type = type;
657 sect->nrelocs++;
659 return offset - sym->symv.key;
662 static void elf_out(int32_t segto, const void *data,
663 enum out_type type, uint64_t size,
664 int32_t segment, int32_t wrt)
666 struct elf_section *s;
667 int32_t addr;
668 uint8_t mydata[8], *p;
669 int reltype, bytes;
670 int i;
671 static struct symlininfo sinfo;
674 * handle absolute-assembly (structure definitions)
676 if (segto == NO_SEG) {
677 if (type != OUT_RESERVE)
678 nasm_error(ERR_NONFATAL, "attempt to assemble code in [ABSOLUTE]"
679 " space");
680 return;
683 s = NULL;
684 for (i = 0; i < nsects; i++)
685 if (segto == sects[i]->index) {
686 s = sects[i];
687 break;
689 if (!s) {
690 int tempint; /* ignored */
691 if (segto != elf_section_names(".text", 2, &tempint))
692 nasm_panic(0, "strange segment conditions in ELF driver");
693 else {
694 s = sects[nsects - 1];
695 i = nsects - 1;
699 /* again some stabs debugging stuff */
700 sinfo.offset = s->len;
701 sinfo.section = i;
702 sinfo.segto = segto;
703 sinfo.name = s->name;
704 dfmt->debug_output(TY_DEBUGSYMLIN, &sinfo);
705 /* end of debugging stuff */
707 if (s->type == SHT_NOBITS && type != OUT_RESERVE) {
708 nasm_error(ERR_WARNING, "attempt to initialize memory in"
709 " BSS section `%s': ignored", s->name);
710 s->len += realsize(type, size);
711 return;
714 memset(mydata, 0, sizeof(mydata));
716 switch (type) {
717 case OUT_RESERVE:
718 if (s->type == SHT_PROGBITS) {
719 nasm_error(ERR_WARNING, "uninitialized space declared in"
720 " non-BSS section `%s': zeroing", s->name);
721 elf_sect_write(s, NULL, size);
722 } else
723 s->len += size;
724 break;
726 case OUT_RAWDATA:
727 if (segment != NO_SEG)
728 nasm_panic(0, "OUT_RAWDATA with other than NO_SEG");
729 elf_sect_write(s, data, size);
730 break;
732 case OUT_ADDRESS:
734 bool gnu16 = false;
735 int asize = abs((int)size);
736 addr = *(int64_t *)data;
737 if (segment != NO_SEG) {
738 if (segment % 2) {
739 nasm_error(ERR_NONFATAL, "ELF format does not support"
740 " segment base references");
741 } else {
742 if (wrt == NO_SEG) {
744 * The if() is a hack to deal with compilers which
745 * don't handle switch() statements with 64-bit
746 * expressions.
748 switch (asize) {
749 case 1:
750 gnu16 = true;
751 elf_add_reloc(s, segment, 0, R_386_8);
752 break;
753 case 2:
754 gnu16 = true;
755 elf_add_reloc(s, segment, 0, R_386_16);
756 break;
757 case 4:
758 elf_add_reloc(s, segment, 0, R_386_32);
759 break;
760 default: /* Error issued further down */
761 break;
763 } else if (wrt == elf_gotpc_sect + 1) {
765 * The user will supply GOT relative to $$. ELF
766 * will let us have GOT relative to $. So we
767 * need to fix up the data item by $-$$.
769 addr += s->len;
770 elf_add_reloc(s, segment, 0, R_386_GOTPC);
771 } else if (wrt == elf_gotoff_sect + 1) {
772 elf_add_reloc(s, segment, 0, R_386_GOTOFF);
773 } else if (wrt == elf_tlsie_sect + 1) {
774 addr = elf_add_gsym_reloc(s, segment, addr,
775 R_386_TLS_IE, true);
776 } else if (wrt == elf_got_sect + 1) {
777 addr = elf_add_gsym_reloc(s, segment, addr,
778 R_386_GOT32, true);
779 } else if (wrt == elf_sym_sect + 1) {
780 switch (asize) {
781 case 1:
782 gnu16 = true;
783 addr = elf_add_gsym_reloc(s, segment, addr,
784 R_386_8, false);
785 break;
786 case 2:
787 gnu16 = true;
788 addr = elf_add_gsym_reloc(s, segment, addr,
789 R_386_16, false);
790 break;
791 case 4:
792 addr = elf_add_gsym_reloc(s, segment, addr,
793 R_386_32, false);
794 break;
795 default:
796 break;
798 } else if (wrt == elf_plt_sect + 1) {
799 nasm_error(ERR_NONFATAL, "ELF format cannot produce non-PC-"
800 "relative PLT references");
801 } else {
802 nasm_error(ERR_NONFATAL, "ELF format does not support this"
803 " use of WRT");
804 wrt = NO_SEG; /* we can at least _try_ to continue */
808 p = mydata;
809 if (gnu16) {
810 nasm_error(ERR_WARNING | ERR_WARN_GNUELF,
811 "8- or 16-bit relocations in ELF32 is a GNU extension");
812 } else if (asize != 4 && segment != NO_SEG) {
813 nasm_error(ERR_NONFATAL, "Unsupported non-32-bit ELF relocation");
815 WRITEADDR(p, addr, asize);
816 elf_sect_write(s, mydata, asize);
817 break;
820 case OUT_REL1ADR:
821 bytes = 1;
822 reltype = R_386_PC8;
823 goto rel12adr;
824 case OUT_REL2ADR:
825 bytes = 2;
826 reltype = R_386_PC16;
827 goto rel12adr;
829 rel12adr:
830 nasm_assert(segment != segto);
831 if (segment != NO_SEG && segment % 2) {
832 nasm_error(ERR_NONFATAL, "ELF format does not support"
833 " segment base references");
834 } else {
835 if (wrt == NO_SEG) {
836 nasm_error(ERR_WARNING | ERR_WARN_GNUELF,
837 "8- or 16-bit relocations in ELF is a GNU extension");
838 elf_add_reloc(s, segment, 0, reltype);
839 } else {
840 nasm_error(ERR_NONFATAL,
841 "Unsupported non-32-bit ELF relocation");
844 p = mydata;
845 WRITESHORT(p, *(int64_t *)data - size);
846 elf_sect_write(s, mydata, bytes);
847 break;
849 case OUT_REL4ADR:
850 if (segment == segto)
851 nasm_panic(0, "intra-segment OUT_REL4ADR");
852 if (segment != NO_SEG && segment % 2) {
853 nasm_error(ERR_NONFATAL, "ELF format does not support"
854 " segment base references");
855 } else {
856 if (wrt == NO_SEG) {
857 elf_add_reloc(s, segment, 0, R_386_PC32);
858 } else if (wrt == elf_plt_sect + 1) {
859 elf_add_reloc(s, segment, 0, R_386_PLT32);
860 } else if (wrt == elf_gotpc_sect + 1 ||
861 wrt == elf_gotoff_sect + 1 ||
862 wrt == elf_got_sect + 1) {
863 nasm_error(ERR_NONFATAL, "ELF format cannot produce PC-"
864 "relative GOT references");
865 } else {
866 nasm_error(ERR_NONFATAL, "ELF format does not support this"
867 " use of WRT");
868 wrt = NO_SEG; /* we can at least _try_ to continue */
871 p = mydata;
872 WRITELONG(p, *(int64_t *)data - size);
873 elf_sect_write(s, mydata, 4L);
874 break;
876 case OUT_REL8ADR:
877 nasm_error(ERR_NONFATAL,
878 "32-bit ELF format does not support 64-bit relocations");
879 p = mydata;
880 WRITEDLONG(p, 0);
881 elf_sect_write(s, mydata, 8L);
882 break;
886 static void elf_write(void)
888 int align;
889 char *p;
890 int i;
892 struct SAA *symtab;
893 int32_t symtablen, symtablocal;
896 * Work out how many sections we will have. We have SHN_UNDEF,
897 * then the flexible user sections, then the fixed sections
898 * `.shstrtab', `.symtab' and `.strtab', then optionally
899 * relocation sections for the user sections.
901 nsections = sec_numspecial + 1;
902 if (dfmt == &df_stabs)
903 nsections += 3;
904 else if (dfmt == &df_dwarf)
905 nsections += 10;
907 add_sectname("", ".shstrtab");
908 add_sectname("", ".symtab");
909 add_sectname("", ".strtab");
910 for (i = 0; i < nsects; i++) {
911 nsections++; /* for the section itself */
912 if (sects[i]->head) {
913 nsections++; /* for its relocations */
914 add_sectname(".rel", sects[i]->name);
918 if (dfmt == &df_stabs) {
919 /* in case the debug information is wanted, just add these three sections... */
920 add_sectname("", ".stab");
921 add_sectname("", ".stabstr");
922 add_sectname(".rel", ".stab");
923 } else if (dfmt == &df_dwarf) {
924 /* the dwarf debug standard specifies the following ten sections,
925 not all of which are currently implemented,
926 although all of them are defined. */
927 add_sectname("", ".debug_aranges");
928 add_sectname(".rela", ".debug_aranges");
929 add_sectname("", ".debug_pubnames");
930 add_sectname("", ".debug_info");
931 add_sectname(".rela", ".debug_info");
932 add_sectname("", ".debug_abbrev");
933 add_sectname("", ".debug_line");
934 add_sectname(".rela", ".debug_line");
935 add_sectname("", ".debug_frame");
936 add_sectname("", ".debug_loc");
940 * Output the ELF header.
942 nasm_write("\177ELF\1\1\1", 7, ofile);
943 fputc(elf_osabi, ofile);
944 fputc(elf_abiver, ofile);
945 fwritezero(7, ofile);
946 fwriteint16_t(1, ofile); /* ET_REL relocatable file */
947 fwriteint16_t(3, ofile); /* EM_386 processor ID */
948 fwriteint32_t(1L, ofile); /* EV_CURRENT file format version */
949 fwriteint32_t(0L, ofile); /* no entry point */
950 fwriteint32_t(0L, ofile); /* no program header table */
951 fwriteint32_t(0x40L, ofile); /* section headers straight after
952 * ELF header plus alignment */
953 fwriteint32_t(0L, ofile); /* 386 defines no special flags */
954 fwriteint16_t(0x34, ofile); /* size of ELF header */
955 fwriteint16_t(0, ofile); /* no program header table, again */
956 fwriteint16_t(0, ofile); /* still no program header table */
957 fwriteint16_t(0x28, ofile); /* size of section header */
958 fwriteint16_t(nsections, ofile); /* number of sections */
959 fwriteint16_t(sec_shstrtab, ofile); /* string table section index for
960 * section header table */
961 fwriteint32_t(0L, ofile); /* align to 0x40 bytes */
962 fwriteint32_t(0L, ofile);
963 fwriteint32_t(0L, ofile);
966 * Build the symbol table and relocation tables.
968 symtab = elf_build_symtab(&symtablen, &symtablocal);
969 for (i = 0; i < nsects; i++)
970 if (sects[i]->head)
971 sects[i]->rel = elf_build_reltab(&sects[i]->rellen,
972 sects[i]->head);
975 * Now output the section header table.
978 elf_foffs = 0x40 + sizeof(Elf32_Shdr) * nsections;
979 align = ALIGN(elf_foffs, SEC_FILEALIGN) - elf_foffs;
980 elf_foffs += align;
981 elf_nsect = 0;
982 elf_sects = nasm_malloc(sizeof(*elf_sects) * nsections);
984 /* SHN_UNDEF */
985 elf_section_header(0, SHT_NULL, 0, NULL, false, 0, SHN_UNDEF, 0, 0, 0);
986 p = shstrtab + 1;
988 /* The normal sections */
989 for (i = 0; i < nsects; i++) {
990 elf_section_header(p - shstrtab, sects[i]->type, sects[i]->flags,
991 (sects[i]->type == SHT_PROGBITS ?
992 sects[i]->data : NULL), true,
993 sects[i]->len, 0, 0, sects[i]->align, 0);
994 p += strlen(p) + 1;
997 /* .shstrtab */
998 elf_section_header(p - shstrtab, SHT_STRTAB, 0, shstrtab, false,
999 shstrtablen, 0, 0, 1, 0);
1000 p += strlen(p) + 1;
1002 /* .symtab */
1003 elf_section_header(p - shstrtab, SHT_SYMTAB, 0, symtab, true,
1004 symtablen, sec_strtab, symtablocal, 4, 16);
1005 p += strlen(p) + 1;
1007 /* .strtab */
1008 elf_section_header(p - shstrtab, SHT_STRTAB, 0, strs, true,
1009 strslen, 0, 0, 1, 0);
1010 p += strlen(p) + 1;
1012 /* The relocation sections */
1013 for (i = 0; i < nsects; i++)
1014 if (sects[i]->head) {
1015 elf_section_header(p - shstrtab, SHT_REL, 0, sects[i]->rel, true,
1016 sects[i]->rellen, sec_symtab, i + 1, 4, 8);
1017 p += strlen(p) + 1;
1020 if (dfmt == &df_stabs) {
1021 /* for debugging information, create the last three sections
1022 which are the .stab , .stabstr and .rel.stab sections respectively */
1024 /* this function call creates the stab sections in memory */
1025 stabs_generate();
1027 if (stabbuf && stabstrbuf && stabrelbuf) {
1028 elf_section_header(p - shstrtab, SHT_PROGBITS, 0, stabbuf, false,
1029 stablen, sec_stabstr, 0, 4, 12);
1030 p += strlen(p) + 1;
1032 elf_section_header(p - shstrtab, SHT_STRTAB, 0, stabstrbuf, false,
1033 stabstrlen, 0, 0, 4, 0);
1034 p += strlen(p) + 1;
1036 /* link -> symtable info -> section to refer to */
1037 elf_section_header(p - shstrtab, SHT_REL, 0, stabrelbuf, false,
1038 stabrellen, sec_symtab, sec_stab, 4, 8);
1039 p += strlen(p) + 1;
1041 } else if (dfmt == &df_dwarf) {
1042 /* for dwarf debugging information, create the ten dwarf sections */
1044 /* this function call creates the dwarf sections in memory */
1045 if (dwarf_fsect)
1046 dwarf_generate();
1048 elf_section_header(p - shstrtab, SHT_PROGBITS, 0, arangesbuf, false,
1049 arangeslen, 0, 0, 1, 0);
1050 p += strlen(p) + 1;
1052 elf_section_header(p - shstrtab, SHT_RELA, 0, arangesrelbuf, false,
1053 arangesrellen, sec_symtab, sec_debug_aranges,
1054 1, 12);
1055 p += strlen(p) + 1;
1057 elf_section_header(p - shstrtab, SHT_PROGBITS, 0, pubnamesbuf,
1058 false, pubnameslen, 0, 0, 1, 0);
1059 p += strlen(p) + 1;
1061 elf_section_header(p - shstrtab, SHT_PROGBITS, 0, infobuf, false,
1062 infolen, 0, 0, 1, 0);
1063 p += strlen(p) + 1;
1065 elf_section_header(p - shstrtab, SHT_RELA, 0, inforelbuf, false,
1066 inforellen, sec_symtab, sec_debug_info, 1, 12);
1067 p += strlen(p) + 1;
1069 elf_section_header(p - shstrtab, SHT_PROGBITS, 0, abbrevbuf, false,
1070 abbrevlen, 0, 0, 1, 0);
1071 p += strlen(p) + 1;
1073 elf_section_header(p - shstrtab, SHT_PROGBITS, 0, linebuf, false,
1074 linelen, 0, 0, 1, 0);
1075 p += strlen(p) + 1;
1077 elf_section_header(p - shstrtab, SHT_RELA, 0, linerelbuf, false,
1078 linerellen, sec_symtab, sec_debug_line, 1, 12);
1079 p += strlen(p) + 1;
1081 elf_section_header(p - shstrtab, SHT_PROGBITS, 0, framebuf, false,
1082 framelen, 0, 0, 8, 0);
1083 p += strlen(p) + 1;
1085 elf_section_header(p - shstrtab, SHT_PROGBITS, 0, locbuf, false,
1086 loclen, 0, 0, 1, 0);
1087 p += strlen(p) + 1;
1089 fwritezero(align, ofile);
1092 * Now output the sections.
1094 elf_write_sections();
1096 nasm_free(elf_sects);
1097 saa_free(symtab);
1100 static struct SAA *elf_build_symtab(int32_t *len, int32_t *local)
1102 struct SAA *s = saa_init(1L);
1103 struct elf_symbol *sym;
1104 uint8_t entry[16], *p;
1105 int i;
1107 *len = *local = 0;
1110 * First, an all-zeros entry, required by the ELF spec.
1112 saa_wbytes(s, NULL, 16L); /* null symbol table entry */
1113 *len += 16;
1114 (*local)++;
1117 * Next, an entry for the file name.
1119 p = entry;
1120 WRITELONG(p, 1); /* we know it's 1st entry in strtab */
1121 WRITELONG(p, 0); /* no value */
1122 WRITELONG(p, 0); /* no size either */
1123 WRITESHORT(p, STT_FILE); /* type FILE */
1124 WRITESHORT(p, SHN_ABS);
1125 saa_wbytes(s, entry, 16L);
1126 *len += 16;
1127 (*local)++;
1130 * Now some standard symbols defining the segments, for relocation
1131 * purposes.
1133 for (i = 1; i <= nsects; i++) {
1134 p = entry;
1135 WRITELONG(p, 0); /* no symbol name */
1136 WRITELONG(p, 0); /* offset zero */
1137 WRITELONG(p, 0); /* size zero */
1138 WRITESHORT(p, STT_SECTION); /* type, binding, and visibility */
1139 WRITESHORT(p, i); /* section id */
1140 saa_wbytes(s, entry, 16L);
1141 *len += 16;
1142 (*local)++;
1146 * Now the other local symbols.
1148 saa_rewind(syms);
1149 while ((sym = saa_rstruct(syms))) {
1150 if (sym->type & SYM_GLOBAL)
1151 continue;
1152 p = entry;
1153 WRITELONG(p, sym->strpos);
1154 WRITELONG(p, sym->symv.key);
1155 WRITELONG(p, sym->size);
1156 WRITECHAR(p, sym->type); /* type and binding */
1157 WRITECHAR(p, sym->other); /* visibility */
1158 WRITESHORT(p, sym->section);
1159 saa_wbytes(s, entry, 16L);
1160 *len += 16;
1161 (*local)++;
1164 * dwarf needs symbols for debug sections
1165 * which are relocation targets.
1167 if (dfmt == &df_dwarf) {
1168 dwarf_infosym = *local;
1169 p = entry;
1170 WRITELONG(p, 0); /* no symbol name */
1171 WRITELONG(p, (uint32_t) 0); /* offset zero */
1172 WRITELONG(p, (uint32_t) 0); /* size zero */
1173 WRITESHORT(p, STT_SECTION); /* type, binding, and visibility */
1174 WRITESHORT(p, sec_debug_info); /* section id */
1175 saa_wbytes(s, entry, 16L);
1176 *len += 16;
1177 (*local)++;
1178 dwarf_abbrevsym = *local;
1179 p = entry;
1180 WRITELONG(p, 0); /* no symbol name */
1181 WRITELONG(p, (uint32_t) 0); /* offset zero */
1182 WRITELONG(p, (uint32_t) 0); /* size zero */
1183 WRITESHORT(p, STT_SECTION); /* type, binding, and visibility */
1184 WRITESHORT(p, sec_debug_abbrev); /* section id */
1185 saa_wbytes(s, entry, 16L);
1186 *len += 16;
1187 (*local)++;
1188 dwarf_linesym = *local;
1189 p = entry;
1190 WRITELONG(p, 0); /* no symbol name */
1191 WRITELONG(p, (uint32_t) 0); /* offset zero */
1192 WRITELONG(p, (uint32_t) 0); /* size zero */
1193 WRITESHORT(p, STT_SECTION); /* type, binding, and visibility */
1194 WRITESHORT(p, sec_debug_line); /* section id */
1195 saa_wbytes(s, entry, 16L);
1196 *len += 16;
1197 (*local)++;
1201 * Now the global symbols.
1203 saa_rewind(syms);
1204 while ((sym = saa_rstruct(syms))) {
1205 if (!(sym->type & SYM_GLOBAL))
1206 continue;
1207 p = entry;
1208 WRITELONG(p, sym->strpos);
1209 WRITELONG(p, sym->symv.key);
1210 WRITELONG(p, sym->size);
1211 WRITECHAR(p, sym->type); /* type and binding */
1212 WRITECHAR(p, sym->other); /* visibility */
1213 WRITESHORT(p, sym->section);
1214 saa_wbytes(s, entry, 16L);
1215 *len += 16;
1218 return s;
1221 static struct SAA *elf_build_reltab(uint64_t *len, struct elf_reloc *r)
1223 struct SAA *s;
1224 uint8_t *p, entry[8];
1225 int32_t global_offset;
1227 if (!r)
1228 return NULL;
1230 s = saa_init(1L);
1231 *len = 0;
1234 * How to onvert from a global placeholder to a real symbol index;
1235 * the +2 refers to the two special entries, the null entry and
1236 * the filename entry.
1238 global_offset = -GLOBAL_TEMP_BASE + nsects + nlocals + ndebugs + 2;
1240 while (r) {
1241 int32_t sym = r->symbol;
1243 if (sym >= GLOBAL_TEMP_BASE)
1244 sym += global_offset;
1246 p = entry;
1247 WRITELONG(p, r->address);
1248 WRITELONG(p, (sym << 8) + r->type);
1249 saa_wbytes(s, entry, 8L);
1250 *len += 8;
1252 r = r->next;
1255 return s;
1258 static void elf_section_header(int name, int type, uint64_t flags,
1259 void *data, bool is_saa, uint64_t datalen,
1260 int link, int info, int align, int eltsize)
1262 elf_sects[elf_nsect].data = data;
1263 elf_sects[elf_nsect].len = datalen;
1264 elf_sects[elf_nsect].is_saa = is_saa;
1265 elf_nsect++;
1267 fwriteint32_t((int32_t)name, ofile);
1268 fwriteint32_t((int32_t)type, ofile);
1269 fwriteint32_t((int32_t)flags, ofile);
1270 fwriteint32_t(0L, ofile); /* no address, ever, in object files */
1271 fwriteint32_t(type == 0 ? 0L : elf_foffs, ofile);
1272 fwriteint32_t(datalen, ofile);
1273 if (data)
1274 elf_foffs += ALIGN(datalen, SEC_FILEALIGN);
1275 fwriteint32_t((int32_t)link, ofile);
1276 fwriteint32_t((int32_t)info, ofile);
1277 fwriteint32_t((int32_t)align, ofile);
1278 fwriteint32_t((int32_t)eltsize, ofile);
1281 static void elf_write_sections(void)
1283 int i;
1284 for (i = 0; i < elf_nsect; i++)
1285 if (elf_sects[i].data) {
1286 int32_t len = elf_sects[i].len;
1287 int32_t reallen = ALIGN(len, SEC_FILEALIGN);
1288 int32_t align = reallen - len;
1289 if (elf_sects[i].is_saa)
1290 saa_fpwrite(elf_sects[i].data, ofile);
1291 else
1292 nasm_write(elf_sects[i].data, len, ofile);
1293 fwritezero(align, ofile);
1297 static void elf_sect_write(struct elf_section *sect, const void *data, size_t len)
1299 saa_wbytes(sect->data, data, len);
1300 sect->len += len;
1303 static void elf_sect_writeaddr(struct elf_section *sect, int64_t data, size_t len)
1305 saa_writeaddr(sect->data, data, len);
1306 sect->len += len;
1309 static void elf_sectalign(int32_t seg, unsigned int value)
1311 struct elf_section *s = NULL;
1312 int i;
1314 for (i = 0; i < nsects; i++) {
1315 if (sects[i]->index == seg) {
1316 s = sects[i];
1317 break;
1320 if (!s || !is_power2(value))
1321 return;
1323 if (value > s->align)
1324 s->align = value;
1327 static int32_t elf_segbase(int32_t segment)
1329 return segment;
1332 static void elf_filename(char *inname, char *outname)
1334 strcpy(elf_module, inname);
1335 standard_extension(inname, outname, ".o");
1338 extern macros_t elf_stdmac[];
1340 static int elf_set_info(enum geninfo type, char **val)
1342 (void)type;
1343 (void)val;
1344 return 0;
1346 static const struct dfmt df_dwarf = {
1347 "ELF32 (i386) dwarf debug format for Linux/Unix",
1348 "dwarf",
1349 dwarf_init,
1350 dwarf_linenum,
1351 null_debug_deflabel,
1352 null_debug_directive,
1353 debug_typevalue,
1354 dwarf_output,
1355 dwarf_cleanup
1357 static const struct dfmt df_stabs = {
1358 "ELF32 (i386) stabs debug format for Linux/Unix",
1359 "stabs",
1360 null_debug_init,
1361 stabs_linenum,
1362 null_debug_deflabel,
1363 null_debug_directive,
1364 debug_typevalue,
1365 stabs_output,
1366 stabs_cleanup
1369 static const struct dfmt * const elf32_debugs_arr[3] =
1370 { &df_dwarf, &df_stabs, NULL };
1372 const struct ofmt of_elf32 = {
1373 "ELF32 (i386) object files (e.g. Linux)",
1374 "elf32",
1377 elf32_debugs_arr,
1378 &df_stabs,
1379 elf_stdmac,
1380 elf_init,
1381 elf_set_info,
1382 elf_out,
1383 elf_deflabel,
1384 elf_section_names,
1385 elf_sectalign,
1386 elf_segbase,
1387 elf_directive,
1388 elf_filename,
1389 elf_cleanup
1392 /* common debugging routines */
1393 static void debug_typevalue(int32_t type)
1395 int32_t stype, ssize;
1396 switch (TYM_TYPE(type)) {
1397 case TY_LABEL:
1398 ssize = 0;
1399 stype = STT_NOTYPE;
1400 break;
1401 case TY_BYTE:
1402 ssize = 1;
1403 stype = STT_OBJECT;
1404 break;
1405 case TY_WORD:
1406 ssize = 2;
1407 stype = STT_OBJECT;
1408 break;
1409 case TY_DWORD:
1410 ssize = 4;
1411 stype = STT_OBJECT;
1412 break;
1413 case TY_FLOAT:
1414 ssize = 4;
1415 stype = STT_OBJECT;
1416 break;
1417 case TY_QWORD:
1418 ssize = 8;
1419 stype = STT_OBJECT;
1420 break;
1421 case TY_TBYTE:
1422 ssize = 10;
1423 stype = STT_OBJECT;
1424 break;
1425 case TY_OWORD:
1426 ssize = 16;
1427 stype = STT_OBJECT;
1428 break;
1429 case TY_YWORD:
1430 ssize = 32;
1431 stype = STT_OBJECT;
1432 break;
1433 case TY_COMMON:
1434 ssize = 0;
1435 stype = STT_COMMON;
1436 break;
1437 case TY_SEG:
1438 ssize = 0;
1439 stype = STT_SECTION;
1440 break;
1441 case TY_EXTERN:
1442 ssize = 0;
1443 stype = STT_NOTYPE;
1444 break;
1445 case TY_EQU:
1446 ssize = 0;
1447 stype = STT_NOTYPE;
1448 break;
1449 default:
1450 ssize = 0;
1451 stype = STT_NOTYPE;
1452 break;
1454 if (stype == STT_OBJECT && lastsym && !lastsym->type) {
1455 lastsym->size = ssize;
1456 lastsym->type = stype;
1460 /* stabs debugging routines */
1462 static void stabs_linenum(const char *filename, int32_t linenumber, int32_t segto)
1464 (void)segto;
1465 if (!stabs_filename) {
1466 stabs_filename = (char *)nasm_malloc(strlen(filename) + 1);
1467 strcpy(stabs_filename, filename);
1468 } else {
1469 if (strcmp(stabs_filename, filename)) {
1470 /* yep, a memory leak...this program is one-shot anyway, so who cares...
1471 in fact, this leak comes in quite handy to maintain a list of files
1472 encountered so far in the symbol lines... */
1474 /* why not nasm_free(stabs_filename); we're done with the old one */
1476 stabs_filename = (char *)nasm_malloc(strlen(filename) + 1);
1477 strcpy(stabs_filename, filename);
1480 debug_immcall = 1;
1481 currentline = linenumber;
1484 static void stabs_output(int type, void *param)
1486 struct symlininfo *s;
1487 struct linelist *el;
1488 if (type == TY_DEBUGSYMLIN) {
1489 if (debug_immcall) {
1490 s = (struct symlininfo *)param;
1491 if (!(sects[s->section]->flags & SHF_EXECINSTR))
1492 return; /* line info is only collected for executable sections */
1493 numlinestabs++;
1494 el = (struct linelist *)nasm_malloc(sizeof(struct linelist));
1495 el->info.offset = s->offset;
1496 el->info.section = s->section;
1497 el->info.name = s->name;
1498 el->line = currentline;
1499 el->filename = stabs_filename;
1500 el->next = 0;
1501 if (stabslines) {
1502 stabslines->last->next = el;
1503 stabslines->last = el;
1504 } else {
1505 stabslines = el;
1506 stabslines->last = el;
1510 debug_immcall = 0;
1513 /* for creating the .stab , .stabstr and .rel.stab sections in memory */
1515 static void stabs_generate(void)
1517 int i, numfiles, strsize, numstabs = 0, currfile, mainfileindex;
1518 uint8_t *sbuf, *ssbuf, *rbuf, *sptr, *rptr;
1519 char **allfiles;
1520 int *fileidx;
1522 struct linelist *ptr;
1524 ptr = stabslines;
1526 allfiles = (char **)nasm_zalloc(numlinestabs * sizeof(char *));
1527 numfiles = 0;
1528 while (ptr) {
1529 if (numfiles == 0) {
1530 allfiles[0] = ptr->filename;
1531 numfiles++;
1532 } else {
1533 for (i = 0; i < numfiles; i++) {
1534 if (!strcmp(allfiles[i], ptr->filename))
1535 break;
1537 if (i >= numfiles) {
1538 allfiles[i] = ptr->filename;
1539 numfiles++;
1542 ptr = ptr->next;
1544 strsize = 1;
1545 fileidx = (int *)nasm_malloc(numfiles * sizeof(int));
1546 for (i = 0; i < numfiles; i++) {
1547 fileidx[i] = strsize;
1548 strsize += strlen(allfiles[i]) + 1;
1550 mainfileindex = 0;
1551 for (i = 0; i < numfiles; i++) {
1552 if (!strcmp(allfiles[i], elf_module)) {
1553 mainfileindex = i;
1554 break;
1559 * worst case size of the stab buffer would be:
1560 * the sourcefiles changes each line, which would mean 1 SOL, 1 SYMLIN per line
1561 * plus one "ending" entry
1563 sbuf = (uint8_t *)nasm_malloc((numlinestabs * 2 + 4) *
1564 sizeof(struct stabentry));
1565 ssbuf = (uint8_t *)nasm_malloc(strsize);
1566 rbuf = (uint8_t *)nasm_malloc(numlinestabs * 8 * (2 + 3));
1567 rptr = rbuf;
1569 for (i = 0; i < numfiles; i++)
1570 strcpy((char *)ssbuf + fileidx[i], allfiles[i]);
1571 ssbuf[0] = 0;
1573 stabstrlen = strsize; /* set global variable for length of stab strings */
1575 sptr = sbuf;
1576 ptr = stabslines;
1577 numstabs = 0;
1579 if (ptr) {
1581 * this is the first stab, its strx points to the filename of the
1582 * the source-file, the n_desc field should be set to the number
1583 * of remaining stabs
1585 WRITE_STAB(sptr, fileidx[0], 0, 0, 0, stabstrlen);
1587 /* this is the stab for the main source file */
1588 WRITE_STAB(sptr, fileidx[mainfileindex], N_SO, 0, 0, 0);
1590 /* relocation table entry */
1593 * Since the symbol table has two entries before
1594 * the section symbols, the index in the info.section
1595 * member must be adjusted by adding 2
1598 WRITELONG(rptr, (sptr - sbuf) - 4);
1599 WRITELONG(rptr, ((ptr->info.section + 2) << 8) | R_386_32);
1601 numstabs++;
1602 currfile = mainfileindex;
1605 while (ptr) {
1606 if (strcmp(allfiles[currfile], ptr->filename)) {
1607 /* oops file has changed... */
1608 for (i = 0; i < numfiles; i++)
1609 if (!strcmp(allfiles[i], ptr->filename))
1610 break;
1611 currfile = i;
1612 WRITE_STAB(sptr, fileidx[currfile], N_SOL, 0, 0,
1613 ptr->info.offset);
1614 numstabs++;
1616 /* relocation table entry */
1617 WRITELONG(rptr, (sptr - sbuf) - 4);
1618 WRITELONG(rptr, ((ptr->info.section + 2) << 8) | R_386_32);
1621 WRITE_STAB(sptr, 0, N_SLINE, 0, ptr->line, ptr->info.offset);
1622 numstabs++;
1624 /* relocation table entry */
1626 WRITELONG(rptr, (sptr - sbuf) - 4);
1627 WRITELONG(rptr, ((ptr->info.section + 2) << 8) | R_386_32);
1629 ptr = ptr->next;
1633 /* this is an "ending" token */
1634 WRITE_STAB(sptr, 0, N_SO, 0, 0, 0);
1635 numstabs++;
1637 ((struct stabentry *)sbuf)->n_desc = numstabs;
1639 nasm_free(allfiles);
1640 nasm_free(fileidx);
1642 stablen = (sptr - sbuf);
1643 stabrellen = (rptr - rbuf);
1644 stabrelbuf = rbuf;
1645 stabbuf = sbuf;
1646 stabstrbuf = ssbuf;
1649 static void stabs_cleanup(void)
1651 struct linelist *ptr, *del;
1652 if (!stabslines)
1653 return;
1655 ptr = stabslines;
1656 while (ptr) {
1657 del = ptr;
1658 ptr = ptr->next;
1659 nasm_free(del);
1662 nasm_free(stabbuf);
1663 nasm_free(stabrelbuf);
1664 nasm_free(stabstrbuf);
1667 /* dwarf routines */
1669 static void dwarf_init(void)
1671 ndebugs = 3; /* 3 debug symbols */
1674 static void dwarf_linenum(const char *filename, int32_t linenumber,
1675 int32_t segto)
1677 (void)segto;
1678 dwarf_findfile(filename);
1679 debug_immcall = 1;
1680 currentline = linenumber;
1683 /* called from elf_out with type == TY_DEBUGSYMLIN */
1684 static void dwarf_output(int type, void *param)
1686 int ln, aa, inx, maxln, soc;
1687 struct symlininfo *s;
1688 struct SAA *plinep;
1690 (void)type;
1692 s = (struct symlininfo *)param;
1694 /* line number info is only gathered for executable sections */
1695 if (!(sects[s->section]->flags & SHF_EXECINSTR))
1696 return;
1698 /* Check if section index has changed */
1699 if (!(dwarf_csect && (dwarf_csect->section) == (s->section)))
1700 dwarf_findsect(s->section);
1702 /* do nothing unless line or file has changed */
1703 if (!debug_immcall)
1704 return;
1706 ln = currentline - dwarf_csect->line;
1707 aa = s->offset - dwarf_csect->offset;
1708 inx = dwarf_clist->line;
1709 plinep = dwarf_csect->psaa;
1710 /* check for file change */
1711 if (!(inx == dwarf_csect->file)) {
1712 saa_write8(plinep,DW_LNS_set_file);
1713 saa_write8(plinep,inx);
1714 dwarf_csect->file = inx;
1716 /* check for line change */
1717 if (ln) {
1718 /* test if in range of special op code */
1719 maxln = line_base + line_range;
1720 soc = (ln - line_base) + (line_range * aa) + opcode_base;
1721 if (ln >= line_base && ln < maxln && soc < 256) {
1722 saa_write8(plinep,soc);
1723 } else {
1724 saa_write8(plinep,DW_LNS_advance_line);
1725 saa_wleb128s(plinep,ln);
1726 if (aa) {
1727 saa_write8(plinep,DW_LNS_advance_pc);
1728 saa_wleb128u(plinep,aa);
1731 dwarf_csect->line = currentline;
1732 dwarf_csect->offset = s->offset;
1735 /* show change handled */
1736 debug_immcall = 0;
1740 static void dwarf_generate(void)
1742 uint8_t *pbuf;
1743 int indx;
1744 struct linelist *ftentry;
1745 struct SAA *paranges, *ppubnames, *pinfo, *pabbrev, *plines, *plinep;
1746 struct SAA *parangesrel, *plinesrel, *pinforel;
1747 struct sectlist *psect;
1748 size_t saalen, linepoff, totlen, highaddr;
1750 /* write epilogues for each line program range */
1751 /* and build aranges section */
1752 paranges = saa_init(1L);
1753 parangesrel = saa_init(1L);
1754 saa_write16(paranges,2); /* dwarf version */
1755 saa_write32(parangesrel, paranges->datalen+4);
1756 saa_write32(parangesrel, (dwarf_infosym << 8) + R_386_32); /* reloc to info */
1757 saa_write32(parangesrel, 0);
1758 saa_write32(paranges,0); /* offset into info */
1759 saa_write8(paranges,4); /* pointer size */
1760 saa_write8(paranges,0); /* not segmented */
1761 saa_write32(paranges,0); /* padding */
1762 /* iterate though sectlist entries */
1763 psect = dwarf_fsect;
1764 totlen = 0;
1765 highaddr = 0;
1766 for (indx = 0; indx < dwarf_nsections; indx++) {
1767 plinep = psect->psaa;
1768 /* Line Number Program Epilogue */
1769 saa_write8(plinep,2); /* std op 2 */
1770 saa_write8(plinep,(sects[psect->section]->len)-psect->offset);
1771 saa_write8(plinep,DW_LNS_extended_op);
1772 saa_write8(plinep,1); /* operand length */
1773 saa_write8(plinep,DW_LNE_end_sequence);
1774 totlen += plinep->datalen;
1775 /* range table relocation entry */
1776 saa_write32(parangesrel, paranges->datalen + 4);
1777 saa_write32(parangesrel, ((uint32_t) (psect->section + 2) << 8) + R_386_32);
1778 saa_write32(parangesrel, (uint32_t) 0);
1779 /* range table entry */
1780 saa_write32(paranges,0x0000); /* range start */
1781 saa_write32(paranges,sects[psect->section]->len); /* range length */
1782 highaddr += sects[psect->section]->len;
1783 /* done with this entry */
1784 psect = psect->next;
1786 saa_write32(paranges,0); /* null address */
1787 saa_write32(paranges,0); /* null length */
1788 saalen = paranges->datalen;
1789 arangeslen = saalen + 4;
1790 arangesbuf = pbuf = nasm_malloc(arangeslen);
1791 WRITELONG(pbuf,saalen); /* initial length */
1792 saa_rnbytes(paranges, pbuf, saalen);
1793 saa_free(paranges);
1795 /* build rela.aranges section */
1796 arangesrellen = saalen = parangesrel->datalen;
1797 arangesrelbuf = pbuf = nasm_malloc(arangesrellen);
1798 saa_rnbytes(parangesrel, pbuf, saalen);
1799 saa_free(parangesrel);
1801 /* build pubnames section */
1802 ppubnames = saa_init(1L);
1803 saa_write16(ppubnames,3); /* dwarf version */
1804 saa_write32(ppubnames,0); /* offset into info */
1805 saa_write32(ppubnames,0); /* space used in info */
1806 saa_write32(ppubnames,0); /* end of list */
1807 saalen = ppubnames->datalen;
1808 pubnameslen = saalen + 4;
1809 pubnamesbuf = pbuf = nasm_malloc(pubnameslen);
1810 WRITELONG(pbuf,saalen); /* initial length */
1811 saa_rnbytes(ppubnames, pbuf, saalen);
1812 saa_free(ppubnames);
1814 /* build info section */
1815 pinfo = saa_init(1L);
1816 pinforel = saa_init(1L);
1817 saa_write16(pinfo,2); /* dwarf version */
1818 saa_write32(pinforel, pinfo->datalen + 4);
1819 saa_write32(pinforel, (dwarf_abbrevsym << 8) + R_386_32); /* reloc to abbrev */
1820 saa_write32(pinforel, 0);
1821 saa_write32(pinfo,0); /* offset into abbrev */
1822 saa_write8(pinfo,4); /* pointer size */
1823 saa_write8(pinfo,1); /* abbrviation number LEB128u */
1824 saa_write32(pinforel, pinfo->datalen + 4);
1825 saa_write32(pinforel, ((dwarf_fsect->section + 2) << 8) + R_386_32);
1826 saa_write32(pinforel, 0);
1827 saa_write32(pinfo,0); /* DW_AT_low_pc */
1828 saa_write32(pinforel, pinfo->datalen + 4);
1829 saa_write32(pinforel, ((dwarf_fsect->section + 2) << 8) + R_386_32);
1830 saa_write32(pinforel, 0);
1831 saa_write32(pinfo,highaddr); /* DW_AT_high_pc */
1832 saa_write32(pinforel, pinfo->datalen + 4);
1833 saa_write32(pinforel, (dwarf_linesym << 8) + R_386_32); /* reloc to line */
1834 saa_write32(pinforel, 0);
1835 saa_write32(pinfo,0); /* DW_AT_stmt_list */
1836 saa_wbytes(pinfo, elf_module, strlen(elf_module)+1);
1837 saa_wbytes(pinfo, nasm_signature, strlen(nasm_signature)+1);
1838 saa_write16(pinfo,DW_LANG_Mips_Assembler);
1839 saa_write8(pinfo,2); /* abbrviation number LEB128u */
1840 saa_write32(pinforel, pinfo->datalen + 4);
1841 saa_write32(pinforel, ((dwarf_fsect->section + 2) << 8) + R_386_32);
1842 saa_write32(pinforel, 0);
1843 saa_write32(pinfo,0); /* DW_AT_low_pc */
1844 saa_write32(pinfo,0); /* DW_AT_frame_base */
1845 saa_write8(pinfo,0); /* end of entries */
1846 saalen = pinfo->datalen;
1847 infolen = saalen + 4;
1848 infobuf = pbuf = nasm_malloc(infolen);
1849 WRITELONG(pbuf,saalen); /* initial length */
1850 saa_rnbytes(pinfo, pbuf, saalen);
1851 saa_free(pinfo);
1853 /* build rela.info section */
1854 inforellen = saalen = pinforel->datalen;
1855 inforelbuf = pbuf = nasm_malloc(inforellen);
1856 saa_rnbytes(pinforel, pbuf, saalen);
1857 saa_free(pinforel);
1859 /* build abbrev section */
1860 pabbrev = saa_init(1L);
1861 saa_write8(pabbrev,1); /* entry number LEB128u */
1862 saa_write8(pabbrev,DW_TAG_compile_unit); /* tag LEB128u */
1863 saa_write8(pabbrev,1); /* has children */
1864 /* the following attributes and forms are all LEB128u values */
1865 saa_write8(pabbrev,DW_AT_low_pc);
1866 saa_write8(pabbrev,DW_FORM_addr);
1867 saa_write8(pabbrev,DW_AT_high_pc);
1868 saa_write8(pabbrev,DW_FORM_addr);
1869 saa_write8(pabbrev,DW_AT_stmt_list);
1870 saa_write8(pabbrev,DW_FORM_data4);
1871 saa_write8(pabbrev,DW_AT_name);
1872 saa_write8(pabbrev,DW_FORM_string);
1873 saa_write8(pabbrev,DW_AT_producer);
1874 saa_write8(pabbrev,DW_FORM_string);
1875 saa_write8(pabbrev,DW_AT_language);
1876 saa_write8(pabbrev,DW_FORM_data2);
1877 saa_write16(pabbrev,0); /* end of entry */
1878 /* LEB128u usage same as above */
1879 saa_write8(pabbrev,2); /* entry number */
1880 saa_write8(pabbrev,DW_TAG_subprogram);
1881 saa_write8(pabbrev,0); /* no children */
1882 saa_write8(pabbrev,DW_AT_low_pc);
1883 saa_write8(pabbrev,DW_FORM_addr);
1884 saa_write8(pabbrev,DW_AT_frame_base);
1885 saa_write8(pabbrev,DW_FORM_data4);
1886 saa_write16(pabbrev,0); /* end of entry */
1887 abbrevlen = saalen = pabbrev->datalen;
1888 abbrevbuf = pbuf = nasm_malloc(saalen);
1889 saa_rnbytes(pabbrev, pbuf, saalen);
1890 saa_free(pabbrev);
1892 /* build line section */
1893 /* prolog */
1894 plines = saa_init(1L);
1895 saa_write8(plines,1); /* Minimum Instruction Length */
1896 saa_write8(plines,1); /* Initial value of 'is_stmt' */
1897 saa_write8(plines,line_base); /* Line Base */
1898 saa_write8(plines,line_range); /* Line Range */
1899 saa_write8(plines,opcode_base); /* Opcode Base */
1900 /* standard opcode lengths (# of LEB128u operands) */
1901 saa_write8(plines,0); /* Std opcode 1 length */
1902 saa_write8(plines,1); /* Std opcode 2 length */
1903 saa_write8(plines,1); /* Std opcode 3 length */
1904 saa_write8(plines,1); /* Std opcode 4 length */
1905 saa_write8(plines,1); /* Std opcode 5 length */
1906 saa_write8(plines,0); /* Std opcode 6 length */
1907 saa_write8(plines,0); /* Std opcode 7 length */
1908 saa_write8(plines,0); /* Std opcode 8 length */
1909 saa_write8(plines,1); /* Std opcode 9 length */
1910 saa_write8(plines,0); /* Std opcode 10 length */
1911 saa_write8(plines,0); /* Std opcode 11 length */
1912 saa_write8(plines,1); /* Std opcode 12 length */
1913 /* Directory Table */
1914 saa_write8(plines,0); /* End of table */
1915 /* File Name Table */
1916 ftentry = dwarf_flist;
1917 for (indx = 0; indx < dwarf_numfiles; indx++) {
1918 saa_wbytes(plines, ftentry->filename, (int32_t)(strlen(ftentry->filename) + 1));
1919 saa_write8(plines,0); /* directory LEB128u */
1920 saa_write8(plines,0); /* time LEB128u */
1921 saa_write8(plines,0); /* size LEB128u */
1922 ftentry = ftentry->next;
1924 saa_write8(plines,0); /* End of table */
1925 linepoff = plines->datalen;
1926 linelen = linepoff + totlen + 10;
1927 linebuf = pbuf = nasm_malloc(linelen);
1928 WRITELONG(pbuf,linelen-4); /* initial length */
1929 WRITESHORT(pbuf,3); /* dwarf version */
1930 WRITELONG(pbuf,linepoff); /* offset to line number program */
1931 /* write line header */
1932 saalen = linepoff;
1933 saa_rnbytes(plines, pbuf, saalen); /* read a given no. of bytes */
1934 pbuf += linepoff;
1935 saa_free(plines);
1936 /* concatonate line program ranges */
1937 linepoff += 13;
1938 plinesrel = saa_init(1L);
1939 psect = dwarf_fsect;
1940 for (indx = 0; indx < dwarf_nsections; indx++) {
1941 saa_write32(plinesrel, linepoff);
1942 saa_write32(plinesrel, ((uint32_t) (psect->section + 2) << 8) + R_386_32);
1943 saa_write32(plinesrel, (uint32_t) 0);
1944 plinep = psect->psaa;
1945 saalen = plinep->datalen;
1946 saa_rnbytes(plinep, pbuf, saalen);
1947 pbuf += saalen;
1948 linepoff += saalen;
1949 saa_free(plinep);
1950 /* done with this entry */
1951 psect = psect->next;
1955 /* build rela.lines section */
1956 linerellen =saalen = plinesrel->datalen;
1957 linerelbuf = pbuf = nasm_malloc(linerellen);
1958 saa_rnbytes(plinesrel, pbuf, saalen);
1959 saa_free(plinesrel);
1961 /* build frame section */
1962 framelen = 4;
1963 framebuf = pbuf = nasm_malloc(framelen);
1964 WRITELONG(pbuf,framelen-4); /* initial length */
1966 /* build loc section */
1967 loclen = 16;
1968 locbuf = pbuf = nasm_malloc(loclen);
1969 WRITELONG(pbuf,0); /* null beginning offset */
1970 WRITELONG(pbuf,0); /* null ending offset */
1973 static void dwarf_cleanup(void)
1975 nasm_free(arangesbuf);
1976 nasm_free(arangesrelbuf);
1977 nasm_free(pubnamesbuf);
1978 nasm_free(infobuf);
1979 nasm_free(inforelbuf);
1980 nasm_free(abbrevbuf);
1981 nasm_free(linebuf);
1982 nasm_free(linerelbuf);
1983 nasm_free(framebuf);
1984 nasm_free(locbuf);
1987 static void dwarf_findfile(const char * fname)
1989 int finx;
1990 struct linelist *match;
1992 /* return if fname is current file name */
1993 if (dwarf_clist && !(strcmp(fname, dwarf_clist->filename)))
1994 return;
1996 /* search for match */
1997 match = 0;
1998 if (dwarf_flist) {
1999 match = dwarf_flist;
2000 for (finx = 0; finx < dwarf_numfiles; finx++) {
2001 if (!(strcmp(fname, match->filename))) {
2002 dwarf_clist = match;
2003 return;
2008 /* add file name to end of list */
2009 dwarf_clist = (struct linelist *)nasm_malloc(sizeof(struct linelist));
2010 dwarf_numfiles++;
2011 dwarf_clist->line = dwarf_numfiles;
2012 dwarf_clist->filename = nasm_malloc(strlen(fname) + 1);
2013 strcpy(dwarf_clist->filename,fname);
2014 dwarf_clist->next = 0;
2015 if (!dwarf_flist) { /* if first entry */
2016 dwarf_flist = dwarf_elist = dwarf_clist;
2017 dwarf_clist->last = 0;
2018 } else { /* chain to previous entry */
2019 dwarf_elist->next = dwarf_clist;
2020 dwarf_elist = dwarf_clist;
2024 static void dwarf_findsect(const int index)
2026 int sinx;
2027 struct sectlist *match;
2028 struct SAA *plinep;
2030 /* return if index is current section index */
2031 if (dwarf_csect && (dwarf_csect->section == index))
2032 return;
2034 /* search for match */
2035 match = 0;
2036 if (dwarf_fsect) {
2037 match = dwarf_fsect;
2038 for (sinx = 0; sinx < dwarf_nsections; sinx++) {
2039 if (match->section == index) {
2040 dwarf_csect = match;
2041 return;
2043 match = match->next;
2047 /* add entry to end of list */
2048 dwarf_csect = (struct sectlist *)nasm_malloc(sizeof(struct sectlist));
2049 dwarf_nsections++;
2050 dwarf_csect->psaa = plinep = saa_init(1L);
2051 dwarf_csect->line = 1;
2052 dwarf_csect->offset = 0;
2053 dwarf_csect->file = 1;
2054 dwarf_csect->section = index;
2055 dwarf_csect->next = 0;
2056 /* set relocatable address at start of line program */
2057 saa_write8(plinep,DW_LNS_extended_op);
2058 saa_write8(plinep,5); /* operand length */
2059 saa_write8(plinep,DW_LNE_set_address);
2060 saa_write32(plinep,0); /* Start Address */
2062 if (!dwarf_fsect) { /* if first entry */
2063 dwarf_fsect = dwarf_esect = dwarf_csect;
2064 dwarf_csect->last = 0;
2065 } else { /* chain to previous entry */
2066 dwarf_esect->next = dwarf_csect;
2067 dwarf_esect = dwarf_csect;
2071 #endif /* OF_ELF */