Merge branch 'nasm-2.14.xx'
[nasm.git] / output / outbin.c
blobea49abb569ea12d9fd120e6577aea1cb197d4dc3
1 /* ----------------------------------------------------------------------- *
2 *
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
9 * conditions are met:
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 * ----------------------------------------------------------------------- */
34 /*
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
42 * ordering.
44 * Feature summary:
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
76 #include "compiler.h"
78 #include <stdio.h>
79 #include <stdlib.h>
80 #include <string.h>
81 #include <ctype.h>
83 #include "nasm.h"
84 #include "nasmlib.h"
85 #include "error.h"
86 #include "saa.h"
87 #include "stdscan.h"
88 #include "labels.h"
89 #include "eval.h"
90 #include "outform.h"
91 #include "outlib.h"
93 #ifdef OF_BIN
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 {
111 char *name;
112 struct bin_label *next;
113 } *no_seg_labels, **nsl_tail;
115 static struct Section {
116 char *name;
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 {
147 struct Reloc *next;
148 int32_t posn;
149 int32_t bytes;
150 int32_t secref;
151 int32_t secrel;
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. */
159 #define MAP_ORIGIN 1
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,
168 int32_t secrel)
170 struct Reloc *r;
172 r = *reloctail = nasm_malloc(sizeof(struct Reloc));
173 reloctail = &r->next;
174 r->next = NULL;
175 r->posn = s->length;
176 r->bytes = bytes;
177 r->secref = secref;
178 r->secrel = secrel;
179 r->target = s;
182 static struct Section *find_section_by_name(const char *name)
184 struct Section *s;
186 list_for_each(s, sections)
187 if (!strcmp(s->name, name))
188 break;
189 return s;
192 static struct Section *find_section_by_index(int32_t index)
194 struct Section *s;
196 list_for_each(s, sections)
197 if ((index == s->vstart_index) || (index == s->start_index))
198 break;
199 return s;
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;
217 last_section = s;
219 return last_section;
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;
229 struct bin_label *l;
230 struct Reloc *r;
231 uint64_t pend;
232 int h;
234 #ifdef DEBUG
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);
239 #endif
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. */
258 nt = &nobits;
259 /* Move nobits sections into a separate list. Also pre-process nobits
260 * sections' attributes. */
261 for (sp = &sections->next, s = sections->next; s; s = *sp) { /* Skip progbits sections. */
262 if (s->flags & TYPE_PROGBITS) {
263 sp = &s->next;
264 continue;
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 |
269 VFOLLOWS_DEFINED))
270 nasm_fatal("cannot mix real and virtual attributes"
271 " in nobits section (%s)", s->name);
272 /* Real and virtual attributes mean the same thing for nobits sections. */
273 if (s->flags & START_DEFINED) {
274 s->vstart = s->start;
275 s->flags |= VSTART_DEFINED;
277 if (s->flags & ALIGN_DEFINED) {
278 s->valign = s->align;
279 s->flags |= VALIGN_DEFINED;
281 if (s->flags & FOLLOWS_DEFINED) {
282 s->vfollows = s->follows;
283 s->flags |= VFOLLOWS_DEFINED;
284 s->flags &= ~FOLLOWS_DEFINED;
287 /* Every section must have a start address. */
288 if (s->flags & VSTART_DEFINED) {
289 s->start = s->vstart;
290 s->flags |= START_DEFINED;
292 /* Move the section into the nobits list. */
293 *sp = s->next;
294 s->next = NULL;
295 *nt = s;
296 nt = &s->next;
299 /* Step 2: Sort the progbits sections into their output order. */
301 /* In Step 2 we move around sections in groups. A group
302 * begins with a section (group leader) that has a user-
303 * defined start address or follows section. The remainder
304 * of the group is made up of the sections that implicitly
305 * follow the group leader (i.e., they were defined after
306 * the group leader and were not given an explicit start
307 * address or follows section by the user). */
309 /* For anyone attempting to read this code:
310 * g (group) points to a group of sections, the first one of which has
311 * a user-defined start address or follows section.
312 * gp (g previous) holds the location of the pointer to g.
313 * gs (g scan) is a temp variable that we use to scan to the end of the group.
314 * gsp (gs previous) holds the location of the pointer to gs.
315 * nt (nobits tail) points to the nobits section-list tail.
318 /* Link all 'follows' groups to their proper position. To do
319 * this we need to know three things: the start of the group
320 * to relocate (g), the section it is following (s), and the
321 * end of the group we're relocating (gs). */
322 for (gp = &sections, g = sections; g; g = gs) { /* Find the next follows group that is out of place (g). */
323 if (!(g->flags & FOLLOWS_DEFINED)) {
324 while (g->next) {
325 if ((g->next->flags & FOLLOWS_DEFINED) &&
326 strcmp(g->name, g->next->follows))
327 break;
328 g = g->next;
330 if (!g->next)
331 break;
332 gp = &g->next;
333 g = g->next;
335 /* Find the section that this group follows (s). */
336 for (sp = &sections, s = sections;
337 s && strcmp(s->name, g->follows);
338 sp = &s->next, s = s->next) ;
339 if (!s)
340 nasm_fatal("section %s follows an invalid or"
341 " unknown section (%s)", g->name, g->follows);
342 if (s->next && (s->next->flags & FOLLOWS_DEFINED) &&
343 !strcmp(s->name, s->next->follows))
344 nasm_fatal("sections %s and %s can't both follow"
345 " section %s", g->name, s->next->name, s->name);
346 /* Find the end of the current follows group (gs). */
347 for (gsp = &g->next, gs = g->next;
348 gs && (gs != s) && !(gs->flags & START_DEFINED);
349 gsp = &gs->next, gs = gs->next) {
350 if (gs->next && (gs->next->flags & FOLLOWS_DEFINED) &&
351 strcmp(gs->name, gs->next->follows)) {
352 gsp = &gs->next;
353 gs = gs->next;
354 break;
357 /* Re-link the group after its follows section. */
358 *gsp = s->next;
359 s->next = g;
360 *gp = gs;
363 /* Link all 'start' groups to their proper position. Once
364 * again we need to know g, s, and gs (see above). The main
365 * difference is we already know g since we sort by moving
366 * groups from the 'unsorted' list into a 'sorted' list (g
367 * will always be the first section in the unsorted list). */
368 for (g = sections, sections = NULL; g; g = gs) { /* Find the section that we will insert this group before (s). */
369 for (sp = &sections, s = sections; s; sp = &s->next, s = s->next)
370 if ((s->flags & START_DEFINED) && (g->start < s->start))
371 break;
372 /* Find the end of the group (gs). */
373 for (gs = g->next, gsp = &g->next;
374 gs && !(gs->flags & START_DEFINED);
375 gsp = &gs->next, gs = gs->next) ;
376 /* Re-link the group before the target section. */
377 *sp = g;
378 *gsp = s;
381 /* Step 3: Compute start addresses for all progbits sections. */
383 /* Make sure we have an origin and a start address for the first section. */
384 if (origin_defined) {
385 if (sections->flags & START_DEFINED) {
386 /* Make sure this section doesn't begin before the origin. */
387 if (sections->start < origin)
388 nasm_fatal("section %s begins"
389 " before program origin", sections->name);
390 } else if (sections->flags & ALIGN_DEFINED) {
391 sections->start = ALIGN(origin, sections->align);
392 } else {
393 sections->start = origin;
395 } else {
396 if (!(sections->flags & START_DEFINED))
397 sections->start = 0;
398 origin = sections->start;
400 sections->flags |= START_DEFINED;
402 /* Make sure each section has an explicit start address. If it
403 * doesn't, then compute one based its alignment and the end of
404 * the previous section. */
405 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
406 * (has a defined start address, and is not zero length). */
407 if (g == s)
408 for (s = g->next;
409 s && ((s->length == 0) || !(s->flags & START_DEFINED));
410 s = s->next) ;
411 /* Compute the start address of this section, if necessary. */
412 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
413 if (!(g->flags & ALIGN_DEFINED)) {
414 g->align = 4;
415 g->flags |= ALIGN_DEFINED;
417 /* Set the section start address. */
418 g->start = ALIGN(pend, g->align);
419 g->flags |= START_DEFINED;
421 /* Ugly special case for progbits sections' virtual attributes:
422 * If there is a defined valign, but no vstart and no vfollows, then
423 * we valign after the previous progbits section. This case doesn't
424 * really make much sense for progbits sections with a defined start
425 * address, but it is possible and we must do *something*.
426 * Not-so-ugly special case:
427 * If a progbits section has no virtual attributes, we set the
428 * vstart equal to the start address. */
429 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
430 if (g->flags & VALIGN_DEFINED)
431 g->vstart = ALIGN(pend, g->valign);
432 else
433 g->vstart = g->start;
434 g->flags |= VSTART_DEFINED;
436 /* Ignore zero-length sections. */
437 if (g->start < pend)
438 continue;
439 /* Compute the span of this section. */
440 pend = g->start + g->length;
441 /* Check for section overlap. */
442 if (s) {
443 if (s->start < origin)
444 nasm_fatal("section %s beings before program origin",
445 s->name);
446 if (g->start > s->start)
447 nasm_fatal("sections %s ~ %s and %s overlap!",
448 gs->name, g->name, s->name);
449 if (pend > s->start)
450 nasm_fatal("sections %s and %s overlap!",
451 g->name, s->name);
453 /* Remember this section as the latest >0 length section. */
454 gs = g;
457 /* Step 4: Compute vstart addresses for all sections. */
459 /* Attach the nobits sections to the end of the progbits sections. */
460 for (s = sections; s->next; s = s->next) ;
461 s->next = nobits;
462 last_progbits = s;
464 * Scan for sections that don't have a vstart address. If we find
465 * one we'll attempt to compute its vstart. If we can't compute
466 * the vstart, we leave it alone and come back to it in a
467 * subsequent scan. We continue scanning and re-scanning until
468 * we've gone one full cycle without computing any vstarts.
470 do { /* Do one full scan of the sections list. */
471 for (h = 0, g = sections; g; g = g->next) {
472 if (g->flags & VSTART_DEFINED)
473 continue;
474 /* Find the section that this one virtually follows. */
475 if (g->flags & VFOLLOWS_DEFINED) {
476 for (s = sections; s && strcmp(g->vfollows, s->name);
477 s = s->next) ;
478 if (!s)
479 nasm_fatal("section %s vfollows unknown section (%s)",
480 g->name, g->vfollows);
481 } else if (g->prev != NULL)
482 for (s = sections; s && (s != g->prev); s = s->next) ;
483 /* The .bss section is the only one with prev = NULL.
484 In this case we implicitly follow the last progbits
485 section. */
486 else
487 s = last_progbits;
489 /* If the section we're following has a vstart, we can proceed. */
490 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
491 if (!(g->flags & VALIGN_DEFINED)) {
492 g->valign = 4;
493 g->flags |= VALIGN_DEFINED;
495 /* Compute the vstart address. */
496 g->vstart = ALIGN(s->vstart + s->length, g->valign);
497 g->flags |= VSTART_DEFINED;
498 h++;
499 /* Start and vstart mean the same thing for nobits sections. */
500 if (g->flags & TYPE_NOBITS)
501 g->start = g->vstart;
504 } while (h);
506 /* Now check for any circular vfollows references, which will manifest
507 * themselves as sections without a defined vstart. */
508 for (h = 0, s = sections; s; s = s->next) {
509 if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
510 * no-no, but we'll throw a fatal one eventually so it's ok. */
511 nasm_error(ERR_NONFATAL, "cannot compute vstart for section %s",
512 s->name);
513 h++;
516 if (h)
517 nasm_fatal("circular vfollows path detected");
519 #ifdef DEBUG
520 nasm_error(ERR_DEBUG,
521 "bin_cleanup: Confirm final section order for output file:\n");
522 for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
523 h++, s = s->next)
524 fprintf(stdout, "%i. %s\n", h, s->name);
525 #endif
527 /* Step 5: Apply relocations. */
529 /* Prepare the sections for relocating. */
530 list_for_each(s, sections)
531 saa_rewind(s->contents);
532 /* Apply relocations. */
533 list_for_each(r, relocs) {
534 uint8_t *p, mydata[8];
535 int64_t l;
536 int b;
538 nasm_assert(r->bytes <= 8);
540 memset(mydata, 0, sizeof(mydata));
542 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
543 p = mydata;
544 l = 0;
545 for (b = r->bytes - 1; b >= 0; b--)
546 l = (l << 8) + mydata[b];
548 s = find_section_by_index(r->secref);
549 if (s) {
550 if (r->secref == s->start_index)
551 l += s->start;
552 else
553 l += s->vstart;
555 s = find_section_by_index(r->secrel);
556 if (s) {
557 if (r->secrel == s->start_index)
558 l -= s->start;
559 else
560 l -= s->vstart;
563 WRITEADDR(p, l, r->bytes);
564 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
567 /* Step 6: Write the section data to the output file. */
568 do_output();
570 /* Step 7: Generate the map file. */
572 if (map_control) {
573 static const char not_defined[] = "not defined";
575 /* Display input and output file names. */
576 fprintf(rf, "\n- NASM Map file ");
577 for (h = 63; h; h--)
578 fputc('-', rf);
579 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
580 inname, outname);
582 if (map_control & MAP_ORIGIN) { /* Display program origin. */
583 fprintf(rf, "-- Program origin ");
584 for (h = 61; h; h--)
585 fputc('-', rf);
586 fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
588 /* Display sections summary. */
589 if (map_control & MAP_SUMMARY) {
590 fprintf(rf, "-- Sections (summary) ");
591 for (h = 57; h; h--)
592 fputc('-', rf);
593 fprintf(rf, "\n\nVstart Start Stop "
594 "Length Class Name\n");
595 list_for_each(s, sections) {
596 fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
597 s->vstart, s->start, s->start + s->length,
598 s->length);
599 if (s->flags & TYPE_PROGBITS)
600 fprintf(rf, "progbits ");
601 else
602 fprintf(rf, "nobits ");
603 fprintf(rf, "%s\n", s->name);
605 fprintf(rf, "\n");
607 /* Display detailed section information. */
608 if (map_control & MAP_SECTIONS) {
609 fprintf(rf, "-- Sections (detailed) ");
610 for (h = 56; h; h--)
611 fputc('-', rf);
612 fprintf(rf, "\n\n");
613 list_for_each(s, sections) {
614 fprintf(rf, "---- Section %s ", s->name);
615 for (h = 65 - strlen(s->name); h; h--)
616 fputc('-', rf);
617 fprintf(rf, "\n\nclass: ");
618 if (s->flags & TYPE_PROGBITS)
619 fprintf(rf, "progbits");
620 else
621 fprintf(rf, "nobits");
622 fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
623 "\nalign: ", s->length, s->start);
624 if (s->flags & ALIGN_DEFINED)
625 fprintf(rf, "%16"PRIX64"", s->align);
626 else
627 fputs(not_defined, rf);
628 fprintf(rf, "\nfollows: ");
629 if (s->flags & FOLLOWS_DEFINED)
630 fprintf(rf, "%s", s->follows);
631 else
632 fputs(not_defined, rf);
633 fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
634 if (s->flags & VALIGN_DEFINED)
635 fprintf(rf, "%16"PRIX64"", s->valign);
636 else
637 fputs(not_defined, rf);
638 fprintf(rf, "\nvfollows: ");
639 if (s->flags & VFOLLOWS_DEFINED)
640 fprintf(rf, "%s", s->vfollows);
641 else
642 fputs(not_defined, rf);
643 fprintf(rf, "\n\n");
646 /* Display symbols information. */
647 if (map_control & MAP_SYMBOLS) {
648 int32_t segment;
649 int64_t offset;
650 bool found_label;
652 fprintf(rf, "-- Symbols ");
653 for (h = 68; h; h--)
654 fputc('-', rf);
655 fprintf(rf, "\n\n");
656 if (no_seg_labels) {
657 fprintf(rf, "---- No Section ");
658 for (h = 63; h; h--)
659 fputc('-', rf);
660 fprintf(rf, "\n\nValue Name\n");
661 list_for_each(l, no_seg_labels) {
662 found_label = lookup_label(l->name, &segment, &offset);
663 nasm_assert(found_label);
664 fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
666 fprintf(rf, "\n\n");
668 list_for_each(s, sections) {
669 if (s->labels) {
670 fprintf(rf, "---- Section %s ", s->name);
671 for (h = 65 - strlen(s->name); h; h--)
672 fputc('-', rf);
673 fprintf(rf, "\n\nReal Virtual Name\n");
674 list_for_each(l, s->labels) {
675 found_label = lookup_label(l->name, &segment, &offset);
676 nasm_assert(found_label);
677 fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
678 s->start + offset, s->vstart + offset,
679 l->name);
681 fprintf(rf, "\n");
687 /* Close the report file. */
688 if (map_control && (rf != stdout) && (rf != stderr))
689 fclose(rf);
691 /* Step 8: Release all allocated memory. */
693 /* Free sections, label pointer structs, etc.. */
694 while (sections) {
695 s = sections;
696 sections = s->next;
697 saa_free(s->contents);
698 nasm_free(s->name);
699 if (s->flags & FOLLOWS_DEFINED)
700 nasm_free(s->follows);
701 if (s->flags & VFOLLOWS_DEFINED)
702 nasm_free(s->vfollows);
703 while (s->labels) {
704 l = s->labels;
705 s->labels = l->next;
706 nasm_free(l);
708 nasm_free(s);
711 /* Free no-section labels. */
712 while (no_seg_labels) {
713 l = no_seg_labels;
714 no_seg_labels = l->next;
715 nasm_free(l);
718 /* Free relocation structures. */
719 while (relocs) {
720 r = relocs->next;
721 nasm_free(relocs);
722 relocs = r;
726 static void bin_out(int32_t segto, const void *data,
727 enum out_type type, uint64_t size,
728 int32_t segment, int32_t wrt)
730 uint8_t *p, mydata[8];
731 struct Section *s;
733 if (wrt != NO_SEG) {
734 wrt = NO_SEG; /* continue to do _something_ */
735 nasm_error(ERR_NONFATAL, "WRT not supported by binary output format");
738 /* Find the segment we are targeting. */
739 s = find_section_by_index(segto);
740 if (!s)
741 nasm_panic("code directed to nonexistent segment?");
743 /* "Smart" section-type adaptation code. */
744 if (!(s->flags & TYPE_DEFINED)) {
745 if (type == OUT_RESERVE)
746 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
747 else
748 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
751 if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
752 nasm_error(ERR_WARNING, "attempt to initialize memory in a"
753 " nobits section: ignored");
755 switch (type) {
756 case OUT_ADDRESS:
758 int asize = abs((int)size);
760 if (segment != NO_SEG && !find_section_by_index(segment)) {
761 if (segment % 2)
762 nasm_error(ERR_NONFATAL, "binary output format does not support"
763 " segment base references");
764 else
765 nasm_error(ERR_NONFATAL, "binary output format does not support"
766 " external references");
767 segment = NO_SEG;
769 if (s->flags & TYPE_PROGBITS) {
770 if (segment != NO_SEG)
771 add_reloc(s, asize, segment, -1L);
772 p = mydata;
773 WRITEADDR(p, *(int64_t *)data, asize);
774 saa_wbytes(s->contents, mydata, asize);
778 * Reassign size with sign dropped, we will need it
779 * for section length calculation.
781 size = asize;
782 break;
785 case OUT_RAWDATA:
786 if (s->flags & TYPE_PROGBITS)
787 saa_wbytes(s->contents, data, size);
788 break;
790 case OUT_RESERVE:
791 if (s->flags & TYPE_PROGBITS) {
792 nasm_error(ERR_WARNING, "uninitialized space declared in"
793 " %s section: zeroing", s->name);
794 saa_wbytes(s->contents, NULL, size);
796 break;
798 case OUT_REL1ADR:
799 case OUT_REL2ADR:
800 case OUT_REL4ADR:
801 case OUT_REL8ADR:
803 int64_t addr = *(int64_t *)data - size;
804 size = realsize(type, size);
805 if (segment != NO_SEG && !find_section_by_index(segment)) {
806 if (segment % 2)
807 nasm_error(ERR_NONFATAL, "binary output format does not support"
808 " segment base references");
809 else
810 nasm_error(ERR_NONFATAL, "binary output format does not support"
811 " external references");
812 segment = NO_SEG;
814 if (s->flags & TYPE_PROGBITS) {
815 add_reloc(s, size, segment, segto);
816 p = mydata;
817 WRITEADDR(p, addr - s->length, size);
818 saa_wbytes(s->contents, mydata, size);
820 break;
823 default:
824 nasm_error(ERR_NONFATAL, "unsupported relocation type %d\n", type);
825 break;
828 s->length += size;
831 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
832 int is_global, char *special)
834 (void)segment; /* Don't warn that this parameter is unused */
835 (void)offset; /* Don't warn that this parameter is unused */
837 if (special)
838 nasm_error(ERR_NONFATAL, "binary format does not support any"
839 " special symbol types");
840 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
841 nasm_error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
842 else if (is_global == 2)
843 nasm_error(ERR_NONFATAL, "binary output format does not support common"
844 " variables");
845 else {
846 struct Section *s;
847 struct bin_label ***ltp;
849 /* Remember label definition so we can look it up later when
850 * creating the map file. */
851 s = find_section_by_index(segment);
852 if (s)
853 ltp = &(s->labels_end);
854 else
855 ltp = &nsl_tail;
856 (**ltp) = nasm_malloc(sizeof(struct bin_label));
857 (**ltp)->name = name;
858 (**ltp)->next = NULL;
859 *ltp = &((**ltp)->next);
864 /* These constants and the following function are used
865 * by bin_secname() to parse attribute assignments. */
867 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
868 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
869 ATTRIB_NOBITS, ATTRIB_PROGBITS
872 static int bin_read_attribute(char **line, int *attribute,
873 uint64_t *value)
875 expr *e;
876 int attrib_name_size;
877 struct tokenval tokval;
878 char *exp;
880 /* Skip whitespace. */
881 while (**line && nasm_isspace(**line))
882 (*line)++;
883 if (!**line)
884 return 0;
886 /* Figure out what attribute we're reading. */
887 if (!nasm_strnicmp(*line, "align=", 6)) {
888 *attribute = ATTRIB_ALIGN;
889 attrib_name_size = 6;
890 } else {
891 if (!nasm_strnicmp(*line, "start=", 6)) {
892 *attribute = ATTRIB_START;
893 attrib_name_size = 6;
894 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
895 *attribute = ATTRIB_FOLLOWS;
896 *line += 8;
897 return 1;
898 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
899 *attribute = ATTRIB_VSTART;
900 attrib_name_size = 7;
901 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
902 *attribute = ATTRIB_VALIGN;
903 attrib_name_size = 7;
904 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
905 *attribute = ATTRIB_VFOLLOWS;
906 *line += 9;
907 return 1;
908 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
909 (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
910 *attribute = ATTRIB_NOBITS;
911 *line += 6;
912 return 1;
913 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
914 (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
915 *attribute = ATTRIB_PROGBITS;
916 *line += 8;
917 return 1;
918 } else
919 return 0;
922 /* Find the end of the expression. */
923 if ((*line)[attrib_name_size] != '(') {
924 /* Single term (no parenthesis). */
925 exp = *line += attrib_name_size;
926 while (**line && !nasm_isspace(**line))
927 (*line)++;
928 if (**line) {
929 **line = '\0';
930 (*line)++;
932 } else {
933 char c;
934 int pcount = 1;
936 /* Full expression (delimited by parenthesis) */
937 exp = *line += attrib_name_size + 1;
938 while (1) {
939 (*line) += strcspn(*line, "()'\"");
940 if (**line == '(') {
941 ++(*line);
942 ++pcount;
944 if (**line == ')') {
945 ++(*line);
946 --pcount;
947 if (!pcount)
948 break;
950 if ((**line == '"') || (**line == '\'')) {
951 c = **line;
952 while (**line) {
953 ++(*line);
954 if (**line == c)
955 break;
957 if (!**line) {
958 nasm_error(ERR_NONFATAL,
959 "invalid syntax in `section' directive");
960 return -1;
962 ++(*line);
964 if (!**line) {
965 nasm_error(ERR_NONFATAL, "expecting `)'");
966 return -1;
969 *(*line - 1) = '\0'; /* Terminate the expression. */
972 /* Check for no value given. */
973 if (!*exp) {
974 nasm_error(ERR_WARNING, "No value given to attribute in"
975 " `section' directive");
976 return -1;
979 /* Read and evaluate the expression. */
980 stdscan_reset();
981 stdscan_set(exp);
982 tokval.t_type = TOKEN_INVALID;
983 e = evaluate(stdscan, NULL, &tokval, NULL, 1, NULL);
984 if (e) {
985 if (!is_really_simple(e)) {
986 nasm_error(ERR_NONFATAL, "section attribute value must be"
987 " a critical expression");
988 return -1;
990 } else {
991 nasm_error(ERR_NONFATAL, "Invalid attribute value"
992 " specified in `section' directive.");
993 return -1;
995 *value = (uint64_t)reloc_value(e);
996 return 1;
999 static void bin_sectalign(int32_t seg, unsigned int value)
1001 struct Section *s = find_section_by_index(seg);
1003 if (!s || !is_power2(value))
1004 return;
1006 if (value > s->align)
1007 s->align = value;
1009 if (!(s->flags & ALIGN_DEFINED))
1010 s->flags |= ALIGN_DEFINED;
1013 static void bin_assign_attributes(struct Section *sec, char *astring)
1015 int attribute, check;
1016 uint64_t value;
1017 char *p;
1019 while (1) { /* Get the next attribute. */
1020 check = bin_read_attribute(&astring, &attribute, &value);
1021 /* Skip bad attribute. */
1022 if (check == -1)
1023 continue;
1024 /* Unknown section attribute, so skip it and warn the user. */
1025 if (!check) {
1026 if (!*astring)
1027 break; /* End of line. */
1028 else {
1029 p = astring;
1030 while (*astring && !nasm_isspace(*astring))
1031 astring++;
1032 if (*astring) {
1033 *astring = '\0';
1034 astring++;
1036 nasm_error(ERR_WARNING, "ignoring unknown section attribute:"
1037 " \"%s\"", p);
1039 continue;
1042 switch (attribute) { /* Handle nobits attribute. */
1043 case ATTRIB_NOBITS:
1044 if ((sec->flags & TYPE_DEFINED)
1045 && (sec->flags & TYPE_PROGBITS))
1046 nasm_error(ERR_NONFATAL,
1047 "attempt to change section type"
1048 " from progbits to nobits");
1049 else
1050 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1051 continue;
1053 /* Handle progbits attribute. */
1054 case ATTRIB_PROGBITS:
1055 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1056 nasm_error(ERR_NONFATAL, "attempt to change section type"
1057 " from nobits to progbits");
1058 else
1059 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1060 continue;
1062 /* Handle align attribute. */
1063 case ATTRIB_ALIGN:
1064 if (!value || ((value - 1) & value)) {
1065 nasm_error(ERR_NONFATAL,
1066 "argument to `align' is not a power of two");
1067 } else {
1069 * Alignment is already satisfied if
1070 * the previous align value is greater
1072 if ((sec->flags & ALIGN_DEFINED) && (value < sec->align))
1073 value = sec->align;
1075 /* Don't allow a conflicting align value. */
1076 if ((sec->flags & START_DEFINED) && (sec->start & (value - 1))) {
1077 nasm_error(ERR_NONFATAL,
1078 "`align' value conflicts with section start address");
1079 } else {
1080 sec->align = value;
1081 sec->flags |= ALIGN_DEFINED;
1084 continue;
1086 /* Handle valign attribute. */
1087 case ATTRIB_VALIGN:
1088 if (!value || ((value - 1) & value))
1089 nasm_error(ERR_NONFATAL, "argument to `valign' is not a"
1090 " power of two");
1091 else { /* Alignment is already satisfied if the previous
1092 * align value is greater. */
1093 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1094 value = sec->valign;
1096 /* Don't allow a conflicting valign value. */
1097 if ((sec->flags & VSTART_DEFINED)
1098 && (sec->vstart & (value - 1)))
1099 nasm_error(ERR_NONFATAL,
1100 "`valign' value conflicts "
1101 "with `vstart' address");
1102 else {
1103 sec->valign = value;
1104 sec->flags |= VALIGN_DEFINED;
1107 continue;
1109 /* Handle start attribute. */
1110 case ATTRIB_START:
1111 if (sec->flags & FOLLOWS_DEFINED)
1112 nasm_error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1113 " section attributes");
1114 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1115 nasm_error(ERR_NONFATAL, "section start address redefined");
1116 else {
1117 sec->start = value;
1118 sec->flags |= START_DEFINED;
1119 if (sec->flags & ALIGN_DEFINED) {
1120 if (sec->start & (sec->align - 1))
1121 nasm_error(ERR_NONFATAL, "`start' address conflicts"
1122 " with section alignment");
1123 sec->flags ^= ALIGN_DEFINED;
1126 continue;
1128 /* Handle vstart attribute. */
1129 case ATTRIB_VSTART:
1130 if (sec->flags & VFOLLOWS_DEFINED)
1131 nasm_error(ERR_NONFATAL,
1132 "cannot combine `vstart' and `vfollows'"
1133 " section attributes");
1134 else if ((sec->flags & VSTART_DEFINED)
1135 && (value != sec->vstart))
1136 nasm_error(ERR_NONFATAL,
1137 "section virtual start address"
1138 " (vstart) redefined");
1139 else {
1140 sec->vstart = value;
1141 sec->flags |= VSTART_DEFINED;
1142 if (sec->flags & VALIGN_DEFINED) {
1143 if (sec->vstart & (sec->valign - 1))
1144 nasm_error(ERR_NONFATAL, "`vstart' address conflicts"
1145 " with `valign' value");
1146 sec->flags ^= VALIGN_DEFINED;
1149 continue;
1151 /* Handle follows attribute. */
1152 case ATTRIB_FOLLOWS:
1153 p = astring;
1154 astring += strcspn(astring, " \t");
1155 if (astring == p)
1156 nasm_error(ERR_NONFATAL, "expecting section name for `follows'"
1157 " attribute");
1158 else {
1159 *(astring++) = '\0';
1160 if (sec->flags & START_DEFINED)
1161 nasm_error(ERR_NONFATAL,
1162 "cannot combine `start' and `follows'"
1163 " section attributes");
1164 sec->follows = nasm_strdup(p);
1165 sec->flags |= FOLLOWS_DEFINED;
1167 continue;
1169 /* Handle vfollows attribute. */
1170 case ATTRIB_VFOLLOWS:
1171 if (sec->flags & VSTART_DEFINED)
1172 nasm_error(ERR_NONFATAL,
1173 "cannot combine `vstart' and `vfollows'"
1174 " section attributes");
1175 else {
1176 p = astring;
1177 astring += strcspn(astring, " \t");
1178 if (astring == p)
1179 nasm_error(ERR_NONFATAL,
1180 "expecting section name for `vfollows'"
1181 " attribute");
1182 else {
1183 *(astring++) = '\0';
1184 sec->vfollows = nasm_strdup(p);
1185 sec->flags |= VFOLLOWS_DEFINED;
1188 continue;
1193 static void bin_define_section_labels(void)
1195 static int labels_defined = 0;
1196 struct Section *sec;
1197 char *label_name;
1198 size_t base_len;
1200 if (labels_defined)
1201 return;
1202 list_for_each(sec, sections) {
1203 base_len = strlen(sec->name) + 8;
1204 label_name = nasm_malloc(base_len + 8);
1205 strcpy(label_name, "section.");
1206 strcpy(label_name + 8, sec->name);
1208 /* section.<name>.start */
1209 strcpy(label_name + base_len, ".start");
1210 define_label(label_name, sec->start_index, 0L, false);
1212 /* section.<name>.vstart */
1213 strcpy(label_name + base_len, ".vstart");
1214 define_label(label_name, sec->vstart_index, 0L, false);
1216 nasm_free(label_name);
1218 labels_defined = 1;
1221 static int32_t bin_secname(char *name, int pass, int *bits)
1223 char *p;
1224 struct Section *sec;
1226 /* bin_secname is called with *name = NULL at the start of each
1227 * pass. Use this opportunity to establish the default section
1228 * (default is BITS-16 ".text" segment).
1230 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1231 origin_defined = 0;
1232 list_for_each(sec, sections)
1233 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1234 ALIGN_DEFINED | VALIGN_DEFINED);
1236 /* Define section start and vstart labels. */
1237 if (pass != 1)
1238 bin_define_section_labels();
1240 /* Establish the default (.text) section. */
1241 *bits = 16;
1242 sec = find_section_by_name(".text");
1243 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1244 return sec->vstart_index;
1247 /* Attempt to find the requested section. If it does not
1248 * exist, create it. */
1249 p = name;
1250 while (*p && !nasm_isspace(*p))
1251 p++;
1252 if (*p)
1253 *p++ = '\0';
1254 sec = find_section_by_name(name);
1255 if (!sec) {
1256 sec = create_section(name);
1257 if (!strcmp(name, ".data"))
1258 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1259 else if (!strcmp(name, ".bss")) {
1260 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1261 sec->prev = NULL;
1265 /* Handle attribute assignments. */
1266 if (pass != 1)
1267 bin_assign_attributes(sec, p);
1269 #ifndef ABIN_SMART_ADAPT
1270 /* The following line disables smart adaptation of
1271 * PROGBITS/NOBITS section types (it forces sections to
1272 * default to PROGBITS). */
1273 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1274 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1275 #endif
1277 return sec->vstart_index;
1280 static enum directive_result
1281 bin_directive(enum directive directive, char *args, int pass)
1283 switch (directive) {
1284 case D_ORG:
1286 struct tokenval tokval;
1287 uint64_t value;
1288 expr *e;
1290 stdscan_reset();
1291 stdscan_set(args);
1292 tokval.t_type = TOKEN_INVALID;
1293 e = evaluate(stdscan, NULL, &tokval, NULL, 1, NULL);
1294 if (e) {
1295 if (!is_really_simple(e))
1296 nasm_error(ERR_NONFATAL, "org value must be a critical"
1297 " expression");
1298 else {
1299 value = reloc_value(e);
1300 /* Check for ORG redefinition. */
1301 if (origin_defined && (value != origin))
1302 nasm_error(ERR_NONFATAL, "program origin redefined");
1303 else {
1304 origin = value;
1305 origin_defined = 1;
1308 } else
1309 nasm_error(ERR_NONFATAL, "No or invalid offset specified"
1310 " in ORG directive.");
1311 return DIRR_OK;
1313 case D_MAP:
1315 /* The 'map' directive allows the user to generate section
1316 * and symbol information to stdout, stderr, or to a file. */
1317 char *p;
1319 if (pass != 1)
1320 return DIRR_OK;
1321 args += strspn(args, " \t");
1322 while (*args) {
1323 p = args;
1324 args += strcspn(args, " \t");
1325 if (*args != '\0')
1326 *(args++) = '\0';
1327 if (!nasm_stricmp(p, "all"))
1328 map_control |=
1329 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1330 else if (!nasm_stricmp(p, "brief"))
1331 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1332 else if (!nasm_stricmp(p, "sections"))
1333 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1334 else if (!nasm_stricmp(p, "segments"))
1335 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1336 else if (!nasm_stricmp(p, "symbols"))
1337 map_control |= MAP_SYMBOLS;
1338 else if (!rf) {
1339 if (!nasm_stricmp(p, "stdout"))
1340 rf = stdout;
1341 else if (!nasm_stricmp(p, "stderr"))
1342 rf = stderr;
1343 else { /* Must be a filename. */
1344 rf = nasm_open_write(p, NF_TEXT);
1345 if (!rf) {
1346 nasm_error(ERR_WARNING, "unable to open map file `%s'",
1348 map_control = 0;
1349 return DIRR_OK;
1352 } else
1353 nasm_error(ERR_WARNING, "map file already specified");
1355 if (map_control == 0)
1356 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1357 if (!rf)
1358 rf = stdout;
1359 return DIRR_OK;
1361 default:
1362 return DIRR_UNKNOWN;
1366 const struct ofmt of_bin, of_ith, of_srec;
1367 static void binfmt_init(void);
1368 static void do_output_bin(void);
1369 static void do_output_ith(void);
1370 static void do_output_srec(void);
1372 static void bin_init(void)
1374 do_output = do_output_bin;
1375 binfmt_init();
1378 static void ith_init(void)
1380 do_output = do_output_ith;
1381 binfmt_init();
1384 static void srec_init(void)
1386 do_output = do_output_srec;
1387 binfmt_init();
1390 static void binfmt_init(void)
1392 relocs = NULL;
1393 reloctail = &relocs;
1394 origin_defined = 0;
1395 no_seg_labels = NULL;
1396 nsl_tail = &no_seg_labels;
1398 /* Create default section (.text). */
1399 sections = last_section = nasm_zalloc(sizeof(struct Section));
1400 last_section->name = nasm_strdup(".text");
1401 last_section->contents = saa_init(1L);
1402 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1403 last_section->labels_end = &(last_section->labels);
1404 last_section->start_index = seg_alloc();
1405 last_section->vstart_index = seg_alloc();
1408 /* Generate binary file output */
1409 static void do_output_bin(void)
1411 struct Section *s;
1412 uint64_t addr = origin;
1414 /* Write the progbits sections to the output file. */
1415 list_for_each(s, sections) {
1416 /* Skip non-progbits sections */
1417 if (!(s->flags & TYPE_PROGBITS))
1418 continue;
1419 /* Skip zero-length sections */
1420 if (s->length == 0)
1421 continue;
1423 /* Pad the space between sections. */
1424 nasm_assert(addr <= s->start);
1425 fwritezero(s->start - addr, ofile);
1427 /* Write the section to the output file. */
1428 saa_fpwrite(s->contents, ofile);
1430 /* Keep track of the current file position */
1431 addr = s->start + s->length;
1435 /* Generate Intel hex file output */
1436 static void write_ith_record(unsigned int len, uint16_t addr,
1437 uint8_t type, void *data)
1439 char buf[1+2+4+2+255*2+2+2];
1440 char *p = buf;
1441 uint8_t csum, *dptr = data;
1442 unsigned int i;
1444 nasm_assert(len <= 255);
1446 csum = len + addr + (addr >> 8) + type;
1447 for (i = 0; i < len; i++)
1448 csum += dptr[i];
1449 csum = -csum;
1451 p += sprintf(p, ":%02X%04X%02X", len, addr, type);
1452 for (i = 0; i < len; i++)
1453 p += sprintf(p, "%02X", dptr[i]);
1454 p += sprintf(p, "%02X\n", csum);
1456 nasm_write(buf, p-buf, ofile);
1459 static void do_output_ith(void)
1461 uint8_t buf[32];
1462 struct Section *s;
1463 uint64_t addr, hiaddr, hilba;
1464 uint64_t length;
1465 unsigned int chunk;
1467 /* Write the progbits sections to the output file. */
1468 hilba = 0;
1469 list_for_each(s, sections) {
1470 /* Skip non-progbits sections */
1471 if (!(s->flags & TYPE_PROGBITS))
1472 continue;
1473 /* Skip zero-length sections */
1474 if (s->length == 0)
1475 continue;
1477 addr = s->start;
1478 length = s->length;
1479 saa_rewind(s->contents);
1481 while (length) {
1482 hiaddr = addr >> 16;
1483 if (hiaddr != hilba) {
1484 buf[0] = hiaddr >> 8;
1485 buf[1] = hiaddr;
1486 write_ith_record(2, 0, 4, buf);
1487 hilba = hiaddr;
1490 chunk = 32 - (addr & 31);
1491 if (length < chunk)
1492 chunk = length;
1494 saa_rnbytes(s->contents, buf, chunk);
1495 write_ith_record(chunk, (uint16_t)addr, 0, buf);
1497 addr += chunk;
1498 length -= chunk;
1502 /* Write closing record */
1503 write_ith_record(0, 0, 1, NULL);
1506 /* Generate Motorola S-records */
1507 static void write_srecord(unsigned int len, unsigned int alen,
1508 uint32_t addr, uint8_t type, void *data)
1510 char buf[2+2+8+255*2+2+2];
1511 char *p = buf;
1512 uint8_t csum, *dptr = data;
1513 unsigned int i;
1515 nasm_assert(len <= 255);
1517 switch (alen) {
1518 case 2:
1519 addr &= 0xffff;
1520 break;
1521 case 3:
1522 addr &= 0xffffff;
1523 break;
1524 case 4:
1525 break;
1526 default:
1527 nasm_assert(0);
1528 break;
1531 csum = (len+alen+1) + addr + (addr >> 8) + (addr >> 16) + (addr >> 24);
1532 for (i = 0; i < len; i++)
1533 csum += dptr[i];
1534 csum = 0xff-csum;
1536 p += sprintf(p, "S%c%02X%0*X", type, len+alen+1, alen*2, addr);
1537 for (i = 0; i < len; i++)
1538 p += sprintf(p, "%02X", dptr[i]);
1539 p += sprintf(p, "%02X\n", csum);
1541 nasm_write(buf, p-buf, ofile);
1544 static void do_output_srec(void)
1546 uint8_t buf[32];
1547 struct Section *s;
1548 uint64_t addr, maxaddr;
1549 uint64_t length;
1550 int alen;
1551 unsigned int chunk;
1552 char dtype, etype;
1554 maxaddr = 0;
1555 list_for_each(s, sections) {
1556 /* Skip non-progbits sections */
1557 if (!(s->flags & TYPE_PROGBITS))
1558 continue;
1559 /* Skip zero-length sections */
1560 if (s->length == 0)
1561 continue;
1563 addr = s->start + s->length - 1;
1564 if (addr > maxaddr)
1565 maxaddr = addr;
1568 if (maxaddr <= 0xffff) {
1569 alen = 2;
1570 dtype = '1'; /* S1 = 16-bit data */
1571 etype = '9'; /* S9 = 16-bit end */
1572 } else if (maxaddr <= 0xffffff) {
1573 alen = 3;
1574 dtype = '2'; /* S2 = 24-bit data */
1575 etype = '8'; /* S8 = 24-bit end */
1576 } else {
1577 alen = 4;
1578 dtype = '3'; /* S3 = 32-bit data */
1579 etype = '7'; /* S7 = 32-bit end */
1582 /* Write head record */
1583 write_srecord(0, 2, 0, '0', NULL);
1585 /* Write the progbits sections to the output file. */
1586 list_for_each(s, sections) {
1587 /* Skip non-progbits sections */
1588 if (!(s->flags & TYPE_PROGBITS))
1589 continue;
1590 /* Skip zero-length sections */
1591 if (s->length == 0)
1592 continue;
1594 addr = s->start;
1595 length = s->length;
1596 saa_rewind(s->contents);
1598 while (length) {
1599 chunk = 32 - (addr & 31);
1600 if (length < chunk)
1601 chunk = length;
1603 saa_rnbytes(s->contents, buf, chunk);
1604 write_srecord(chunk, alen, (uint32_t)addr, dtype, buf);
1606 addr += chunk;
1607 length -= chunk;
1611 /* Write closing record */
1612 write_srecord(0, alen, 0, etype, NULL);
1616 const struct ofmt of_bin = {
1617 "flat-form binary files (e.g. DOS .COM, .SYS)",
1618 "bin",
1622 null_debug_arr,
1623 &null_debug_form,
1624 bin_stdmac,
1625 bin_init,
1626 null_reset,
1627 nasm_do_legacy_output,
1628 bin_out,
1629 bin_deflabel,
1630 bin_secname,
1631 NULL,
1632 bin_sectalign,
1633 null_segbase,
1634 bin_directive,
1635 bin_cleanup,
1636 NULL /* pragma list */
1639 const struct ofmt of_ith = {
1640 "Intel hex",
1641 "ith",
1642 ".ith", /* really should have been ".hex"... */
1643 OFMT_TEXT,
1645 null_debug_arr,
1646 &null_debug_form,
1647 bin_stdmac,
1648 ith_init,
1649 null_reset,
1650 nasm_do_legacy_output,
1651 bin_out,
1652 bin_deflabel,
1653 bin_secname,
1654 NULL,
1655 bin_sectalign,
1656 null_segbase,
1657 bin_directive,
1658 bin_cleanup,
1659 NULL /* pragma list */
1662 const struct ofmt of_srec = {
1663 "Motorola S-records",
1664 "srec",
1665 ".srec",
1666 OFMT_TEXT,
1668 null_debug_arr,
1669 &null_debug_form,
1670 bin_stdmac,
1671 srec_init,
1672 null_reset,
1673 nasm_do_legacy_output,
1674 bin_out,
1675 bin_deflabel,
1676 bin_secname,
1677 NULL,
1678 bin_sectalign,
1679 null_segbase,
1680 bin_directive,
1681 bin_cleanup,
1682 NULL /* pragma list */
1685 #endif /* #ifdef OF_BIN */