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
92 static FILE *rf
= NULL
;
93 static void (*do_output
)(void);
95 /* Section flags keep track of which attributes the user has defined. */
96 #define START_DEFINED 0x001
97 #define ALIGN_DEFINED 0x002
98 #define FOLLOWS_DEFINED 0x004
99 #define VSTART_DEFINED 0x008
100 #define VALIGN_DEFINED 0x010
101 #define VFOLLOWS_DEFINED 0x020
102 #define TYPE_DEFINED 0x040
103 #define TYPE_PROGBITS 0x080
104 #define TYPE_NOBITS 0x100
106 /* This struct is used to keep track of symbols for map-file generation. */
107 static struct bin_label
{
109 struct bin_label
*next
;
110 } *no_seg_labels
, **nsl_tail
;
112 static struct Section
{
114 struct SAA
*contents
;
115 int64_t length
; /* section length in bytes */
117 /* Section attributes */
118 int flags
; /* see flag definitions above */
119 uint64_t align
; /* section alignment */
120 uint64_t valign
; /* notional section alignment */
121 uint64_t start
; /* section start address */
122 uint64_t vstart
; /* section virtual start address */
123 char *follows
; /* the section that this one will follow */
124 char *vfollows
; /* the section that this one will notionally follow */
125 int32_t start_index
; /* NASM section id for non-relocated version */
126 int32_t vstart_index
; /* the NASM section id */
128 struct bin_label
*labels
; /* linked-list of label handles for map output. */
129 struct bin_label
**labels_end
; /* Holds address of end of labels list. */
130 struct Section
*prev
; /* Points to previous section (implicit follows). */
131 struct Section
*next
; /* This links sections with a defined start address. */
133 /* The extended bin format allows for sections to have a "virtual"
134 * start address. This is accomplished by creating two sections:
135 * one beginning at the Load Memory Address and the other beginning
136 * at the Virtual Memory Address. The LMA section is only used to
137 * define the section.<section_name>.start label, but there isn't
138 * any other good way for us to handle that label.
141 } *sections
, *last_section
;
143 static struct Reloc
{
149 struct Section
*target
;
150 } *relocs
, **reloctail
;
152 static uint64_t origin
;
153 static int origin_defined
;
155 /* Stuff we need for map-file generation. */
157 #define MAP_SUMMARY 2
158 #define MAP_SECTIONS 4
159 #define MAP_SYMBOLS 8
160 static int map_control
= 0;
162 extern macros_t bin_stdmac
[];
164 static void add_reloc(struct Section
*s
, int32_t bytes
, int32_t secref
,
169 r
= *reloctail
= nasm_malloc(sizeof(struct Reloc
));
170 reloctail
= &r
->next
;
179 static struct Section
*find_section_by_name(const char *name
)
183 list_for_each(s
, sections
)
184 if (!strcmp(s
->name
, name
))
189 static struct Section
*find_section_by_index(int32_t index
)
193 list_for_each(s
, sections
)
194 if ((index
== s
->vstart_index
) || (index
== s
->start_index
))
199 static struct Section
*create_section(char *name
)
201 struct Section
*s
= nasm_zalloc(sizeof(*s
));
203 s
->prev
= last_section
;
204 s
->name
= nasm_strdup(name
);
205 s
->labels_end
= &(s
->labels
);
206 s
->contents
= saa_init(1L);
208 /* Register our sections with NASM. */
209 s
->vstart_index
= seg_alloc();
210 s
->start_index
= seg_alloc();
212 /* FIXME: Append to a tail, we need some helper */
213 last_section
->next
= s
;
219 static void bin_cleanup(void)
221 struct Section
*g
, **gp
;
222 struct Section
*gs
= NULL
, **gsp
;
223 struct Section
*s
, **sp
;
224 struct Section
*nobits
= NULL
, **nt
;
225 struct Section
*last_progbits
;
231 if (debug_level(1)) {
232 nasm_debug("bin_cleanup: Sections were initially referenced in this order:\n");
233 for (h
= 0, s
= sections
; s
; h
++, s
= s
->next
)
234 nasm_debug("%i. %s\n", h
, s
->name
);
237 /* Assembly has completed, so now we need to generate the output file.
238 * Step 1: Separate progbits and nobits sections into separate lists.
239 * Step 2: Sort the progbits sections into their output order.
240 * Step 3: Compute start addresses for all progbits sections.
241 * Step 4: Compute vstart addresses for all sections.
242 * Step 5: Apply relocations.
243 * Step 6: Write the sections' data to the output file.
244 * Step 7: Generate the map file.
245 * Step 8: Release all allocated memory.
248 /* To do: Smart section-type adaptation could leave some empty sections
249 * without a defined type (progbits/nobits). Won't fix now since this
250 * feature will be disabled. */
252 /* Step 1: Split progbits and nobits sections into separate lists. */
255 /* Move nobits sections into a separate list. Also pre-process nobits
256 * sections' attributes. */
257 for (sp
= §ions
->next
, s
= sections
->next
; s
; s
= *sp
) { /* Skip progbits sections. */
258 if (s
->flags
& TYPE_PROGBITS
) {
262 /* Do some special pre-processing on nobits sections' attributes. */
263 if (s
->flags
& (START_DEFINED
| ALIGN_DEFINED
| FOLLOWS_DEFINED
)) { /* Check for a mixture of real and virtual section attributes. */
264 if (s
->flags
& (VSTART_DEFINED
| VALIGN_DEFINED
|
266 nasm_fatal("cannot mix real and virtual attributes"
267 " in nobits section (%s)", s
->name
);
268 /* Real and virtual attributes mean the same thing for nobits sections. */
269 if (s
->flags
& START_DEFINED
) {
270 s
->vstart
= s
->start
;
271 s
->flags
|= VSTART_DEFINED
;
273 if (s
->flags
& ALIGN_DEFINED
) {
274 s
->valign
= s
->align
;
275 s
->flags
|= VALIGN_DEFINED
;
277 if (s
->flags
& FOLLOWS_DEFINED
) {
278 s
->vfollows
= s
->follows
;
279 s
->flags
|= VFOLLOWS_DEFINED
;
280 s
->flags
&= ~FOLLOWS_DEFINED
;
283 /* Every section must have a start address. */
284 if (s
->flags
& VSTART_DEFINED
) {
285 s
->start
= s
->vstart
;
286 s
->flags
|= START_DEFINED
;
288 /* Move the section into the nobits list. */
295 /* Step 2: Sort the progbits sections into their output order. */
297 /* In Step 2 we move around sections in groups. A group
298 * begins with a section (group leader) that has a user-
299 * defined start address or follows section. The remainder
300 * of the group is made up of the sections that implicitly
301 * follow the group leader (i.e., they were defined after
302 * the group leader and were not given an explicit start
303 * address or follows section by the user). */
305 /* For anyone attempting to read this code:
306 * g (group) points to a group of sections, the first one of which has
307 * a user-defined start address or follows section.
308 * gp (g previous) holds the location of the pointer to g.
309 * gs (g scan) is a temp variable that we use to scan to the end of the group.
310 * gsp (gs previous) holds the location of the pointer to gs.
311 * nt (nobits tail) points to the nobits section-list tail.
314 /* Link all 'follows' groups to their proper position. To do
315 * this we need to know three things: the start of the group
316 * to relocate (g), the section it is following (s), and the
317 * end of the group we're relocating (gs). */
318 for (gp
= §ions
, g
= sections
; g
; g
= gs
) { /* Find the next follows group that is out of place (g). */
319 if (!(g
->flags
& FOLLOWS_DEFINED
)) {
321 if ((g
->next
->flags
& FOLLOWS_DEFINED
) &&
322 strcmp(g
->name
, g
->next
->follows
))
331 /* Find the section that this group follows (s). */
332 for (sp
= §ions
, s
= sections
;
333 s
&& strcmp(s
->name
, g
->follows
);
334 sp
= &s
->next
, s
= s
->next
) ;
336 nasm_fatal("section %s follows an invalid or"
337 " unknown section (%s)", g
->name
, g
->follows
);
338 if (s
->next
&& (s
->next
->flags
& FOLLOWS_DEFINED
) &&
339 !strcmp(s
->name
, s
->next
->follows
))
340 nasm_fatal("sections %s and %s can't both follow"
341 " section %s", g
->name
, s
->next
->name
, s
->name
);
342 /* Find the end of the current follows group (gs). */
343 for (gsp
= &g
->next
, gs
= g
->next
;
344 gs
&& (gs
!= s
) && !(gs
->flags
& START_DEFINED
);
345 gsp
= &gs
->next
, gs
= gs
->next
) {
346 if (gs
->next
&& (gs
->next
->flags
& FOLLOWS_DEFINED
) &&
347 strcmp(gs
->name
, gs
->next
->follows
)) {
353 /* Re-link the group after its follows section. */
359 /* Link all 'start' groups to their proper position. Once
360 * again we need to know g, s, and gs (see above). The main
361 * difference is we already know g since we sort by moving
362 * groups from the 'unsorted' list into a 'sorted' list (g
363 * will always be the first section in the unsorted list). */
364 for (g
= sections
, sections
= NULL
; g
; g
= gs
) { /* Find the section that we will insert this group before (s). */
365 for (sp
= §ions
, s
= sections
; s
; sp
= &s
->next
, s
= s
->next
)
366 if ((s
->flags
& START_DEFINED
) && (g
->start
< s
->start
))
368 /* Find the end of the group (gs). */
369 for (gs
= g
->next
, gsp
= &g
->next
;
370 gs
&& !(gs
->flags
& START_DEFINED
);
371 gsp
= &gs
->next
, gs
= gs
->next
) ;
372 /* Re-link the group before the target section. */
377 /* Step 3: Compute start addresses for all progbits sections. */
379 /* Make sure we have an origin and a start address for the first section. */
380 if (origin_defined
) {
381 if (sections
->flags
& START_DEFINED
) {
382 /* Make sure this section doesn't begin before the origin. */
383 if (sections
->start
< origin
)
384 nasm_fatal("section %s begins"
385 " before program origin", sections
->name
);
386 } else if (sections
->flags
& ALIGN_DEFINED
) {
387 sections
->start
= ALIGN(origin
, sections
->align
);
389 sections
->start
= origin
;
392 if (!(sections
->flags
& START_DEFINED
))
394 origin
= sections
->start
;
396 sections
->flags
|= START_DEFINED
;
398 /* Make sure each section has an explicit start address. If it
399 * doesn't, then compute one based its alignment and the end of
400 * the previous section. */
401 for (pend
= sections
->start
, g
= s
= sections
; g
; g
= g
->next
) { /* Find the next section that could cause an overlap situation
402 * (has a defined start address, and is not zero length). */
405 s
&& ((s
->length
== 0) || !(s
->flags
& START_DEFINED
));
407 /* Compute the start address of this section, if necessary. */
408 if (!(g
->flags
& START_DEFINED
)) { /* Default to an alignment of 4 if unspecified. */
409 if (!(g
->flags
& ALIGN_DEFINED
)) {
411 g
->flags
|= ALIGN_DEFINED
;
413 /* Set the section start address. */
414 g
->start
= ALIGN(pend
, g
->align
);
415 g
->flags
|= START_DEFINED
;
417 /* Ugly special case for progbits sections' virtual attributes:
418 * If there is a defined valign, but no vstart and no vfollows, then
419 * we valign after the previous progbits section. This case doesn't
420 * really make much sense for progbits sections with a defined start
421 * address, but it is possible and we must do *something*.
422 * Not-so-ugly special case:
423 * If a progbits section has no virtual attributes, we set the
424 * vstart equal to the start address. */
425 if (!(g
->flags
& (VSTART_DEFINED
| VFOLLOWS_DEFINED
))) {
426 if (g
->flags
& VALIGN_DEFINED
)
427 g
->vstart
= ALIGN(pend
, g
->valign
);
429 g
->vstart
= g
->start
;
430 g
->flags
|= VSTART_DEFINED
;
432 /* Ignore zero-length sections. */
435 /* Compute the span of this section. */
436 pend
= g
->start
+ g
->length
;
437 /* Check for section overlap. */
439 if (s
->start
< origin
)
440 nasm_fatal("section %s beings before program origin",
442 if (g
->start
> s
->start
)
443 nasm_fatal("sections %s ~ %s and %s overlap!",
444 gs
->name
, g
->name
, s
->name
);
446 nasm_fatal("sections %s and %s overlap!",
449 /* Remember this section as the latest >0 length section. */
453 /* Step 4: Compute vstart addresses for all sections. */
455 /* Attach the nobits sections to the end of the progbits sections. */
456 for (s
= sections
; s
->next
; s
= s
->next
) ;
460 * Scan for sections that don't have a vstart address. If we find
461 * one we'll attempt to compute its vstart. If we can't compute
462 * the vstart, we leave it alone and come back to it in a
463 * subsequent scan. We continue scanning and re-scanning until
464 * we've gone one full cycle without computing any vstarts.
466 do { /* Do one full scan of the sections list. */
467 for (h
= 0, g
= sections
; g
; g
= g
->next
) {
468 if (g
->flags
& VSTART_DEFINED
)
470 /* Find the section that this one virtually follows. */
471 if (g
->flags
& VFOLLOWS_DEFINED
) {
472 for (s
= sections
; s
&& strcmp(g
->vfollows
, s
->name
);
475 nasm_fatal("section %s vfollows unknown section (%s)",
476 g
->name
, g
->vfollows
);
477 } else if (g
->prev
!= NULL
)
478 for (s
= sections
; s
&& (s
!= g
->prev
); s
= s
->next
) ;
479 /* The .bss section is the only one with prev = NULL.
480 In this case we implicitly follow the last progbits
485 /* If the section we're following has a vstart, we can proceed. */
486 if (s
->flags
& VSTART_DEFINED
) { /* Default to virtual alignment of four. */
487 if (!(g
->flags
& VALIGN_DEFINED
)) {
489 g
->flags
|= VALIGN_DEFINED
;
491 /* Compute the vstart address. */
492 g
->vstart
= ALIGN(s
->vstart
+ s
->length
, g
->valign
);
493 g
->flags
|= VSTART_DEFINED
;
495 /* Start and vstart mean the same thing for nobits sections. */
496 if (g
->flags
& TYPE_NOBITS
)
497 g
->start
= g
->vstart
;
502 /* Now check for any circular vfollows references, which will manifest
503 * themselves as sections without a defined vstart. */
504 for (h
= 0, s
= sections
; s
; s
= s
->next
) {
505 if (!(s
->flags
& VSTART_DEFINED
)) { /* Non-fatal errors after assembly has completed are generally a
506 * no-no, but we'll throw a fatal one eventually so it's ok. */
507 nasm_nonfatal("cannot compute vstart for section %s", s
->name
);
512 nasm_fatal("circular vfollows path detected");
514 if (debug_level(1)) {
515 nasm_debug("bin_cleanup: Confirm final section order for output file:\n");
516 for (h
= 0, s
= sections
; s
&& (s
->flags
& TYPE_PROGBITS
);
518 nasm_debug("%i. %s\n", h
, s
->name
);
521 /* Step 5: Apply relocations. */
523 /* Prepare the sections for relocating. */
524 list_for_each(s
, sections
)
525 saa_rewind(s
->contents
);
526 /* Apply relocations. */
527 list_for_each(r
, relocs
) {
528 uint8_t *p
, mydata
[8];
532 nasm_assert(r
->bytes
<= 8);
534 memset(mydata
, 0, sizeof(mydata
));
536 saa_fread(r
->target
->contents
, r
->posn
, mydata
, r
->bytes
);
539 for (b
= r
->bytes
- 1; b
>= 0; b
--)
540 l
= (l
<< 8) + mydata
[b
];
542 s
= find_section_by_index(r
->secref
);
544 if (r
->secref
== s
->start_index
)
549 s
= find_section_by_index(r
->secrel
);
551 if (r
->secrel
== s
->start_index
)
557 WRITEADDR(p
, l
, r
->bytes
);
558 saa_fwrite(r
->target
->contents
, r
->posn
, mydata
, r
->bytes
);
561 /* Step 6: Write the section data to the output file. */
564 /* Step 7: Generate the map file. */
567 static const char not_defined
[] = "not defined";
569 /* Display input and output file names. */
570 fprintf(rf
, "\n- NASM Map file ");
573 fprintf(rf
, "\n\nSource file: %s\nOutput file: %s\n\n",
576 if (map_control
& MAP_ORIGIN
) { /* Display program origin. */
577 fprintf(rf
, "-- Program origin ");
580 fprintf(rf
, "\n\n%08"PRIX64
"\n\n", origin
);
582 /* Display sections summary. */
583 if (map_control
& MAP_SUMMARY
) {
584 fprintf(rf
, "-- Sections (summary) ");
587 fprintf(rf
, "\n\nVstart Start Stop "
588 "Length Class Name\n");
589 list_for_each(s
, sections
) {
590 fprintf(rf
, "%16"PRIX64
" %16"PRIX64
" %16"PRIX64
" %08"PRIX64
" ",
591 s
->vstart
, s
->start
, s
->start
+ s
->length
,
593 if (s
->flags
& TYPE_PROGBITS
)
594 fprintf(rf
, "progbits ");
596 fprintf(rf
, "nobits ");
597 fprintf(rf
, "%s\n", s
->name
);
601 /* Display detailed section information. */
602 if (map_control
& MAP_SECTIONS
) {
603 fprintf(rf
, "-- Sections (detailed) ");
607 list_for_each(s
, sections
) {
608 fprintf(rf
, "---- Section %s ", s
->name
);
609 if (strlen(s
->name
) < 65)
610 for (h
= 65 - strlen(s
->name
); h
; h
--)
612 fprintf(rf
, "\n\nclass: ");
613 if (s
->flags
& TYPE_PROGBITS
)
614 fprintf(rf
, "progbits");
616 fprintf(rf
, "nobits");
617 fprintf(rf
, "\nlength: %16"PRIX64
"\nstart: %16"PRIX64
""
618 "\nalign: ", s
->length
, s
->start
);
619 if (s
->flags
& ALIGN_DEFINED
)
620 fprintf(rf
, "%16"PRIX64
"", s
->align
);
622 fputs(not_defined
, rf
);
623 fprintf(rf
, "\nfollows: ");
624 if (s
->flags
& FOLLOWS_DEFINED
)
625 fprintf(rf
, "%s", s
->follows
);
627 fputs(not_defined
, rf
);
628 fprintf(rf
, "\nvstart: %16"PRIX64
"\nvalign: ", s
->vstart
);
629 if (s
->flags
& VALIGN_DEFINED
)
630 fprintf(rf
, "%16"PRIX64
"", s
->valign
);
632 fputs(not_defined
, rf
);
633 fprintf(rf
, "\nvfollows: ");
634 if (s
->flags
& VFOLLOWS_DEFINED
)
635 fprintf(rf
, "%s", s
->vfollows
);
637 fputs(not_defined
, rf
);
641 /* Display symbols information. */
642 if (map_control
& MAP_SYMBOLS
) {
645 enum label_type found_label
;
647 fprintf(rf
, "-- Symbols ");
652 fprintf(rf
, "---- No Section ");
655 fprintf(rf
, "\n\nValue Name\n");
656 list_for_each(l
, no_seg_labels
) {
657 found_label
= lookup_label(l
->name
, &segment
, &offset
);
658 nasm_assert(found_label
!= LBL_none
);
659 fprintf(rf
, "%08"PRIX64
" %s\n", offset
, l
->name
);
663 list_for_each(s
, sections
) {
665 fprintf(rf
, "---- Section %s ", s
->name
);
666 for (h
= 65 - strlen(s
->name
); h
; h
--)
668 fprintf(rf
, "\n\nReal Virtual Name\n");
669 list_for_each(l
, s
->labels
) {
670 found_label
= lookup_label(l
->name
, &segment
, &offset
);
671 nasm_assert(found_label
!= LBL_none
);
672 fprintf(rf
, "%16"PRIX64
" %16"PRIX64
" %s\n",
673 s
->start
+ offset
, s
->vstart
+ offset
,
682 /* Close the report file. */
683 if (map_control
&& (rf
!= stdout
) && (rf
!= stderr
))
686 /* Step 8: Release all allocated memory. */
688 /* Free sections, label pointer structs, etc.. */
692 saa_free(s
->contents
);
694 if (s
->flags
& FOLLOWS_DEFINED
)
695 nasm_free(s
->follows
);
696 if (s
->flags
& VFOLLOWS_DEFINED
)
697 nasm_free(s
->vfollows
);
706 /* Free no-section labels. */
707 while (no_seg_labels
) {
709 no_seg_labels
= l
->next
;
713 /* Free relocation structures. */
721 static void bin_out(int32_t segto
, const void *data
,
722 enum out_type type
, uint64_t size
,
723 int32_t segment
, int32_t wrt
)
725 uint8_t *p
, mydata
[8];
729 wrt
= NO_SEG
; /* continue to do _something_ */
730 nasm_nonfatal("WRT not supported by binary output format");
733 /* Find the segment we are targeting. */
734 s
= find_section_by_index(segto
);
736 nasm_panic("code directed to nonexistent segment?");
738 /* "Smart" section-type adaptation code. */
739 if (!(s
->flags
& TYPE_DEFINED
)) {
740 if (type
== OUT_RESERVE
)
741 s
->flags
|= TYPE_DEFINED
| TYPE_NOBITS
;
743 s
->flags
|= TYPE_DEFINED
| TYPE_PROGBITS
;
746 if ((s
->flags
& TYPE_NOBITS
) && (type
!= OUT_RESERVE
))
747 nasm_warn(WARN_OTHER
, "attempt to initialize memory in a"
748 " nobits section: ignored");
753 int asize
= abs((int)size
);
755 if (segment
!= NO_SEG
&& !find_section_by_index(segment
)) {
757 nasm_nonfatal("binary output format does not support"
758 " segment base references");
760 nasm_nonfatal("binary output format does not support"
761 " external references");
764 if (s
->flags
& TYPE_PROGBITS
) {
765 if (segment
!= NO_SEG
)
766 add_reloc(s
, asize
, segment
, -1L);
768 WRITEADDR(p
, *(int64_t *)data
, asize
);
769 saa_wbytes(s
->contents
, mydata
, asize
);
773 * Reassign size with sign dropped, we will need it
774 * for section length calculation.
781 if (s
->flags
& TYPE_PROGBITS
)
782 saa_wbytes(s
->contents
, data
, size
);
786 if (s
->flags
& TYPE_PROGBITS
) {
787 nasm_warn(WARN_ZEROING
, "uninitialized space declared in"
788 " %s section: zeroing", s
->name
);
789 saa_wbytes(s
->contents
, NULL
, size
);
798 int64_t addr
= *(int64_t *)data
- size
;
799 size
= realsize(type
, size
);
800 if (segment
!= NO_SEG
&& !find_section_by_index(segment
)) {
802 nasm_nonfatal("binary output format does not support"
803 " segment base references");
805 nasm_nonfatal("binary output format does not support"
806 " external references");
809 if (s
->flags
& TYPE_PROGBITS
) {
810 add_reloc(s
, size
, segment
, segto
);
812 WRITEADDR(p
, addr
- s
->length
, size
);
813 saa_wbytes(s
->contents
, mydata
, size
);
819 nasm_nonfatal("unsupported relocation type %d\n", type
);
826 static void bin_deflabel(char *name
, int32_t segment
, int64_t offset
,
827 int is_global
, char *special
)
829 (void)segment
; /* Don't warn that this parameter is unused */
830 (void)offset
; /* Don't warn that this parameter is unused */
833 nasm_nonfatal("binary format does not support any"
834 " special symbol types");
835 else if (name
[0] == '.' && name
[1] == '.' && name
[2] != '@')
836 nasm_nonfatal("unrecognised special symbol `%s'", name
);
837 else if (is_global
== 2)
838 nasm_nonfatal("binary output format does not support common"
842 struct bin_label
***ltp
;
844 /* Remember label definition so we can look it up later when
845 * creating the map file. */
846 s
= find_section_by_index(segment
);
848 ltp
= &(s
->labels_end
);
851 (**ltp
) = nasm_malloc(sizeof(struct bin_label
));
852 (**ltp
)->name
= name
;
853 (**ltp
)->next
= NULL
;
854 *ltp
= &((**ltp
)->next
);
859 /* These constants and the following function are used
860 * by bin_secname() to parse attribute assignments. */
862 enum { ATTRIB_START
, ATTRIB_ALIGN
, ATTRIB_FOLLOWS
,
863 ATTRIB_VSTART
, ATTRIB_VALIGN
, ATTRIB_VFOLLOWS
,
864 ATTRIB_NOBITS
, ATTRIB_PROGBITS
867 static int bin_read_attribute(char **line
, int *attribute
,
871 int attrib_name_size
;
872 struct tokenval tokval
;
875 /* Skip whitespace. */
876 while (**line
&& nasm_isspace(**line
))
881 /* Figure out what attribute we're reading. */
882 if (!nasm_strnicmp(*line
, "align=", 6)) {
883 *attribute
= ATTRIB_ALIGN
;
884 attrib_name_size
= 6;
886 if (!nasm_strnicmp(*line
, "start=", 6)) {
887 *attribute
= ATTRIB_START
;
888 attrib_name_size
= 6;
889 } else if (!nasm_strnicmp(*line
, "follows=", 8)) {
890 *attribute
= ATTRIB_FOLLOWS
;
893 } else if (!nasm_strnicmp(*line
, "vstart=", 7)) {
894 *attribute
= ATTRIB_VSTART
;
895 attrib_name_size
= 7;
896 } else if (!nasm_strnicmp(*line
, "valign=", 7)) {
897 *attribute
= ATTRIB_VALIGN
;
898 attrib_name_size
= 7;
899 } else if (!nasm_strnicmp(*line
, "vfollows=", 9)) {
900 *attribute
= ATTRIB_VFOLLOWS
;
903 } else if (!nasm_strnicmp(*line
, "nobits", 6) &&
904 (nasm_isspace((*line
)[6]) || ((*line
)[6] == '\0'))) {
905 *attribute
= ATTRIB_NOBITS
;
908 } else if (!nasm_strnicmp(*line
, "progbits", 8) &&
909 (nasm_isspace((*line
)[8]) || ((*line
)[8] == '\0'))) {
910 *attribute
= ATTRIB_PROGBITS
;
917 /* Find the end of the expression. */
918 if ((*line
)[attrib_name_size
] != '(') {
919 /* Single term (no parenthesis). */
920 exp
= *line
+= attrib_name_size
;
921 while (**line
&& !nasm_isspace(**line
))
931 /* Full expression (delimited by parenthesis) */
932 exp
= *line
+= attrib_name_size
+ 1;
934 (*line
) += strcspn(*line
, "()'\"");
945 if ((**line
== '"') || (**line
== '\'')) {
953 nasm_nonfatal("invalid syntax in `section' directive");
959 nasm_nonfatal("expecting `)'");
963 *(*line
- 1) = '\0'; /* Terminate the expression. */
966 /* Check for no value given. */
968 nasm_warn(WARN_OTHER
, "No value given to attribute in"
969 " `section' directive");
973 /* Read and evaluate the expression. */
976 tokval
.t_type
= TOKEN_INVALID
;
977 e
= evaluate(stdscan
, NULL
, &tokval
, NULL
, 1, NULL
);
979 if (!is_really_simple(e
)) {
980 nasm_nonfatal("section attribute value must be"
981 " a critical expression");
985 nasm_nonfatal("Invalid attribute value"
986 " specified in `section' directive.");
989 *value
= (uint64_t)reloc_value(e
);
993 static void bin_sectalign(int32_t seg
, unsigned int value
)
995 struct Section
*s
= find_section_by_index(seg
);
997 if (!s
|| !is_power2(value
))
1000 if (value
> s
->align
)
1003 if (!(s
->flags
& ALIGN_DEFINED
))
1004 s
->flags
|= ALIGN_DEFINED
;
1007 static void bin_assign_attributes(struct Section
*sec
, char *astring
)
1009 int attribute
, check
;
1013 while (1) { /* Get the next attribute. */
1014 check
= bin_read_attribute(&astring
, &attribute
, &value
);
1015 /* Skip bad attribute. */
1018 /* Unknown section attribute, so skip it and warn the user. */
1021 break; /* End of line. */
1024 while (*astring
&& !nasm_isspace(*astring
))
1030 nasm_warn(WARN_OTHER
, "ignoring unknown section attribute: \"%s\"", p
);
1035 switch (attribute
) { /* Handle nobits attribute. */
1037 if ((sec
->flags
& TYPE_DEFINED
)
1038 && (sec
->flags
& TYPE_PROGBITS
))
1039 nasm_nonfatal("attempt to change section type"
1040 " from progbits to nobits");
1042 sec
->flags
|= TYPE_DEFINED
| TYPE_NOBITS
;
1045 /* Handle progbits attribute. */
1046 case ATTRIB_PROGBITS
:
1047 if ((sec
->flags
& TYPE_DEFINED
) && (sec
->flags
& TYPE_NOBITS
))
1048 nasm_nonfatal("attempt to change section type"
1049 " from nobits to progbits");
1051 sec
->flags
|= TYPE_DEFINED
| TYPE_PROGBITS
;
1054 /* Handle align attribute. */
1056 if (!value
|| ((value
- 1) & value
)) {
1057 nasm_nonfatal("argument to `align' is not a power of two");
1060 * Alignment is already satisfied if
1061 * the previous align value is greater
1063 if ((sec
->flags
& ALIGN_DEFINED
) && (value
< sec
->align
))
1066 /* Don't allow a conflicting align value. */
1067 if ((sec
->flags
& START_DEFINED
) && (sec
->start
& (value
- 1))) {
1068 nasm_nonfatal("`align' value conflicts with section start address");
1071 sec
->flags
|= ALIGN_DEFINED
;
1076 /* Handle valign attribute. */
1078 if (!value
|| ((value
- 1) & value
))
1079 nasm_nonfatal("argument to `valign' is not a power of two");
1080 else { /* Alignment is already satisfied if the previous
1081 * align value is greater. */
1082 if ((sec
->flags
& VALIGN_DEFINED
) && (value
< sec
->valign
))
1083 value
= sec
->valign
;
1085 /* Don't allow a conflicting valign value. */
1086 if ((sec
->flags
& VSTART_DEFINED
)
1087 && (sec
->vstart
& (value
- 1)))
1088 nasm_nonfatal("`valign' value conflicts with `vstart' address");
1090 sec
->valign
= value
;
1091 sec
->flags
|= VALIGN_DEFINED
;
1096 /* Handle start attribute. */
1098 if (sec
->flags
& FOLLOWS_DEFINED
)
1099 nasm_nonfatal("cannot combine `start' and `follows'"
1100 " section attributes");
1101 else if ((sec
->flags
& START_DEFINED
) && (value
!= sec
->start
))
1102 nasm_nonfatal("section start address redefined");
1105 sec
->flags
|= START_DEFINED
;
1106 if (sec
->flags
& ALIGN_DEFINED
) {
1107 if (sec
->start
& (sec
->align
- 1))
1108 nasm_nonfatal("`start' address conflicts"
1109 " with section alignment");
1110 sec
->flags
^= ALIGN_DEFINED
;
1115 /* Handle vstart attribute. */
1117 if (sec
->flags
& VFOLLOWS_DEFINED
)
1118 nasm_nonfatal("cannot combine `vstart' and `vfollows'"
1119 " section attributes");
1120 else if ((sec
->flags
& VSTART_DEFINED
)
1121 && (value
!= sec
->vstart
))
1122 nasm_nonfatal("section virtual start address"
1123 " (vstart) redefined");
1125 sec
->vstart
= value
;
1126 sec
->flags
|= VSTART_DEFINED
;
1127 if (sec
->flags
& VALIGN_DEFINED
) {
1128 if (sec
->vstart
& (sec
->valign
- 1))
1129 nasm_nonfatal("`vstart' address conflicts"
1130 " with `valign' value");
1131 sec
->flags
^= VALIGN_DEFINED
;
1136 /* Handle follows attribute. */
1137 case ATTRIB_FOLLOWS
:
1139 astring
+= strcspn(astring
, " \t");
1141 nasm_nonfatal("expecting section name for `follows'"
1144 *(astring
++) = '\0';
1145 if (sec
->flags
& START_DEFINED
)
1146 nasm_nonfatal("cannot combine `start' and `follows'"
1147 " section attributes");
1148 sec
->follows
= nasm_strdup(p
);
1149 sec
->flags
|= FOLLOWS_DEFINED
;
1153 /* Handle vfollows attribute. */
1154 case ATTRIB_VFOLLOWS
:
1155 if (sec
->flags
& VSTART_DEFINED
)
1156 nasm_nonfatal("cannot combine `vstart' and `vfollows'"
1157 " section attributes");
1160 astring
+= strcspn(astring
, " \t");
1162 nasm_nonfatal("expecting section name for `vfollows'"
1165 *(astring
++) = '\0';
1166 sec
->vfollows
= nasm_strdup(p
);
1167 sec
->flags
|= VFOLLOWS_DEFINED
;
1175 static void bin_define_section_labels(void)
1177 static int labels_defined
= 0;
1178 struct Section
*sec
;
1184 list_for_each(sec
, sections
) {
1185 base_len
= strlen(sec
->name
) + 8;
1186 label_name
= nasm_malloc(base_len
+ 8);
1187 strcpy(label_name
, "section.");
1188 strcpy(label_name
+ 8, sec
->name
);
1190 /* section.<name>.start */
1191 strcpy(label_name
+ base_len
, ".start");
1192 define_label(label_name
, sec
->start_index
, 0L, false);
1194 /* section.<name>.vstart */
1195 strcpy(label_name
+ base_len
, ".vstart");
1196 define_label(label_name
, sec
->vstart_index
, 0L, false);
1198 nasm_free(label_name
);
1203 static int32_t bin_secname(char *name
, int *bits
)
1206 struct Section
*sec
;
1208 /* bin_secname is called with *name = NULL at the start of each
1209 * pass. Use this opportunity to establish the default section
1210 * (default is BITS-16 ".text" segment).
1213 /* Reset ORG and section attributes at the start of each pass. */
1215 list_for_each(sec
, sections
)
1216 sec
->flags
&= ~(START_DEFINED
| VSTART_DEFINED
|
1217 ALIGN_DEFINED
| VALIGN_DEFINED
);
1219 /* Define section start and vstart labels. */
1221 bin_define_section_labels();
1223 /* Establish the default (.text) section. */
1225 sec
= find_section_by_name(".text");
1226 sec
->flags
|= TYPE_DEFINED
| TYPE_PROGBITS
;
1227 return sec
->vstart_index
;
1230 /* Attempt to find the requested section. If it does not
1231 * exist, create it. */
1233 while (*p
&& !nasm_isspace(*p
))
1237 sec
= find_section_by_name(name
);
1239 sec
= create_section(name
);
1240 if (!strcmp(name
, ".data"))
1241 sec
->flags
|= TYPE_DEFINED
| TYPE_PROGBITS
;
1242 else if (!strcmp(name
, ".bss")) {
1243 sec
->flags
|= TYPE_DEFINED
| TYPE_NOBITS
;
1248 /* Handle attribute assignments. */
1250 bin_assign_attributes(sec
, p
);
1252 #ifndef ABIN_SMART_ADAPT
1253 /* The following line disables smart adaptation of
1254 * PROGBITS/NOBITS section types (it forces sections to
1255 * default to PROGBITS). */
1256 if (!pass_first() && !(sec
->flags
& TYPE_DEFINED
))
1257 sec
->flags
|= TYPE_DEFINED
| TYPE_PROGBITS
;
1260 return sec
->vstart_index
;
1263 static enum directive_result
1264 bin_directive(enum directive directive
, char *args
)
1266 switch (directive
) {
1269 struct tokenval tokval
;
1275 tokval
.t_type
= TOKEN_INVALID
;
1276 e
= evaluate(stdscan
, NULL
, &tokval
, NULL
, 1, NULL
);
1278 if (!is_really_simple(e
))
1279 nasm_nonfatal("org value must be a critical"
1282 value
= reloc_value(e
);
1283 /* Check for ORG redefinition. */
1284 if (origin_defined
&& (value
!= origin
))
1285 nasm_nonfatal("program origin redefined");
1292 nasm_nonfatal("No or invalid offset specified"
1293 " in ORG directive.");
1298 /* The 'map' directive allows the user to generate section
1299 * and symbol information to stdout, stderr, or to a file. */
1304 args
+= strspn(args
, " \t");
1307 args
+= strcspn(args
, " \t");
1310 if (!nasm_stricmp(p
, "all"))
1312 MAP_ORIGIN
| MAP_SUMMARY
| MAP_SECTIONS
| MAP_SYMBOLS
;
1313 else if (!nasm_stricmp(p
, "brief"))
1314 map_control
|= MAP_ORIGIN
| MAP_SUMMARY
;
1315 else if (!nasm_stricmp(p
, "sections"))
1316 map_control
|= MAP_ORIGIN
| MAP_SUMMARY
| MAP_SECTIONS
;
1317 else if (!nasm_stricmp(p
, "segments"))
1318 map_control
|= MAP_ORIGIN
| MAP_SUMMARY
| MAP_SECTIONS
;
1319 else if (!nasm_stricmp(p
, "symbols"))
1320 map_control
|= MAP_SYMBOLS
;
1322 if (!nasm_stricmp(p
, "stdout"))
1324 else if (!nasm_stricmp(p
, "stderr"))
1326 else { /* Must be a filename. */
1327 rf
= nasm_open_write(p
, NF_TEXT
);
1329 nasm_warn(WARN_OTHER
|ERR_PASS1
, "unable to open map file `%s'", p
);
1335 nasm_warn(WARN_OTHER
|ERR_PASS1
, "map file already specified");
1337 if (map_control
== 0)
1338 map_control
|= MAP_ORIGIN
| MAP_SUMMARY
;
1344 return DIRR_UNKNOWN
;
1348 const struct ofmt of_bin
, of_ith
, of_srec
;
1349 static void binfmt_init(void);
1350 static void do_output_bin(void);
1351 static void do_output_ith(void);
1352 static void do_output_srec(void);
1354 static void bin_init(void)
1356 do_output
= do_output_bin
;
1360 static void ith_init(void)
1362 do_output
= do_output_ith
;
1366 static void srec_init(void)
1368 do_output
= do_output_srec
;
1372 static void binfmt_init(void)
1375 reloctail
= &relocs
;
1377 no_seg_labels
= NULL
;
1378 nsl_tail
= &no_seg_labels
;
1380 /* Create default section (.text). */
1381 sections
= last_section
= nasm_zalloc(sizeof(struct Section
));
1382 last_section
->name
= nasm_strdup(".text");
1383 last_section
->contents
= saa_init(1L);
1384 last_section
->flags
= TYPE_DEFINED
| TYPE_PROGBITS
;
1385 last_section
->labels_end
= &(last_section
->labels
);
1386 last_section
->start_index
= seg_alloc();
1387 last_section
->vstart_index
= seg_alloc();
1390 /* Generate binary file output */
1391 static void do_output_bin(void)
1394 uint64_t addr
= origin
;
1396 /* Write the progbits sections to the output file. */
1397 list_for_each(s
, sections
) {
1398 /* Skip non-progbits sections */
1399 if (!(s
->flags
& TYPE_PROGBITS
))
1401 /* Skip zero-length sections */
1405 /* Pad the space between sections. */
1406 nasm_assert(addr
<= s
->start
);
1407 fwritezero(s
->start
- addr
, ofile
);
1409 /* Write the section to the output file. */
1410 saa_fpwrite(s
->contents
, ofile
);
1412 /* Keep track of the current file position */
1413 addr
= s
->start
+ s
->length
;
1417 /* Generate Intel hex file output */
1418 static void write_ith_record(unsigned int len
, uint16_t addr
,
1419 uint8_t type
, void *data
)
1421 char buf
[1+2+4+2+255*2+2+2];
1423 uint8_t csum
, *dptr
= data
;
1426 nasm_assert(len
<= 255);
1428 csum
= len
+ addr
+ (addr
>> 8) + type
;
1429 for (i
= 0; i
< len
; i
++)
1433 p
+= sprintf(p
, ":%02X%04X%02X", len
, addr
, type
);
1434 for (i
= 0; i
< len
; i
++)
1435 p
+= sprintf(p
, "%02X", dptr
[i
]);
1436 p
+= sprintf(p
, "%02X\n", csum
);
1438 nasm_write(buf
, p
-buf
, ofile
);
1441 static void do_output_ith(void)
1445 uint64_t addr
, hiaddr
, hilba
;
1449 /* Write the progbits sections to the output file. */
1451 list_for_each(s
, sections
) {
1452 /* Skip non-progbits sections */
1453 if (!(s
->flags
& TYPE_PROGBITS
))
1455 /* Skip zero-length sections */
1461 saa_rewind(s
->contents
);
1464 hiaddr
= addr
>> 16;
1465 if (hiaddr
!= hilba
) {
1466 buf
[0] = hiaddr
>> 8;
1468 write_ith_record(2, 0, 4, buf
);
1472 chunk
= 32 - (addr
& 31);
1476 saa_rnbytes(s
->contents
, buf
, chunk
);
1477 write_ith_record(chunk
, (uint16_t)addr
, 0, buf
);
1484 /* Write closing record */
1485 write_ith_record(0, 0, 1, NULL
);
1488 /* Generate Motorola S-records */
1489 static void write_srecord(unsigned int len
, unsigned int alen
,
1490 uint32_t addr
, uint8_t type
, void *data
)
1492 char buf
[2+2+8+255*2+2+2];
1494 uint8_t csum
, *dptr
= data
;
1497 nasm_assert(len
<= 255);
1513 csum
= (len
+alen
+1) + addr
+ (addr
>> 8) + (addr
>> 16) + (addr
>> 24);
1514 for (i
= 0; i
< len
; i
++)
1518 p
+= sprintf(p
, "S%c%02X%0*X", type
, len
+alen
+1, alen
*2, addr
);
1519 for (i
= 0; i
< len
; i
++)
1520 p
+= sprintf(p
, "%02X", dptr
[i
]);
1521 p
+= sprintf(p
, "%02X\n", csum
);
1523 nasm_write(buf
, p
-buf
, ofile
);
1526 static void do_output_srec(void)
1530 uint64_t addr
, maxaddr
;
1537 list_for_each(s
, sections
) {
1538 /* Skip non-progbits sections */
1539 if (!(s
->flags
& TYPE_PROGBITS
))
1541 /* Skip zero-length sections */
1545 addr
= s
->start
+ s
->length
- 1;
1550 if (maxaddr
<= 0xffff) {
1552 dtype
= '1'; /* S1 = 16-bit data */
1553 etype
= '9'; /* S9 = 16-bit end */
1554 } else if (maxaddr
<= 0xffffff) {
1556 dtype
= '2'; /* S2 = 24-bit data */
1557 etype
= '8'; /* S8 = 24-bit end */
1560 dtype
= '3'; /* S3 = 32-bit data */
1561 etype
= '7'; /* S7 = 32-bit end */
1564 /* Write head record */
1565 write_srecord(0, 2, 0, '0', NULL
);
1567 /* Write the progbits sections to the output file. */
1568 list_for_each(s
, sections
) {
1569 /* Skip non-progbits sections */
1570 if (!(s
->flags
& TYPE_PROGBITS
))
1572 /* Skip zero-length sections */
1578 saa_rewind(s
->contents
);
1581 chunk
= 32 - (addr
& 31);
1585 saa_rnbytes(s
->contents
, buf
, chunk
);
1586 write_srecord(chunk
, alen
, (uint32_t)addr
, dtype
, buf
);
1593 /* Write closing record */
1594 write_srecord(0, alen
, 0, etype
, NULL
);
1598 const struct ofmt of_bin
= {
1599 "Flat raw binary (MS-DOS, embedded, ...)",
1609 nasm_do_legacy_output
,
1618 NULL
/* pragma list */
1621 const struct ofmt of_ith
= {
1622 "Intel Hex encoded flat binary",
1624 ".ith", /* really should have been ".hex"... */
1632 nasm_do_legacy_output
,
1641 NULL
/* pragma list */
1644 const struct ofmt of_srec
= {
1645 "Motorola S-records encoded flat binary",
1655 nasm_do_legacy_output
,
1664 NULL
/* pragma list */
1667 #endif /* #ifdef OF_BIN */