output: bin -- Use nasm_error helpers
[nasm.git] / output / outbin.c
bloba3220e86a499f1f324fdd300934b88cb44fe7b9c
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_debug("bin_cleanup: Sections were initially referenced in this order:\n");
236 for (h = 0, s = sections; s; h++, s = s->next)
237 fprintf(stdout, "%i. %s\n", h, s->name);
238 #endif
240 /* Assembly has completed, so now we need to generate the output file.
241 * Step 1: Separate progbits and nobits sections into separate lists.
242 * Step 2: Sort the progbits sections into their output order.
243 * Step 3: Compute start addresses for all progbits sections.
244 * Step 4: Compute vstart addresses for all sections.
245 * Step 5: Apply relocations.
246 * Step 6: Write the sections' data to the output file.
247 * Step 7: Generate the map file.
248 * Step 8: Release all allocated memory.
251 /* To do: Smart section-type adaptation could leave some empty sections
252 * without a defined type (progbits/nobits). Won't fix now since this
253 * feature will be disabled. */
255 /* Step 1: Split progbits and nobits sections into separate lists. */
257 nt = &nobits;
258 /* Move nobits sections into a separate list. Also pre-process nobits
259 * sections' attributes. */
260 for (sp = &sections->next, s = sections->next; s; s = *sp) { /* Skip progbits sections. */
261 if (s->flags & TYPE_PROGBITS) {
262 sp = &s->next;
263 continue;
265 /* Do some special pre-processing on nobits sections' attributes. */
266 if (s->flags & (START_DEFINED | ALIGN_DEFINED | FOLLOWS_DEFINED)) { /* Check for a mixture of real and virtual section attributes. */
267 if (s->flags & (VSTART_DEFINED | VALIGN_DEFINED |
268 VFOLLOWS_DEFINED))
269 nasm_fatal("cannot mix real and virtual attributes"
270 " in nobits section (%s)", s->name);
271 /* Real and virtual attributes mean the same thing for nobits sections. */
272 if (s->flags & START_DEFINED) {
273 s->vstart = s->start;
274 s->flags |= VSTART_DEFINED;
276 if (s->flags & ALIGN_DEFINED) {
277 s->valign = s->align;
278 s->flags |= VALIGN_DEFINED;
280 if (s->flags & FOLLOWS_DEFINED) {
281 s->vfollows = s->follows;
282 s->flags |= VFOLLOWS_DEFINED;
283 s->flags &= ~FOLLOWS_DEFINED;
286 /* Every section must have a start address. */
287 if (s->flags & VSTART_DEFINED) {
288 s->start = s->vstart;
289 s->flags |= START_DEFINED;
291 /* Move the section into the nobits list. */
292 *sp = s->next;
293 s->next = NULL;
294 *nt = s;
295 nt = &s->next;
298 /* Step 2: Sort the progbits sections into their output order. */
300 /* In Step 2 we move around sections in groups. A group
301 * begins with a section (group leader) that has a user-
302 * defined start address or follows section. The remainder
303 * of the group is made up of the sections that implicitly
304 * follow the group leader (i.e., they were defined after
305 * the group leader and were not given an explicit start
306 * address or follows section by the user). */
308 /* For anyone attempting to read this code:
309 * g (group) points to a group of sections, the first one of which has
310 * a user-defined start address or follows section.
311 * gp (g previous) holds the location of the pointer to g.
312 * gs (g scan) is a temp variable that we use to scan to the end of the group.
313 * gsp (gs previous) holds the location of the pointer to gs.
314 * nt (nobits tail) points to the nobits section-list tail.
317 /* Link all 'follows' groups to their proper position. To do
318 * this we need to know three things: the start of the group
319 * to relocate (g), the section it is following (s), and the
320 * end of the group we're relocating (gs). */
321 for (gp = &sections, g = sections; g; g = gs) { /* Find the next follows group that is out of place (g). */
322 if (!(g->flags & FOLLOWS_DEFINED)) {
323 while (g->next) {
324 if ((g->next->flags & FOLLOWS_DEFINED) &&
325 strcmp(g->name, g->next->follows))
326 break;
327 g = g->next;
329 if (!g->next)
330 break;
331 gp = &g->next;
332 g = g->next;
334 /* Find the section that this group follows (s). */
335 for (sp = &sections, s = sections;
336 s && strcmp(s->name, g->follows);
337 sp = &s->next, s = s->next) ;
338 if (!s)
339 nasm_fatal("section %s follows an invalid or"
340 " unknown section (%s)", g->name, g->follows);
341 if (s->next && (s->next->flags & FOLLOWS_DEFINED) &&
342 !strcmp(s->name, s->next->follows))
343 nasm_fatal("sections %s and %s can't both follow"
344 " section %s", g->name, s->next->name, s->name);
345 /* Find the end of the current follows group (gs). */
346 for (gsp = &g->next, gs = g->next;
347 gs && (gs != s) && !(gs->flags & START_DEFINED);
348 gsp = &gs->next, gs = gs->next) {
349 if (gs->next && (gs->next->flags & FOLLOWS_DEFINED) &&
350 strcmp(gs->name, gs->next->follows)) {
351 gsp = &gs->next;
352 gs = gs->next;
353 break;
356 /* Re-link the group after its follows section. */
357 *gsp = s->next;
358 s->next = g;
359 *gp = gs;
362 /* Link all 'start' groups to their proper position. Once
363 * again we need to know g, s, and gs (see above). The main
364 * difference is we already know g since we sort by moving
365 * groups from the 'unsorted' list into a 'sorted' list (g
366 * will always be the first section in the unsorted list). */
367 for (g = sections, sections = NULL; g; g = gs) { /* Find the section that we will insert this group before (s). */
368 for (sp = &sections, s = sections; s; sp = &s->next, s = s->next)
369 if ((s->flags & START_DEFINED) && (g->start < s->start))
370 break;
371 /* Find the end of the group (gs). */
372 for (gs = g->next, gsp = &g->next;
373 gs && !(gs->flags & START_DEFINED);
374 gsp = &gs->next, gs = gs->next) ;
375 /* Re-link the group before the target section. */
376 *sp = g;
377 *gsp = s;
380 /* Step 3: Compute start addresses for all progbits sections. */
382 /* Make sure we have an origin and a start address for the first section. */
383 if (origin_defined) {
384 if (sections->flags & START_DEFINED) {
385 /* Make sure this section doesn't begin before the origin. */
386 if (sections->start < origin)
387 nasm_fatal("section %s begins"
388 " before program origin", sections->name);
389 } else if (sections->flags & ALIGN_DEFINED) {
390 sections->start = ALIGN(origin, sections->align);
391 } else {
392 sections->start = origin;
394 } else {
395 if (!(sections->flags & START_DEFINED))
396 sections->start = 0;
397 origin = sections->start;
399 sections->flags |= START_DEFINED;
401 /* Make sure each section has an explicit start address. If it
402 * doesn't, then compute one based its alignment and the end of
403 * the previous section. */
404 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
405 * (has a defined start address, and is not zero length). */
406 if (g == s)
407 for (s = g->next;
408 s && ((s->length == 0) || !(s->flags & START_DEFINED));
409 s = s->next) ;
410 /* Compute the start address of this section, if necessary. */
411 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
412 if (!(g->flags & ALIGN_DEFINED)) {
413 g->align = 4;
414 g->flags |= ALIGN_DEFINED;
416 /* Set the section start address. */
417 g->start = ALIGN(pend, g->align);
418 g->flags |= START_DEFINED;
420 /* Ugly special case for progbits sections' virtual attributes:
421 * If there is a defined valign, but no vstart and no vfollows, then
422 * we valign after the previous progbits section. This case doesn't
423 * really make much sense for progbits sections with a defined start
424 * address, but it is possible and we must do *something*.
425 * Not-so-ugly special case:
426 * If a progbits section has no virtual attributes, we set the
427 * vstart equal to the start address. */
428 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
429 if (g->flags & VALIGN_DEFINED)
430 g->vstart = ALIGN(pend, g->valign);
431 else
432 g->vstart = g->start;
433 g->flags |= VSTART_DEFINED;
435 /* Ignore zero-length sections. */
436 if (g->start < pend)
437 continue;
438 /* Compute the span of this section. */
439 pend = g->start + g->length;
440 /* Check for section overlap. */
441 if (s) {
442 if (s->start < origin)
443 nasm_fatal("section %s beings before program origin",
444 s->name);
445 if (g->start > s->start)
446 nasm_fatal("sections %s ~ %s and %s overlap!",
447 gs->name, g->name, s->name);
448 if (pend > s->start)
449 nasm_fatal("sections %s and %s overlap!",
450 g->name, s->name);
452 /* Remember this section as the latest >0 length section. */
453 gs = g;
456 /* Step 4: Compute vstart addresses for all sections. */
458 /* Attach the nobits sections to the end of the progbits sections. */
459 for (s = sections; s->next; s = s->next) ;
460 s->next = nobits;
461 last_progbits = s;
463 * Scan for sections that don't have a vstart address. If we find
464 * one we'll attempt to compute its vstart. If we can't compute
465 * the vstart, we leave it alone and come back to it in a
466 * subsequent scan. We continue scanning and re-scanning until
467 * we've gone one full cycle without computing any vstarts.
469 do { /* Do one full scan of the sections list. */
470 for (h = 0, g = sections; g; g = g->next) {
471 if (g->flags & VSTART_DEFINED)
472 continue;
473 /* Find the section that this one virtually follows. */
474 if (g->flags & VFOLLOWS_DEFINED) {
475 for (s = sections; s && strcmp(g->vfollows, s->name);
476 s = s->next) ;
477 if (!s)
478 nasm_fatal("section %s vfollows unknown section (%s)",
479 g->name, g->vfollows);
480 } else if (g->prev != NULL)
481 for (s = sections; s && (s != g->prev); s = s->next) ;
482 /* The .bss section is the only one with prev = NULL.
483 In this case we implicitly follow the last progbits
484 section. */
485 else
486 s = last_progbits;
488 /* If the section we're following has a vstart, we can proceed. */
489 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
490 if (!(g->flags & VALIGN_DEFINED)) {
491 g->valign = 4;
492 g->flags |= VALIGN_DEFINED;
494 /* Compute the vstart address. */
495 g->vstart = ALIGN(s->vstart + s->length, g->valign);
496 g->flags |= VSTART_DEFINED;
497 h++;
498 /* Start and vstart mean the same thing for nobits sections. */
499 if (g->flags & TYPE_NOBITS)
500 g->start = g->vstart;
503 } while (h);
505 /* Now check for any circular vfollows references, which will manifest
506 * themselves as sections without a defined vstart. */
507 for (h = 0, s = sections; s; s = s->next) {
508 if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
509 * no-no, but we'll throw a fatal one eventually so it's ok. */
510 nasm_nonfatal("cannot compute vstart for section %s", s->name);
511 h++;
514 if (h)
515 nasm_fatal("circular vfollows path detected");
517 #ifdef DEBUG
518 nasm_debug("bin_cleanup: Confirm final section order for output file:\n");
519 for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
520 h++, s = s->next)
521 fprintf(stdout, "%i. %s\n", h, s->name);
522 #endif
524 /* Step 5: Apply relocations. */
526 /* Prepare the sections for relocating. */
527 list_for_each(s, sections)
528 saa_rewind(s->contents);
529 /* Apply relocations. */
530 list_for_each(r, relocs) {
531 uint8_t *p, mydata[8];
532 int64_t l;
533 int b;
535 nasm_assert(r->bytes <= 8);
537 memset(mydata, 0, sizeof(mydata));
539 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
540 p = mydata;
541 l = 0;
542 for (b = r->bytes - 1; b >= 0; b--)
543 l = (l << 8) + mydata[b];
545 s = find_section_by_index(r->secref);
546 if (s) {
547 if (r->secref == s->start_index)
548 l += s->start;
549 else
550 l += s->vstart;
552 s = find_section_by_index(r->secrel);
553 if (s) {
554 if (r->secrel == s->start_index)
555 l -= s->start;
556 else
557 l -= s->vstart;
560 WRITEADDR(p, l, r->bytes);
561 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
564 /* Step 6: Write the section data to the output file. */
565 do_output();
567 /* Step 7: Generate the map file. */
569 if (map_control) {
570 static const char not_defined[] = "not defined";
572 /* Display input and output file names. */
573 fprintf(rf, "\n- NASM Map file ");
574 for (h = 63; h; h--)
575 fputc('-', rf);
576 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
577 inname, outname);
579 if (map_control & MAP_ORIGIN) { /* Display program origin. */
580 fprintf(rf, "-- Program origin ");
581 for (h = 61; h; h--)
582 fputc('-', rf);
583 fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
585 /* Display sections summary. */
586 if (map_control & MAP_SUMMARY) {
587 fprintf(rf, "-- Sections (summary) ");
588 for (h = 57; h; h--)
589 fputc('-', rf);
590 fprintf(rf, "\n\nVstart Start Stop "
591 "Length Class Name\n");
592 list_for_each(s, sections) {
593 fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
594 s->vstart, s->start, s->start + s->length,
595 s->length);
596 if (s->flags & TYPE_PROGBITS)
597 fprintf(rf, "progbits ");
598 else
599 fprintf(rf, "nobits ");
600 fprintf(rf, "%s\n", s->name);
602 fprintf(rf, "\n");
604 /* Display detailed section information. */
605 if (map_control & MAP_SECTIONS) {
606 fprintf(rf, "-- Sections (detailed) ");
607 for (h = 56; h; h--)
608 fputc('-', rf);
609 fprintf(rf, "\n\n");
610 list_for_each(s, sections) {
611 fprintf(rf, "---- Section %s ", s->name);
612 for (h = 65 - strlen(s->name); h; h--)
613 fputc('-', rf);
614 fprintf(rf, "\n\nclass: ");
615 if (s->flags & TYPE_PROGBITS)
616 fprintf(rf, "progbits");
617 else
618 fprintf(rf, "nobits");
619 fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
620 "\nalign: ", s->length, s->start);
621 if (s->flags & ALIGN_DEFINED)
622 fprintf(rf, "%16"PRIX64"", s->align);
623 else
624 fputs(not_defined, rf);
625 fprintf(rf, "\nfollows: ");
626 if (s->flags & FOLLOWS_DEFINED)
627 fprintf(rf, "%s", s->follows);
628 else
629 fputs(not_defined, rf);
630 fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
631 if (s->flags & VALIGN_DEFINED)
632 fprintf(rf, "%16"PRIX64"", s->valign);
633 else
634 fputs(not_defined, rf);
635 fprintf(rf, "\nvfollows: ");
636 if (s->flags & VFOLLOWS_DEFINED)
637 fprintf(rf, "%s", s->vfollows);
638 else
639 fputs(not_defined, rf);
640 fprintf(rf, "\n\n");
643 /* Display symbols information. */
644 if (map_control & MAP_SYMBOLS) {
645 int32_t segment;
646 int64_t offset;
647 bool found_label;
649 fprintf(rf, "-- Symbols ");
650 for (h = 68; h; h--)
651 fputc('-', rf);
652 fprintf(rf, "\n\n");
653 if (no_seg_labels) {
654 fprintf(rf, "---- No Section ");
655 for (h = 63; h; h--)
656 fputc('-', rf);
657 fprintf(rf, "\n\nValue Name\n");
658 list_for_each(l, no_seg_labels) {
659 found_label = lookup_label(l->name, &segment, &offset);
660 nasm_assert(found_label);
661 fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
663 fprintf(rf, "\n\n");
665 list_for_each(s, sections) {
666 if (s->labels) {
667 fprintf(rf, "---- Section %s ", s->name);
668 for (h = 65 - strlen(s->name); h; h--)
669 fputc('-', rf);
670 fprintf(rf, "\n\nReal Virtual Name\n");
671 list_for_each(l, s->labels) {
672 found_label = lookup_label(l->name, &segment, &offset);
673 nasm_assert(found_label);
674 fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
675 s->start + offset, s->vstart + offset,
676 l->name);
678 fprintf(rf, "\n");
684 /* Close the report file. */
685 if (map_control && (rf != stdout) && (rf != stderr))
686 fclose(rf);
688 /* Step 8: Release all allocated memory. */
690 /* Free sections, label pointer structs, etc.. */
691 while (sections) {
692 s = sections;
693 sections = s->next;
694 saa_free(s->contents);
695 nasm_free(s->name);
696 if (s->flags & FOLLOWS_DEFINED)
697 nasm_free(s->follows);
698 if (s->flags & VFOLLOWS_DEFINED)
699 nasm_free(s->vfollows);
700 while (s->labels) {
701 l = s->labels;
702 s->labels = l->next;
703 nasm_free(l);
705 nasm_free(s);
708 /* Free no-section labels. */
709 while (no_seg_labels) {
710 l = no_seg_labels;
711 no_seg_labels = l->next;
712 nasm_free(l);
715 /* Free relocation structures. */
716 while (relocs) {
717 r = relocs->next;
718 nasm_free(relocs);
719 relocs = r;
723 static void bin_out(int32_t segto, const void *data,
724 enum out_type type, uint64_t size,
725 int32_t segment, int32_t wrt)
727 uint8_t *p, mydata[8];
728 struct Section *s;
730 if (wrt != NO_SEG) {
731 wrt = NO_SEG; /* continue to do _something_ */
732 nasm_nonfatal("WRT not supported by binary output format");
735 /* Find the segment we are targeting. */
736 s = find_section_by_index(segto);
737 if (!s)
738 nasm_panic("code directed to nonexistent segment?");
740 /* "Smart" section-type adaptation code. */
741 if (!(s->flags & TYPE_DEFINED)) {
742 if (type == OUT_RESERVE)
743 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
744 else
745 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
748 if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
749 nasm_warn("attempt to initialize memory in a"
750 " nobits section: ignored");
752 switch (type) {
753 case OUT_ADDRESS:
755 int asize = abs((int)size);
757 if (segment != NO_SEG && !find_section_by_index(segment)) {
758 if (segment % 2)
759 nasm_nonfatal("binary output format does not support"
760 " segment base references");
761 else
762 nasm_nonfatal("binary output format does not support"
763 " external references");
764 segment = NO_SEG;
766 if (s->flags & TYPE_PROGBITS) {
767 if (segment != NO_SEG)
768 add_reloc(s, asize, segment, -1L);
769 p = mydata;
770 WRITEADDR(p, *(int64_t *)data, asize);
771 saa_wbytes(s->contents, mydata, asize);
775 * Reassign size with sign dropped, we will need it
776 * for section length calculation.
778 size = asize;
779 break;
782 case OUT_RAWDATA:
783 if (s->flags & TYPE_PROGBITS)
784 saa_wbytes(s->contents, data, size);
785 break;
787 case OUT_RESERVE:
788 if (s->flags & TYPE_PROGBITS) {
789 nasm_warn("uninitialized space declared in"
790 " %s section: zeroing", s->name);
791 saa_wbytes(s->contents, NULL, size);
793 break;
795 case OUT_REL1ADR:
796 case OUT_REL2ADR:
797 case OUT_REL4ADR:
798 case OUT_REL8ADR:
800 int64_t addr = *(int64_t *)data - size;
801 size = realsize(type, size);
802 if (segment != NO_SEG && !find_section_by_index(segment)) {
803 if (segment % 2)
804 nasm_nonfatal("binary output format does not support"
805 " segment base references");
806 else
807 nasm_nonfatal("binary output format does not support"
808 " external references");
809 segment = NO_SEG;
811 if (s->flags & TYPE_PROGBITS) {
812 add_reloc(s, size, segment, segto);
813 p = mydata;
814 WRITEADDR(p, addr - s->length, size);
815 saa_wbytes(s->contents, mydata, size);
817 break;
820 default:
821 nasm_nonfatal("unsupported relocation type %d\n", type);
822 break;
825 s->length += size;
828 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
829 int is_global, char *special)
831 (void)segment; /* Don't warn that this parameter is unused */
832 (void)offset; /* Don't warn that this parameter is unused */
834 if (special)
835 nasm_nonfatal("binary format does not support any"
836 " special symbol types");
837 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
838 nasm_nonfatal("unrecognised special symbol `%s'", name);
839 else if (is_global == 2)
840 nasm_nonfatal("binary output format does not support common"
841 " variables");
842 else {
843 struct Section *s;
844 struct bin_label ***ltp;
846 /* Remember label definition so we can look it up later when
847 * creating the map file. */
848 s = find_section_by_index(segment);
849 if (s)
850 ltp = &(s->labels_end);
851 else
852 ltp = &nsl_tail;
853 (**ltp) = nasm_malloc(sizeof(struct bin_label));
854 (**ltp)->name = name;
855 (**ltp)->next = NULL;
856 *ltp = &((**ltp)->next);
861 /* These constants and the following function are used
862 * by bin_secname() to parse attribute assignments. */
864 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
865 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
866 ATTRIB_NOBITS, ATTRIB_PROGBITS
869 static int bin_read_attribute(char **line, int *attribute,
870 uint64_t *value)
872 expr *e;
873 int attrib_name_size;
874 struct tokenval tokval;
875 char *exp;
877 /* Skip whitespace. */
878 while (**line && nasm_isspace(**line))
879 (*line)++;
880 if (!**line)
881 return 0;
883 /* Figure out what attribute we're reading. */
884 if (!nasm_strnicmp(*line, "align=", 6)) {
885 *attribute = ATTRIB_ALIGN;
886 attrib_name_size = 6;
887 } else {
888 if (!nasm_strnicmp(*line, "start=", 6)) {
889 *attribute = ATTRIB_START;
890 attrib_name_size = 6;
891 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
892 *attribute = ATTRIB_FOLLOWS;
893 *line += 8;
894 return 1;
895 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
896 *attribute = ATTRIB_VSTART;
897 attrib_name_size = 7;
898 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
899 *attribute = ATTRIB_VALIGN;
900 attrib_name_size = 7;
901 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
902 *attribute = ATTRIB_VFOLLOWS;
903 *line += 9;
904 return 1;
905 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
906 (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
907 *attribute = ATTRIB_NOBITS;
908 *line += 6;
909 return 1;
910 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
911 (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
912 *attribute = ATTRIB_PROGBITS;
913 *line += 8;
914 return 1;
915 } else
916 return 0;
919 /* Find the end of the expression. */
920 if ((*line)[attrib_name_size] != '(') {
921 /* Single term (no parenthesis). */
922 exp = *line += attrib_name_size;
923 while (**line && !nasm_isspace(**line))
924 (*line)++;
925 if (**line) {
926 **line = '\0';
927 (*line)++;
929 } else {
930 char c;
931 int pcount = 1;
933 /* Full expression (delimited by parenthesis) */
934 exp = *line += attrib_name_size + 1;
935 while (1) {
936 (*line) += strcspn(*line, "()'\"");
937 if (**line == '(') {
938 ++(*line);
939 ++pcount;
941 if (**line == ')') {
942 ++(*line);
943 --pcount;
944 if (!pcount)
945 break;
947 if ((**line == '"') || (**line == '\'')) {
948 c = **line;
949 while (**line) {
950 ++(*line);
951 if (**line == c)
952 break;
954 if (!**line) {
955 nasm_nonfatal("invalid syntax in `section' directive");
956 return -1;
958 ++(*line);
960 if (!**line) {
961 nasm_nonfatal("expecting `)'");
962 return -1;
965 *(*line - 1) = '\0'; /* Terminate the expression. */
968 /* Check for no value given. */
969 if (!*exp) {
970 nasm_warn("No value given to attribute in"
971 " `section' directive");
972 return -1;
975 /* Read and evaluate the expression. */
976 stdscan_reset();
977 stdscan_set(exp);
978 tokval.t_type = TOKEN_INVALID;
979 e = evaluate(stdscan, NULL, &tokval, NULL, 1, NULL);
980 if (e) {
981 if (!is_really_simple(e)) {
982 nasm_nonfatal("section attribute value must be"
983 " a critical expression");
984 return -1;
986 } else {
987 nasm_nonfatal("Invalid attribute value"
988 " specified in `section' directive.");
989 return -1;
991 *value = (uint64_t)reloc_value(e);
992 return 1;
995 static void bin_sectalign(int32_t seg, unsigned int value)
997 struct Section *s = find_section_by_index(seg);
999 if (!s || !is_power2(value))
1000 return;
1002 if (value > s->align)
1003 s->align = value;
1005 if (!(s->flags & ALIGN_DEFINED))
1006 s->flags |= ALIGN_DEFINED;
1009 static void bin_assign_attributes(struct Section *sec, char *astring)
1011 int attribute, check;
1012 uint64_t value;
1013 char *p;
1015 while (1) { /* Get the next attribute. */
1016 check = bin_read_attribute(&astring, &attribute, &value);
1017 /* Skip bad attribute. */
1018 if (check == -1)
1019 continue;
1020 /* Unknown section attribute, so skip it and warn the user. */
1021 if (!check) {
1022 if (!*astring)
1023 break; /* End of line. */
1024 else {
1025 p = astring;
1026 while (*astring && !nasm_isspace(*astring))
1027 astring++;
1028 if (*astring) {
1029 *astring = '\0';
1030 astring++;
1032 nasm_warn("ignoring unknown section attribute: \"%s\"", p);
1034 continue;
1037 switch (attribute) { /* Handle nobits attribute. */
1038 case ATTRIB_NOBITS:
1039 if ((sec->flags & TYPE_DEFINED)
1040 && (sec->flags & TYPE_PROGBITS))
1041 nasm_nonfatal("attempt to change section type"
1042 " from progbits to nobits");
1043 else
1044 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1045 continue;
1047 /* Handle progbits attribute. */
1048 case ATTRIB_PROGBITS:
1049 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1050 nasm_nonfatal("attempt to change section type"
1051 " from nobits to progbits");
1052 else
1053 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1054 continue;
1056 /* Handle align attribute. */
1057 case ATTRIB_ALIGN:
1058 if (!value || ((value - 1) & value)) {
1059 nasm_nonfatal("argument to `align' is not a power of two");
1060 } else {
1062 * Alignment is already satisfied if
1063 * the previous align value is greater
1065 if ((sec->flags & ALIGN_DEFINED) && (value < sec->align))
1066 value = sec->align;
1068 /* Don't allow a conflicting align value. */
1069 if ((sec->flags & START_DEFINED) && (sec->start & (value - 1))) {
1070 nasm_nonfatal("`align' value conflicts with section start address");
1071 } else {
1072 sec->align = value;
1073 sec->flags |= ALIGN_DEFINED;
1076 continue;
1078 /* Handle valign attribute. */
1079 case ATTRIB_VALIGN:
1080 if (!value || ((value - 1) & value))
1081 nasm_nonfatal("argument to `valign' is not a power of two");
1082 else { /* Alignment is already satisfied if the previous
1083 * align value is greater. */
1084 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1085 value = sec->valign;
1087 /* Don't allow a conflicting valign value. */
1088 if ((sec->flags & VSTART_DEFINED)
1089 && (sec->vstart & (value - 1)))
1090 nasm_nonfatal("`valign' value conflicts with `vstart' address");
1091 else {
1092 sec->valign = value;
1093 sec->flags |= VALIGN_DEFINED;
1096 continue;
1098 /* Handle start attribute. */
1099 case ATTRIB_START:
1100 if (sec->flags & FOLLOWS_DEFINED)
1101 nasm_nonfatal("cannot combine `start' and `follows'"
1102 " section attributes");
1103 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1104 nasm_nonfatal("section start address redefined");
1105 else {
1106 sec->start = value;
1107 sec->flags |= START_DEFINED;
1108 if (sec->flags & ALIGN_DEFINED) {
1109 if (sec->start & (sec->align - 1))
1110 nasm_nonfatal("`start' address conflicts"
1111 " with section alignment");
1112 sec->flags ^= ALIGN_DEFINED;
1115 continue;
1117 /* Handle vstart attribute. */
1118 case ATTRIB_VSTART:
1119 if (sec->flags & VFOLLOWS_DEFINED)
1120 nasm_nonfatal("cannot combine `vstart' and `vfollows'"
1121 " section attributes");
1122 else if ((sec->flags & VSTART_DEFINED)
1123 && (value != sec->vstart))
1124 nasm_nonfatal("section virtual start address"
1125 " (vstart) redefined");
1126 else {
1127 sec->vstart = value;
1128 sec->flags |= VSTART_DEFINED;
1129 if (sec->flags & VALIGN_DEFINED) {
1130 if (sec->vstart & (sec->valign - 1))
1131 nasm_nonfatal("`vstart' address conflicts"
1132 " with `valign' value");
1133 sec->flags ^= VALIGN_DEFINED;
1136 continue;
1138 /* Handle follows attribute. */
1139 case ATTRIB_FOLLOWS:
1140 p = astring;
1141 astring += strcspn(astring, " \t");
1142 if (astring == p)
1143 nasm_nonfatal("expecting section name for `follows'"
1144 " attribute");
1145 else {
1146 *(astring++) = '\0';
1147 if (sec->flags & START_DEFINED)
1148 nasm_nonfatal("cannot combine `start' and `follows'"
1149 " section attributes");
1150 sec->follows = nasm_strdup(p);
1151 sec->flags |= FOLLOWS_DEFINED;
1153 continue;
1155 /* Handle vfollows attribute. */
1156 case ATTRIB_VFOLLOWS:
1157 if (sec->flags & VSTART_DEFINED)
1158 nasm_nonfatal("cannot combine `vstart' and `vfollows'"
1159 " section attributes");
1160 else {
1161 p = astring;
1162 astring += strcspn(astring, " \t");
1163 if (astring == p)
1164 nasm_nonfatal("expecting section name for `vfollows'"
1165 " attribute");
1166 else {
1167 *(astring++) = '\0';
1168 sec->vfollows = nasm_strdup(p);
1169 sec->flags |= VFOLLOWS_DEFINED;
1172 continue;
1177 static void bin_define_section_labels(void)
1179 static int labels_defined = 0;
1180 struct Section *sec;
1181 char *label_name;
1182 size_t base_len;
1184 if (labels_defined)
1185 return;
1186 list_for_each(sec, sections) {
1187 base_len = strlen(sec->name) + 8;
1188 label_name = nasm_malloc(base_len + 8);
1189 strcpy(label_name, "section.");
1190 strcpy(label_name + 8, sec->name);
1192 /* section.<name>.start */
1193 strcpy(label_name + base_len, ".start");
1194 define_label(label_name, sec->start_index, 0L, false);
1196 /* section.<name>.vstart */
1197 strcpy(label_name + base_len, ".vstart");
1198 define_label(label_name, sec->vstart_index, 0L, false);
1200 nasm_free(label_name);
1202 labels_defined = 1;
1205 static int32_t bin_secname(char *name, int pass, int *bits)
1207 char *p;
1208 struct Section *sec;
1210 /* bin_secname is called with *name = NULL at the start of each
1211 * pass. Use this opportunity to establish the default section
1212 * (default is BITS-16 ".text" segment).
1214 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1215 origin_defined = 0;
1216 list_for_each(sec, sections)
1217 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1218 ALIGN_DEFINED | VALIGN_DEFINED);
1220 /* Define section start and vstart labels. */
1221 if (pass != 1)
1222 bin_define_section_labels();
1224 /* Establish the default (.text) section. */
1225 *bits = 16;
1226 sec = find_section_by_name(".text");
1227 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1228 return sec->vstart_index;
1231 /* Attempt to find the requested section. If it does not
1232 * exist, create it. */
1233 p = name;
1234 while (*p && !nasm_isspace(*p))
1235 p++;
1236 if (*p)
1237 *p++ = '\0';
1238 sec = find_section_by_name(name);
1239 if (!sec) {
1240 sec = create_section(name);
1241 if (!strcmp(name, ".data"))
1242 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1243 else if (!strcmp(name, ".bss")) {
1244 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1245 sec->prev = NULL;
1249 /* Handle attribute assignments. */
1250 if (pass != 1)
1251 bin_assign_attributes(sec, p);
1253 #ifndef ABIN_SMART_ADAPT
1254 /* The following line disables smart adaptation of
1255 * PROGBITS/NOBITS section types (it forces sections to
1256 * default to PROGBITS). */
1257 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1258 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1259 #endif
1261 return sec->vstart_index;
1264 static enum directive_result
1265 bin_directive(enum directive directive, char *args, int pass)
1267 switch (directive) {
1268 case D_ORG:
1270 struct tokenval tokval;
1271 uint64_t value;
1272 expr *e;
1274 stdscan_reset();
1275 stdscan_set(args);
1276 tokval.t_type = TOKEN_INVALID;
1277 e = evaluate(stdscan, NULL, &tokval, NULL, 1, NULL);
1278 if (e) {
1279 if (!is_really_simple(e))
1280 nasm_nonfatal("org value must be a critical"
1281 " expression");
1282 else {
1283 value = reloc_value(e);
1284 /* Check for ORG redefinition. */
1285 if (origin_defined && (value != origin))
1286 nasm_nonfatal("program origin redefined");
1287 else {
1288 origin = value;
1289 origin_defined = 1;
1292 } else
1293 nasm_nonfatal("No or invalid offset specified"
1294 " in ORG directive.");
1295 return DIRR_OK;
1297 case D_MAP:
1299 /* The 'map' directive allows the user to generate section
1300 * and symbol information to stdout, stderr, or to a file. */
1301 char *p;
1303 if (pass != 1)
1304 return DIRR_OK;
1305 args += strspn(args, " \t");
1306 while (*args) {
1307 p = args;
1308 args += strcspn(args, " \t");
1309 if (*args != '\0')
1310 *(args++) = '\0';
1311 if (!nasm_stricmp(p, "all"))
1312 map_control |=
1313 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1314 else if (!nasm_stricmp(p, "brief"))
1315 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1316 else if (!nasm_stricmp(p, "sections"))
1317 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1318 else if (!nasm_stricmp(p, "segments"))
1319 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1320 else if (!nasm_stricmp(p, "symbols"))
1321 map_control |= MAP_SYMBOLS;
1322 else if (!rf) {
1323 if (!nasm_stricmp(p, "stdout"))
1324 rf = stdout;
1325 else if (!nasm_stricmp(p, "stderr"))
1326 rf = stderr;
1327 else { /* Must be a filename. */
1328 rf = nasm_open_write(p, NF_TEXT);
1329 if (!rf) {
1330 nasm_warn("unable to open map file `%s'", p);
1331 map_control = 0;
1332 return DIRR_OK;
1335 } else
1336 nasm_warn("map file already specified");
1338 if (map_control == 0)
1339 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1340 if (!rf)
1341 rf = stdout;
1342 return DIRR_OK;
1344 default:
1345 return DIRR_UNKNOWN;
1349 const struct ofmt of_bin, of_ith, of_srec;
1350 static void binfmt_init(void);
1351 static void do_output_bin(void);
1352 static void do_output_ith(void);
1353 static void do_output_srec(void);
1355 static void bin_init(void)
1357 do_output = do_output_bin;
1358 binfmt_init();
1361 static void ith_init(void)
1363 do_output = do_output_ith;
1364 binfmt_init();
1367 static void srec_init(void)
1369 do_output = do_output_srec;
1370 binfmt_init();
1373 static void binfmt_init(void)
1375 relocs = NULL;
1376 reloctail = &relocs;
1377 origin_defined = 0;
1378 no_seg_labels = NULL;
1379 nsl_tail = &no_seg_labels;
1381 /* Create default section (.text). */
1382 sections = last_section = nasm_zalloc(sizeof(struct Section));
1383 last_section->name = nasm_strdup(".text");
1384 last_section->contents = saa_init(1L);
1385 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1386 last_section->labels_end = &(last_section->labels);
1387 last_section->start_index = seg_alloc();
1388 last_section->vstart_index = seg_alloc();
1391 /* Generate binary file output */
1392 static void do_output_bin(void)
1394 struct Section *s;
1395 uint64_t addr = origin;
1397 /* Write the progbits sections to the output file. */
1398 list_for_each(s, sections) {
1399 /* Skip non-progbits sections */
1400 if (!(s->flags & TYPE_PROGBITS))
1401 continue;
1402 /* Skip zero-length sections */
1403 if (s->length == 0)
1404 continue;
1406 /* Pad the space between sections. */
1407 nasm_assert(addr <= s->start);
1408 fwritezero(s->start - addr, ofile);
1410 /* Write the section to the output file. */
1411 saa_fpwrite(s->contents, ofile);
1413 /* Keep track of the current file position */
1414 addr = s->start + s->length;
1418 /* Generate Intel hex file output */
1419 static void write_ith_record(unsigned int len, uint16_t addr,
1420 uint8_t type, void *data)
1422 char buf[1+2+4+2+255*2+2+2];
1423 char *p = buf;
1424 uint8_t csum, *dptr = data;
1425 unsigned int i;
1427 nasm_assert(len <= 255);
1429 csum = len + addr + (addr >> 8) + type;
1430 for (i = 0; i < len; i++)
1431 csum += dptr[i];
1432 csum = -csum;
1434 p += sprintf(p, ":%02X%04X%02X", len, addr, type);
1435 for (i = 0; i < len; i++)
1436 p += sprintf(p, "%02X", dptr[i]);
1437 p += sprintf(p, "%02X\n", csum);
1439 nasm_write(buf, p-buf, ofile);
1442 static void do_output_ith(void)
1444 uint8_t buf[32];
1445 struct Section *s;
1446 uint64_t addr, hiaddr, hilba;
1447 uint64_t length;
1448 unsigned int chunk;
1450 /* Write the progbits sections to the output file. */
1451 hilba = 0;
1452 list_for_each(s, sections) {
1453 /* Skip non-progbits sections */
1454 if (!(s->flags & TYPE_PROGBITS))
1455 continue;
1456 /* Skip zero-length sections */
1457 if (s->length == 0)
1458 continue;
1460 addr = s->start;
1461 length = s->length;
1462 saa_rewind(s->contents);
1464 while (length) {
1465 hiaddr = addr >> 16;
1466 if (hiaddr != hilba) {
1467 buf[0] = hiaddr >> 8;
1468 buf[1] = hiaddr;
1469 write_ith_record(2, 0, 4, buf);
1470 hilba = hiaddr;
1473 chunk = 32 - (addr & 31);
1474 if (length < chunk)
1475 chunk = length;
1477 saa_rnbytes(s->contents, buf, chunk);
1478 write_ith_record(chunk, (uint16_t)addr, 0, buf);
1480 addr += chunk;
1481 length -= chunk;
1485 /* Write closing record */
1486 write_ith_record(0, 0, 1, NULL);
1489 /* Generate Motorola S-records */
1490 static void write_srecord(unsigned int len, unsigned int alen,
1491 uint32_t addr, uint8_t type, void *data)
1493 char buf[2+2+8+255*2+2+2];
1494 char *p = buf;
1495 uint8_t csum, *dptr = data;
1496 unsigned int i;
1498 nasm_assert(len <= 255);
1500 switch (alen) {
1501 case 2:
1502 addr &= 0xffff;
1503 break;
1504 case 3:
1505 addr &= 0xffffff;
1506 break;
1507 case 4:
1508 break;
1509 default:
1510 nasm_assert(0);
1511 break;
1514 csum = (len+alen+1) + addr + (addr >> 8) + (addr >> 16) + (addr >> 24);
1515 for (i = 0; i < len; i++)
1516 csum += dptr[i];
1517 csum = 0xff-csum;
1519 p += sprintf(p, "S%c%02X%0*X", type, len+alen+1, alen*2, addr);
1520 for (i = 0; i < len; i++)
1521 p += sprintf(p, "%02X", dptr[i]);
1522 p += sprintf(p, "%02X\n", csum);
1524 nasm_write(buf, p-buf, ofile);
1527 static void do_output_srec(void)
1529 uint8_t buf[32];
1530 struct Section *s;
1531 uint64_t addr, maxaddr;
1532 uint64_t length;
1533 int alen;
1534 unsigned int chunk;
1535 char dtype, etype;
1537 maxaddr = 0;
1538 list_for_each(s, sections) {
1539 /* Skip non-progbits sections */
1540 if (!(s->flags & TYPE_PROGBITS))
1541 continue;
1542 /* Skip zero-length sections */
1543 if (s->length == 0)
1544 continue;
1546 addr = s->start + s->length - 1;
1547 if (addr > maxaddr)
1548 maxaddr = addr;
1551 if (maxaddr <= 0xffff) {
1552 alen = 2;
1553 dtype = '1'; /* S1 = 16-bit data */
1554 etype = '9'; /* S9 = 16-bit end */
1555 } else if (maxaddr <= 0xffffff) {
1556 alen = 3;
1557 dtype = '2'; /* S2 = 24-bit data */
1558 etype = '8'; /* S8 = 24-bit end */
1559 } else {
1560 alen = 4;
1561 dtype = '3'; /* S3 = 32-bit data */
1562 etype = '7'; /* S7 = 32-bit end */
1565 /* Write head record */
1566 write_srecord(0, 2, 0, '0', NULL);
1568 /* Write the progbits sections to the output file. */
1569 list_for_each(s, sections) {
1570 /* Skip non-progbits sections */
1571 if (!(s->flags & TYPE_PROGBITS))
1572 continue;
1573 /* Skip zero-length sections */
1574 if (s->length == 0)
1575 continue;
1577 addr = s->start;
1578 length = s->length;
1579 saa_rewind(s->contents);
1581 while (length) {
1582 chunk = 32 - (addr & 31);
1583 if (length < chunk)
1584 chunk = length;
1586 saa_rnbytes(s->contents, buf, chunk);
1587 write_srecord(chunk, alen, (uint32_t)addr, dtype, buf);
1589 addr += chunk;
1590 length -= chunk;
1594 /* Write closing record */
1595 write_srecord(0, alen, 0, etype, NULL);
1599 const struct ofmt of_bin = {
1600 "flat-form binary files (e.g. DOS .COM, .SYS)",
1601 "bin",
1605 null_debug_arr,
1606 &null_debug_form,
1607 bin_stdmac,
1608 bin_init,
1609 null_reset,
1610 nasm_do_legacy_output,
1611 bin_out,
1612 bin_deflabel,
1613 bin_secname,
1614 NULL,
1615 bin_sectalign,
1616 null_segbase,
1617 bin_directive,
1618 bin_cleanup,
1619 NULL /* pragma list */
1622 const struct ofmt of_ith = {
1623 "Intel hex",
1624 "ith",
1625 ".ith", /* really should have been ".hex"... */
1626 OFMT_TEXT,
1628 null_debug_arr,
1629 &null_debug_form,
1630 bin_stdmac,
1631 ith_init,
1632 null_reset,
1633 nasm_do_legacy_output,
1634 bin_out,
1635 bin_deflabel,
1636 bin_secname,
1637 NULL,
1638 bin_sectalign,
1639 null_segbase,
1640 bin_directive,
1641 bin_cleanup,
1642 NULL /* pragma list */
1645 const struct ofmt of_srec = {
1646 "Motorola S-records",
1647 "srec",
1648 ".srec",
1649 OFMT_TEXT,
1651 null_debug_arr,
1652 &null_debug_form,
1653 bin_stdmac,
1654 srec_init,
1655 null_reset,
1656 nasm_do_legacy_output,
1657 bin_out,
1658 bin_deflabel,
1659 bin_secname,
1660 NULL,
1661 bin_sectalign,
1662 null_segbase,
1663 bin_directive,
1664 bin_cleanup,
1665 NULL /* pragma list */
1668 #endif /* #ifdef OF_BIN */