BR: 2196966: make the -w/-W options work again
[nasm/perl-rewrite.git] / output / outbin.c
blobcfa0aa600f586687192351858250457f4f11df57
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 int64_t addr = *(int64_t *)data - size;
802 switch (type) {
803 case OUT_REL2ADR:
804 size = 2;
805 break;
806 case OUT_REL4ADR:
807 size = 4;
808 break;
809 case OUT_REL8ADR:
810 size = 8;
811 break;
812 default:
813 size = 0; /* Shut up warning */
814 break;
816 if (segment != NO_SEG && !find_section_by_index(segment)) {
817 if (segment % 2)
818 error(ERR_NONFATAL, "binary output format does not support"
819 " segment base references");
820 else
821 error(ERR_NONFATAL, "binary output format does not support"
822 " external references");
823 segment = NO_SEG;
825 if (s->flags & TYPE_PROGBITS) {
826 add_reloc(s, size, segment, segto);
827 p = mydata;
828 WRITEADDR(p, addr - s->length, size);
829 saa_wbytes(s->contents, mydata, size);
831 s->length += size;
835 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
836 int is_global, char *special)
838 (void)segment; /* Don't warn that this parameter is unused */
839 (void)offset; /* Don't warn that this parameter is unused */
841 if (special)
842 error(ERR_NONFATAL, "binary format does not support any"
843 " special symbol types");
844 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
845 error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
846 else if (is_global == 2)
847 error(ERR_NONFATAL, "binary output format does not support common"
848 " variables");
849 else {
850 struct Section *s;
851 struct bin_label ***ltp;
853 /* Remember label definition so we can look it up later when
854 * creating the map file. */
855 s = find_section_by_index(segment);
856 if (s)
857 ltp = &(s->labels_end);
858 else
859 ltp = &nsl_tail;
860 (**ltp) = nasm_malloc(sizeof(struct bin_label));
861 (**ltp)->name = name;
862 (**ltp)->next = NULL;
863 *ltp = &((**ltp)->next);
868 /* These constants and the following function are used
869 * by bin_secname() to parse attribute assignments. */
871 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
872 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
873 ATTRIB_NOBITS, ATTRIB_PROGBITS
876 static int bin_read_attribute(char **line, int *attribute,
877 uint64_t *value)
879 expr *e;
880 int attrib_name_size;
881 struct tokenval tokval;
882 char *exp;
884 /* Skip whitespace. */
885 while (**line && nasm_isspace(**line))
886 (*line)++;
887 if (!**line)
888 return 0;
890 /* Figure out what attribute we're reading. */
891 if (!nasm_strnicmp(*line, "align=", 6)) {
892 *attribute = ATTRIB_ALIGN;
893 attrib_name_size = 6;
894 } else if (format_mode) {
895 if (!nasm_strnicmp(*line, "start=", 6)) {
896 *attribute = ATTRIB_START;
897 attrib_name_size = 6;
898 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
899 *attribute = ATTRIB_FOLLOWS;
900 *line += 8;
901 return 1;
902 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
903 *attribute = ATTRIB_VSTART;
904 attrib_name_size = 7;
905 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
906 *attribute = ATTRIB_VALIGN;
907 attrib_name_size = 7;
908 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
909 *attribute = ATTRIB_VFOLLOWS;
910 *line += 9;
911 return 1;
912 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
913 (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
914 *attribute = ATTRIB_NOBITS;
915 *line += 6;
916 return 1;
917 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
918 (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
919 *attribute = ATTRIB_PROGBITS;
920 *line += 8;
921 return 1;
922 } else
923 return 0;
924 } else
925 return 0;
927 /* Find the end of the expression. */
928 if ((*line)[attrib_name_size] != '(') {
929 /* Single term (no parenthesis). */
930 exp = *line += attrib_name_size;
931 while (**line && !nasm_isspace(**line))
932 (*line)++;
933 if (**line) {
934 **line = '\0';
935 (*line)++;
937 } else {
938 char c;
939 int pcount = 1;
941 /* Full expression (delimited by parenthesis) */
942 exp = *line += attrib_name_size + 1;
943 while (1) {
944 (*line) += strcspn(*line, "()'\"");
945 if (**line == '(') {
946 ++(*line);
947 ++pcount;
949 if (**line == ')') {
950 ++(*line);
951 --pcount;
952 if (!pcount)
953 break;
955 if ((**line == '"') || (**line == '\'')) {
956 c = **line;
957 while (**line) {
958 ++(*line);
959 if (**line == c)
960 break;
962 if (!**line) {
963 error(ERR_NONFATAL,
964 "invalid syntax in `section' directive");
965 return -1;
967 ++(*line);
969 if (!**line) {
970 error(ERR_NONFATAL, "expecting `)'");
971 return -1;
974 *(*line - 1) = '\0'; /* Terminate the expression. */
977 /* Check for no value given. */
978 if (!*exp) {
979 error(ERR_WARNING, "No value given to attribute in"
980 " `section' directive");
981 return -1;
984 /* Read and evaluate the expression. */
985 stdscan_reset();
986 stdscan_bufptr = exp;
987 tokval.t_type = TOKEN_INVALID;
988 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
989 if (e) {
990 if (!is_really_simple(e)) {
991 error(ERR_NONFATAL, "section attribute value must be"
992 " a critical expression");
993 return -1;
995 } else {
996 error(ERR_NONFATAL, "Invalid attribute value"
997 " specified in `section' directive.");
998 return -1;
1000 *value = (uint64_t)reloc_value(e);
1001 return 1;
1004 static void bin_assign_attributes(struct Section *sec, char *astring)
1006 int attribute, check;
1007 uint64_t value;
1008 char *p;
1010 while (1) { /* Get the next attribute. */
1011 check = bin_read_attribute(&astring, &attribute, &value);
1012 /* Skip bad attribute. */
1013 if (check == -1)
1014 continue;
1015 /* Unknown section attribute, so skip it and warn the user. */
1016 if (!check) {
1017 if (!*astring)
1018 break; /* End of line. */
1019 else {
1020 p = astring;
1021 while (*astring && !nasm_isspace(*astring))
1022 astring++;
1023 if (*astring) {
1024 *astring = '\0';
1025 astring++;
1027 error(ERR_WARNING, "ignoring unknown section attribute:"
1028 " \"%s\"", p);
1030 continue;
1033 switch (attribute) { /* Handle nobits attribute. */
1034 case ATTRIB_NOBITS:
1035 if ((sec->flags & TYPE_DEFINED)
1036 && (sec->flags & TYPE_PROGBITS))
1037 error(ERR_NONFATAL,
1038 "attempt to change section type"
1039 " from progbits to nobits");
1040 else
1041 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1042 continue;
1044 /* Handle progbits attribute. */
1045 case ATTRIB_PROGBITS:
1046 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1047 error(ERR_NONFATAL, "attempt to change section type"
1048 " from nobits to progbits");
1049 else
1050 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1051 continue;
1053 /* Handle align attribute. */
1054 case ATTRIB_ALIGN:
1055 if (!format_mode && (!strcmp(sec->name, ".text")))
1056 error(ERR_NONFATAL, "cannot specify an alignment"
1057 " to the .text section");
1058 else {
1059 if (!value || ((value - 1) & value))
1060 error(ERR_NONFATAL, "argument to `align' is not a"
1061 " power of two");
1062 else { /* Alignment is already satisfied if the previous
1063 * align value is greater. */
1064 if ((sec->flags & ALIGN_DEFINED)
1065 && (value < sec->align))
1066 value = sec->align;
1068 /* Don't allow a conflicting align value. */
1069 if ((sec->flags & START_DEFINED)
1070 && (sec->start & (value - 1)))
1071 error(ERR_NONFATAL,
1072 "`align' value conflicts "
1073 "with section start address");
1074 else {
1075 sec->align = value;
1076 sec->flags |= ALIGN_DEFINED;
1080 continue;
1082 /* Handle valign attribute. */
1083 case ATTRIB_VALIGN:
1084 if (!value || ((value - 1) & value))
1085 error(ERR_NONFATAL, "argument to `valign' is not a"
1086 " power of two");
1087 else { /* Alignment is already satisfied if the previous
1088 * align value is greater. */
1089 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1090 value = sec->valign;
1092 /* Don't allow a conflicting valign value. */
1093 if ((sec->flags & VSTART_DEFINED)
1094 && (sec->vstart & (value - 1)))
1095 error(ERR_NONFATAL,
1096 "`valign' value conflicts "
1097 "with `vstart' address");
1098 else {
1099 sec->valign = value;
1100 sec->flags |= VALIGN_DEFINED;
1103 continue;
1105 /* Handle start attribute. */
1106 case ATTRIB_START:
1107 if (sec->flags & FOLLOWS_DEFINED)
1108 error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1109 " section attributes");
1110 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1111 error(ERR_NONFATAL, "section start address redefined");
1112 else {
1113 sec->start = value;
1114 sec->flags |= START_DEFINED;
1115 if (sec->flags & ALIGN_DEFINED) {
1116 if (sec->start & (sec->align - 1))
1117 error(ERR_NONFATAL, "`start' address conflicts"
1118 " with section alignment");
1119 sec->flags ^= ALIGN_DEFINED;
1122 continue;
1124 /* Handle vstart attribute. */
1125 case ATTRIB_VSTART:
1126 if (sec->flags & VFOLLOWS_DEFINED)
1127 error(ERR_NONFATAL,
1128 "cannot combine `vstart' and `vfollows'"
1129 " section attributes");
1130 else if ((sec->flags & VSTART_DEFINED)
1131 && (value != sec->vstart))
1132 error(ERR_NONFATAL,
1133 "section virtual start address"
1134 " (vstart) redefined");
1135 else {
1136 sec->vstart = value;
1137 sec->flags |= VSTART_DEFINED;
1138 if (sec->flags & VALIGN_DEFINED) {
1139 if (sec->vstart & (sec->valign - 1))
1140 error(ERR_NONFATAL, "`vstart' address conflicts"
1141 " with `valign' value");
1142 sec->flags ^= VALIGN_DEFINED;
1145 continue;
1147 /* Handle follows attribute. */
1148 case ATTRIB_FOLLOWS:
1149 p = astring;
1150 astring += strcspn(astring, " \t");
1151 if (astring == p)
1152 error(ERR_NONFATAL, "expecting section name for `follows'"
1153 " attribute");
1154 else {
1155 *(astring++) = '\0';
1156 if (sec->flags & START_DEFINED)
1157 error(ERR_NONFATAL,
1158 "cannot combine `start' and `follows'"
1159 " section attributes");
1160 sec->follows = nasm_strdup(p);
1161 sec->flags |= FOLLOWS_DEFINED;
1163 continue;
1165 /* Handle vfollows attribute. */
1166 case ATTRIB_VFOLLOWS:
1167 if (sec->flags & VSTART_DEFINED)
1168 error(ERR_NONFATAL,
1169 "cannot combine `vstart' and `vfollows'"
1170 " section attributes");
1171 else {
1172 p = astring;
1173 astring += strcspn(astring, " \t");
1174 if (astring == p)
1175 error(ERR_NONFATAL,
1176 "expecting section name for `vfollows'"
1177 " attribute");
1178 else {
1179 *(astring++) = '\0';
1180 sec->vfollows = nasm_strdup(p);
1181 sec->flags |= VFOLLOWS_DEFINED;
1184 continue;
1189 static void bin_define_section_labels(void)
1191 static int labels_defined = 0;
1192 struct Section *sec;
1193 char *label_name;
1194 size_t base_len;
1196 if (labels_defined)
1197 return;
1198 for (sec = sections; sec; sec = sec->next) {
1199 base_len = strlen(sec->name) + 8;
1200 label_name = nasm_malloc(base_len + 8);
1201 strcpy(label_name, "section.");
1202 strcpy(label_name + 8, sec->name);
1204 /* section.<name>.start */
1205 strcpy(label_name + base_len, ".start");
1206 define_label(label_name, sec->start_index, 0L,
1207 NULL, 0, 0, bin_get_ofmt(), error);
1209 /* section.<name>.vstart */
1210 strcpy(label_name + base_len, ".vstart");
1211 define_label(label_name, sec->vstart_index, 0L,
1212 NULL, 0, 0, bin_get_ofmt(), error);
1214 nasm_free(label_name);
1216 labels_defined = 1;
1219 static int32_t bin_secname(char *name, int pass, int *bits)
1221 char *p;
1222 struct Section *sec;
1224 /* bin_secname is called with *name = NULL at the start of each
1225 * pass. Use this opportunity to establish the default section
1226 * (default is BITS-16 ".text" segment).
1228 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1229 origin_defined = 0;
1230 for (sec = sections; sec; sec = sec->next)
1231 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1232 ALIGN_DEFINED | VALIGN_DEFINED);
1234 /* Define section start and vstart labels. */
1235 if (format_mode && (pass != 1))
1236 bin_define_section_labels();
1238 /* Establish the default (.text) section. */
1239 *bits = 16;
1240 sec = find_section_by_name(".text");
1241 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1242 current_section = sec->vstart_index;
1243 return current_section;
1246 /* Attempt to find the requested section. If it does not
1247 * exist, create it. */
1248 p = name;
1249 while (*p && !nasm_isspace(*p))
1250 p++;
1251 if (*p)
1252 *p++ = '\0';
1253 sec = find_section_by_name(name);
1254 if (!sec) {
1255 sec = create_section(name);
1256 if (!strcmp(name, ".data"))
1257 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1258 else if (!strcmp(name, ".bss")) {
1259 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1260 sec->ifollows = NULL;
1261 } else if (!format_mode) {
1262 error(ERR_NONFATAL, "section name must be "
1263 ".text, .data, or .bss");
1264 return current_section;
1268 /* Handle attribute assignments. */
1269 if (pass != 1)
1270 bin_assign_attributes(sec, p);
1272 #ifndef ABIN_SMART_ADAPT
1273 /* The following line disables smart adaptation of
1274 * PROGBITS/NOBITS section types (it forces sections to
1275 * default to PROGBITS). */
1276 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1277 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1278 #endif
1280 /* Set the current section and return. */
1281 current_section = sec->vstart_index;
1282 return current_section;
1285 static int bin_directive(char *directive, char *args, int pass)
1287 /* Handle ORG directive */
1288 if (!nasm_stricmp(directive, "org")) {
1289 struct tokenval tokval;
1290 uint64_t value;
1291 expr *e;
1293 stdscan_reset();
1294 stdscan_bufptr = args;
1295 tokval.t_type = TOKEN_INVALID;
1296 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
1297 if (e) {
1298 if (!is_really_simple(e))
1299 error(ERR_NONFATAL, "org value must be a critical"
1300 " expression");
1301 else {
1302 value = reloc_value(e);
1303 /* Check for ORG redefinition. */
1304 if (origin_defined && (value != origin))
1305 error(ERR_NONFATAL, "program origin redefined");
1306 else {
1307 origin = value;
1308 origin_defined = 1;
1311 } else
1312 error(ERR_NONFATAL, "No or invalid offset specified"
1313 " in ORG directive.");
1314 return 1;
1317 /* The 'map' directive allows the user to generate section
1318 * and symbol information to stdout, stderr, or to a file. */
1319 else if (format_mode && !nasm_stricmp(directive, "map")) {
1320 char *p;
1322 if (pass != 1)
1323 return 1;
1324 args += strspn(args, " \t");
1325 while (*args) {
1326 p = args;
1327 args += strcspn(args, " \t");
1328 if (*args != '\0')
1329 *(args++) = '\0';
1330 if (!nasm_stricmp(p, "all"))
1331 map_control |=
1332 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1333 else if (!nasm_stricmp(p, "brief"))
1334 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1335 else if (!nasm_stricmp(p, "sections"))
1336 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1337 else if (!nasm_stricmp(p, "segments"))
1338 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1339 else if (!nasm_stricmp(p, "symbols"))
1340 map_control |= MAP_SYMBOLS;
1341 else if (!rf) {
1342 if (!nasm_stricmp(p, "stdout"))
1343 rf = stdout;
1344 else if (!nasm_stricmp(p, "stderr"))
1345 rf = stderr;
1346 else { /* Must be a filename. */
1347 rf = fopen(p, "wt");
1348 if (!rf) {
1349 error(ERR_WARNING, "unable to open map file `%s'",
1351 map_control = 0;
1352 return 1;
1355 } else
1356 error(ERR_WARNING, "map file already specified");
1358 if (map_control == 0)
1359 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1360 if (!rf)
1361 rf = stdout;
1362 return 1;
1364 return 0;
1367 static void bin_filename(char *inname, char *outname, efunc error)
1369 standard_extension(inname, outname, "", error);
1370 infile = inname;
1371 outfile = outname;
1374 static int32_t bin_segbase(int32_t segment)
1376 return segment;
1379 static int bin_set_info(enum geninfo type, char **val)
1381 (void)type;
1382 (void)val;
1383 return 0;
1386 static void bin_init(FILE * afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1388 fp = afp;
1389 error = errfunc;
1391 (void)eval; /* Don't warn that this parameter is unused. */
1392 (void)ldef; /* Placate optimizers. */
1394 maxbits = 64; /* Support 64-bit Segments */
1395 relocs = NULL;
1396 reloctail = &relocs;
1397 origin_defined = 0;
1398 no_seg_labels = NULL;
1399 nsl_tail = &no_seg_labels;
1400 format_mode = 1; /* Extended bin format
1401 * (set this to zero for old bin format). */
1403 /* Create default section (.text). */
1404 sections = last_section = nasm_malloc(sizeof(struct Section));
1405 last_section->next = NULL;
1406 last_section->name = nasm_strdup(".text");
1407 last_section->contents = saa_init(1L);
1408 last_section->follows = last_section->vfollows = 0;
1409 last_section->ifollows = NULL;
1410 last_section->length = 0;
1411 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1412 last_section->labels = NULL;
1413 last_section->labels_end = &(last_section->labels);
1414 last_section->start_index = seg_alloc();
1415 last_section->vstart_index = current_section = seg_alloc();
1418 struct ofmt of_bin = {
1419 "flat-form binary files (e.g. DOS .COM, .SYS)",
1420 "bin",
1421 NULL,
1422 null_debug_arr,
1423 &null_debug_form,
1424 bin_stdmac,
1425 bin_init,
1426 bin_set_info,
1427 bin_out,
1428 bin_deflabel,
1429 bin_secname,
1430 bin_segbase,
1431 bin_directive,
1432 bin_filename,
1433 bin_cleanup
1436 /* This is needed for bin_define_section_labels() */
1437 struct ofmt *bin_get_ofmt(void)
1439 return &of_bin;
1442 #endif /* #ifdef OF_BIN */