1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2009 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * ----------------------------------------------------------------------- */
35 * outbin.c output routines for the Netwide Assembler to produce
36 * flat-form binary files
39 /* This is the extended version of NASM's original binary output
40 * format. It is backward compatible with the original BIN format,
41 * and contains support for multiple sections and advanced section
46 * - Users can create an arbitrary number of sections; they are not
47 * limited to just ".text", ".data", and ".bss".
49 * - Sections can be either progbits or nobits type.
51 * - You can specify that they be aligned at a certian boundary
52 * following the previous section ("align="), or positioned at an
53 * arbitrary byte-granular location ("start=").
55 * - You can specify a "virtual" start address for a section, which
56 * will be used for the calculation for all address references
57 * with respect to that section ("vstart=").
59 * - The ORG directive, as well as the section/segment directive
60 * arguments ("align=", "start=", "vstart="), can take a critical
61 * expression as their value. For example: "align=(1 << 12)".
63 * - You can generate map files using the 'map' directive.
67 /* Uncomment the following define if you want sections to adapt
68 * their progbits/nobits state depending on what type of
69 * instructions are issued, rather than defaulting to progbits.
70 * Note that this behavior violates the specification.
72 #define ABIN_SMART_ADAPT
90 #include "output/outform.h"
91 #include "output/outlib.h"
95 static FILE *fp, *rf = NULL;
97 static struct ofmt *my_ofmt;
98 static void (*do_output)(void);
100 /* Section flags keep track of which attributes the user has defined. */
101 #define START_DEFINED 0x001
102 #define ALIGN_DEFINED 0x002
103 #define FOLLOWS_DEFINED 0x004
104 #define VSTART_DEFINED 0x008
105 #define VALIGN_DEFINED 0x010
106 #define VFOLLOWS_DEFINED 0x020
107 #define TYPE_DEFINED 0x040
108 #define TYPE_PROGBITS 0x080
109 #define TYPE_NOBITS 0x100
111 /* This struct is used to keep track of symbols for map-file generation. */
112 static struct bin_label {
114 struct bin_label *next;
115 } *no_seg_labels, **nsl_tail;
117 static struct Section {
119 struct SAA *contents;
120 int64_t length; /* section length in bytes */
122 /* Section attributes */
123 int flags; /* see flag definitions above */
124 uint64_t align; /* section alignment */
125 uint64_t valign; /* notional section alignment */
126 uint64_t start; /* section start address */
127 uint64_t vstart; /* section virtual start address */
128 char *follows; /* the section that this one will follow */
129 char *vfollows; /* the section that this one will notionally follow */
130 int32_t start_index; /* NASM section id for non-relocated version */
131 int32_t vstart_index; /* the NASM section id */
133 struct bin_label *labels; /* linked-list of label handles for map output. */
134 struct bin_label **labels_end; /* Holds address of end of labels list. */
135 struct Section *ifollows; /* Points to previous section (implicit follows). */
136 struct Section *next; /* This links sections with a defined start address. */
138 /* The extended bin format allows for sections to have a "virtual"
139 * start address. This is accomplished by creating two sections:
140 * one beginning at the Load Memory Address and the other beginning
141 * at the Virtual Memory Address. The LMA section is only used to
142 * define the section.<section_name>.start label, but there isn't
143 * any other good way for us to handle that label.
146 } *sections, *last_section;
148 static struct Reloc {
154 struct Section *target;
155 } *relocs, **reloctail;
157 extern char *stdscan_bufptr;
159 static uint8_t format_mode; /* 0 = original bin, 1 = extended bin */
160 static int32_t current_section; /* only really needed if format_mode = 0 */
161 static uint64_t origin;
162 static int origin_defined;
164 /* Stuff we need for map-file generation. */
166 #define MAP_SUMMARY 2
167 #define MAP_SECTIONS 4
168 #define MAP_SYMBOLS 8
169 static int map_control = 0;
170 static char *infile, *outfile;
172 extern macros_t bin_stdmac[];
174 static void add_reloc(struct Section *s, int32_t bytes, int32_t secref,
179 r = *reloctail = nasm_malloc(sizeof(struct Reloc));
180 reloctail = &r->next;
189 static struct Section *find_section_by_name(const char *name)
193 for (s = sections; s; s = s->next)
194 if (!strcmp(s->name, name))
199 static struct Section *find_section_by_index(int32_t index)
203 for (s = sections; s; s = s->next)
204 if ((index == s->vstart_index) || (index == s->start_index))
209 static struct Section *create_section(char *name)
210 { /* Create a new section. */
211 last_section->next = nasm_malloc(sizeof(struct Section));
212 last_section->next->ifollows = last_section;
213 last_section = last_section->next;
214 last_section->labels = NULL;
215 last_section->labels_end = &(last_section->labels);
217 /* Initialize section attributes. */
218 last_section->name = nasm_strdup(name);
219 last_section->contents = saa_init(1L);
220 last_section->follows = last_section->vfollows = 0;
221 last_section->length = 0;
222 last_section->flags = 0;
223 last_section->next = NULL;
225 /* Register our sections with NASM. */
226 last_section->vstart_index = seg_alloc();
227 last_section->start_index = seg_alloc();
231 static void bin_cleanup(int debuginfo)
233 struct Section *g, **gp;
234 struct Section *gs = NULL, **gsp;
235 struct Section *s, **sp;
236 struct Section *nobits = NULL, **nt;
237 struct Section *last_progbits;
243 (void)debuginfo; /* placate optimizers */
247 "bin_cleanup: Sections were initially referenced in this order:\n");
248 for (h = 0, s = sections; s; h++, s = s->next)
249 fprintf(stdout, "%i. %s\n", h, s->name);
252 /* Assembly has completed, so now we need to generate the output file.
253 * Step 1: Separate progbits and nobits sections into separate lists.
254 * Step 2: Sort the progbits sections into their output order.
255 * Step 3: Compute start addresses for all progbits sections.
256 * Step 4: Compute vstart addresses for all sections.
257 * Step 5: Apply relocations.
258 * Step 6: Write the sections' data to the output file.
259 * Step 7: Generate the map file.
260 * Step 8: Release all allocated memory.
263 /* To do: Smart section-type adaptation could leave some empty sections
264 * without a defined type (progbits/nobits). Won't fix now since this
265 * feature will be disabled. */
267 /* Step 1: Split progbits and nobits sections into separate lists. */
270 /* Move nobits sections into a separate list. Also pre-process nobits
271 * sections' attributes. */
272 for (sp = §ions->next, s = sections->next; s; s = *sp) { /* Skip progbits sections. */
273 if (s->flags & TYPE_PROGBITS) {
277 /* Do some special pre-processing on nobits sections' attributes. */
278 if (s->flags & (START_DEFINED | ALIGN_DEFINED | FOLLOWS_DEFINED)) { /* Check for a mixture of real and virtual section attributes. */
279 if (s->flags & (VSTART_DEFINED | VALIGN_DEFINED |
281 error(ERR_FATAL|ERR_NOFILE,
282 "cannot mix real and virtual attributes"
283 " in nobits section (%s)", s->name);
284 /* Real and virtual attributes mean the same thing for nobits sections. */
285 if (s->flags & START_DEFINED) {
286 s->vstart = s->start;
287 s->flags |= VSTART_DEFINED;
289 if (s->flags & ALIGN_DEFINED) {
290 s->valign = s->align;
291 s->flags |= VALIGN_DEFINED;
293 if (s->flags & FOLLOWS_DEFINED) {
294 s->vfollows = s->follows;
295 s->flags |= VFOLLOWS_DEFINED;
296 s->flags &= ~FOLLOWS_DEFINED;
299 /* Every section must have a start address. */
300 if (s->flags & VSTART_DEFINED) {
301 s->start = s->vstart;
302 s->flags |= START_DEFINED;
304 /* Move the section into the nobits list. */
311 /* Step 2: Sort the progbits sections into their output order. */
313 /* In Step 2 we move around sections in groups. A group
314 * begins with a section (group leader) that has a user-
315 * defined start address or follows section. The remainder
316 * of the group is made up of the sections that implicitly
317 * follow the group leader (i.e., they were defined after
318 * the group leader and were not given an explicit start
319 * address or follows section by the user). */
321 /* For anyone attempting to read this code:
322 * g (group) points to a group of sections, the first one of which has
323 * a user-defined start address or follows section.
324 * gp (g previous) holds the location of the pointer to g.
325 * gs (g scan) is a temp variable that we use to scan to the end of the group.
326 * gsp (gs previous) holds the location of the pointer to gs.
327 * nt (nobits tail) points to the nobits section-list tail.
330 /* Link all 'follows' groups to their proper position. To do
331 * this we need to know three things: the start of the group
332 * to relocate (g), the section it is following (s), and the
333 * end of the group we're relocating (gs). */
334 for (gp = §ions, g = sections; g; g = gs) { /* Find the next follows group that is out of place (g). */
335 if (!(g->flags & FOLLOWS_DEFINED)) {
337 if ((g->next->flags & FOLLOWS_DEFINED) &&
338 strcmp(g->name, g->next->follows))
347 /* Find the section that this group follows (s). */
348 for (sp = §ions, s = sections;
349 s && strcmp(s->name, g->follows);
350 sp = &s->next, s = s->next) ;
352 error(ERR_FATAL|ERR_NOFILE, "section %s follows an invalid or"
353 " unknown section (%s)", g->name, g->follows);
354 if (s->next && (s->next->flags & FOLLOWS_DEFINED) &&
355 !strcmp(s->name, s->next->follows))
356 error(ERR_FATAL|ERR_NOFILE, "sections %s and %s can't both follow"
357 " section %s", g->name, s->next->name, s->name);
358 /* Find the end of the current follows group (gs). */
359 for (gsp = &g->next, gs = g->next;
360 gs && (gs != s) && !(gs->flags & START_DEFINED);
361 gsp = &gs->next, gs = gs->next) {
362 if (gs->next && (gs->next->flags & FOLLOWS_DEFINED) &&
363 strcmp(gs->name, gs->next->follows)) {
369 /* Re-link the group after its follows section. */
375 /* Link all 'start' groups to their proper position. Once
376 * again we need to know g, s, and gs (see above). The main
377 * difference is we already know g since we sort by moving
378 * groups from the 'unsorted' list into a 'sorted' list (g
379 * will always be the first section in the unsorted list). */
380 for (g = sections, sections = NULL; g; g = gs) { /* Find the section that we will insert this group before (s). */
381 for (sp = §ions, s = sections; s; sp = &s->next, s = s->next)
382 if ((s->flags & START_DEFINED) && (g->start < s->start))
384 /* Find the end of the group (gs). */
385 for (gs = g->next, gsp = &g->next;
386 gs && !(gs->flags & START_DEFINED);
387 gsp = &gs->next, gs = gs->next) ;
388 /* Re-link the group before the target section. */
393 /* Step 3: Compute start addresses for all progbits sections. */
395 /* Make sure we have an origin and a start address for the first section. */
396 if (origin_defined) {
397 if (sections->flags & START_DEFINED) {
398 /* Make sure this section doesn't begin before the origin. */
399 if (sections->start < origin)
400 error(ERR_FATAL|ERR_NOFILE, "section %s begins"
401 " before program origin", sections->name);
402 } else if (sections->flags & ALIGN_DEFINED) {
403 sections->start = ((origin + sections->align - 1) &
404 ~(sections->align - 1));
406 sections->start = origin;
409 if (!(sections->flags & START_DEFINED))
411 origin = sections->start;
413 sections->flags |= START_DEFINED;
415 /* Make sure each section has an explicit start address. If it
416 * doesn't, then compute one based its alignment and the end of
417 * the previous section. */
418 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
419 * (has a defined start address, and is not zero length). */
422 s && ((s->length == 0) || !(s->flags & START_DEFINED));
424 /* Compute the start address of this section, if necessary. */
425 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
426 if (!(g->flags & ALIGN_DEFINED)) {
428 g->flags |= ALIGN_DEFINED;
430 /* Set the section start address. */
431 g->start = (pend + g->align - 1) & ~(g->align - 1);
432 g->flags |= START_DEFINED;
434 /* Ugly special case for progbits sections' virtual attributes:
435 * If there is a defined valign, but no vstart and no vfollows, then
436 * we valign after the previous progbits section. This case doesn't
437 * really make much sense for progbits sections with a defined start
438 * address, but it is possible and we must do *something*.
439 * Not-so-ugly special case:
440 * If a progbits section has no virtual attributes, we set the
441 * vstart equal to the start address. */
442 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
443 if (g->flags & VALIGN_DEFINED)
444 g->vstart = (pend + g->valign - 1) & ~(g->valign - 1);
446 g->vstart = g->start;
447 g->flags |= VSTART_DEFINED;
449 /* Ignore zero-length sections. */
452 /* Compute the span of this section. */
453 pend = g->start + g->length;
454 /* Check for section overlap. */
456 if (s->start < origin)
457 error(ERR_FATAL|ERR_NOFILE, "section %s beings before program origin",
459 if (g->start > s->start)
460 error(ERR_FATAL|ERR_NOFILE, "sections %s ~ %s and %s overlap!",
461 gs->name, g->name, s->name);
463 error(ERR_FATAL|ERR_NOFILE, "sections %s and %s overlap!",
466 /* Remember this section as the latest >0 length section. */
470 /* Step 4: Compute vstart addresses for all sections. */
472 /* Attach the nobits sections to the end of the progbits sections. */
473 for (s = sections; s->next; s = s->next) ;
477 * Scan for sections that don't have a vstart address. If we find
478 * one we'll attempt to compute its vstart. If we can't compute
479 * the vstart, we leave it alone and come back to it in a
480 * subsequent scan. We continue scanning and re-scanning until
481 * we've gone one full cycle without computing any vstarts.
483 do { /* Do one full scan of the sections list. */
484 for (h = 0, g = sections; g; g = g->next) {
485 if (g->flags & VSTART_DEFINED)
487 /* Find the section that this one virtually follows. */
488 if (g->flags & VFOLLOWS_DEFINED) {
489 for (s = sections; s && strcmp(g->vfollows, s->name);
492 error(ERR_FATAL|ERR_NOFILE,
493 "section %s vfollows unknown section (%s)",
494 g->name, g->vfollows);
495 } else if (g->ifollows != NULL)
496 for (s = sections; s && (s != g->ifollows); s = s->next) ;
497 /* The .bss section is the only one with ifollows = NULL.
498 In this case we implicitly follow the last progbits
503 /* If the section we're following has a vstart, we can proceed. */
504 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
505 if (!(g->flags & VALIGN_DEFINED)) {
507 g->flags |= VALIGN_DEFINED;
509 /* Compute the vstart address. */
510 g->vstart = (s->vstart + s->length + g->valign - 1)
512 g->flags |= VSTART_DEFINED;
514 /* Start and vstart mean the same thing for nobits sections. */
515 if (g->flags & TYPE_NOBITS)
516 g->start = g->vstart;
521 /* Now check for any circular vfollows references, which will manifest
522 * themselves as sections without a defined vstart. */
523 for (h = 0, s = sections; s; s = s->next) {
524 if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
525 * no-no, but we'll throw a fatal one eventually so it's ok. */
526 error(ERR_NONFATAL, "cannot compute vstart for section %s",
532 error(ERR_FATAL|ERR_NOFILE, "circular vfollows path detected");
536 "bin_cleanup: Confirm final section order for output file:\n");
537 for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
539 fprintf(stdout, "%i. %s\n", h, s->name);
542 /* Step 5: Apply relocations. */
544 /* Prepare the sections for relocating. */
545 for (s = sections; s; s = s->next)
546 saa_rewind(s->contents);
547 /* Apply relocations. */
548 for (r = relocs; r; r = r->next) {
549 uint8_t *p, *q, mydata[8];
552 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
557 l += ((int64_t)*p++) << 8;
559 l += ((int64_t)*p++) << 16;
560 l += ((int64_t)*p++) << 24;
563 l += ((int64_t)*p++) << 32;
564 l += ((int64_t)*p++) << 40;
565 l += ((int64_t)*p++) << 48;
566 l += ((int64_t)*p++) << 56;
570 s = find_section_by_index(r->secref);
572 if (r->secref == s->start_index)
577 s = find_section_by_index(r->secrel);
579 if (r->secrel == s->start_index)
587 else if (r->bytes == 2)
590 *q++ = (uint8_t)(l & 0xFF);
591 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
594 /* Step 6: Write the section data to the output file. */
597 /* Step 7: Generate the map file. */
600 static const char not_defined[] = "not defined";
602 /* Display input and output file names. */
603 fprintf(rf, "\n- NASM Map file ");
606 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
609 if (map_control & MAP_ORIGIN) { /* Display program origin. */
610 fprintf(rf, "-- Program origin ");
613 fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
615 /* Display sections summary. */
616 if (map_control & MAP_SUMMARY) {
617 fprintf(rf, "-- Sections (summary) ");
620 fprintf(rf, "\n\nVstart Start Stop "
621 "Length Class Name\n");
622 for (s = sections; s; s = s->next) {
623 fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
624 s->vstart, s->start, s->start + s->length,
626 if (s->flags & TYPE_PROGBITS)
627 fprintf(rf, "progbits ");
629 fprintf(rf, "nobits ");
630 fprintf(rf, "%s\n", s->name);
634 /* Display detailed section information. */
635 if (map_control & MAP_SECTIONS) {
636 fprintf(rf, "-- Sections (detailed) ");
640 for (s = sections; s; s = s->next) {
641 fprintf(rf, "---- Section %s ", s->name);
642 for (h = 65 - strlen(s->name); h; h--)
644 fprintf(rf, "\n\nclass: ");
645 if (s->flags & TYPE_PROGBITS)
646 fprintf(rf, "progbits");
648 fprintf(rf, "nobits");
649 fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
650 "\nalign: ", s->length, s->start);
651 if (s->flags & ALIGN_DEFINED)
652 fprintf(rf, "%16"PRIX64"", s->align);
654 fputs(not_defined, rf);
655 fprintf(rf, "\nfollows: ");
656 if (s->flags & FOLLOWS_DEFINED)
657 fprintf(rf, "%s", s->follows);
659 fputs(not_defined, rf);
660 fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
661 if (s->flags & VALIGN_DEFINED)
662 fprintf(rf, "%16"PRIX64"", s->valign);
664 fputs(not_defined, rf);
665 fprintf(rf, "\nvfollows: ");
666 if (s->flags & VFOLLOWS_DEFINED)
667 fprintf(rf, "%s", s->vfollows);
669 fputs(not_defined, rf);
673 /* Display symbols information. */
674 if (map_control & MAP_SYMBOLS) {
678 fprintf(rf, "-- Symbols ");
683 fprintf(rf, "---- No Section ");
686 fprintf(rf, "\n\nValue Name\n");
687 for (l = no_seg_labels; l; l = l->next) {
688 lookup_label(l->name, &segment, &offset);
689 fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
693 for (s = sections; s; s = s->next) {
695 fprintf(rf, "---- Section %s ", s->name);
696 for (h = 65 - strlen(s->name); h; h--)
698 fprintf(rf, "\n\nReal Virtual Name\n");
699 for (l = s->labels; l; l = l->next) {
700 lookup_label(l->name, &segment, &offset);
701 fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
702 s->start + offset, s->vstart + offset,
711 /* Close the report file. */
712 if (map_control && (rf != stdout) && (rf != stderr))
715 /* Step 8: Release all allocated memory. */
717 /* Free sections, label pointer structs, etc.. */
721 saa_free(s->contents);
723 if (s->flags & FOLLOWS_DEFINED)
724 nasm_free(s->follows);
725 if (s->flags & VFOLLOWS_DEFINED)
726 nasm_free(s->vfollows);
735 /* Free no-section labels. */
736 while (no_seg_labels) {
738 no_seg_labels = l->next;
742 /* Free relocation structures. */
750 static void bin_out(int32_t segto, const void *data,
751 enum out_type type, uint64_t size,
752 int32_t segment, int32_t wrt)
754 uint8_t *p, mydata[8];
758 wrt = NO_SEG; /* continue to do _something_ */
759 error(ERR_NONFATAL, "WRT not supported by binary output format");
762 /* Handle absolute-assembly (structure definitions). */
763 if (segto == NO_SEG) {
764 if (type != OUT_RESERVE)
765 error(ERR_NONFATAL, "attempt to assemble code in"
766 " [ABSOLUTE] space");
770 /* Find the segment we are targeting. */
771 s = find_section_by_index(segto);
773 error(ERR_PANIC, "code directed to nonexistent segment?");
775 /* "Smart" section-type adaptation code. */
776 if (!(s->flags & TYPE_DEFINED)) {
777 if (type == OUT_RESERVE)
778 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
780 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
783 if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
784 error(ERR_WARNING, "attempt to initialize memory in a"
785 " nobits section: ignored");
787 if (type == OUT_ADDRESS) {
788 if (segment != NO_SEG && !find_section_by_index(segment)) {
790 error(ERR_NONFATAL, "binary output format does not support"
791 " segment base references");
793 error(ERR_NONFATAL, "binary output format does not support"
794 " external references");
797 if (s->flags & TYPE_PROGBITS) {
798 if (segment != NO_SEG)
799 add_reloc(s, size, segment, -1L);
801 WRITEADDR(p, *(int64_t *)data, size);
802 saa_wbytes(s->contents, mydata, size);
805 } else if (type == OUT_RAWDATA) {
806 if (s->flags & TYPE_PROGBITS)
807 saa_wbytes(s->contents, data, size);
809 } else if (type == OUT_RESERVE) {
810 if (s->flags & TYPE_PROGBITS) {
811 error(ERR_WARNING, "uninitialized space declared in"
812 " %s section: zeroing", s->name);
813 saa_wbytes(s->contents, NULL, size);
816 } else if (type == OUT_REL2ADR || type == OUT_REL4ADR ||
817 type == OUT_REL8ADR) {
818 int64_t addr = *(int64_t *)data - size;
819 size = realsize(type, size);
820 if (segment != NO_SEG && !find_section_by_index(segment)) {
822 error(ERR_NONFATAL, "binary output format does not support"
823 " segment base references");
825 error(ERR_NONFATAL, "binary output format does not support"
826 " external references");
829 if (s->flags & TYPE_PROGBITS) {
830 add_reloc(s, size, segment, segto);
832 WRITEADDR(p, addr - s->length, size);
833 saa_wbytes(s->contents, mydata, size);
839 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
840 int is_global, char *special)
842 (void)segment; /* Don't warn that this parameter is unused */
843 (void)offset; /* Don't warn that this parameter is unused */
846 error(ERR_NONFATAL, "binary format does not support any"
847 " special symbol types");
848 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
849 error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
850 else if (is_global == 2)
851 error(ERR_NONFATAL, "binary output format does not support common"
855 struct bin_label ***ltp;
857 /* Remember label definition so we can look it up later when
858 * creating the map file. */
859 s = find_section_by_index(segment);
861 ltp = &(s->labels_end);
864 (**ltp) = nasm_malloc(sizeof(struct bin_label));
865 (**ltp)->name = name;
866 (**ltp)->next = NULL;
867 *ltp = &((**ltp)->next);
872 /* These constants and the following function are used
873 * by bin_secname() to parse attribute assignments. */
875 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
876 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
877 ATTRIB_NOBITS, ATTRIB_PROGBITS
880 static int bin_read_attribute(char **line, int *attribute,
884 int attrib_name_size;
885 struct tokenval tokval;
888 /* Skip whitespace. */
889 while (**line && nasm_isspace(**line))
894 /* Figure out what attribute we're reading. */
895 if (!nasm_strnicmp(*line, "align=", 6)) {
896 *attribute = ATTRIB_ALIGN;
897 attrib_name_size = 6;
898 } else if (format_mode) {
899 if (!nasm_strnicmp(*line, "start=", 6)) {
900 *attribute = ATTRIB_START;
901 attrib_name_size = 6;
902 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
903 *attribute = ATTRIB_FOLLOWS;
906 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
907 *attribute = ATTRIB_VSTART;
908 attrib_name_size = 7;
909 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
910 *attribute = ATTRIB_VALIGN;
911 attrib_name_size = 7;
912 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
913 *attribute = ATTRIB_VFOLLOWS;
916 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
917 (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
918 *attribute = ATTRIB_NOBITS;
921 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
922 (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
923 *attribute = ATTRIB_PROGBITS;
931 /* Find the end of the expression. */
932 if ((*line)[attrib_name_size] != '(') {
933 /* Single term (no parenthesis). */
934 exp = *line += attrib_name_size;
935 while (**line && !nasm_isspace(**line))
945 /* Full expression (delimited by parenthesis) */
946 exp = *line += attrib_name_size + 1;
948 (*line) += strcspn(*line, "()'\"");
959 if ((**line == '"') || (**line == '\'')) {
968 "invalid syntax in `section' directive");
974 error(ERR_NONFATAL, "expecting `)'");
978 *(*line - 1) = '\0'; /* Terminate the expression. */
981 /* Check for no value given. */
983 error(ERR_WARNING, "No value given to attribute in"
984 " `section' directive");
988 /* Read and evaluate the expression. */
990 stdscan_bufptr = exp;
991 tokval.t_type = TOKEN_INVALID;
992 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
994 if (!is_really_simple(e)) {
995 error(ERR_NONFATAL, "section attribute value must be"
996 " a critical expression");
1000 error(ERR_NONFATAL, "Invalid attribute value"
1001 " specified in `section' directive.");
1004 *value = (uint64_t)reloc_value(e);
1008 static void bin_assign_attributes(struct Section *sec, char *astring)
1010 int attribute, check;
1014 while (1) { /* Get the next attribute. */
1015 check = bin_read_attribute(&astring, &attribute, &value);
1016 /* Skip bad attribute. */
1019 /* Unknown section attribute, so skip it and warn the user. */
1022 break; /* End of line. */
1025 while (*astring && !nasm_isspace(*astring))
1031 error(ERR_WARNING, "ignoring unknown section attribute:"
1037 switch (attribute) { /* Handle nobits attribute. */
1039 if ((sec->flags & TYPE_DEFINED)
1040 && (sec->flags & TYPE_PROGBITS))
1042 "attempt to change section type"
1043 " from progbits to nobits");
1045 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1048 /* Handle progbits attribute. */
1049 case ATTRIB_PROGBITS:
1050 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1051 error(ERR_NONFATAL, "attempt to change section type"
1052 " from nobits to progbits");
1054 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1057 /* Handle align attribute. */
1059 if (!format_mode && (!strcmp(sec->name, ".text")))
1060 error(ERR_NONFATAL, "cannot specify an alignment"
1061 " to the .text section");
1063 if (!value || ((value - 1) & value))
1064 error(ERR_NONFATAL, "argument to `align' is not a"
1066 else { /* Alignment is already satisfied if the previous
1067 * align value is greater. */
1068 if ((sec->flags & ALIGN_DEFINED)
1069 && (value < sec->align))
1072 /* Don't allow a conflicting align value. */
1073 if ((sec->flags & START_DEFINED)
1074 && (sec->start & (value - 1)))
1076 "`align' value conflicts "
1077 "with section start address");
1080 sec->flags |= ALIGN_DEFINED;
1086 /* Handle valign attribute. */
1088 if (!value || ((value - 1) & value))
1089 error(ERR_NONFATAL, "argument to `valign' is not a"
1091 else { /* Alignment is already satisfied if the previous
1092 * align value is greater. */
1093 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1094 value = sec->valign;
1096 /* Don't allow a conflicting valign value. */
1097 if ((sec->flags & VSTART_DEFINED)
1098 && (sec->vstart & (value - 1)))
1100 "`valign' value conflicts "
1101 "with `vstart' address");
1103 sec->valign = value;
1104 sec->flags |= VALIGN_DEFINED;
1109 /* Handle start attribute. */
1111 if (sec->flags & FOLLOWS_DEFINED)
1112 error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1113 " section attributes");
1114 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1115 error(ERR_NONFATAL, "section start address redefined");
1118 sec->flags |= START_DEFINED;
1119 if (sec->flags & ALIGN_DEFINED) {
1120 if (sec->start & (sec->align - 1))
1121 error(ERR_NONFATAL, "`start' address conflicts"
1122 " with section alignment");
1123 sec->flags ^= ALIGN_DEFINED;
1128 /* Handle vstart attribute. */
1130 if (sec->flags & VFOLLOWS_DEFINED)
1132 "cannot combine `vstart' and `vfollows'"
1133 " section attributes");
1134 else if ((sec->flags & VSTART_DEFINED)
1135 && (value != sec->vstart))
1137 "section virtual start address"
1138 " (vstart) redefined");
1140 sec->vstart = value;
1141 sec->flags |= VSTART_DEFINED;
1142 if (sec->flags & VALIGN_DEFINED) {
1143 if (sec->vstart & (sec->valign - 1))
1144 error(ERR_NONFATAL, "`vstart' address conflicts"
1145 " with `valign' value");
1146 sec->flags ^= VALIGN_DEFINED;
1151 /* Handle follows attribute. */
1152 case ATTRIB_FOLLOWS:
1154 astring += strcspn(astring, " \t");
1156 error(ERR_NONFATAL, "expecting section name for `follows'"
1159 *(astring++) = '\0';
1160 if (sec->flags & START_DEFINED)
1162 "cannot combine `start' and `follows'"
1163 " section attributes");
1164 sec->follows = nasm_strdup(p);
1165 sec->flags |= FOLLOWS_DEFINED;
1169 /* Handle vfollows attribute. */
1170 case ATTRIB_VFOLLOWS:
1171 if (sec->flags & VSTART_DEFINED)
1173 "cannot combine `vstart' and `vfollows'"
1174 " section attributes");
1177 astring += strcspn(astring, " \t");
1180 "expecting section name for `vfollows'"
1183 *(astring++) = '\0';
1184 sec->vfollows = nasm_strdup(p);
1185 sec->flags |= VFOLLOWS_DEFINED;
1193 static void bin_define_section_labels(void)
1195 static int labels_defined = 0;
1196 struct Section *sec;
1202 for (sec = sections; sec; sec = sec->next) {
1203 base_len = strlen(sec->name) + 8;
1204 label_name = nasm_malloc(base_len + 8);
1205 strcpy(label_name, "section.");
1206 strcpy(label_name + 8, sec->name);
1208 /* section.<name>.start */
1209 strcpy(label_name + base_len, ".start");
1210 define_label(label_name, sec->start_index, 0L,
1211 NULL, 0, 0, my_ofmt, error);
1213 /* section.<name>.vstart */
1214 strcpy(label_name + base_len, ".vstart");
1215 define_label(label_name, sec->vstart_index, 0L,
1216 NULL, 0, 0, my_ofmt, error);
1218 nasm_free(label_name);
1223 static int32_t bin_secname(char *name, int pass, int *bits)
1226 struct Section *sec;
1228 /* bin_secname is called with *name = NULL at the start of each
1229 * pass. Use this opportunity to establish the default section
1230 * (default is BITS-16 ".text" segment).
1232 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1234 for (sec = sections; sec; sec = sec->next)
1235 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1236 ALIGN_DEFINED | VALIGN_DEFINED);
1238 /* Define section start and vstart labels. */
1239 if (format_mode && (pass != 1))
1240 bin_define_section_labels();
1242 /* Establish the default (.text) section. */
1244 sec = find_section_by_name(".text");
1245 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1246 current_section = sec->vstart_index;
1247 return current_section;
1250 /* Attempt to find the requested section. If it does not
1251 * exist, create it. */
1253 while (*p && !nasm_isspace(*p))
1257 sec = find_section_by_name(name);
1259 sec = create_section(name);
1260 if (!strcmp(name, ".data"))
1261 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1262 else if (!strcmp(name, ".bss")) {
1263 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1264 sec->ifollows = NULL;
1265 } else if (!format_mode) {
1266 error(ERR_NONFATAL, "section name must be "
1267 ".text, .data, or .bss");
1268 return current_section;
1272 /* Handle attribute assignments. */
1274 bin_assign_attributes(sec, p);
1276 #ifndef ABIN_SMART_ADAPT
1277 /* The following line disables smart adaptation of
1278 * PROGBITS/NOBITS section types (it forces sections to
1279 * default to PROGBITS). */
1280 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1281 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1284 /* Set the current section and return. */
1285 current_section = sec->vstart_index;
1286 return current_section;
1289 static int bin_directive(enum directives directive, char *args, int pass)
1291 switch (directive) {
1294 struct tokenval tokval;
1299 stdscan_bufptr = args;
1300 tokval.t_type = TOKEN_INVALID;
1301 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
1303 if (!is_really_simple(e))
1304 error(ERR_NONFATAL, "org value must be a critical"
1307 value = reloc_value(e);
1308 /* Check for ORG redefinition. */
1309 if (origin_defined && (value != origin))
1310 error(ERR_NONFATAL, "program origin redefined");
1317 error(ERR_NONFATAL, "No or invalid offset specified"
1318 " in ORG directive.");
1323 /* The 'map' directive allows the user to generate section
1324 * and symbol information to stdout, stderr, or to a file. */
1329 args += strspn(args, " \t");
1332 args += strcspn(args, " \t");
1335 if (!nasm_stricmp(p, "all"))
1337 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1338 else if (!nasm_stricmp(p, "brief"))
1339 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1340 else if (!nasm_stricmp(p, "sections"))
1341 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1342 else if (!nasm_stricmp(p, "segments"))
1343 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1344 else if (!nasm_stricmp(p, "symbols"))
1345 map_control |= MAP_SYMBOLS;
1347 if (!nasm_stricmp(p, "stdout"))
1349 else if (!nasm_stricmp(p, "stderr"))
1351 else { /* Must be a filename. */
1352 rf = fopen(p, "wt");
1354 error(ERR_WARNING, "unable to open map file `%s'",
1361 error(ERR_WARNING, "map file already specified");
1363 if (map_control == 0)
1364 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1374 static void bin_filename(char *inname, char *outname, efunc error)
1376 standard_extension(inname, outname, "", error);
1381 static void ith_filename(char *inname, char *outname, efunc error)
1383 standard_extension(inname, outname, ".ith", error);
1388 static void srec_filename(char *inname, char *outname, efunc error)
1390 standard_extension(inname, outname, ".srec", error);
1395 static int32_t bin_segbase(int32_t segment)
1400 static int bin_set_info(enum geninfo type, char **val)
1407 static void binfmt_init(FILE *afp, efunc errfunc, ldfunc ldef, evalfunc eval);
1408 struct ofmt of_bin, of_ith, of_srec;
1409 static void do_output_bin(void);
1410 static void do_output_ith(void);
1411 static void do_output_srec(void);
1413 static void bin_init(FILE *afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1416 do_output = do_output_bin;
1417 binfmt_init(afp, errfunc, ldef, eval);
1420 static void ith_init(FILE *afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1423 do_output = do_output_ith;
1424 binfmt_init(afp, errfunc, ldef, eval);
1427 static void srec_init(FILE *afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1430 do_output = do_output_srec;
1431 binfmt_init(afp, errfunc, ldef, eval);
1434 static void binfmt_init(FILE *afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1439 (void)eval; /* Don't warn that this parameter is unused. */
1440 (void)ldef; /* Placate optimizers. */
1442 maxbits = 64; /* Support 64-bit Segments */
1444 reloctail = &relocs;
1446 no_seg_labels = NULL;
1447 nsl_tail = &no_seg_labels;
1448 format_mode = 1; /* Extended bin format
1449 * (set this to zero for old bin format). */
1451 /* Create default section (.text). */
1452 sections = last_section = nasm_malloc(sizeof(struct Section));
1453 last_section->next = NULL;
1454 last_section->name = nasm_strdup(".text");
1455 last_section->contents = saa_init(1L);
1456 last_section->follows = last_section->vfollows = 0;
1457 last_section->ifollows = NULL;
1458 last_section->length = 0;
1459 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1460 last_section->labels = NULL;
1461 last_section->labels_end = &(last_section->labels);
1462 last_section->start_index = seg_alloc();
1463 last_section->vstart_index = current_section = seg_alloc();
1466 /* Generate binary file output */
1467 static void do_output_bin(void)
1470 uint64_t addr = origin;
1472 /* Write the progbits sections to the output file. */
1473 for (s = sections; s; s = s->next) {
1474 /* Skip non-progbits sections */
1475 if (!(s->flags & TYPE_PROGBITS))
1477 /* Skip zero-length sections */
1481 /* Pad the space between sections. */
1482 nasm_assert(addr <= s->start);
1483 fwritezero(s->start - addr, fp);
1485 /* Write the section to the output file. */
1486 saa_fpwrite(s->contents, fp);
1488 /* Keep track of the current file position */
1489 addr = s->start + s->length;
1493 /* Generate Intel hex file output */
1494 static int write_ith_record(unsigned int len, uint16_t addr,
1495 uint8_t type, void *data)
1497 char buf[1+2+4+2+255*2+2+2];
1499 uint8_t csum, *dptr = data;
1502 nasm_assert(len <= 255);
1504 csum = len + addr + (addr >> 8) + type;
1505 for (i = 0; i < len; i++)
1509 p += sprintf(p, ":%02X%04X%02X", len, addr, type);
1510 for (i = 0; i < len; i++)
1511 p += sprintf(p, "%02X", dptr[i]);
1512 p += sprintf(p, "%02X\n", csum);
1514 if (fwrite(buf, 1, p-buf, fp) != (size_t)(p-buf))
1520 static void do_output_ith(void)
1524 uint64_t addr, hiaddr, hilba;
1528 /* Write the progbits sections to the output file. */
1530 for (s = sections; s; s = s->next) {
1531 /* Skip non-progbits sections */
1532 if (!(s->flags & TYPE_PROGBITS))
1534 /* Skip zero-length sections */
1540 saa_rewind(s->contents);
1543 hiaddr = addr >> 16;
1544 if (hiaddr != hilba) {
1545 buf[0] = hiaddr >> 8;
1547 write_ith_record(2, 0, 4, buf);
1551 chunk = 32 - (addr & 31);
1555 saa_rnbytes(s->contents, buf, chunk);
1556 write_ith_record(chunk, (uint16_t)addr, 0, buf);
1563 /* Write closing record */
1564 write_ith_record(0, 0, 1, NULL);
1567 /* Generate Motorola S-records */
1568 static int write_srecord(unsigned int len, unsigned int alen,
1569 uint32_t addr, uint8_t type, void *data)
1571 char buf[2+2+8+255*2+2+2];
1573 uint8_t csum, *dptr = data;
1576 nasm_assert(len <= 255);
1592 csum = (len+alen+1) + addr + (addr >> 8) + (addr >> 16) + (addr >> 24);
1593 for (i = 0; i < len; i++)
1597 p += sprintf(p, "S%c%02X%0*X", type, len+alen+1, alen*2, addr);
1598 for (i = 0; i < len; i++)
1599 p += sprintf(p, "%02X", dptr[i]);
1600 p += sprintf(p, "%02X\n", csum);
1602 if (fwrite(buf, 1, p-buf, fp) != (size_t)(p-buf))
1608 static void do_output_srec(void)
1612 uint64_t addr, maxaddr;
1619 for (s = sections; s; s = s->next) {
1620 /* Skip non-progbits sections */
1621 if (!(s->flags & TYPE_PROGBITS))
1623 /* Skip zero-length sections */
1627 addr = s->start + s->length - 1;
1632 if (maxaddr <= 0xffff) {
1634 dtype = '1'; /* S1 = 16-bit data */
1635 etype = '9'; /* S9 = 16-bit end */
1636 } else if (maxaddr <= 0xffffff) {
1638 dtype = '2'; /* S2 = 24-bit data */
1639 etype = '8'; /* S8 = 24-bit end */
1642 dtype = '3'; /* S3 = 32-bit data */
1643 etype = '7'; /* S7 = 32-bit end */
1646 /* Write head record */
1647 write_srecord(0, 2, 0, '0', NULL);
1649 /* Write the progbits sections to the output file. */
1650 for (s = sections; s; s = s->next) {
1651 /* Skip non-progbits sections */
1652 if (!(s->flags & TYPE_PROGBITS))
1654 /* Skip zero-length sections */
1660 saa_rewind(s->contents);
1663 chunk = 32 - (addr & 31);
1667 saa_rnbytes(s->contents, buf, chunk);
1668 write_srecord(chunk, alen, (uint32_t)addr, dtype, buf);
1675 /* Write closing record */
1676 write_srecord(0, alen, 0, etype, NULL);
1680 struct ofmt of_bin = {
1681 "flat-form binary files (e.g. DOS .COM, .SYS)",
1698 struct ofmt of_ith = {
1716 struct ofmt of_srec = {
1717 "Motorola S-records",
1734 #endif /* #ifdef OF_BIN */