Add missing static declarations in output/outobj.c
[nasm.git] / output / outbin.c
blob01eae1cf0ec1faac85967eb77b3493e4ccd71c56
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_error(ERR_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_error(ERR_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_error(ERR_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_error(ERR_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_error(ERR_FATAL|ERR_NOFILE, "section %s beings before program origin",
449 s->name);
450 if (g->start > s->start)
451 nasm_error(ERR_FATAL|ERR_NOFILE, "sections %s ~ %s and %s overlap!",
452 gs->name, g->name, s->name);
453 if (pend > s->start)
454 nasm_error(ERR_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_error(ERR_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_error(ERR_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 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_error(ERR_PANIC, "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(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);
784 break;
787 case OUT_RAWDATA:
788 if (s->flags & TYPE_PROGBITS)
789 saa_wbytes(s->contents, data, size);
790 break;
792 case OUT_RESERVE:
793 if (s->flags & TYPE_PROGBITS) {
794 nasm_error(ERR_WARNING, "uninitialized space declared in"
795 " %s section: zeroing", s->name);
796 saa_wbytes(s->contents, NULL, size);
798 break;
800 case OUT_REL1ADR:
801 case OUT_REL2ADR:
802 case OUT_REL4ADR:
803 case OUT_REL8ADR:
805 int64_t addr = *(int64_t *)data - size;
806 size = realsize(type, size);
807 if (segment != NO_SEG && !find_section_by_index(segment)) {
808 if (segment % 2)
809 nasm_error(ERR_NONFATAL, "binary output format does not support"
810 " segment base references");
811 else
812 nasm_error(ERR_NONFATAL, "binary output format does not support"
813 " external references");
814 segment = NO_SEG;
816 if (s->flags & TYPE_PROGBITS) {
817 add_reloc(s, size, segment, segto);
818 p = mydata;
819 WRITEADDR(p, addr - s->length, size);
820 saa_wbytes(s->contents, mydata, size);
822 break;
825 default:
826 nasm_error(ERR_NONFATAL, "unsupported relocation type %d\n", type);
827 break;
830 s->length += size;
833 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
834 int is_global, char *special)
836 (void)segment; /* Don't warn that this parameter is unused */
837 (void)offset; /* Don't warn that this parameter is unused */
839 if (special)
840 nasm_error(ERR_NONFATAL, "binary format does not support any"
841 " special symbol types");
842 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
843 nasm_error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
844 else if (is_global == 2)
845 nasm_error(ERR_NONFATAL, "binary output format does not support common"
846 " variables");
847 else {
848 struct Section *s;
849 struct bin_label ***ltp;
851 /* Remember label definition so we can look it up later when
852 * creating the map file. */
853 s = find_section_by_index(segment);
854 if (s)
855 ltp = &(s->labels_end);
856 else
857 ltp = &nsl_tail;
858 (**ltp) = nasm_malloc(sizeof(struct bin_label));
859 (**ltp)->name = name;
860 (**ltp)->next = NULL;
861 *ltp = &((**ltp)->next);
866 /* These constants and the following function are used
867 * by bin_secname() to parse attribute assignments. */
869 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
870 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
871 ATTRIB_NOBITS, ATTRIB_PROGBITS
874 static int bin_read_attribute(char **line, int *attribute,
875 uint64_t *value)
877 expr *e;
878 int attrib_name_size;
879 struct tokenval tokval;
880 char *exp;
882 /* Skip whitespace. */
883 while (**line && nasm_isspace(**line))
884 (*line)++;
885 if (!**line)
886 return 0;
888 /* Figure out what attribute we're reading. */
889 if (!nasm_strnicmp(*line, "align=", 6)) {
890 *attribute = ATTRIB_ALIGN;
891 attrib_name_size = 6;
892 } else {
893 if (!nasm_strnicmp(*line, "start=", 6)) {
894 *attribute = ATTRIB_START;
895 attrib_name_size = 6;
896 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
897 *attribute = ATTRIB_FOLLOWS;
898 *line += 8;
899 return 1;
900 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
901 *attribute = ATTRIB_VSTART;
902 attrib_name_size = 7;
903 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
904 *attribute = ATTRIB_VALIGN;
905 attrib_name_size = 7;
906 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
907 *attribute = ATTRIB_VFOLLOWS;
908 *line += 9;
909 return 1;
910 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
911 (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
912 *attribute = ATTRIB_NOBITS;
913 *line += 6;
914 return 1;
915 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
916 (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
917 *attribute = ATTRIB_PROGBITS;
918 *line += 8;
919 return 1;
920 } else
921 return 0;
924 /* Find the end of the expression. */
925 if ((*line)[attrib_name_size] != '(') {
926 /* Single term (no parenthesis). */
927 exp = *line += attrib_name_size;
928 while (**line && !nasm_isspace(**line))
929 (*line)++;
930 if (**line) {
931 **line = '\0';
932 (*line)++;
934 } else {
935 char c;
936 int pcount = 1;
938 /* Full expression (delimited by parenthesis) */
939 exp = *line += attrib_name_size + 1;
940 while (1) {
941 (*line) += strcspn(*line, "()'\"");
942 if (**line == '(') {
943 ++(*line);
944 ++pcount;
946 if (**line == ')') {
947 ++(*line);
948 --pcount;
949 if (!pcount)
950 break;
952 if ((**line == '"') || (**line == '\'')) {
953 c = **line;
954 while (**line) {
955 ++(*line);
956 if (**line == c)
957 break;
959 if (!**line) {
960 nasm_error(ERR_NONFATAL,
961 "invalid syntax in `section' directive");
962 return -1;
964 ++(*line);
966 if (!**line) {
967 nasm_error(ERR_NONFATAL, "expecting `)'");
968 return -1;
971 *(*line - 1) = '\0'; /* Terminate the expression. */
974 /* Check for no value given. */
975 if (!*exp) {
976 nasm_error(ERR_WARNING, "No value given to attribute in"
977 " `section' directive");
978 return -1;
981 /* Read and evaluate the expression. */
982 stdscan_reset();
983 stdscan_set(exp);
984 tokval.t_type = TOKEN_INVALID;
985 e = evaluate(stdscan, NULL, &tokval, NULL, 1, nasm_error, NULL);
986 if (e) {
987 if (!is_really_simple(e)) {
988 nasm_error(ERR_NONFATAL, "section attribute value must be"
989 " a critical expression");
990 return -1;
992 } else {
993 nasm_error(ERR_NONFATAL, "Invalid attribute value"
994 " specified in `section' directive.");
995 return -1;
997 *value = (uint64_t)reloc_value(e);
998 return 1;
1001 static void bin_sectalign(int32_t seg, unsigned int value)
1003 struct Section *s = find_section_by_index(seg);
1005 if (!s || !is_power2(value))
1006 return;
1008 if (value > s->align)
1009 s->align = value;
1011 if (!(s->flags & ALIGN_DEFINED))
1012 s->flags |= ALIGN_DEFINED;
1015 static void bin_assign_attributes(struct Section *sec, char *astring)
1017 int attribute, check;
1018 uint64_t value;
1019 char *p;
1021 while (1) { /* Get the next attribute. */
1022 check = bin_read_attribute(&astring, &attribute, &value);
1023 /* Skip bad attribute. */
1024 if (check == -1)
1025 continue;
1026 /* Unknown section attribute, so skip it and warn the user. */
1027 if (!check) {
1028 if (!*astring)
1029 break; /* End of line. */
1030 else {
1031 p = astring;
1032 while (*astring && !nasm_isspace(*astring))
1033 astring++;
1034 if (*astring) {
1035 *astring = '\0';
1036 astring++;
1038 nasm_error(ERR_WARNING, "ignoring unknown section attribute:"
1039 " \"%s\"", p);
1041 continue;
1044 switch (attribute) { /* Handle nobits attribute. */
1045 case ATTRIB_NOBITS:
1046 if ((sec->flags & TYPE_DEFINED)
1047 && (sec->flags & TYPE_PROGBITS))
1048 nasm_error(ERR_NONFATAL,
1049 "attempt to change section type"
1050 " from progbits to nobits");
1051 else
1052 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1053 continue;
1055 /* Handle progbits attribute. */
1056 case ATTRIB_PROGBITS:
1057 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1058 nasm_error(ERR_NONFATAL, "attempt to change section type"
1059 " from nobits to progbits");
1060 else
1061 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1062 continue;
1064 /* Handle align attribute. */
1065 case ATTRIB_ALIGN:
1066 if (!value || ((value - 1) & value)) {
1067 nasm_error(ERR_NONFATAL,
1068 "argument to `align' is not a power of two");
1069 } else {
1071 * Alignment is already satisfied if
1072 * the previous align value is greater
1074 if ((sec->flags & ALIGN_DEFINED) && (value < sec->align))
1075 value = sec->align;
1077 /* Don't allow a conflicting align value. */
1078 if ((sec->flags & START_DEFINED) && (sec->start & (value - 1))) {
1079 nasm_error(ERR_NONFATAL,
1080 "`align' value conflicts with section start address");
1081 } else {
1082 sec->align = value;
1083 sec->flags |= ALIGN_DEFINED;
1086 continue;
1088 /* Handle valign attribute. */
1089 case ATTRIB_VALIGN:
1090 if (!value || ((value - 1) & value))
1091 nasm_error(ERR_NONFATAL, "argument to `valign' is not a"
1092 " power of two");
1093 else { /* Alignment is already satisfied if the previous
1094 * align value is greater. */
1095 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1096 value = sec->valign;
1098 /* Don't allow a conflicting valign value. */
1099 if ((sec->flags & VSTART_DEFINED)
1100 && (sec->vstart & (value - 1)))
1101 nasm_error(ERR_NONFATAL,
1102 "`valign' value conflicts "
1103 "with `vstart' address");
1104 else {
1105 sec->valign = value;
1106 sec->flags |= VALIGN_DEFINED;
1109 continue;
1111 /* Handle start attribute. */
1112 case ATTRIB_START:
1113 if (sec->flags & FOLLOWS_DEFINED)
1114 nasm_error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1115 " section attributes");
1116 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1117 nasm_error(ERR_NONFATAL, "section start address redefined");
1118 else {
1119 sec->start = value;
1120 sec->flags |= START_DEFINED;
1121 if (sec->flags & ALIGN_DEFINED) {
1122 if (sec->start & (sec->align - 1))
1123 nasm_error(ERR_NONFATAL, "`start' address conflicts"
1124 " with section alignment");
1125 sec->flags ^= ALIGN_DEFINED;
1128 continue;
1130 /* Handle vstart attribute. */
1131 case ATTRIB_VSTART:
1132 if (sec->flags & VFOLLOWS_DEFINED)
1133 nasm_error(ERR_NONFATAL,
1134 "cannot combine `vstart' and `vfollows'"
1135 " section attributes");
1136 else if ((sec->flags & VSTART_DEFINED)
1137 && (value != sec->vstart))
1138 nasm_error(ERR_NONFATAL,
1139 "section virtual start address"
1140 " (vstart) redefined");
1141 else {
1142 sec->vstart = value;
1143 sec->flags |= VSTART_DEFINED;
1144 if (sec->flags & VALIGN_DEFINED) {
1145 if (sec->vstart & (sec->valign - 1))
1146 nasm_error(ERR_NONFATAL, "`vstart' address conflicts"
1147 " with `valign' value");
1148 sec->flags ^= VALIGN_DEFINED;
1151 continue;
1153 /* Handle follows attribute. */
1154 case ATTRIB_FOLLOWS:
1155 p = astring;
1156 astring += strcspn(astring, " \t");
1157 if (astring == p)
1158 nasm_error(ERR_NONFATAL, "expecting section name for `follows'"
1159 " attribute");
1160 else {
1161 *(astring++) = '\0';
1162 if (sec->flags & START_DEFINED)
1163 nasm_error(ERR_NONFATAL,
1164 "cannot combine `start' and `follows'"
1165 " section attributes");
1166 sec->follows = nasm_strdup(p);
1167 sec->flags |= FOLLOWS_DEFINED;
1169 continue;
1171 /* Handle vfollows attribute. */
1172 case ATTRIB_VFOLLOWS:
1173 if (sec->flags & VSTART_DEFINED)
1174 nasm_error(ERR_NONFATAL,
1175 "cannot combine `vstart' and `vfollows'"
1176 " section attributes");
1177 else {
1178 p = astring;
1179 astring += strcspn(astring, " \t");
1180 if (astring == p)
1181 nasm_error(ERR_NONFATAL,
1182 "expecting section name for `vfollows'"
1183 " attribute");
1184 else {
1185 *(astring++) = '\0';
1186 sec->vfollows = nasm_strdup(p);
1187 sec->flags |= VFOLLOWS_DEFINED;
1190 continue;
1195 static void bin_define_section_labels(void)
1197 static int labels_defined = 0;
1198 struct Section *sec;
1199 char *label_name;
1200 size_t base_len;
1202 if (labels_defined)
1203 return;
1204 list_for_each(sec, sections) {
1205 base_len = strlen(sec->name) + 8;
1206 label_name = nasm_malloc(base_len + 8);
1207 strcpy(label_name, "section.");
1208 strcpy(label_name + 8, sec->name);
1210 /* section.<name>.start */
1211 strcpy(label_name + base_len, ".start");
1212 define_label(label_name, sec->start_index, 0L, NULL, 0, 0);
1214 /* section.<name>.vstart */
1215 strcpy(label_name + base_len, ".vstart");
1216 define_label(label_name, sec->vstart_index, 0L, NULL, 0, 0);
1218 nasm_free(label_name);
1220 labels_defined = 1;
1223 static int32_t bin_secname(char *name, int pass, int *bits)
1225 char *p;
1226 struct Section *sec;
1228 /* bin_secname is called with *name = NULL at the start of each
1229 * pass. Use this opportunity to establish the default section
1230 * (default is BITS-16 ".text" segment).
1232 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1233 origin_defined = 0;
1234 list_for_each(sec, sections)
1235 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1236 ALIGN_DEFINED | VALIGN_DEFINED);
1238 /* Define section start and vstart labels. */
1239 if (pass != 1)
1240 bin_define_section_labels();
1242 /* Establish the default (.text) section. */
1243 *bits = 16;
1244 sec = find_section_by_name(".text");
1245 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1246 return sec->vstart_index;
1249 /* Attempt to find the requested section. If it does not
1250 * exist, create it. */
1251 p = name;
1252 while (*p && !nasm_isspace(*p))
1253 p++;
1254 if (*p)
1255 *p++ = '\0';
1256 sec = find_section_by_name(name);
1257 if (!sec) {
1258 sec = create_section(name);
1259 if (!strcmp(name, ".data"))
1260 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1261 else if (!strcmp(name, ".bss")) {
1262 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1263 sec->prev = NULL;
1267 /* Handle attribute assignments. */
1268 if (pass != 1)
1269 bin_assign_attributes(sec, p);
1271 #ifndef ABIN_SMART_ADAPT
1272 /* The following line disables smart adaptation of
1273 * PROGBITS/NOBITS section types (it forces sections to
1274 * default to PROGBITS). */
1275 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1276 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1277 #endif
1279 return sec->vstart_index;
1282 static int bin_directive(enum directives directive, char *args, int pass)
1284 switch (directive) {
1285 case D_ORG:
1287 struct tokenval tokval;
1288 uint64_t value;
1289 expr *e;
1291 stdscan_reset();
1292 stdscan_set(args);
1293 tokval.t_type = TOKEN_INVALID;
1294 e = evaluate(stdscan, NULL, &tokval, NULL, 1, nasm_error, NULL);
1295 if (e) {
1296 if (!is_really_simple(e))
1297 nasm_error(ERR_NONFATAL, "org value must be a critical"
1298 " expression");
1299 else {
1300 value = reloc_value(e);
1301 /* Check for ORG redefinition. */
1302 if (origin_defined && (value != origin))
1303 nasm_error(ERR_NONFATAL, "program origin redefined");
1304 else {
1305 origin = value;
1306 origin_defined = 1;
1309 } else
1310 nasm_error(ERR_NONFATAL, "No or invalid offset specified"
1311 " in ORG directive.");
1312 return 1;
1314 case D_MAP:
1316 /* The 'map' directive allows the user to generate section
1317 * and symbol information to stdout, stderr, or to a file. */
1318 char *p;
1320 if (pass != 1)
1321 return 1;
1322 args += strspn(args, " \t");
1323 while (*args) {
1324 p = args;
1325 args += strcspn(args, " \t");
1326 if (*args != '\0')
1327 *(args++) = '\0';
1328 if (!nasm_stricmp(p, "all"))
1329 map_control |=
1330 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1331 else if (!nasm_stricmp(p, "brief"))
1332 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1333 else if (!nasm_stricmp(p, "sections"))
1334 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1335 else if (!nasm_stricmp(p, "segments"))
1336 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1337 else if (!nasm_stricmp(p, "symbols"))
1338 map_control |= MAP_SYMBOLS;
1339 else if (!rf) {
1340 if (!nasm_stricmp(p, "stdout"))
1341 rf = stdout;
1342 else if (!nasm_stricmp(p, "stderr"))
1343 rf = stderr;
1344 else { /* Must be a filename. */
1345 rf = fopen(p, "wt");
1346 if (!rf) {
1347 nasm_error(ERR_WARNING, "unable to open map file `%s'",
1349 map_control = 0;
1350 return 1;
1353 } else
1354 nasm_error(ERR_WARNING, "map file already specified");
1356 if (map_control == 0)
1357 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1358 if (!rf)
1359 rf = stdout;
1360 return 1;
1362 default:
1363 return 0;
1367 static void bin_filename(char *inname, char *outname)
1369 standard_extension(inname, outname, "");
1370 infile = inname;
1371 outfile = outname;
1374 static void ith_filename(char *inname, char *outname)
1376 standard_extension(inname, outname, ".ith");
1377 infile = inname;
1378 outfile = outname;
1381 static void srec_filename(char *inname, char *outname)
1383 standard_extension(inname, outname, ".srec");
1384 infile = inname;
1385 outfile = outname;
1388 static int32_t bin_segbase(int32_t segment)
1390 return segment;
1393 static int bin_set_info(enum geninfo type, char **val)
1395 (void)type;
1396 (void)val;
1397 return 0;
1400 struct ofmt of_bin, of_ith, of_srec;
1401 static void binfmt_init(void);
1402 static void do_output_bin(void);
1403 static void do_output_ith(void);
1404 static void do_output_srec(void);
1406 static void bin_init(void)
1408 do_output = do_output_bin;
1409 binfmt_init();
1412 static void ith_init(void)
1414 do_output = do_output_ith;
1415 binfmt_init();
1418 static void srec_init(void)
1420 do_output = do_output_srec;
1421 binfmt_init();
1424 static void binfmt_init(void)
1426 maxbits = 64; /* Support 64-bit Segments */
1427 relocs = NULL;
1428 reloctail = &relocs;
1429 origin_defined = 0;
1430 no_seg_labels = NULL;
1431 nsl_tail = &no_seg_labels;
1433 /* Create default section (.text). */
1434 sections = last_section = nasm_zalloc(sizeof(struct Section));
1435 last_section->name = nasm_strdup(".text");
1436 last_section->contents = saa_init(1L);
1437 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1438 last_section->labels_end = &(last_section->labels);
1439 last_section->start_index = seg_alloc();
1440 last_section->vstart_index = seg_alloc();
1443 /* Generate binary file output */
1444 static void do_output_bin(void)
1446 struct Section *s;
1447 uint64_t addr = origin;
1449 /* Write the progbits sections to the output file. */
1450 list_for_each(s, sections) {
1451 /* Skip non-progbits sections */
1452 if (!(s->flags & TYPE_PROGBITS))
1453 continue;
1454 /* Skip zero-length sections */
1455 if (s->length == 0)
1456 continue;
1458 /* Pad the space between sections. */
1459 nasm_assert(addr <= s->start);
1460 fwritezero(s->start - addr, ofile);
1462 /* Write the section to the output file. */
1463 saa_fpwrite(s->contents, ofile);
1465 /* Keep track of the current file position */
1466 addr = s->start + s->length;
1470 /* Generate Intel hex file output */
1471 static void write_ith_record(unsigned int len, uint16_t addr,
1472 uint8_t type, void *data)
1474 char buf[1+2+4+2+255*2+2+2];
1475 char *p = buf;
1476 uint8_t csum, *dptr = data;
1477 unsigned int i;
1479 nasm_assert(len <= 255);
1481 csum = len + addr + (addr >> 8) + type;
1482 for (i = 0; i < len; i++)
1483 csum += dptr[i];
1484 csum = -csum;
1486 p += sprintf(p, ":%02X%04X%02X", len, addr, type);
1487 for (i = 0; i < len; i++)
1488 p += sprintf(p, "%02X", dptr[i]);
1489 p += sprintf(p, "%02X\n", csum);
1491 nasm_write(buf, p-buf, ofile);
1494 static void do_output_ith(void)
1496 uint8_t buf[32];
1497 struct Section *s;
1498 uint64_t addr, hiaddr, hilba;
1499 uint64_t length;
1500 unsigned int chunk;
1502 /* Write the progbits sections to the output file. */
1503 hilba = 0;
1504 list_for_each(s, sections) {
1505 /* Skip non-progbits sections */
1506 if (!(s->flags & TYPE_PROGBITS))
1507 continue;
1508 /* Skip zero-length sections */
1509 if (s->length == 0)
1510 continue;
1512 addr = s->start;
1513 length = s->length;
1514 saa_rewind(s->contents);
1516 while (length) {
1517 hiaddr = addr >> 16;
1518 if (hiaddr != hilba) {
1519 buf[0] = hiaddr >> 8;
1520 buf[1] = hiaddr;
1521 write_ith_record(2, 0, 4, buf);
1522 hilba = hiaddr;
1525 chunk = 32 - (addr & 31);
1526 if (length < chunk)
1527 chunk = length;
1529 saa_rnbytes(s->contents, buf, chunk);
1530 write_ith_record(chunk, (uint16_t)addr, 0, buf);
1532 addr += chunk;
1533 length -= chunk;
1537 /* Write closing record */
1538 write_ith_record(0, 0, 1, NULL);
1541 /* Generate Motorola S-records */
1542 static void write_srecord(unsigned int len, unsigned int alen,
1543 uint32_t addr, uint8_t type, void *data)
1545 char buf[2+2+8+255*2+2+2];
1546 char *p = buf;
1547 uint8_t csum, *dptr = data;
1548 unsigned int i;
1550 nasm_assert(len <= 255);
1552 switch (alen) {
1553 case 2:
1554 addr &= 0xffff;
1555 break;
1556 case 3:
1557 addr &= 0xffffff;
1558 break;
1559 case 4:
1560 break;
1561 default:
1562 nasm_assert(0);
1563 break;
1566 csum = (len+alen+1) + addr + (addr >> 8) + (addr >> 16) + (addr >> 24);
1567 for (i = 0; i < len; i++)
1568 csum += dptr[i];
1569 csum = 0xff-csum;
1571 p += sprintf(p, "S%c%02X%0*X", type, len+alen+1, alen*2, addr);
1572 for (i = 0; i < len; i++)
1573 p += sprintf(p, "%02X", dptr[i]);
1574 p += sprintf(p, "%02X\n", csum);
1576 nasm_write(buf, p-buf, ofile);
1579 static void do_output_srec(void)
1581 uint8_t buf[32];
1582 struct Section *s;
1583 uint64_t addr, maxaddr;
1584 uint64_t length;
1585 int alen;
1586 unsigned int chunk;
1587 char dtype, etype;
1589 maxaddr = 0;
1590 list_for_each(s, sections) {
1591 /* Skip non-progbits sections */
1592 if (!(s->flags & TYPE_PROGBITS))
1593 continue;
1594 /* Skip zero-length sections */
1595 if (s->length == 0)
1596 continue;
1598 addr = s->start + s->length - 1;
1599 if (addr > maxaddr)
1600 maxaddr = addr;
1603 if (maxaddr <= 0xffff) {
1604 alen = 2;
1605 dtype = '1'; /* S1 = 16-bit data */
1606 etype = '9'; /* S9 = 16-bit end */
1607 } else if (maxaddr <= 0xffffff) {
1608 alen = 3;
1609 dtype = '2'; /* S2 = 24-bit data */
1610 etype = '8'; /* S8 = 24-bit end */
1611 } else {
1612 alen = 4;
1613 dtype = '3'; /* S3 = 32-bit data */
1614 etype = '7'; /* S7 = 32-bit end */
1617 /* Write head record */
1618 write_srecord(0, 2, 0, '0', NULL);
1620 /* Write the progbits sections to the output file. */
1621 list_for_each(s, sections) {
1622 /* Skip non-progbits sections */
1623 if (!(s->flags & TYPE_PROGBITS))
1624 continue;
1625 /* Skip zero-length sections */
1626 if (s->length == 0)
1627 continue;
1629 addr = s->start;
1630 length = s->length;
1631 saa_rewind(s->contents);
1633 while (length) {
1634 chunk = 32 - (addr & 31);
1635 if (length < chunk)
1636 chunk = length;
1638 saa_rnbytes(s->contents, buf, chunk);
1639 write_srecord(chunk, alen, (uint32_t)addr, dtype, buf);
1641 addr += chunk;
1642 length -= chunk;
1646 /* Write closing record */
1647 write_srecord(0, alen, 0, etype, NULL);
1651 struct ofmt of_bin = {
1652 "flat-form binary files (e.g. DOS .COM, .SYS)",
1653 "bin",
1655 null_debug_arr,
1656 &null_debug_form,
1657 bin_stdmac,
1658 bin_init,
1659 bin_set_info,
1660 bin_out,
1661 bin_deflabel,
1662 bin_secname,
1663 bin_sectalign,
1664 bin_segbase,
1665 bin_directive,
1666 bin_filename,
1667 bin_cleanup
1670 struct ofmt of_ith = {
1671 "Intel hex",
1672 "ith",
1673 OFMT_TEXT,
1674 null_debug_arr,
1675 &null_debug_form,
1676 bin_stdmac,
1677 ith_init,
1678 bin_set_info,
1679 bin_out,
1680 bin_deflabel,
1681 bin_secname,
1682 bin_sectalign,
1683 bin_segbase,
1684 bin_directive,
1685 ith_filename,
1686 bin_cleanup
1689 struct ofmt of_srec = {
1690 "Motorola S-records",
1691 "srec",
1693 null_debug_arr,
1694 &null_debug_form,
1695 bin_stdmac,
1696 srec_init,
1697 bin_set_info,
1698 bin_out,
1699 bin_deflabel,
1700 bin_secname,
1701 bin_sectalign,
1702 bin_segbase,
1703 bin_directive,
1704 srec_filename,
1705 bin_cleanup
1708 #endif /* #ifdef OF_BIN */