asm/*: Move directive processing to its own file, refactor error handling
[nasm.git] / output / outbin.c
blob04f27f8c44af2002ea7364db39819ffd3123a6dc
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>
83 #include "nasm.h"
84 #include "nasmlib.h"
85 #include "error.h"
86 #include "saa.h"
87 #include "stdscan.h"
88 #include "labels.h"
89 #include "eval.h"
90 #include "outform.h"
91 #include "outlib.h"
93 #ifdef OF_BIN
95 static FILE *rf = NULL;
96 static void (*do_output)(void);
98 /* Section flags keep track of which attributes the user has defined. */
99 #define START_DEFINED 0x001
100 #define ALIGN_DEFINED 0x002
101 #define FOLLOWS_DEFINED 0x004
102 #define VSTART_DEFINED 0x008
103 #define VALIGN_DEFINED 0x010
104 #define VFOLLOWS_DEFINED 0x020
105 #define TYPE_DEFINED 0x040
106 #define TYPE_PROGBITS 0x080
107 #define TYPE_NOBITS 0x100
109 /* This struct is used to keep track of symbols for map-file generation. */
110 static struct bin_label {
111 char *name;
112 struct bin_label *next;
113 } *no_seg_labels, **nsl_tail;
115 static struct Section {
116 char *name;
117 struct SAA *contents;
118 int64_t length; /* section length in bytes */
120 /* Section attributes */
121 int flags; /* see flag definitions above */
122 uint64_t align; /* section alignment */
123 uint64_t valign; /* notional section alignment */
124 uint64_t start; /* section start address */
125 uint64_t vstart; /* section virtual start address */
126 char *follows; /* the section that this one will follow */
127 char *vfollows; /* the section that this one will notionally follow */
128 int32_t start_index; /* NASM section id for non-relocated version */
129 int32_t vstart_index; /* the NASM section id */
131 struct bin_label *labels; /* linked-list of label handles for map output. */
132 struct bin_label **labels_end; /* Holds address of end of labels list. */
133 struct Section *prev; /* Points to previous section (implicit follows). */
134 struct Section *next; /* This links sections with a defined start address. */
136 /* The extended bin format allows for sections to have a "virtual"
137 * start address. This is accomplished by creating two sections:
138 * one beginning at the Load Memory Address and the other beginning
139 * at the Virtual Memory Address. The LMA section is only used to
140 * define the section.<section_name>.start label, but there isn't
141 * any other good way for us to handle that label.
144 } *sections, *last_section;
146 static struct Reloc {
147 struct Reloc *next;
148 int32_t posn;
149 int32_t bytes;
150 int32_t secref;
151 int32_t secrel;
152 struct Section *target;
153 } *relocs, **reloctail;
155 static uint64_t origin;
156 static int origin_defined;
158 /* Stuff we need for map-file generation. */
159 #define MAP_ORIGIN 1
160 #define MAP_SUMMARY 2
161 #define MAP_SECTIONS 4
162 #define MAP_SYMBOLS 8
163 static int map_control = 0;
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(void)
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 #ifdef DEBUG
236 nasm_error(ERR_DEBUG,
237 "bin_cleanup: Sections were initially referenced in this order:\n");
238 for (h = 0, s = sections; s; h++, s = s->next)
239 fprintf(stdout, "%i. %s\n", h, s->name);
240 #endif
242 /* Assembly has completed, so now we need to generate the output file.
243 * Step 1: Separate progbits and nobits sections into separate lists.
244 * Step 2: Sort the progbits sections into their output order.
245 * Step 3: Compute start addresses for all progbits sections.
246 * Step 4: Compute vstart addresses for all sections.
247 * Step 5: Apply relocations.
248 * Step 6: Write the sections' data to the output file.
249 * Step 7: Generate the map file.
250 * Step 8: Release all allocated memory.
253 /* To do: Smart section-type adaptation could leave some empty sections
254 * without a defined type (progbits/nobits). Won't fix now since this
255 * feature will be disabled. */
257 /* Step 1: Split progbits and nobits sections into separate lists. */
259 nt = &nobits;
260 /* Move nobits sections into a separate list. Also pre-process nobits
261 * sections' attributes. */
262 for (sp = &sections->next, s = sections->next; s; s = *sp) { /* Skip progbits sections. */
263 if (s->flags & TYPE_PROGBITS) {
264 sp = &s->next;
265 continue;
267 /* Do some special pre-processing on nobits sections' attributes. */
268 if (s->flags & (START_DEFINED | ALIGN_DEFINED | FOLLOWS_DEFINED)) { /* Check for a mixture of real and virtual section attributes. */
269 if (s->flags & (VSTART_DEFINED | VALIGN_DEFINED |
270 VFOLLOWS_DEFINED))
271 nasm_fatal(ERR_NOFILE,
272 "cannot mix real and virtual attributes"
273 " in nobits section (%s)", s->name);
274 /* Real and virtual attributes mean the same thing for nobits sections. */
275 if (s->flags & START_DEFINED) {
276 s->vstart = s->start;
277 s->flags |= VSTART_DEFINED;
279 if (s->flags & ALIGN_DEFINED) {
280 s->valign = s->align;
281 s->flags |= VALIGN_DEFINED;
283 if (s->flags & FOLLOWS_DEFINED) {
284 s->vfollows = s->follows;
285 s->flags |= VFOLLOWS_DEFINED;
286 s->flags &= ~FOLLOWS_DEFINED;
289 /* Every section must have a start address. */
290 if (s->flags & VSTART_DEFINED) {
291 s->start = s->vstart;
292 s->flags |= START_DEFINED;
294 /* Move the section into the nobits list. */
295 *sp = s->next;
296 s->next = NULL;
297 *nt = s;
298 nt = &s->next;
301 /* Step 2: Sort the progbits sections into their output order. */
303 /* In Step 2 we move around sections in groups. A group
304 * begins with a section (group leader) that has a user-
305 * defined start address or follows section. The remainder
306 * of the group is made up of the sections that implicitly
307 * follow the group leader (i.e., they were defined after
308 * the group leader and were not given an explicit start
309 * address or follows section by the user). */
311 /* For anyone attempting to read this code:
312 * g (group) points to a group of sections, the first one of which has
313 * a user-defined start address or follows section.
314 * gp (g previous) holds the location of the pointer to g.
315 * gs (g scan) is a temp variable that we use to scan to the end of the group.
316 * gsp (gs previous) holds the location of the pointer to gs.
317 * nt (nobits tail) points to the nobits section-list tail.
320 /* Link all 'follows' groups to their proper position. To do
321 * this we need to know three things: the start of the group
322 * to relocate (g), the section it is following (s), and the
323 * end of the group we're relocating (gs). */
324 for (gp = &sections, g = sections; g; g = gs) { /* Find the next follows group that is out of place (g). */
325 if (!(g->flags & FOLLOWS_DEFINED)) {
326 while (g->next) {
327 if ((g->next->flags & FOLLOWS_DEFINED) &&
328 strcmp(g->name, g->next->follows))
329 break;
330 g = g->next;
332 if (!g->next)
333 break;
334 gp = &g->next;
335 g = g->next;
337 /* Find the section that this group follows (s). */
338 for (sp = &sections, s = sections;
339 s && strcmp(s->name, g->follows);
340 sp = &s->next, s = s->next) ;
341 if (!s)
342 nasm_fatal(ERR_NOFILE, "section %s follows an invalid or"
343 " unknown section (%s)", g->name, g->follows);
344 if (s->next && (s->next->flags & FOLLOWS_DEFINED) &&
345 !strcmp(s->name, s->next->follows))
346 nasm_fatal(ERR_NOFILE, "sections %s and %s can't both follow"
347 " section %s", g->name, s->next->name, s->name);
348 /* Find the end of the current follows group (gs). */
349 for (gsp = &g->next, gs = g->next;
350 gs && (gs != s) && !(gs->flags & START_DEFINED);
351 gsp = &gs->next, gs = gs->next) {
352 if (gs->next && (gs->next->flags & FOLLOWS_DEFINED) &&
353 strcmp(gs->name, gs->next->follows)) {
354 gsp = &gs->next;
355 gs = gs->next;
356 break;
359 /* Re-link the group after its follows section. */
360 *gsp = s->next;
361 s->next = g;
362 *gp = gs;
365 /* Link all 'start' groups to their proper position. Once
366 * again we need to know g, s, and gs (see above). The main
367 * difference is we already know g since we sort by moving
368 * groups from the 'unsorted' list into a 'sorted' list (g
369 * will always be the first section in the unsorted list). */
370 for (g = sections, sections = NULL; g; g = gs) { /* Find the section that we will insert this group before (s). */
371 for (sp = &sections, s = sections; s; sp = &s->next, s = s->next)
372 if ((s->flags & START_DEFINED) && (g->start < s->start))
373 break;
374 /* Find the end of the group (gs). */
375 for (gs = g->next, gsp = &g->next;
376 gs && !(gs->flags & START_DEFINED);
377 gsp = &gs->next, gs = gs->next) ;
378 /* Re-link the group before the target section. */
379 *sp = g;
380 *gsp = s;
383 /* Step 3: Compute start addresses for all progbits sections. */
385 /* Make sure we have an origin and a start address for the first section. */
386 if (origin_defined) {
387 if (sections->flags & START_DEFINED) {
388 /* Make sure this section doesn't begin before the origin. */
389 if (sections->start < origin)
390 nasm_fatal(ERR_NOFILE, "section %s begins"
391 " before program origin", sections->name);
392 } else if (sections->flags & ALIGN_DEFINED) {
393 sections->start = ALIGN(origin, sections->align);
394 } else {
395 sections->start = origin;
397 } else {
398 if (!(sections->flags & START_DEFINED))
399 sections->start = 0;
400 origin = sections->start;
402 sections->flags |= START_DEFINED;
404 /* Make sure each section has an explicit start address. If it
405 * doesn't, then compute one based its alignment and the end of
406 * the previous section. */
407 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
408 * (has a defined start address, and is not zero length). */
409 if (g == s)
410 for (s = g->next;
411 s && ((s->length == 0) || !(s->flags & START_DEFINED));
412 s = s->next) ;
413 /* Compute the start address of this section, if necessary. */
414 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
415 if (!(g->flags & ALIGN_DEFINED)) {
416 g->align = 4;
417 g->flags |= ALIGN_DEFINED;
419 /* Set the section start address. */
420 g->start = ALIGN(pend, g->align);
421 g->flags |= START_DEFINED;
423 /* Ugly special case for progbits sections' virtual attributes:
424 * If there is a defined valign, but no vstart and no vfollows, then
425 * we valign after the previous progbits section. This case doesn't
426 * really make much sense for progbits sections with a defined start
427 * address, but it is possible and we must do *something*.
428 * Not-so-ugly special case:
429 * If a progbits section has no virtual attributes, we set the
430 * vstart equal to the start address. */
431 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
432 if (g->flags & VALIGN_DEFINED)
433 g->vstart = ALIGN(pend, g->valign);
434 else
435 g->vstart = g->start;
436 g->flags |= VSTART_DEFINED;
438 /* Ignore zero-length sections. */
439 if (g->start < pend)
440 continue;
441 /* Compute the span of this section. */
442 pend = g->start + g->length;
443 /* Check for section overlap. */
444 if (s) {
445 if (s->start < origin)
446 nasm_fatal(ERR_NOFILE, "section %s beings before program origin",
447 s->name);
448 if (g->start > s->start)
449 nasm_fatal(ERR_NOFILE, "sections %s ~ %s and %s overlap!",
450 gs->name, g->name, s->name);
451 if (pend > s->start)
452 nasm_fatal(ERR_NOFILE, "sections %s and %s overlap!",
453 g->name, s->name);
455 /* Remember this section as the latest >0 length section. */
456 gs = g;
459 /* Step 4: Compute vstart addresses for all sections. */
461 /* Attach the nobits sections to the end of the progbits sections. */
462 for (s = sections; s->next; s = s->next) ;
463 s->next = nobits;
464 last_progbits = s;
466 * Scan for sections that don't have a vstart address. If we find
467 * one we'll attempt to compute its vstart. If we can't compute
468 * the vstart, we leave it alone and come back to it in a
469 * subsequent scan. We continue scanning and re-scanning until
470 * we've gone one full cycle without computing any vstarts.
472 do { /* Do one full scan of the sections list. */
473 for (h = 0, g = sections; g; g = g->next) {
474 if (g->flags & VSTART_DEFINED)
475 continue;
476 /* Find the section that this one virtually follows. */
477 if (g->flags & VFOLLOWS_DEFINED) {
478 for (s = sections; s && strcmp(g->vfollows, s->name);
479 s = s->next) ;
480 if (!s)
481 nasm_fatal(ERR_NOFILE,
482 "section %s vfollows unknown section (%s)",
483 g->name, g->vfollows);
484 } else if (g->prev != NULL)
485 for (s = sections; s && (s != g->prev); s = s->next) ;
486 /* The .bss section is the only one with prev = NULL.
487 In this case we implicitly follow the last progbits
488 section. */
489 else
490 s = last_progbits;
492 /* If the section we're following has a vstart, we can proceed. */
493 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
494 if (!(g->flags & VALIGN_DEFINED)) {
495 g->valign = 4;
496 g->flags |= VALIGN_DEFINED;
498 /* Compute the vstart address. */
499 g->vstart = ALIGN(s->vstart + s->length, g->valign);
500 g->flags |= VSTART_DEFINED;
501 h++;
502 /* Start and vstart mean the same thing for nobits sections. */
503 if (g->flags & TYPE_NOBITS)
504 g->start = g->vstart;
507 } while (h);
509 /* Now check for any circular vfollows references, which will manifest
510 * themselves as sections without a defined vstart. */
511 for (h = 0, s = sections; s; s = s->next) {
512 if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
513 * no-no, but we'll throw a fatal one eventually so it's ok. */
514 nasm_error(ERR_NONFATAL, "cannot compute vstart for section %s",
515 s->name);
516 h++;
519 if (h)
520 nasm_fatal(ERR_NOFILE, "circular vfollows path detected");
522 #ifdef DEBUG
523 nasm_error(ERR_DEBUG,
524 "bin_cleanup: Confirm final section order for output file:\n");
525 for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
526 h++, s = s->next)
527 fprintf(stdout, "%i. %s\n", h, s->name);
528 #endif
530 /* Step 5: Apply relocations. */
532 /* Prepare the sections for relocating. */
533 list_for_each(s, sections)
534 saa_rewind(s->contents);
535 /* Apply relocations. */
536 list_for_each(r, relocs) {
537 uint8_t *p, mydata[8];
538 int64_t l;
539 int b;
541 nasm_assert(r->bytes <= 8);
543 memset(mydata, 0, sizeof(mydata));
545 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
546 p = mydata;
547 l = 0;
548 for (b = r->bytes - 1; b >= 0; b--)
549 l = (l << 8) + mydata[b];
551 s = find_section_by_index(r->secref);
552 if (s) {
553 if (r->secref == s->start_index)
554 l += s->start;
555 else
556 l += s->vstart;
558 s = find_section_by_index(r->secrel);
559 if (s) {
560 if (r->secrel == s->start_index)
561 l -= s->start;
562 else
563 l -= s->vstart;
566 WRITEADDR(p, l, r->bytes);
567 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
570 /* Step 6: Write the section data to the output file. */
571 do_output();
573 /* Step 7: Generate the map file. */
575 if (map_control) {
576 static const char not_defined[] = "not defined";
578 /* Display input and output file names. */
579 fprintf(rf, "\n- NASM Map file ");
580 for (h = 63; h; h--)
581 fputc('-', rf);
582 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
583 infile, outfile);
585 if (map_control & MAP_ORIGIN) { /* Display program origin. */
586 fprintf(rf, "-- Program origin ");
587 for (h = 61; h; h--)
588 fputc('-', rf);
589 fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
591 /* Display sections summary. */
592 if (map_control & MAP_SUMMARY) {
593 fprintf(rf, "-- Sections (summary) ");
594 for (h = 57; h; h--)
595 fputc('-', rf);
596 fprintf(rf, "\n\nVstart Start Stop "
597 "Length Class Name\n");
598 list_for_each(s, sections) {
599 fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
600 s->vstart, s->start, s->start + s->length,
601 s->length);
602 if (s->flags & TYPE_PROGBITS)
603 fprintf(rf, "progbits ");
604 else
605 fprintf(rf, "nobits ");
606 fprintf(rf, "%s\n", s->name);
608 fprintf(rf, "\n");
610 /* Display detailed section information. */
611 if (map_control & MAP_SECTIONS) {
612 fprintf(rf, "-- Sections (detailed) ");
613 for (h = 56; h; h--)
614 fputc('-', rf);
615 fprintf(rf, "\n\n");
616 list_for_each(s, sections) {
617 fprintf(rf, "---- Section %s ", s->name);
618 for (h = 65 - strlen(s->name); h; h--)
619 fputc('-', rf);
620 fprintf(rf, "\n\nclass: ");
621 if (s->flags & TYPE_PROGBITS)
622 fprintf(rf, "progbits");
623 else
624 fprintf(rf, "nobits");
625 fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
626 "\nalign: ", s->length, s->start);
627 if (s->flags & ALIGN_DEFINED)
628 fprintf(rf, "%16"PRIX64"", s->align);
629 else
630 fputs(not_defined, rf);
631 fprintf(rf, "\nfollows: ");
632 if (s->flags & FOLLOWS_DEFINED)
633 fprintf(rf, "%s", s->follows);
634 else
635 fputs(not_defined, rf);
636 fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
637 if (s->flags & VALIGN_DEFINED)
638 fprintf(rf, "%16"PRIX64"", s->valign);
639 else
640 fputs(not_defined, rf);
641 fprintf(rf, "\nvfollows: ");
642 if (s->flags & VFOLLOWS_DEFINED)
643 fprintf(rf, "%s", s->vfollows);
644 else
645 fputs(not_defined, rf);
646 fprintf(rf, "\n\n");
649 /* Display symbols information. */
650 if (map_control & MAP_SYMBOLS) {
651 int32_t segment;
652 int64_t offset;
654 fprintf(rf, "-- Symbols ");
655 for (h = 68; h; h--)
656 fputc('-', rf);
657 fprintf(rf, "\n\n");
658 if (no_seg_labels) {
659 fprintf(rf, "---- No Section ");
660 for (h = 63; h; h--)
661 fputc('-', rf);
662 fprintf(rf, "\n\nValue Name\n");
663 list_for_each(l, no_seg_labels) {
664 lookup_label(l->name, &segment, &offset);
665 fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
667 fprintf(rf, "\n\n");
669 list_for_each(s, sections) {
670 if (s->labels) {
671 fprintf(rf, "---- Section %s ", s->name);
672 for (h = 65 - strlen(s->name); h; h--)
673 fputc('-', rf);
674 fprintf(rf, "\n\nReal Virtual Name\n");
675 list_for_each(l, s->labels) {
676 lookup_label(l->name, &segment, &offset);
677 fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
678 s->start + offset, s->vstart + offset,
679 l->name);
681 fprintf(rf, "\n");
687 /* Close the report file. */
688 if (map_control && (rf != stdout) && (rf != stderr))
689 fclose(rf);
691 /* Step 8: Release all allocated memory. */
693 /* Free sections, label pointer structs, etc.. */
694 while (sections) {
695 s = sections;
696 sections = s->next;
697 saa_free(s->contents);
698 nasm_free(s->name);
699 if (s->flags & FOLLOWS_DEFINED)
700 nasm_free(s->follows);
701 if (s->flags & VFOLLOWS_DEFINED)
702 nasm_free(s->vfollows);
703 while (s->labels) {
704 l = s->labels;
705 s->labels = l->next;
706 nasm_free(l);
708 nasm_free(s);
711 /* Free no-section labels. */
712 while (no_seg_labels) {
713 l = no_seg_labels;
714 no_seg_labels = l->next;
715 nasm_free(l);
718 /* Free relocation structures. */
719 while (relocs) {
720 r = relocs->next;
721 nasm_free(relocs);
722 relocs = r;
726 static void bin_out(int32_t segto, const void *data,
727 enum out_type type, uint64_t size,
728 int32_t segment, int32_t wrt)
730 uint8_t *p, mydata[8];
731 struct Section *s;
733 if (wrt != NO_SEG) {
734 wrt = NO_SEG; /* continue to do _something_ */
735 nasm_error(ERR_NONFATAL, "WRT not supported by binary output format");
738 /* Handle absolute-assembly (structure definitions). */
739 if (segto == NO_SEG) {
740 if (type != OUT_RESERVE)
741 nasm_error(ERR_NONFATAL, "attempt to assemble code in"
742 " [ABSOLUTE] space");
743 return;
746 /* Find the segment we are targeting. */
747 s = find_section_by_index(segto);
748 if (!s)
749 nasm_panic(0, "code directed to nonexistent segment?");
751 /* "Smart" section-type adaptation code. */
752 if (!(s->flags & TYPE_DEFINED)) {
753 if (type == OUT_RESERVE)
754 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
755 else
756 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
759 if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
760 nasm_error(ERR_WARNING, "attempt to initialize memory in a"
761 " nobits section: ignored");
763 switch (type) {
764 case OUT_ADDRESS:
766 int asize = abs((int)size);
768 if (segment != NO_SEG && !find_section_by_index(segment)) {
769 if (segment % 2)
770 nasm_error(ERR_NONFATAL, "binary output format does not support"
771 " segment base references");
772 else
773 nasm_error(ERR_NONFATAL, "binary output format does not support"
774 " external references");
775 segment = NO_SEG;
777 if (s->flags & TYPE_PROGBITS) {
778 if (segment != NO_SEG)
779 add_reloc(s, asize, segment, -1L);
780 p = mydata;
781 WRITEADDR(p, *(int64_t *)data, asize);
782 saa_wbytes(s->contents, mydata, asize);
786 * Reassign size with sign dropped, we will need it
787 * for section length calculation.
789 size = asize;
790 break;
793 case OUT_RAWDATA:
794 if (s->flags & TYPE_PROGBITS)
795 saa_wbytes(s->contents, data, size);
796 break;
798 case OUT_RESERVE:
799 if (s->flags & TYPE_PROGBITS) {
800 nasm_error(ERR_WARNING, "uninitialized space declared in"
801 " %s section: zeroing", s->name);
802 saa_wbytes(s->contents, NULL, size);
804 break;
806 case OUT_REL1ADR:
807 case OUT_REL2ADR:
808 case OUT_REL4ADR:
809 case OUT_REL8ADR:
811 int64_t addr = *(int64_t *)data - size;
812 size = realsize(type, size);
813 if (segment != NO_SEG && !find_section_by_index(segment)) {
814 if (segment % 2)
815 nasm_error(ERR_NONFATAL, "binary output format does not support"
816 " segment base references");
817 else
818 nasm_error(ERR_NONFATAL, "binary output format does not support"
819 " external references");
820 segment = NO_SEG;
822 if (s->flags & TYPE_PROGBITS) {
823 add_reloc(s, size, segment, segto);
824 p = mydata;
825 WRITEADDR(p, addr - s->length, size);
826 saa_wbytes(s->contents, mydata, size);
828 break;
831 default:
832 nasm_error(ERR_NONFATAL, "unsupported relocation type %d\n", type);
833 break;
836 s->length += size;
839 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
840 int is_global, char *special)
842 (void)segment; /* Don't warn that this parameter is unused */
843 (void)offset; /* Don't warn that this parameter is unused */
845 if (special)
846 nasm_error(ERR_NONFATAL, "binary format does not support any"
847 " special symbol types");
848 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
849 nasm_error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
850 else if (is_global == 2)
851 nasm_error(ERR_NONFATAL, "binary output format does not support common"
852 " variables");
853 else {
854 struct Section *s;
855 struct bin_label ***ltp;
857 /* Remember label definition so we can look it up later when
858 * creating the map file. */
859 s = find_section_by_index(segment);
860 if (s)
861 ltp = &(s->labels_end);
862 else
863 ltp = &nsl_tail;
864 (**ltp) = nasm_malloc(sizeof(struct bin_label));
865 (**ltp)->name = name;
866 (**ltp)->next = NULL;
867 *ltp = &((**ltp)->next);
872 /* These constants and the following function are used
873 * by bin_secname() to parse attribute assignments. */
875 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
876 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
877 ATTRIB_NOBITS, ATTRIB_PROGBITS
880 static int bin_read_attribute(char **line, int *attribute,
881 uint64_t *value)
883 expr *e;
884 int attrib_name_size;
885 struct tokenval tokval;
886 char *exp;
888 /* Skip whitespace. */
889 while (**line && nasm_isspace(**line))
890 (*line)++;
891 if (!**line)
892 return 0;
894 /* Figure out what attribute we're reading. */
895 if (!nasm_strnicmp(*line, "align=", 6)) {
896 *attribute = ATTRIB_ALIGN;
897 attrib_name_size = 6;
898 } else {
899 if (!nasm_strnicmp(*line, "start=", 6)) {
900 *attribute = ATTRIB_START;
901 attrib_name_size = 6;
902 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
903 *attribute = ATTRIB_FOLLOWS;
904 *line += 8;
905 return 1;
906 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
907 *attribute = ATTRIB_VSTART;
908 attrib_name_size = 7;
909 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
910 *attribute = ATTRIB_VALIGN;
911 attrib_name_size = 7;
912 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
913 *attribute = ATTRIB_VFOLLOWS;
914 *line += 9;
915 return 1;
916 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
917 (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
918 *attribute = ATTRIB_NOBITS;
919 *line += 6;
920 return 1;
921 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
922 (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
923 *attribute = ATTRIB_PROGBITS;
924 *line += 8;
925 return 1;
926 } else
927 return 0;
930 /* Find the end of the expression. */
931 if ((*line)[attrib_name_size] != '(') {
932 /* Single term (no parenthesis). */
933 exp = *line += attrib_name_size;
934 while (**line && !nasm_isspace(**line))
935 (*line)++;
936 if (**line) {
937 **line = '\0';
938 (*line)++;
940 } else {
941 char c;
942 int pcount = 1;
944 /* Full expression (delimited by parenthesis) */
945 exp = *line += attrib_name_size + 1;
946 while (1) {
947 (*line) += strcspn(*line, "()'\"");
948 if (**line == '(') {
949 ++(*line);
950 ++pcount;
952 if (**line == ')') {
953 ++(*line);
954 --pcount;
955 if (!pcount)
956 break;
958 if ((**line == '"') || (**line == '\'')) {
959 c = **line;
960 while (**line) {
961 ++(*line);
962 if (**line == c)
963 break;
965 if (!**line) {
966 nasm_error(ERR_NONFATAL,
967 "invalid syntax in `section' directive");
968 return -1;
970 ++(*line);
972 if (!**line) {
973 nasm_error(ERR_NONFATAL, "expecting `)'");
974 return -1;
977 *(*line - 1) = '\0'; /* Terminate the expression. */
980 /* Check for no value given. */
981 if (!*exp) {
982 nasm_error(ERR_WARNING, "No value given to attribute in"
983 " `section' directive");
984 return -1;
987 /* Read and evaluate the expression. */
988 stdscan_reset();
989 stdscan_set(exp);
990 tokval.t_type = TOKEN_INVALID;
991 e = evaluate(stdscan, NULL, &tokval, NULL, 1, NULL);
992 if (e) {
993 if (!is_really_simple(e)) {
994 nasm_error(ERR_NONFATAL, "section attribute value must be"
995 " a critical expression");
996 return -1;
998 } else {
999 nasm_error(ERR_NONFATAL, "Invalid attribute value"
1000 " specified in `section' directive.");
1001 return -1;
1003 *value = (uint64_t)reloc_value(e);
1004 return 1;
1007 static void bin_sectalign(int32_t seg, unsigned int value)
1009 struct Section *s = find_section_by_index(seg);
1011 if (!s || !is_power2(value))
1012 return;
1014 if (value > s->align)
1015 s->align = value;
1017 if (!(s->flags & ALIGN_DEFINED))
1018 s->flags |= ALIGN_DEFINED;
1021 static void bin_assign_attributes(struct Section *sec, char *astring)
1023 int attribute, check;
1024 uint64_t value;
1025 char *p;
1027 while (1) { /* Get the next attribute. */
1028 check = bin_read_attribute(&astring, &attribute, &value);
1029 /* Skip bad attribute. */
1030 if (check == -1)
1031 continue;
1032 /* Unknown section attribute, so skip it and warn the user. */
1033 if (!check) {
1034 if (!*astring)
1035 break; /* End of line. */
1036 else {
1037 p = astring;
1038 while (*astring && !nasm_isspace(*astring))
1039 astring++;
1040 if (*astring) {
1041 *astring = '\0';
1042 astring++;
1044 nasm_error(ERR_WARNING, "ignoring unknown section attribute:"
1045 " \"%s\"", p);
1047 continue;
1050 switch (attribute) { /* Handle nobits attribute. */
1051 case ATTRIB_NOBITS:
1052 if ((sec->flags & TYPE_DEFINED)
1053 && (sec->flags & TYPE_PROGBITS))
1054 nasm_error(ERR_NONFATAL,
1055 "attempt to change section type"
1056 " from progbits to nobits");
1057 else
1058 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1059 continue;
1061 /* Handle progbits attribute. */
1062 case ATTRIB_PROGBITS:
1063 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1064 nasm_error(ERR_NONFATAL, "attempt to change section type"
1065 " from nobits to progbits");
1066 else
1067 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1068 continue;
1070 /* Handle align attribute. */
1071 case ATTRIB_ALIGN:
1072 if (!value || ((value - 1) & value)) {
1073 nasm_error(ERR_NONFATAL,
1074 "argument to `align' is not a power of two");
1075 } else {
1077 * Alignment is already satisfied if
1078 * the previous align value is greater
1080 if ((sec->flags & ALIGN_DEFINED) && (value < sec->align))
1081 value = sec->align;
1083 /* Don't allow a conflicting align value. */
1084 if ((sec->flags & START_DEFINED) && (sec->start & (value - 1))) {
1085 nasm_error(ERR_NONFATAL,
1086 "`align' value conflicts with section start address");
1087 } else {
1088 sec->align = value;
1089 sec->flags |= ALIGN_DEFINED;
1092 continue;
1094 /* Handle valign attribute. */
1095 case ATTRIB_VALIGN:
1096 if (!value || ((value - 1) & value))
1097 nasm_error(ERR_NONFATAL, "argument to `valign' is not a"
1098 " power of two");
1099 else { /* Alignment is already satisfied if the previous
1100 * align value is greater. */
1101 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1102 value = sec->valign;
1104 /* Don't allow a conflicting valign value. */
1105 if ((sec->flags & VSTART_DEFINED)
1106 && (sec->vstart & (value - 1)))
1107 nasm_error(ERR_NONFATAL,
1108 "`valign' value conflicts "
1109 "with `vstart' address");
1110 else {
1111 sec->valign = value;
1112 sec->flags |= VALIGN_DEFINED;
1115 continue;
1117 /* Handle start attribute. */
1118 case ATTRIB_START:
1119 if (sec->flags & FOLLOWS_DEFINED)
1120 nasm_error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1121 " section attributes");
1122 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1123 nasm_error(ERR_NONFATAL, "section start address redefined");
1124 else {
1125 sec->start = value;
1126 sec->flags |= START_DEFINED;
1127 if (sec->flags & ALIGN_DEFINED) {
1128 if (sec->start & (sec->align - 1))
1129 nasm_error(ERR_NONFATAL, "`start' address conflicts"
1130 " with section alignment");
1131 sec->flags ^= ALIGN_DEFINED;
1134 continue;
1136 /* Handle vstart attribute. */
1137 case ATTRIB_VSTART:
1138 if (sec->flags & VFOLLOWS_DEFINED)
1139 nasm_error(ERR_NONFATAL,
1140 "cannot combine `vstart' and `vfollows'"
1141 " section attributes");
1142 else if ((sec->flags & VSTART_DEFINED)
1143 && (value != sec->vstart))
1144 nasm_error(ERR_NONFATAL,
1145 "section virtual start address"
1146 " (vstart) redefined");
1147 else {
1148 sec->vstart = value;
1149 sec->flags |= VSTART_DEFINED;
1150 if (sec->flags & VALIGN_DEFINED) {
1151 if (sec->vstart & (sec->valign - 1))
1152 nasm_error(ERR_NONFATAL, "`vstart' address conflicts"
1153 " with `valign' value");
1154 sec->flags ^= VALIGN_DEFINED;
1157 continue;
1159 /* Handle follows attribute. */
1160 case ATTRIB_FOLLOWS:
1161 p = astring;
1162 astring += strcspn(astring, " \t");
1163 if (astring == p)
1164 nasm_error(ERR_NONFATAL, "expecting section name for `follows'"
1165 " attribute");
1166 else {
1167 *(astring++) = '\0';
1168 if (sec->flags & START_DEFINED)
1169 nasm_error(ERR_NONFATAL,
1170 "cannot combine `start' and `follows'"
1171 " section attributes");
1172 sec->follows = nasm_strdup(p);
1173 sec->flags |= FOLLOWS_DEFINED;
1175 continue;
1177 /* Handle vfollows attribute. */
1178 case ATTRIB_VFOLLOWS:
1179 if (sec->flags & VSTART_DEFINED)
1180 nasm_error(ERR_NONFATAL,
1181 "cannot combine `vstart' and `vfollows'"
1182 " section attributes");
1183 else {
1184 p = astring;
1185 astring += strcspn(astring, " \t");
1186 if (astring == p)
1187 nasm_error(ERR_NONFATAL,
1188 "expecting section name for `vfollows'"
1189 " attribute");
1190 else {
1191 *(astring++) = '\0';
1192 sec->vfollows = nasm_strdup(p);
1193 sec->flags |= VFOLLOWS_DEFINED;
1196 continue;
1201 static void bin_define_section_labels(void)
1203 static int labels_defined = 0;
1204 struct Section *sec;
1205 char *label_name;
1206 size_t base_len;
1208 if (labels_defined)
1209 return;
1210 list_for_each(sec, sections) {
1211 base_len = strlen(sec->name) + 8;
1212 label_name = nasm_malloc(base_len + 8);
1213 strcpy(label_name, "section.");
1214 strcpy(label_name + 8, sec->name);
1216 /* section.<name>.start */
1217 strcpy(label_name + base_len, ".start");
1218 define_label(label_name, sec->start_index, 0L, NULL, 0, 0);
1220 /* section.<name>.vstart */
1221 strcpy(label_name + base_len, ".vstart");
1222 define_label(label_name, sec->vstart_index, 0L, NULL, 0, 0);
1224 nasm_free(label_name);
1226 labels_defined = 1;
1229 static int32_t bin_secname(char *name, int pass, int *bits)
1231 char *p;
1232 struct Section *sec;
1234 /* bin_secname is called with *name = NULL at the start of each
1235 * pass. Use this opportunity to establish the default section
1236 * (default is BITS-16 ".text" segment).
1238 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1239 origin_defined = 0;
1240 list_for_each(sec, sections)
1241 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1242 ALIGN_DEFINED | VALIGN_DEFINED);
1244 /* Define section start and vstart labels. */
1245 if (pass != 1)
1246 bin_define_section_labels();
1248 /* Establish the default (.text) section. */
1249 *bits = 16;
1250 sec = find_section_by_name(".text");
1251 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1252 return sec->vstart_index;
1255 /* Attempt to find the requested section. If it does not
1256 * exist, create it. */
1257 p = name;
1258 while (*p && !nasm_isspace(*p))
1259 p++;
1260 if (*p)
1261 *p++ = '\0';
1262 sec = find_section_by_name(name);
1263 if (!sec) {
1264 sec = create_section(name);
1265 if (!strcmp(name, ".data"))
1266 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1267 else if (!strcmp(name, ".bss")) {
1268 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1269 sec->prev = NULL;
1273 /* Handle attribute assignments. */
1274 if (pass != 1)
1275 bin_assign_attributes(sec, p);
1277 #ifndef ABIN_SMART_ADAPT
1278 /* The following line disables smart adaptation of
1279 * PROGBITS/NOBITS section types (it forces sections to
1280 * default to PROGBITS). */
1281 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1282 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1283 #endif
1285 return sec->vstart_index;
1288 static int bin_directive(enum directives directive, char *args, int pass)
1290 switch (directive) {
1291 case D_ORG:
1293 struct tokenval tokval;
1294 uint64_t value;
1295 expr *e;
1297 stdscan_reset();
1298 stdscan_set(args);
1299 tokval.t_type = TOKEN_INVALID;
1300 e = evaluate(stdscan, NULL, &tokval, NULL, 1, NULL);
1301 if (e) {
1302 if (!is_really_simple(e))
1303 nasm_error(ERR_NONFATAL, "org value must be a critical"
1304 " expression");
1305 else {
1306 value = reloc_value(e);
1307 /* Check for ORG redefinition. */
1308 if (origin_defined && (value != origin))
1309 nasm_error(ERR_NONFATAL, "program origin redefined");
1310 else {
1311 origin = value;
1312 origin_defined = 1;
1315 } else
1316 nasm_error(ERR_NONFATAL, "No or invalid offset specified"
1317 " in ORG directive.");
1318 return 1;
1320 case D_MAP:
1322 /* The 'map' directive allows the user to generate section
1323 * and symbol information to stdout, stderr, or to a file. */
1324 char *p;
1326 if (pass != 1)
1327 return 1;
1328 args += strspn(args, " \t");
1329 while (*args) {
1330 p = args;
1331 args += strcspn(args, " \t");
1332 if (*args != '\0')
1333 *(args++) = '\0';
1334 if (!nasm_stricmp(p, "all"))
1335 map_control |=
1336 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1337 else if (!nasm_stricmp(p, "brief"))
1338 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1339 else if (!nasm_stricmp(p, "sections"))
1340 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1341 else if (!nasm_stricmp(p, "segments"))
1342 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1343 else if (!nasm_stricmp(p, "symbols"))
1344 map_control |= MAP_SYMBOLS;
1345 else if (!rf) {
1346 if (!nasm_stricmp(p, "stdout"))
1347 rf = stdout;
1348 else if (!nasm_stricmp(p, "stderr"))
1349 rf = stderr;
1350 else { /* Must be a filename. */
1351 rf = nasm_open_write(p, NF_TEXT);
1352 if (!rf) {
1353 nasm_error(ERR_WARNING, "unable to open map file `%s'",
1355 map_control = 0;
1356 return 1;
1359 } else
1360 nasm_error(ERR_WARNING, "map file already specified");
1362 if (map_control == 0)
1363 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1364 if (!rf)
1365 rf = stdout;
1366 return 1;
1368 default:
1369 return 0;
1373 static void bin_filename(char *inname, char *outname)
1375 standard_extension(inname, outname, "");
1376 infile = inname;
1377 outfile = outname;
1380 static void ith_filename(char *inname, char *outname)
1382 standard_extension(inname, outname, ".ith");
1383 infile = inname;
1384 outfile = outname;
1387 static void srec_filename(char *inname, char *outname)
1389 standard_extension(inname, outname, ".srec");
1390 infile = inname;
1391 outfile = outname;
1394 static int32_t bin_segbase(int32_t segment)
1396 return segment;
1399 static int bin_set_info(enum geninfo type, char **val)
1401 (void)type;
1402 (void)val;
1403 return 0;
1406 const struct ofmt of_bin, of_ith, of_srec;
1407 static void binfmt_init(void);
1408 static void do_output_bin(void);
1409 static void do_output_ith(void);
1410 static void do_output_srec(void);
1412 static void bin_init(void)
1414 do_output = do_output_bin;
1415 binfmt_init();
1418 static void ith_init(void)
1420 do_output = do_output_ith;
1421 binfmt_init();
1424 static void srec_init(void)
1426 do_output = do_output_srec;
1427 binfmt_init();
1430 static void binfmt_init(void)
1432 relocs = NULL;
1433 reloctail = &relocs;
1434 origin_defined = 0;
1435 no_seg_labels = NULL;
1436 nsl_tail = &no_seg_labels;
1438 /* Create default section (.text). */
1439 sections = last_section = nasm_zalloc(sizeof(struct Section));
1440 last_section->name = nasm_strdup(".text");
1441 last_section->contents = saa_init(1L);
1442 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1443 last_section->labels_end = &(last_section->labels);
1444 last_section->start_index = seg_alloc();
1445 last_section->vstart_index = seg_alloc();
1448 /* Generate binary file output */
1449 static void do_output_bin(void)
1451 struct Section *s;
1452 uint64_t addr = origin;
1454 /* Write the progbits sections to the output file. */
1455 list_for_each(s, sections) {
1456 /* Skip non-progbits sections */
1457 if (!(s->flags & TYPE_PROGBITS))
1458 continue;
1459 /* Skip zero-length sections */
1460 if (s->length == 0)
1461 continue;
1463 /* Pad the space between sections. */
1464 nasm_assert(addr <= s->start);
1465 fwritezero(s->start - addr, ofile);
1467 /* Write the section to the output file. */
1468 saa_fpwrite(s->contents, ofile);
1470 /* Keep track of the current file position */
1471 addr = s->start + s->length;
1475 /* Generate Intel hex file output */
1476 static void write_ith_record(unsigned int len, uint16_t addr,
1477 uint8_t type, void *data)
1479 char buf[1+2+4+2+255*2+2+2];
1480 char *p = buf;
1481 uint8_t csum, *dptr = data;
1482 unsigned int i;
1484 nasm_assert(len <= 255);
1486 csum = len + addr + (addr >> 8) + type;
1487 for (i = 0; i < len; i++)
1488 csum += dptr[i];
1489 csum = -csum;
1491 p += sprintf(p, ":%02X%04X%02X", len, addr, type);
1492 for (i = 0; i < len; i++)
1493 p += sprintf(p, "%02X", dptr[i]);
1494 p += sprintf(p, "%02X\n", csum);
1496 nasm_write(buf, p-buf, ofile);
1499 static void do_output_ith(void)
1501 uint8_t buf[32];
1502 struct Section *s;
1503 uint64_t addr, hiaddr, hilba;
1504 uint64_t length;
1505 unsigned int chunk;
1507 /* Write the progbits sections to the output file. */
1508 hilba = 0;
1509 list_for_each(s, sections) {
1510 /* Skip non-progbits sections */
1511 if (!(s->flags & TYPE_PROGBITS))
1512 continue;
1513 /* Skip zero-length sections */
1514 if (s->length == 0)
1515 continue;
1517 addr = s->start;
1518 length = s->length;
1519 saa_rewind(s->contents);
1521 while (length) {
1522 hiaddr = addr >> 16;
1523 if (hiaddr != hilba) {
1524 buf[0] = hiaddr >> 8;
1525 buf[1] = hiaddr;
1526 write_ith_record(2, 0, 4, buf);
1527 hilba = hiaddr;
1530 chunk = 32 - (addr & 31);
1531 if (length < chunk)
1532 chunk = length;
1534 saa_rnbytes(s->contents, buf, chunk);
1535 write_ith_record(chunk, (uint16_t)addr, 0, buf);
1537 addr += chunk;
1538 length -= chunk;
1542 /* Write closing record */
1543 write_ith_record(0, 0, 1, NULL);
1546 /* Generate Motorola S-records */
1547 static void write_srecord(unsigned int len, unsigned int alen,
1548 uint32_t addr, uint8_t type, void *data)
1550 char buf[2+2+8+255*2+2+2];
1551 char *p = buf;
1552 uint8_t csum, *dptr = data;
1553 unsigned int i;
1555 nasm_assert(len <= 255);
1557 switch (alen) {
1558 case 2:
1559 addr &= 0xffff;
1560 break;
1561 case 3:
1562 addr &= 0xffffff;
1563 break;
1564 case 4:
1565 break;
1566 default:
1567 nasm_assert(0);
1568 break;
1571 csum = (len+alen+1) + addr + (addr >> 8) + (addr >> 16) + (addr >> 24);
1572 for (i = 0; i < len; i++)
1573 csum += dptr[i];
1574 csum = 0xff-csum;
1576 p += sprintf(p, "S%c%02X%0*X", type, len+alen+1, alen*2, addr);
1577 for (i = 0; i < len; i++)
1578 p += sprintf(p, "%02X", dptr[i]);
1579 p += sprintf(p, "%02X\n", csum);
1581 nasm_write(buf, p-buf, ofile);
1584 static void do_output_srec(void)
1586 uint8_t buf[32];
1587 struct Section *s;
1588 uint64_t addr, maxaddr;
1589 uint64_t length;
1590 int alen;
1591 unsigned int chunk;
1592 char dtype, etype;
1594 maxaddr = 0;
1595 list_for_each(s, sections) {
1596 /* Skip non-progbits sections */
1597 if (!(s->flags & TYPE_PROGBITS))
1598 continue;
1599 /* Skip zero-length sections */
1600 if (s->length == 0)
1601 continue;
1603 addr = s->start + s->length - 1;
1604 if (addr > maxaddr)
1605 maxaddr = addr;
1608 if (maxaddr <= 0xffff) {
1609 alen = 2;
1610 dtype = '1'; /* S1 = 16-bit data */
1611 etype = '9'; /* S9 = 16-bit end */
1612 } else if (maxaddr <= 0xffffff) {
1613 alen = 3;
1614 dtype = '2'; /* S2 = 24-bit data */
1615 etype = '8'; /* S8 = 24-bit end */
1616 } else {
1617 alen = 4;
1618 dtype = '3'; /* S3 = 32-bit data */
1619 etype = '7'; /* S7 = 32-bit end */
1622 /* Write head record */
1623 write_srecord(0, 2, 0, '0', NULL);
1625 /* Write the progbits sections to the output file. */
1626 list_for_each(s, sections) {
1627 /* Skip non-progbits sections */
1628 if (!(s->flags & TYPE_PROGBITS))
1629 continue;
1630 /* Skip zero-length sections */
1631 if (s->length == 0)
1632 continue;
1634 addr = s->start;
1635 length = s->length;
1636 saa_rewind(s->contents);
1638 while (length) {
1639 chunk = 32 - (addr & 31);
1640 if (length < chunk)
1641 chunk = length;
1643 saa_rnbytes(s->contents, buf, chunk);
1644 write_srecord(chunk, alen, (uint32_t)addr, dtype, buf);
1646 addr += chunk;
1647 length -= chunk;
1651 /* Write closing record */
1652 write_srecord(0, alen, 0, etype, NULL);
1656 const struct ofmt of_bin = {
1657 "flat-form binary files (e.g. DOS .COM, .SYS)",
1658 "bin",
1661 null_debug_arr,
1662 &null_debug_form,
1663 bin_stdmac,
1664 bin_init,
1665 bin_set_info,
1666 nasm_do_legacy_output,
1667 bin_out,
1668 bin_deflabel,
1669 bin_secname,
1670 bin_sectalign,
1671 bin_segbase,
1672 bin_directive,
1673 bin_filename,
1674 bin_cleanup
1677 const struct ofmt of_ith = {
1678 "Intel hex",
1679 "ith",
1680 OFMT_TEXT,
1682 null_debug_arr,
1683 &null_debug_form,
1684 bin_stdmac,
1685 ith_init,
1686 bin_set_info,
1687 nasm_do_legacy_output,
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 const 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 nasm_do_legacy_output,
1709 bin_out,
1710 bin_deflabel,
1711 bin_secname,
1712 bin_sectalign,
1713 bin_segbase,
1714 bin_directive,
1715 srec_filename,
1716 bin_cleanup
1719 #endif /* #ifdef OF_BIN */