Document the as86 ..start label
[nasm.git] / output / outbin.c
blobf6be9643b5ff4d8353b5fa76ae333758ebb86bc9
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->
251 flags & (VSTART_DEFINED | VALIGN_DEFINED |
252 VFOLLOWS_DEFINED))
253 error(ERR_FATAL,
254 "cannot mix real and virtual attributes"
255 " in nobits section (%s)", s->name);
256 /* Real and virtual attributes mean the same thing for nobits sections. */
257 if (s->flags & START_DEFINED) {
258 s->vstart = s->start;
259 s->flags |= VSTART_DEFINED;
261 if (s->flags & ALIGN_DEFINED) {
262 s->valign = s->align;
263 s->flags |= VALIGN_DEFINED;
265 if (s->flags & FOLLOWS_DEFINED) {
266 s->vfollows = s->follows;
267 s->flags |= VFOLLOWS_DEFINED;
268 s->flags &= ~FOLLOWS_DEFINED;
271 /* Every section must have a start address. */
272 if (s->flags & VSTART_DEFINED) {
273 s->start = s->vstart;
274 s->flags |= START_DEFINED;
276 /* Move the section into the nobits list. */
277 *sp = s->next;
278 s->next = NULL;
279 *nt = s;
280 nt = &s->next;
283 /* Step 2: Sort the progbits sections into their output order. */
285 /* In Step 2 we move around sections in groups. A group
286 * begins with a section (group leader) that has a user-
287 * defined start address or follows section. The remainder
288 * of the group is made up of the sections that implicitly
289 * follow the group leader (i.e., they were defined after
290 * the group leader and were not given an explicit start
291 * address or follows section by the user). */
293 /* For anyone attempting to read this code:
294 * g (group) points to a group of sections, the first one of which has
295 * a user-defined start address or follows section.
296 * gp (g previous) holds the location of the pointer to g.
297 * gs (g scan) is a temp variable that we use to scan to the end of the group.
298 * gsp (gs previous) holds the location of the pointer to gs.
299 * nt (nobits tail) points to the nobits section-list tail.
302 /* Link all 'follows' groups to their proper position. To do
303 * this we need to know three things: the start of the group
304 * to relocate (g), the section it is following (s), and the
305 * end of the group we're relocating (gs). */
306 for (gp = &sections, g = sections; g; g = gs) { /* Find the next follows group that is out of place (g). */
307 if (!(g->flags & FOLLOWS_DEFINED)) {
308 while (g->next) {
309 if ((g->next->flags & FOLLOWS_DEFINED) &&
310 strcmp(g->name, g->next->follows))
311 break;
312 g = g->next;
314 if (!g->next)
315 break;
316 gp = &g->next;
317 g = g->next;
319 /* Find the section that this group follows (s). */
320 for (sp = &sections, s = sections;
321 s && strcmp(s->name, g->follows);
322 sp = &s->next, s = s->next) ;
323 if (!s)
324 error(ERR_FATAL, "section %s follows an invalid or"
325 " unknown section (%s)", g->name, g->follows);
326 if (s->next && (s->next->flags & FOLLOWS_DEFINED) &&
327 !strcmp(s->name, s->next->follows))
328 error(ERR_FATAL, "sections %s and %s can't both follow"
329 " section %s", g->name, s->next->name, s->name);
330 /* Find the end of the current follows group (gs). */
331 for (gsp = &g->next, gs = g->next;
332 gs && (gs != s) && !(gs->flags & START_DEFINED);
333 gsp = &gs->next, gs = gs->next) {
334 if (gs->next && (gs->next->flags & FOLLOWS_DEFINED) &&
335 strcmp(gs->name, gs->next->follows)) {
336 gsp = &gs->next;
337 gs = gs->next;
338 break;
341 /* Re-link the group after its follows section. */
342 *gsp = s->next;
343 s->next = g;
344 *gp = gs;
347 /* Link all 'start' groups to their proper position. Once
348 * again we need to know g, s, and gs (see above). The main
349 * difference is we already know g since we sort by moving
350 * groups from the 'unsorted' list into a 'sorted' list (g
351 * will always be the first section in the unsorted list). */
352 for (g = sections, sections = NULL; g; g = gs) { /* Find the section that we will insert this group before (s). */
353 for (sp = &sections, s = sections; s; sp = &s->next, s = s->next)
354 if ((s->flags & START_DEFINED) && (g->start < s->start))
355 break;
356 /* Find the end of the group (gs). */
357 for (gs = g->next, gsp = &g->next;
358 gs && !(gs->flags & START_DEFINED);
359 gsp = &gs->next, gs = gs->next) ;
360 /* Re-link the group before the target section. */
361 *sp = g;
362 *gsp = s;
365 /* Step 3: Compute start addresses for all progbits sections. */
367 /* Make sure we have an origin and a start address for the first section. */
368 if (origin_defined)
369 switch (sections->flags & (START_DEFINED | ALIGN_DEFINED)) {
370 case START_DEFINED | ALIGN_DEFINED:
371 case START_DEFINED:
372 /* Make sure this section doesn't begin before the origin. */
373 if (sections->start < origin)
374 error(ERR_FATAL, "section %s begins"
375 " before program origin", sections->name);
376 break;
377 case ALIGN_DEFINED:
378 sections->start = ((origin + sections->align - 1) &
379 ~(sections->align - 1));
380 break;
381 case 0:
382 sections->start = origin;
383 } else {
384 if (!(sections->flags & START_DEFINED))
385 sections->start = 0;
386 origin = sections->start;
388 sections->flags |= START_DEFINED;
390 /* Make sure each section has an explicit start address. If it
391 * doesn't, then compute one based its alignment and the end of
392 * the previous section. */
393 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
394 * (has a defined start address, and is not zero length). */
395 if (g == s)
396 for (s = g->next;
397 s && ((s->length == 0) || !(s->flags & START_DEFINED));
398 s = s->next) ;
399 /* Compute the start address of this section, if necessary. */
400 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
401 if (!(g->flags & ALIGN_DEFINED)) {
402 g->align = 4;
403 g->flags |= ALIGN_DEFINED;
405 /* Set the section start address. */
406 g->start = (pend + g->align - 1) & ~(g->align - 1);
407 g->flags |= START_DEFINED;
409 /* Ugly special case for progbits sections' virtual attributes:
410 * If there is a defined valign, but no vstart and no vfollows, then
411 * we valign after the previous progbits section. This case doesn't
412 * really make much sense for progbits sections with a defined start
413 * address, but it is possible and we must do *something*.
414 * Not-so-ugly special case:
415 * If a progbits section has no virtual attributes, we set the
416 * vstart equal to the start address. */
417 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
418 if (g->flags & VALIGN_DEFINED)
419 g->vstart = (pend + g->valign - 1) & ~(g->valign - 1);
420 else
421 g->vstart = g->start;
422 g->flags |= VSTART_DEFINED;
424 /* Ignore zero-length sections. */
425 if (g->start < pend)
426 continue;
427 /* Compute the span of this section. */
428 pend = g->start + g->length;
429 /* Check for section overlap. */
430 if (s) {
431 if (g->start > s->start)
432 error(ERR_FATAL, "sections %s ~ %s and %s overlap!",
433 gs->name, g->name, s->name);
434 if (pend > s->start)
435 error(ERR_FATAL, "sections %s and %s overlap!",
436 g->name, s->name);
438 /* Remember this section as the latest >0 length section. */
439 gs = g;
442 /* Step 4: Compute vstart addresses for all sections. */
444 /* Attach the nobits sections to the end of the progbits sections. */
445 for (s = sections; s->next; s = s->next) ;
446 s->next = nobits;
447 last_progbits = s;
448 /* Scan for sections that don't have a vstart address. If we find one we'll
449 * attempt to compute its vstart. If we can't compute the vstart, we leave
450 * it alone and come back to it in a subsequent scan. We continue scanning
451 * and re-scanning until we've gone one full cycle without computing any
452 * vstarts. */
453 do { /* Do one full scan of the sections list. */
454 for (h = 0, g = sections; g; g = g->next) {
455 if (g->flags & VSTART_DEFINED)
456 continue;
457 /* Find the section that this one virtually follows. */
458 if (g->flags & VFOLLOWS_DEFINED) {
459 for (s = sections; s && strcmp(g->vfollows, s->name);
460 s = s->next) ;
461 if (!s)
462 error(ERR_FATAL,
463 "section %s vfollows unknown section (%s)",
464 g->name, g->vfollows);
465 } else if (g->ifollows != NULL)
466 for (s = sections; s && (s != g->ifollows); s = s->next) ;
467 /* The .bss section is the only one with ifollows = NULL. In this case we
468 * implicitly follow the last progbits section. */
469 else
470 s = last_progbits;
472 /* If the section we're following has a vstart, we can proceed. */
473 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
474 if (!(g->flags & VALIGN_DEFINED)) {
475 g->valign = 4;
476 g->flags |= VALIGN_DEFINED;
478 /* Compute the vstart address. */
479 g->vstart =
480 (s->vstart + s->length + g->valign - 1) & ~(g->valign -
482 g->flags |= VSTART_DEFINED;
483 h++;
484 /* Start and vstart mean the same thing for nobits sections. */
485 if (g->flags & TYPE_NOBITS)
486 g->start = g->vstart;
489 } while (h);
491 /* Now check for any circular vfollows references, which will manifest
492 * themselves as sections without a defined vstart. */
493 for (h = 0, s = sections; s; s = s->next) {
494 if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
495 * no-no, but we'll throw a fatal one eventually so it's ok. */
496 error(ERR_NONFATAL, "cannot compute vstart for section %s",
497 s->name);
498 h++;
501 if (h)
502 error(ERR_FATAL, "circular vfollows path detected");
504 #ifdef DEBUG
505 fprintf(stdout,
506 "bin_cleanup: Confirm final section order for output file:\n");
507 for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
508 h++, s = s->next)
509 fprintf(stdout, "%i. %s\n", h, s->name);
510 #endif
512 /* Step 5: Apply relocations. */
514 /* Prepare the sections for relocating. */
515 for (s = sections; s; s = s->next)
516 saa_rewind(s->contents);
517 /* Apply relocations. */
518 for (r = relocs; r; r = r->next) {
519 uint8_t *p, *q, mydata[8];
520 int64_t l;
522 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
523 p = q = mydata;
524 l = *p++;
526 if (r->bytes > 1) {
527 l += ((int64_t)*p++) << 8;
528 if (r->bytes >= 4) {
529 l += ((int64_t)*p++) << 16;
530 l += ((int64_t)*p++) << 24;
532 if (r->bytes == 8) {
533 l += ((int64_t)*p++) << 32;
534 l += ((int64_t)*p++) << 40;
535 l += ((int64_t)*p++) << 48;
536 l += ((int64_t)*p++) << 56;
540 s = find_section_by_index(r->secref);
541 if (s) {
542 if (r->secref == s->start_index)
543 l += s->start;
544 else
545 l += s->vstart;
547 s = find_section_by_index(r->secrel);
548 if (s) {
549 if (r->secrel == s->start_index)
550 l -= s->start;
551 else
552 l -= s->vstart;
555 if (r->bytes >= 4)
556 WRITEDLONG(q, l);
557 else if (r->bytes == 2)
558 WRITESHORT(q, l);
559 else
560 *q++ = (uint8_t)(l & 0xFF);
561 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
564 /* Step 6: Write the section data to the output file. */
566 /* Write the progbits sections to the output file. */
567 for (pend = origin, s = sections; s && (s->flags & TYPE_PROGBITS); s = s->next) { /* Skip zero-length sections. */
568 if (s->length == 0)
569 continue;
570 /* Pad the space between sections. */
571 for (h = s->start - pend; h; h--)
572 fputc('\0', fp);
573 /* Write the section to the output file. */
574 if (s->length > 0)
575 saa_fpwrite(s->contents, fp);
576 pend = s->start + s->length;
578 /* Done writing the file, so close it. */
579 fclose(fp);
581 /* Step 7: Generate the map file. */
583 if (map_control) {
584 const char *not_defined = { "not defined" };
586 /* Display input and output file names. */
587 fprintf(rf, "\n- NASM Map file ");
588 for (h = 63; h; h--)
589 fputc('-', rf);
590 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
591 infile, outfile);
593 if (map_control & MAP_ORIGIN) { /* Display program origin. */
594 fprintf(rf, "-- Program origin ");
595 for (h = 61; h; h--)
596 fputc('-', rf);
597 fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
599 /* Display sections summary. */
600 if (map_control & MAP_SUMMARY) {
601 fprintf(rf, "-- Sections (summary) ");
602 for (h = 57; h; h--)
603 fputc('-', rf);
604 fprintf(rf, "\n\nVstart Start Stop "
605 "Length Class Name\n");
606 for (s = sections; s; s = s->next) {
607 fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
608 s->vstart, s->start, s->start + s->length,
609 s->length);
610 if (s->flags & TYPE_PROGBITS)
611 fprintf(rf, "progbits ");
612 else
613 fprintf(rf, "nobits ");
614 fprintf(rf, "%s\n", s->name);
616 fprintf(rf, "\n");
618 /* Display detailed section information. */
619 if (map_control & MAP_SECTIONS) {
620 fprintf(rf, "-- Sections (detailed) ");
621 for (h = 56; h; h--)
622 fputc('-', rf);
623 fprintf(rf, "\n\n");
624 for (s = sections; s; s = s->next) {
625 fprintf(rf, "---- Section %s ", s->name);
626 for (h = 65 - strlen(s->name); h; h--)
627 fputc('-', rf);
628 fprintf(rf, "\n\nclass: ");
629 if (s->flags & TYPE_PROGBITS)
630 fprintf(rf, "progbits");
631 else
632 fprintf(rf, "nobits");
633 fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
634 "\nalign: ", s->length, s->start);
635 if (s->flags & ALIGN_DEFINED)
636 fprintf(rf, "%16"PRIX64"", s->align);
637 else
638 fprintf(rf, not_defined);
639 fprintf(rf, "\nfollows: ");
640 if (s->flags & FOLLOWS_DEFINED)
641 fprintf(rf, "%s", s->follows);
642 else
643 fprintf(rf, not_defined);
644 fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
645 if (s->flags & VALIGN_DEFINED)
646 fprintf(rf, "%16"PRIX64"", s->valign);
647 else
648 fprintf(rf, not_defined);
649 fprintf(rf, "\nvfollows: ");
650 if (s->flags & VFOLLOWS_DEFINED)
651 fprintf(rf, "%s", s->vfollows);
652 else
653 fprintf(rf, not_defined);
654 fprintf(rf, "\n\n");
657 /* Display symbols information. */
658 if (map_control & MAP_SYMBOLS) {
659 int32_t segment;
660 int64_t offset;
662 fprintf(rf, "-- Symbols ");
663 for (h = 68; h; h--)
664 fputc('-', rf);
665 fprintf(rf, "\n\n");
666 if (no_seg_labels) {
667 fprintf(rf, "---- No Section ");
668 for (h = 63; h; h--)
669 fputc('-', rf);
670 fprintf(rf, "\n\nValue Name\n");
671 for (l = no_seg_labels; l; l = l->next) {
672 lookup_label(l->name, &segment, &offset);
673 fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
675 fprintf(rf, "\n\n");
677 for (s = sections; s; s = s->next) {
678 if (s->labels) {
679 fprintf(rf, "---- Section %s ", s->name);
680 for (h = 65 - strlen(s->name); h; h--)
681 fputc('-', rf);
682 fprintf(rf, "\n\nReal Virtual Name\n");
683 for (l = s->labels; l; l = l->next) {
684 lookup_label(l->name, &segment, &offset);
685 fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
686 s->start + offset, s->vstart + offset,
687 l->name);
689 fprintf(rf, "\n");
695 /* Close the report file. */
696 if (map_control && (rf != stdout) && (rf != stderr))
697 fclose(rf);
699 /* Step 8: Release all allocated memory. */
701 /* Free sections, label pointer structs, etc.. */
702 while (sections) {
703 s = sections;
704 sections = s->next;
705 saa_free(s->contents);
706 nasm_free(s->name);
707 if (s->flags & FOLLOWS_DEFINED)
708 nasm_free(s->follows);
709 if (s->flags & VFOLLOWS_DEFINED)
710 nasm_free(s->vfollows);
711 while (s->labels) {
712 l = s->labels;
713 s->labels = l->next;
714 nasm_free(l);
716 nasm_free(s);
719 /* Free no-section labels. */
720 while (no_seg_labels) {
721 l = no_seg_labels;
722 no_seg_labels = l->next;
723 nasm_free(l);
726 /* Free relocation structures. */
727 while (relocs) {
728 r = relocs->next;
729 nasm_free(relocs);
730 relocs = r;
734 static void bin_out(int32_t segto, const void *data,
735 enum out_type type, uint64_t size,
736 int32_t segment, int32_t wrt)
738 uint8_t *p, mydata[8];
739 struct Section *s;
741 if (wrt != NO_SEG) {
742 wrt = NO_SEG; /* continue to do _something_ */
743 error(ERR_NONFATAL, "WRT not supported by binary output format");
746 /* Handle absolute-assembly (structure definitions). */
747 if (segto == NO_SEG) {
748 if (type != OUT_RESERVE)
749 error(ERR_NONFATAL, "attempt to assemble code in"
750 " [ABSOLUTE] space");
751 return;
754 /* Find the segment we are targeting. */
755 s = find_section_by_index(segto);
756 if (!s)
757 error(ERR_PANIC, "code directed to nonexistent segment?");
759 /* "Smart" section-type adaptation code. */
760 if (!(s->flags & TYPE_DEFINED)) {
761 if (type == OUT_RESERVE)
762 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
763 else
764 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
767 if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
768 error(ERR_WARNING, "attempt to initialize memory in a"
769 " nobits section: ignored");
771 if (type == OUT_ADDRESS) {
772 if (segment != NO_SEG && !find_section_by_index(segment)) {
773 if (segment % 2)
774 error(ERR_NONFATAL, "binary output format does not support"
775 " segment base references");
776 else
777 error(ERR_NONFATAL, "binary output format does not support"
778 " external references");
779 segment = NO_SEG;
781 if (s->flags & TYPE_PROGBITS) {
782 if (segment != NO_SEG)
783 add_reloc(s, size, segment, -1L);
784 p = mydata;
785 WRITEADDR(p, *(int64_t *)data, size);
786 saa_wbytes(s->contents, mydata, size);
788 s->length += size;
789 } else if (type == OUT_RAWDATA) {
790 if (s->flags & TYPE_PROGBITS)
791 saa_wbytes(s->contents, data, size);
792 s->length += size;
793 } else if (type == OUT_RESERVE) {
794 if (s->flags & TYPE_PROGBITS) {
795 error(ERR_WARNING, "uninitialized space declared in"
796 " %s section: zeroing", s->name);
797 saa_wbytes(s->contents, NULL, size);
799 s->length += size;
800 } else if (type == OUT_REL2ADR || type == OUT_REL4ADR ||
801 type == OUT_REL8ADR) {
802 int64_t addr = *(int64_t *)data - size;
803 size = realsize(type, size);
804 if (segment != NO_SEG && !find_section_by_index(segment)) {
805 if (segment % 2)
806 error(ERR_NONFATAL, "binary output format does not support"
807 " segment base references");
808 else
809 error(ERR_NONFATAL, "binary output format does not support"
810 " external references");
811 segment = NO_SEG;
813 if (s->flags & TYPE_PROGBITS) {
814 add_reloc(s, size, segment, segto);
815 p = mydata;
816 WRITEADDR(p, addr - s->length, size);
817 saa_wbytes(s->contents, mydata, size);
819 s->length += size;
823 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
824 int is_global, char *special)
826 (void)segment; /* Don't warn that this parameter is unused */
827 (void)offset; /* Don't warn that this parameter is unused */
829 if (special)
830 error(ERR_NONFATAL, "binary format does not support any"
831 " special symbol types");
832 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
833 error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
834 else if (is_global == 2)
835 error(ERR_NONFATAL, "binary output format does not support common"
836 " variables");
837 else {
838 struct Section *s;
839 struct bin_label ***ltp;
841 /* Remember label definition so we can look it up later when
842 * creating the map file. */
843 s = find_section_by_index(segment);
844 if (s)
845 ltp = &(s->labels_end);
846 else
847 ltp = &nsl_tail;
848 (**ltp) = nasm_malloc(sizeof(struct bin_label));
849 (**ltp)->name = name;
850 (**ltp)->next = NULL;
851 *ltp = &((**ltp)->next);
856 /* These constants and the following function are used
857 * by bin_secname() to parse attribute assignments. */
859 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
860 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
861 ATTRIB_NOBITS, ATTRIB_PROGBITS
864 static int bin_read_attribute(char **line, int *attribute,
865 uint64_t *value)
867 expr *e;
868 int attrib_name_size;
869 struct tokenval tokval;
870 char *exp;
872 /* Skip whitespace. */
873 while (**line && nasm_isspace(**line))
874 (*line)++;
875 if (!**line)
876 return 0;
878 /* Figure out what attribute we're reading. */
879 if (!nasm_strnicmp(*line, "align=", 6)) {
880 *attribute = ATTRIB_ALIGN;
881 attrib_name_size = 6;
882 } else if (format_mode) {
883 if (!nasm_strnicmp(*line, "start=", 6)) {
884 *attribute = ATTRIB_START;
885 attrib_name_size = 6;
886 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
887 *attribute = ATTRIB_FOLLOWS;
888 *line += 8;
889 return 1;
890 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
891 *attribute = ATTRIB_VSTART;
892 attrib_name_size = 7;
893 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
894 *attribute = ATTRIB_VALIGN;
895 attrib_name_size = 7;
896 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
897 *attribute = ATTRIB_VFOLLOWS;
898 *line += 9;
899 return 1;
900 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
901 (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
902 *attribute = ATTRIB_NOBITS;
903 *line += 6;
904 return 1;
905 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
906 (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
907 *attribute = ATTRIB_PROGBITS;
908 *line += 8;
909 return 1;
910 } else
911 return 0;
912 } else
913 return 0;
915 /* Find the end of the expression. */
916 if ((*line)[attrib_name_size] != '(') {
917 /* Single term (no parenthesis). */
918 exp = *line += attrib_name_size;
919 while (**line && !nasm_isspace(**line))
920 (*line)++;
921 if (**line) {
922 **line = '\0';
923 (*line)++;
925 } else {
926 char c;
927 int pcount = 1;
929 /* Full expression (delimited by parenthesis) */
930 exp = *line += attrib_name_size + 1;
931 while (1) {
932 (*line) += strcspn(*line, "()'\"");
933 if (**line == '(') {
934 ++(*line);
935 ++pcount;
937 if (**line == ')') {
938 ++(*line);
939 --pcount;
940 if (!pcount)
941 break;
943 if ((**line == '"') || (**line == '\'')) {
944 c = **line;
945 while (**line) {
946 ++(*line);
947 if (**line == c)
948 break;
950 if (!**line) {
951 error(ERR_NONFATAL,
952 "invalid syntax in `section' directive");
953 return -1;
955 ++(*line);
957 if (!**line) {
958 error(ERR_NONFATAL, "expecting `)'");
959 return -1;
962 *(*line - 1) = '\0'; /* Terminate the expression. */
965 /* Check for no value given. */
966 if (!*exp) {
967 error(ERR_WARNING, "No value given to attribute in"
968 " `section' directive");
969 return -1;
972 /* Read and evaluate the expression. */
973 stdscan_reset();
974 stdscan_bufptr = exp;
975 tokval.t_type = TOKEN_INVALID;
976 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
977 if (e) {
978 if (!is_really_simple(e)) {
979 error(ERR_NONFATAL, "section attribute value must be"
980 " a critical expression");
981 return -1;
983 } else {
984 error(ERR_NONFATAL, "Invalid attribute value"
985 " specified in `section' directive.");
986 return -1;
988 *value = (uint64_t)reloc_value(e);
989 return 1;
992 static void bin_assign_attributes(struct Section *sec, char *astring)
994 int attribute, check;
995 uint64_t value;
996 char *p;
998 while (1) { /* Get the next attribute. */
999 check = bin_read_attribute(&astring, &attribute, &value);
1000 /* Skip bad attribute. */
1001 if (check == -1)
1002 continue;
1003 /* Unknown section attribute, so skip it and warn the user. */
1004 if (!check) {
1005 if (!*astring)
1006 break; /* End of line. */
1007 else {
1008 p = astring;
1009 while (*astring && !nasm_isspace(*astring))
1010 astring++;
1011 if (*astring) {
1012 *astring = '\0';
1013 astring++;
1015 error(ERR_WARNING, "ignoring unknown section attribute:"
1016 " \"%s\"", p);
1018 continue;
1021 switch (attribute) { /* Handle nobits attribute. */
1022 case ATTRIB_NOBITS:
1023 if ((sec->flags & TYPE_DEFINED)
1024 && (sec->flags & TYPE_PROGBITS))
1025 error(ERR_NONFATAL,
1026 "attempt to change section type"
1027 " from progbits to nobits");
1028 else
1029 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1030 continue;
1032 /* Handle progbits attribute. */
1033 case ATTRIB_PROGBITS:
1034 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1035 error(ERR_NONFATAL, "attempt to change section type"
1036 " from nobits to progbits");
1037 else
1038 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1039 continue;
1041 /* Handle align attribute. */
1042 case ATTRIB_ALIGN:
1043 if (!format_mode && (!strcmp(sec->name, ".text")))
1044 error(ERR_NONFATAL, "cannot specify an alignment"
1045 " to the .text section");
1046 else {
1047 if (!value || ((value - 1) & value))
1048 error(ERR_NONFATAL, "argument to `align' is not a"
1049 " power of two");
1050 else { /* Alignment is already satisfied if the previous
1051 * align value is greater. */
1052 if ((sec->flags & ALIGN_DEFINED)
1053 && (value < sec->align))
1054 value = sec->align;
1056 /* Don't allow a conflicting align value. */
1057 if ((sec->flags & START_DEFINED)
1058 && (sec->start & (value - 1)))
1059 error(ERR_NONFATAL,
1060 "`align' value conflicts "
1061 "with section start address");
1062 else {
1063 sec->align = value;
1064 sec->flags |= ALIGN_DEFINED;
1068 continue;
1070 /* Handle valign attribute. */
1071 case ATTRIB_VALIGN:
1072 if (!value || ((value - 1) & value))
1073 error(ERR_NONFATAL, "argument to `valign' is not a"
1074 " power of two");
1075 else { /* Alignment is already satisfied if the previous
1076 * align value is greater. */
1077 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1078 value = sec->valign;
1080 /* Don't allow a conflicting valign value. */
1081 if ((sec->flags & VSTART_DEFINED)
1082 && (sec->vstart & (value - 1)))
1083 error(ERR_NONFATAL,
1084 "`valign' value conflicts "
1085 "with `vstart' address");
1086 else {
1087 sec->valign = value;
1088 sec->flags |= VALIGN_DEFINED;
1091 continue;
1093 /* Handle start attribute. */
1094 case ATTRIB_START:
1095 if (sec->flags & FOLLOWS_DEFINED)
1096 error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1097 " section attributes");
1098 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1099 error(ERR_NONFATAL, "section start address redefined");
1100 else {
1101 sec->start = value;
1102 sec->flags |= START_DEFINED;
1103 if (sec->flags & ALIGN_DEFINED) {
1104 if (sec->start & (sec->align - 1))
1105 error(ERR_NONFATAL, "`start' address conflicts"
1106 " with section alignment");
1107 sec->flags ^= ALIGN_DEFINED;
1110 continue;
1112 /* Handle vstart attribute. */
1113 case ATTRIB_VSTART:
1114 if (sec->flags & VFOLLOWS_DEFINED)
1115 error(ERR_NONFATAL,
1116 "cannot combine `vstart' and `vfollows'"
1117 " section attributes");
1118 else if ((sec->flags & VSTART_DEFINED)
1119 && (value != sec->vstart))
1120 error(ERR_NONFATAL,
1121 "section virtual start address"
1122 " (vstart) redefined");
1123 else {
1124 sec->vstart = value;
1125 sec->flags |= VSTART_DEFINED;
1126 if (sec->flags & VALIGN_DEFINED) {
1127 if (sec->vstart & (sec->valign - 1))
1128 error(ERR_NONFATAL, "`vstart' address conflicts"
1129 " with `valign' value");
1130 sec->flags ^= VALIGN_DEFINED;
1133 continue;
1135 /* Handle follows attribute. */
1136 case ATTRIB_FOLLOWS:
1137 p = astring;
1138 astring += strcspn(astring, " \t");
1139 if (astring == p)
1140 error(ERR_NONFATAL, "expecting section name for `follows'"
1141 " attribute");
1142 else {
1143 *(astring++) = '\0';
1144 if (sec->flags & START_DEFINED)
1145 error(ERR_NONFATAL,
1146 "cannot combine `start' and `follows'"
1147 " section attributes");
1148 sec->follows = nasm_strdup(p);
1149 sec->flags |= FOLLOWS_DEFINED;
1151 continue;
1153 /* Handle vfollows attribute. */
1154 case ATTRIB_VFOLLOWS:
1155 if (sec->flags & VSTART_DEFINED)
1156 error(ERR_NONFATAL,
1157 "cannot combine `vstart' and `vfollows'"
1158 " section attributes");
1159 else {
1160 p = astring;
1161 astring += strcspn(astring, " \t");
1162 if (astring == p)
1163 error(ERR_NONFATAL,
1164 "expecting section name for `vfollows'"
1165 " attribute");
1166 else {
1167 *(astring++) = '\0';
1168 sec->vfollows = nasm_strdup(p);
1169 sec->flags |= VFOLLOWS_DEFINED;
1172 continue;
1177 static void bin_define_section_labels(void)
1179 static int labels_defined = 0;
1180 struct Section *sec;
1181 char *label_name;
1182 size_t base_len;
1184 if (labels_defined)
1185 return;
1186 for (sec = sections; sec; sec = sec->next) {
1187 base_len = strlen(sec->name) + 8;
1188 label_name = nasm_malloc(base_len + 8);
1189 strcpy(label_name, "section.");
1190 strcpy(label_name + 8, sec->name);
1192 /* section.<name>.start */
1193 strcpy(label_name + base_len, ".start");
1194 define_label(label_name, sec->start_index, 0L,
1195 NULL, 0, 0, bin_get_ofmt(), error);
1197 /* section.<name>.vstart */
1198 strcpy(label_name + base_len, ".vstart");
1199 define_label(label_name, sec->vstart_index, 0L,
1200 NULL, 0, 0, bin_get_ofmt(), error);
1202 nasm_free(label_name);
1204 labels_defined = 1;
1207 static int32_t bin_secname(char *name, int pass, int *bits)
1209 char *p;
1210 struct Section *sec;
1212 /* bin_secname is called with *name = NULL at the start of each
1213 * pass. Use this opportunity to establish the default section
1214 * (default is BITS-16 ".text" segment).
1216 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1217 origin_defined = 0;
1218 for (sec = sections; sec; sec = sec->next)
1219 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1220 ALIGN_DEFINED | VALIGN_DEFINED);
1222 /* Define section start and vstart labels. */
1223 if (format_mode && (pass != 1))
1224 bin_define_section_labels();
1226 /* Establish the default (.text) section. */
1227 *bits = 16;
1228 sec = find_section_by_name(".text");
1229 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1230 current_section = sec->vstart_index;
1231 return current_section;
1234 /* Attempt to find the requested section. If it does not
1235 * exist, create it. */
1236 p = name;
1237 while (*p && !nasm_isspace(*p))
1238 p++;
1239 if (*p)
1240 *p++ = '\0';
1241 sec = find_section_by_name(name);
1242 if (!sec) {
1243 sec = create_section(name);
1244 if (!strcmp(name, ".data"))
1245 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1246 else if (!strcmp(name, ".bss")) {
1247 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1248 sec->ifollows = NULL;
1249 } else if (!format_mode) {
1250 error(ERR_NONFATAL, "section name must be "
1251 ".text, .data, or .bss");
1252 return current_section;
1256 /* Handle attribute assignments. */
1257 if (pass != 1)
1258 bin_assign_attributes(sec, p);
1260 #ifndef ABIN_SMART_ADAPT
1261 /* The following line disables smart adaptation of
1262 * PROGBITS/NOBITS section types (it forces sections to
1263 * default to PROGBITS). */
1264 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1265 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1266 #endif
1268 /* Set the current section and return. */
1269 current_section = sec->vstart_index;
1270 return current_section;
1273 static int bin_directive(char *directive, char *args, int pass)
1275 /* Handle ORG directive */
1276 if (!nasm_stricmp(directive, "org")) {
1277 struct tokenval tokval;
1278 uint64_t value;
1279 expr *e;
1281 stdscan_reset();
1282 stdscan_bufptr = args;
1283 tokval.t_type = TOKEN_INVALID;
1284 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
1285 if (e) {
1286 if (!is_really_simple(e))
1287 error(ERR_NONFATAL, "org value must be a critical"
1288 " expression");
1289 else {
1290 value = reloc_value(e);
1291 /* Check for ORG redefinition. */
1292 if (origin_defined && (value != origin))
1293 error(ERR_NONFATAL, "program origin redefined");
1294 else {
1295 origin = value;
1296 origin_defined = 1;
1299 } else
1300 error(ERR_NONFATAL, "No or invalid offset specified"
1301 " in ORG directive.");
1302 return 1;
1305 /* The 'map' directive allows the user to generate section
1306 * and symbol information to stdout, stderr, or to a file. */
1307 else if (format_mode && !nasm_stricmp(directive, "map")) {
1308 char *p;
1310 if (pass != 1)
1311 return 1;
1312 args += strspn(args, " \t");
1313 while (*args) {
1314 p = args;
1315 args += strcspn(args, " \t");
1316 if (*args != '\0')
1317 *(args++) = '\0';
1318 if (!nasm_stricmp(p, "all"))
1319 map_control |=
1320 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1321 else if (!nasm_stricmp(p, "brief"))
1322 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1323 else if (!nasm_stricmp(p, "sections"))
1324 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1325 else if (!nasm_stricmp(p, "segments"))
1326 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1327 else if (!nasm_stricmp(p, "symbols"))
1328 map_control |= MAP_SYMBOLS;
1329 else if (!rf) {
1330 if (!nasm_stricmp(p, "stdout"))
1331 rf = stdout;
1332 else if (!nasm_stricmp(p, "stderr"))
1333 rf = stderr;
1334 else { /* Must be a filename. */
1335 rf = fopen(p, "wt");
1336 if (!rf) {
1337 error(ERR_WARNING, "unable to open map file `%s'",
1339 map_control = 0;
1340 return 1;
1343 } else
1344 error(ERR_WARNING, "map file already specified");
1346 if (map_control == 0)
1347 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1348 if (!rf)
1349 rf = stdout;
1350 return 1;
1352 return 0;
1355 static void bin_filename(char *inname, char *outname, efunc error)
1357 standard_extension(inname, outname, "", error);
1358 infile = inname;
1359 outfile = outname;
1362 static int32_t bin_segbase(int32_t segment)
1364 return segment;
1367 static int bin_set_info(enum geninfo type, char **val)
1369 (void)type;
1370 (void)val;
1371 return 0;
1374 static void bin_init(FILE * afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1376 fp = afp;
1377 error = errfunc;
1379 (void)eval; /* Don't warn that this parameter is unused. */
1380 (void)ldef; /* Placate optimizers. */
1382 maxbits = 64; /* Support 64-bit Segments */
1383 relocs = NULL;
1384 reloctail = &relocs;
1385 origin_defined = 0;
1386 no_seg_labels = NULL;
1387 nsl_tail = &no_seg_labels;
1388 format_mode = 1; /* Extended bin format
1389 * (set this to zero for old bin format). */
1391 /* Create default section (.text). */
1392 sections = last_section = nasm_malloc(sizeof(struct Section));
1393 last_section->next = NULL;
1394 last_section->name = nasm_strdup(".text");
1395 last_section->contents = saa_init(1L);
1396 last_section->follows = last_section->vfollows = 0;
1397 last_section->ifollows = NULL;
1398 last_section->length = 0;
1399 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1400 last_section->labels = NULL;
1401 last_section->labels_end = &(last_section->labels);
1402 last_section->start_index = seg_alloc();
1403 last_section->vstart_index = current_section = seg_alloc();
1406 struct ofmt of_bin = {
1407 "flat-form binary files (e.g. DOS .COM, .SYS)",
1408 "bin",
1409 NULL,
1410 null_debug_arr,
1411 &null_debug_form,
1412 bin_stdmac,
1413 bin_init,
1414 bin_set_info,
1415 bin_out,
1416 bin_deflabel,
1417 bin_secname,
1418 bin_segbase,
1419 bin_directive,
1420 bin_filename,
1421 bin_cleanup
1424 /* This is needed for bin_define_section_labels() */
1425 struct ofmt *bin_get_ofmt(void)
1427 return &of_bin;
1430 #endif /* #ifdef OF_BIN */