rbtree: add rb_search_exact()
[nasm.git] / output / outbin.c
blob29659f00105f89efd48b4a4146dd87745368fcad
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 "nctype.h"
80 #include "nasm.h"
81 #include "nasmlib.h"
82 #include "error.h"
83 #include "saa.h"
84 #include "stdscan.h"
85 #include "labels.h"
86 #include "eval.h"
87 #include "outform.h"
88 #include "outlib.h"
90 #ifdef OF_BIN
92 static FILE *rf = NULL;
93 static void (*do_output)(void);
95 /* Section flags keep track of which attributes the user has defined. */
96 #define START_DEFINED 0x001
97 #define ALIGN_DEFINED 0x002
98 #define FOLLOWS_DEFINED 0x004
99 #define VSTART_DEFINED 0x008
100 #define VALIGN_DEFINED 0x010
101 #define VFOLLOWS_DEFINED 0x020
102 #define TYPE_DEFINED 0x040
103 #define TYPE_PROGBITS 0x080
104 #define TYPE_NOBITS 0x100
106 /* This struct is used to keep track of symbols for map-file generation. */
107 static struct bin_label {
108 char *name;
109 struct bin_label *next;
110 } *no_seg_labels, **nsl_tail;
112 static struct Section {
113 char *name;
114 struct SAA *contents;
115 int64_t length; /* section length in bytes */
117 /* Section attributes */
118 int flags; /* see flag definitions above */
119 uint64_t align; /* section alignment */
120 uint64_t valign; /* notional section alignment */
121 uint64_t start; /* section start address */
122 uint64_t vstart; /* section virtual start address */
123 char *follows; /* the section that this one will follow */
124 char *vfollows; /* the section that this one will notionally follow */
125 int32_t start_index; /* NASM section id for non-relocated version */
126 int32_t vstart_index; /* the NASM section id */
128 struct bin_label *labels; /* linked-list of label handles for map output. */
129 struct bin_label **labels_end; /* Holds address of end of labels list. */
130 struct Section *prev; /* Points to previous section (implicit follows). */
131 struct Section *next; /* This links sections with a defined start address. */
133 /* The extended bin format allows for sections to have a "virtual"
134 * start address. This is accomplished by creating two sections:
135 * one beginning at the Load Memory Address and the other beginning
136 * at the Virtual Memory Address. The LMA section is only used to
137 * define the section.<section_name>.start label, but there isn't
138 * any other good way for us to handle that label.
141 } *sections, *last_section;
143 static struct Reloc {
144 struct Reloc *next;
145 int32_t posn;
146 int32_t bytes;
147 int32_t secref;
148 int32_t secrel;
149 struct Section *target;
150 } *relocs, **reloctail;
152 static uint64_t origin;
153 static int origin_defined;
155 /* Stuff we need for map-file generation. */
156 #define MAP_ORIGIN 1
157 #define MAP_SUMMARY 2
158 #define MAP_SECTIONS 4
159 #define MAP_SYMBOLS 8
160 static int map_control = 0;
162 extern macros_t bin_stdmac[];
164 static void add_reloc(struct Section *s, int32_t bytes, int32_t secref,
165 int32_t secrel)
167 struct Reloc *r;
169 r = *reloctail = nasm_malloc(sizeof(struct Reloc));
170 reloctail = &r->next;
171 r->next = NULL;
172 r->posn = s->length;
173 r->bytes = bytes;
174 r->secref = secref;
175 r->secrel = secrel;
176 r->target = s;
179 static struct Section *find_section_by_name(const char *name)
181 struct Section *s;
183 list_for_each(s, sections)
184 if (!strcmp(s->name, name))
185 break;
186 return s;
189 static struct Section *find_section_by_index(int32_t index)
191 struct Section *s;
193 list_for_each(s, sections)
194 if ((index == s->vstart_index) || (index == s->start_index))
195 break;
196 return s;
199 static struct Section *create_section(char *name)
201 struct Section *s = nasm_zalloc(sizeof(*s));
203 s->prev = last_section;
204 s->name = nasm_strdup(name);
205 s->labels_end = &(s->labels);
206 s->contents = saa_init(1L);
208 /* Register our sections with NASM. */
209 s->vstart_index = seg_alloc();
210 s->start_index = seg_alloc();
212 /* FIXME: Append to a tail, we need some helper */
213 last_section->next = s;
214 last_section = s;
216 return last_section;
219 static void bin_cleanup(void)
221 struct Section *g, **gp;
222 struct Section *gs = NULL, **gsp;
223 struct Section *s, **sp;
224 struct Section *nobits = NULL, **nt;
225 struct Section *last_progbits;
226 struct bin_label *l;
227 struct Reloc *r;
228 uint64_t pend;
229 int h;
231 if (debug_level(1)) {
232 nasm_debug("bin_cleanup: Sections were initially referenced in this order:\n");
233 for (h = 0, s = sections; s; h++, s = s->next)
234 nasm_debug("%i. %s\n", h, s->name);
237 /* Assembly has completed, so now we need to generate the output file.
238 * Step 1: Separate progbits and nobits sections into separate lists.
239 * Step 2: Sort the progbits sections into their output order.
240 * Step 3: Compute start addresses for all progbits sections.
241 * Step 4: Compute vstart addresses for all sections.
242 * Step 5: Apply relocations.
243 * Step 6: Write the sections' data to the output file.
244 * Step 7: Generate the map file.
245 * Step 8: Release all allocated memory.
248 /* To do: Smart section-type adaptation could leave some empty sections
249 * without a defined type (progbits/nobits). Won't fix now since this
250 * feature will be disabled. */
252 /* Step 1: Split progbits and nobits sections into separate lists. */
254 nt = &nobits;
255 /* Move nobits sections into a separate list. Also pre-process nobits
256 * sections' attributes. */
257 for (sp = &sections->next, s = sections->next; s; s = *sp) { /* Skip progbits sections. */
258 if (s->flags & TYPE_PROGBITS) {
259 sp = &s->next;
260 continue;
262 /* Do some special pre-processing on nobits sections' attributes. */
263 if (s->flags & (START_DEFINED | ALIGN_DEFINED | FOLLOWS_DEFINED)) { /* Check for a mixture of real and virtual section attributes. */
264 if (s->flags & (VSTART_DEFINED | VALIGN_DEFINED |
265 VFOLLOWS_DEFINED))
266 nasm_fatal("cannot mix real and virtual attributes"
267 " in nobits section (%s)", s->name);
268 /* Real and virtual attributes mean the same thing for nobits sections. */
269 if (s->flags & START_DEFINED) {
270 s->vstart = s->start;
271 s->flags |= VSTART_DEFINED;
273 if (s->flags & ALIGN_DEFINED) {
274 s->valign = s->align;
275 s->flags |= VALIGN_DEFINED;
277 if (s->flags & FOLLOWS_DEFINED) {
278 s->vfollows = s->follows;
279 s->flags |= VFOLLOWS_DEFINED;
280 s->flags &= ~FOLLOWS_DEFINED;
283 /* Every section must have a start address. */
284 if (s->flags & VSTART_DEFINED) {
285 s->start = s->vstart;
286 s->flags |= START_DEFINED;
288 /* Move the section into the nobits list. */
289 *sp = s->next;
290 s->next = NULL;
291 *nt = s;
292 nt = &s->next;
295 /* Step 2: Sort the progbits sections into their output order. */
297 /* In Step 2 we move around sections in groups. A group
298 * begins with a section (group leader) that has a user-
299 * defined start address or follows section. The remainder
300 * of the group is made up of the sections that implicitly
301 * follow the group leader (i.e., they were defined after
302 * the group leader and were not given an explicit start
303 * address or follows section by the user). */
305 /* For anyone attempting to read this code:
306 * g (group) points to a group of sections, the first one of which has
307 * a user-defined start address or follows section.
308 * gp (g previous) holds the location of the pointer to g.
309 * gs (g scan) is a temp variable that we use to scan to the end of the group.
310 * gsp (gs previous) holds the location of the pointer to gs.
311 * nt (nobits tail) points to the nobits section-list tail.
314 /* Link all 'follows' groups to their proper position. To do
315 * this we need to know three things: the start of the group
316 * to relocate (g), the section it is following (s), and the
317 * end of the group we're relocating (gs). */
318 for (gp = &sections, g = sections; g; g = gs) { /* Find the next follows group that is out of place (g). */
319 if (!(g->flags & FOLLOWS_DEFINED)) {
320 while (g->next) {
321 if ((g->next->flags & FOLLOWS_DEFINED) &&
322 strcmp(g->name, g->next->follows))
323 break;
324 g = g->next;
326 if (!g->next)
327 break;
328 gp = &g->next;
329 g = g->next;
331 /* Find the section that this group follows (s). */
332 for (sp = &sections, s = sections;
333 s && strcmp(s->name, g->follows);
334 sp = &s->next, s = s->next) ;
335 if (!s)
336 nasm_fatal("section %s follows an invalid or"
337 " unknown section (%s)", g->name, g->follows);
338 if (s->next && (s->next->flags & FOLLOWS_DEFINED) &&
339 !strcmp(s->name, s->next->follows))
340 nasm_fatal("sections %s and %s can't both follow"
341 " section %s", g->name, s->next->name, s->name);
342 /* Find the end of the current follows group (gs). */
343 for (gsp = &g->next, gs = g->next;
344 gs && (gs != s) && !(gs->flags & START_DEFINED);
345 gsp = &gs->next, gs = gs->next) {
346 if (gs->next && (gs->next->flags & FOLLOWS_DEFINED) &&
347 strcmp(gs->name, gs->next->follows)) {
348 gsp = &gs->next;
349 gs = gs->next;
350 break;
353 /* Re-link the group after its follows section. */
354 *gsp = s->next;
355 s->next = g;
356 *gp = gs;
359 /* Link all 'start' groups to their proper position. Once
360 * again we need to know g, s, and gs (see above). The main
361 * difference is we already know g since we sort by moving
362 * groups from the 'unsorted' list into a 'sorted' list (g
363 * will always be the first section in the unsorted list). */
364 for (g = sections, sections = NULL; g; g = gs) { /* Find the section that we will insert this group before (s). */
365 for (sp = &sections, s = sections; s; sp = &s->next, s = s->next)
366 if ((s->flags & START_DEFINED) && (g->start < s->start))
367 break;
368 /* Find the end of the group (gs). */
369 for (gs = g->next, gsp = &g->next;
370 gs && !(gs->flags & START_DEFINED);
371 gsp = &gs->next, gs = gs->next) ;
372 /* Re-link the group before the target section. */
373 *sp = g;
374 *gsp = s;
377 /* Step 3: Compute start addresses for all progbits sections. */
379 /* Make sure we have an origin and a start address for the first section. */
380 if (origin_defined) {
381 if (sections->flags & START_DEFINED) {
382 /* Make sure this section doesn't begin before the origin. */
383 if (sections->start < origin)
384 nasm_fatal("section %s begins"
385 " before program origin", sections->name);
386 } else if (sections->flags & ALIGN_DEFINED) {
387 sections->start = ALIGN(origin, sections->align);
388 } else {
389 sections->start = origin;
391 } else {
392 if (!(sections->flags & START_DEFINED))
393 sections->start = 0;
394 origin = sections->start;
396 sections->flags |= START_DEFINED;
398 /* Make sure each section has an explicit start address. If it
399 * doesn't, then compute one based its alignment and the end of
400 * the previous section. */
401 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
402 * (has a defined start address, and is not zero length). */
403 if (g == s)
404 for (s = g->next;
405 s && ((s->length == 0) || !(s->flags & START_DEFINED));
406 s = s->next) ;
407 /* Compute the start address of this section, if necessary. */
408 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
409 if (!(g->flags & ALIGN_DEFINED)) {
410 g->align = 4;
411 g->flags |= ALIGN_DEFINED;
413 /* Set the section start address. */
414 g->start = ALIGN(pend, g->align);
415 g->flags |= START_DEFINED;
417 /* Ugly special case for progbits sections' virtual attributes:
418 * If there is a defined valign, but no vstart and no vfollows, then
419 * we valign after the previous progbits section. This case doesn't
420 * really make much sense for progbits sections with a defined start
421 * address, but it is possible and we must do *something*.
422 * Not-so-ugly special case:
423 * If a progbits section has no virtual attributes, we set the
424 * vstart equal to the start address. */
425 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
426 if (g->flags & VALIGN_DEFINED)
427 g->vstart = ALIGN(pend, g->valign);
428 else
429 g->vstart = g->start;
430 g->flags |= VSTART_DEFINED;
432 /* Ignore zero-length sections. */
433 if (g->start < pend)
434 continue;
435 /* Compute the span of this section. */
436 pend = g->start + g->length;
437 /* Check for section overlap. */
438 if (s) {
439 if (s->start < origin)
440 nasm_fatal("section %s beings before program origin",
441 s->name);
442 if (g->start > s->start)
443 nasm_fatal("sections %s ~ %s and %s overlap!",
444 gs->name, g->name, s->name);
445 if (pend > s->start)
446 nasm_fatal("sections %s and %s overlap!",
447 g->name, s->name);
449 /* Remember this section as the latest >0 length section. */
450 gs = g;
453 /* Step 4: Compute vstart addresses for all sections. */
455 /* Attach the nobits sections to the end of the progbits sections. */
456 for (s = sections; s->next; s = s->next) ;
457 s->next = nobits;
458 last_progbits = s;
460 * Scan for sections that don't have a vstart address. If we find
461 * one we'll attempt to compute its vstart. If we can't compute
462 * the vstart, we leave it alone and come back to it in a
463 * subsequent scan. We continue scanning and re-scanning until
464 * we've gone one full cycle without computing any vstarts.
466 do { /* Do one full scan of the sections list. */
467 for (h = 0, g = sections; g; g = g->next) {
468 if (g->flags & VSTART_DEFINED)
469 continue;
470 /* Find the section that this one virtually follows. */
471 if (g->flags & VFOLLOWS_DEFINED) {
472 for (s = sections; s && strcmp(g->vfollows, s->name);
473 s = s->next) ;
474 if (!s)
475 nasm_fatal("section %s vfollows unknown section (%s)",
476 g->name, g->vfollows);
477 } else if (g->prev != NULL)
478 for (s = sections; s && (s != g->prev); s = s->next) ;
479 /* The .bss section is the only one with prev = NULL.
480 In this case we implicitly follow the last progbits
481 section. */
482 else
483 s = last_progbits;
485 /* If the section we're following has a vstart, we can proceed. */
486 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
487 if (!(g->flags & VALIGN_DEFINED)) {
488 g->valign = 4;
489 g->flags |= VALIGN_DEFINED;
491 /* Compute the vstart address. */
492 g->vstart = ALIGN(s->vstart + s->length, g->valign);
493 g->flags |= VSTART_DEFINED;
494 h++;
495 /* Start and vstart mean the same thing for nobits sections. */
496 if (g->flags & TYPE_NOBITS)
497 g->start = g->vstart;
500 } while (h);
502 /* Now check for any circular vfollows references, which will manifest
503 * themselves as sections without a defined vstart. */
504 for (h = 0, s = sections; s; s = s->next) {
505 if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
506 * no-no, but we'll throw a fatal one eventually so it's ok. */
507 nasm_nonfatal("cannot compute vstart for section %s", s->name);
508 h++;
511 if (h)
512 nasm_fatal("circular vfollows path detected");
514 if (debug_level(1)) {
515 nasm_debug("bin_cleanup: Confirm final section order for output file:\n");
516 for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
517 h++, s = s->next)
518 nasm_debug("%i. %s\n", h, s->name);
521 /* Step 5: Apply relocations. */
523 /* Prepare the sections for relocating. */
524 list_for_each(s, sections)
525 saa_rewind(s->contents);
526 /* Apply relocations. */
527 list_for_each(r, relocs) {
528 uint8_t *p, mydata[8];
529 int64_t l;
530 int b;
532 nasm_assert(r->bytes <= 8);
534 memset(mydata, 0, sizeof(mydata));
536 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
537 p = mydata;
538 l = 0;
539 for (b = r->bytes - 1; b >= 0; b--)
540 l = (l << 8) + mydata[b];
542 s = find_section_by_index(r->secref);
543 if (s) {
544 if (r->secref == s->start_index)
545 l += s->start;
546 else
547 l += s->vstart;
549 s = find_section_by_index(r->secrel);
550 if (s) {
551 if (r->secrel == s->start_index)
552 l -= s->start;
553 else
554 l -= s->vstart;
557 WRITEADDR(p, l, r->bytes);
558 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
561 /* Step 6: Write the section data to the output file. */
562 do_output();
564 /* Step 7: Generate the map file. */
566 if (map_control) {
567 static const char not_defined[] = "not defined";
569 /* Display input and output file names. */
570 fprintf(rf, "\n- NASM Map file ");
571 for (h = 63; h; h--)
572 fputc('-', rf);
573 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
574 inname, outname);
576 if (map_control & MAP_ORIGIN) { /* Display program origin. */
577 fprintf(rf, "-- Program origin ");
578 for (h = 61; h; h--)
579 fputc('-', rf);
580 fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
582 /* Display sections summary. */
583 if (map_control & MAP_SUMMARY) {
584 fprintf(rf, "-- Sections (summary) ");
585 for (h = 57; h; h--)
586 fputc('-', rf);
587 fprintf(rf, "\n\nVstart Start Stop "
588 "Length Class Name\n");
589 list_for_each(s, sections) {
590 fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
591 s->vstart, s->start, s->start + s->length,
592 s->length);
593 if (s->flags & TYPE_PROGBITS)
594 fprintf(rf, "progbits ");
595 else
596 fprintf(rf, "nobits ");
597 fprintf(rf, "%s\n", s->name);
599 fprintf(rf, "\n");
601 /* Display detailed section information. */
602 if (map_control & MAP_SECTIONS) {
603 fprintf(rf, "-- Sections (detailed) ");
604 for (h = 56; h; h--)
605 fputc('-', rf);
606 fprintf(rf, "\n\n");
607 list_for_each(s, sections) {
608 fprintf(rf, "---- Section %s ", s->name);
609 if (strlen(s->name) < 65)
610 for (h = 65 - strlen(s->name); h; h--)
611 fputc('-', rf);
612 fprintf(rf, "\n\nclass: ");
613 if (s->flags & TYPE_PROGBITS)
614 fprintf(rf, "progbits");
615 else
616 fprintf(rf, "nobits");
617 fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
618 "\nalign: ", s->length, s->start);
619 if (s->flags & ALIGN_DEFINED)
620 fprintf(rf, "%16"PRIX64"", s->align);
621 else
622 fputs(not_defined, rf);
623 fprintf(rf, "\nfollows: ");
624 if (s->flags & FOLLOWS_DEFINED)
625 fprintf(rf, "%s", s->follows);
626 else
627 fputs(not_defined, rf);
628 fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
629 if (s->flags & VALIGN_DEFINED)
630 fprintf(rf, "%16"PRIX64"", s->valign);
631 else
632 fputs(not_defined, rf);
633 fprintf(rf, "\nvfollows: ");
634 if (s->flags & VFOLLOWS_DEFINED)
635 fprintf(rf, "%s", s->vfollows);
636 else
637 fputs(not_defined, rf);
638 fprintf(rf, "\n\n");
641 /* Display symbols information. */
642 if (map_control & MAP_SYMBOLS) {
643 int32_t segment;
644 int64_t offset;
645 enum label_type found_label;
647 fprintf(rf, "-- Symbols ");
648 for (h = 68; h; h--)
649 fputc('-', rf);
650 fprintf(rf, "\n\n");
651 if (no_seg_labels) {
652 fprintf(rf, "---- No Section ");
653 for (h = 63; h; h--)
654 fputc('-', rf);
655 fprintf(rf, "\n\nValue Name\n");
656 list_for_each(l, no_seg_labels) {
657 found_label = lookup_label(l->name, &segment, &offset);
658 nasm_assert(found_label != LBL_none);
659 fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
661 fprintf(rf, "\n\n");
663 list_for_each(s, sections) {
664 if (s->labels) {
665 fprintf(rf, "---- Section %s ", s->name);
666 for (h = 65 - strlen(s->name); h; h--)
667 fputc('-', rf);
668 fprintf(rf, "\n\nReal Virtual Name\n");
669 list_for_each(l, s->labels) {
670 found_label = lookup_label(l->name, &segment, &offset);
671 nasm_assert(found_label != LBL_none);
672 fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
673 s->start + offset, s->vstart + offset,
674 l->name);
676 fprintf(rf, "\n");
682 /* Close the report file. */
683 if (map_control && (rf != stdout) && (rf != stderr))
684 fclose(rf);
686 /* Step 8: Release all allocated memory. */
688 /* Free sections, label pointer structs, etc.. */
689 while (sections) {
690 s = sections;
691 sections = s->next;
692 saa_free(s->contents);
693 nasm_free(s->name);
694 if (s->flags & FOLLOWS_DEFINED)
695 nasm_free(s->follows);
696 if (s->flags & VFOLLOWS_DEFINED)
697 nasm_free(s->vfollows);
698 while (s->labels) {
699 l = s->labels;
700 s->labels = l->next;
701 nasm_free(l);
703 nasm_free(s);
706 /* Free no-section labels. */
707 while (no_seg_labels) {
708 l = no_seg_labels;
709 no_seg_labels = l->next;
710 nasm_free(l);
713 /* Free relocation structures. */
714 while (relocs) {
715 r = relocs->next;
716 nasm_free(relocs);
717 relocs = r;
721 static void bin_out(int32_t segto, const void *data,
722 enum out_type type, uint64_t size,
723 int32_t segment, int32_t wrt)
725 uint8_t *p, mydata[8];
726 struct Section *s;
728 if (wrt != NO_SEG) {
729 wrt = NO_SEG; /* continue to do _something_ */
730 nasm_nonfatal("WRT not supported by binary output format");
733 /* Find the segment we are targeting. */
734 s = find_section_by_index(segto);
735 if (!s)
736 nasm_panic("code directed to nonexistent segment?");
738 /* "Smart" section-type adaptation code. */
739 if (!(s->flags & TYPE_DEFINED)) {
740 if (type == OUT_RESERVE)
741 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
742 else
743 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
746 if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
747 nasm_warn(WARN_OTHER, "attempt to initialize memory in a"
748 " nobits section: ignored");
750 switch (type) {
751 case OUT_ADDRESS:
753 int asize = abs((int)size);
755 if (segment != NO_SEG && !find_section_by_index(segment)) {
756 if (segment % 2)
757 nasm_nonfatal("binary output format does not support"
758 " segment base references");
759 else
760 nasm_nonfatal("binary output format does not support"
761 " external references");
762 segment = NO_SEG;
764 if (s->flags & TYPE_PROGBITS) {
765 if (segment != NO_SEG)
766 add_reloc(s, asize, segment, -1L);
767 p = mydata;
768 WRITEADDR(p, *(int64_t *)data, asize);
769 saa_wbytes(s->contents, mydata, asize);
773 * Reassign size with sign dropped, we will need it
774 * for section length calculation.
776 size = asize;
777 break;
780 case OUT_RAWDATA:
781 if (s->flags & TYPE_PROGBITS)
782 saa_wbytes(s->contents, data, size);
783 break;
785 case OUT_RESERVE:
786 if (s->flags & TYPE_PROGBITS) {
787 nasm_warn(WARN_ZEROING, "uninitialized space declared in"
788 " %s section: zeroing", s->name);
789 saa_wbytes(s->contents, NULL, size);
791 break;
793 case OUT_REL1ADR:
794 case OUT_REL2ADR:
795 case OUT_REL4ADR:
796 case OUT_REL8ADR:
798 int64_t addr = *(int64_t *)data - size;
799 size = realsize(type, size);
800 if (segment != NO_SEG && !find_section_by_index(segment)) {
801 if (segment % 2)
802 nasm_nonfatal("binary output format does not support"
803 " segment base references");
804 else
805 nasm_nonfatal("binary output format does not support"
806 " external references");
807 segment = NO_SEG;
809 if (s->flags & TYPE_PROGBITS) {
810 add_reloc(s, size, segment, segto);
811 p = mydata;
812 WRITEADDR(p, addr - s->length, size);
813 saa_wbytes(s->contents, mydata, size);
815 break;
818 default:
819 nasm_nonfatal("unsupported relocation type %d\n", type);
820 break;
823 s->length += size;
826 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
827 int is_global, char *special)
829 (void)segment; /* Don't warn that this parameter is unused */
830 (void)offset; /* Don't warn that this parameter is unused */
832 if (special)
833 nasm_nonfatal("binary format does not support any"
834 " special symbol types");
835 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
836 nasm_nonfatal("unrecognised special symbol `%s'", name);
837 else if (is_global == 2)
838 nasm_nonfatal("binary output format does not support common"
839 " variables");
840 else {
841 struct Section *s;
842 struct bin_label ***ltp;
844 /* Remember label definition so we can look it up later when
845 * creating the map file. */
846 s = find_section_by_index(segment);
847 if (s)
848 ltp = &(s->labels_end);
849 else
850 ltp = &nsl_tail;
851 (**ltp) = nasm_malloc(sizeof(struct bin_label));
852 (**ltp)->name = name;
853 (**ltp)->next = NULL;
854 *ltp = &((**ltp)->next);
859 /* These constants and the following function are used
860 * by bin_secname() to parse attribute assignments. */
862 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
863 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
864 ATTRIB_NOBITS, ATTRIB_PROGBITS
867 static int bin_read_attribute(char **line, int *attribute,
868 uint64_t *value)
870 expr *e;
871 int attrib_name_size;
872 struct tokenval tokval;
873 char *exp;
875 /* Skip whitespace. */
876 while (**line && nasm_isspace(**line))
877 (*line)++;
878 if (!**line)
879 return 0;
881 /* Figure out what attribute we're reading. */
882 if (!nasm_strnicmp(*line, "align=", 6)) {
883 *attribute = ATTRIB_ALIGN;
884 attrib_name_size = 6;
885 } else {
886 if (!nasm_strnicmp(*line, "start=", 6)) {
887 *attribute = ATTRIB_START;
888 attrib_name_size = 6;
889 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
890 *attribute = ATTRIB_FOLLOWS;
891 *line += 8;
892 return 1;
893 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
894 *attribute = ATTRIB_VSTART;
895 attrib_name_size = 7;
896 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
897 *attribute = ATTRIB_VALIGN;
898 attrib_name_size = 7;
899 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
900 *attribute = ATTRIB_VFOLLOWS;
901 *line += 9;
902 return 1;
903 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
904 (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
905 *attribute = ATTRIB_NOBITS;
906 *line += 6;
907 return 1;
908 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
909 (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
910 *attribute = ATTRIB_PROGBITS;
911 *line += 8;
912 return 1;
913 } else
914 return 0;
917 /* Find the end of the expression. */
918 if ((*line)[attrib_name_size] != '(') {
919 /* Single term (no parenthesis). */
920 exp = *line += attrib_name_size;
921 while (**line && !nasm_isspace(**line))
922 (*line)++;
923 if (**line) {
924 **line = '\0';
925 (*line)++;
927 } else {
928 char c;
929 int pcount = 1;
931 /* Full expression (delimited by parenthesis) */
932 exp = *line += attrib_name_size + 1;
933 while (1) {
934 (*line) += strcspn(*line, "()'\"");
935 if (**line == '(') {
936 ++(*line);
937 ++pcount;
939 if (**line == ')') {
940 ++(*line);
941 --pcount;
942 if (!pcount)
943 break;
945 if ((**line == '"') || (**line == '\'')) {
946 c = **line;
947 while (**line) {
948 ++(*line);
949 if (**line == c)
950 break;
952 if (!**line) {
953 nasm_nonfatal("invalid syntax in `section' directive");
954 return -1;
956 ++(*line);
958 if (!**line) {
959 nasm_nonfatal("expecting `)'");
960 return -1;
963 *(*line - 1) = '\0'; /* Terminate the expression. */
966 /* Check for no value given. */
967 if (!*exp) {
968 nasm_warn(WARN_OTHER, "No value given to attribute in"
969 " `section' directive");
970 return -1;
973 /* Read and evaluate the expression. */
974 stdscan_reset();
975 stdscan_set(exp);
976 tokval.t_type = TOKEN_INVALID;
977 e = evaluate(stdscan, NULL, &tokval, NULL, 1, NULL);
978 if (e) {
979 if (!is_really_simple(e)) {
980 nasm_nonfatal("section attribute value must be"
981 " a critical expression");
982 return -1;
984 } else {
985 nasm_nonfatal("Invalid attribute value"
986 " specified in `section' directive.");
987 return -1;
989 *value = (uint64_t)reloc_value(e);
990 return 1;
993 static void bin_sectalign(int32_t seg, unsigned int value)
995 struct Section *s = find_section_by_index(seg);
997 if (!s || !is_power2(value))
998 return;
1000 if (value > s->align)
1001 s->align = value;
1003 if (!(s->flags & ALIGN_DEFINED))
1004 s->flags |= ALIGN_DEFINED;
1007 static void bin_assign_attributes(struct Section *sec, char *astring)
1009 int attribute, check;
1010 uint64_t value;
1011 char *p;
1013 while (1) { /* Get the next attribute. */
1014 check = bin_read_attribute(&astring, &attribute, &value);
1015 /* Skip bad attribute. */
1016 if (check == -1)
1017 continue;
1018 /* Unknown section attribute, so skip it and warn the user. */
1019 if (!check) {
1020 if (!*astring)
1021 break; /* End of line. */
1022 else {
1023 p = astring;
1024 while (*astring && !nasm_isspace(*astring))
1025 astring++;
1026 if (*astring) {
1027 *astring = '\0';
1028 astring++;
1030 nasm_warn(WARN_OTHER, "ignoring unknown section attribute: \"%s\"", p);
1032 continue;
1035 switch (attribute) { /* Handle nobits attribute. */
1036 case ATTRIB_NOBITS:
1037 if ((sec->flags & TYPE_DEFINED)
1038 && (sec->flags & TYPE_PROGBITS))
1039 nasm_nonfatal("attempt to change section type"
1040 " from progbits to nobits");
1041 else
1042 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1043 continue;
1045 /* Handle progbits attribute. */
1046 case ATTRIB_PROGBITS:
1047 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1048 nasm_nonfatal("attempt to change section type"
1049 " from nobits to progbits");
1050 else
1051 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1052 continue;
1054 /* Handle align attribute. */
1055 case ATTRIB_ALIGN:
1056 if (!value || ((value - 1) & value)) {
1057 nasm_nonfatal("argument to `align' is not a power of two");
1058 } else {
1060 * Alignment is already satisfied if
1061 * the previous align value is greater
1063 if ((sec->flags & ALIGN_DEFINED) && (value < sec->align))
1064 value = sec->align;
1066 /* Don't allow a conflicting align value. */
1067 if ((sec->flags & START_DEFINED) && (sec->start & (value - 1))) {
1068 nasm_nonfatal("`align' value conflicts with section start address");
1069 } else {
1070 sec->align = value;
1071 sec->flags |= ALIGN_DEFINED;
1074 continue;
1076 /* Handle valign attribute. */
1077 case ATTRIB_VALIGN:
1078 if (!value || ((value - 1) & value))
1079 nasm_nonfatal("argument to `valign' is not a power of two");
1080 else { /* Alignment is already satisfied if the previous
1081 * align value is greater. */
1082 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1083 value = sec->valign;
1085 /* Don't allow a conflicting valign value. */
1086 if ((sec->flags & VSTART_DEFINED)
1087 && (sec->vstart & (value - 1)))
1088 nasm_nonfatal("`valign' value conflicts with `vstart' address");
1089 else {
1090 sec->valign = value;
1091 sec->flags |= VALIGN_DEFINED;
1094 continue;
1096 /* Handle start attribute. */
1097 case ATTRIB_START:
1098 if (sec->flags & FOLLOWS_DEFINED)
1099 nasm_nonfatal("cannot combine `start' and `follows'"
1100 " section attributes");
1101 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1102 nasm_nonfatal("section start address redefined");
1103 else {
1104 sec->start = value;
1105 sec->flags |= START_DEFINED;
1106 if (sec->flags & ALIGN_DEFINED) {
1107 if (sec->start & (sec->align - 1))
1108 nasm_nonfatal("`start' address conflicts"
1109 " with section alignment");
1110 sec->flags ^= ALIGN_DEFINED;
1113 continue;
1115 /* Handle vstart attribute. */
1116 case ATTRIB_VSTART:
1117 if (sec->flags & VFOLLOWS_DEFINED)
1118 nasm_nonfatal("cannot combine `vstart' and `vfollows'"
1119 " section attributes");
1120 else if ((sec->flags & VSTART_DEFINED)
1121 && (value != sec->vstart))
1122 nasm_nonfatal("section virtual start address"
1123 " (vstart) redefined");
1124 else {
1125 sec->vstart = value;
1126 sec->flags |= VSTART_DEFINED;
1127 if (sec->flags & VALIGN_DEFINED) {
1128 if (sec->vstart & (sec->valign - 1))
1129 nasm_nonfatal("`vstart' address conflicts"
1130 " with `valign' value");
1131 sec->flags ^= VALIGN_DEFINED;
1134 continue;
1136 /* Handle follows attribute. */
1137 case ATTRIB_FOLLOWS:
1138 p = astring;
1139 astring += strcspn(astring, " \t");
1140 if (astring == p)
1141 nasm_nonfatal("expecting section name for `follows'"
1142 " attribute");
1143 else {
1144 *(astring++) = '\0';
1145 if (sec->flags & START_DEFINED)
1146 nasm_nonfatal("cannot combine `start' and `follows'"
1147 " section attributes");
1148 sec->follows = nasm_strdup(p);
1149 sec->flags |= FOLLOWS_DEFINED;
1151 continue;
1153 /* Handle vfollows attribute. */
1154 case ATTRIB_VFOLLOWS:
1155 if (sec->flags & VSTART_DEFINED)
1156 nasm_nonfatal("cannot combine `vstart' and `vfollows'"
1157 " section attributes");
1158 else {
1159 p = astring;
1160 astring += strcspn(astring, " \t");
1161 if (astring == p)
1162 nasm_nonfatal("expecting section name for `vfollows'"
1163 " attribute");
1164 else {
1165 *(astring++) = '\0';
1166 sec->vfollows = nasm_strdup(p);
1167 sec->flags |= VFOLLOWS_DEFINED;
1170 continue;
1175 static void bin_define_section_labels(void)
1177 static int labels_defined = 0;
1178 struct Section *sec;
1179 char *label_name;
1180 size_t base_len;
1182 if (labels_defined)
1183 return;
1184 list_for_each(sec, sections) {
1185 base_len = strlen(sec->name) + 8;
1186 label_name = nasm_malloc(base_len + 8);
1187 strcpy(label_name, "section.");
1188 strcpy(label_name + 8, sec->name);
1190 /* section.<name>.start */
1191 strcpy(label_name + base_len, ".start");
1192 define_label(label_name, sec->start_index, 0L, false);
1194 /* section.<name>.vstart */
1195 strcpy(label_name + base_len, ".vstart");
1196 define_label(label_name, sec->vstart_index, 0L, false);
1198 nasm_free(label_name);
1200 labels_defined = 1;
1203 static int32_t bin_secname(char *name, int *bits)
1205 char *p;
1206 struct Section *sec;
1208 /* bin_secname is called with *name = NULL at the start of each
1209 * pass. Use this opportunity to establish the default section
1210 * (default is BITS-16 ".text" segment).
1212 if (!name) {
1213 /* Reset ORG and section attributes at the start of each pass. */
1214 origin_defined = 0;
1215 list_for_each(sec, sections)
1216 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1217 ALIGN_DEFINED | VALIGN_DEFINED);
1219 /* Define section start and vstart labels. */
1220 if (!pass_first())
1221 bin_define_section_labels();
1223 /* Establish the default (.text) section. */
1224 *bits = 16;
1225 sec = find_section_by_name(".text");
1226 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1227 return sec->vstart_index;
1230 /* Attempt to find the requested section. If it does not
1231 * exist, create it. */
1232 p = name;
1233 while (*p && !nasm_isspace(*p))
1234 p++;
1235 if (*p)
1236 *p++ = '\0';
1237 sec = find_section_by_name(name);
1238 if (!sec) {
1239 sec = create_section(name);
1240 if (!strcmp(name, ".data"))
1241 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1242 else if (!strcmp(name, ".bss")) {
1243 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1244 sec->prev = NULL;
1248 /* Handle attribute assignments. */
1249 if (!pass_first())
1250 bin_assign_attributes(sec, p);
1252 #ifndef ABIN_SMART_ADAPT
1253 /* The following line disables smart adaptation of
1254 * PROGBITS/NOBITS section types (it forces sections to
1255 * default to PROGBITS). */
1256 if (!pass_first() && !(sec->flags & TYPE_DEFINED))
1257 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1258 #endif
1260 return sec->vstart_index;
1263 static enum directive_result
1264 bin_directive(enum directive directive, char *args)
1266 switch (directive) {
1267 case D_ORG:
1269 struct tokenval tokval;
1270 uint64_t value;
1271 expr *e;
1273 stdscan_reset();
1274 stdscan_set(args);
1275 tokval.t_type = TOKEN_INVALID;
1276 e = evaluate(stdscan, NULL, &tokval, NULL, 1, NULL);
1277 if (e) {
1278 if (!is_really_simple(e))
1279 nasm_nonfatal("org value must be a critical"
1280 " expression");
1281 else {
1282 value = reloc_value(e);
1283 /* Check for ORG redefinition. */
1284 if (origin_defined && (value != origin))
1285 nasm_nonfatal("program origin redefined");
1286 else {
1287 origin = value;
1288 origin_defined = 1;
1291 } else
1292 nasm_nonfatal("No or invalid offset specified"
1293 " in ORG directive.");
1294 return DIRR_OK;
1296 case D_MAP:
1298 /* The 'map' directive allows the user to generate section
1299 * and symbol information to stdout, stderr, or to a file. */
1300 char *p;
1302 if (!pass_first())
1303 return DIRR_OK;
1304 args += strspn(args, " \t");
1305 while (*args) {
1306 p = args;
1307 args += strcspn(args, " \t");
1308 if (*args != '\0')
1309 *(args++) = '\0';
1310 if (!nasm_stricmp(p, "all"))
1311 map_control |=
1312 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1313 else if (!nasm_stricmp(p, "brief"))
1314 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1315 else if (!nasm_stricmp(p, "sections"))
1316 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1317 else if (!nasm_stricmp(p, "segments"))
1318 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1319 else if (!nasm_stricmp(p, "symbols"))
1320 map_control |= MAP_SYMBOLS;
1321 else if (!rf) {
1322 if (!nasm_stricmp(p, "stdout"))
1323 rf = stdout;
1324 else if (!nasm_stricmp(p, "stderr"))
1325 rf = stderr;
1326 else { /* Must be a filename. */
1327 rf = nasm_open_write(p, NF_TEXT);
1328 if (!rf) {
1329 nasm_warn(WARN_OTHER|ERR_PASS1, "unable to open map file `%s'", p);
1330 map_control = 0;
1331 return DIRR_OK;
1334 } else
1335 nasm_warn(WARN_OTHER|ERR_PASS1, "map file already specified");
1337 if (map_control == 0)
1338 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1339 if (!rf)
1340 rf = stdout;
1341 return DIRR_OK;
1343 default:
1344 return DIRR_UNKNOWN;
1348 const struct ofmt of_bin, of_ith, of_srec;
1349 static void binfmt_init(void);
1350 static void do_output_bin(void);
1351 static void do_output_ith(void);
1352 static void do_output_srec(void);
1354 static void bin_init(void)
1356 do_output = do_output_bin;
1357 binfmt_init();
1360 static void ith_init(void)
1362 do_output = do_output_ith;
1363 binfmt_init();
1366 static void srec_init(void)
1368 do_output = do_output_srec;
1369 binfmt_init();
1372 static void binfmt_init(void)
1374 relocs = NULL;
1375 reloctail = &relocs;
1376 origin_defined = 0;
1377 no_seg_labels = NULL;
1378 nsl_tail = &no_seg_labels;
1380 /* Create default section (.text). */
1381 sections = last_section = nasm_zalloc(sizeof(struct Section));
1382 last_section->name = nasm_strdup(".text");
1383 last_section->contents = saa_init(1L);
1384 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1385 last_section->labels_end = &(last_section->labels);
1386 last_section->start_index = seg_alloc();
1387 last_section->vstart_index = seg_alloc();
1390 /* Generate binary file output */
1391 static void do_output_bin(void)
1393 struct Section *s;
1394 uint64_t addr = origin;
1396 /* Write the progbits sections to the output file. */
1397 list_for_each(s, sections) {
1398 /* Skip non-progbits sections */
1399 if (!(s->flags & TYPE_PROGBITS))
1400 continue;
1401 /* Skip zero-length sections */
1402 if (s->length == 0)
1403 continue;
1405 /* Pad the space between sections. */
1406 nasm_assert(addr <= s->start);
1407 fwritezero(s->start - addr, ofile);
1409 /* Write the section to the output file. */
1410 saa_fpwrite(s->contents, ofile);
1412 /* Keep track of the current file position */
1413 addr = s->start + s->length;
1417 /* Generate Intel hex file output */
1418 static void write_ith_record(unsigned int len, uint16_t addr,
1419 uint8_t type, void *data)
1421 char buf[1+2+4+2+255*2+2+2];
1422 char *p = buf;
1423 uint8_t csum, *dptr = data;
1424 unsigned int i;
1426 nasm_assert(len <= 255);
1428 csum = len + addr + (addr >> 8) + type;
1429 for (i = 0; i < len; i++)
1430 csum += dptr[i];
1431 csum = -csum;
1433 p += sprintf(p, ":%02X%04X%02X", len, addr, type);
1434 for (i = 0; i < len; i++)
1435 p += sprintf(p, "%02X", dptr[i]);
1436 p += sprintf(p, "%02X\n", csum);
1438 nasm_write(buf, p-buf, ofile);
1441 static void do_output_ith(void)
1443 uint8_t buf[32];
1444 struct Section *s;
1445 uint64_t addr, hiaddr, hilba;
1446 uint64_t length;
1447 unsigned int chunk;
1449 /* Write the progbits sections to the output file. */
1450 hilba = 0;
1451 list_for_each(s, sections) {
1452 /* Skip non-progbits sections */
1453 if (!(s->flags & TYPE_PROGBITS))
1454 continue;
1455 /* Skip zero-length sections */
1456 if (s->length == 0)
1457 continue;
1459 addr = s->start;
1460 length = s->length;
1461 saa_rewind(s->contents);
1463 while (length) {
1464 hiaddr = addr >> 16;
1465 if (hiaddr != hilba) {
1466 buf[0] = hiaddr >> 8;
1467 buf[1] = hiaddr;
1468 write_ith_record(2, 0, 4, buf);
1469 hilba = hiaddr;
1472 chunk = 32 - (addr & 31);
1473 if (length < chunk)
1474 chunk = length;
1476 saa_rnbytes(s->contents, buf, chunk);
1477 write_ith_record(chunk, (uint16_t)addr, 0, buf);
1479 addr += chunk;
1480 length -= chunk;
1484 /* Write closing record */
1485 write_ith_record(0, 0, 1, NULL);
1488 /* Generate Motorola S-records */
1489 static void write_srecord(unsigned int len, unsigned int alen,
1490 uint32_t addr, uint8_t type, void *data)
1492 char buf[2+2+8+255*2+2+2];
1493 char *p = buf;
1494 uint8_t csum, *dptr = data;
1495 unsigned int i;
1497 nasm_assert(len <= 255);
1499 switch (alen) {
1500 case 2:
1501 addr &= 0xffff;
1502 break;
1503 case 3:
1504 addr &= 0xffffff;
1505 break;
1506 case 4:
1507 break;
1508 default:
1509 panic();
1510 break;
1513 csum = (len+alen+1) + addr + (addr >> 8) + (addr >> 16) + (addr >> 24);
1514 for (i = 0; i < len; i++)
1515 csum += dptr[i];
1516 csum = 0xff-csum;
1518 p += sprintf(p, "S%c%02X%0*X", type, len+alen+1, alen*2, addr);
1519 for (i = 0; i < len; i++)
1520 p += sprintf(p, "%02X", dptr[i]);
1521 p += sprintf(p, "%02X\n", csum);
1523 nasm_write(buf, p-buf, ofile);
1526 static void do_output_srec(void)
1528 uint8_t buf[32];
1529 struct Section *s;
1530 uint64_t addr, maxaddr;
1531 uint64_t length;
1532 int alen;
1533 unsigned int chunk;
1534 char dtype, etype;
1536 maxaddr = 0;
1537 list_for_each(s, sections) {
1538 /* Skip non-progbits sections */
1539 if (!(s->flags & TYPE_PROGBITS))
1540 continue;
1541 /* Skip zero-length sections */
1542 if (s->length == 0)
1543 continue;
1545 addr = s->start + s->length - 1;
1546 if (addr > maxaddr)
1547 maxaddr = addr;
1550 if (maxaddr <= 0xffff) {
1551 alen = 2;
1552 dtype = '1'; /* S1 = 16-bit data */
1553 etype = '9'; /* S9 = 16-bit end */
1554 } else if (maxaddr <= 0xffffff) {
1555 alen = 3;
1556 dtype = '2'; /* S2 = 24-bit data */
1557 etype = '8'; /* S8 = 24-bit end */
1558 } else {
1559 alen = 4;
1560 dtype = '3'; /* S3 = 32-bit data */
1561 etype = '7'; /* S7 = 32-bit end */
1564 /* Write head record */
1565 write_srecord(0, 2, 0, '0', NULL);
1567 /* Write the progbits sections to the output file. */
1568 list_for_each(s, sections) {
1569 /* Skip non-progbits sections */
1570 if (!(s->flags & TYPE_PROGBITS))
1571 continue;
1572 /* Skip zero-length sections */
1573 if (s->length == 0)
1574 continue;
1576 addr = s->start;
1577 length = s->length;
1578 saa_rewind(s->contents);
1580 while (length) {
1581 chunk = 32 - (addr & 31);
1582 if (length < chunk)
1583 chunk = length;
1585 saa_rnbytes(s->contents, buf, chunk);
1586 write_srecord(chunk, alen, (uint32_t)addr, dtype, buf);
1588 addr += chunk;
1589 length -= chunk;
1593 /* Write closing record */
1594 write_srecord(0, alen, 0, etype, NULL);
1598 const struct ofmt of_bin = {
1599 "Flat raw binary (MS-DOS, embedded, ...)",
1600 "bin",
1604 null_debug_arr,
1605 &null_debug_form,
1606 bin_stdmac,
1607 bin_init,
1608 null_reset,
1609 nasm_do_legacy_output,
1610 bin_out,
1611 bin_deflabel,
1612 bin_secname,
1613 NULL,
1614 bin_sectalign,
1615 null_segbase,
1616 bin_directive,
1617 bin_cleanup,
1618 NULL /* pragma list */
1621 const struct ofmt of_ith = {
1622 "Intel Hex encoded flat binary",
1623 "ith",
1624 ".ith", /* really should have been ".hex"... */
1625 OFMT_TEXT,
1627 null_debug_arr,
1628 &null_debug_form,
1629 bin_stdmac,
1630 ith_init,
1631 null_reset,
1632 nasm_do_legacy_output,
1633 bin_out,
1634 bin_deflabel,
1635 bin_secname,
1636 NULL,
1637 bin_sectalign,
1638 null_segbase,
1639 bin_directive,
1640 bin_cleanup,
1641 NULL /* pragma list */
1644 const struct ofmt of_srec = {
1645 "Motorola S-records encoded flat binary",
1646 "srec",
1647 ".srec",
1648 OFMT_TEXT,
1650 null_debug_arr,
1651 &null_debug_form,
1652 bin_stdmac,
1653 srec_init,
1654 null_reset,
1655 nasm_do_legacy_output,
1656 bin_out,
1657 bin_deflabel,
1658 bin_secname,
1659 NULL,
1660 bin_sectalign,
1661 null_segbase,
1662 bin_directive,
1663 bin_cleanup,
1664 NULL /* pragma list */
1667 #endif /* #ifdef OF_BIN */