1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2017 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
95 static FILE *rf
= NULL
;
96 static void (*do_output
)(void);
98 /* Section flags keep track of which attributes the user has defined. */
99 #define START_DEFINED 0x001
100 #define ALIGN_DEFINED 0x002
101 #define FOLLOWS_DEFINED 0x004
102 #define VSTART_DEFINED 0x008
103 #define VALIGN_DEFINED 0x010
104 #define VFOLLOWS_DEFINED 0x020
105 #define TYPE_DEFINED 0x040
106 #define TYPE_PROGBITS 0x080
107 #define TYPE_NOBITS 0x100
109 /* This struct is used to keep track of symbols for map-file generation. */
110 static struct bin_label
{
112 struct bin_label
*next
;
113 } *no_seg_labels
, **nsl_tail
;
115 static struct Section
{
117 struct SAA
*contents
;
118 int64_t length
; /* section length in bytes */
120 /* Section attributes */
121 int flags
; /* see flag definitions above */
122 uint64_t align
; /* section alignment */
123 uint64_t valign
; /* notional section alignment */
124 uint64_t start
; /* section start address */
125 uint64_t vstart
; /* section virtual start address */
126 char *follows
; /* the section that this one will follow */
127 char *vfollows
; /* the section that this one will notionally follow */
128 int32_t start_index
; /* NASM section id for non-relocated version */
129 int32_t vstart_index
; /* the NASM section id */
131 struct bin_label
*labels
; /* linked-list of label handles for map output. */
132 struct bin_label
**labels_end
; /* Holds address of end of labels list. */
133 struct Section
*prev
; /* Points to previous section (implicit follows). */
134 struct Section
*next
; /* This links sections with a defined start address. */
136 /* The extended bin format allows for sections to have a "virtual"
137 * start address. This is accomplished by creating two sections:
138 * one beginning at the Load Memory Address and the other beginning
139 * at the Virtual Memory Address. The LMA section is only used to
140 * define the section.<section_name>.start label, but there isn't
141 * any other good way for us to handle that label.
144 } *sections
, *last_section
;
146 static struct Reloc
{
152 struct Section
*target
;
153 } *relocs
, **reloctail
;
155 static uint64_t origin
;
156 static int origin_defined
;
158 /* Stuff we need for map-file generation. */
160 #define MAP_SUMMARY 2
161 #define MAP_SECTIONS 4
162 #define MAP_SYMBOLS 8
163 static int map_control
= 0;
165 extern macros_t bin_stdmac
[];
167 static void add_reloc(struct Section
*s
, int32_t bytes
, int32_t secref
,
172 r
= *reloctail
= nasm_malloc(sizeof(struct Reloc
));
173 reloctail
= &r
->next
;
182 static struct Section
*find_section_by_name(const char *name
)
186 list_for_each(s
, sections
)
187 if (!strcmp(s
->name
, name
))
192 static struct Section
*find_section_by_index(int32_t index
)
196 list_for_each(s
, sections
)
197 if ((index
== s
->vstart_index
) || (index
== s
->start_index
))
202 static struct Section
*create_section(char *name
)
204 struct Section
*s
= nasm_zalloc(sizeof(*s
));
206 s
->prev
= last_section
;
207 s
->name
= nasm_strdup(name
);
208 s
->labels_end
= &(s
->labels
);
209 s
->contents
= saa_init(1L);
211 /* Register our sections with NASM. */
212 s
->vstart_index
= seg_alloc();
213 s
->start_index
= seg_alloc();
215 /* FIXME: Append to a tail, we need some helper */
216 last_section
->next
= s
;
222 static void bin_cleanup(void)
224 struct Section
*g
, **gp
;
225 struct Section
*gs
= NULL
, **gsp
;
226 struct Section
*s
, **sp
;
227 struct Section
*nobits
= NULL
, **nt
;
228 struct Section
*last_progbits
;
235 nasm_debug("bin_cleanup: Sections were initially referenced in this order:\n");
236 for (h
= 0, s
= sections
; s
; h
++, s
= s
->next
)
237 fprintf(stdout
, "%i. %s\n", h
, s
->name
);
240 /* Assembly has completed, so now we need to generate the output file.
241 * Step 1: Separate progbits and nobits sections into separate lists.
242 * Step 2: Sort the progbits sections into their output order.
243 * Step 3: Compute start addresses for all progbits sections.
244 * Step 4: Compute vstart addresses for all sections.
245 * Step 5: Apply relocations.
246 * Step 6: Write the sections' data to the output file.
247 * Step 7: Generate the map file.
248 * Step 8: Release all allocated memory.
251 /* To do: Smart section-type adaptation could leave some empty sections
252 * without a defined type (progbits/nobits). Won't fix now since this
253 * feature will be disabled. */
255 /* Step 1: Split progbits and nobits sections into separate lists. */
258 /* Move nobits sections into a separate list. Also pre-process nobits
259 * sections' attributes. */
260 for (sp
= §ions
->next
, s
= sections
->next
; s
; s
= *sp
) { /* Skip progbits sections. */
261 if (s
->flags
& TYPE_PROGBITS
) {
265 /* Do some special pre-processing on nobits sections' attributes. */
266 if (s
->flags
& (START_DEFINED
| ALIGN_DEFINED
| FOLLOWS_DEFINED
)) { /* Check for a mixture of real and virtual section attributes. */
267 if (s
->flags
& (VSTART_DEFINED
| VALIGN_DEFINED
|
269 nasm_fatal("cannot mix real and virtual attributes"
270 " in nobits section (%s)", s
->name
);
271 /* Real and virtual attributes mean the same thing for nobits sections. */
272 if (s
->flags
& START_DEFINED
) {
273 s
->vstart
= s
->start
;
274 s
->flags
|= VSTART_DEFINED
;
276 if (s
->flags
& ALIGN_DEFINED
) {
277 s
->valign
= s
->align
;
278 s
->flags
|= VALIGN_DEFINED
;
280 if (s
->flags
& FOLLOWS_DEFINED
) {
281 s
->vfollows
= s
->follows
;
282 s
->flags
|= VFOLLOWS_DEFINED
;
283 s
->flags
&= ~FOLLOWS_DEFINED
;
286 /* Every section must have a start address. */
287 if (s
->flags
& VSTART_DEFINED
) {
288 s
->start
= s
->vstart
;
289 s
->flags
|= START_DEFINED
;
291 /* Move the section into the nobits list. */
298 /* Step 2: Sort the progbits sections into their output order. */
300 /* In Step 2 we move around sections in groups. A group
301 * begins with a section (group leader) that has a user-
302 * defined start address or follows section. The remainder
303 * of the group is made up of the sections that implicitly
304 * follow the group leader (i.e., they were defined after
305 * the group leader and were not given an explicit start
306 * address or follows section by the user). */
308 /* For anyone attempting to read this code:
309 * g (group) points to a group of sections, the first one of which has
310 * a user-defined start address or follows section.
311 * gp (g previous) holds the location of the pointer to g.
312 * gs (g scan) is a temp variable that we use to scan to the end of the group.
313 * gsp (gs previous) holds the location of the pointer to gs.
314 * nt (nobits tail) points to the nobits section-list tail.
317 /* Link all 'follows' groups to their proper position. To do
318 * this we need to know three things: the start of the group
319 * to relocate (g), the section it is following (s), and the
320 * end of the group we're relocating (gs). */
321 for (gp
= §ions
, g
= sections
; g
; g
= gs
) { /* Find the next follows group that is out of place (g). */
322 if (!(g
->flags
& FOLLOWS_DEFINED
)) {
324 if ((g
->next
->flags
& FOLLOWS_DEFINED
) &&
325 strcmp(g
->name
, g
->next
->follows
))
334 /* Find the section that this group follows (s). */
335 for (sp
= §ions
, s
= sections
;
336 s
&& strcmp(s
->name
, g
->follows
);
337 sp
= &s
->next
, s
= s
->next
) ;
339 nasm_fatal("section %s follows an invalid or"
340 " unknown section (%s)", g
->name
, g
->follows
);
341 if (s
->next
&& (s
->next
->flags
& FOLLOWS_DEFINED
) &&
342 !strcmp(s
->name
, s
->next
->follows
))
343 nasm_fatal("sections %s and %s can't both follow"
344 " section %s", g
->name
, s
->next
->name
, s
->name
);
345 /* Find the end of the current follows group (gs). */
346 for (gsp
= &g
->next
, gs
= g
->next
;
347 gs
&& (gs
!= s
) && !(gs
->flags
& START_DEFINED
);
348 gsp
= &gs
->next
, gs
= gs
->next
) {
349 if (gs
->next
&& (gs
->next
->flags
& FOLLOWS_DEFINED
) &&
350 strcmp(gs
->name
, gs
->next
->follows
)) {
356 /* Re-link the group after its follows section. */
362 /* Link all 'start' groups to their proper position. Once
363 * again we need to know g, s, and gs (see above). The main
364 * difference is we already know g since we sort by moving
365 * groups from the 'unsorted' list into a 'sorted' list (g
366 * will always be the first section in the unsorted list). */
367 for (g
= sections
, sections
= NULL
; g
; g
= gs
) { /* Find the section that we will insert this group before (s). */
368 for (sp
= §ions
, s
= sections
; s
; sp
= &s
->next
, s
= s
->next
)
369 if ((s
->flags
& START_DEFINED
) && (g
->start
< s
->start
))
371 /* Find the end of the group (gs). */
372 for (gs
= g
->next
, gsp
= &g
->next
;
373 gs
&& !(gs
->flags
& START_DEFINED
);
374 gsp
= &gs
->next
, gs
= gs
->next
) ;
375 /* Re-link the group before the target section. */
380 /* Step 3: Compute start addresses for all progbits sections. */
382 /* Make sure we have an origin and a start address for the first section. */
383 if (origin_defined
) {
384 if (sections
->flags
& START_DEFINED
) {
385 /* Make sure this section doesn't begin before the origin. */
386 if (sections
->start
< origin
)
387 nasm_fatal("section %s begins"
388 " before program origin", sections
->name
);
389 } else if (sections
->flags
& ALIGN_DEFINED
) {
390 sections
->start
= ALIGN(origin
, sections
->align
);
392 sections
->start
= origin
;
395 if (!(sections
->flags
& START_DEFINED
))
397 origin
= sections
->start
;
399 sections
->flags
|= START_DEFINED
;
401 /* Make sure each section has an explicit start address. If it
402 * doesn't, then compute one based its alignment and the end of
403 * the previous section. */
404 for (pend
= sections
->start
, g
= s
= sections
; g
; g
= g
->next
) { /* Find the next section that could cause an overlap situation
405 * (has a defined start address, and is not zero length). */
408 s
&& ((s
->length
== 0) || !(s
->flags
& START_DEFINED
));
410 /* Compute the start address of this section, if necessary. */
411 if (!(g
->flags
& START_DEFINED
)) { /* Default to an alignment of 4 if unspecified. */
412 if (!(g
->flags
& ALIGN_DEFINED
)) {
414 g
->flags
|= ALIGN_DEFINED
;
416 /* Set the section start address. */
417 g
->start
= ALIGN(pend
, g
->align
);
418 g
->flags
|= START_DEFINED
;
420 /* Ugly special case for progbits sections' virtual attributes:
421 * If there is a defined valign, but no vstart and no vfollows, then
422 * we valign after the previous progbits section. This case doesn't
423 * really make much sense for progbits sections with a defined start
424 * address, but it is possible and we must do *something*.
425 * Not-so-ugly special case:
426 * If a progbits section has no virtual attributes, we set the
427 * vstart equal to the start address. */
428 if (!(g
->flags
& (VSTART_DEFINED
| VFOLLOWS_DEFINED
))) {
429 if (g
->flags
& VALIGN_DEFINED
)
430 g
->vstart
= ALIGN(pend
, g
->valign
);
432 g
->vstart
= g
->start
;
433 g
->flags
|= VSTART_DEFINED
;
435 /* Ignore zero-length sections. */
438 /* Compute the span of this section. */
439 pend
= g
->start
+ g
->length
;
440 /* Check for section overlap. */
442 if (s
->start
< origin
)
443 nasm_fatal("section %s beings before program origin",
445 if (g
->start
> s
->start
)
446 nasm_fatal("sections %s ~ %s and %s overlap!",
447 gs
->name
, g
->name
, s
->name
);
449 nasm_fatal("sections %s and %s overlap!",
452 /* Remember this section as the latest >0 length section. */
456 /* Step 4: Compute vstart addresses for all sections. */
458 /* Attach the nobits sections to the end of the progbits sections. */
459 for (s
= sections
; s
->next
; s
= s
->next
) ;
463 * Scan for sections that don't have a vstart address. If we find
464 * one we'll attempt to compute its vstart. If we can't compute
465 * the vstart, we leave it alone and come back to it in a
466 * subsequent scan. We continue scanning and re-scanning until
467 * we've gone one full cycle without computing any vstarts.
469 do { /* Do one full scan of the sections list. */
470 for (h
= 0, g
= sections
; g
; g
= g
->next
) {
471 if (g
->flags
& VSTART_DEFINED
)
473 /* Find the section that this one virtually follows. */
474 if (g
->flags
& VFOLLOWS_DEFINED
) {
475 for (s
= sections
; s
&& strcmp(g
->vfollows
, s
->name
);
478 nasm_fatal("section %s vfollows unknown section (%s)",
479 g
->name
, g
->vfollows
);
480 } else if (g
->prev
!= NULL
)
481 for (s
= sections
; s
&& (s
!= g
->prev
); s
= s
->next
) ;
482 /* The .bss section is the only one with prev = NULL.
483 In this case we implicitly follow the last progbits
488 /* If the section we're following has a vstart, we can proceed. */
489 if (s
->flags
& VSTART_DEFINED
) { /* Default to virtual alignment of four. */
490 if (!(g
->flags
& VALIGN_DEFINED
)) {
492 g
->flags
|= VALIGN_DEFINED
;
494 /* Compute the vstart address. */
495 g
->vstart
= ALIGN(s
->vstart
+ s
->length
, g
->valign
);
496 g
->flags
|= VSTART_DEFINED
;
498 /* Start and vstart mean the same thing for nobits sections. */
499 if (g
->flags
& TYPE_NOBITS
)
500 g
->start
= g
->vstart
;
505 /* Now check for any circular vfollows references, which will manifest
506 * themselves as sections without a defined vstart. */
507 for (h
= 0, s
= sections
; s
; s
= s
->next
) {
508 if (!(s
->flags
& VSTART_DEFINED
)) { /* Non-fatal errors after assembly has completed are generally a
509 * no-no, but we'll throw a fatal one eventually so it's ok. */
510 nasm_nonfatal("cannot compute vstart for section %s", s
->name
);
515 nasm_fatal("circular vfollows path detected");
518 nasm_debug("bin_cleanup: Confirm final section order for output file:\n");
519 for (h
= 0, s
= sections
; s
&& (s
->flags
& TYPE_PROGBITS
);
521 fprintf(stdout
, "%i. %s\n", h
, s
->name
);
524 /* Step 5: Apply relocations. */
526 /* Prepare the sections for relocating. */
527 list_for_each(s
, sections
)
528 saa_rewind(s
->contents
);
529 /* Apply relocations. */
530 list_for_each(r
, relocs
) {
531 uint8_t *p
, mydata
[8];
535 nasm_assert(r
->bytes
<= 8);
537 memset(mydata
, 0, sizeof(mydata
));
539 saa_fread(r
->target
->contents
, r
->posn
, mydata
, r
->bytes
);
542 for (b
= r
->bytes
- 1; b
>= 0; b
--)
543 l
= (l
<< 8) + mydata
[b
];
545 s
= find_section_by_index(r
->secref
);
547 if (r
->secref
== s
->start_index
)
552 s
= find_section_by_index(r
->secrel
);
554 if (r
->secrel
== s
->start_index
)
560 WRITEADDR(p
, l
, r
->bytes
);
561 saa_fwrite(r
->target
->contents
, r
->posn
, mydata
, r
->bytes
);
564 /* Step 6: Write the section data to the output file. */
567 /* Step 7: Generate the map file. */
570 static const char not_defined
[] = "not defined";
572 /* Display input and output file names. */
573 fprintf(rf
, "\n- NASM Map file ");
576 fprintf(rf
, "\n\nSource file: %s\nOutput file: %s\n\n",
579 if (map_control
& MAP_ORIGIN
) { /* Display program origin. */
580 fprintf(rf
, "-- Program origin ");
583 fprintf(rf
, "\n\n%08"PRIX64
"\n\n", origin
);
585 /* Display sections summary. */
586 if (map_control
& MAP_SUMMARY
) {
587 fprintf(rf
, "-- Sections (summary) ");
590 fprintf(rf
, "\n\nVstart Start Stop "
591 "Length Class Name\n");
592 list_for_each(s
, sections
) {
593 fprintf(rf
, "%16"PRIX64
" %16"PRIX64
" %16"PRIX64
" %08"PRIX64
" ",
594 s
->vstart
, s
->start
, s
->start
+ s
->length
,
596 if (s
->flags
& TYPE_PROGBITS
)
597 fprintf(rf
, "progbits ");
599 fprintf(rf
, "nobits ");
600 fprintf(rf
, "%s\n", s
->name
);
604 /* Display detailed section information. */
605 if (map_control
& MAP_SECTIONS
) {
606 fprintf(rf
, "-- Sections (detailed) ");
610 list_for_each(s
, sections
) {
611 fprintf(rf
, "---- Section %s ", s
->name
);
612 for (h
= 65 - strlen(s
->name
); h
; h
--)
614 fprintf(rf
, "\n\nclass: ");
615 if (s
->flags
& TYPE_PROGBITS
)
616 fprintf(rf
, "progbits");
618 fprintf(rf
, "nobits");
619 fprintf(rf
, "\nlength: %16"PRIX64
"\nstart: %16"PRIX64
""
620 "\nalign: ", s
->length
, s
->start
);
621 if (s
->flags
& ALIGN_DEFINED
)
622 fprintf(rf
, "%16"PRIX64
"", s
->align
);
624 fputs(not_defined
, rf
);
625 fprintf(rf
, "\nfollows: ");
626 if (s
->flags
& FOLLOWS_DEFINED
)
627 fprintf(rf
, "%s", s
->follows
);
629 fputs(not_defined
, rf
);
630 fprintf(rf
, "\nvstart: %16"PRIX64
"\nvalign: ", s
->vstart
);
631 if (s
->flags
& VALIGN_DEFINED
)
632 fprintf(rf
, "%16"PRIX64
"", s
->valign
);
634 fputs(not_defined
, rf
);
635 fprintf(rf
, "\nvfollows: ");
636 if (s
->flags
& VFOLLOWS_DEFINED
)
637 fprintf(rf
, "%s", s
->vfollows
);
639 fputs(not_defined
, rf
);
643 /* Display symbols information. */
644 if (map_control
& MAP_SYMBOLS
) {
649 fprintf(rf
, "-- Symbols ");
654 fprintf(rf
, "---- No Section ");
657 fprintf(rf
, "\n\nValue Name\n");
658 list_for_each(l
, no_seg_labels
) {
659 found_label
= lookup_label(l
->name
, &segment
, &offset
);
660 nasm_assert(found_label
);
661 fprintf(rf
, "%08"PRIX64
" %s\n", offset
, l
->name
);
665 list_for_each(s
, sections
) {
667 fprintf(rf
, "---- Section %s ", s
->name
);
668 for (h
= 65 - strlen(s
->name
); h
; h
--)
670 fprintf(rf
, "\n\nReal Virtual Name\n");
671 list_for_each(l
, s
->labels
) {
672 found_label
= lookup_label(l
->name
, &segment
, &offset
);
673 nasm_assert(found_label
);
674 fprintf(rf
, "%16"PRIX64
" %16"PRIX64
" %s\n",
675 s
->start
+ offset
, s
->vstart
+ offset
,
684 /* Close the report file. */
685 if (map_control
&& (rf
!= stdout
) && (rf
!= stderr
))
688 /* Step 8: Release all allocated memory. */
690 /* Free sections, label pointer structs, etc.. */
694 saa_free(s
->contents
);
696 if (s
->flags
& FOLLOWS_DEFINED
)
697 nasm_free(s
->follows
);
698 if (s
->flags
& VFOLLOWS_DEFINED
)
699 nasm_free(s
->vfollows
);
708 /* Free no-section labels. */
709 while (no_seg_labels
) {
711 no_seg_labels
= l
->next
;
715 /* Free relocation structures. */
723 static void bin_out(int32_t segto
, const void *data
,
724 enum out_type type
, uint64_t size
,
725 int32_t segment
, int32_t wrt
)
727 uint8_t *p
, mydata
[8];
731 wrt
= NO_SEG
; /* continue to do _something_ */
732 nasm_nonfatal("WRT not supported by binary output format");
735 /* Find the segment we are targeting. */
736 s
= find_section_by_index(segto
);
738 nasm_panic("code directed to nonexistent segment?");
740 /* "Smart" section-type adaptation code. */
741 if (!(s
->flags
& TYPE_DEFINED
)) {
742 if (type
== OUT_RESERVE
)
743 s
->flags
|= TYPE_DEFINED
| TYPE_NOBITS
;
745 s
->flags
|= TYPE_DEFINED
| TYPE_PROGBITS
;
748 if ((s
->flags
& TYPE_NOBITS
) && (type
!= OUT_RESERVE
))
749 nasm_warn("attempt to initialize memory in a"
750 " nobits section: ignored");
755 int asize
= abs((int)size
);
757 if (segment
!= NO_SEG
&& !find_section_by_index(segment
)) {
759 nasm_nonfatal("binary output format does not support"
760 " segment base references");
762 nasm_nonfatal("binary output format does not support"
763 " external references");
766 if (s
->flags
& TYPE_PROGBITS
) {
767 if (segment
!= NO_SEG
)
768 add_reloc(s
, asize
, segment
, -1L);
770 WRITEADDR(p
, *(int64_t *)data
, asize
);
771 saa_wbytes(s
->contents
, mydata
, asize
);
775 * Reassign size with sign dropped, we will need it
776 * for section length calculation.
783 if (s
->flags
& TYPE_PROGBITS
)
784 saa_wbytes(s
->contents
, data
, size
);
788 if (s
->flags
& TYPE_PROGBITS
) {
789 nasm_warn("uninitialized space declared in"
790 " %s section: zeroing", s
->name
);
791 saa_wbytes(s
->contents
, NULL
, size
);
800 int64_t addr
= *(int64_t *)data
- size
;
801 size
= realsize(type
, size
);
802 if (segment
!= NO_SEG
&& !find_section_by_index(segment
)) {
804 nasm_nonfatal("binary output format does not support"
805 " segment base references");
807 nasm_nonfatal("binary output format does not support"
808 " external references");
811 if (s
->flags
& TYPE_PROGBITS
) {
812 add_reloc(s
, size
, segment
, segto
);
814 WRITEADDR(p
, addr
- s
->length
, size
);
815 saa_wbytes(s
->contents
, mydata
, size
);
821 nasm_nonfatal("unsupported relocation type %d\n", type
);
828 static void bin_deflabel(char *name
, int32_t segment
, int64_t offset
,
829 int is_global
, char *special
)
831 (void)segment
; /* Don't warn that this parameter is unused */
832 (void)offset
; /* Don't warn that this parameter is unused */
835 nasm_nonfatal("binary format does not support any"
836 " special symbol types");
837 else if (name
[0] == '.' && name
[1] == '.' && name
[2] != '@')
838 nasm_nonfatal("unrecognised special symbol `%s'", name
);
839 else if (is_global
== 2)
840 nasm_nonfatal("binary output format does not support common"
844 struct bin_label
***ltp
;
846 /* Remember label definition so we can look it up later when
847 * creating the map file. */
848 s
= find_section_by_index(segment
);
850 ltp
= &(s
->labels_end
);
853 (**ltp
) = nasm_malloc(sizeof(struct bin_label
));
854 (**ltp
)->name
= name
;
855 (**ltp
)->next
= NULL
;
856 *ltp
= &((**ltp
)->next
);
861 /* These constants and the following function are used
862 * by bin_secname() to parse attribute assignments. */
864 enum { ATTRIB_START
, ATTRIB_ALIGN
, ATTRIB_FOLLOWS
,
865 ATTRIB_VSTART
, ATTRIB_VALIGN
, ATTRIB_VFOLLOWS
,
866 ATTRIB_NOBITS
, ATTRIB_PROGBITS
869 static int bin_read_attribute(char **line
, int *attribute
,
873 int attrib_name_size
;
874 struct tokenval tokval
;
877 /* Skip whitespace. */
878 while (**line
&& nasm_isspace(**line
))
883 /* Figure out what attribute we're reading. */
884 if (!nasm_strnicmp(*line
, "align=", 6)) {
885 *attribute
= ATTRIB_ALIGN
;
886 attrib_name_size
= 6;
888 if (!nasm_strnicmp(*line
, "start=", 6)) {
889 *attribute
= ATTRIB_START
;
890 attrib_name_size
= 6;
891 } else if (!nasm_strnicmp(*line
, "follows=", 8)) {
892 *attribute
= ATTRIB_FOLLOWS
;
895 } else if (!nasm_strnicmp(*line
, "vstart=", 7)) {
896 *attribute
= ATTRIB_VSTART
;
897 attrib_name_size
= 7;
898 } else if (!nasm_strnicmp(*line
, "valign=", 7)) {
899 *attribute
= ATTRIB_VALIGN
;
900 attrib_name_size
= 7;
901 } else if (!nasm_strnicmp(*line
, "vfollows=", 9)) {
902 *attribute
= ATTRIB_VFOLLOWS
;
905 } else if (!nasm_strnicmp(*line
, "nobits", 6) &&
906 (nasm_isspace((*line
)[6]) || ((*line
)[6] == '\0'))) {
907 *attribute
= ATTRIB_NOBITS
;
910 } else if (!nasm_strnicmp(*line
, "progbits", 8) &&
911 (nasm_isspace((*line
)[8]) || ((*line
)[8] == '\0'))) {
912 *attribute
= ATTRIB_PROGBITS
;
919 /* Find the end of the expression. */
920 if ((*line
)[attrib_name_size
] != '(') {
921 /* Single term (no parenthesis). */
922 exp
= *line
+= attrib_name_size
;
923 while (**line
&& !nasm_isspace(**line
))
933 /* Full expression (delimited by parenthesis) */
934 exp
= *line
+= attrib_name_size
+ 1;
936 (*line
) += strcspn(*line
, "()'\"");
947 if ((**line
== '"') || (**line
== '\'')) {
955 nasm_nonfatal("invalid syntax in `section' directive");
961 nasm_nonfatal("expecting `)'");
965 *(*line
- 1) = '\0'; /* Terminate the expression. */
968 /* Check for no value given. */
970 nasm_warn("No value given to attribute in"
971 " `section' directive");
975 /* Read and evaluate the expression. */
978 tokval
.t_type
= TOKEN_INVALID
;
979 e
= evaluate(stdscan
, NULL
, &tokval
, NULL
, 1, NULL
);
981 if (!is_really_simple(e
)) {
982 nasm_nonfatal("section attribute value must be"
983 " a critical expression");
987 nasm_nonfatal("Invalid attribute value"
988 " specified in `section' directive.");
991 *value
= (uint64_t)reloc_value(e
);
995 static void bin_sectalign(int32_t seg
, unsigned int value
)
997 struct Section
*s
= find_section_by_index(seg
);
999 if (!s
|| !is_power2(value
))
1002 if (value
> s
->align
)
1005 if (!(s
->flags
& ALIGN_DEFINED
))
1006 s
->flags
|= ALIGN_DEFINED
;
1009 static void bin_assign_attributes(struct Section
*sec
, char *astring
)
1011 int attribute
, check
;
1015 while (1) { /* Get the next attribute. */
1016 check
= bin_read_attribute(&astring
, &attribute
, &value
);
1017 /* Skip bad attribute. */
1020 /* Unknown section attribute, so skip it and warn the user. */
1023 break; /* End of line. */
1026 while (*astring
&& !nasm_isspace(*astring
))
1032 nasm_warn("ignoring unknown section attribute: \"%s\"", p
);
1037 switch (attribute
) { /* Handle nobits attribute. */
1039 if ((sec
->flags
& TYPE_DEFINED
)
1040 && (sec
->flags
& TYPE_PROGBITS
))
1041 nasm_nonfatal("attempt to change section type"
1042 " from progbits to nobits");
1044 sec
->flags
|= TYPE_DEFINED
| TYPE_NOBITS
;
1047 /* Handle progbits attribute. */
1048 case ATTRIB_PROGBITS
:
1049 if ((sec
->flags
& TYPE_DEFINED
) && (sec
->flags
& TYPE_NOBITS
))
1050 nasm_nonfatal("attempt to change section type"
1051 " from nobits to progbits");
1053 sec
->flags
|= TYPE_DEFINED
| TYPE_PROGBITS
;
1056 /* Handle align attribute. */
1058 if (!value
|| ((value
- 1) & value
)) {
1059 nasm_nonfatal("argument to `align' is not a power of two");
1062 * Alignment is already satisfied if
1063 * the previous align value is greater
1065 if ((sec
->flags
& ALIGN_DEFINED
) && (value
< sec
->align
))
1068 /* Don't allow a conflicting align value. */
1069 if ((sec
->flags
& START_DEFINED
) && (sec
->start
& (value
- 1))) {
1070 nasm_nonfatal("`align' value conflicts with section start address");
1073 sec
->flags
|= ALIGN_DEFINED
;
1078 /* Handle valign attribute. */
1080 if (!value
|| ((value
- 1) & value
))
1081 nasm_nonfatal("argument to `valign' is not a power of two");
1082 else { /* Alignment is already satisfied if the previous
1083 * align value is greater. */
1084 if ((sec
->flags
& VALIGN_DEFINED
) && (value
< sec
->valign
))
1085 value
= sec
->valign
;
1087 /* Don't allow a conflicting valign value. */
1088 if ((sec
->flags
& VSTART_DEFINED
)
1089 && (sec
->vstart
& (value
- 1)))
1090 nasm_nonfatal("`valign' value conflicts with `vstart' address");
1092 sec
->valign
= value
;
1093 sec
->flags
|= VALIGN_DEFINED
;
1098 /* Handle start attribute. */
1100 if (sec
->flags
& FOLLOWS_DEFINED
)
1101 nasm_nonfatal("cannot combine `start' and `follows'"
1102 " section attributes");
1103 else if ((sec
->flags
& START_DEFINED
) && (value
!= sec
->start
))
1104 nasm_nonfatal("section start address redefined");
1107 sec
->flags
|= START_DEFINED
;
1108 if (sec
->flags
& ALIGN_DEFINED
) {
1109 if (sec
->start
& (sec
->align
- 1))
1110 nasm_nonfatal("`start' address conflicts"
1111 " with section alignment");
1112 sec
->flags
^= ALIGN_DEFINED
;
1117 /* Handle vstart attribute. */
1119 if (sec
->flags
& VFOLLOWS_DEFINED
)
1120 nasm_nonfatal("cannot combine `vstart' and `vfollows'"
1121 " section attributes");
1122 else if ((sec
->flags
& VSTART_DEFINED
)
1123 && (value
!= sec
->vstart
))
1124 nasm_nonfatal("section virtual start address"
1125 " (vstart) redefined");
1127 sec
->vstart
= value
;
1128 sec
->flags
|= VSTART_DEFINED
;
1129 if (sec
->flags
& VALIGN_DEFINED
) {
1130 if (sec
->vstart
& (sec
->valign
- 1))
1131 nasm_nonfatal("`vstart' address conflicts"
1132 " with `valign' value");
1133 sec
->flags
^= VALIGN_DEFINED
;
1138 /* Handle follows attribute. */
1139 case ATTRIB_FOLLOWS
:
1141 astring
+= strcspn(astring
, " \t");
1143 nasm_nonfatal("expecting section name for `follows'"
1146 *(astring
++) = '\0';
1147 if (sec
->flags
& START_DEFINED
)
1148 nasm_nonfatal("cannot combine `start' and `follows'"
1149 " section attributes");
1150 sec
->follows
= nasm_strdup(p
);
1151 sec
->flags
|= FOLLOWS_DEFINED
;
1155 /* Handle vfollows attribute. */
1156 case ATTRIB_VFOLLOWS
:
1157 if (sec
->flags
& VSTART_DEFINED
)
1158 nasm_nonfatal("cannot combine `vstart' and `vfollows'"
1159 " section attributes");
1162 astring
+= strcspn(astring
, " \t");
1164 nasm_nonfatal("expecting section name for `vfollows'"
1167 *(astring
++) = '\0';
1168 sec
->vfollows
= nasm_strdup(p
);
1169 sec
->flags
|= VFOLLOWS_DEFINED
;
1177 static void bin_define_section_labels(void)
1179 static int labels_defined
= 0;
1180 struct Section
*sec
;
1186 list_for_each(sec
, sections
) {
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, false);
1196 /* section.<name>.vstart */
1197 strcpy(label_name
+ base_len
, ".vstart");
1198 define_label(label_name
, sec
->vstart_index
, 0L, false);
1200 nasm_free(label_name
);
1205 static int32_t bin_secname(char *name
, int pass
, int *bits
)
1208 struct Section
*sec
;
1210 /* bin_secname is called with *name = NULL at the start of each
1211 * pass. Use this opportunity to establish the default section
1212 * (default is BITS-16 ".text" segment).
1214 if (!name
) { /* Reset ORG and section attributes at the start of each pass. */
1216 list_for_each(sec
, sections
)
1217 sec
->flags
&= ~(START_DEFINED
| VSTART_DEFINED
|
1218 ALIGN_DEFINED
| VALIGN_DEFINED
);
1220 /* Define section start and vstart labels. */
1222 bin_define_section_labels();
1224 /* Establish the default (.text) section. */
1226 sec
= find_section_by_name(".text");
1227 sec
->flags
|= TYPE_DEFINED
| TYPE_PROGBITS
;
1228 return sec
->vstart_index
;
1231 /* Attempt to find the requested section. If it does not
1232 * exist, create it. */
1234 while (*p
&& !nasm_isspace(*p
))
1238 sec
= find_section_by_name(name
);
1240 sec
= create_section(name
);
1241 if (!strcmp(name
, ".data"))
1242 sec
->flags
|= TYPE_DEFINED
| TYPE_PROGBITS
;
1243 else if (!strcmp(name
, ".bss")) {
1244 sec
->flags
|= TYPE_DEFINED
| TYPE_NOBITS
;
1249 /* Handle attribute assignments. */
1251 bin_assign_attributes(sec
, p
);
1253 #ifndef ABIN_SMART_ADAPT
1254 /* The following line disables smart adaptation of
1255 * PROGBITS/NOBITS section types (it forces sections to
1256 * default to PROGBITS). */
1257 if ((pass
!= 1) && !(sec
->flags
& TYPE_DEFINED
))
1258 sec
->flags
|= TYPE_DEFINED
| TYPE_PROGBITS
;
1261 return sec
->vstart_index
;
1264 static enum directive_result
1265 bin_directive(enum directive directive
, char *args
, int pass
)
1267 switch (directive
) {
1270 struct tokenval tokval
;
1276 tokval
.t_type
= TOKEN_INVALID
;
1277 e
= evaluate(stdscan
, NULL
, &tokval
, NULL
, 1, NULL
);
1279 if (!is_really_simple(e
))
1280 nasm_nonfatal("org value must be a critical"
1283 value
= reloc_value(e
);
1284 /* Check for ORG redefinition. */
1285 if (origin_defined
&& (value
!= origin
))
1286 nasm_nonfatal("program origin redefined");
1293 nasm_nonfatal("No or invalid offset specified"
1294 " in ORG directive.");
1299 /* The 'map' directive allows the user to generate section
1300 * and symbol information to stdout, stderr, or to a file. */
1305 args
+= strspn(args
, " \t");
1308 args
+= strcspn(args
, " \t");
1311 if (!nasm_stricmp(p
, "all"))
1313 MAP_ORIGIN
| MAP_SUMMARY
| MAP_SECTIONS
| MAP_SYMBOLS
;
1314 else if (!nasm_stricmp(p
, "brief"))
1315 map_control
|= MAP_ORIGIN
| MAP_SUMMARY
;
1316 else if (!nasm_stricmp(p
, "sections"))
1317 map_control
|= MAP_ORIGIN
| MAP_SUMMARY
| MAP_SECTIONS
;
1318 else if (!nasm_stricmp(p
, "segments"))
1319 map_control
|= MAP_ORIGIN
| MAP_SUMMARY
| MAP_SECTIONS
;
1320 else if (!nasm_stricmp(p
, "symbols"))
1321 map_control
|= MAP_SYMBOLS
;
1323 if (!nasm_stricmp(p
, "stdout"))
1325 else if (!nasm_stricmp(p
, "stderr"))
1327 else { /* Must be a filename. */
1328 rf
= nasm_open_write(p
, NF_TEXT
);
1330 nasm_warn("unable to open map file `%s'", p
);
1336 nasm_warn("map file already specified");
1338 if (map_control
== 0)
1339 map_control
|= MAP_ORIGIN
| MAP_SUMMARY
;
1345 return DIRR_UNKNOWN
;
1349 const struct ofmt of_bin
, of_ith
, of_srec
;
1350 static void binfmt_init(void);
1351 static void do_output_bin(void);
1352 static void do_output_ith(void);
1353 static void do_output_srec(void);
1355 static void bin_init(void)
1357 do_output
= do_output_bin
;
1361 static void ith_init(void)
1363 do_output
= do_output_ith
;
1367 static void srec_init(void)
1369 do_output
= do_output_srec
;
1373 static void binfmt_init(void)
1376 reloctail
= &relocs
;
1378 no_seg_labels
= NULL
;
1379 nsl_tail
= &no_seg_labels
;
1381 /* Create default section (.text). */
1382 sections
= last_section
= nasm_zalloc(sizeof(struct Section
));
1383 last_section
->name
= nasm_strdup(".text");
1384 last_section
->contents
= saa_init(1L);
1385 last_section
->flags
= TYPE_DEFINED
| TYPE_PROGBITS
;
1386 last_section
->labels_end
= &(last_section
->labels
);
1387 last_section
->start_index
= seg_alloc();
1388 last_section
->vstart_index
= seg_alloc();
1391 /* Generate binary file output */
1392 static void do_output_bin(void)
1395 uint64_t addr
= origin
;
1397 /* Write the progbits sections to the output file. */
1398 list_for_each(s
, sections
) {
1399 /* Skip non-progbits sections */
1400 if (!(s
->flags
& TYPE_PROGBITS
))
1402 /* Skip zero-length sections */
1406 /* Pad the space between sections. */
1407 nasm_assert(addr
<= s
->start
);
1408 fwritezero(s
->start
- addr
, ofile
);
1410 /* Write the section to the output file. */
1411 saa_fpwrite(s
->contents
, ofile
);
1413 /* Keep track of the current file position */
1414 addr
= s
->start
+ s
->length
;
1418 /* Generate Intel hex file output */
1419 static void write_ith_record(unsigned int len
, uint16_t addr
,
1420 uint8_t type
, void *data
)
1422 char buf
[1+2+4+2+255*2+2+2];
1424 uint8_t csum
, *dptr
= data
;
1427 nasm_assert(len
<= 255);
1429 csum
= len
+ addr
+ (addr
>> 8) + type
;
1430 for (i
= 0; i
< len
; i
++)
1434 p
+= sprintf(p
, ":%02X%04X%02X", len
, addr
, type
);
1435 for (i
= 0; i
< len
; i
++)
1436 p
+= sprintf(p
, "%02X", dptr
[i
]);
1437 p
+= sprintf(p
, "%02X\n", csum
);
1439 nasm_write(buf
, p
-buf
, ofile
);
1442 static void do_output_ith(void)
1446 uint64_t addr
, hiaddr
, hilba
;
1450 /* Write the progbits sections to the output file. */
1452 list_for_each(s
, sections
) {
1453 /* Skip non-progbits sections */
1454 if (!(s
->flags
& TYPE_PROGBITS
))
1456 /* Skip zero-length sections */
1462 saa_rewind(s
->contents
);
1465 hiaddr
= addr
>> 16;
1466 if (hiaddr
!= hilba
) {
1467 buf
[0] = hiaddr
>> 8;
1469 write_ith_record(2, 0, 4, buf
);
1473 chunk
= 32 - (addr
& 31);
1477 saa_rnbytes(s
->contents
, buf
, chunk
);
1478 write_ith_record(chunk
, (uint16_t)addr
, 0, buf
);
1485 /* Write closing record */
1486 write_ith_record(0, 0, 1, NULL
);
1489 /* Generate Motorola S-records */
1490 static void write_srecord(unsigned int len
, unsigned int alen
,
1491 uint32_t addr
, uint8_t type
, void *data
)
1493 char buf
[2+2+8+255*2+2+2];
1495 uint8_t csum
, *dptr
= data
;
1498 nasm_assert(len
<= 255);
1514 csum
= (len
+alen
+1) + addr
+ (addr
>> 8) + (addr
>> 16) + (addr
>> 24);
1515 for (i
= 0; i
< len
; i
++)
1519 p
+= sprintf(p
, "S%c%02X%0*X", type
, len
+alen
+1, alen
*2, addr
);
1520 for (i
= 0; i
< len
; i
++)
1521 p
+= sprintf(p
, "%02X", dptr
[i
]);
1522 p
+= sprintf(p
, "%02X\n", csum
);
1524 nasm_write(buf
, p
-buf
, ofile
);
1527 static void do_output_srec(void)
1531 uint64_t addr
, maxaddr
;
1538 list_for_each(s
, sections
) {
1539 /* Skip non-progbits sections */
1540 if (!(s
->flags
& TYPE_PROGBITS
))
1542 /* Skip zero-length sections */
1546 addr
= s
->start
+ s
->length
- 1;
1551 if (maxaddr
<= 0xffff) {
1553 dtype
= '1'; /* S1 = 16-bit data */
1554 etype
= '9'; /* S9 = 16-bit end */
1555 } else if (maxaddr
<= 0xffffff) {
1557 dtype
= '2'; /* S2 = 24-bit data */
1558 etype
= '8'; /* S8 = 24-bit end */
1561 dtype
= '3'; /* S3 = 32-bit data */
1562 etype
= '7'; /* S7 = 32-bit end */
1565 /* Write head record */
1566 write_srecord(0, 2, 0, '0', NULL
);
1568 /* Write the progbits sections to the output file. */
1569 list_for_each(s
, sections
) {
1570 /* Skip non-progbits sections */
1571 if (!(s
->flags
& TYPE_PROGBITS
))
1573 /* Skip zero-length sections */
1579 saa_rewind(s
->contents
);
1582 chunk
= 32 - (addr
& 31);
1586 saa_rnbytes(s
->contents
, buf
, chunk
);
1587 write_srecord(chunk
, alen
, (uint32_t)addr
, dtype
, buf
);
1594 /* Write closing record */
1595 write_srecord(0, alen
, 0, etype
, NULL
);
1599 const struct ofmt of_bin
= {
1600 "flat-form binary files (e.g. DOS .COM, .SYS)",
1610 nasm_do_legacy_output
,
1619 NULL
/* pragma list */
1622 const struct ofmt of_ith
= {
1625 ".ith", /* really should have been ".hex"... */
1633 nasm_do_legacy_output
,
1642 NULL
/* pragma list */
1645 const struct ofmt of_srec
= {
1646 "Motorola S-records",
1656 nasm_do_legacy_output
,
1665 NULL
/* pragma list */
1668 #endif /* #ifdef OF_BIN */