Move the output format macros into the macros.pl mechanism
[nasm/autotest.git] / output / outbin.c
blobe71a60eb6a7e5bab7099a580efc9e99c72cba350
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"
63 #ifdef OF_BIN
65 struct ofmt *bin_get_ofmt(); /* Prototype goes here since no header file. */
67 static FILE *fp, *rf = NULL;
68 static efunc error;
70 /* Section flags keep track of which attributes the user has defined. */
71 #define START_DEFINED 0x001
72 #define ALIGN_DEFINED 0x002
73 #define FOLLOWS_DEFINED 0x004
74 #define VSTART_DEFINED 0x008
75 #define VALIGN_DEFINED 0x010
76 #define VFOLLOWS_DEFINED 0x020
77 #define TYPE_DEFINED 0x040
78 #define TYPE_PROGBITS 0x080
79 #define TYPE_NOBITS 0x100
81 /* This struct is used to keep track of symbols for map-file generation. */
82 static struct bin_label {
83 char *name;
84 struct bin_label *next;
85 } *no_seg_labels, **nsl_tail;
87 static struct Section {
88 char *name;
89 struct SAA *contents;
90 int64_t length; /* section length in bytes */
92 /* Section attributes */
93 int flags; /* see flag definitions above */
94 uint64_t align; /* section alignment */
95 uint64_t valign; /* notional section alignment */
96 uint64_t start; /* section start address */
97 uint64_t vstart; /* section virtual start address */
98 char *follows; /* the section that this one will follow */
99 char *vfollows; /* the section that this one will notionally follow */
100 int32_t start_index; /* NASM section id for non-relocated version */
101 int32_t vstart_index; /* the NASM section id */
103 struct bin_label *labels; /* linked-list of label handles for map output. */
104 struct bin_label **labels_end; /* Holds address of end of labels list. */
105 struct Section *ifollows; /* Points to previous section (implicit follows). */
106 struct Section *next; /* This links sections with a defined start address. */
108 /* The extended bin format allows for sections to have a "virtual"
109 * start address. This is accomplished by creating two sections:
110 * one beginning at the Load Memory Address and the other beginning
111 * at the Virtual Memory Address. The LMA section is only used to
112 * define the section.<section_name>.start label, but there isn't
113 * any other good way for us to handle that label.
116 } *sections, *last_section;
118 static struct Reloc {
119 struct Reloc *next;
120 int32_t posn;
121 int32_t bytes;
122 int32_t secref;
123 int32_t secrel;
124 struct Section *target;
125 } *relocs, **reloctail;
127 extern char *stdscan_bufptr;
129 static uint8_t format_mode; /* 0 = original bin, 1 = extended bin */
130 static int32_t current_section; /* only really needed if format_mode = 0 */
131 static uint64_t origin;
132 static int origin_defined;
134 /* Stuff we need for map-file generation. */
135 #define MAP_ORIGIN 1
136 #define MAP_SUMMARY 2
137 #define MAP_SECTIONS 4
138 #define MAP_SYMBOLS 8
139 static int map_control = 0;
140 static char *infile, *outfile;
142 extern macros_t bin_stdmac[];
144 static void add_reloc(struct Section *s, int32_t bytes, int32_t secref,
145 int32_t secrel)
147 struct Reloc *r;
149 r = *reloctail = nasm_malloc(sizeof(struct Reloc));
150 reloctail = &r->next;
151 r->next = NULL;
152 r->posn = s->length;
153 r->bytes = bytes;
154 r->secref = secref;
155 r->secrel = secrel;
156 r->target = s;
159 static struct Section *find_section_by_name(const char *name)
161 struct Section *s;
163 for (s = sections; s; s = s->next)
164 if (!strcmp(s->name, name))
165 break;
166 return s;
169 static struct Section *find_section_by_index(int32_t index)
171 struct Section *s;
173 for (s = sections; s; s = s->next)
174 if ((index == s->vstart_index) || (index == s->start_index))
175 break;
176 return s;
179 static struct Section *create_section(char *name)
180 { /* Create a new section. */
181 last_section->next = nasm_malloc(sizeof(struct Section));
182 last_section->next->ifollows = last_section;
183 last_section = last_section->next;
184 last_section->labels = NULL;
185 last_section->labels_end = &(last_section->labels);
187 /* Initialize section attributes. */
188 last_section->name = nasm_strdup(name);
189 last_section->contents = saa_init(1L);
190 last_section->follows = last_section->vfollows = 0;
191 last_section->length = 0;
192 last_section->flags = 0;
193 last_section->next = NULL;
195 /* Register our sections with NASM. */
196 last_section->vstart_index = seg_alloc();
197 last_section->start_index = seg_alloc();
198 return last_section;
201 static void bin_cleanup(int debuginfo)
203 struct Section *g, **gp;
204 struct Section *gs = NULL, **gsp;
205 struct Section *s, **sp;
206 struct Section *nobits = NULL, **nt;
207 struct Section *last_progbits;
208 struct bin_label *l;
209 struct Reloc *r;
210 uint64_t pend;
211 int h;
213 (void)debuginfo; /* placate optimizers */
215 #ifdef DEBUG
216 fprintf(stdout,
217 "bin_cleanup: Sections were initially referenced in this order:\n");
218 for (h = 0, s = sections; s; h++, s = s->next)
219 fprintf(stdout, "%i. %s\n", h, s->name);
220 #endif
222 /* Assembly has completed, so now we need to generate the output file.
223 * Step 1: Separate progbits and nobits sections into separate lists.
224 * Step 2: Sort the progbits sections into their output order.
225 * Step 3: Compute start addresses for all progbits sections.
226 * Step 4: Compute vstart addresses for all sections.
227 * Step 5: Apply relocations.
228 * Step 6: Write the sections' data to the output file.
229 * Step 7: Generate the map file.
230 * Step 8: Release all allocated memory.
233 /* To do: Smart section-type adaptation could leave some empty sections
234 * without a defined type (progbits/nobits). Won't fix now since this
235 * feature will be disabled. */
237 /* Step 1: Split progbits and nobits sections into separate lists. */
239 nt = &nobits;
240 /* Move nobits sections into a separate list. Also pre-process nobits
241 * sections' attributes. */
242 for (sp = &sections->next, s = sections->next; s; s = *sp) { /* Skip progbits sections. */
243 if (s->flags & TYPE_PROGBITS) {
244 sp = &s->next;
245 continue;
247 /* Do some special pre-processing on nobits sections' attributes. */
248 if (s->flags & (START_DEFINED | ALIGN_DEFINED | FOLLOWS_DEFINED)) { /* Check for a mixture of real and virtual section attributes. */
249 if (s->
250 flags & (VSTART_DEFINED | VALIGN_DEFINED |
251 VFOLLOWS_DEFINED))
252 error(ERR_FATAL,
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, "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, "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 switch (sections->flags & (START_DEFINED | ALIGN_DEFINED)) {
369 case START_DEFINED | ALIGN_DEFINED:
370 case START_DEFINED:
371 /* Make sure this section doesn't begin before the origin. */
372 if (sections->start < origin)
373 error(ERR_FATAL, "section %s begins"
374 " before program origin", sections->name);
375 break;
376 case ALIGN_DEFINED:
377 sections->start = ((origin + sections->align - 1) &
378 ~(sections->align - 1));
379 break;
380 case 0:
381 sections->start = origin;
382 } else {
383 if (!(sections->flags & START_DEFINED))
384 sections->start = 0;
385 origin = sections->start;
387 sections->flags |= START_DEFINED;
389 /* Make sure each section has an explicit start address. If it
390 * doesn't, then compute one based its alignment and the end of
391 * the previous section. */
392 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
393 * (has a defined start address, and is not zero length). */
394 if (g == s)
395 for (s = g->next;
396 s && ((s->length == 0) || !(s->flags & START_DEFINED));
397 s = s->next) ;
398 /* Compute the start address of this section, if necessary. */
399 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
400 if (!(g->flags & ALIGN_DEFINED)) {
401 g->align = 4;
402 g->flags |= ALIGN_DEFINED;
404 /* Set the section start address. */
405 g->start = (pend + g->align - 1) & ~(g->align - 1);
406 g->flags |= START_DEFINED;
408 /* Ugly special case for progbits sections' virtual attributes:
409 * If there is a defined valign, but no vstart and no vfollows, then
410 * we valign after the previous progbits section. This case doesn't
411 * really make much sense for progbits sections with a defined start
412 * address, but it is possible and we must do *something*.
413 * Not-so-ugly special case:
414 * If a progbits section has no virtual attributes, we set the
415 * vstart equal to the start address. */
416 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
417 if (g->flags & VALIGN_DEFINED)
418 g->vstart = (pend + g->valign - 1) & ~(g->valign - 1);
419 else
420 g->vstart = g->start;
421 g->flags |= VSTART_DEFINED;
423 /* Ignore zero-length sections. */
424 if (g->start < pend)
425 continue;
426 /* Compute the span of this section. */
427 pend = g->start + g->length;
428 /* Check for section overlap. */
429 if (s) {
430 if (g->start > s->start)
431 error(ERR_FATAL, "sections %s ~ %s and %s overlap!",
432 gs->name, g->name, s->name);
433 if (pend > s->start)
434 error(ERR_FATAL, "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;
447 /* Scan for sections that don't have a vstart address. If we find one we'll
448 * attempt to compute its vstart. If we can't compute the vstart, we leave
449 * it alone and come back to it in a subsequent scan. We continue scanning
450 * and re-scanning until we've gone one full cycle without computing any
451 * vstarts. */
452 do { /* Do one full scan of the sections list. */
453 for (h = 0, g = sections; g; g = g->next) {
454 if (g->flags & VSTART_DEFINED)
455 continue;
456 /* Find the section that this one virtually follows. */
457 if (g->flags & VFOLLOWS_DEFINED) {
458 for (s = sections; s && strcmp(g->vfollows, s->name);
459 s = s->next) ;
460 if (!s)
461 error(ERR_FATAL,
462 "section %s vfollows unknown section (%s)",
463 g->name, g->vfollows);
464 } else if (g->ifollows != NULL)
465 for (s = sections; s && (s != g->ifollows); s = s->next) ;
466 /* The .bss section is the only one with ifollows = NULL. In this case we
467 * implicitly follow the last progbits section. */
468 else
469 s = last_progbits;
471 /* If the section we're following has a vstart, we can proceed. */
472 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
473 if (!(g->flags & VALIGN_DEFINED)) {
474 g->valign = 4;
475 g->flags |= VALIGN_DEFINED;
477 /* Compute the vstart address. */
478 g->vstart =
479 (s->vstart + s->length + g->valign - 1) & ~(g->valign -
481 g->flags |= VSTART_DEFINED;
482 h++;
483 /* Start and vstart mean the same thing for nobits sections. */
484 if (g->flags & TYPE_NOBITS)
485 g->start = g->vstart;
488 } while (h);
490 /* Now check for any circular vfollows references, which will manifest
491 * themselves as sections without a defined vstart. */
492 for (h = 0, s = sections; s; s = s->next) {
493 if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
494 * no-no, but we'll throw a fatal one eventually so it's ok. */
495 error(ERR_NONFATAL, "cannot compute vstart for section %s",
496 s->name);
497 h++;
500 if (h)
501 error(ERR_FATAL, "circular vfollows path detected");
503 #ifdef DEBUG
504 fprintf(stdout,
505 "bin_cleanup: Confirm final section order for output file:\n");
506 for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
507 h++, s = s->next)
508 fprintf(stdout, "%i. %s\n", h, s->name);
509 #endif
511 /* Step 5: Apply relocations. */
513 /* Prepare the sections for relocating. */
514 for (s = sections; s; s = s->next)
515 saa_rewind(s->contents);
516 /* Apply relocations. */
517 for (r = relocs; r; r = r->next) {
518 uint8_t *p, *q, mydata[8];
519 int64_t l;
521 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
522 p = q = mydata;
523 l = *p++;
525 if (r->bytes > 1) {
526 l += ((int64_t)*p++) << 8;
527 if (r->bytes >= 4) {
528 l += ((int64_t)*p++) << 16;
529 l += ((int64_t)*p++) << 24;
531 if (r->bytes == 8) {
532 l += ((int64_t)*p++) << 32;
533 l += ((int64_t)*p++) << 40;
534 l += ((int64_t)*p++) << 48;
535 l += ((int64_t)*p++) << 56;
539 s = find_section_by_index(r->secref);
540 if (s) {
541 if (r->secref == s->start_index)
542 l += s->start;
543 else
544 l += s->vstart;
546 s = find_section_by_index(r->secrel);
547 if (s) {
548 if (r->secrel == s->start_index)
549 l -= s->start;
550 else
551 l -= s->vstart;
554 if (r->bytes >= 4)
555 WRITEDLONG(q, l);
556 else if (r->bytes == 2)
557 WRITESHORT(q, l);
558 else
559 *q++ = (uint8_t)(l & 0xFF);
560 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
563 /* Step 6: Write the section data to the output file. */
565 /* Write the progbits sections to the output file. */
566 for (pend = origin, s = sections; s && (s->flags & TYPE_PROGBITS); s = s->next) { /* Skip zero-length sections. */
567 if (s->length == 0)
568 continue;
569 /* Pad the space between sections. */
570 for (h = s->start - pend; h; h--)
571 fputc('\0', fp);
572 /* Write the section to the output file. */
573 if (s->length > 0)
574 saa_fpwrite(s->contents, fp);
575 pend = s->start + s->length;
577 /* Done writing the file, so close it. */
578 fclose(fp);
580 /* Step 7: Generate the map file. */
582 if (map_control) {
583 const char *not_defined = { "not defined" };
585 /* Display input and output file names. */
586 fprintf(rf, "\n- NASM Map file ");
587 for (h = 63; h; h--)
588 fputc('-', rf);
589 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
590 infile, outfile);
592 if (map_control & MAP_ORIGIN) { /* Display program origin. */
593 fprintf(rf, "-- Program origin ");
594 for (h = 61; h; h--)
595 fputc('-', rf);
596 fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
598 /* Display sections summary. */
599 if (map_control & MAP_SUMMARY) {
600 fprintf(rf, "-- Sections (summary) ");
601 for (h = 57; h; h--)
602 fputc('-', rf);
603 fprintf(rf, "\n\nVstart Start Stop "
604 "Length Class Name\n");
605 for (s = sections; s; s = s->next) {
606 fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
607 s->vstart, s->start, s->start + s->length,
608 s->length);
609 if (s->flags & TYPE_PROGBITS)
610 fprintf(rf, "progbits ");
611 else
612 fprintf(rf, "nobits ");
613 fprintf(rf, "%s\n", s->name);
615 fprintf(rf, "\n");
617 /* Display detailed section information. */
618 if (map_control & MAP_SECTIONS) {
619 fprintf(rf, "-- Sections (detailed) ");
620 for (h = 56; h; h--)
621 fputc('-', rf);
622 fprintf(rf, "\n\n");
623 for (s = sections; s; s = s->next) {
624 fprintf(rf, "---- Section %s ", s->name);
625 for (h = 65 - strlen(s->name); h; h--)
626 fputc('-', rf);
627 fprintf(rf, "\n\nclass: ");
628 if (s->flags & TYPE_PROGBITS)
629 fprintf(rf, "progbits");
630 else
631 fprintf(rf, "nobits");
632 fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
633 "\nalign: ", s->length, s->start);
634 if (s->flags & ALIGN_DEFINED)
635 fprintf(rf, "%16"PRIX64"", s->align);
636 else
637 fprintf(rf, not_defined);
638 fprintf(rf, "\nfollows: ");
639 if (s->flags & FOLLOWS_DEFINED)
640 fprintf(rf, "%s", s->follows);
641 else
642 fprintf(rf, not_defined);
643 fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
644 if (s->flags & VALIGN_DEFINED)
645 fprintf(rf, "%16"PRIX64"", s->valign);
646 else
647 fprintf(rf, not_defined);
648 fprintf(rf, "\nvfollows: ");
649 if (s->flags & VFOLLOWS_DEFINED)
650 fprintf(rf, "%s", s->vfollows);
651 else
652 fprintf(rf, not_defined);
653 fprintf(rf, "\n\n");
656 /* Display symbols information. */
657 if (map_control & MAP_SYMBOLS) {
658 int32_t segment;
659 int64_t offset;
661 fprintf(rf, "-- Symbols ");
662 for (h = 68; h; h--)
663 fputc('-', rf);
664 fprintf(rf, "\n\n");
665 if (no_seg_labels) {
666 fprintf(rf, "---- No Section ");
667 for (h = 63; h; h--)
668 fputc('-', rf);
669 fprintf(rf, "\n\nValue Name\n");
670 for (l = no_seg_labels; l; l = l->next) {
671 lookup_label(l->name, &segment, &offset);
672 fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
674 fprintf(rf, "\n\n");
676 for (s = sections; s; s = s->next) {
677 if (s->labels) {
678 fprintf(rf, "---- Section %s ", s->name);
679 for (h = 65 - strlen(s->name); h; h--)
680 fputc('-', rf);
681 fprintf(rf, "\n\nReal Virtual Name\n");
682 for (l = s->labels; l; l = l->next) {
683 lookup_label(l->name, &segment, &offset);
684 fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
685 s->start + offset, s->vstart + offset,
686 l->name);
688 fprintf(rf, "\n");
694 /* Close the report file. */
695 if (map_control && (rf != stdout) && (rf != stderr))
696 fclose(rf);
698 /* Step 8: Release all allocated memory. */
700 /* Free sections, label pointer structs, etc.. */
701 while (sections) {
702 s = sections;
703 sections = s->next;
704 saa_free(s->contents);
705 nasm_free(s->name);
706 if (s->flags & FOLLOWS_DEFINED)
707 nasm_free(s->follows);
708 if (s->flags & VFOLLOWS_DEFINED)
709 nasm_free(s->vfollows);
710 while (s->labels) {
711 l = s->labels;
712 s->labels = l->next;
713 nasm_free(l);
715 nasm_free(s);
718 /* Free no-section labels. */
719 while (no_seg_labels) {
720 l = no_seg_labels;
721 no_seg_labels = l->next;
722 nasm_free(l);
725 /* Free relocation structures. */
726 while (relocs) {
727 r = relocs->next;
728 nasm_free(relocs);
729 relocs = r;
733 static void bin_out(int32_t segto, const void *data,
734 enum out_type type, uint64_t size,
735 int32_t segment, int32_t wrt)
737 uint8_t *p, mydata[8];
738 struct Section *s;
740 if (wrt != NO_SEG) {
741 wrt = NO_SEG; /* continue to do _something_ */
742 error(ERR_NONFATAL, "WRT not supported by binary output format");
745 /* Handle absolute-assembly (structure definitions). */
746 if (segto == NO_SEG) {
747 if (type != OUT_RESERVE)
748 error(ERR_NONFATAL, "attempt to assemble code in"
749 " [ABSOLUTE] space");
750 return;
753 /* Find the segment we are targeting. */
754 s = find_section_by_index(segto);
755 if (!s)
756 error(ERR_PANIC, "code directed to nonexistent segment?");
758 /* "Smart" section-type adaptation code. */
759 if (!(s->flags & TYPE_DEFINED)) {
760 if (type == OUT_RESERVE)
761 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
762 else
763 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
766 if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
767 error(ERR_WARNING, "attempt to initialize memory in a"
768 " nobits section: ignored");
770 if (type == OUT_ADDRESS) {
771 if (segment != NO_SEG && !find_section_by_index(segment)) {
772 if (segment % 2)
773 error(ERR_NONFATAL, "binary output format does not support"
774 " segment base references");
775 else
776 error(ERR_NONFATAL, "binary output format does not support"
777 " external references");
778 segment = NO_SEG;
780 if (s->flags & TYPE_PROGBITS) {
781 if (segment != NO_SEG)
782 add_reloc(s, size, segment, -1L);
783 p = mydata;
784 WRITEADDR(p, *(int64_t *)data, size);
785 saa_wbytes(s->contents, mydata, size);
787 s->length += size;
788 } else if (type == OUT_RAWDATA) {
789 if (s->flags & TYPE_PROGBITS)
790 saa_wbytes(s->contents, data, size);
791 s->length += size;
792 } else if (type == OUT_RESERVE) {
793 if (s->flags & TYPE_PROGBITS) {
794 error(ERR_WARNING, "uninitialized space declared in"
795 " %s section: zeroing", s->name);
796 saa_wbytes(s->contents, NULL, size);
798 s->length += size;
799 } else if (type == OUT_REL2ADR || type == OUT_REL4ADR ||
800 type == OUT_REL8ADR) {
801 switch (type) {
802 case OUT_REL2ADR:
803 size = 2;
804 break;
805 case OUT_REL4ADR:
806 size = 4;
807 break;
808 case OUT_REL8ADR:
809 size = 8;
810 break;
811 default:
812 size = 0; /* Shut up warning */
813 break;
815 if (segment != NO_SEG && !find_section_by_index(segment)) {
816 if (segment % 2)
817 error(ERR_NONFATAL, "binary output format does not support"
818 " segment base references");
819 else
820 error(ERR_NONFATAL, "binary output format does not support"
821 " external references");
822 segment = NO_SEG;
824 if (s->flags & TYPE_PROGBITS) {
825 add_reloc(s, size, segment, segto);
826 p = mydata;
827 WRITEADDR(p, *(int64_t *)data - size - s->length, size);
828 saa_wbytes(s->contents, mydata, size);
830 s->length += size;
834 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
835 int is_global, char *special)
837 (void)segment; /* Don't warn that this parameter is unused */
838 (void)offset; /* Don't warn that this parameter is unused */
840 if (special)
841 error(ERR_NONFATAL, "binary format does not support any"
842 " special symbol types");
843 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
844 error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
845 else if (is_global == 2)
846 error(ERR_NONFATAL, "binary output format does not support common"
847 " variables");
848 else {
849 struct Section *s;
850 struct bin_label ***ltp;
852 /* Remember label definition so we can look it up later when
853 * creating the map file. */
854 s = find_section_by_index(segment);
855 if (s)
856 ltp = &(s->labels_end);
857 else
858 ltp = &nsl_tail;
859 (**ltp) = nasm_malloc(sizeof(struct bin_label));
860 (**ltp)->name = name;
861 (**ltp)->next = NULL;
862 *ltp = &((**ltp)->next);
867 /* These constants and the following function are used
868 * by bin_secname() to parse attribute assignments. */
870 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
871 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
872 ATTRIB_NOBITS, ATTRIB_PROGBITS
875 static int bin_read_attribute(char **line, int *attribute,
876 uint64_t *value)
878 expr *e;
879 int attrib_name_size;
880 struct tokenval tokval;
881 char *exp;
883 /* Skip whitespace. */
884 while (**line && isspace(**line))
885 (*line)++;
886 if (!**line)
887 return 0;
889 /* Figure out what attribute we're reading. */
890 if (!nasm_strnicmp(*line, "align=", 6)) {
891 *attribute = ATTRIB_ALIGN;
892 attrib_name_size = 6;
893 } else if (format_mode) {
894 if (!nasm_strnicmp(*line, "start=", 6)) {
895 *attribute = ATTRIB_START;
896 attrib_name_size = 6;
897 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
898 *attribute = ATTRIB_FOLLOWS;
899 *line += 8;
900 return 1;
901 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
902 *attribute = ATTRIB_VSTART;
903 attrib_name_size = 7;
904 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
905 *attribute = ATTRIB_VALIGN;
906 attrib_name_size = 7;
907 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
908 *attribute = ATTRIB_VFOLLOWS;
909 *line += 9;
910 return 1;
911 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
912 (isspace((*line)[6]) || ((*line)[6] == '\0'))) {
913 *attribute = ATTRIB_NOBITS;
914 *line += 6;
915 return 1;
916 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
917 (isspace((*line)[8]) || ((*line)[8] == '\0'))) {
918 *attribute = ATTRIB_PROGBITS;
919 *line += 8;
920 return 1;
921 } else
922 return 0;
923 } else
924 return 0;
926 /* Find the end of the expression. */
927 if ((*line)[attrib_name_size] != '(') {
928 /* Single term (no parenthesis). */
929 exp = *line += attrib_name_size;
930 while (**line && !isspace(**line))
931 (*line)++;
932 if (**line) {
933 **line = '\0';
934 (*line)++;
936 } else {
937 char c;
938 int pcount = 1;
940 /* Full expression (delimited by parenthesis) */
941 exp = *line += attrib_name_size + 1;
942 while (1) {
943 (*line) += strcspn(*line, "()'\"");
944 if (**line == '(') {
945 ++(*line);
946 ++pcount;
948 if (**line == ')') {
949 ++(*line);
950 --pcount;
951 if (!pcount)
952 break;
954 if ((**line == '"') || (**line == '\'')) {
955 c = **line;
956 while (**line) {
957 ++(*line);
958 if (**line == c)
959 break;
961 if (!**line) {
962 error(ERR_NONFATAL,
963 "invalid syntax in `section' directive");
964 return -1;
966 ++(*line);
968 if (!**line) {
969 error(ERR_NONFATAL, "expecting `)'");
970 return -1;
973 *(*line - 1) = '\0'; /* Terminate the expression. */
976 /* Check for no value given. */
977 if (!*exp) {
978 error(ERR_WARNING, "No value given to attribute in"
979 " `section' directive");
980 return -1;
983 /* Read and evaluate the expression. */
984 stdscan_reset();
985 stdscan_bufptr = exp;
986 tokval.t_type = TOKEN_INVALID;
987 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
988 if (e) {
989 if (!is_really_simple(e)) {
990 error(ERR_NONFATAL, "section attribute value must be"
991 " a critical expression");
992 return -1;
994 } else {
995 error(ERR_NONFATAL, "Invalid attribute value"
996 " specified in `section' directive.");
997 return -1;
999 *value = (uint64_t)reloc_value(e);
1000 return 1;
1003 static void bin_assign_attributes(struct Section *sec, char *astring)
1005 int attribute, check;
1006 uint64_t value;
1007 char *p;
1009 while (1) { /* Get the next attribute. */
1010 check = bin_read_attribute(&astring, &attribute, &value);
1011 /* Skip bad attribute. */
1012 if (check == -1)
1013 continue;
1014 /* Unknown section attribute, so skip it and warn the user. */
1015 if (!check) {
1016 if (!*astring)
1017 break; /* End of line. */
1018 else {
1019 p = astring;
1020 while (*astring && !isspace(*astring))
1021 astring++;
1022 if (*astring) {
1023 *astring = '\0';
1024 astring++;
1026 error(ERR_WARNING, "ignoring unknown section attribute:"
1027 " \"%s\"", p);
1029 continue;
1032 switch (attribute) { /* Handle nobits attribute. */
1033 case ATTRIB_NOBITS:
1034 if ((sec->flags & TYPE_DEFINED)
1035 && (sec->flags & TYPE_PROGBITS))
1036 error(ERR_NONFATAL,
1037 "attempt to change section type"
1038 " from progbits to nobits");
1039 else
1040 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1041 continue;
1043 /* Handle progbits attribute. */
1044 case ATTRIB_PROGBITS:
1045 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1046 error(ERR_NONFATAL, "attempt to change section type"
1047 " from nobits to progbits");
1048 else
1049 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1050 continue;
1052 /* Handle align attribute. */
1053 case ATTRIB_ALIGN:
1054 if (!format_mode && (!strcmp(sec->name, ".text")))
1055 error(ERR_NONFATAL, "cannot specify an alignment"
1056 " to the .text section");
1057 else {
1058 if (!value || ((value - 1) & value))
1059 error(ERR_NONFATAL, "argument to `align' is not a"
1060 " power of two");
1061 else { /* Alignment is already satisfied if the previous
1062 * align value is greater. */
1063 if ((sec->flags & ALIGN_DEFINED)
1064 && (value < sec->align))
1065 value = sec->align;
1067 /* Don't allow a conflicting align value. */
1068 if ((sec->flags & START_DEFINED)
1069 && (sec->start & (value - 1)))
1070 error(ERR_NONFATAL,
1071 "`align' value conflicts "
1072 "with section start address");
1073 else {
1074 sec->align = value;
1075 sec->flags |= ALIGN_DEFINED;
1079 continue;
1081 /* Handle valign attribute. */
1082 case ATTRIB_VALIGN:
1083 if (!value || ((value - 1) & value))
1084 error(ERR_NONFATAL, "argument to `valign' is not a"
1085 " power of two");
1086 else { /* Alignment is already satisfied if the previous
1087 * align value is greater. */
1088 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1089 value = sec->valign;
1091 /* Don't allow a conflicting valign value. */
1092 if ((sec->flags & VSTART_DEFINED)
1093 && (sec->vstart & (value - 1)))
1094 error(ERR_NONFATAL,
1095 "`valign' value conflicts "
1096 "with `vstart' address");
1097 else {
1098 sec->valign = value;
1099 sec->flags |= VALIGN_DEFINED;
1102 continue;
1104 /* Handle start attribute. */
1105 case ATTRIB_START:
1106 if (sec->flags & FOLLOWS_DEFINED)
1107 error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1108 " section attributes");
1109 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1110 error(ERR_NONFATAL, "section start address redefined");
1111 else {
1112 sec->start = value;
1113 sec->flags |= START_DEFINED;
1114 if (sec->flags & ALIGN_DEFINED) {
1115 if (sec->start & (sec->align - 1))
1116 error(ERR_NONFATAL, "`start' address conflicts"
1117 " with section alignment");
1118 sec->flags ^= ALIGN_DEFINED;
1121 continue;
1123 /* Handle vstart attribute. */
1124 case ATTRIB_VSTART:
1125 if (sec->flags & VFOLLOWS_DEFINED)
1126 error(ERR_NONFATAL,
1127 "cannot combine `vstart' and `vfollows'"
1128 " section attributes");
1129 else if ((sec->flags & VSTART_DEFINED)
1130 && (value != sec->vstart))
1131 error(ERR_NONFATAL,
1132 "section virtual start address"
1133 " (vstart) redefined");
1134 else {
1135 sec->vstart = value;
1136 sec->flags |= VSTART_DEFINED;
1137 if (sec->flags & VALIGN_DEFINED) {
1138 if (sec->vstart & (sec->valign - 1))
1139 error(ERR_NONFATAL, "`vstart' address conflicts"
1140 " with `valign' value");
1141 sec->flags ^= VALIGN_DEFINED;
1144 continue;
1146 /* Handle follows attribute. */
1147 case ATTRIB_FOLLOWS:
1148 p = astring;
1149 astring += strcspn(astring, " \t");
1150 if (astring == p)
1151 error(ERR_NONFATAL, "expecting section name for `follows'"
1152 " attribute");
1153 else {
1154 *(astring++) = '\0';
1155 if (sec->flags & START_DEFINED)
1156 error(ERR_NONFATAL,
1157 "cannot combine `start' and `follows'"
1158 " section attributes");
1159 sec->follows = nasm_strdup(p);
1160 sec->flags |= FOLLOWS_DEFINED;
1162 continue;
1164 /* Handle vfollows attribute. */
1165 case ATTRIB_VFOLLOWS:
1166 if (sec->flags & VSTART_DEFINED)
1167 error(ERR_NONFATAL,
1168 "cannot combine `vstart' and `vfollows'"
1169 " section attributes");
1170 else {
1171 p = astring;
1172 astring += strcspn(astring, " \t");
1173 if (astring == p)
1174 error(ERR_NONFATAL,
1175 "expecting section name for `vfollows'"
1176 " attribute");
1177 else {
1178 *(astring++) = '\0';
1179 sec->vfollows = nasm_strdup(p);
1180 sec->flags |= VFOLLOWS_DEFINED;
1183 continue;
1188 static void bin_define_section_labels(void)
1190 static int labels_defined = 0;
1191 struct Section *sec;
1192 char *label_name;
1193 size_t base_len;
1195 if (labels_defined)
1196 return;
1197 for (sec = sections; sec; sec = sec->next) {
1198 base_len = strlen(sec->name) + 8;
1199 label_name = nasm_malloc(base_len + 8);
1200 strcpy(label_name, "section.");
1201 strcpy(label_name + 8, sec->name);
1203 /* section.<name>.start */
1204 strcpy(label_name + base_len, ".start");
1205 define_label(label_name, sec->start_index, 0L,
1206 NULL, 0, 0, bin_get_ofmt(), error);
1208 /* section.<name>.vstart */
1209 strcpy(label_name + base_len, ".vstart");
1210 define_label(label_name, sec->vstart_index, 0L,
1211 NULL, 0, 0, bin_get_ofmt(), error);
1213 nasm_free(label_name);
1215 labels_defined = 1;
1218 static int32_t bin_secname(char *name, int pass, int *bits)
1220 char *p;
1221 struct Section *sec;
1223 /* bin_secname is called with *name = NULL at the start of each
1224 * pass. Use this opportunity to establish the default section
1225 * (default is BITS-16 ".text" segment).
1227 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1228 origin_defined = 0;
1229 for (sec = sections; sec; sec = sec->next)
1230 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1231 ALIGN_DEFINED | VALIGN_DEFINED);
1233 /* Define section start and vstart labels. */
1234 if (format_mode && (pass != 1))
1235 bin_define_section_labels();
1237 /* Establish the default (.text) section. */
1238 *bits = 16;
1239 sec = find_section_by_name(".text");
1240 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1241 current_section = sec->vstart_index;
1242 return current_section;
1245 /* Attempt to find the requested section. If it does not
1246 * exist, create it. */
1247 p = name;
1248 while (*p && !isspace(*p))
1249 p++;
1250 if (*p)
1251 *p++ = '\0';
1252 sec = find_section_by_name(name);
1253 if (!sec) {
1254 sec = create_section(name);
1255 if (!strcmp(name, ".data"))
1256 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1257 else if (!strcmp(name, ".bss")) {
1258 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1259 sec->ifollows = NULL;
1260 } else if (!format_mode) {
1261 error(ERR_NONFATAL, "section name must be "
1262 ".text, .data, or .bss");
1263 return current_section;
1267 /* Handle attribute assignments. */
1268 if (pass != 1)
1269 bin_assign_attributes(sec, p);
1271 #ifndef ABIN_SMART_ADAPT
1272 /* The following line disables smart adaptation of
1273 * PROGBITS/NOBITS section types (it forces sections to
1274 * default to PROGBITS). */
1275 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1276 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1277 #endif
1279 /* Set the current section and return. */
1280 current_section = sec->vstart_index;
1281 return current_section;
1284 static int bin_directive(char *directive, char *args, int pass)
1286 /* Handle ORG directive */
1287 if (!nasm_stricmp(directive, "org")) {
1288 struct tokenval tokval;
1289 uint64_t value;
1290 expr *e;
1292 stdscan_reset();
1293 stdscan_bufptr = args;
1294 tokval.t_type = TOKEN_INVALID;
1295 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
1296 if (e) {
1297 if (!is_really_simple(e))
1298 error(ERR_NONFATAL, "org value must be a critical"
1299 " expression");
1300 else {
1301 value = reloc_value(e);
1302 /* Check for ORG redefinition. */
1303 if (origin_defined && (value != origin))
1304 error(ERR_NONFATAL, "program origin redefined");
1305 else {
1306 origin = value;
1307 origin_defined = 1;
1310 } else
1311 error(ERR_NONFATAL, "No or invalid offset specified"
1312 " in ORG directive.");
1313 return 1;
1316 /* The 'map' directive allows the user to generate section
1317 * and symbol information to stdout, stderr, or to a file. */
1318 else if (format_mode && !nasm_stricmp(directive, "map")) {
1319 char *p;
1321 if (pass != 1)
1322 return 1;
1323 args += strspn(args, " \t");
1324 while (*args) {
1325 p = args;
1326 args += strcspn(args, " \t");
1327 if (*args != '\0')
1328 *(args++) = '\0';
1329 if (!nasm_stricmp(p, "all"))
1330 map_control |=
1331 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1332 else if (!nasm_stricmp(p, "brief"))
1333 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1334 else if (!nasm_stricmp(p, "sections"))
1335 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1336 else if (!nasm_stricmp(p, "segments"))
1337 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1338 else if (!nasm_stricmp(p, "symbols"))
1339 map_control |= MAP_SYMBOLS;
1340 else if (!rf) {
1341 if (!nasm_stricmp(p, "stdout"))
1342 rf = stdout;
1343 else if (!nasm_stricmp(p, "stderr"))
1344 rf = stderr;
1345 else { /* Must be a filename. */
1346 rf = fopen(p, "wt");
1347 if (!rf) {
1348 error(ERR_WARNING, "unable to open map file `%s'",
1350 map_control = 0;
1351 return 1;
1354 } else
1355 error(ERR_WARNING, "map file already specified");
1357 if (map_control == 0)
1358 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1359 if (!rf)
1360 rf = stdout;
1361 return 1;
1363 return 0;
1366 static void bin_filename(char *inname, char *outname, efunc error)
1368 standard_extension(inname, outname, "", error);
1369 infile = inname;
1370 outfile = outname;
1373 static int32_t bin_segbase(int32_t segment)
1375 return segment;
1378 static int bin_set_info(enum geninfo type, char **val)
1380 (void)type;
1381 (void)val;
1382 return 0;
1385 static void bin_init(FILE * afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1387 fp = afp;
1388 error = errfunc;
1390 (void)eval; /* Don't warn that this parameter is unused. */
1391 (void)ldef; /* Placate optimizers. */
1393 maxbits = 64; /* Support 64-bit Segments */
1394 relocs = NULL;
1395 reloctail = &relocs;
1396 origin_defined = 0;
1397 no_seg_labels = NULL;
1398 nsl_tail = &no_seg_labels;
1399 format_mode = 1; /* Extended bin format
1400 * (set this to zero for old bin format). */
1402 /* Create default section (.text). */
1403 sections = last_section = nasm_malloc(sizeof(struct Section));
1404 last_section->next = NULL;
1405 last_section->name = nasm_strdup(".text");
1406 last_section->contents = saa_init(1L);
1407 last_section->follows = last_section->vfollows = 0;
1408 last_section->ifollows = NULL;
1409 last_section->length = 0;
1410 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1411 last_section->labels = NULL;
1412 last_section->labels_end = &(last_section->labels);
1413 last_section->start_index = seg_alloc();
1414 last_section->vstart_index = current_section = seg_alloc();
1417 struct ofmt of_bin = {
1418 "flat-form binary files (e.g. DOS .COM, .SYS)",
1419 "bin",
1420 NULL,
1421 null_debug_arr,
1422 &null_debug_form,
1423 bin_stdmac,
1424 bin_init,
1425 bin_set_info,
1426 bin_out,
1427 bin_deflabel,
1428 bin_secname,
1429 bin_segbase,
1430 bin_directive,
1431 bin_filename,
1432 bin_cleanup
1435 /* This is needed for bin_define_section_labels() */
1436 struct ofmt *bin_get_ofmt(void)
1438 return &of_bin;
1441 #endif /* #ifdef OF_BIN */