outcoff: BR 2685756: fix SAFESEH with an internal symbol
[nasm/perl-rewrite.git] / output / outbin.c
blob71867c1e297709cf1bf30c1a09e735e2ac8edbf6
1 /* outbin.c output routines for the Netwide Assembler to produce
2 * flat-form binary files
4 * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
5 * Julian Hall. All rights reserved. The software is
6 * redistributable under the license given in the file "LICENSE"
7 * distributed in the NASM archive.
8 */
10 /* This is the extended version of NASM's original binary output
11 * format. It is backward compatible with the original BIN format,
12 * and contains support for multiple sections and advanced section
13 * ordering.
15 * Feature summary:
17 * - Users can create an arbitrary number of sections; they are not
18 * limited to just ".text", ".data", and ".bss".
20 * - Sections can be either progbits or nobits type.
22 * - You can specify that they be aligned at a certian boundary
23 * following the previous section ("align="), or positioned at an
24 * arbitrary byte-granular location ("start=").
26 * - You can specify a "virtual" start address for a section, which
27 * will be used for the calculation for all address references
28 * with respect to that section ("vstart=").
30 * - The ORG directive, as well as the section/segment directive
31 * arguments ("align=", "start=", "vstart="), can take a critical
32 * expression as their value. For example: "align=(1 << 12)".
34 * - You can generate map files using the 'map' directive.
38 /* Uncomment the following define if you want sections to adapt
39 * their progbits/nobits state depending on what type of
40 * instructions are issued, rather than defaulting to progbits.
41 * Note that this behavior violates the specification.
43 #define ABIN_SMART_ADAPT
47 #include "compiler.h"
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <ctype.h>
53 #include <inttypes.h>
55 #include "nasm.h"
56 #include "nasmlib.h"
57 #include "saa.h"
58 #include "stdscan.h"
59 #include "labels.h"
60 #include "eval.h"
61 #include "outform.h"
62 #include "outlib.h"
64 #ifdef OF_BIN
66 struct ofmt *bin_get_ofmt(); /* Prototype goes here since no header file. */
68 static FILE *fp, *rf = NULL;
69 static efunc error;
71 /* Section flags keep track of which attributes the user has defined. */
72 #define START_DEFINED 0x001
73 #define ALIGN_DEFINED 0x002
74 #define FOLLOWS_DEFINED 0x004
75 #define VSTART_DEFINED 0x008
76 #define VALIGN_DEFINED 0x010
77 #define VFOLLOWS_DEFINED 0x020
78 #define TYPE_DEFINED 0x040
79 #define TYPE_PROGBITS 0x080
80 #define TYPE_NOBITS 0x100
82 /* This struct is used to keep track of symbols for map-file generation. */
83 static struct bin_label {
84 char *name;
85 struct bin_label *next;
86 } *no_seg_labels, **nsl_tail;
88 static struct Section {
89 char *name;
90 struct SAA *contents;
91 int64_t length; /* section length in bytes */
93 /* Section attributes */
94 int flags; /* see flag definitions above */
95 uint64_t align; /* section alignment */
96 uint64_t valign; /* notional section alignment */
97 uint64_t start; /* section start address */
98 uint64_t vstart; /* section virtual start address */
99 char *follows; /* the section that this one will follow */
100 char *vfollows; /* the section that this one will notionally follow */
101 int32_t start_index; /* NASM section id for non-relocated version */
102 int32_t vstart_index; /* the NASM section id */
104 struct bin_label *labels; /* linked-list of label handles for map output. */
105 struct bin_label **labels_end; /* Holds address of end of labels list. */
106 struct Section *ifollows; /* Points to previous section (implicit follows). */
107 struct Section *next; /* This links sections with a defined start address. */
109 /* The extended bin format allows for sections to have a "virtual"
110 * start address. This is accomplished by creating two sections:
111 * one beginning at the Load Memory Address and the other beginning
112 * at the Virtual Memory Address. The LMA section is only used to
113 * define the section.<section_name>.start label, but there isn't
114 * any other good way for us to handle that label.
117 } *sections, *last_section;
119 static struct Reloc {
120 struct Reloc *next;
121 int32_t posn;
122 int32_t bytes;
123 int32_t secref;
124 int32_t secrel;
125 struct Section *target;
126 } *relocs, **reloctail;
128 extern char *stdscan_bufptr;
130 static uint8_t format_mode; /* 0 = original bin, 1 = extended bin */
131 static int32_t current_section; /* only really needed if format_mode = 0 */
132 static uint64_t origin;
133 static int origin_defined;
135 /* Stuff we need for map-file generation. */
136 #define MAP_ORIGIN 1
137 #define MAP_SUMMARY 2
138 #define MAP_SECTIONS 4
139 #define MAP_SYMBOLS 8
140 static int map_control = 0;
141 static char *infile, *outfile;
143 extern macros_t bin_stdmac[];
145 static void add_reloc(struct Section *s, int32_t bytes, int32_t secref,
146 int32_t secrel)
148 struct Reloc *r;
150 r = *reloctail = nasm_malloc(sizeof(struct Reloc));
151 reloctail = &r->next;
152 r->next = NULL;
153 r->posn = s->length;
154 r->bytes = bytes;
155 r->secref = secref;
156 r->secrel = secrel;
157 r->target = s;
160 static struct Section *find_section_by_name(const char *name)
162 struct Section *s;
164 for (s = sections; s; s = s->next)
165 if (!strcmp(s->name, name))
166 break;
167 return s;
170 static struct Section *find_section_by_index(int32_t index)
172 struct Section *s;
174 for (s = sections; s; s = s->next)
175 if ((index == s->vstart_index) || (index == s->start_index))
176 break;
177 return s;
180 static struct Section *create_section(char *name)
181 { /* Create a new section. */
182 last_section->next = nasm_malloc(sizeof(struct Section));
183 last_section->next->ifollows = last_section;
184 last_section = last_section->next;
185 last_section->labels = NULL;
186 last_section->labels_end = &(last_section->labels);
188 /* Initialize section attributes. */
189 last_section->name = nasm_strdup(name);
190 last_section->contents = saa_init(1L);
191 last_section->follows = last_section->vfollows = 0;
192 last_section->length = 0;
193 last_section->flags = 0;
194 last_section->next = NULL;
196 /* Register our sections with NASM. */
197 last_section->vstart_index = seg_alloc();
198 last_section->start_index = seg_alloc();
199 return last_section;
202 static void bin_cleanup(int debuginfo)
204 struct Section *g, **gp;
205 struct Section *gs = NULL, **gsp;
206 struct Section *s, **sp;
207 struct Section *nobits = NULL, **nt;
208 struct Section *last_progbits;
209 struct bin_label *l;
210 struct Reloc *r;
211 uint64_t pend;
212 int h;
214 (void)debuginfo; /* placate optimizers */
216 #ifdef DEBUG
217 fprintf(stdout,
218 "bin_cleanup: Sections were initially referenced in this order:\n");
219 for (h = 0, s = sections; s; h++, s = s->next)
220 fprintf(stdout, "%i. %s\n", h, s->name);
221 #endif
223 /* Assembly has completed, so now we need to generate the output file.
224 * Step 1: Separate progbits and nobits sections into separate lists.
225 * Step 2: Sort the progbits sections into their output order.
226 * Step 3: Compute start addresses for all progbits sections.
227 * Step 4: Compute vstart addresses for all sections.
228 * Step 5: Apply relocations.
229 * Step 6: Write the sections' data to the output file.
230 * Step 7: Generate the map file.
231 * Step 8: Release all allocated memory.
234 /* To do: Smart section-type adaptation could leave some empty sections
235 * without a defined type (progbits/nobits). Won't fix now since this
236 * feature will be disabled. */
238 /* Step 1: Split progbits and nobits sections into separate lists. */
240 nt = &nobits;
241 /* Move nobits sections into a separate list. Also pre-process nobits
242 * sections' attributes. */
243 for (sp = &sections->next, s = sections->next; s; s = *sp) { /* Skip progbits sections. */
244 if (s->flags & TYPE_PROGBITS) {
245 sp = &s->next;
246 continue;
248 /* Do some special pre-processing on nobits sections' attributes. */
249 if (s->flags & (START_DEFINED | ALIGN_DEFINED | FOLLOWS_DEFINED)) { /* Check for a mixture of real and virtual section attributes. */
250 if (s->flags & (VSTART_DEFINED | VALIGN_DEFINED |
251 VFOLLOWS_DEFINED))
252 error(ERR_FATAL|ERR_NOFILE,
253 "cannot mix real and virtual attributes"
254 " in nobits section (%s)", s->name);
255 /* Real and virtual attributes mean the same thing for nobits sections. */
256 if (s->flags & START_DEFINED) {
257 s->vstart = s->start;
258 s->flags |= VSTART_DEFINED;
260 if (s->flags & ALIGN_DEFINED) {
261 s->valign = s->align;
262 s->flags |= VALIGN_DEFINED;
264 if (s->flags & FOLLOWS_DEFINED) {
265 s->vfollows = s->follows;
266 s->flags |= VFOLLOWS_DEFINED;
267 s->flags &= ~FOLLOWS_DEFINED;
270 /* Every section must have a start address. */
271 if (s->flags & VSTART_DEFINED) {
272 s->start = s->vstart;
273 s->flags |= START_DEFINED;
275 /* Move the section into the nobits list. */
276 *sp = s->next;
277 s->next = NULL;
278 *nt = s;
279 nt = &s->next;
282 /* Step 2: Sort the progbits sections into their output order. */
284 /* In Step 2 we move around sections in groups. A group
285 * begins with a section (group leader) that has a user-
286 * defined start address or follows section. The remainder
287 * of the group is made up of the sections that implicitly
288 * follow the group leader (i.e., they were defined after
289 * the group leader and were not given an explicit start
290 * address or follows section by the user). */
292 /* For anyone attempting to read this code:
293 * g (group) points to a group of sections, the first one of which has
294 * a user-defined start address or follows section.
295 * gp (g previous) holds the location of the pointer to g.
296 * gs (g scan) is a temp variable that we use to scan to the end of the group.
297 * gsp (gs previous) holds the location of the pointer to gs.
298 * nt (nobits tail) points to the nobits section-list tail.
301 /* Link all 'follows' groups to their proper position. To do
302 * this we need to know three things: the start of the group
303 * to relocate (g), the section it is following (s), and the
304 * end of the group we're relocating (gs). */
305 for (gp = &sections, g = sections; g; g = gs) { /* Find the next follows group that is out of place (g). */
306 if (!(g->flags & FOLLOWS_DEFINED)) {
307 while (g->next) {
308 if ((g->next->flags & FOLLOWS_DEFINED) &&
309 strcmp(g->name, g->next->follows))
310 break;
311 g = g->next;
313 if (!g->next)
314 break;
315 gp = &g->next;
316 g = g->next;
318 /* Find the section that this group follows (s). */
319 for (sp = &sections, s = sections;
320 s && strcmp(s->name, g->follows);
321 sp = &s->next, s = s->next) ;
322 if (!s)
323 error(ERR_FATAL|ERR_NOFILE, "section %s follows an invalid or"
324 " unknown section (%s)", g->name, g->follows);
325 if (s->next && (s->next->flags & FOLLOWS_DEFINED) &&
326 !strcmp(s->name, s->next->follows))
327 error(ERR_FATAL|ERR_NOFILE, "sections %s and %s can't both follow"
328 " section %s", g->name, s->next->name, s->name);
329 /* Find the end of the current follows group (gs). */
330 for (gsp = &g->next, gs = g->next;
331 gs && (gs != s) && !(gs->flags & START_DEFINED);
332 gsp = &gs->next, gs = gs->next) {
333 if (gs->next && (gs->next->flags & FOLLOWS_DEFINED) &&
334 strcmp(gs->name, gs->next->follows)) {
335 gsp = &gs->next;
336 gs = gs->next;
337 break;
340 /* Re-link the group after its follows section. */
341 *gsp = s->next;
342 s->next = g;
343 *gp = gs;
346 /* Link all 'start' groups to their proper position. Once
347 * again we need to know g, s, and gs (see above). The main
348 * difference is we already know g since we sort by moving
349 * groups from the 'unsorted' list into a 'sorted' list (g
350 * will always be the first section in the unsorted list). */
351 for (g = sections, sections = NULL; g; g = gs) { /* Find the section that we will insert this group before (s). */
352 for (sp = &sections, s = sections; s; sp = &s->next, s = s->next)
353 if ((s->flags & START_DEFINED) && (g->start < s->start))
354 break;
355 /* Find the end of the group (gs). */
356 for (gs = g->next, gsp = &g->next;
357 gs && !(gs->flags & START_DEFINED);
358 gsp = &gs->next, gs = gs->next) ;
359 /* Re-link the group before the target section. */
360 *sp = g;
361 *gsp = s;
364 /* Step 3: Compute start addresses for all progbits sections. */
366 /* Make sure we have an origin and a start address for the first section. */
367 if (origin_defined) {
368 if (sections->flags & START_DEFINED) {
369 /* Make sure this section doesn't begin before the origin. */
370 if (sections->start < origin)
371 error(ERR_FATAL|ERR_NOFILE, "section %s begins"
372 " before program origin", sections->name);
373 } else if (sections->flags & ALIGN_DEFINED) {
374 sections->start = ((origin + sections->align - 1) &
375 ~(sections->align - 1));
376 } else {
377 sections->start = origin;
379 } else {
380 if (!(sections->flags & START_DEFINED))
381 sections->start = 0;
382 origin = sections->start;
384 sections->flags |= START_DEFINED;
386 /* Make sure each section has an explicit start address. If it
387 * doesn't, then compute one based its alignment and the end of
388 * the previous section. */
389 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
390 * (has a defined start address, and is not zero length). */
391 if (g == s)
392 for (s = g->next;
393 s && ((s->length == 0) || !(s->flags & START_DEFINED));
394 s = s->next) ;
395 /* Compute the start address of this section, if necessary. */
396 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
397 if (!(g->flags & ALIGN_DEFINED)) {
398 g->align = 4;
399 g->flags |= ALIGN_DEFINED;
401 /* Set the section start address. */
402 g->start = (pend + g->align - 1) & ~(g->align - 1);
403 g->flags |= START_DEFINED;
405 /* Ugly special case for progbits sections' virtual attributes:
406 * If there is a defined valign, but no vstart and no vfollows, then
407 * we valign after the previous progbits section. This case doesn't
408 * really make much sense for progbits sections with a defined start
409 * address, but it is possible and we must do *something*.
410 * Not-so-ugly special case:
411 * If a progbits section has no virtual attributes, we set the
412 * vstart equal to the start address. */
413 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
414 if (g->flags & VALIGN_DEFINED)
415 g->vstart = (pend + g->valign - 1) & ~(g->valign - 1);
416 else
417 g->vstart = g->start;
418 g->flags |= VSTART_DEFINED;
420 /* Ignore zero-length sections. */
421 if (g->start < pend)
422 continue;
423 /* Compute the span of this section. */
424 pend = g->start + g->length;
425 /* Check for section overlap. */
426 if (s) {
427 if (s->start < origin)
428 error(ERR_FATAL|ERR_NOFILE, "section %s beings before program origin",
429 s->name);
430 if (g->start > s->start)
431 error(ERR_FATAL|ERR_NOFILE, "sections %s ~ %s and %s overlap!",
432 gs->name, g->name, s->name);
433 if (pend > s->start)
434 error(ERR_FATAL|ERR_NOFILE, "sections %s and %s overlap!",
435 g->name, s->name);
437 /* Remember this section as the latest >0 length section. */
438 gs = g;
441 /* Step 4: Compute vstart addresses for all sections. */
443 /* Attach the nobits sections to the end of the progbits sections. */
444 for (s = sections; s->next; s = s->next) ;
445 s->next = nobits;
446 last_progbits = s;
448 * Scan for sections that don't have a vstart address. If we find
449 * one we'll attempt to compute its vstart. If we can't compute
450 * the vstart, we leave it alone and come back to it in a
451 * subsequent scan. We continue scanning and re-scanning until
452 * we've gone one full cycle without computing any vstarts.
454 do { /* Do one full scan of the sections list. */
455 for (h = 0, g = sections; g; g = g->next) {
456 if (g->flags & VSTART_DEFINED)
457 continue;
458 /* Find the section that this one virtually follows. */
459 if (g->flags & VFOLLOWS_DEFINED) {
460 for (s = sections; s && strcmp(g->vfollows, s->name);
461 s = s->next) ;
462 if (!s)
463 error(ERR_FATAL|ERR_NOFILE,
464 "section %s vfollows unknown section (%s)",
465 g->name, g->vfollows);
466 } else if (g->ifollows != NULL)
467 for (s = sections; s && (s != g->ifollows); s = s->next) ;
468 /* The .bss section is the only one with ifollows = NULL.
469 In this case we implicitly follow the last progbits
470 section. */
471 else
472 s = last_progbits;
474 /* If the section we're following has a vstart, we can proceed. */
475 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
476 if (!(g->flags & VALIGN_DEFINED)) {
477 g->valign = 4;
478 g->flags |= VALIGN_DEFINED;
480 /* Compute the vstart address. */
481 g->vstart = (s->vstart + s->length + g->valign - 1)
482 & ~(g->valign - 1);
483 g->flags |= VSTART_DEFINED;
484 h++;
485 /* Start and vstart mean the same thing for nobits sections. */
486 if (g->flags & TYPE_NOBITS)
487 g->start = g->vstart;
490 } while (h);
492 /* Now check for any circular vfollows references, which will manifest
493 * themselves as sections without a defined vstart. */
494 for (h = 0, s = sections; s; s = s->next) {
495 if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
496 * no-no, but we'll throw a fatal one eventually so it's ok. */
497 error(ERR_NONFATAL, "cannot compute vstart for section %s",
498 s->name);
499 h++;
502 if (h)
503 error(ERR_FATAL|ERR_NOFILE, "circular vfollows path detected");
505 #ifdef DEBUG
506 fprintf(stdout,
507 "bin_cleanup: Confirm final section order for output file:\n");
508 for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
509 h++, s = s->next)
510 fprintf(stdout, "%i. %s\n", h, s->name);
511 #endif
513 /* Step 5: Apply relocations. */
515 /* Prepare the sections for relocating. */
516 for (s = sections; s; s = s->next)
517 saa_rewind(s->contents);
518 /* Apply relocations. */
519 for (r = relocs; r; r = r->next) {
520 uint8_t *p, *q, mydata[8];
521 int64_t l;
523 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
524 p = q = mydata;
525 l = *p++;
527 if (r->bytes > 1) {
528 l += ((int64_t)*p++) << 8;
529 if (r->bytes >= 4) {
530 l += ((int64_t)*p++) << 16;
531 l += ((int64_t)*p++) << 24;
533 if (r->bytes == 8) {
534 l += ((int64_t)*p++) << 32;
535 l += ((int64_t)*p++) << 40;
536 l += ((int64_t)*p++) << 48;
537 l += ((int64_t)*p++) << 56;
541 s = find_section_by_index(r->secref);
542 if (s) {
543 if (r->secref == s->start_index)
544 l += s->start;
545 else
546 l += s->vstart;
548 s = find_section_by_index(r->secrel);
549 if (s) {
550 if (r->secrel == s->start_index)
551 l -= s->start;
552 else
553 l -= s->vstart;
556 if (r->bytes >= 4)
557 WRITEDLONG(q, l);
558 else if (r->bytes == 2)
559 WRITESHORT(q, l);
560 else
561 *q++ = (uint8_t)(l & 0xFF);
562 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
565 /* Step 6: Write the section data to the output file. */
567 /* Write the progbits sections to the output file. */
568 for (pend = origin, s = sections; s && (s->flags & TYPE_PROGBITS); s = s->next) { /* Skip zero-length sections. */
569 if (s->length == 0)
570 continue;
571 /* Pad the space between sections. */
572 for (h = s->start - pend; h; h--)
573 fputc('\0', fp);
574 /* Write the section to the output file. */
575 if (s->length > 0)
576 saa_fpwrite(s->contents, fp);
577 pend = s->start + s->length;
579 /* Done writing the file, so close it. */
580 fclose(fp);
582 /* Step 7: Generate the map file. */
584 if (map_control) {
585 const char *not_defined = { "not defined" };
587 /* Display input and output file names. */
588 fprintf(rf, "\n- NASM Map file ");
589 for (h = 63; h; h--)
590 fputc('-', rf);
591 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
592 infile, outfile);
594 if (map_control & MAP_ORIGIN) { /* Display program origin. */
595 fprintf(rf, "-- Program origin ");
596 for (h = 61; h; h--)
597 fputc('-', rf);
598 fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
600 /* Display sections summary. */
601 if (map_control & MAP_SUMMARY) {
602 fprintf(rf, "-- Sections (summary) ");
603 for (h = 57; h; h--)
604 fputc('-', rf);
605 fprintf(rf, "\n\nVstart Start Stop "
606 "Length Class Name\n");
607 for (s = sections; s; s = s->next) {
608 fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
609 s->vstart, s->start, s->start + s->length,
610 s->length);
611 if (s->flags & TYPE_PROGBITS)
612 fprintf(rf, "progbits ");
613 else
614 fprintf(rf, "nobits ");
615 fprintf(rf, "%s\n", s->name);
617 fprintf(rf, "\n");
619 /* Display detailed section information. */
620 if (map_control & MAP_SECTIONS) {
621 fprintf(rf, "-- Sections (detailed) ");
622 for (h = 56; h; h--)
623 fputc('-', rf);
624 fprintf(rf, "\n\n");
625 for (s = sections; s; s = s->next) {
626 fprintf(rf, "---- Section %s ", s->name);
627 for (h = 65 - strlen(s->name); h; h--)
628 fputc('-', rf);
629 fprintf(rf, "\n\nclass: ");
630 if (s->flags & TYPE_PROGBITS)
631 fprintf(rf, "progbits");
632 else
633 fprintf(rf, "nobits");
634 fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
635 "\nalign: ", s->length, s->start);
636 if (s->flags & ALIGN_DEFINED)
637 fprintf(rf, "%16"PRIX64"", s->align);
638 else
639 fprintf(rf, not_defined);
640 fprintf(rf, "\nfollows: ");
641 if (s->flags & FOLLOWS_DEFINED)
642 fprintf(rf, "%s", s->follows);
643 else
644 fprintf(rf, not_defined);
645 fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
646 if (s->flags & VALIGN_DEFINED)
647 fprintf(rf, "%16"PRIX64"", s->valign);
648 else
649 fprintf(rf, not_defined);
650 fprintf(rf, "\nvfollows: ");
651 if (s->flags & VFOLLOWS_DEFINED)
652 fprintf(rf, "%s", s->vfollows);
653 else
654 fprintf(rf, not_defined);
655 fprintf(rf, "\n\n");
658 /* Display symbols information. */
659 if (map_control & MAP_SYMBOLS) {
660 int32_t segment;
661 int64_t offset;
663 fprintf(rf, "-- Symbols ");
664 for (h = 68; h; h--)
665 fputc('-', rf);
666 fprintf(rf, "\n\n");
667 if (no_seg_labels) {
668 fprintf(rf, "---- No Section ");
669 for (h = 63; h; h--)
670 fputc('-', rf);
671 fprintf(rf, "\n\nValue Name\n");
672 for (l = no_seg_labels; l; l = l->next) {
673 lookup_label(l->name, &segment, &offset);
674 fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
676 fprintf(rf, "\n\n");
678 for (s = sections; s; s = s->next) {
679 if (s->labels) {
680 fprintf(rf, "---- Section %s ", s->name);
681 for (h = 65 - strlen(s->name); h; h--)
682 fputc('-', rf);
683 fprintf(rf, "\n\nReal Virtual Name\n");
684 for (l = s->labels; l; l = l->next) {
685 lookup_label(l->name, &segment, &offset);
686 fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
687 s->start + offset, s->vstart + offset,
688 l->name);
690 fprintf(rf, "\n");
696 /* Close the report file. */
697 if (map_control && (rf != stdout) && (rf != stderr))
698 fclose(rf);
700 /* Step 8: Release all allocated memory. */
702 /* Free sections, label pointer structs, etc.. */
703 while (sections) {
704 s = sections;
705 sections = s->next;
706 saa_free(s->contents);
707 nasm_free(s->name);
708 if (s->flags & FOLLOWS_DEFINED)
709 nasm_free(s->follows);
710 if (s->flags & VFOLLOWS_DEFINED)
711 nasm_free(s->vfollows);
712 while (s->labels) {
713 l = s->labels;
714 s->labels = l->next;
715 nasm_free(l);
717 nasm_free(s);
720 /* Free no-section labels. */
721 while (no_seg_labels) {
722 l = no_seg_labels;
723 no_seg_labels = l->next;
724 nasm_free(l);
727 /* Free relocation structures. */
728 while (relocs) {
729 r = relocs->next;
730 nasm_free(relocs);
731 relocs = r;
735 static void bin_out(int32_t segto, const void *data,
736 enum out_type type, uint64_t size,
737 int32_t segment, int32_t wrt)
739 uint8_t *p, mydata[8];
740 struct Section *s;
742 if (wrt != NO_SEG) {
743 wrt = NO_SEG; /* continue to do _something_ */
744 error(ERR_NONFATAL, "WRT not supported by binary output format");
747 /* Handle absolute-assembly (structure definitions). */
748 if (segto == NO_SEG) {
749 if (type != OUT_RESERVE)
750 error(ERR_NONFATAL, "attempt to assemble code in"
751 " [ABSOLUTE] space");
752 return;
755 /* Find the segment we are targeting. */
756 s = find_section_by_index(segto);
757 if (!s)
758 error(ERR_PANIC, "code directed to nonexistent segment?");
760 /* "Smart" section-type adaptation code. */
761 if (!(s->flags & TYPE_DEFINED)) {
762 if (type == OUT_RESERVE)
763 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
764 else
765 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
768 if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
769 error(ERR_WARNING, "attempt to initialize memory in a"
770 " nobits section: ignored");
772 if (type == OUT_ADDRESS) {
773 if (segment != NO_SEG && !find_section_by_index(segment)) {
774 if (segment % 2)
775 error(ERR_NONFATAL, "binary output format does not support"
776 " segment base references");
777 else
778 error(ERR_NONFATAL, "binary output format does not support"
779 " external references");
780 segment = NO_SEG;
782 if (s->flags & TYPE_PROGBITS) {
783 if (segment != NO_SEG)
784 add_reloc(s, size, segment, -1L);
785 p = mydata;
786 WRITEADDR(p, *(int64_t *)data, size);
787 saa_wbytes(s->contents, mydata, size);
789 s->length += size;
790 } else if (type == OUT_RAWDATA) {
791 if (s->flags & TYPE_PROGBITS)
792 saa_wbytes(s->contents, data, size);
793 s->length += size;
794 } else if (type == OUT_RESERVE) {
795 if (s->flags & TYPE_PROGBITS) {
796 error(ERR_WARNING, "uninitialized space declared in"
797 " %s section: zeroing", s->name);
798 saa_wbytes(s->contents, NULL, size);
800 s->length += size;
801 } else if (type == OUT_REL2ADR || type == OUT_REL4ADR ||
802 type == OUT_REL8ADR) {
803 int64_t addr = *(int64_t *)data - size;
804 size = realsize(type, size);
805 if (segment != NO_SEG && !find_section_by_index(segment)) {
806 if (segment % 2)
807 error(ERR_NONFATAL, "binary output format does not support"
808 " segment base references");
809 else
810 error(ERR_NONFATAL, "binary output format does not support"
811 " external references");
812 segment = NO_SEG;
814 if (s->flags & TYPE_PROGBITS) {
815 add_reloc(s, size, segment, segto);
816 p = mydata;
817 WRITEADDR(p, addr - s->length, size);
818 saa_wbytes(s->contents, mydata, size);
820 s->length += size;
824 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
825 int is_global, char *special)
827 (void)segment; /* Don't warn that this parameter is unused */
828 (void)offset; /* Don't warn that this parameter is unused */
830 if (special)
831 error(ERR_NONFATAL, "binary format does not support any"
832 " special symbol types");
833 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
834 error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
835 else if (is_global == 2)
836 error(ERR_NONFATAL, "binary output format does not support common"
837 " variables");
838 else {
839 struct Section *s;
840 struct bin_label ***ltp;
842 /* Remember label definition so we can look it up later when
843 * creating the map file. */
844 s = find_section_by_index(segment);
845 if (s)
846 ltp = &(s->labels_end);
847 else
848 ltp = &nsl_tail;
849 (**ltp) = nasm_malloc(sizeof(struct bin_label));
850 (**ltp)->name = name;
851 (**ltp)->next = NULL;
852 *ltp = &((**ltp)->next);
857 /* These constants and the following function are used
858 * by bin_secname() to parse attribute assignments. */
860 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
861 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
862 ATTRIB_NOBITS, ATTRIB_PROGBITS
865 static int bin_read_attribute(char **line, int *attribute,
866 uint64_t *value)
868 expr *e;
869 int attrib_name_size;
870 struct tokenval tokval;
871 char *exp;
873 /* Skip whitespace. */
874 while (**line && nasm_isspace(**line))
875 (*line)++;
876 if (!**line)
877 return 0;
879 /* Figure out what attribute we're reading. */
880 if (!nasm_strnicmp(*line, "align=", 6)) {
881 *attribute = ATTRIB_ALIGN;
882 attrib_name_size = 6;
883 } else if (format_mode) {
884 if (!nasm_strnicmp(*line, "start=", 6)) {
885 *attribute = ATTRIB_START;
886 attrib_name_size = 6;
887 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
888 *attribute = ATTRIB_FOLLOWS;
889 *line += 8;
890 return 1;
891 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
892 *attribute = ATTRIB_VSTART;
893 attrib_name_size = 7;
894 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
895 *attribute = ATTRIB_VALIGN;
896 attrib_name_size = 7;
897 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
898 *attribute = ATTRIB_VFOLLOWS;
899 *line += 9;
900 return 1;
901 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
902 (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
903 *attribute = ATTRIB_NOBITS;
904 *line += 6;
905 return 1;
906 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
907 (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
908 *attribute = ATTRIB_PROGBITS;
909 *line += 8;
910 return 1;
911 } else
912 return 0;
913 } else
914 return 0;
916 /* Find the end of the expression. */
917 if ((*line)[attrib_name_size] != '(') {
918 /* Single term (no parenthesis). */
919 exp = *line += attrib_name_size;
920 while (**line && !nasm_isspace(**line))
921 (*line)++;
922 if (**line) {
923 **line = '\0';
924 (*line)++;
926 } else {
927 char c;
928 int pcount = 1;
930 /* Full expression (delimited by parenthesis) */
931 exp = *line += attrib_name_size + 1;
932 while (1) {
933 (*line) += strcspn(*line, "()'\"");
934 if (**line == '(') {
935 ++(*line);
936 ++pcount;
938 if (**line == ')') {
939 ++(*line);
940 --pcount;
941 if (!pcount)
942 break;
944 if ((**line == '"') || (**line == '\'')) {
945 c = **line;
946 while (**line) {
947 ++(*line);
948 if (**line == c)
949 break;
951 if (!**line) {
952 error(ERR_NONFATAL,
953 "invalid syntax in `section' directive");
954 return -1;
956 ++(*line);
958 if (!**line) {
959 error(ERR_NONFATAL, "expecting `)'");
960 return -1;
963 *(*line - 1) = '\0'; /* Terminate the expression. */
966 /* Check for no value given. */
967 if (!*exp) {
968 error(ERR_WARNING, "No value given to attribute in"
969 " `section' directive");
970 return -1;
973 /* Read and evaluate the expression. */
974 stdscan_reset();
975 stdscan_bufptr = exp;
976 tokval.t_type = TOKEN_INVALID;
977 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
978 if (e) {
979 if (!is_really_simple(e)) {
980 error(ERR_NONFATAL, "section attribute value must be"
981 " a critical expression");
982 return -1;
984 } else {
985 error(ERR_NONFATAL, "Invalid attribute value"
986 " specified in `section' directive.");
987 return -1;
989 *value = (uint64_t)reloc_value(e);
990 return 1;
993 static void bin_assign_attributes(struct Section *sec, char *astring)
995 int attribute, check;
996 uint64_t value;
997 char *p;
999 while (1) { /* Get the next attribute. */
1000 check = bin_read_attribute(&astring, &attribute, &value);
1001 /* Skip bad attribute. */
1002 if (check == -1)
1003 continue;
1004 /* Unknown section attribute, so skip it and warn the user. */
1005 if (!check) {
1006 if (!*astring)
1007 break; /* End of line. */
1008 else {
1009 p = astring;
1010 while (*astring && !nasm_isspace(*astring))
1011 astring++;
1012 if (*astring) {
1013 *astring = '\0';
1014 astring++;
1016 error(ERR_WARNING, "ignoring unknown section attribute:"
1017 " \"%s\"", p);
1019 continue;
1022 switch (attribute) { /* Handle nobits attribute. */
1023 case ATTRIB_NOBITS:
1024 if ((sec->flags & TYPE_DEFINED)
1025 && (sec->flags & TYPE_PROGBITS))
1026 error(ERR_NONFATAL,
1027 "attempt to change section type"
1028 " from progbits to nobits");
1029 else
1030 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1031 continue;
1033 /* Handle progbits attribute. */
1034 case ATTRIB_PROGBITS:
1035 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1036 error(ERR_NONFATAL, "attempt to change section type"
1037 " from nobits to progbits");
1038 else
1039 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1040 continue;
1042 /* Handle align attribute. */
1043 case ATTRIB_ALIGN:
1044 if (!format_mode && (!strcmp(sec->name, ".text")))
1045 error(ERR_NONFATAL, "cannot specify an alignment"
1046 " to the .text section");
1047 else {
1048 if (!value || ((value - 1) & value))
1049 error(ERR_NONFATAL, "argument to `align' is not a"
1050 " power of two");
1051 else { /* Alignment is already satisfied if the previous
1052 * align value is greater. */
1053 if ((sec->flags & ALIGN_DEFINED)
1054 && (value < sec->align))
1055 value = sec->align;
1057 /* Don't allow a conflicting align value. */
1058 if ((sec->flags & START_DEFINED)
1059 && (sec->start & (value - 1)))
1060 error(ERR_NONFATAL,
1061 "`align' value conflicts "
1062 "with section start address");
1063 else {
1064 sec->align = value;
1065 sec->flags |= ALIGN_DEFINED;
1069 continue;
1071 /* Handle valign attribute. */
1072 case ATTRIB_VALIGN:
1073 if (!value || ((value - 1) & value))
1074 error(ERR_NONFATAL, "argument to `valign' is not a"
1075 " power of two");
1076 else { /* Alignment is already satisfied if the previous
1077 * align value is greater. */
1078 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1079 value = sec->valign;
1081 /* Don't allow a conflicting valign value. */
1082 if ((sec->flags & VSTART_DEFINED)
1083 && (sec->vstart & (value - 1)))
1084 error(ERR_NONFATAL,
1085 "`valign' value conflicts "
1086 "with `vstart' address");
1087 else {
1088 sec->valign = value;
1089 sec->flags |= VALIGN_DEFINED;
1092 continue;
1094 /* Handle start attribute. */
1095 case ATTRIB_START:
1096 if (sec->flags & FOLLOWS_DEFINED)
1097 error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1098 " section attributes");
1099 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1100 error(ERR_NONFATAL, "section start address redefined");
1101 else {
1102 sec->start = value;
1103 sec->flags |= START_DEFINED;
1104 if (sec->flags & ALIGN_DEFINED) {
1105 if (sec->start & (sec->align - 1))
1106 error(ERR_NONFATAL, "`start' address conflicts"
1107 " with section alignment");
1108 sec->flags ^= ALIGN_DEFINED;
1111 continue;
1113 /* Handle vstart attribute. */
1114 case ATTRIB_VSTART:
1115 if (sec->flags & VFOLLOWS_DEFINED)
1116 error(ERR_NONFATAL,
1117 "cannot combine `vstart' and `vfollows'"
1118 " section attributes");
1119 else if ((sec->flags & VSTART_DEFINED)
1120 && (value != sec->vstart))
1121 error(ERR_NONFATAL,
1122 "section virtual start address"
1123 " (vstart) redefined");
1124 else {
1125 sec->vstart = value;
1126 sec->flags |= VSTART_DEFINED;
1127 if (sec->flags & VALIGN_DEFINED) {
1128 if (sec->vstart & (sec->valign - 1))
1129 error(ERR_NONFATAL, "`vstart' address conflicts"
1130 " with `valign' value");
1131 sec->flags ^= VALIGN_DEFINED;
1134 continue;
1136 /* Handle follows attribute. */
1137 case ATTRIB_FOLLOWS:
1138 p = astring;
1139 astring += strcspn(astring, " \t");
1140 if (astring == p)
1141 error(ERR_NONFATAL, "expecting section name for `follows'"
1142 " attribute");
1143 else {
1144 *(astring++) = '\0';
1145 if (sec->flags & START_DEFINED)
1146 error(ERR_NONFATAL,
1147 "cannot combine `start' and `follows'"
1148 " section attributes");
1149 sec->follows = nasm_strdup(p);
1150 sec->flags |= FOLLOWS_DEFINED;
1152 continue;
1154 /* Handle vfollows attribute. */
1155 case ATTRIB_VFOLLOWS:
1156 if (sec->flags & VSTART_DEFINED)
1157 error(ERR_NONFATAL,
1158 "cannot combine `vstart' and `vfollows'"
1159 " section attributes");
1160 else {
1161 p = astring;
1162 astring += strcspn(astring, " \t");
1163 if (astring == p)
1164 error(ERR_NONFATAL,
1165 "expecting section name for `vfollows'"
1166 " attribute");
1167 else {
1168 *(astring++) = '\0';
1169 sec->vfollows = nasm_strdup(p);
1170 sec->flags |= VFOLLOWS_DEFINED;
1173 continue;
1178 static void bin_define_section_labels(void)
1180 static int labels_defined = 0;
1181 struct Section *sec;
1182 char *label_name;
1183 size_t base_len;
1185 if (labels_defined)
1186 return;
1187 for (sec = sections; sec; sec = sec->next) {
1188 base_len = strlen(sec->name) + 8;
1189 label_name = nasm_malloc(base_len + 8);
1190 strcpy(label_name, "section.");
1191 strcpy(label_name + 8, sec->name);
1193 /* section.<name>.start */
1194 strcpy(label_name + base_len, ".start");
1195 define_label(label_name, sec->start_index, 0L,
1196 NULL, 0, 0, bin_get_ofmt(), error);
1198 /* section.<name>.vstart */
1199 strcpy(label_name + base_len, ".vstart");
1200 define_label(label_name, sec->vstart_index, 0L,
1201 NULL, 0, 0, bin_get_ofmt(), error);
1203 nasm_free(label_name);
1205 labels_defined = 1;
1208 static int32_t bin_secname(char *name, int pass, int *bits)
1210 char *p;
1211 struct Section *sec;
1213 /* bin_secname is called with *name = NULL at the start of each
1214 * pass. Use this opportunity to establish the default section
1215 * (default is BITS-16 ".text" segment).
1217 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1218 origin_defined = 0;
1219 for (sec = sections; sec; sec = sec->next)
1220 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1221 ALIGN_DEFINED | VALIGN_DEFINED);
1223 /* Define section start and vstart labels. */
1224 if (format_mode && (pass != 1))
1225 bin_define_section_labels();
1227 /* Establish the default (.text) section. */
1228 *bits = 16;
1229 sec = find_section_by_name(".text");
1230 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1231 current_section = sec->vstart_index;
1232 return current_section;
1235 /* Attempt to find the requested section. If it does not
1236 * exist, create it. */
1237 p = name;
1238 while (*p && !nasm_isspace(*p))
1239 p++;
1240 if (*p)
1241 *p++ = '\0';
1242 sec = find_section_by_name(name);
1243 if (!sec) {
1244 sec = create_section(name);
1245 if (!strcmp(name, ".data"))
1246 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1247 else if (!strcmp(name, ".bss")) {
1248 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1249 sec->ifollows = NULL;
1250 } else if (!format_mode) {
1251 error(ERR_NONFATAL, "section name must be "
1252 ".text, .data, or .bss");
1253 return current_section;
1257 /* Handle attribute assignments. */
1258 if (pass != 1)
1259 bin_assign_attributes(sec, p);
1261 #ifndef ABIN_SMART_ADAPT
1262 /* The following line disables smart adaptation of
1263 * PROGBITS/NOBITS section types (it forces sections to
1264 * default to PROGBITS). */
1265 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1266 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1267 #endif
1269 /* Set the current section and return. */
1270 current_section = sec->vstart_index;
1271 return current_section;
1274 static int bin_directive(char *directive, char *args, int pass)
1276 /* Handle ORG directive */
1277 if (!nasm_stricmp(directive, "org")) {
1278 struct tokenval tokval;
1279 uint64_t value;
1280 expr *e;
1282 stdscan_reset();
1283 stdscan_bufptr = args;
1284 tokval.t_type = TOKEN_INVALID;
1285 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
1286 if (e) {
1287 if (!is_really_simple(e))
1288 error(ERR_NONFATAL, "org value must be a critical"
1289 " expression");
1290 else {
1291 value = reloc_value(e);
1292 /* Check for ORG redefinition. */
1293 if (origin_defined && (value != origin))
1294 error(ERR_NONFATAL, "program origin redefined");
1295 else {
1296 origin = value;
1297 origin_defined = 1;
1300 } else
1301 error(ERR_NONFATAL, "No or invalid offset specified"
1302 " in ORG directive.");
1303 return 1;
1306 /* The 'map' directive allows the user to generate section
1307 * and symbol information to stdout, stderr, or to a file. */
1308 else if (format_mode && !nasm_stricmp(directive, "map")) {
1309 char *p;
1311 if (pass != 1)
1312 return 1;
1313 args += strspn(args, " \t");
1314 while (*args) {
1315 p = args;
1316 args += strcspn(args, " \t");
1317 if (*args != '\0')
1318 *(args++) = '\0';
1319 if (!nasm_stricmp(p, "all"))
1320 map_control |=
1321 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1322 else if (!nasm_stricmp(p, "brief"))
1323 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1324 else if (!nasm_stricmp(p, "sections"))
1325 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1326 else if (!nasm_stricmp(p, "segments"))
1327 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1328 else if (!nasm_stricmp(p, "symbols"))
1329 map_control |= MAP_SYMBOLS;
1330 else if (!rf) {
1331 if (!nasm_stricmp(p, "stdout"))
1332 rf = stdout;
1333 else if (!nasm_stricmp(p, "stderr"))
1334 rf = stderr;
1335 else { /* Must be a filename. */
1336 rf = fopen(p, "wt");
1337 if (!rf) {
1338 error(ERR_WARNING, "unable to open map file `%s'",
1340 map_control = 0;
1341 return 1;
1344 } else
1345 error(ERR_WARNING, "map file already specified");
1347 if (map_control == 0)
1348 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1349 if (!rf)
1350 rf = stdout;
1351 return 1;
1353 return 0;
1356 static void bin_filename(char *inname, char *outname, efunc error)
1358 standard_extension(inname, outname, "", error);
1359 infile = inname;
1360 outfile = outname;
1363 static int32_t bin_segbase(int32_t segment)
1365 return segment;
1368 static int bin_set_info(enum geninfo type, char **val)
1370 (void)type;
1371 (void)val;
1372 return 0;
1375 static void bin_init(FILE * afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1377 fp = afp;
1378 error = errfunc;
1380 (void)eval; /* Don't warn that this parameter is unused. */
1381 (void)ldef; /* Placate optimizers. */
1383 maxbits = 64; /* Support 64-bit Segments */
1384 relocs = NULL;
1385 reloctail = &relocs;
1386 origin_defined = 0;
1387 no_seg_labels = NULL;
1388 nsl_tail = &no_seg_labels;
1389 format_mode = 1; /* Extended bin format
1390 * (set this to zero for old bin format). */
1392 /* Create default section (.text). */
1393 sections = last_section = nasm_malloc(sizeof(struct Section));
1394 last_section->next = NULL;
1395 last_section->name = nasm_strdup(".text");
1396 last_section->contents = saa_init(1L);
1397 last_section->follows = last_section->vfollows = 0;
1398 last_section->ifollows = NULL;
1399 last_section->length = 0;
1400 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1401 last_section->labels = NULL;
1402 last_section->labels_end = &(last_section->labels);
1403 last_section->start_index = seg_alloc();
1404 last_section->vstart_index = current_section = seg_alloc();
1407 struct ofmt of_bin = {
1408 "flat-form binary files (e.g. DOS .COM, .SYS)",
1409 "bin",
1410 NULL,
1411 null_debug_arr,
1412 &null_debug_form,
1413 bin_stdmac,
1414 bin_init,
1415 bin_set_info,
1416 bin_out,
1417 bin_deflabel,
1418 bin_secname,
1419 bin_segbase,
1420 bin_directive,
1421 bin_filename,
1422 bin_cleanup
1425 /* This is needed for bin_define_section_labels() */
1426 struct ofmt *bin_get_ofmt(void)
1428 return &of_bin;
1431 #endif /* #ifdef OF_BIN */