Get rid of a bunch of unnecessary indirections
[nasm.git] / output / outbin.c
blob915dc45f6bebb9688d796ebe7e0b407b94f1141e
1 /* ----------------------------------------------------------------------- *
2 *
3 * Copyright 1996-2013 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
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>
82 #include <inttypes.h>
84 #include "nasm.h"
85 #include "nasmlib.h"
86 #include "saa.h"
87 #include "stdscan.h"
88 #include "labels.h"
89 #include "eval.h"
90 #include "output/outform.h"
91 #include "output/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;
164 static char *infile, *outfile;
166 extern macros_t bin_stdmac[];
168 static void add_reloc(struct Section *s, int32_t bytes, int32_t secref,
169 int32_t secrel)
171 struct Reloc *r;
173 r = *reloctail = nasm_malloc(sizeof(struct Reloc));
174 reloctail = &r->next;
175 r->next = NULL;
176 r->posn = s->length;
177 r->bytes = bytes;
178 r->secref = secref;
179 r->secrel = secrel;
180 r->target = s;
183 static struct Section *find_section_by_name(const char *name)
185 struct Section *s;
187 list_for_each(s, sections)
188 if (!strcmp(s->name, name))
189 break;
190 return s;
193 static struct Section *find_section_by_index(int32_t index)
195 struct Section *s;
197 list_for_each(s, sections)
198 if ((index == s->vstart_index) || (index == s->start_index))
199 break;
200 return s;
203 static struct Section *create_section(char *name)
205 struct Section *s = nasm_zalloc(sizeof(*s));
207 s->prev = last_section;
208 s->name = nasm_strdup(name);
209 s->labels_end = &(s->labels);
210 s->contents = saa_init(1L);
212 /* Register our sections with NASM. */
213 s->vstart_index = seg_alloc();
214 s->start_index = seg_alloc();
216 /* FIXME: Append to a tail, we need some helper */
217 last_section->next = s;
218 last_section = s;
220 return last_section;
223 static void bin_cleanup(int debuginfo)
225 struct Section *g, **gp;
226 struct Section *gs = NULL, **gsp;
227 struct Section *s, **sp;
228 struct Section *nobits = NULL, **nt;
229 struct Section *last_progbits;
230 struct bin_label *l;
231 struct Reloc *r;
232 uint64_t pend;
233 int h;
235 (void)debuginfo; /* placate optimizers */
237 #ifdef DEBUG
238 nasm_error(ERR_DEBUG,
239 "bin_cleanup: Sections were initially referenced in this order:\n");
240 for (h = 0, s = sections; s; h++, s = s->next)
241 fprintf(stdout, "%i. %s\n", h, s->name);
242 #endif
244 /* Assembly has completed, so now we need to generate the output file.
245 * Step 1: Separate progbits and nobits sections into separate lists.
246 * Step 2: Sort the progbits sections into their output order.
247 * Step 3: Compute start addresses for all progbits sections.
248 * Step 4: Compute vstart addresses for all sections.
249 * Step 5: Apply relocations.
250 * Step 6: Write the sections' data to the output file.
251 * Step 7: Generate the map file.
252 * Step 8: Release all allocated memory.
255 /* To do: Smart section-type adaptation could leave some empty sections
256 * without a defined type (progbits/nobits). Won't fix now since this
257 * feature will be disabled. */
259 /* Step 1: Split progbits and nobits sections into separate lists. */
261 nt = &nobits;
262 /* Move nobits sections into a separate list. Also pre-process nobits
263 * sections' attributes. */
264 for (sp = &sections->next, s = sections->next; s; s = *sp) { /* Skip progbits sections. */
265 if (s->flags & TYPE_PROGBITS) {
266 sp = &s->next;
267 continue;
269 /* Do some special pre-processing on nobits sections' attributes. */
270 if (s->flags & (START_DEFINED | ALIGN_DEFINED | FOLLOWS_DEFINED)) { /* Check for a mixture of real and virtual section attributes. */
271 if (s->flags & (VSTART_DEFINED | VALIGN_DEFINED |
272 VFOLLOWS_DEFINED))
273 nasm_fatal(ERR_NOFILE,
274 "cannot mix real and virtual attributes"
275 " in nobits section (%s)", s->name);
276 /* Real and virtual attributes mean the same thing for nobits sections. */
277 if (s->flags & START_DEFINED) {
278 s->vstart = s->start;
279 s->flags |= VSTART_DEFINED;
281 if (s->flags & ALIGN_DEFINED) {
282 s->valign = s->align;
283 s->flags |= VALIGN_DEFINED;
285 if (s->flags & FOLLOWS_DEFINED) {
286 s->vfollows = s->follows;
287 s->flags |= VFOLLOWS_DEFINED;
288 s->flags &= ~FOLLOWS_DEFINED;
291 /* Every section must have a start address. */
292 if (s->flags & VSTART_DEFINED) {
293 s->start = s->vstart;
294 s->flags |= START_DEFINED;
296 /* Move the section into the nobits list. */
297 *sp = s->next;
298 s->next = NULL;
299 *nt = s;
300 nt = &s->next;
303 /* Step 2: Sort the progbits sections into their output order. */
305 /* In Step 2 we move around sections in groups. A group
306 * begins with a section (group leader) that has a user-
307 * defined start address or follows section. The remainder
308 * of the group is made up of the sections that implicitly
309 * follow the group leader (i.e., they were defined after
310 * the group leader and were not given an explicit start
311 * address or follows section by the user). */
313 /* For anyone attempting to read this code:
314 * g (group) points to a group of sections, the first one of which has
315 * a user-defined start address or follows section.
316 * gp (g previous) holds the location of the pointer to g.
317 * gs (g scan) is a temp variable that we use to scan to the end of the group.
318 * gsp (gs previous) holds the location of the pointer to gs.
319 * nt (nobits tail) points to the nobits section-list tail.
322 /* Link all 'follows' groups to their proper position. To do
323 * this we need to know three things: the start of the group
324 * to relocate (g), the section it is following (s), and the
325 * end of the group we're relocating (gs). */
326 for (gp = &sections, g = sections; g; g = gs) { /* Find the next follows group that is out of place (g). */
327 if (!(g->flags & FOLLOWS_DEFINED)) {
328 while (g->next) {
329 if ((g->next->flags & FOLLOWS_DEFINED) &&
330 strcmp(g->name, g->next->follows))
331 break;
332 g = g->next;
334 if (!g->next)
335 break;
336 gp = &g->next;
337 g = g->next;
339 /* Find the section that this group follows (s). */
340 for (sp = &sections, s = sections;
341 s && strcmp(s->name, g->follows);
342 sp = &s->next, s = s->next) ;
343 if (!s)
344 nasm_fatal(ERR_NOFILE, "section %s follows an invalid or"
345 " unknown section (%s)", g->name, g->follows);
346 if (s->next && (s->next->flags & FOLLOWS_DEFINED) &&
347 !strcmp(s->name, s->next->follows))
348 nasm_fatal(ERR_NOFILE, "sections %s and %s can't both follow"
349 " section %s", g->name, s->next->name, s->name);
350 /* Find the end of the current follows group (gs). */
351 for (gsp = &g->next, gs = g->next;
352 gs && (gs != s) && !(gs->flags & START_DEFINED);
353 gsp = &gs->next, gs = gs->next) {
354 if (gs->next && (gs->next->flags & FOLLOWS_DEFINED) &&
355 strcmp(gs->name, gs->next->follows)) {
356 gsp = &gs->next;
357 gs = gs->next;
358 break;
361 /* Re-link the group after its follows section. */
362 *gsp = s->next;
363 s->next = g;
364 *gp = gs;
367 /* Link all 'start' groups to their proper position. Once
368 * again we need to know g, s, and gs (see above). The main
369 * difference is we already know g since we sort by moving
370 * groups from the 'unsorted' list into a 'sorted' list (g
371 * will always be the first section in the unsorted list). */
372 for (g = sections, sections = NULL; g; g = gs) { /* Find the section that we will insert this group before (s). */
373 for (sp = &sections, s = sections; s; sp = &s->next, s = s->next)
374 if ((s->flags & START_DEFINED) && (g->start < s->start))
375 break;
376 /* Find the end of the group (gs). */
377 for (gs = g->next, gsp = &g->next;
378 gs && !(gs->flags & START_DEFINED);
379 gsp = &gs->next, gs = gs->next) ;
380 /* Re-link the group before the target section. */
381 *sp = g;
382 *gsp = s;
385 /* Step 3: Compute start addresses for all progbits sections. */
387 /* Make sure we have an origin and a start address for the first section. */
388 if (origin_defined) {
389 if (sections->flags & START_DEFINED) {
390 /* Make sure this section doesn't begin before the origin. */
391 if (sections->start < origin)
392 nasm_fatal(ERR_NOFILE, "section %s begins"
393 " before program origin", sections->name);
394 } else if (sections->flags & ALIGN_DEFINED) {
395 sections->start = ALIGN(origin, sections->align);
396 } else {
397 sections->start = origin;
399 } else {
400 if (!(sections->flags & START_DEFINED))
401 sections->start = 0;
402 origin = sections->start;
404 sections->flags |= START_DEFINED;
406 /* Make sure each section has an explicit start address. If it
407 * doesn't, then compute one based its alignment and the end of
408 * the previous section. */
409 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
410 * (has a defined start address, and is not zero length). */
411 if (g == s)
412 for (s = g->next;
413 s && ((s->length == 0) || !(s->flags & START_DEFINED));
414 s = s->next) ;
415 /* Compute the start address of this section, if necessary. */
416 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
417 if (!(g->flags & ALIGN_DEFINED)) {
418 g->align = 4;
419 g->flags |= ALIGN_DEFINED;
421 /* Set the section start address. */
422 g->start = ALIGN(pend, g->align);
423 g->flags |= START_DEFINED;
425 /* Ugly special case for progbits sections' virtual attributes:
426 * If there is a defined valign, but no vstart and no vfollows, then
427 * we valign after the previous progbits section. This case doesn't
428 * really make much sense for progbits sections with a defined start
429 * address, but it is possible and we must do *something*.
430 * Not-so-ugly special case:
431 * If a progbits section has no virtual attributes, we set the
432 * vstart equal to the start address. */
433 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
434 if (g->flags & VALIGN_DEFINED)
435 g->vstart = ALIGN(pend, g->valign);
436 else
437 g->vstart = g->start;
438 g->flags |= VSTART_DEFINED;
440 /* Ignore zero-length sections. */
441 if (g->start < pend)
442 continue;
443 /* Compute the span of this section. */
444 pend = g->start + g->length;
445 /* Check for section overlap. */
446 if (s) {
447 if (s->start < origin)
448 nasm_fatal(ERR_NOFILE, "section %s beings before program origin",
449 s->name);
450 if (g->start > s->start)
451 nasm_fatal(ERR_NOFILE, "sections %s ~ %s and %s overlap!",
452 gs->name, g->name, s->name);
453 if (pend > s->start)
454 nasm_fatal(ERR_NOFILE, "sections %s and %s overlap!",
455 g->name, s->name);
457 /* Remember this section as the latest >0 length section. */
458 gs = g;
461 /* Step 4: Compute vstart addresses for all sections. */
463 /* Attach the nobits sections to the end of the progbits sections. */
464 for (s = sections; s->next; s = s->next) ;
465 s->next = nobits;
466 last_progbits = s;
468 * Scan for sections that don't have a vstart address. If we find
469 * one we'll attempt to compute its vstart. If we can't compute
470 * the vstart, we leave it alone and come back to it in a
471 * subsequent scan. We continue scanning and re-scanning until
472 * we've gone one full cycle without computing any vstarts.
474 do { /* Do one full scan of the sections list. */
475 for (h = 0, g = sections; g; g = g->next) {
476 if (g->flags & VSTART_DEFINED)
477 continue;
478 /* Find the section that this one virtually follows. */
479 if (g->flags & VFOLLOWS_DEFINED) {
480 for (s = sections; s && strcmp(g->vfollows, s->name);
481 s = s->next) ;
482 if (!s)
483 nasm_fatal(ERR_NOFILE,
484 "section %s vfollows unknown section (%s)",
485 g->name, g->vfollows);
486 } else if (g->prev != NULL)
487 for (s = sections; s && (s != g->prev); s = s->next) ;
488 /* The .bss section is the only one with prev = NULL.
489 In this case we implicitly follow the last progbits
490 section. */
491 else
492 s = last_progbits;
494 /* If the section we're following has a vstart, we can proceed. */
495 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
496 if (!(g->flags & VALIGN_DEFINED)) {
497 g->valign = 4;
498 g->flags |= VALIGN_DEFINED;
500 /* Compute the vstart address. */
501 g->vstart = ALIGN(s->vstart + s->length, g->valign);
502 g->flags |= VSTART_DEFINED;
503 h++;
504 /* Start and vstart mean the same thing for nobits sections. */
505 if (g->flags & TYPE_NOBITS)
506 g->start = g->vstart;
509 } while (h);
511 /* Now check for any circular vfollows references, which will manifest
512 * themselves as sections without a defined vstart. */
513 for (h = 0, s = sections; s; s = s->next) {
514 if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
515 * no-no, but we'll throw a fatal one eventually so it's ok. */
516 nasm_error(ERR_NONFATAL, "cannot compute vstart for section %s",
517 s->name);
518 h++;
521 if (h)
522 nasm_fatal(ERR_NOFILE, "circular vfollows path detected");
524 #ifdef DEBUG
525 nasm_error(ERR_DEBUG,
526 "bin_cleanup: Confirm final section order for output file:\n");
527 for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
528 h++, s = s->next)
529 fprintf(stdout, "%i. %s\n", h, s->name);
530 #endif
532 /* Step 5: Apply relocations. */
534 /* Prepare the sections for relocating. */
535 list_for_each(s, sections)
536 saa_rewind(s->contents);
537 /* Apply relocations. */
538 list_for_each(r, relocs) {
539 uint8_t *p, mydata[8];
540 int64_t l;
541 int b;
543 nasm_assert(r->bytes <= 8);
545 memset(mydata, 0, sizeof(mydata));
547 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
548 p = mydata;
549 l = 0;
550 for (b = r->bytes - 1; b >= 0; b--)
551 l = (l << 8) + mydata[b];
553 s = find_section_by_index(r->secref);
554 if (s) {
555 if (r->secref == s->start_index)
556 l += s->start;
557 else
558 l += s->vstart;
560 s = find_section_by_index(r->secrel);
561 if (s) {
562 if (r->secrel == s->start_index)
563 l -= s->start;
564 else
565 l -= s->vstart;
568 WRITEADDR(p, l, r->bytes);
569 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
572 /* Step 6: Write the section data to the output file. */
573 do_output();
575 /* Step 7: Generate the map file. */
577 if (map_control) {
578 static const char not_defined[] = "not defined";
580 /* Display input and output file names. */
581 fprintf(rf, "\n- NASM Map file ");
582 for (h = 63; h; h--)
583 fputc('-', rf);
584 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
585 infile, outfile);
587 if (map_control & MAP_ORIGIN) { /* Display program origin. */
588 fprintf(rf, "-- Program origin ");
589 for (h = 61; h; h--)
590 fputc('-', rf);
591 fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
593 /* Display sections summary. */
594 if (map_control & MAP_SUMMARY) {
595 fprintf(rf, "-- Sections (summary) ");
596 for (h = 57; h; h--)
597 fputc('-', rf);
598 fprintf(rf, "\n\nVstart Start Stop "
599 "Length Class Name\n");
600 list_for_each(s, sections) {
601 fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
602 s->vstart, s->start, s->start + s->length,
603 s->length);
604 if (s->flags & TYPE_PROGBITS)
605 fprintf(rf, "progbits ");
606 else
607 fprintf(rf, "nobits ");
608 fprintf(rf, "%s\n", s->name);
610 fprintf(rf, "\n");
612 /* Display detailed section information. */
613 if (map_control & MAP_SECTIONS) {
614 fprintf(rf, "-- Sections (detailed) ");
615 for (h = 56; h; h--)
616 fputc('-', rf);
617 fprintf(rf, "\n\n");
618 list_for_each(s, sections) {
619 fprintf(rf, "---- Section %s ", s->name);
620 for (h = 65 - strlen(s->name); h; h--)
621 fputc('-', rf);
622 fprintf(rf, "\n\nclass: ");
623 if (s->flags & TYPE_PROGBITS)
624 fprintf(rf, "progbits");
625 else
626 fprintf(rf, "nobits");
627 fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
628 "\nalign: ", s->length, s->start);
629 if (s->flags & ALIGN_DEFINED)
630 fprintf(rf, "%16"PRIX64"", s->align);
631 else
632 fputs(not_defined, rf);
633 fprintf(rf, "\nfollows: ");
634 if (s->flags & FOLLOWS_DEFINED)
635 fprintf(rf, "%s", s->follows);
636 else
637 fputs(not_defined, rf);
638 fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
639 if (s->flags & VALIGN_DEFINED)
640 fprintf(rf, "%16"PRIX64"", s->valign);
641 else
642 fputs(not_defined, rf);
643 fprintf(rf, "\nvfollows: ");
644 if (s->flags & VFOLLOWS_DEFINED)
645 fprintf(rf, "%s", s->vfollows);
646 else
647 fputs(not_defined, rf);
648 fprintf(rf, "\n\n");
651 /* Display symbols information. */
652 if (map_control & MAP_SYMBOLS) {
653 int32_t segment;
654 int64_t offset;
656 fprintf(rf, "-- Symbols ");
657 for (h = 68; h; h--)
658 fputc('-', rf);
659 fprintf(rf, "\n\n");
660 if (no_seg_labels) {
661 fprintf(rf, "---- No Section ");
662 for (h = 63; h; h--)
663 fputc('-', rf);
664 fprintf(rf, "\n\nValue Name\n");
665 list_for_each(l, no_seg_labels) {
666 lookup_label(l->name, &segment, &offset);
667 fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
669 fprintf(rf, "\n\n");
671 list_for_each(s, sections) {
672 if (s->labels) {
673 fprintf(rf, "---- Section %s ", s->name);
674 for (h = 65 - strlen(s->name); h; h--)
675 fputc('-', rf);
676 fprintf(rf, "\n\nReal Virtual Name\n");
677 list_for_each(l, s->labels) {
678 lookup_label(l->name, &segment, &offset);
679 fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
680 s->start + offset, s->vstart + offset,
681 l->name);
683 fprintf(rf, "\n");
689 /* Close the report file. */
690 if (map_control && (rf != stdout) && (rf != stderr))
691 fclose(rf);
693 /* Step 8: Release all allocated memory. */
695 /* Free sections, label pointer structs, etc.. */
696 while (sections) {
697 s = sections;
698 sections = s->next;
699 saa_free(s->contents);
700 nasm_free(s->name);
701 if (s->flags & FOLLOWS_DEFINED)
702 nasm_free(s->follows);
703 if (s->flags & VFOLLOWS_DEFINED)
704 nasm_free(s->vfollows);
705 while (s->labels) {
706 l = s->labels;
707 s->labels = l->next;
708 nasm_free(l);
710 nasm_free(s);
713 /* Free no-section labels. */
714 while (no_seg_labels) {
715 l = no_seg_labels;
716 no_seg_labels = l->next;
717 nasm_free(l);
720 /* Free relocation structures. */
721 while (relocs) {
722 r = relocs->next;
723 nasm_free(relocs);
724 relocs = r;
728 static void bin_out(int32_t segto, const void *data,
729 enum out_type type, uint64_t size,
730 int32_t segment, int32_t wrt)
732 uint8_t *p, mydata[8];
733 struct Section *s;
735 if (wrt != NO_SEG) {
736 wrt = NO_SEG; /* continue to do _something_ */
737 nasm_error(ERR_NONFATAL, "WRT not supported by binary output format");
740 /* Handle absolute-assembly (structure definitions). */
741 if (segto == NO_SEG) {
742 if (type != OUT_RESERVE)
743 nasm_error(ERR_NONFATAL, "attempt to assemble code in"
744 " [ABSOLUTE] space");
745 return;
748 /* Find the segment we are targeting. */
749 s = find_section_by_index(segto);
750 if (!s)
751 nasm_panic(0, "code directed to nonexistent segment?");
753 /* "Smart" section-type adaptation code. */
754 if (!(s->flags & TYPE_DEFINED)) {
755 if (type == OUT_RESERVE)
756 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
757 else
758 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
761 if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
762 nasm_error(ERR_WARNING, "attempt to initialize memory in a"
763 " nobits section: ignored");
765 switch (type) {
766 case OUT_ADDRESS:
768 int asize = abs((int)size);
770 if (segment != NO_SEG && !find_section_by_index(segment)) {
771 if (segment % 2)
772 nasm_error(ERR_NONFATAL, "binary output format does not support"
773 " segment base references");
774 else
775 nasm_error(ERR_NONFATAL, "binary output format does not support"
776 " external references");
777 segment = NO_SEG;
779 if (s->flags & TYPE_PROGBITS) {
780 if (segment != NO_SEG)
781 add_reloc(s, asize, segment, -1L);
782 p = mydata;
783 WRITEADDR(p, *(int64_t *)data, asize);
784 saa_wbytes(s->contents, mydata, asize);
788 * Reassign size with sign dropped, we will need it
789 * for section length calculation.
791 size = asize;
792 break;
795 case OUT_RAWDATA:
796 if (s->flags & TYPE_PROGBITS)
797 saa_wbytes(s->contents, data, size);
798 break;
800 case OUT_RESERVE:
801 if (s->flags & TYPE_PROGBITS) {
802 nasm_error(ERR_WARNING, "uninitialized space declared in"
803 " %s section: zeroing", s->name);
804 saa_wbytes(s->contents, NULL, size);
806 break;
808 case OUT_REL1ADR:
809 case OUT_REL2ADR:
810 case OUT_REL4ADR:
811 case OUT_REL8ADR:
813 int64_t addr = *(int64_t *)data - size;
814 size = realsize(type, size);
815 if (segment != NO_SEG && !find_section_by_index(segment)) {
816 if (segment % 2)
817 nasm_error(ERR_NONFATAL, "binary output format does not support"
818 " segment base references");
819 else
820 nasm_error(ERR_NONFATAL, "binary output format does not support"
821 " external references");
822 segment = NO_SEG;
824 if (s->flags & TYPE_PROGBITS) {
825 add_reloc(s, size, segment, segto);
826 p = mydata;
827 WRITEADDR(p, addr - s->length, size);
828 saa_wbytes(s->contents, mydata, size);
830 break;
833 default:
834 nasm_error(ERR_NONFATAL, "unsupported relocation type %d\n", type);
835 break;
838 s->length += size;
841 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
842 int is_global, char *special)
844 (void)segment; /* Don't warn that this parameter is unused */
845 (void)offset; /* Don't warn that this parameter is unused */
847 if (special)
848 nasm_error(ERR_NONFATAL, "binary format does not support any"
849 " special symbol types");
850 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
851 nasm_error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
852 else if (is_global == 2)
853 nasm_error(ERR_NONFATAL, "binary output format does not support common"
854 " variables");
855 else {
856 struct Section *s;
857 struct bin_label ***ltp;
859 /* Remember label definition so we can look it up later when
860 * creating the map file. */
861 s = find_section_by_index(segment);
862 if (s)
863 ltp = &(s->labels_end);
864 else
865 ltp = &nsl_tail;
866 (**ltp) = nasm_malloc(sizeof(struct bin_label));
867 (**ltp)->name = name;
868 (**ltp)->next = NULL;
869 *ltp = &((**ltp)->next);
874 /* These constants and the following function are used
875 * by bin_secname() to parse attribute assignments. */
877 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
878 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
879 ATTRIB_NOBITS, ATTRIB_PROGBITS
882 static int bin_read_attribute(char **line, int *attribute,
883 uint64_t *value)
885 expr *e;
886 int attrib_name_size;
887 struct tokenval tokval;
888 char *exp;
890 /* Skip whitespace. */
891 while (**line && nasm_isspace(**line))
892 (*line)++;
893 if (!**line)
894 return 0;
896 /* Figure out what attribute we're reading. */
897 if (!nasm_strnicmp(*line, "align=", 6)) {
898 *attribute = ATTRIB_ALIGN;
899 attrib_name_size = 6;
900 } else {
901 if (!nasm_strnicmp(*line, "start=", 6)) {
902 *attribute = ATTRIB_START;
903 attrib_name_size = 6;
904 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
905 *attribute = ATTRIB_FOLLOWS;
906 *line += 8;
907 return 1;
908 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
909 *attribute = ATTRIB_VSTART;
910 attrib_name_size = 7;
911 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
912 *attribute = ATTRIB_VALIGN;
913 attrib_name_size = 7;
914 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
915 *attribute = ATTRIB_VFOLLOWS;
916 *line += 9;
917 return 1;
918 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
919 (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
920 *attribute = ATTRIB_NOBITS;
921 *line += 6;
922 return 1;
923 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
924 (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
925 *attribute = ATTRIB_PROGBITS;
926 *line += 8;
927 return 1;
928 } else
929 return 0;
932 /* Find the end of the expression. */
933 if ((*line)[attrib_name_size] != '(') {
934 /* Single term (no parenthesis). */
935 exp = *line += attrib_name_size;
936 while (**line && !nasm_isspace(**line))
937 (*line)++;
938 if (**line) {
939 **line = '\0';
940 (*line)++;
942 } else {
943 char c;
944 int pcount = 1;
946 /* Full expression (delimited by parenthesis) */
947 exp = *line += attrib_name_size + 1;
948 while (1) {
949 (*line) += strcspn(*line, "()'\"");
950 if (**line == '(') {
951 ++(*line);
952 ++pcount;
954 if (**line == ')') {
955 ++(*line);
956 --pcount;
957 if (!pcount)
958 break;
960 if ((**line == '"') || (**line == '\'')) {
961 c = **line;
962 while (**line) {
963 ++(*line);
964 if (**line == c)
965 break;
967 if (!**line) {
968 nasm_error(ERR_NONFATAL,
969 "invalid syntax in `section' directive");
970 return -1;
972 ++(*line);
974 if (!**line) {
975 nasm_error(ERR_NONFATAL, "expecting `)'");
976 return -1;
979 *(*line - 1) = '\0'; /* Terminate the expression. */
982 /* Check for no value given. */
983 if (!*exp) {
984 nasm_error(ERR_WARNING, "No value given to attribute in"
985 " `section' directive");
986 return -1;
989 /* Read and evaluate the expression. */
990 stdscan_reset();
991 stdscan_set(exp);
992 tokval.t_type = TOKEN_INVALID;
993 e = evaluate(stdscan, NULL, &tokval, NULL, 1, NULL);
994 if (e) {
995 if (!is_really_simple(e)) {
996 nasm_error(ERR_NONFATAL, "section attribute value must be"
997 " a critical expression");
998 return -1;
1000 } else {
1001 nasm_error(ERR_NONFATAL, "Invalid attribute value"
1002 " specified in `section' directive.");
1003 return -1;
1005 *value = (uint64_t)reloc_value(e);
1006 return 1;
1009 static void bin_sectalign(int32_t seg, unsigned int value)
1011 struct Section *s = find_section_by_index(seg);
1013 if (!s || !is_power2(value))
1014 return;
1016 if (value > s->align)
1017 s->align = value;
1019 if (!(s->flags & ALIGN_DEFINED))
1020 s->flags |= ALIGN_DEFINED;
1023 static void bin_assign_attributes(struct Section *sec, char *astring)
1025 int attribute, check;
1026 uint64_t value;
1027 char *p;
1029 while (1) { /* Get the next attribute. */
1030 check = bin_read_attribute(&astring, &attribute, &value);
1031 /* Skip bad attribute. */
1032 if (check == -1)
1033 continue;
1034 /* Unknown section attribute, so skip it and warn the user. */
1035 if (!check) {
1036 if (!*astring)
1037 break; /* End of line. */
1038 else {
1039 p = astring;
1040 while (*astring && !nasm_isspace(*astring))
1041 astring++;
1042 if (*astring) {
1043 *astring = '\0';
1044 astring++;
1046 nasm_error(ERR_WARNING, "ignoring unknown section attribute:"
1047 " \"%s\"", p);
1049 continue;
1052 switch (attribute) { /* Handle nobits attribute. */
1053 case ATTRIB_NOBITS:
1054 if ((sec->flags & TYPE_DEFINED)
1055 && (sec->flags & TYPE_PROGBITS))
1056 nasm_error(ERR_NONFATAL,
1057 "attempt to change section type"
1058 " from progbits to nobits");
1059 else
1060 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1061 continue;
1063 /* Handle progbits attribute. */
1064 case ATTRIB_PROGBITS:
1065 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1066 nasm_error(ERR_NONFATAL, "attempt to change section type"
1067 " from nobits to progbits");
1068 else
1069 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1070 continue;
1072 /* Handle align attribute. */
1073 case ATTRIB_ALIGN:
1074 if (!value || ((value - 1) & value)) {
1075 nasm_error(ERR_NONFATAL,
1076 "argument to `align' is not a power of two");
1077 } else {
1079 * Alignment is already satisfied if
1080 * the previous align value is greater
1082 if ((sec->flags & ALIGN_DEFINED) && (value < sec->align))
1083 value = sec->align;
1085 /* Don't allow a conflicting align value. */
1086 if ((sec->flags & START_DEFINED) && (sec->start & (value - 1))) {
1087 nasm_error(ERR_NONFATAL,
1088 "`align' value conflicts with section start address");
1089 } else {
1090 sec->align = value;
1091 sec->flags |= ALIGN_DEFINED;
1094 continue;
1096 /* Handle valign attribute. */
1097 case ATTRIB_VALIGN:
1098 if (!value || ((value - 1) & value))
1099 nasm_error(ERR_NONFATAL, "argument to `valign' is not a"
1100 " power of two");
1101 else { /* Alignment is already satisfied if the previous
1102 * align value is greater. */
1103 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1104 value = sec->valign;
1106 /* Don't allow a conflicting valign value. */
1107 if ((sec->flags & VSTART_DEFINED)
1108 && (sec->vstart & (value - 1)))
1109 nasm_error(ERR_NONFATAL,
1110 "`valign' value conflicts "
1111 "with `vstart' address");
1112 else {
1113 sec->valign = value;
1114 sec->flags |= VALIGN_DEFINED;
1117 continue;
1119 /* Handle start attribute. */
1120 case ATTRIB_START:
1121 if (sec->flags & FOLLOWS_DEFINED)
1122 nasm_error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1123 " section attributes");
1124 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1125 nasm_error(ERR_NONFATAL, "section start address redefined");
1126 else {
1127 sec->start = value;
1128 sec->flags |= START_DEFINED;
1129 if (sec->flags & ALIGN_DEFINED) {
1130 if (sec->start & (sec->align - 1))
1131 nasm_error(ERR_NONFATAL, "`start' address conflicts"
1132 " with section alignment");
1133 sec->flags ^= ALIGN_DEFINED;
1136 continue;
1138 /* Handle vstart attribute. */
1139 case ATTRIB_VSTART:
1140 if (sec->flags & VFOLLOWS_DEFINED)
1141 nasm_error(ERR_NONFATAL,
1142 "cannot combine `vstart' and `vfollows'"
1143 " section attributes");
1144 else if ((sec->flags & VSTART_DEFINED)
1145 && (value != sec->vstart))
1146 nasm_error(ERR_NONFATAL,
1147 "section virtual start address"
1148 " (vstart) redefined");
1149 else {
1150 sec->vstart = value;
1151 sec->flags |= VSTART_DEFINED;
1152 if (sec->flags & VALIGN_DEFINED) {
1153 if (sec->vstart & (sec->valign - 1))
1154 nasm_error(ERR_NONFATAL, "`vstart' address conflicts"
1155 " with `valign' value");
1156 sec->flags ^= VALIGN_DEFINED;
1159 continue;
1161 /* Handle follows attribute. */
1162 case ATTRIB_FOLLOWS:
1163 p = astring;
1164 astring += strcspn(astring, " \t");
1165 if (astring == p)
1166 nasm_error(ERR_NONFATAL, "expecting section name for `follows'"
1167 " attribute");
1168 else {
1169 *(astring++) = '\0';
1170 if (sec->flags & START_DEFINED)
1171 nasm_error(ERR_NONFATAL,
1172 "cannot combine `start' and `follows'"
1173 " section attributes");
1174 sec->follows = nasm_strdup(p);
1175 sec->flags |= FOLLOWS_DEFINED;
1177 continue;
1179 /* Handle vfollows attribute. */
1180 case ATTRIB_VFOLLOWS:
1181 if (sec->flags & VSTART_DEFINED)
1182 nasm_error(ERR_NONFATAL,
1183 "cannot combine `vstart' and `vfollows'"
1184 " section attributes");
1185 else {
1186 p = astring;
1187 astring += strcspn(astring, " \t");
1188 if (astring == p)
1189 nasm_error(ERR_NONFATAL,
1190 "expecting section name for `vfollows'"
1191 " attribute");
1192 else {
1193 *(astring++) = '\0';
1194 sec->vfollows = nasm_strdup(p);
1195 sec->flags |= VFOLLOWS_DEFINED;
1198 continue;
1203 static void bin_define_section_labels(void)
1205 static int labels_defined = 0;
1206 struct Section *sec;
1207 char *label_name;
1208 size_t base_len;
1210 if (labels_defined)
1211 return;
1212 list_for_each(sec, sections) {
1213 base_len = strlen(sec->name) + 8;
1214 label_name = nasm_malloc(base_len + 8);
1215 strcpy(label_name, "section.");
1216 strcpy(label_name + 8, sec->name);
1218 /* section.<name>.start */
1219 strcpy(label_name + base_len, ".start");
1220 define_label(label_name, sec->start_index, 0L, NULL, 0, 0);
1222 /* section.<name>.vstart */
1223 strcpy(label_name + base_len, ".vstart");
1224 define_label(label_name, sec->vstart_index, 0L, NULL, 0, 0);
1226 nasm_free(label_name);
1228 labels_defined = 1;
1231 static int32_t bin_secname(char *name, int pass, int *bits)
1233 char *p;
1234 struct Section *sec;
1236 /* bin_secname is called with *name = NULL at the start of each
1237 * pass. Use this opportunity to establish the default section
1238 * (default is BITS-16 ".text" segment).
1240 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1241 origin_defined = 0;
1242 list_for_each(sec, sections)
1243 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1244 ALIGN_DEFINED | VALIGN_DEFINED);
1246 /* Define section start and vstart labels. */
1247 if (pass != 1)
1248 bin_define_section_labels();
1250 /* Establish the default (.text) section. */
1251 *bits = 16;
1252 sec = find_section_by_name(".text");
1253 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1254 return sec->vstart_index;
1257 /* Attempt to find the requested section. If it does not
1258 * exist, create it. */
1259 p = name;
1260 while (*p && !nasm_isspace(*p))
1261 p++;
1262 if (*p)
1263 *p++ = '\0';
1264 sec = find_section_by_name(name);
1265 if (!sec) {
1266 sec = create_section(name);
1267 if (!strcmp(name, ".data"))
1268 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1269 else if (!strcmp(name, ".bss")) {
1270 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1271 sec->prev = NULL;
1275 /* Handle attribute assignments. */
1276 if (pass != 1)
1277 bin_assign_attributes(sec, p);
1279 #ifndef ABIN_SMART_ADAPT
1280 /* The following line disables smart adaptation of
1281 * PROGBITS/NOBITS section types (it forces sections to
1282 * default to PROGBITS). */
1283 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1284 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1285 #endif
1287 return sec->vstart_index;
1290 static int bin_directive(enum directives directive, char *args, int pass)
1292 switch (directive) {
1293 case D_ORG:
1295 struct tokenval tokval;
1296 uint64_t value;
1297 expr *e;
1299 stdscan_reset();
1300 stdscan_set(args);
1301 tokval.t_type = TOKEN_INVALID;
1302 e = evaluate(stdscan, NULL, &tokval, NULL, 1, NULL);
1303 if (e) {
1304 if (!is_really_simple(e))
1305 nasm_error(ERR_NONFATAL, "org value must be a critical"
1306 " expression");
1307 else {
1308 value = reloc_value(e);
1309 /* Check for ORG redefinition. */
1310 if (origin_defined && (value != origin))
1311 nasm_error(ERR_NONFATAL, "program origin redefined");
1312 else {
1313 origin = value;
1314 origin_defined = 1;
1317 } else
1318 nasm_error(ERR_NONFATAL, "No or invalid offset specified"
1319 " in ORG directive.");
1320 return 1;
1322 case D_MAP:
1324 /* The 'map' directive allows the user to generate section
1325 * and symbol information to stdout, stderr, or to a file. */
1326 char *p;
1328 if (pass != 1)
1329 return 1;
1330 args += strspn(args, " \t");
1331 while (*args) {
1332 p = args;
1333 args += strcspn(args, " \t");
1334 if (*args != '\0')
1335 *(args++) = '\0';
1336 if (!nasm_stricmp(p, "all"))
1337 map_control |=
1338 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1339 else if (!nasm_stricmp(p, "brief"))
1340 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1341 else if (!nasm_stricmp(p, "sections"))
1342 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1343 else if (!nasm_stricmp(p, "segments"))
1344 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1345 else if (!nasm_stricmp(p, "symbols"))
1346 map_control |= MAP_SYMBOLS;
1347 else if (!rf) {
1348 if (!nasm_stricmp(p, "stdout"))
1349 rf = stdout;
1350 else if (!nasm_stricmp(p, "stderr"))
1351 rf = stderr;
1352 else { /* Must be a filename. */
1353 rf = fopen(p, "wt");
1354 if (!rf) {
1355 nasm_error(ERR_WARNING, "unable to open map file `%s'",
1357 map_control = 0;
1358 return 1;
1361 } else
1362 nasm_error(ERR_WARNING, "map file already specified");
1364 if (map_control == 0)
1365 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1366 if (!rf)
1367 rf = stdout;
1368 return 1;
1370 default:
1371 return 0;
1375 static void bin_filename(char *inname, char *outname)
1377 standard_extension(inname, outname, "");
1378 infile = inname;
1379 outfile = outname;
1382 static void ith_filename(char *inname, char *outname)
1384 standard_extension(inname, outname, ".ith");
1385 infile = inname;
1386 outfile = outname;
1389 static void srec_filename(char *inname, char *outname)
1391 standard_extension(inname, outname, ".srec");
1392 infile = inname;
1393 outfile = outname;
1396 static int32_t bin_segbase(int32_t segment)
1398 return segment;
1401 static int bin_set_info(enum geninfo type, char **val)
1403 (void)type;
1404 (void)val;
1405 return 0;
1408 struct ofmt of_bin, of_ith, of_srec;
1409 static void binfmt_init(void);
1410 static void do_output_bin(void);
1411 static void do_output_ith(void);
1412 static void do_output_srec(void);
1414 static void bin_init(void)
1416 do_output = do_output_bin;
1417 binfmt_init();
1420 static void ith_init(void)
1422 do_output = do_output_ith;
1423 binfmt_init();
1426 static void srec_init(void)
1428 do_output = do_output_srec;
1429 binfmt_init();
1432 static void binfmt_init(void)
1434 relocs = NULL;
1435 reloctail = &relocs;
1436 origin_defined = 0;
1437 no_seg_labels = NULL;
1438 nsl_tail = &no_seg_labels;
1440 /* Create default section (.text). */
1441 sections = last_section = nasm_zalloc(sizeof(struct Section));
1442 last_section->name = nasm_strdup(".text");
1443 last_section->contents = saa_init(1L);
1444 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1445 last_section->labels_end = &(last_section->labels);
1446 last_section->start_index = seg_alloc();
1447 last_section->vstart_index = seg_alloc();
1450 /* Generate binary file output */
1451 static void do_output_bin(void)
1453 struct Section *s;
1454 uint64_t addr = origin;
1456 /* Write the progbits sections to the output file. */
1457 list_for_each(s, sections) {
1458 /* Skip non-progbits sections */
1459 if (!(s->flags & TYPE_PROGBITS))
1460 continue;
1461 /* Skip zero-length sections */
1462 if (s->length == 0)
1463 continue;
1465 /* Pad the space between sections. */
1466 nasm_assert(addr <= s->start);
1467 fwritezero(s->start - addr, ofile);
1469 /* Write the section to the output file. */
1470 saa_fpwrite(s->contents, ofile);
1472 /* Keep track of the current file position */
1473 addr = s->start + s->length;
1477 /* Generate Intel hex file output */
1478 static void write_ith_record(unsigned int len, uint16_t addr,
1479 uint8_t type, void *data)
1481 char buf[1+2+4+2+255*2+2+2];
1482 char *p = buf;
1483 uint8_t csum, *dptr = data;
1484 unsigned int i;
1486 nasm_assert(len <= 255);
1488 csum = len + addr + (addr >> 8) + type;
1489 for (i = 0; i < len; i++)
1490 csum += dptr[i];
1491 csum = -csum;
1493 p += sprintf(p, ":%02X%04X%02X", len, addr, type);
1494 for (i = 0; i < len; i++)
1495 p += sprintf(p, "%02X", dptr[i]);
1496 p += sprintf(p, "%02X\n", csum);
1498 nasm_write(buf, p-buf, ofile);
1501 static void do_output_ith(void)
1503 uint8_t buf[32];
1504 struct Section *s;
1505 uint64_t addr, hiaddr, hilba;
1506 uint64_t length;
1507 unsigned int chunk;
1509 /* Write the progbits sections to the output file. */
1510 hilba = 0;
1511 list_for_each(s, sections) {
1512 /* Skip non-progbits sections */
1513 if (!(s->flags & TYPE_PROGBITS))
1514 continue;
1515 /* Skip zero-length sections */
1516 if (s->length == 0)
1517 continue;
1519 addr = s->start;
1520 length = s->length;
1521 saa_rewind(s->contents);
1523 while (length) {
1524 hiaddr = addr >> 16;
1525 if (hiaddr != hilba) {
1526 buf[0] = hiaddr >> 8;
1527 buf[1] = hiaddr;
1528 write_ith_record(2, 0, 4, buf);
1529 hilba = hiaddr;
1532 chunk = 32 - (addr & 31);
1533 if (length < chunk)
1534 chunk = length;
1536 saa_rnbytes(s->contents, buf, chunk);
1537 write_ith_record(chunk, (uint16_t)addr, 0, buf);
1539 addr += chunk;
1540 length -= chunk;
1544 /* Write closing record */
1545 write_ith_record(0, 0, 1, NULL);
1548 /* Generate Motorola S-records */
1549 static void write_srecord(unsigned int len, unsigned int alen,
1550 uint32_t addr, uint8_t type, void *data)
1552 char buf[2+2+8+255*2+2+2];
1553 char *p = buf;
1554 uint8_t csum, *dptr = data;
1555 unsigned int i;
1557 nasm_assert(len <= 255);
1559 switch (alen) {
1560 case 2:
1561 addr &= 0xffff;
1562 break;
1563 case 3:
1564 addr &= 0xffffff;
1565 break;
1566 case 4:
1567 break;
1568 default:
1569 nasm_assert(0);
1570 break;
1573 csum = (len+alen+1) + addr + (addr >> 8) + (addr >> 16) + (addr >> 24);
1574 for (i = 0; i < len; i++)
1575 csum += dptr[i];
1576 csum = 0xff-csum;
1578 p += sprintf(p, "S%c%02X%0*X", type, len+alen+1, alen*2, addr);
1579 for (i = 0; i < len; i++)
1580 p += sprintf(p, "%02X", dptr[i]);
1581 p += sprintf(p, "%02X\n", csum);
1583 nasm_write(buf, p-buf, ofile);
1586 static void do_output_srec(void)
1588 uint8_t buf[32];
1589 struct Section *s;
1590 uint64_t addr, maxaddr;
1591 uint64_t length;
1592 int alen;
1593 unsigned int chunk;
1594 char dtype, etype;
1596 maxaddr = 0;
1597 list_for_each(s, sections) {
1598 /* Skip non-progbits sections */
1599 if (!(s->flags & TYPE_PROGBITS))
1600 continue;
1601 /* Skip zero-length sections */
1602 if (s->length == 0)
1603 continue;
1605 addr = s->start + s->length - 1;
1606 if (addr > maxaddr)
1607 maxaddr = addr;
1610 if (maxaddr <= 0xffff) {
1611 alen = 2;
1612 dtype = '1'; /* S1 = 16-bit data */
1613 etype = '9'; /* S9 = 16-bit end */
1614 } else if (maxaddr <= 0xffffff) {
1615 alen = 3;
1616 dtype = '2'; /* S2 = 24-bit data */
1617 etype = '8'; /* S8 = 24-bit end */
1618 } else {
1619 alen = 4;
1620 dtype = '3'; /* S3 = 32-bit data */
1621 etype = '7'; /* S7 = 32-bit end */
1624 /* Write head record */
1625 write_srecord(0, 2, 0, '0', NULL);
1627 /* Write the progbits sections to the output file. */
1628 list_for_each(s, sections) {
1629 /* Skip non-progbits sections */
1630 if (!(s->flags & TYPE_PROGBITS))
1631 continue;
1632 /* Skip zero-length sections */
1633 if (s->length == 0)
1634 continue;
1636 addr = s->start;
1637 length = s->length;
1638 saa_rewind(s->contents);
1640 while (length) {
1641 chunk = 32 - (addr & 31);
1642 if (length < chunk)
1643 chunk = length;
1645 saa_rnbytes(s->contents, buf, chunk);
1646 write_srecord(chunk, alen, (uint32_t)addr, dtype, buf);
1648 addr += chunk;
1649 length -= chunk;
1653 /* Write closing record */
1654 write_srecord(0, alen, 0, etype, NULL);
1658 struct ofmt of_bin = {
1659 "flat-form binary files (e.g. DOS .COM, .SYS)",
1660 "bin",
1663 null_debug_arr,
1664 &null_debug_form,
1665 bin_stdmac,
1666 bin_init,
1667 bin_set_info,
1668 bin_out,
1669 bin_deflabel,
1670 bin_secname,
1671 bin_sectalign,
1672 bin_segbase,
1673 bin_directive,
1674 bin_filename,
1675 bin_cleanup
1678 struct ofmt of_ith = {
1679 "Intel hex",
1680 "ith",
1681 OFMT_TEXT,
1683 null_debug_arr,
1684 &null_debug_form,
1685 bin_stdmac,
1686 ith_init,
1687 bin_set_info,
1688 bin_out,
1689 bin_deflabel,
1690 bin_secname,
1691 bin_sectalign,
1692 bin_segbase,
1693 bin_directive,
1694 ith_filename,
1695 bin_cleanup
1698 struct ofmt of_srec = {
1699 "Motorola S-records",
1700 "srec",
1701 OFMT_TEXT,
1703 null_debug_arr,
1704 &null_debug_form,
1705 bin_stdmac,
1706 srec_init,
1707 bin_set_info,
1708 bin_out,
1709 bin_deflabel,
1710 bin_secname,
1711 bin_sectalign,
1712 bin_segbase,
1713 bin_directive,
1714 srec_filename,
1715 bin_cleanup
1718 #endif /* #ifdef OF_BIN */