1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2013 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
89 #include "output/outform.h"
90 #include "output/outlib.h"
94 static FILE *rf
= NULL
;
95 static void (*do_output
)(void);
97 /* Section flags keep track of which attributes the user has defined. */
98 #define START_DEFINED 0x001
99 #define ALIGN_DEFINED 0x002
100 #define FOLLOWS_DEFINED 0x004
101 #define VSTART_DEFINED 0x008
102 #define VALIGN_DEFINED 0x010
103 #define VFOLLOWS_DEFINED 0x020
104 #define TYPE_DEFINED 0x040
105 #define TYPE_PROGBITS 0x080
106 #define TYPE_NOBITS 0x100
108 /* This struct is used to keep track of symbols for map-file generation. */
109 static struct bin_label
{
111 struct bin_label
*next
;
112 } *no_seg_labels
, **nsl_tail
;
114 static struct Section
{
116 struct SAA
*contents
;
117 int64_t length
; /* section length in bytes */
119 /* Section attributes */
120 int flags
; /* see flag definitions above */
121 uint64_t align
; /* section alignment */
122 uint64_t valign
; /* notional section alignment */
123 uint64_t start
; /* section start address */
124 uint64_t vstart
; /* section virtual start address */
125 char *follows
; /* the section that this one will follow */
126 char *vfollows
; /* the section that this one will notionally follow */
127 int32_t start_index
; /* NASM section id for non-relocated version */
128 int32_t vstart_index
; /* the NASM section id */
130 struct bin_label
*labels
; /* linked-list of label handles for map output. */
131 struct bin_label
**labels_end
; /* Holds address of end of labels list. */
132 struct Section
*prev
; /* Points to previous section (implicit follows). */
133 struct Section
*next
; /* This links sections with a defined start address. */
135 /* The extended bin format allows for sections to have a "virtual"
136 * start address. This is accomplished by creating two sections:
137 * one beginning at the Load Memory Address and the other beginning
138 * at the Virtual Memory Address. The LMA section is only used to
139 * define the section.<section_name>.start label, but there isn't
140 * any other good way for us to handle that label.
143 } *sections
, *last_section
;
145 static struct Reloc
{
151 struct Section
*target
;
152 } *relocs
, **reloctail
;
154 static uint64_t origin
;
155 static int origin_defined
;
157 /* Stuff we need for map-file generation. */
159 #define MAP_SUMMARY 2
160 #define MAP_SECTIONS 4
161 #define MAP_SYMBOLS 8
162 static int map_control
= 0;
163 static char *infile
, *outfile
;
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_error(ERR_DEBUG
,
236 "bin_cleanup: Sections were initially referenced in this order:\n");
237 for (h
= 0, s
= sections
; s
; h
++, s
= s
->next
)
238 fprintf(stdout
, "%i. %s\n", h
, s
->name
);
241 /* Assembly has completed, so now we need to generate the output file.
242 * Step 1: Separate progbits and nobits sections into separate lists.
243 * Step 2: Sort the progbits sections into their output order.
244 * Step 3: Compute start addresses for all progbits sections.
245 * Step 4: Compute vstart addresses for all sections.
246 * Step 5: Apply relocations.
247 * Step 6: Write the sections' data to the output file.
248 * Step 7: Generate the map file.
249 * Step 8: Release all allocated memory.
252 /* To do: Smart section-type adaptation could leave some empty sections
253 * without a defined type (progbits/nobits). Won't fix now since this
254 * feature will be disabled. */
256 /* Step 1: Split progbits and nobits sections into separate lists. */
259 /* Move nobits sections into a separate list. Also pre-process nobits
260 * sections' attributes. */
261 for (sp
= §ions
->next
, s
= sections
->next
; s
; s
= *sp
) { /* Skip progbits sections. */
262 if (s
->flags
& TYPE_PROGBITS
) {
266 /* Do some special pre-processing on nobits sections' attributes. */
267 if (s
->flags
& (START_DEFINED
| ALIGN_DEFINED
| FOLLOWS_DEFINED
)) { /* Check for a mixture of real and virtual section attributes. */
268 if (s
->flags
& (VSTART_DEFINED
| VALIGN_DEFINED
|
270 nasm_fatal(ERR_NOFILE
,
271 "cannot mix real and virtual attributes"
272 " in nobits section (%s)", s
->name
);
273 /* Real and virtual attributes mean the same thing for nobits sections. */
274 if (s
->flags
& START_DEFINED
) {
275 s
->vstart
= s
->start
;
276 s
->flags
|= VSTART_DEFINED
;
278 if (s
->flags
& ALIGN_DEFINED
) {
279 s
->valign
= s
->align
;
280 s
->flags
|= VALIGN_DEFINED
;
282 if (s
->flags
& FOLLOWS_DEFINED
) {
283 s
->vfollows
= s
->follows
;
284 s
->flags
|= VFOLLOWS_DEFINED
;
285 s
->flags
&= ~FOLLOWS_DEFINED
;
288 /* Every section must have a start address. */
289 if (s
->flags
& VSTART_DEFINED
) {
290 s
->start
= s
->vstart
;
291 s
->flags
|= START_DEFINED
;
293 /* Move the section into the nobits list. */
300 /* Step 2: Sort the progbits sections into their output order. */
302 /* In Step 2 we move around sections in groups. A group
303 * begins with a section (group leader) that has a user-
304 * defined start address or follows section. The remainder
305 * of the group is made up of the sections that implicitly
306 * follow the group leader (i.e., they were defined after
307 * the group leader and were not given an explicit start
308 * address or follows section by the user). */
310 /* For anyone attempting to read this code:
311 * g (group) points to a group of sections, the first one of which has
312 * a user-defined start address or follows section.
313 * gp (g previous) holds the location of the pointer to g.
314 * gs (g scan) is a temp variable that we use to scan to the end of the group.
315 * gsp (gs previous) holds the location of the pointer to gs.
316 * nt (nobits tail) points to the nobits section-list tail.
319 /* Link all 'follows' groups to their proper position. To do
320 * this we need to know three things: the start of the group
321 * to relocate (g), the section it is following (s), and the
322 * end of the group we're relocating (gs). */
323 for (gp
= §ions
, g
= sections
; g
; g
= gs
) { /* Find the next follows group that is out of place (g). */
324 if (!(g
->flags
& FOLLOWS_DEFINED
)) {
326 if ((g
->next
->flags
& FOLLOWS_DEFINED
) &&
327 strcmp(g
->name
, g
->next
->follows
))
336 /* Find the section that this group follows (s). */
337 for (sp
= §ions
, s
= sections
;
338 s
&& strcmp(s
->name
, g
->follows
);
339 sp
= &s
->next
, s
= s
->next
) ;
341 nasm_fatal(ERR_NOFILE
, "section %s follows an invalid or"
342 " unknown section (%s)", g
->name
, g
->follows
);
343 if (s
->next
&& (s
->next
->flags
& FOLLOWS_DEFINED
) &&
344 !strcmp(s
->name
, s
->next
->follows
))
345 nasm_fatal(ERR_NOFILE
, "sections %s and %s can't both follow"
346 " section %s", g
->name
, s
->next
->name
, s
->name
);
347 /* Find the end of the current follows group (gs). */
348 for (gsp
= &g
->next
, gs
= g
->next
;
349 gs
&& (gs
!= s
) && !(gs
->flags
& START_DEFINED
);
350 gsp
= &gs
->next
, gs
= gs
->next
) {
351 if (gs
->next
&& (gs
->next
->flags
& FOLLOWS_DEFINED
) &&
352 strcmp(gs
->name
, gs
->next
->follows
)) {
358 /* Re-link the group after its follows section. */
364 /* Link all 'start' groups to their proper position. Once
365 * again we need to know g, s, and gs (see above). The main
366 * difference is we already know g since we sort by moving
367 * groups from the 'unsorted' list into a 'sorted' list (g
368 * will always be the first section in the unsorted list). */
369 for (g
= sections
, sections
= NULL
; g
; g
= gs
) { /* Find the section that we will insert this group before (s). */
370 for (sp
= §ions
, s
= sections
; s
; sp
= &s
->next
, s
= s
->next
)
371 if ((s
->flags
& START_DEFINED
) && (g
->start
< s
->start
))
373 /* Find the end of the group (gs). */
374 for (gs
= g
->next
, gsp
= &g
->next
;
375 gs
&& !(gs
->flags
& START_DEFINED
);
376 gsp
= &gs
->next
, gs
= gs
->next
) ;
377 /* Re-link the group before the target section. */
382 /* Step 3: Compute start addresses for all progbits sections. */
384 /* Make sure we have an origin and a start address for the first section. */
385 if (origin_defined
) {
386 if (sections
->flags
& START_DEFINED
) {
387 /* Make sure this section doesn't begin before the origin. */
388 if (sections
->start
< origin
)
389 nasm_fatal(ERR_NOFILE
, "section %s begins"
390 " before program origin", sections
->name
);
391 } else if (sections
->flags
& ALIGN_DEFINED
) {
392 sections
->start
= ALIGN(origin
, sections
->align
);
394 sections
->start
= origin
;
397 if (!(sections
->flags
& START_DEFINED
))
399 origin
= sections
->start
;
401 sections
->flags
|= START_DEFINED
;
403 /* Make sure each section has an explicit start address. If it
404 * doesn't, then compute one based its alignment and the end of
405 * the previous section. */
406 for (pend
= sections
->start
, g
= s
= sections
; g
; g
= g
->next
) { /* Find the next section that could cause an overlap situation
407 * (has a defined start address, and is not zero length). */
410 s
&& ((s
->length
== 0) || !(s
->flags
& START_DEFINED
));
412 /* Compute the start address of this section, if necessary. */
413 if (!(g
->flags
& START_DEFINED
)) { /* Default to an alignment of 4 if unspecified. */
414 if (!(g
->flags
& ALIGN_DEFINED
)) {
416 g
->flags
|= ALIGN_DEFINED
;
418 /* Set the section start address. */
419 g
->start
= ALIGN(pend
, g
->align
);
420 g
->flags
|= START_DEFINED
;
422 /* Ugly special case for progbits sections' virtual attributes:
423 * If there is a defined valign, but no vstart and no vfollows, then
424 * we valign after the previous progbits section. This case doesn't
425 * really make much sense for progbits sections with a defined start
426 * address, but it is possible and we must do *something*.
427 * Not-so-ugly special case:
428 * If a progbits section has no virtual attributes, we set the
429 * vstart equal to the start address. */
430 if (!(g
->flags
& (VSTART_DEFINED
| VFOLLOWS_DEFINED
))) {
431 if (g
->flags
& VALIGN_DEFINED
)
432 g
->vstart
= ALIGN(pend
, g
->valign
);
434 g
->vstart
= g
->start
;
435 g
->flags
|= VSTART_DEFINED
;
437 /* Ignore zero-length sections. */
440 /* Compute the span of this section. */
441 pend
= g
->start
+ g
->length
;
442 /* Check for section overlap. */
444 if (s
->start
< origin
)
445 nasm_fatal(ERR_NOFILE
, "section %s beings before program origin",
447 if (g
->start
> s
->start
)
448 nasm_fatal(ERR_NOFILE
, "sections %s ~ %s and %s overlap!",
449 gs
->name
, g
->name
, s
->name
);
451 nasm_fatal(ERR_NOFILE
, "sections %s and %s overlap!",
454 /* Remember this section as the latest >0 length section. */
458 /* Step 4: Compute vstart addresses for all sections. */
460 /* Attach the nobits sections to the end of the progbits sections. */
461 for (s
= sections
; s
->next
; s
= s
->next
) ;
465 * Scan for sections that don't have a vstart address. If we find
466 * one we'll attempt to compute its vstart. If we can't compute
467 * the vstart, we leave it alone and come back to it in a
468 * subsequent scan. We continue scanning and re-scanning until
469 * we've gone one full cycle without computing any vstarts.
471 do { /* Do one full scan of the sections list. */
472 for (h
= 0, g
= sections
; g
; g
= g
->next
) {
473 if (g
->flags
& VSTART_DEFINED
)
475 /* Find the section that this one virtually follows. */
476 if (g
->flags
& VFOLLOWS_DEFINED
) {
477 for (s
= sections
; s
&& strcmp(g
->vfollows
, s
->name
);
480 nasm_fatal(ERR_NOFILE
,
481 "section %s vfollows unknown section (%s)",
482 g
->name
, g
->vfollows
);
483 } else if (g
->prev
!= NULL
)
484 for (s
= sections
; s
&& (s
!= g
->prev
); s
= s
->next
) ;
485 /* The .bss section is the only one with prev = NULL.
486 In this case we implicitly follow the last progbits
491 /* If the section we're following has a vstart, we can proceed. */
492 if (s
->flags
& VSTART_DEFINED
) { /* Default to virtual alignment of four. */
493 if (!(g
->flags
& VALIGN_DEFINED
)) {
495 g
->flags
|= VALIGN_DEFINED
;
497 /* Compute the vstart address. */
498 g
->vstart
= ALIGN(s
->vstart
+ s
->length
, g
->valign
);
499 g
->flags
|= VSTART_DEFINED
;
501 /* Start and vstart mean the same thing for nobits sections. */
502 if (g
->flags
& TYPE_NOBITS
)
503 g
->start
= g
->vstart
;
508 /* Now check for any circular vfollows references, which will manifest
509 * themselves as sections without a defined vstart. */
510 for (h
= 0, s
= sections
; s
; s
= s
->next
) {
511 if (!(s
->flags
& VSTART_DEFINED
)) { /* Non-fatal errors after assembly has completed are generally a
512 * no-no, but we'll throw a fatal one eventually so it's ok. */
513 nasm_error(ERR_NONFATAL
, "cannot compute vstart for section %s",
519 nasm_fatal(ERR_NOFILE
, "circular vfollows path detected");
522 nasm_error(ERR_DEBUG
,
523 "bin_cleanup: Confirm final section order for output file:\n");
524 for (h
= 0, s
= sections
; s
&& (s
->flags
& TYPE_PROGBITS
);
526 fprintf(stdout
, "%i. %s\n", h
, s
->name
);
529 /* Step 5: Apply relocations. */
531 /* Prepare the sections for relocating. */
532 list_for_each(s
, sections
)
533 saa_rewind(s
->contents
);
534 /* Apply relocations. */
535 list_for_each(r
, relocs
) {
536 uint8_t *p
, mydata
[8];
540 nasm_assert(r
->bytes
<= 8);
542 memset(mydata
, 0, sizeof(mydata
));
544 saa_fread(r
->target
->contents
, r
->posn
, mydata
, r
->bytes
);
547 for (b
= r
->bytes
- 1; b
>= 0; b
--)
548 l
= (l
<< 8) + mydata
[b
];
550 s
= find_section_by_index(r
->secref
);
552 if (r
->secref
== s
->start_index
)
557 s
= find_section_by_index(r
->secrel
);
559 if (r
->secrel
== s
->start_index
)
565 WRITEADDR(p
, l
, r
->bytes
);
566 saa_fwrite(r
->target
->contents
, r
->posn
, mydata
, r
->bytes
);
569 /* Step 6: Write the section data to the output file. */
572 /* Step 7: Generate the map file. */
575 static const char not_defined
[] = "not defined";
577 /* Display input and output file names. */
578 fprintf(rf
, "\n- NASM Map file ");
581 fprintf(rf
, "\n\nSource file: %s\nOutput file: %s\n\n",
584 if (map_control
& MAP_ORIGIN
) { /* Display program origin. */
585 fprintf(rf
, "-- Program origin ");
588 fprintf(rf
, "\n\n%08"PRIX64
"\n\n", origin
);
590 /* Display sections summary. */
591 if (map_control
& MAP_SUMMARY
) {
592 fprintf(rf
, "-- Sections (summary) ");
595 fprintf(rf
, "\n\nVstart Start Stop "
596 "Length Class Name\n");
597 list_for_each(s
, sections
) {
598 fprintf(rf
, "%16"PRIX64
" %16"PRIX64
" %16"PRIX64
" %08"PRIX64
" ",
599 s
->vstart
, s
->start
, s
->start
+ s
->length
,
601 if (s
->flags
& TYPE_PROGBITS
)
602 fprintf(rf
, "progbits ");
604 fprintf(rf
, "nobits ");
605 fprintf(rf
, "%s\n", s
->name
);
609 /* Display detailed section information. */
610 if (map_control
& MAP_SECTIONS
) {
611 fprintf(rf
, "-- Sections (detailed) ");
615 list_for_each(s
, sections
) {
616 fprintf(rf
, "---- Section %s ", s
->name
);
617 for (h
= 65 - strlen(s
->name
); h
; h
--)
619 fprintf(rf
, "\n\nclass: ");
620 if (s
->flags
& TYPE_PROGBITS
)
621 fprintf(rf
, "progbits");
623 fprintf(rf
, "nobits");
624 fprintf(rf
, "\nlength: %16"PRIX64
"\nstart: %16"PRIX64
""
625 "\nalign: ", s
->length
, s
->start
);
626 if (s
->flags
& ALIGN_DEFINED
)
627 fprintf(rf
, "%16"PRIX64
"", s
->align
);
629 fputs(not_defined
, rf
);
630 fprintf(rf
, "\nfollows: ");
631 if (s
->flags
& FOLLOWS_DEFINED
)
632 fprintf(rf
, "%s", s
->follows
);
634 fputs(not_defined
, rf
);
635 fprintf(rf
, "\nvstart: %16"PRIX64
"\nvalign: ", s
->vstart
);
636 if (s
->flags
& VALIGN_DEFINED
)
637 fprintf(rf
, "%16"PRIX64
"", s
->valign
);
639 fputs(not_defined
, rf
);
640 fprintf(rf
, "\nvfollows: ");
641 if (s
->flags
& VFOLLOWS_DEFINED
)
642 fprintf(rf
, "%s", s
->vfollows
);
644 fputs(not_defined
, rf
);
648 /* Display symbols information. */
649 if (map_control
& MAP_SYMBOLS
) {
653 fprintf(rf
, "-- Symbols ");
658 fprintf(rf
, "---- No Section ");
661 fprintf(rf
, "\n\nValue Name\n");
662 list_for_each(l
, no_seg_labels
) {
663 lookup_label(l
->name
, &segment
, &offset
);
664 fprintf(rf
, "%08"PRIX64
" %s\n", offset
, l
->name
);
668 list_for_each(s
, sections
) {
670 fprintf(rf
, "---- Section %s ", s
->name
);
671 for (h
= 65 - strlen(s
->name
); h
; h
--)
673 fprintf(rf
, "\n\nReal Virtual Name\n");
674 list_for_each(l
, s
->labels
) {
675 lookup_label(l
->name
, &segment
, &offset
);
676 fprintf(rf
, "%16"PRIX64
" %16"PRIX64
" %s\n",
677 s
->start
+ offset
, s
->vstart
+ offset
,
686 /* Close the report file. */
687 if (map_control
&& (rf
!= stdout
) && (rf
!= stderr
))
690 /* Step 8: Release all allocated memory. */
692 /* Free sections, label pointer structs, etc.. */
696 saa_free(s
->contents
);
698 if (s
->flags
& FOLLOWS_DEFINED
)
699 nasm_free(s
->follows
);
700 if (s
->flags
& VFOLLOWS_DEFINED
)
701 nasm_free(s
->vfollows
);
710 /* Free no-section labels. */
711 while (no_seg_labels
) {
713 no_seg_labels
= l
->next
;
717 /* Free relocation structures. */
725 static void bin_out(int32_t segto
, const void *data
,
726 enum out_type type
, uint64_t size
,
727 int32_t segment
, int32_t wrt
)
729 uint8_t *p
, mydata
[8];
733 wrt
= NO_SEG
; /* continue to do _something_ */
734 nasm_error(ERR_NONFATAL
, "WRT not supported by binary output format");
737 /* Handle absolute-assembly (structure definitions). */
738 if (segto
== NO_SEG
) {
739 if (type
!= OUT_RESERVE
)
740 nasm_error(ERR_NONFATAL
, "attempt to assemble code in"
741 " [ABSOLUTE] space");
745 /* Find the segment we are targeting. */
746 s
= find_section_by_index(segto
);
748 nasm_panic(0, "code directed to nonexistent segment?");
750 /* "Smart" section-type adaptation code. */
751 if (!(s
->flags
& TYPE_DEFINED
)) {
752 if (type
== OUT_RESERVE
)
753 s
->flags
|= TYPE_DEFINED
| TYPE_NOBITS
;
755 s
->flags
|= TYPE_DEFINED
| TYPE_PROGBITS
;
758 if ((s
->flags
& TYPE_NOBITS
) && (type
!= OUT_RESERVE
))
759 nasm_error(ERR_WARNING
, "attempt to initialize memory in a"
760 " nobits section: ignored");
765 int asize
= abs((int)size
);
767 if (segment
!= NO_SEG
&& !find_section_by_index(segment
)) {
769 nasm_error(ERR_NONFATAL
, "binary output format does not support"
770 " segment base references");
772 nasm_error(ERR_NONFATAL
, "binary output format does not support"
773 " external references");
776 if (s
->flags
& TYPE_PROGBITS
) {
777 if (segment
!= NO_SEG
)
778 add_reloc(s
, asize
, segment
, -1L);
780 WRITEADDR(p
, *(int64_t *)data
, asize
);
781 saa_wbytes(s
->contents
, mydata
, asize
);
785 * Reassign size with sign dropped, we will need it
786 * for section length calculation.
793 if (s
->flags
& TYPE_PROGBITS
)
794 saa_wbytes(s
->contents
, data
, size
);
798 if (s
->flags
& TYPE_PROGBITS
) {
799 nasm_error(ERR_WARNING
, "uninitialized space declared in"
800 " %s section: zeroing", s
->name
);
801 saa_wbytes(s
->contents
, NULL
, size
);
810 int64_t addr
= *(int64_t *)data
- size
;
811 size
= realsize(type
, size
);
812 if (segment
!= NO_SEG
&& !find_section_by_index(segment
)) {
814 nasm_error(ERR_NONFATAL
, "binary output format does not support"
815 " segment base references");
817 nasm_error(ERR_NONFATAL
, "binary output format does not support"
818 " external references");
821 if (s
->flags
& TYPE_PROGBITS
) {
822 add_reloc(s
, size
, segment
, segto
);
824 WRITEADDR(p
, addr
- s
->length
, size
);
825 saa_wbytes(s
->contents
, mydata
, size
);
831 nasm_error(ERR_NONFATAL
, "unsupported relocation type %d\n", type
);
838 static void bin_deflabel(char *name
, int32_t segment
, int64_t offset
,
839 int is_global
, char *special
)
841 (void)segment
; /* Don't warn that this parameter is unused */
842 (void)offset
; /* Don't warn that this parameter is unused */
845 nasm_error(ERR_NONFATAL
, "binary format does not support any"
846 " special symbol types");
847 else if (name
[0] == '.' && name
[1] == '.' && name
[2] != '@')
848 nasm_error(ERR_NONFATAL
, "unrecognised special symbol `%s'", name
);
849 else if (is_global
== 2)
850 nasm_error(ERR_NONFATAL
, "binary output format does not support common"
854 struct bin_label
***ltp
;
856 /* Remember label definition so we can look it up later when
857 * creating the map file. */
858 s
= find_section_by_index(segment
);
860 ltp
= &(s
->labels_end
);
863 (**ltp
) = nasm_malloc(sizeof(struct bin_label
));
864 (**ltp
)->name
= name
;
865 (**ltp
)->next
= NULL
;
866 *ltp
= &((**ltp
)->next
);
871 /* These constants and the following function are used
872 * by bin_secname() to parse attribute assignments. */
874 enum { ATTRIB_START
, ATTRIB_ALIGN
, ATTRIB_FOLLOWS
,
875 ATTRIB_VSTART
, ATTRIB_VALIGN
, ATTRIB_VFOLLOWS
,
876 ATTRIB_NOBITS
, ATTRIB_PROGBITS
879 static int bin_read_attribute(char **line
, int *attribute
,
883 int attrib_name_size
;
884 struct tokenval tokval
;
887 /* Skip whitespace. */
888 while (**line
&& nasm_isspace(**line
))
893 /* Figure out what attribute we're reading. */
894 if (!nasm_strnicmp(*line
, "align=", 6)) {
895 *attribute
= ATTRIB_ALIGN
;
896 attrib_name_size
= 6;
898 if (!nasm_strnicmp(*line
, "start=", 6)) {
899 *attribute
= ATTRIB_START
;
900 attrib_name_size
= 6;
901 } else if (!nasm_strnicmp(*line
, "follows=", 8)) {
902 *attribute
= ATTRIB_FOLLOWS
;
905 } else if (!nasm_strnicmp(*line
, "vstart=", 7)) {
906 *attribute
= ATTRIB_VSTART
;
907 attrib_name_size
= 7;
908 } else if (!nasm_strnicmp(*line
, "valign=", 7)) {
909 *attribute
= ATTRIB_VALIGN
;
910 attrib_name_size
= 7;
911 } else if (!nasm_strnicmp(*line
, "vfollows=", 9)) {
912 *attribute
= ATTRIB_VFOLLOWS
;
915 } else if (!nasm_strnicmp(*line
, "nobits", 6) &&
916 (nasm_isspace((*line
)[6]) || ((*line
)[6] == '\0'))) {
917 *attribute
= ATTRIB_NOBITS
;
920 } else if (!nasm_strnicmp(*line
, "progbits", 8) &&
921 (nasm_isspace((*line
)[8]) || ((*line
)[8] == '\0'))) {
922 *attribute
= ATTRIB_PROGBITS
;
929 /* Find the end of the expression. */
930 if ((*line
)[attrib_name_size
] != '(') {
931 /* Single term (no parenthesis). */
932 exp
= *line
+= attrib_name_size
;
933 while (**line
&& !nasm_isspace(**line
))
943 /* Full expression (delimited by parenthesis) */
944 exp
= *line
+= attrib_name_size
+ 1;
946 (*line
) += strcspn(*line
, "()'\"");
957 if ((**line
== '"') || (**line
== '\'')) {
965 nasm_error(ERR_NONFATAL
,
966 "invalid syntax in `section' directive");
972 nasm_error(ERR_NONFATAL
, "expecting `)'");
976 *(*line
- 1) = '\0'; /* Terminate the expression. */
979 /* Check for no value given. */
981 nasm_error(ERR_WARNING
, "No value given to attribute in"
982 " `section' directive");
986 /* Read and evaluate the expression. */
989 tokval
.t_type
= TOKEN_INVALID
;
990 e
= evaluate(stdscan
, NULL
, &tokval
, NULL
, 1, NULL
);
992 if (!is_really_simple(e
)) {
993 nasm_error(ERR_NONFATAL
, "section attribute value must be"
994 " a critical expression");
998 nasm_error(ERR_NONFATAL
, "Invalid attribute value"
999 " specified in `section' directive.");
1002 *value
= (uint64_t)reloc_value(e
);
1006 static void bin_sectalign(int32_t seg
, unsigned int value
)
1008 struct Section
*s
= find_section_by_index(seg
);
1010 if (!s
|| !is_power2(value
))
1013 if (value
> s
->align
)
1016 if (!(s
->flags
& ALIGN_DEFINED
))
1017 s
->flags
|= ALIGN_DEFINED
;
1020 static void bin_assign_attributes(struct Section
*sec
, char *astring
)
1022 int attribute
, check
;
1026 while (1) { /* Get the next attribute. */
1027 check
= bin_read_attribute(&astring
, &attribute
, &value
);
1028 /* Skip bad attribute. */
1031 /* Unknown section attribute, so skip it and warn the user. */
1034 break; /* End of line. */
1037 while (*astring
&& !nasm_isspace(*astring
))
1043 nasm_error(ERR_WARNING
, "ignoring unknown section attribute:"
1049 switch (attribute
) { /* Handle nobits attribute. */
1051 if ((sec
->flags
& TYPE_DEFINED
)
1052 && (sec
->flags
& TYPE_PROGBITS
))
1053 nasm_error(ERR_NONFATAL
,
1054 "attempt to change section type"
1055 " from progbits to nobits");
1057 sec
->flags
|= TYPE_DEFINED
| TYPE_NOBITS
;
1060 /* Handle progbits attribute. */
1061 case ATTRIB_PROGBITS
:
1062 if ((sec
->flags
& TYPE_DEFINED
) && (sec
->flags
& TYPE_NOBITS
))
1063 nasm_error(ERR_NONFATAL
, "attempt to change section type"
1064 " from nobits to progbits");
1066 sec
->flags
|= TYPE_DEFINED
| TYPE_PROGBITS
;
1069 /* Handle align attribute. */
1071 if (!value
|| ((value
- 1) & value
)) {
1072 nasm_error(ERR_NONFATAL
,
1073 "argument to `align' is not a power of two");
1076 * Alignment is already satisfied if
1077 * the previous align value is greater
1079 if ((sec
->flags
& ALIGN_DEFINED
) && (value
< sec
->align
))
1082 /* Don't allow a conflicting align value. */
1083 if ((sec
->flags
& START_DEFINED
) && (sec
->start
& (value
- 1))) {
1084 nasm_error(ERR_NONFATAL
,
1085 "`align' value conflicts with section start address");
1088 sec
->flags
|= ALIGN_DEFINED
;
1093 /* Handle valign attribute. */
1095 if (!value
|| ((value
- 1) & value
))
1096 nasm_error(ERR_NONFATAL
, "argument to `valign' is not a"
1098 else { /* Alignment is already satisfied if the previous
1099 * align value is greater. */
1100 if ((sec
->flags
& VALIGN_DEFINED
) && (value
< sec
->valign
))
1101 value
= sec
->valign
;
1103 /* Don't allow a conflicting valign value. */
1104 if ((sec
->flags
& VSTART_DEFINED
)
1105 && (sec
->vstart
& (value
- 1)))
1106 nasm_error(ERR_NONFATAL
,
1107 "`valign' value conflicts "
1108 "with `vstart' address");
1110 sec
->valign
= value
;
1111 sec
->flags
|= VALIGN_DEFINED
;
1116 /* Handle start attribute. */
1118 if (sec
->flags
& FOLLOWS_DEFINED
)
1119 nasm_error(ERR_NONFATAL
, "cannot combine `start' and `follows'"
1120 " section attributes");
1121 else if ((sec
->flags
& START_DEFINED
) && (value
!= sec
->start
))
1122 nasm_error(ERR_NONFATAL
, "section start address redefined");
1125 sec
->flags
|= START_DEFINED
;
1126 if (sec
->flags
& ALIGN_DEFINED
) {
1127 if (sec
->start
& (sec
->align
- 1))
1128 nasm_error(ERR_NONFATAL
, "`start' address conflicts"
1129 " with section alignment");
1130 sec
->flags
^= ALIGN_DEFINED
;
1135 /* Handle vstart attribute. */
1137 if (sec
->flags
& VFOLLOWS_DEFINED
)
1138 nasm_error(ERR_NONFATAL
,
1139 "cannot combine `vstart' and `vfollows'"
1140 " section attributes");
1141 else if ((sec
->flags
& VSTART_DEFINED
)
1142 && (value
!= sec
->vstart
))
1143 nasm_error(ERR_NONFATAL
,
1144 "section virtual start address"
1145 " (vstart) redefined");
1147 sec
->vstart
= value
;
1148 sec
->flags
|= VSTART_DEFINED
;
1149 if (sec
->flags
& VALIGN_DEFINED
) {
1150 if (sec
->vstart
& (sec
->valign
- 1))
1151 nasm_error(ERR_NONFATAL
, "`vstart' address conflicts"
1152 " with `valign' value");
1153 sec
->flags
^= VALIGN_DEFINED
;
1158 /* Handle follows attribute. */
1159 case ATTRIB_FOLLOWS
:
1161 astring
+= strcspn(astring
, " \t");
1163 nasm_error(ERR_NONFATAL
, "expecting section name for `follows'"
1166 *(astring
++) = '\0';
1167 if (sec
->flags
& START_DEFINED
)
1168 nasm_error(ERR_NONFATAL
,
1169 "cannot combine `start' and `follows'"
1170 " section attributes");
1171 sec
->follows
= nasm_strdup(p
);
1172 sec
->flags
|= FOLLOWS_DEFINED
;
1176 /* Handle vfollows attribute. */
1177 case ATTRIB_VFOLLOWS
:
1178 if (sec
->flags
& VSTART_DEFINED
)
1179 nasm_error(ERR_NONFATAL
,
1180 "cannot combine `vstart' and `vfollows'"
1181 " section attributes");
1184 astring
+= strcspn(astring
, " \t");
1186 nasm_error(ERR_NONFATAL
,
1187 "expecting section name for `vfollows'"
1190 *(astring
++) = '\0';
1191 sec
->vfollows
= nasm_strdup(p
);
1192 sec
->flags
|= VFOLLOWS_DEFINED
;
1200 static void bin_define_section_labels(void)
1202 static int labels_defined
= 0;
1203 struct Section
*sec
;
1209 list_for_each(sec
, sections
) {
1210 base_len
= strlen(sec
->name
) + 8;
1211 label_name
= nasm_malloc(base_len
+ 8);
1212 strcpy(label_name
, "section.");
1213 strcpy(label_name
+ 8, sec
->name
);
1215 /* section.<name>.start */
1216 strcpy(label_name
+ base_len
, ".start");
1217 define_label(label_name
, sec
->start_index
, 0L, NULL
, 0, 0);
1219 /* section.<name>.vstart */
1220 strcpy(label_name
+ base_len
, ".vstart");
1221 define_label(label_name
, sec
->vstart_index
, 0L, NULL
, 0, 0);
1223 nasm_free(label_name
);
1228 static int32_t bin_secname(char *name
, int pass
, int *bits
)
1231 struct Section
*sec
;
1233 /* bin_secname is called with *name = NULL at the start of each
1234 * pass. Use this opportunity to establish the default section
1235 * (default is BITS-16 ".text" segment).
1237 if (!name
) { /* Reset ORG and section attributes at the start of each pass. */
1239 list_for_each(sec
, sections
)
1240 sec
->flags
&= ~(START_DEFINED
| VSTART_DEFINED
|
1241 ALIGN_DEFINED
| VALIGN_DEFINED
);
1243 /* Define section start and vstart labels. */
1245 bin_define_section_labels();
1247 /* Establish the default (.text) section. */
1249 sec
= find_section_by_name(".text");
1250 sec
->flags
|= TYPE_DEFINED
| TYPE_PROGBITS
;
1251 return sec
->vstart_index
;
1254 /* Attempt to find the requested section. If it does not
1255 * exist, create it. */
1257 while (*p
&& !nasm_isspace(*p
))
1261 sec
= find_section_by_name(name
);
1263 sec
= create_section(name
);
1264 if (!strcmp(name
, ".data"))
1265 sec
->flags
|= TYPE_DEFINED
| TYPE_PROGBITS
;
1266 else if (!strcmp(name
, ".bss")) {
1267 sec
->flags
|= TYPE_DEFINED
| TYPE_NOBITS
;
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 return sec
->vstart_index
;
1287 static int bin_directive(enum directives directive
, char *args
, int pass
)
1289 switch (directive
) {
1292 struct tokenval tokval
;
1298 tokval
.t_type
= TOKEN_INVALID
;
1299 e
= evaluate(stdscan
, NULL
, &tokval
, NULL
, 1, NULL
);
1301 if (!is_really_simple(e
))
1302 nasm_error(ERR_NONFATAL
, "org value must be a critical"
1305 value
= reloc_value(e
);
1306 /* Check for ORG redefinition. */
1307 if (origin_defined
&& (value
!= origin
))
1308 nasm_error(ERR_NONFATAL
, "program origin redefined");
1315 nasm_error(ERR_NONFATAL
, "No or invalid offset specified"
1316 " in ORG directive.");
1321 /* The 'map' directive allows the user to generate section
1322 * and symbol information to stdout, stderr, or to a file. */
1327 args
+= strspn(args
, " \t");
1330 args
+= strcspn(args
, " \t");
1333 if (!nasm_stricmp(p
, "all"))
1335 MAP_ORIGIN
| MAP_SUMMARY
| MAP_SECTIONS
| MAP_SYMBOLS
;
1336 else if (!nasm_stricmp(p
, "brief"))
1337 map_control
|= MAP_ORIGIN
| MAP_SUMMARY
;
1338 else if (!nasm_stricmp(p
, "sections"))
1339 map_control
|= MAP_ORIGIN
| MAP_SUMMARY
| MAP_SECTIONS
;
1340 else if (!nasm_stricmp(p
, "segments"))
1341 map_control
|= MAP_ORIGIN
| MAP_SUMMARY
| MAP_SECTIONS
;
1342 else if (!nasm_stricmp(p
, "symbols"))
1343 map_control
|= MAP_SYMBOLS
;
1345 if (!nasm_stricmp(p
, "stdout"))
1347 else if (!nasm_stricmp(p
, "stderr"))
1349 else { /* Must be a filename. */
1350 rf
= fopen(p
, "wt");
1352 nasm_error(ERR_WARNING
, "unable to open map file `%s'",
1359 nasm_error(ERR_WARNING
, "map file already specified");
1361 if (map_control
== 0)
1362 map_control
|= MAP_ORIGIN
| MAP_SUMMARY
;
1372 static void bin_filename(char *inname
, char *outname
)
1374 standard_extension(inname
, outname
, "");
1379 static void ith_filename(char *inname
, char *outname
)
1381 standard_extension(inname
, outname
, ".ith");
1386 static void srec_filename(char *inname
, char *outname
)
1388 standard_extension(inname
, outname
, ".srec");
1393 static int32_t bin_segbase(int32_t segment
)
1398 static int bin_set_info(enum geninfo type
, char **val
)
1405 const struct ofmt of_bin
, of_ith
, of_srec
;
1406 static void binfmt_init(void);
1407 static void do_output_bin(void);
1408 static void do_output_ith(void);
1409 static void do_output_srec(void);
1411 static void bin_init(void)
1413 do_output
= do_output_bin
;
1417 static void ith_init(void)
1419 do_output
= do_output_ith
;
1423 static void srec_init(void)
1425 do_output
= do_output_srec
;
1429 static void binfmt_init(void)
1432 reloctail
= &relocs
;
1434 no_seg_labels
= NULL
;
1435 nsl_tail
= &no_seg_labels
;
1437 /* Create default section (.text). */
1438 sections
= last_section
= nasm_zalloc(sizeof(struct Section
));
1439 last_section
->name
= nasm_strdup(".text");
1440 last_section
->contents
= saa_init(1L);
1441 last_section
->flags
= TYPE_DEFINED
| TYPE_PROGBITS
;
1442 last_section
->labels_end
= &(last_section
->labels
);
1443 last_section
->start_index
= seg_alloc();
1444 last_section
->vstart_index
= seg_alloc();
1447 /* Generate binary file output */
1448 static void do_output_bin(void)
1451 uint64_t addr
= origin
;
1453 /* Write the progbits sections to the output file. */
1454 list_for_each(s
, sections
) {
1455 /* Skip non-progbits sections */
1456 if (!(s
->flags
& TYPE_PROGBITS
))
1458 /* Skip zero-length sections */
1462 /* Pad the space between sections. */
1463 nasm_assert(addr
<= s
->start
);
1464 fwritezero(s
->start
- addr
, ofile
);
1466 /* Write the section to the output file. */
1467 saa_fpwrite(s
->contents
, ofile
);
1469 /* Keep track of the current file position */
1470 addr
= s
->start
+ s
->length
;
1474 /* Generate Intel hex file output */
1475 static void write_ith_record(unsigned int len
, uint16_t addr
,
1476 uint8_t type
, void *data
)
1478 char buf
[1+2+4+2+255*2+2+2];
1480 uint8_t csum
, *dptr
= data
;
1483 nasm_assert(len
<= 255);
1485 csum
= len
+ addr
+ (addr
>> 8) + type
;
1486 for (i
= 0; i
< len
; i
++)
1490 p
+= sprintf(p
, ":%02X%04X%02X", len
, addr
, type
);
1491 for (i
= 0; i
< len
; i
++)
1492 p
+= sprintf(p
, "%02X", dptr
[i
]);
1493 p
+= sprintf(p
, "%02X\n", csum
);
1495 nasm_write(buf
, p
-buf
, ofile
);
1498 static void do_output_ith(void)
1502 uint64_t addr
, hiaddr
, hilba
;
1506 /* Write the progbits sections to the output file. */
1508 list_for_each(s
, sections
) {
1509 /* Skip non-progbits sections */
1510 if (!(s
->flags
& TYPE_PROGBITS
))
1512 /* Skip zero-length sections */
1518 saa_rewind(s
->contents
);
1521 hiaddr
= addr
>> 16;
1522 if (hiaddr
!= hilba
) {
1523 buf
[0] = hiaddr
>> 8;
1525 write_ith_record(2, 0, 4, buf
);
1529 chunk
= 32 - (addr
& 31);
1533 saa_rnbytes(s
->contents
, buf
, chunk
);
1534 write_ith_record(chunk
, (uint16_t)addr
, 0, buf
);
1541 /* Write closing record */
1542 write_ith_record(0, 0, 1, NULL
);
1545 /* Generate Motorola S-records */
1546 static void write_srecord(unsigned int len
, unsigned int alen
,
1547 uint32_t addr
, uint8_t type
, void *data
)
1549 char buf
[2+2+8+255*2+2+2];
1551 uint8_t csum
, *dptr
= data
;
1554 nasm_assert(len
<= 255);
1570 csum
= (len
+alen
+1) + addr
+ (addr
>> 8) + (addr
>> 16) + (addr
>> 24);
1571 for (i
= 0; i
< len
; i
++)
1575 p
+= sprintf(p
, "S%c%02X%0*X", type
, len
+alen
+1, alen
*2, addr
);
1576 for (i
= 0; i
< len
; i
++)
1577 p
+= sprintf(p
, "%02X", dptr
[i
]);
1578 p
+= sprintf(p
, "%02X\n", csum
);
1580 nasm_write(buf
, p
-buf
, ofile
);
1583 static void do_output_srec(void)
1587 uint64_t addr
, maxaddr
;
1594 list_for_each(s
, sections
) {
1595 /* Skip non-progbits sections */
1596 if (!(s
->flags
& TYPE_PROGBITS
))
1598 /* Skip zero-length sections */
1602 addr
= s
->start
+ s
->length
- 1;
1607 if (maxaddr
<= 0xffff) {
1609 dtype
= '1'; /* S1 = 16-bit data */
1610 etype
= '9'; /* S9 = 16-bit end */
1611 } else if (maxaddr
<= 0xffffff) {
1613 dtype
= '2'; /* S2 = 24-bit data */
1614 etype
= '8'; /* S8 = 24-bit end */
1617 dtype
= '3'; /* S3 = 32-bit data */
1618 etype
= '7'; /* S7 = 32-bit end */
1621 /* Write head record */
1622 write_srecord(0, 2, 0, '0', NULL
);
1624 /* Write the progbits sections to the output file. */
1625 list_for_each(s
, sections
) {
1626 /* Skip non-progbits sections */
1627 if (!(s
->flags
& TYPE_PROGBITS
))
1629 /* Skip zero-length sections */
1635 saa_rewind(s
->contents
);
1638 chunk
= 32 - (addr
& 31);
1642 saa_rnbytes(s
->contents
, buf
, chunk
);
1643 write_srecord(chunk
, alen
, (uint32_t)addr
, dtype
, buf
);
1650 /* Write closing record */
1651 write_srecord(0, alen
, 0, etype
, NULL
);
1655 const struct ofmt of_bin
= {
1656 "flat-form binary files (e.g. DOS .COM, .SYS)",
1675 const struct ofmt of_ith
= {
1695 const struct ofmt of_srec
= {
1696 "Motorola S-records",
1715 #endif /* #ifdef OF_BIN */