output/outbin.c: Fix misprinted alignment bound
[nasm/sigaren-mirror.git] / output / outbin.c
blob332d84e79e90f0cfc7e8452d2a2a4625348912d9
1 /* ----------------------------------------------------------------------- *
2 *
3 * Copyright 1996-2009 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 *ifollows; /* 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 uint8_t format_mode; /* 0 = original bin, 1 = extended bin */
156 static int32_t current_section; /* only really needed if format_mode = 0 */
157 static uint64_t origin;
158 static int origin_defined;
160 /* Stuff we need for map-file generation. */
161 #define MAP_ORIGIN 1
162 #define MAP_SUMMARY 2
163 #define MAP_SECTIONS 4
164 #define MAP_SYMBOLS 8
165 static int map_control = 0;
166 static char *infile, *outfile;
168 extern macros_t bin_stdmac[];
170 static void add_reloc(struct Section *s, int32_t bytes, int32_t secref,
171 int32_t secrel)
173 struct Reloc *r;
175 r = *reloctail = nasm_malloc(sizeof(struct Reloc));
176 reloctail = &r->next;
177 r->next = NULL;
178 r->posn = s->length;
179 r->bytes = bytes;
180 r->secref = secref;
181 r->secrel = secrel;
182 r->target = s;
185 static struct Section *find_section_by_name(const char *name)
187 struct Section *s;
189 list_for_each(s, sections)
190 if (!strcmp(s->name, name))
191 break;
192 return s;
195 static struct Section *find_section_by_index(int32_t index)
197 struct Section *s;
199 list_for_each(s, sections)
200 if ((index == s->vstart_index) || (index == s->start_index))
201 break;
202 return s;
205 static struct Section *create_section(char *name)
206 { /* Create a new section. */
207 last_section->next = nasm_malloc(sizeof(struct Section));
208 last_section->next->ifollows = last_section;
209 last_section = last_section->next;
210 last_section->labels = NULL;
211 last_section->labels_end = &(last_section->labels);
213 /* Initialize section attributes. */
214 last_section->name = nasm_strdup(name);
215 last_section->contents = saa_init(1L);
216 last_section->follows = last_section->vfollows = 0;
217 last_section->length = 0;
218 last_section->flags = 0;
219 last_section->next = NULL;
221 /* Register our sections with NASM. */
222 last_section->vstart_index = seg_alloc();
223 last_section->start_index = seg_alloc();
224 return last_section;
227 static void bin_cleanup(int debuginfo)
229 struct Section *g, **gp;
230 struct Section *gs = NULL, **gsp;
231 struct Section *s, **sp;
232 struct Section *nobits = NULL, **nt;
233 struct Section *last_progbits;
234 struct bin_label *l;
235 struct Reloc *r;
236 uint64_t pend;
237 int h;
239 (void)debuginfo; /* placate optimizers */
241 #ifdef DEBUG
242 nasm_error(ERR_DEBUG,
243 "bin_cleanup: Sections were initially referenced in this order:\n");
244 for (h = 0, s = sections; s; h++, s = s->next)
245 fprintf(stdout, "%i. %s\n", h, s->name);
246 #endif
248 /* Assembly has completed, so now we need to generate the output file.
249 * Step 1: Separate progbits and nobits sections into separate lists.
250 * Step 2: Sort the progbits sections into their output order.
251 * Step 3: Compute start addresses for all progbits sections.
252 * Step 4: Compute vstart addresses for all sections.
253 * Step 5: Apply relocations.
254 * Step 6: Write the sections' data to the output file.
255 * Step 7: Generate the map file.
256 * Step 8: Release all allocated memory.
259 /* To do: Smart section-type adaptation could leave some empty sections
260 * without a defined type (progbits/nobits). Won't fix now since this
261 * feature will be disabled. */
263 /* Step 1: Split progbits and nobits sections into separate lists. */
265 nt = &nobits;
266 /* Move nobits sections into a separate list. Also pre-process nobits
267 * sections' attributes. */
268 for (sp = &sections->next, s = sections->next; s; s = *sp) { /* Skip progbits sections. */
269 if (s->flags & TYPE_PROGBITS) {
270 sp = &s->next;
271 continue;
273 /* Do some special pre-processing on nobits sections' attributes. */
274 if (s->flags & (START_DEFINED | ALIGN_DEFINED | FOLLOWS_DEFINED)) { /* Check for a mixture of real and virtual section attributes. */
275 if (s->flags & (VSTART_DEFINED | VALIGN_DEFINED |
276 VFOLLOWS_DEFINED))
277 nasm_error(ERR_FATAL|ERR_NOFILE,
278 "cannot mix real and virtual attributes"
279 " in nobits section (%s)", s->name);
280 /* Real and virtual attributes mean the same thing for nobits sections. */
281 if (s->flags & START_DEFINED) {
282 s->vstart = s->start;
283 s->flags |= VSTART_DEFINED;
285 if (s->flags & ALIGN_DEFINED) {
286 s->valign = s->align;
287 s->flags |= VALIGN_DEFINED;
289 if (s->flags & FOLLOWS_DEFINED) {
290 s->vfollows = s->follows;
291 s->flags |= VFOLLOWS_DEFINED;
292 s->flags &= ~FOLLOWS_DEFINED;
295 /* Every section must have a start address. */
296 if (s->flags & VSTART_DEFINED) {
297 s->start = s->vstart;
298 s->flags |= START_DEFINED;
300 /* Move the section into the nobits list. */
301 *sp = s->next;
302 s->next = NULL;
303 *nt = s;
304 nt = &s->next;
307 /* Step 2: Sort the progbits sections into their output order. */
309 /* In Step 2 we move around sections in groups. A group
310 * begins with a section (group leader) that has a user-
311 * defined start address or follows section. The remainder
312 * of the group is made up of the sections that implicitly
313 * follow the group leader (i.e., they were defined after
314 * the group leader and were not given an explicit start
315 * address or follows section by the user). */
317 /* For anyone attempting to read this code:
318 * g (group) points to a group of sections, the first one of which has
319 * a user-defined start address or follows section.
320 * gp (g previous) holds the location of the pointer to g.
321 * gs (g scan) is a temp variable that we use to scan to the end of the group.
322 * gsp (gs previous) holds the location of the pointer to gs.
323 * nt (nobits tail) points to the nobits section-list tail.
326 /* Link all 'follows' groups to their proper position. To do
327 * this we need to know three things: the start of the group
328 * to relocate (g), the section it is following (s), and the
329 * end of the group we're relocating (gs). */
330 for (gp = &sections, g = sections; g; g = gs) { /* Find the next follows group that is out of place (g). */
331 if (!(g->flags & FOLLOWS_DEFINED)) {
332 while (g->next) {
333 if ((g->next->flags & FOLLOWS_DEFINED) &&
334 strcmp(g->name, g->next->follows))
335 break;
336 g = g->next;
338 if (!g->next)
339 break;
340 gp = &g->next;
341 g = g->next;
343 /* Find the section that this group follows (s). */
344 for (sp = &sections, s = sections;
345 s && strcmp(s->name, g->follows);
346 sp = &s->next, s = s->next) ;
347 if (!s)
348 nasm_error(ERR_FATAL|ERR_NOFILE, "section %s follows an invalid or"
349 " unknown section (%s)", g->name, g->follows);
350 if (s->next && (s->next->flags & FOLLOWS_DEFINED) &&
351 !strcmp(s->name, s->next->follows))
352 nasm_error(ERR_FATAL|ERR_NOFILE, "sections %s and %s can't both follow"
353 " section %s", g->name, s->next->name, s->name);
354 /* Find the end of the current follows group (gs). */
355 for (gsp = &g->next, gs = g->next;
356 gs && (gs != s) && !(gs->flags & START_DEFINED);
357 gsp = &gs->next, gs = gs->next) {
358 if (gs->next && (gs->next->flags & FOLLOWS_DEFINED) &&
359 strcmp(gs->name, gs->next->follows)) {
360 gsp = &gs->next;
361 gs = gs->next;
362 break;
365 /* Re-link the group after its follows section. */
366 *gsp = s->next;
367 s->next = g;
368 *gp = gs;
371 /* Link all 'start' groups to their proper position. Once
372 * again we need to know g, s, and gs (see above). The main
373 * difference is we already know g since we sort by moving
374 * groups from the 'unsorted' list into a 'sorted' list (g
375 * will always be the first section in the unsorted list). */
376 for (g = sections, sections = NULL; g; g = gs) { /* Find the section that we will insert this group before (s). */
377 for (sp = &sections, s = sections; s; sp = &s->next, s = s->next)
378 if ((s->flags & START_DEFINED) && (g->start < s->start))
379 break;
380 /* Find the end of the group (gs). */
381 for (gs = g->next, gsp = &g->next;
382 gs && !(gs->flags & START_DEFINED);
383 gsp = &gs->next, gs = gs->next) ;
384 /* Re-link the group before the target section. */
385 *sp = g;
386 *gsp = s;
389 /* Step 3: Compute start addresses for all progbits sections. */
391 /* Make sure we have an origin and a start address for the first section. */
392 if (origin_defined) {
393 if (sections->flags & START_DEFINED) {
394 /* Make sure this section doesn't begin before the origin. */
395 if (sections->start < origin)
396 nasm_error(ERR_FATAL|ERR_NOFILE, "section %s begins"
397 " before program origin", sections->name);
398 } else if (sections->flags & ALIGN_DEFINED) {
399 sections->start = ALIGN(origin, sections->align);
400 } else {
401 sections->start = origin;
403 } else {
404 if (!(sections->flags & START_DEFINED))
405 sections->start = 0;
406 origin = sections->start;
408 sections->flags |= START_DEFINED;
410 /* Make sure each section has an explicit start address. If it
411 * doesn't, then compute one based its alignment and the end of
412 * the previous section. */
413 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
414 * (has a defined start address, and is not zero length). */
415 if (g == s)
416 for (s = g->next;
417 s && ((s->length == 0) || !(s->flags & START_DEFINED));
418 s = s->next) ;
419 /* Compute the start address of this section, if necessary. */
420 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
421 if (!(g->flags & ALIGN_DEFINED)) {
422 g->align = 4;
423 g->flags |= ALIGN_DEFINED;
425 /* Set the section start address. */
426 g->start = ALIGN(pend, g->align);
427 g->flags |= START_DEFINED;
429 /* Ugly special case for progbits sections' virtual attributes:
430 * If there is a defined valign, but no vstart and no vfollows, then
431 * we valign after the previous progbits section. This case doesn't
432 * really make much sense for progbits sections with a defined start
433 * address, but it is possible and we must do *something*.
434 * Not-so-ugly special case:
435 * If a progbits section has no virtual attributes, we set the
436 * vstart equal to the start address. */
437 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
438 if (g->flags & VALIGN_DEFINED)
439 g->vstart = ALIGN(pend, g->valign);
440 else
441 g->vstart = g->start;
442 g->flags |= VSTART_DEFINED;
444 /* Ignore zero-length sections. */
445 if (g->start < pend)
446 continue;
447 /* Compute the span of this section. */
448 pend = g->start + g->length;
449 /* Check for section overlap. */
450 if (s) {
451 if (s->start < origin)
452 nasm_error(ERR_FATAL|ERR_NOFILE, "section %s beings before program origin",
453 s->name);
454 if (g->start > s->start)
455 nasm_error(ERR_FATAL|ERR_NOFILE, "sections %s ~ %s and %s overlap!",
456 gs->name, g->name, s->name);
457 if (pend > s->start)
458 nasm_error(ERR_FATAL|ERR_NOFILE, "sections %s and %s overlap!",
459 g->name, s->name);
461 /* Remember this section as the latest >0 length section. */
462 gs = g;
465 /* Step 4: Compute vstart addresses for all sections. */
467 /* Attach the nobits sections to the end of the progbits sections. */
468 for (s = sections; s->next; s = s->next) ;
469 s->next = nobits;
470 last_progbits = s;
472 * Scan for sections that don't have a vstart address. If we find
473 * one we'll attempt to compute its vstart. If we can't compute
474 * the vstart, we leave it alone and come back to it in a
475 * subsequent scan. We continue scanning and re-scanning until
476 * we've gone one full cycle without computing any vstarts.
478 do { /* Do one full scan of the sections list. */
479 for (h = 0, g = sections; g; g = g->next) {
480 if (g->flags & VSTART_DEFINED)
481 continue;
482 /* Find the section that this one virtually follows. */
483 if (g->flags & VFOLLOWS_DEFINED) {
484 for (s = sections; s && strcmp(g->vfollows, s->name);
485 s = s->next) ;
486 if (!s)
487 nasm_error(ERR_FATAL|ERR_NOFILE,
488 "section %s vfollows unknown section (%s)",
489 g->name, g->vfollows);
490 } else if (g->ifollows != NULL)
491 for (s = sections; s && (s != g->ifollows); s = s->next) ;
492 /* The .bss section is the only one with ifollows = NULL.
493 In this case we implicitly follow the last progbits
494 section. */
495 else
496 s = last_progbits;
498 /* If the section we're following has a vstart, we can proceed. */
499 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
500 if (!(g->flags & VALIGN_DEFINED)) {
501 g->valign = 4;
502 g->flags |= VALIGN_DEFINED;
504 /* Compute the vstart address. */
505 g->vstart = ALIGN(s->vstart + s->length, g->valign);
506 g->flags |= VSTART_DEFINED;
507 h++;
508 /* Start and vstart mean the same thing for nobits sections. */
509 if (g->flags & TYPE_NOBITS)
510 g->start = g->vstart;
513 } while (h);
515 /* Now check for any circular vfollows references, which will manifest
516 * themselves as sections without a defined vstart. */
517 for (h = 0, s = sections; s; s = s->next) {
518 if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
519 * no-no, but we'll throw a fatal one eventually so it's ok. */
520 nasm_error(ERR_NONFATAL, "cannot compute vstart for section %s",
521 s->name);
522 h++;
525 if (h)
526 nasm_error(ERR_FATAL|ERR_NOFILE, "circular vfollows path detected");
528 #ifdef DEBUG
529 nasm_error(ERR_DEBUG,
530 "bin_cleanup: Confirm final section order for output file:\n");
531 for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
532 h++, s = s->next)
533 fprintf(stdout, "%i. %s\n", h, s->name);
534 #endif
536 /* Step 5: Apply relocations. */
538 /* Prepare the sections for relocating. */
539 list_for_each(s, sections)
540 saa_rewind(s->contents);
541 /* Apply relocations. */
542 list_for_each(r, relocs) {
543 uint8_t *p, *q, mydata[8];
544 int64_t l;
546 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
547 p = q = mydata;
548 l = *p++;
550 if (r->bytes > 1) {
551 l += ((int64_t)*p++) << 8;
552 if (r->bytes >= 4) {
553 l += ((int64_t)*p++) << 16;
554 l += ((int64_t)*p++) << 24;
556 if (r->bytes == 8) {
557 l += ((int64_t)*p++) << 32;
558 l += ((int64_t)*p++) << 40;
559 l += ((int64_t)*p++) << 48;
560 l += ((int64_t)*p++) << 56;
564 s = find_section_by_index(r->secref);
565 if (s) {
566 if (r->secref == s->start_index)
567 l += s->start;
568 else
569 l += s->vstart;
571 s = find_section_by_index(r->secrel);
572 if (s) {
573 if (r->secrel == s->start_index)
574 l -= s->start;
575 else
576 l -= s->vstart;
579 if (r->bytes >= 4)
580 WRITEDLONG(q, l);
581 else if (r->bytes == 2)
582 WRITESHORT(q, l);
583 else
584 *q++ = (uint8_t)(l & 0xFF);
585 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
588 /* Step 6: Write the section data to the output file. */
589 do_output();
591 /* Step 7: Generate the map file. */
593 if (map_control) {
594 static const char not_defined[] = "not defined";
596 /* Display input and output file names. */
597 fprintf(rf, "\n- NASM Map file ");
598 for (h = 63; h; h--)
599 fputc('-', rf);
600 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
601 infile, outfile);
603 if (map_control & MAP_ORIGIN) { /* Display program origin. */
604 fprintf(rf, "-- Program origin ");
605 for (h = 61; h; h--)
606 fputc('-', rf);
607 fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
609 /* Display sections summary. */
610 if (map_control & MAP_SUMMARY) {
611 fprintf(rf, "-- Sections (summary) ");
612 for (h = 57; h; h--)
613 fputc('-', rf);
614 fprintf(rf, "\n\nVstart Start Stop "
615 "Length Class Name\n");
616 list_for_each(s, sections) {
617 fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
618 s->vstart, s->start, s->start + s->length,
619 s->length);
620 if (s->flags & TYPE_PROGBITS)
621 fprintf(rf, "progbits ");
622 else
623 fprintf(rf, "nobits ");
624 fprintf(rf, "%s\n", s->name);
626 fprintf(rf, "\n");
628 /* Display detailed section information. */
629 if (map_control & MAP_SECTIONS) {
630 fprintf(rf, "-- Sections (detailed) ");
631 for (h = 56; h; h--)
632 fputc('-', rf);
633 fprintf(rf, "\n\n");
634 list_for_each(s, sections) {
635 fprintf(rf, "---- Section %s ", s->name);
636 for (h = 65 - strlen(s->name); h; h--)
637 fputc('-', rf);
638 fprintf(rf, "\n\nclass: ");
639 if (s->flags & TYPE_PROGBITS)
640 fprintf(rf, "progbits");
641 else
642 fprintf(rf, "nobits");
643 fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
644 "\nalign: ", s->length, s->start);
645 if (s->flags & ALIGN_DEFINED)
646 fprintf(rf, "%16"PRIX64"", s->align);
647 else
648 fputs(not_defined, rf);
649 fprintf(rf, "\nfollows: ");
650 if (s->flags & FOLLOWS_DEFINED)
651 fprintf(rf, "%s", s->follows);
652 else
653 fputs(not_defined, rf);
654 fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
655 if (s->flags & VALIGN_DEFINED)
656 fprintf(rf, "%16"PRIX64"", s->valign);
657 else
658 fputs(not_defined, rf);
659 fprintf(rf, "\nvfollows: ");
660 if (s->flags & VFOLLOWS_DEFINED)
661 fprintf(rf, "%s", s->vfollows);
662 else
663 fputs(not_defined, rf);
664 fprintf(rf, "\n\n");
667 /* Display symbols information. */
668 if (map_control & MAP_SYMBOLS) {
669 int32_t segment;
670 int64_t offset;
672 fprintf(rf, "-- Symbols ");
673 for (h = 68; h; h--)
674 fputc('-', rf);
675 fprintf(rf, "\n\n");
676 if (no_seg_labels) {
677 fprintf(rf, "---- No Section ");
678 for (h = 63; h; h--)
679 fputc('-', rf);
680 fprintf(rf, "\n\nValue Name\n");
681 list_for_each(l, no_seg_labels) {
682 lookup_label(l->name, &segment, &offset);
683 fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
685 fprintf(rf, "\n\n");
687 list_for_each(s, sections) {
688 if (s->labels) {
689 fprintf(rf, "---- Section %s ", s->name);
690 for (h = 65 - strlen(s->name); h; h--)
691 fputc('-', rf);
692 fprintf(rf, "\n\nReal Virtual Name\n");
693 list_for_each(l, s->labels) {
694 lookup_label(l->name, &segment, &offset);
695 fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
696 s->start + offset, s->vstart + offset,
697 l->name);
699 fprintf(rf, "\n");
705 /* Close the report file. */
706 if (map_control && (rf != stdout) && (rf != stderr))
707 fclose(rf);
709 /* Step 8: Release all allocated memory. */
711 /* Free sections, label pointer structs, etc.. */
712 while (sections) {
713 s = sections;
714 sections = s->next;
715 saa_free(s->contents);
716 nasm_free(s->name);
717 if (s->flags & FOLLOWS_DEFINED)
718 nasm_free(s->follows);
719 if (s->flags & VFOLLOWS_DEFINED)
720 nasm_free(s->vfollows);
721 while (s->labels) {
722 l = s->labels;
723 s->labels = l->next;
724 nasm_free(l);
726 nasm_free(s);
729 /* Free no-section labels. */
730 while (no_seg_labels) {
731 l = no_seg_labels;
732 no_seg_labels = l->next;
733 nasm_free(l);
736 /* Free relocation structures. */
737 while (relocs) {
738 r = relocs->next;
739 nasm_free(relocs);
740 relocs = r;
744 static void bin_out(int32_t segto, const void *data,
745 enum out_type type, uint64_t size,
746 int32_t segment, int32_t wrt)
748 uint8_t *p, mydata[8];
749 struct Section *s;
751 if (wrt != NO_SEG) {
752 wrt = NO_SEG; /* continue to do _something_ */
753 nasm_error(ERR_NONFATAL, "WRT not supported by binary output format");
756 /* Handle absolute-assembly (structure definitions). */
757 if (segto == NO_SEG) {
758 if (type != OUT_RESERVE)
759 nasm_error(ERR_NONFATAL, "attempt to assemble code in"
760 " [ABSOLUTE] space");
761 return;
764 /* Find the segment we are targeting. */
765 s = find_section_by_index(segto);
766 if (!s)
767 nasm_error(ERR_PANIC, "code directed to nonexistent segment?");
769 /* "Smart" section-type adaptation code. */
770 if (!(s->flags & TYPE_DEFINED)) {
771 if (type == OUT_RESERVE)
772 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
773 else
774 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
777 if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
778 nasm_error(ERR_WARNING, "attempt to initialize memory in a"
779 " nobits section: ignored");
781 if (type == OUT_ADDRESS) {
782 if (segment != NO_SEG && !find_section_by_index(segment)) {
783 if (segment % 2)
784 nasm_error(ERR_NONFATAL, "binary output format does not support"
785 " segment base references");
786 else
787 nasm_error(ERR_NONFATAL, "binary output format does not support"
788 " external references");
789 segment = NO_SEG;
791 if (s->flags & TYPE_PROGBITS) {
792 if (segment != NO_SEG)
793 add_reloc(s, size, segment, -1L);
794 p = mydata;
795 WRITEADDR(p, *(int64_t *)data, size);
796 saa_wbytes(s->contents, mydata, size);
798 s->length += size;
799 } else if (type == OUT_RAWDATA) {
800 if (s->flags & TYPE_PROGBITS)
801 saa_wbytes(s->contents, data, size);
802 s->length += size;
803 } else if (type == OUT_RESERVE) {
804 if (s->flags & TYPE_PROGBITS) {
805 nasm_error(ERR_WARNING, "uninitialized space declared in"
806 " %s section: zeroing", s->name);
807 saa_wbytes(s->contents, NULL, size);
809 s->length += size;
810 } else if (type == OUT_REL2ADR || type == OUT_REL4ADR ||
811 type == OUT_REL8ADR) {
812 int64_t addr = *(int64_t *)data - size;
813 size = realsize(type, size);
814 if (segment != NO_SEG && !find_section_by_index(segment)) {
815 if (segment % 2)
816 nasm_error(ERR_NONFATAL, "binary output format does not support"
817 " segment base references");
818 else
819 nasm_error(ERR_NONFATAL, "binary output format does not support"
820 " external references");
821 segment = NO_SEG;
823 if (s->flags & TYPE_PROGBITS) {
824 add_reloc(s, size, segment, segto);
825 p = mydata;
826 WRITEADDR(p, addr - s->length, size);
827 saa_wbytes(s->contents, mydata, size);
829 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 if (format_mode) {
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;
922 } else
923 return 0;
925 /* Find the end of the expression. */
926 if ((*line)[attrib_name_size] != '(') {
927 /* Single term (no parenthesis). */
928 exp = *line += attrib_name_size;
929 while (**line && !nasm_isspace(**line))
930 (*line)++;
931 if (**line) {
932 **line = '\0';
933 (*line)++;
935 } else {
936 char c;
937 int pcount = 1;
939 /* Full expression (delimited by parenthesis) */
940 exp = *line += attrib_name_size + 1;
941 while (1) {
942 (*line) += strcspn(*line, "()'\"");
943 if (**line == '(') {
944 ++(*line);
945 ++pcount;
947 if (**line == ')') {
948 ++(*line);
949 --pcount;
950 if (!pcount)
951 break;
953 if ((**line == '"') || (**line == '\'')) {
954 c = **line;
955 while (**line) {
956 ++(*line);
957 if (**line == c)
958 break;
960 if (!**line) {
961 nasm_error(ERR_NONFATAL,
962 "invalid syntax in `section' directive");
963 return -1;
965 ++(*line);
967 if (!**line) {
968 nasm_error(ERR_NONFATAL, "expecting `)'");
969 return -1;
972 *(*line - 1) = '\0'; /* Terminate the expression. */
975 /* Check for no value given. */
976 if (!*exp) {
977 nasm_error(ERR_WARNING, "No value given to attribute in"
978 " `section' directive");
979 return -1;
982 /* Read and evaluate the expression. */
983 stdscan_reset();
984 stdscan_set(exp);
985 tokval.t_type = TOKEN_INVALID;
986 e = evaluate(stdscan, NULL, &tokval, NULL, 1, nasm_error, NULL);
987 if (e) {
988 if (!is_really_simple(e)) {
989 nasm_error(ERR_NONFATAL, "section attribute value must be"
990 " a critical expression");
991 return -1;
993 } else {
994 nasm_error(ERR_NONFATAL, "Invalid attribute value"
995 " specified in `section' directive.");
996 return -1;
998 *value = (uint64_t)reloc_value(e);
999 return 1;
1002 static void bin_assign_attributes(struct Section *sec, char *astring)
1004 int attribute, check;
1005 uint64_t value;
1006 char *p;
1008 while (1) { /* Get the next attribute. */
1009 check = bin_read_attribute(&astring, &attribute, &value);
1010 /* Skip bad attribute. */
1011 if (check == -1)
1012 continue;
1013 /* Unknown section attribute, so skip it and warn the user. */
1014 if (!check) {
1015 if (!*astring)
1016 break; /* End of line. */
1017 else {
1018 p = astring;
1019 while (*astring && !nasm_isspace(*astring))
1020 astring++;
1021 if (*astring) {
1022 *astring = '\0';
1023 astring++;
1025 nasm_error(ERR_WARNING, "ignoring unknown section attribute:"
1026 " \"%s\"", p);
1028 continue;
1031 switch (attribute) { /* Handle nobits attribute. */
1032 case ATTRIB_NOBITS:
1033 if ((sec->flags & TYPE_DEFINED)
1034 && (sec->flags & TYPE_PROGBITS))
1035 nasm_error(ERR_NONFATAL,
1036 "attempt to change section type"
1037 " from progbits to nobits");
1038 else
1039 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1040 continue;
1042 /* Handle progbits attribute. */
1043 case ATTRIB_PROGBITS:
1044 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1045 nasm_error(ERR_NONFATAL, "attempt to change section type"
1046 " from nobits to progbits");
1047 else
1048 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1049 continue;
1051 /* Handle align attribute. */
1052 case ATTRIB_ALIGN:
1053 if (!format_mode && (!strcmp(sec->name, ".text")))
1054 nasm_error(ERR_NONFATAL, "cannot specify an alignment"
1055 " to the .text section");
1056 else {
1057 if (!value || ((value - 1) & value))
1058 nasm_error(ERR_NONFATAL, "argument to `align' is not a"
1059 " power of two");
1060 else { /* Alignment is already satisfied if the previous
1061 * align value is greater. */
1062 if ((sec->flags & ALIGN_DEFINED)
1063 && (value < sec->align))
1064 value = sec->align;
1066 /* Don't allow a conflicting align value. */
1067 if ((sec->flags & START_DEFINED)
1068 && (sec->start & (value - 1)))
1069 nasm_error(ERR_NONFATAL,
1070 "`align' value conflicts "
1071 "with section start address");
1072 else {
1073 sec->align = value;
1074 sec->flags |= ALIGN_DEFINED;
1078 continue;
1080 /* Handle valign attribute. */
1081 case ATTRIB_VALIGN:
1082 if (!value || ((value - 1) & value))
1083 nasm_error(ERR_NONFATAL, "argument to `valign' is not a"
1084 " power of two");
1085 else { /* Alignment is already satisfied if the previous
1086 * align value is greater. */
1087 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1088 value = sec->valign;
1090 /* Don't allow a conflicting valign value. */
1091 if ((sec->flags & VSTART_DEFINED)
1092 && (sec->vstart & (value - 1)))
1093 nasm_error(ERR_NONFATAL,
1094 "`valign' value conflicts "
1095 "with `vstart' address");
1096 else {
1097 sec->valign = value;
1098 sec->flags |= VALIGN_DEFINED;
1101 continue;
1103 /* Handle start attribute. */
1104 case ATTRIB_START:
1105 if (sec->flags & FOLLOWS_DEFINED)
1106 nasm_error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1107 " section attributes");
1108 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1109 nasm_error(ERR_NONFATAL, "section start address redefined");
1110 else {
1111 sec->start = value;
1112 sec->flags |= START_DEFINED;
1113 if (sec->flags & ALIGN_DEFINED) {
1114 if (sec->start & (sec->align - 1))
1115 nasm_error(ERR_NONFATAL, "`start' address conflicts"
1116 " with section alignment");
1117 sec->flags ^= ALIGN_DEFINED;
1120 continue;
1122 /* Handle vstart attribute. */
1123 case ATTRIB_VSTART:
1124 if (sec->flags & VFOLLOWS_DEFINED)
1125 nasm_error(ERR_NONFATAL,
1126 "cannot combine `vstart' and `vfollows'"
1127 " section attributes");
1128 else if ((sec->flags & VSTART_DEFINED)
1129 && (value != sec->vstart))
1130 nasm_error(ERR_NONFATAL,
1131 "section virtual start address"
1132 " (vstart) redefined");
1133 else {
1134 sec->vstart = value;
1135 sec->flags |= VSTART_DEFINED;
1136 if (sec->flags & VALIGN_DEFINED) {
1137 if (sec->vstart & (sec->valign - 1))
1138 nasm_error(ERR_NONFATAL, "`vstart' address conflicts"
1139 " with `valign' value");
1140 sec->flags ^= VALIGN_DEFINED;
1143 continue;
1145 /* Handle follows attribute. */
1146 case ATTRIB_FOLLOWS:
1147 p = astring;
1148 astring += strcspn(astring, " \t");
1149 if (astring == p)
1150 nasm_error(ERR_NONFATAL, "expecting section name for `follows'"
1151 " attribute");
1152 else {
1153 *(astring++) = '\0';
1154 if (sec->flags & START_DEFINED)
1155 nasm_error(ERR_NONFATAL,
1156 "cannot combine `start' and `follows'"
1157 " section attributes");
1158 sec->follows = nasm_strdup(p);
1159 sec->flags |= FOLLOWS_DEFINED;
1161 continue;
1163 /* Handle vfollows attribute. */
1164 case ATTRIB_VFOLLOWS:
1165 if (sec->flags & VSTART_DEFINED)
1166 nasm_error(ERR_NONFATAL,
1167 "cannot combine `vstart' and `vfollows'"
1168 " section attributes");
1169 else {
1170 p = astring;
1171 astring += strcspn(astring, " \t");
1172 if (astring == p)
1173 nasm_error(ERR_NONFATAL,
1174 "expecting section name for `vfollows'"
1175 " attribute");
1176 else {
1177 *(astring++) = '\0';
1178 sec->vfollows = nasm_strdup(p);
1179 sec->flags |= VFOLLOWS_DEFINED;
1182 continue;
1187 static void bin_define_section_labels(void)
1189 static int labels_defined = 0;
1190 struct Section *sec;
1191 char *label_name;
1192 size_t base_len;
1194 if (labels_defined)
1195 return;
1196 list_for_each(sec, sections) {
1197 base_len = strlen(sec->name) + 8;
1198 label_name = nasm_malloc(base_len + 8);
1199 strcpy(label_name, "section.");
1200 strcpy(label_name + 8, sec->name);
1202 /* section.<name>.start */
1203 strcpy(label_name + base_len, ".start");
1204 define_label(label_name, sec->start_index, 0L, NULL, 0, 0);
1206 /* section.<name>.vstart */
1207 strcpy(label_name + base_len, ".vstart");
1208 define_label(label_name, sec->vstart_index, 0L, NULL, 0, 0);
1210 nasm_free(label_name);
1212 labels_defined = 1;
1215 static int32_t bin_secname(char *name, int pass, int *bits)
1217 char *p;
1218 struct Section *sec;
1220 /* bin_secname is called with *name = NULL at the start of each
1221 * pass. Use this opportunity to establish the default section
1222 * (default is BITS-16 ".text" segment).
1224 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1225 origin_defined = 0;
1226 list_for_each(sec, sections)
1227 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1228 ALIGN_DEFINED | VALIGN_DEFINED);
1230 /* Define section start and vstart labels. */
1231 if (format_mode && (pass != 1))
1232 bin_define_section_labels();
1234 /* Establish the default (.text) section. */
1235 *bits = 16;
1236 sec = find_section_by_name(".text");
1237 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1238 current_section = sec->vstart_index;
1239 return current_section;
1242 /* Attempt to find the requested section. If it does not
1243 * exist, create it. */
1244 p = name;
1245 while (*p && !nasm_isspace(*p))
1246 p++;
1247 if (*p)
1248 *p++ = '\0';
1249 sec = find_section_by_name(name);
1250 if (!sec) {
1251 sec = create_section(name);
1252 if (!strcmp(name, ".data"))
1253 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1254 else if (!strcmp(name, ".bss")) {
1255 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1256 sec->ifollows = NULL;
1257 } else if (!format_mode) {
1258 nasm_error(ERR_NONFATAL, "section name must be "
1259 ".text, .data, or .bss");
1260 return current_section;
1264 /* Handle attribute assignments. */
1265 if (pass != 1)
1266 bin_assign_attributes(sec, p);
1268 #ifndef ABIN_SMART_ADAPT
1269 /* The following line disables smart adaptation of
1270 * PROGBITS/NOBITS section types (it forces sections to
1271 * default to PROGBITS). */
1272 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1273 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1274 #endif
1276 /* Set the current section and return. */
1277 current_section = sec->vstart_index;
1278 return current_section;
1281 static int bin_directive(enum directives directive, char *args, int pass)
1283 switch (directive) {
1284 case D_ORG:
1286 struct tokenval tokval;
1287 uint64_t value;
1288 expr *e;
1290 stdscan_reset();
1291 stdscan_set(args);
1292 tokval.t_type = TOKEN_INVALID;
1293 e = evaluate(stdscan, NULL, &tokval, NULL, 1, nasm_error, NULL);
1294 if (e) {
1295 if (!is_really_simple(e))
1296 nasm_error(ERR_NONFATAL, "org value must be a critical"
1297 " expression");
1298 else {
1299 value = reloc_value(e);
1300 /* Check for ORG redefinition. */
1301 if (origin_defined && (value != origin))
1302 nasm_error(ERR_NONFATAL, "program origin redefined");
1303 else {
1304 origin = value;
1305 origin_defined = 1;
1308 } else
1309 nasm_error(ERR_NONFATAL, "No or invalid offset specified"
1310 " in ORG directive.");
1311 return 1;
1313 case D_MAP:
1315 /* The 'map' directive allows the user to generate section
1316 * and symbol information to stdout, stderr, or to a file. */
1317 char *p;
1319 if (pass != 1)
1320 return 1;
1321 args += strspn(args, " \t");
1322 while (*args) {
1323 p = args;
1324 args += strcspn(args, " \t");
1325 if (*args != '\0')
1326 *(args++) = '\0';
1327 if (!nasm_stricmp(p, "all"))
1328 map_control |=
1329 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1330 else if (!nasm_stricmp(p, "brief"))
1331 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1332 else if (!nasm_stricmp(p, "sections"))
1333 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1334 else if (!nasm_stricmp(p, "segments"))
1335 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1336 else if (!nasm_stricmp(p, "symbols"))
1337 map_control |= MAP_SYMBOLS;
1338 else if (!rf) {
1339 if (!nasm_stricmp(p, "stdout"))
1340 rf = stdout;
1341 else if (!nasm_stricmp(p, "stderr"))
1342 rf = stderr;
1343 else { /* Must be a filename. */
1344 rf = fopen(p, "wt");
1345 if (!rf) {
1346 nasm_error(ERR_WARNING, "unable to open map file `%s'",
1348 map_control = 0;
1349 return 1;
1352 } else
1353 nasm_error(ERR_WARNING, "map file already specified");
1355 if (map_control == 0)
1356 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1357 if (!rf)
1358 rf = stdout;
1359 return 1;
1361 default:
1362 return 0;
1366 static void bin_filename(char *inname, char *outname)
1368 standard_extension(inname, outname, "");
1369 infile = inname;
1370 outfile = outname;
1373 static void ith_filename(char *inname, char *outname)
1375 standard_extension(inname, outname, ".ith");
1376 infile = inname;
1377 outfile = outname;
1380 static void srec_filename(char *inname, char *outname)
1382 standard_extension(inname, outname, ".srec");
1383 infile = inname;
1384 outfile = outname;
1387 static int32_t bin_segbase(int32_t segment)
1389 return segment;
1392 static int bin_set_info(enum geninfo type, char **val)
1394 (void)type;
1395 (void)val;
1396 return 0;
1399 struct ofmt of_bin, of_ith, of_srec;
1400 static void binfmt_init(void);
1401 static void do_output_bin(void);
1402 static void do_output_ith(void);
1403 static void do_output_srec(void);
1405 static void bin_init(void)
1407 do_output = do_output_bin;
1408 binfmt_init();
1411 static void ith_init(void)
1413 do_output = do_output_ith;
1414 binfmt_init();
1417 static void srec_init(void)
1419 do_output = do_output_srec;
1420 binfmt_init();
1423 static void binfmt_init(void)
1425 maxbits = 64; /* Support 64-bit Segments */
1426 relocs = NULL;
1427 reloctail = &relocs;
1428 origin_defined = 0;
1429 no_seg_labels = NULL;
1430 nsl_tail = &no_seg_labels;
1431 format_mode = 1; /* Extended bin format
1432 * (set this to zero for old bin format). */
1434 /* Create default section (.text). */
1435 sections = last_section = nasm_malloc(sizeof(struct Section));
1436 last_section->next = NULL;
1437 last_section->name = nasm_strdup(".text");
1438 last_section->contents = saa_init(1L);
1439 last_section->follows = last_section->vfollows = 0;
1440 last_section->ifollows = NULL;
1441 last_section->length = 0;
1442 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1443 last_section->labels = NULL;
1444 last_section->labels_end = &(last_section->labels);
1445 last_section->start_index = seg_alloc();
1446 last_section->vstart_index = current_section = seg_alloc();
1449 /* Generate binary file output */
1450 static void do_output_bin(void)
1452 struct Section *s;
1453 uint64_t addr = origin;
1455 /* Write the progbits sections to the output file. */
1456 list_for_each(s, sections) {
1457 /* Skip non-progbits sections */
1458 if (!(s->flags & TYPE_PROGBITS))
1459 continue;
1460 /* Skip zero-length sections */
1461 if (s->length == 0)
1462 continue;
1464 /* Pad the space between sections. */
1465 nasm_assert(addr <= s->start);
1466 fwritezero(s->start - addr, ofile);
1468 /* Write the section to the output file. */
1469 saa_fpwrite(s->contents, ofile);
1471 /* Keep track of the current file position */
1472 addr = s->start + s->length;
1476 /* Generate Intel hex file output */
1477 static int write_ith_record(unsigned int len, uint16_t addr,
1478 uint8_t type, void *data)
1480 char buf[1+2+4+2+255*2+2+2];
1481 char *p = buf;
1482 uint8_t csum, *dptr = data;
1483 unsigned int i;
1485 nasm_assert(len <= 255);
1487 csum = len + addr + (addr >> 8) + type;
1488 for (i = 0; i < len; i++)
1489 csum += dptr[i];
1490 csum = -csum;
1492 p += sprintf(p, ":%02X%04X%02X", len, addr, type);
1493 for (i = 0; i < len; i++)
1494 p += sprintf(p, "%02X", dptr[i]);
1495 p += sprintf(p, "%02X\n", csum);
1497 if (fwrite(buf, 1, p-buf, ofile) != (size_t)(p-buf))
1498 return -1;
1500 return 0;
1503 static void do_output_ith(void)
1505 uint8_t buf[32];
1506 struct Section *s;
1507 uint64_t addr, hiaddr, hilba;
1508 uint64_t length;
1509 unsigned int chunk;
1511 /* Write the progbits sections to the output file. */
1512 hilba = 0;
1513 list_for_each(s, sections) {
1514 /* Skip non-progbits sections */
1515 if (!(s->flags & TYPE_PROGBITS))
1516 continue;
1517 /* Skip zero-length sections */
1518 if (s->length == 0)
1519 continue;
1521 addr = s->start;
1522 length = s->length;
1523 saa_rewind(s->contents);
1525 while (length) {
1526 hiaddr = addr >> 16;
1527 if (hiaddr != hilba) {
1528 buf[0] = hiaddr >> 8;
1529 buf[1] = hiaddr;
1530 write_ith_record(2, 0, 4, buf);
1531 hilba = hiaddr;
1534 chunk = 32 - (addr & 31);
1535 if (length < chunk)
1536 chunk = length;
1538 saa_rnbytes(s->contents, buf, chunk);
1539 write_ith_record(chunk, (uint16_t)addr, 0, buf);
1541 addr += chunk;
1542 length -= chunk;
1546 /* Write closing record */
1547 write_ith_record(0, 0, 1, NULL);
1550 /* Generate Motorola S-records */
1551 static int write_srecord(unsigned int len, unsigned int alen,
1552 uint32_t addr, uint8_t type, void *data)
1554 char buf[2+2+8+255*2+2+2];
1555 char *p = buf;
1556 uint8_t csum, *dptr = data;
1557 unsigned int i;
1559 nasm_assert(len <= 255);
1561 switch (alen) {
1562 case 2:
1563 addr &= 0xffff;
1564 break;
1565 case 3:
1566 addr &= 0xffffff;
1567 break;
1568 case 4:
1569 break;
1570 default:
1571 nasm_assert(0);
1572 break;
1575 csum = (len+alen+1) + addr + (addr >> 8) + (addr >> 16) + (addr >> 24);
1576 for (i = 0; i < len; i++)
1577 csum += dptr[i];
1578 csum = 0xff-csum;
1580 p += sprintf(p, "S%c%02X%0*X", type, len+alen+1, alen*2, addr);
1581 for (i = 0; i < len; i++)
1582 p += sprintf(p, "%02X", dptr[i]);
1583 p += sprintf(p, "%02X\n", csum);
1585 if (fwrite(buf, 1, p-buf, ofile) != (size_t)(p-buf))
1586 return -1;
1588 return 0;
1591 static void do_output_srec(void)
1593 uint8_t buf[32];
1594 struct Section *s;
1595 uint64_t addr, maxaddr;
1596 uint64_t length;
1597 int alen;
1598 unsigned int chunk;
1599 char dtype, etype;
1601 maxaddr = 0;
1602 list_for_each(s, sections) {
1603 /* Skip non-progbits sections */
1604 if (!(s->flags & TYPE_PROGBITS))
1605 continue;
1606 /* Skip zero-length sections */
1607 if (s->length == 0)
1608 continue;
1610 addr = s->start + s->length - 1;
1611 if (addr > maxaddr)
1612 maxaddr = addr;
1615 if (maxaddr <= 0xffff) {
1616 alen = 2;
1617 dtype = '1'; /* S1 = 16-bit data */
1618 etype = '9'; /* S9 = 16-bit end */
1619 } else if (maxaddr <= 0xffffff) {
1620 alen = 3;
1621 dtype = '2'; /* S2 = 24-bit data */
1622 etype = '8'; /* S8 = 24-bit end */
1623 } else {
1624 alen = 4;
1625 dtype = '3'; /* S3 = 32-bit data */
1626 etype = '7'; /* S7 = 32-bit end */
1629 /* Write head record */
1630 write_srecord(0, 2, 0, '0', NULL);
1632 /* Write the progbits sections to the output file. */
1633 list_for_each(s, sections) {
1634 /* Skip non-progbits sections */
1635 if (!(s->flags & TYPE_PROGBITS))
1636 continue;
1637 /* Skip zero-length sections */
1638 if (s->length == 0)
1639 continue;
1641 addr = s->start;
1642 length = s->length;
1643 saa_rewind(s->contents);
1645 while (length) {
1646 chunk = 32 - (addr & 31);
1647 if (length < chunk)
1648 chunk = length;
1650 saa_rnbytes(s->contents, buf, chunk);
1651 write_srecord(chunk, alen, (uint32_t)addr, dtype, buf);
1653 addr += chunk;
1654 length -= chunk;
1658 /* Write closing record */
1659 write_srecord(0, alen, 0, etype, NULL);
1663 struct ofmt of_bin = {
1664 "flat-form binary files (e.g. DOS .COM, .SYS)",
1665 "bin",
1667 null_debug_arr,
1668 &null_debug_form,
1669 bin_stdmac,
1670 bin_init,
1671 bin_set_info,
1672 bin_out,
1673 bin_deflabel,
1674 bin_secname,
1675 bin_segbase,
1676 bin_directive,
1677 bin_filename,
1678 bin_cleanup
1681 struct ofmt of_ith = {
1682 "Intel hex",
1683 "ith",
1684 OFMT_TEXT,
1685 null_debug_arr,
1686 &null_debug_form,
1687 bin_stdmac,
1688 ith_init,
1689 bin_set_info,
1690 bin_out,
1691 bin_deflabel,
1692 bin_secname,
1693 bin_segbase,
1694 bin_directive,
1695 ith_filename,
1696 bin_cleanup
1699 struct ofmt of_srec = {
1700 "Motorola S-records",
1701 "srec",
1703 null_debug_arr,
1704 &null_debug_form,
1705 bin_stdmac,
1706 srec_init,
1707 bin_set_info,
1708 bin_out,
1709 bin_deflabel,
1710 bin_secname,
1711 bin_segbase,
1712 bin_directive,
1713 srec_filename,
1714 bin_cleanup
1717 #endif /* #ifdef OF_BIN */