NASM 2.08rc7
[nasm/avx512.git] / output / outbin.c
blob41c28f30f4be047ad870ff3cc6b78bc5ec3831f0
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 = ((origin + sections->align - 1) &
400 ~(sections->align - 1));
401 } else {
402 sections->start = origin;
404 } else {
405 if (!(sections->flags & START_DEFINED))
406 sections->start = 0;
407 origin = sections->start;
409 sections->flags |= START_DEFINED;
411 /* Make sure each section has an explicit start address. If it
412 * doesn't, then compute one based its alignment and the end of
413 * the previous section. */
414 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
415 * (has a defined start address, and is not zero length). */
416 if (g == s)
417 for (s = g->next;
418 s && ((s->length == 0) || !(s->flags & START_DEFINED));
419 s = s->next) ;
420 /* Compute the start address of this section, if necessary. */
421 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
422 if (!(g->flags & ALIGN_DEFINED)) {
423 g->align = 4;
424 g->flags |= ALIGN_DEFINED;
426 /* Set the section start address. */
427 g->start = (pend + g->align - 1) & ~(g->align - 1);
428 g->flags |= START_DEFINED;
430 /* Ugly special case for progbits sections' virtual attributes:
431 * If there is a defined valign, but no vstart and no vfollows, then
432 * we valign after the previous progbits section. This case doesn't
433 * really make much sense for progbits sections with a defined start
434 * address, but it is possible and we must do *something*.
435 * Not-so-ugly special case:
436 * If a progbits section has no virtual attributes, we set the
437 * vstart equal to the start address. */
438 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
439 if (g->flags & VALIGN_DEFINED)
440 g->vstart = (pend + g->valign - 1) & ~(g->valign - 1);
441 else
442 g->vstart = g->start;
443 g->flags |= VSTART_DEFINED;
445 /* Ignore zero-length sections. */
446 if (g->start < pend)
447 continue;
448 /* Compute the span of this section. */
449 pend = g->start + g->length;
450 /* Check for section overlap. */
451 if (s) {
452 if (s->start < origin)
453 nasm_error(ERR_FATAL|ERR_NOFILE, "section %s beings before program origin",
454 s->name);
455 if (g->start > s->start)
456 nasm_error(ERR_FATAL|ERR_NOFILE, "sections %s ~ %s and %s overlap!",
457 gs->name, g->name, s->name);
458 if (pend > s->start)
459 nasm_error(ERR_FATAL|ERR_NOFILE, "sections %s and %s overlap!",
460 g->name, s->name);
462 /* Remember this section as the latest >0 length section. */
463 gs = g;
466 /* Step 4: Compute vstart addresses for all sections. */
468 /* Attach the nobits sections to the end of the progbits sections. */
469 for (s = sections; s->next; s = s->next) ;
470 s->next = nobits;
471 last_progbits = s;
473 * Scan for sections that don't have a vstart address. If we find
474 * one we'll attempt to compute its vstart. If we can't compute
475 * the vstart, we leave it alone and come back to it in a
476 * subsequent scan. We continue scanning and re-scanning until
477 * we've gone one full cycle without computing any vstarts.
479 do { /* Do one full scan of the sections list. */
480 for (h = 0, g = sections; g; g = g->next) {
481 if (g->flags & VSTART_DEFINED)
482 continue;
483 /* Find the section that this one virtually follows. */
484 if (g->flags & VFOLLOWS_DEFINED) {
485 for (s = sections; s && strcmp(g->vfollows, s->name);
486 s = s->next) ;
487 if (!s)
488 nasm_error(ERR_FATAL|ERR_NOFILE,
489 "section %s vfollows unknown section (%s)",
490 g->name, g->vfollows);
491 } else if (g->ifollows != NULL)
492 for (s = sections; s && (s != g->ifollows); s = s->next) ;
493 /* The .bss section is the only one with ifollows = NULL.
494 In this case we implicitly follow the last progbits
495 section. */
496 else
497 s = last_progbits;
499 /* If the section we're following has a vstart, we can proceed. */
500 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
501 if (!(g->flags & VALIGN_DEFINED)) {
502 g->valign = 4;
503 g->flags |= VALIGN_DEFINED;
505 /* Compute the vstart address. */
506 g->vstart = (s->vstart + s->length + g->valign - 1)
507 & ~(g->valign - 1);
508 g->flags |= VSTART_DEFINED;
509 h++;
510 /* Start and vstart mean the same thing for nobits sections. */
511 if (g->flags & TYPE_NOBITS)
512 g->start = g->vstart;
515 } while (h);
517 /* Now check for any circular vfollows references, which will manifest
518 * themselves as sections without a defined vstart. */
519 for (h = 0, s = sections; s; s = s->next) {
520 if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
521 * no-no, but we'll throw a fatal one eventually so it's ok. */
522 nasm_error(ERR_NONFATAL, "cannot compute vstart for section %s",
523 s->name);
524 h++;
527 if (h)
528 nasm_error(ERR_FATAL|ERR_NOFILE, "circular vfollows path detected");
530 #ifdef DEBUG
531 nasm_error(ERR_DEBUG,
532 "bin_cleanup: Confirm final section order for output file:\n");
533 for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
534 h++, s = s->next)
535 fprintf(stdout, "%i. %s\n", h, s->name);
536 #endif
538 /* Step 5: Apply relocations. */
540 /* Prepare the sections for relocating. */
541 list_for_each(s, sections)
542 saa_rewind(s->contents);
543 /* Apply relocations. */
544 list_for_each(r, relocs) {
545 uint8_t *p, *q, mydata[8];
546 int64_t l;
548 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
549 p = q = mydata;
550 l = *p++;
552 if (r->bytes > 1) {
553 l += ((int64_t)*p++) << 8;
554 if (r->bytes >= 4) {
555 l += ((int64_t)*p++) << 16;
556 l += ((int64_t)*p++) << 24;
558 if (r->bytes == 8) {
559 l += ((int64_t)*p++) << 32;
560 l += ((int64_t)*p++) << 40;
561 l += ((int64_t)*p++) << 48;
562 l += ((int64_t)*p++) << 56;
566 s = find_section_by_index(r->secref);
567 if (s) {
568 if (r->secref == s->start_index)
569 l += s->start;
570 else
571 l += s->vstart;
573 s = find_section_by_index(r->secrel);
574 if (s) {
575 if (r->secrel == s->start_index)
576 l -= s->start;
577 else
578 l -= s->vstart;
581 if (r->bytes >= 4)
582 WRITEDLONG(q, l);
583 else if (r->bytes == 2)
584 WRITESHORT(q, l);
585 else
586 *q++ = (uint8_t)(l & 0xFF);
587 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
590 /* Step 6: Write the section data to the output file. */
591 do_output();
593 /* Step 7: Generate the map file. */
595 if (map_control) {
596 static const char not_defined[] = "not defined";
598 /* Display input and output file names. */
599 fprintf(rf, "\n- NASM Map file ");
600 for (h = 63; h; h--)
601 fputc('-', rf);
602 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
603 infile, outfile);
605 if (map_control & MAP_ORIGIN) { /* Display program origin. */
606 fprintf(rf, "-- Program origin ");
607 for (h = 61; h; h--)
608 fputc('-', rf);
609 fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
611 /* Display sections summary. */
612 if (map_control & MAP_SUMMARY) {
613 fprintf(rf, "-- Sections (summary) ");
614 for (h = 57; h; h--)
615 fputc('-', rf);
616 fprintf(rf, "\n\nVstart Start Stop "
617 "Length Class Name\n");
618 list_for_each(s, sections) {
619 fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
620 s->vstart, s->start, s->start + s->length,
621 s->length);
622 if (s->flags & TYPE_PROGBITS)
623 fprintf(rf, "progbits ");
624 else
625 fprintf(rf, "nobits ");
626 fprintf(rf, "%s\n", s->name);
628 fprintf(rf, "\n");
630 /* Display detailed section information. */
631 if (map_control & MAP_SECTIONS) {
632 fprintf(rf, "-- Sections (detailed) ");
633 for (h = 56; h; h--)
634 fputc('-', rf);
635 fprintf(rf, "\n\n");
636 list_for_each(s, sections) {
637 fprintf(rf, "---- Section %s ", s->name);
638 for (h = 65 - strlen(s->name); h; h--)
639 fputc('-', rf);
640 fprintf(rf, "\n\nclass: ");
641 if (s->flags & TYPE_PROGBITS)
642 fprintf(rf, "progbits");
643 else
644 fprintf(rf, "nobits");
645 fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
646 "\nalign: ", s->length, s->start);
647 if (s->flags & ALIGN_DEFINED)
648 fprintf(rf, "%16"PRIX64"", s->align);
649 else
650 fputs(not_defined, rf);
651 fprintf(rf, "\nfollows: ");
652 if (s->flags & FOLLOWS_DEFINED)
653 fprintf(rf, "%s", s->follows);
654 else
655 fputs(not_defined, rf);
656 fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
657 if (s->flags & VALIGN_DEFINED)
658 fprintf(rf, "%16"PRIX64"", s->valign);
659 else
660 fputs(not_defined, rf);
661 fprintf(rf, "\nvfollows: ");
662 if (s->flags & VFOLLOWS_DEFINED)
663 fprintf(rf, "%s", s->vfollows);
664 else
665 fputs(not_defined, rf);
666 fprintf(rf, "\n\n");
669 /* Display symbols information. */
670 if (map_control & MAP_SYMBOLS) {
671 int32_t segment;
672 int64_t offset;
674 fprintf(rf, "-- Symbols ");
675 for (h = 68; h; h--)
676 fputc('-', rf);
677 fprintf(rf, "\n\n");
678 if (no_seg_labels) {
679 fprintf(rf, "---- No Section ");
680 for (h = 63; h; h--)
681 fputc('-', rf);
682 fprintf(rf, "\n\nValue Name\n");
683 list_for_each(l, no_seg_labels) {
684 lookup_label(l->name, &segment, &offset);
685 fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
687 fprintf(rf, "\n\n");
689 list_for_each(s, sections) {
690 if (s->labels) {
691 fprintf(rf, "---- Section %s ", s->name);
692 for (h = 65 - strlen(s->name); h; h--)
693 fputc('-', rf);
694 fprintf(rf, "\n\nReal Virtual Name\n");
695 list_for_each(l, s->labels) {
696 lookup_label(l->name, &segment, &offset);
697 fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
698 s->start + offset, s->vstart + offset,
699 l->name);
701 fprintf(rf, "\n");
707 /* Close the report file. */
708 if (map_control && (rf != stdout) && (rf != stderr))
709 fclose(rf);
711 /* Step 8: Release all allocated memory. */
713 /* Free sections, label pointer structs, etc.. */
714 while (sections) {
715 s = sections;
716 sections = s->next;
717 saa_free(s->contents);
718 nasm_free(s->name);
719 if (s->flags & FOLLOWS_DEFINED)
720 nasm_free(s->follows);
721 if (s->flags & VFOLLOWS_DEFINED)
722 nasm_free(s->vfollows);
723 while (s->labels) {
724 l = s->labels;
725 s->labels = l->next;
726 nasm_free(l);
728 nasm_free(s);
731 /* Free no-section labels. */
732 while (no_seg_labels) {
733 l = no_seg_labels;
734 no_seg_labels = l->next;
735 nasm_free(l);
738 /* Free relocation structures. */
739 while (relocs) {
740 r = relocs->next;
741 nasm_free(relocs);
742 relocs = r;
746 static void bin_out(int32_t segto, const void *data,
747 enum out_type type, uint64_t size,
748 int32_t segment, int32_t wrt)
750 uint8_t *p, mydata[8];
751 struct Section *s;
753 if (wrt != NO_SEG) {
754 wrt = NO_SEG; /* continue to do _something_ */
755 nasm_error(ERR_NONFATAL, "WRT not supported by binary output format");
758 /* Handle absolute-assembly (structure definitions). */
759 if (segto == NO_SEG) {
760 if (type != OUT_RESERVE)
761 nasm_error(ERR_NONFATAL, "attempt to assemble code in"
762 " [ABSOLUTE] space");
763 return;
766 /* Find the segment we are targeting. */
767 s = find_section_by_index(segto);
768 if (!s)
769 nasm_error(ERR_PANIC, "code directed to nonexistent segment?");
771 /* "Smart" section-type adaptation code. */
772 if (!(s->flags & TYPE_DEFINED)) {
773 if (type == OUT_RESERVE)
774 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
775 else
776 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
779 if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
780 nasm_error(ERR_WARNING, "attempt to initialize memory in a"
781 " nobits section: ignored");
783 if (type == OUT_ADDRESS) {
784 if (segment != NO_SEG && !find_section_by_index(segment)) {
785 if (segment % 2)
786 nasm_error(ERR_NONFATAL, "binary output format does not support"
787 " segment base references");
788 else
789 nasm_error(ERR_NONFATAL, "binary output format does not support"
790 " external references");
791 segment = NO_SEG;
793 if (s->flags & TYPE_PROGBITS) {
794 if (segment != NO_SEG)
795 add_reloc(s, size, segment, -1L);
796 p = mydata;
797 WRITEADDR(p, *(int64_t *)data, size);
798 saa_wbytes(s->contents, mydata, size);
800 s->length += size;
801 } else if (type == OUT_RAWDATA) {
802 if (s->flags & TYPE_PROGBITS)
803 saa_wbytes(s->contents, data, size);
804 s->length += size;
805 } else if (type == OUT_RESERVE) {
806 if (s->flags & TYPE_PROGBITS) {
807 nasm_error(ERR_WARNING, "uninitialized space declared in"
808 " %s section: zeroing", s->name);
809 saa_wbytes(s->contents, NULL, size);
811 s->length += size;
812 } else if (type == OUT_REL2ADR || type == OUT_REL4ADR ||
813 type == OUT_REL8ADR) {
814 int64_t addr = *(int64_t *)data - size;
815 size = realsize(type, size);
816 if (segment != NO_SEG && !find_section_by_index(segment)) {
817 if (segment % 2)
818 nasm_error(ERR_NONFATAL, "binary output format does not support"
819 " segment base references");
820 else
821 nasm_error(ERR_NONFATAL, "binary output format does not support"
822 " external references");
823 segment = NO_SEG;
825 if (s->flags & TYPE_PROGBITS) {
826 add_reloc(s, size, segment, segto);
827 p = mydata;
828 WRITEADDR(p, addr - s->length, size);
829 saa_wbytes(s->contents, mydata, size);
831 s->length += size;
835 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
836 int is_global, char *special)
838 (void)segment; /* Don't warn that this parameter is unused */
839 (void)offset; /* Don't warn that this parameter is unused */
841 if (special)
842 nasm_error(ERR_NONFATAL, "binary format does not support any"
843 " special symbol types");
844 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
845 nasm_error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
846 else if (is_global == 2)
847 nasm_error(ERR_NONFATAL, "binary output format does not support common"
848 " variables");
849 else {
850 struct Section *s;
851 struct bin_label ***ltp;
853 /* Remember label definition so we can look it up later when
854 * creating the map file. */
855 s = find_section_by_index(segment);
856 if (s)
857 ltp = &(s->labels_end);
858 else
859 ltp = &nsl_tail;
860 (**ltp) = nasm_malloc(sizeof(struct bin_label));
861 (**ltp)->name = name;
862 (**ltp)->next = NULL;
863 *ltp = &((**ltp)->next);
868 /* These constants and the following function are used
869 * by bin_secname() to parse attribute assignments. */
871 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
872 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
873 ATTRIB_NOBITS, ATTRIB_PROGBITS
876 static int bin_read_attribute(char **line, int *attribute,
877 uint64_t *value)
879 expr *e;
880 int attrib_name_size;
881 struct tokenval tokval;
882 char *exp;
884 /* Skip whitespace. */
885 while (**line && nasm_isspace(**line))
886 (*line)++;
887 if (!**line)
888 return 0;
890 /* Figure out what attribute we're reading. */
891 if (!nasm_strnicmp(*line, "align=", 6)) {
892 *attribute = ATTRIB_ALIGN;
893 attrib_name_size = 6;
894 } else if (format_mode) {
895 if (!nasm_strnicmp(*line, "start=", 6)) {
896 *attribute = ATTRIB_START;
897 attrib_name_size = 6;
898 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
899 *attribute = ATTRIB_FOLLOWS;
900 *line += 8;
901 return 1;
902 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
903 *attribute = ATTRIB_VSTART;
904 attrib_name_size = 7;
905 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
906 *attribute = ATTRIB_VALIGN;
907 attrib_name_size = 7;
908 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
909 *attribute = ATTRIB_VFOLLOWS;
910 *line += 9;
911 return 1;
912 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
913 (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
914 *attribute = ATTRIB_NOBITS;
915 *line += 6;
916 return 1;
917 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
918 (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
919 *attribute = ATTRIB_PROGBITS;
920 *line += 8;
921 return 1;
922 } else
923 return 0;
924 } else
925 return 0;
927 /* Find the end of the expression. */
928 if ((*line)[attrib_name_size] != '(') {
929 /* Single term (no parenthesis). */
930 exp = *line += attrib_name_size;
931 while (**line && !nasm_isspace(**line))
932 (*line)++;
933 if (**line) {
934 **line = '\0';
935 (*line)++;
937 } else {
938 char c;
939 int pcount = 1;
941 /* Full expression (delimited by parenthesis) */
942 exp = *line += attrib_name_size + 1;
943 while (1) {
944 (*line) += strcspn(*line, "()'\"");
945 if (**line == '(') {
946 ++(*line);
947 ++pcount;
949 if (**line == ')') {
950 ++(*line);
951 --pcount;
952 if (!pcount)
953 break;
955 if ((**line == '"') || (**line == '\'')) {
956 c = **line;
957 while (**line) {
958 ++(*line);
959 if (**line == c)
960 break;
962 if (!**line) {
963 nasm_error(ERR_NONFATAL,
964 "invalid syntax in `section' directive");
965 return -1;
967 ++(*line);
969 if (!**line) {
970 nasm_error(ERR_NONFATAL, "expecting `)'");
971 return -1;
974 *(*line - 1) = '\0'; /* Terminate the expression. */
977 /* Check for no value given. */
978 if (!*exp) {
979 nasm_error(ERR_WARNING, "No value given to attribute in"
980 " `section' directive");
981 return -1;
984 /* Read and evaluate the expression. */
985 stdscan_reset();
986 stdscan_set(exp);
987 tokval.t_type = TOKEN_INVALID;
988 e = evaluate(stdscan, NULL, &tokval, NULL, 1, nasm_error, NULL);
989 if (e) {
990 if (!is_really_simple(e)) {
991 nasm_error(ERR_NONFATAL, "section attribute value must be"
992 " a critical expression");
993 return -1;
995 } else {
996 nasm_error(ERR_NONFATAL, "Invalid attribute value"
997 " specified in `section' directive.");
998 return -1;
1000 *value = (uint64_t)reloc_value(e);
1001 return 1;
1004 static void bin_assign_attributes(struct Section *sec, char *astring)
1006 int attribute, check;
1007 uint64_t value;
1008 char *p;
1010 while (1) { /* Get the next attribute. */
1011 check = bin_read_attribute(&astring, &attribute, &value);
1012 /* Skip bad attribute. */
1013 if (check == -1)
1014 continue;
1015 /* Unknown section attribute, so skip it and warn the user. */
1016 if (!check) {
1017 if (!*astring)
1018 break; /* End of line. */
1019 else {
1020 p = astring;
1021 while (*astring && !nasm_isspace(*astring))
1022 astring++;
1023 if (*astring) {
1024 *astring = '\0';
1025 astring++;
1027 nasm_error(ERR_WARNING, "ignoring unknown section attribute:"
1028 " \"%s\"", p);
1030 continue;
1033 switch (attribute) { /* Handle nobits attribute. */
1034 case ATTRIB_NOBITS:
1035 if ((sec->flags & TYPE_DEFINED)
1036 && (sec->flags & TYPE_PROGBITS))
1037 nasm_error(ERR_NONFATAL,
1038 "attempt to change section type"
1039 " from progbits to nobits");
1040 else
1041 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1042 continue;
1044 /* Handle progbits attribute. */
1045 case ATTRIB_PROGBITS:
1046 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1047 nasm_error(ERR_NONFATAL, "attempt to change section type"
1048 " from nobits to progbits");
1049 else
1050 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1051 continue;
1053 /* Handle align attribute. */
1054 case ATTRIB_ALIGN:
1055 if (!format_mode && (!strcmp(sec->name, ".text")))
1056 nasm_error(ERR_NONFATAL, "cannot specify an alignment"
1057 " to the .text section");
1058 else {
1059 if (!value || ((value - 1) & value))
1060 nasm_error(ERR_NONFATAL, "argument to `align' is not a"
1061 " power of two");
1062 else { /* Alignment is already satisfied if the previous
1063 * align value is greater. */
1064 if ((sec->flags & ALIGN_DEFINED)
1065 && (value < sec->align))
1066 value = sec->align;
1068 /* Don't allow a conflicting align value. */
1069 if ((sec->flags & START_DEFINED)
1070 && (sec->start & (value - 1)))
1071 nasm_error(ERR_NONFATAL,
1072 "`align' value conflicts "
1073 "with section start address");
1074 else {
1075 sec->align = value;
1076 sec->flags |= ALIGN_DEFINED;
1080 continue;
1082 /* Handle valign attribute. */
1083 case ATTRIB_VALIGN:
1084 if (!value || ((value - 1) & value))
1085 nasm_error(ERR_NONFATAL, "argument to `valign' is not a"
1086 " power of two");
1087 else { /* Alignment is already satisfied if the previous
1088 * align value is greater. */
1089 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1090 value = sec->valign;
1092 /* Don't allow a conflicting valign value. */
1093 if ((sec->flags & VSTART_DEFINED)
1094 && (sec->vstart & (value - 1)))
1095 nasm_error(ERR_NONFATAL,
1096 "`valign' value conflicts "
1097 "with `vstart' address");
1098 else {
1099 sec->valign = value;
1100 sec->flags |= VALIGN_DEFINED;
1103 continue;
1105 /* Handle start attribute. */
1106 case ATTRIB_START:
1107 if (sec->flags & FOLLOWS_DEFINED)
1108 nasm_error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1109 " section attributes");
1110 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1111 nasm_error(ERR_NONFATAL, "section start address redefined");
1112 else {
1113 sec->start = value;
1114 sec->flags |= START_DEFINED;
1115 if (sec->flags & ALIGN_DEFINED) {
1116 if (sec->start & (sec->align - 1))
1117 nasm_error(ERR_NONFATAL, "`start' address conflicts"
1118 " with section alignment");
1119 sec->flags ^= ALIGN_DEFINED;
1122 continue;
1124 /* Handle vstart attribute. */
1125 case ATTRIB_VSTART:
1126 if (sec->flags & VFOLLOWS_DEFINED)
1127 nasm_error(ERR_NONFATAL,
1128 "cannot combine `vstart' and `vfollows'"
1129 " section attributes");
1130 else if ((sec->flags & VSTART_DEFINED)
1131 && (value != sec->vstart))
1132 nasm_error(ERR_NONFATAL,
1133 "section virtual start address"
1134 " (vstart) redefined");
1135 else {
1136 sec->vstart = value;
1137 sec->flags |= VSTART_DEFINED;
1138 if (sec->flags & VALIGN_DEFINED) {
1139 if (sec->vstart & (sec->valign - 1))
1140 nasm_error(ERR_NONFATAL, "`vstart' address conflicts"
1141 " with `valign' value");
1142 sec->flags ^= VALIGN_DEFINED;
1145 continue;
1147 /* Handle follows attribute. */
1148 case ATTRIB_FOLLOWS:
1149 p = astring;
1150 astring += strcspn(astring, " \t");
1151 if (astring == p)
1152 nasm_error(ERR_NONFATAL, "expecting section name for `follows'"
1153 " attribute");
1154 else {
1155 *(astring++) = '\0';
1156 if (sec->flags & START_DEFINED)
1157 nasm_error(ERR_NONFATAL,
1158 "cannot combine `start' and `follows'"
1159 " section attributes");
1160 sec->follows = nasm_strdup(p);
1161 sec->flags |= FOLLOWS_DEFINED;
1163 continue;
1165 /* Handle vfollows attribute. */
1166 case ATTRIB_VFOLLOWS:
1167 if (sec->flags & VSTART_DEFINED)
1168 nasm_error(ERR_NONFATAL,
1169 "cannot combine `vstart' and `vfollows'"
1170 " section attributes");
1171 else {
1172 p = astring;
1173 astring += strcspn(astring, " \t");
1174 if (astring == p)
1175 nasm_error(ERR_NONFATAL,
1176 "expecting section name for `vfollows'"
1177 " attribute");
1178 else {
1179 *(astring++) = '\0';
1180 sec->vfollows = nasm_strdup(p);
1181 sec->flags |= VFOLLOWS_DEFINED;
1184 continue;
1189 static void bin_define_section_labels(void)
1191 static int labels_defined = 0;
1192 struct Section *sec;
1193 char *label_name;
1194 size_t base_len;
1196 if (labels_defined)
1197 return;
1198 list_for_each(sec, sections) {
1199 base_len = strlen(sec->name) + 8;
1200 label_name = nasm_malloc(base_len + 8);
1201 strcpy(label_name, "section.");
1202 strcpy(label_name + 8, sec->name);
1204 /* section.<name>.start */
1205 strcpy(label_name + base_len, ".start");
1206 define_label(label_name, sec->start_index, 0L, NULL, 0, 0);
1208 /* section.<name>.vstart */
1209 strcpy(label_name + base_len, ".vstart");
1210 define_label(label_name, sec->vstart_index, 0L, NULL, 0, 0);
1212 nasm_free(label_name);
1214 labels_defined = 1;
1217 static int32_t bin_secname(char *name, int pass, int *bits)
1219 char *p;
1220 struct Section *sec;
1222 /* bin_secname is called with *name = NULL at the start of each
1223 * pass. Use this opportunity to establish the default section
1224 * (default is BITS-16 ".text" segment).
1226 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1227 origin_defined = 0;
1228 list_for_each(sec, sections)
1229 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1230 ALIGN_DEFINED | VALIGN_DEFINED);
1232 /* Define section start and vstart labels. */
1233 if (format_mode && (pass != 1))
1234 bin_define_section_labels();
1236 /* Establish the default (.text) section. */
1237 *bits = 16;
1238 sec = find_section_by_name(".text");
1239 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1240 current_section = sec->vstart_index;
1241 return current_section;
1244 /* Attempt to find the requested section. If it does not
1245 * exist, create it. */
1246 p = name;
1247 while (*p && !nasm_isspace(*p))
1248 p++;
1249 if (*p)
1250 *p++ = '\0';
1251 sec = find_section_by_name(name);
1252 if (!sec) {
1253 sec = create_section(name);
1254 if (!strcmp(name, ".data"))
1255 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1256 else if (!strcmp(name, ".bss")) {
1257 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1258 sec->ifollows = NULL;
1259 } else if (!format_mode) {
1260 nasm_error(ERR_NONFATAL, "section name must be "
1261 ".text, .data, or .bss");
1262 return current_section;
1266 /* Handle attribute assignments. */
1267 if (pass != 1)
1268 bin_assign_attributes(sec, p);
1270 #ifndef ABIN_SMART_ADAPT
1271 /* The following line disables smart adaptation of
1272 * PROGBITS/NOBITS section types (it forces sections to
1273 * default to PROGBITS). */
1274 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1275 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1276 #endif
1278 /* Set the current section and return. */
1279 current_section = sec->vstart_index;
1280 return current_section;
1283 static int bin_directive(enum directives directive, char *args, int pass)
1285 switch (directive) {
1286 case D_ORG:
1288 struct tokenval tokval;
1289 uint64_t value;
1290 expr *e;
1292 stdscan_reset();
1293 stdscan_set(args);
1294 tokval.t_type = TOKEN_INVALID;
1295 e = evaluate(stdscan, NULL, &tokval, NULL, 1, nasm_error, NULL);
1296 if (e) {
1297 if (!is_really_simple(e))
1298 nasm_error(ERR_NONFATAL, "org value must be a critical"
1299 " expression");
1300 else {
1301 value = reloc_value(e);
1302 /* Check for ORG redefinition. */
1303 if (origin_defined && (value != origin))
1304 nasm_error(ERR_NONFATAL, "program origin redefined");
1305 else {
1306 origin = value;
1307 origin_defined = 1;
1310 } else
1311 nasm_error(ERR_NONFATAL, "No or invalid offset specified"
1312 " in ORG directive.");
1313 return 1;
1315 case D_MAP:
1317 /* The 'map' directive allows the user to generate section
1318 * and symbol information to stdout, stderr, or to a file. */
1319 char *p;
1321 if (pass != 1)
1322 return 1;
1323 args += strspn(args, " \t");
1324 while (*args) {
1325 p = args;
1326 args += strcspn(args, " \t");
1327 if (*args != '\0')
1328 *(args++) = '\0';
1329 if (!nasm_stricmp(p, "all"))
1330 map_control |=
1331 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1332 else if (!nasm_stricmp(p, "brief"))
1333 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1334 else if (!nasm_stricmp(p, "sections"))
1335 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1336 else if (!nasm_stricmp(p, "segments"))
1337 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1338 else if (!nasm_stricmp(p, "symbols"))
1339 map_control |= MAP_SYMBOLS;
1340 else if (!rf) {
1341 if (!nasm_stricmp(p, "stdout"))
1342 rf = stdout;
1343 else if (!nasm_stricmp(p, "stderr"))
1344 rf = stderr;
1345 else { /* Must be a filename. */
1346 rf = fopen(p, "wt");
1347 if (!rf) {
1348 nasm_error(ERR_WARNING, "unable to open map file `%s'",
1350 map_control = 0;
1351 return 1;
1354 } else
1355 nasm_error(ERR_WARNING, "map file already specified");
1357 if (map_control == 0)
1358 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1359 if (!rf)
1360 rf = stdout;
1361 return 1;
1363 default:
1364 return 0;
1368 static void bin_filename(char *inname, char *outname)
1370 standard_extension(inname, outname, "");
1371 infile = inname;
1372 outfile = outname;
1375 static void ith_filename(char *inname, char *outname)
1377 standard_extension(inname, outname, ".ith");
1378 infile = inname;
1379 outfile = outname;
1382 static void srec_filename(char *inname, char *outname)
1384 standard_extension(inname, outname, ".srec");
1385 infile = inname;
1386 outfile = outname;
1389 static int32_t bin_segbase(int32_t segment)
1391 return segment;
1394 static int bin_set_info(enum geninfo type, char **val)
1396 (void)type;
1397 (void)val;
1398 return 0;
1401 struct ofmt of_bin, of_ith, of_srec;
1402 static void binfmt_init(void);
1403 static void do_output_bin(void);
1404 static void do_output_ith(void);
1405 static void do_output_srec(void);
1407 static void bin_init(void)
1409 do_output = do_output_bin;
1410 binfmt_init();
1413 static void ith_init(void)
1415 do_output = do_output_ith;
1416 binfmt_init();
1419 static void srec_init(void)
1421 do_output = do_output_srec;
1422 binfmt_init();
1425 static void binfmt_init(void)
1427 maxbits = 64; /* Support 64-bit Segments */
1428 relocs = NULL;
1429 reloctail = &relocs;
1430 origin_defined = 0;
1431 no_seg_labels = NULL;
1432 nsl_tail = &no_seg_labels;
1433 format_mode = 1; /* Extended bin format
1434 * (set this to zero for old bin format). */
1436 /* Create default section (.text). */
1437 sections = last_section = nasm_malloc(sizeof(struct Section));
1438 last_section->next = NULL;
1439 last_section->name = nasm_strdup(".text");
1440 last_section->contents = saa_init(1L);
1441 last_section->follows = last_section->vfollows = 0;
1442 last_section->ifollows = NULL;
1443 last_section->length = 0;
1444 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1445 last_section->labels = NULL;
1446 last_section->labels_end = &(last_section->labels);
1447 last_section->start_index = seg_alloc();
1448 last_section->vstart_index = current_section = seg_alloc();
1451 /* Generate binary file output */
1452 static void do_output_bin(void)
1454 struct Section *s;
1455 uint64_t addr = origin;
1457 /* Write the progbits sections to the output file. */
1458 list_for_each(s, sections) {
1459 /* Skip non-progbits sections */
1460 if (!(s->flags & TYPE_PROGBITS))
1461 continue;
1462 /* Skip zero-length sections */
1463 if (s->length == 0)
1464 continue;
1466 /* Pad the space between sections. */
1467 nasm_assert(addr <= s->start);
1468 fwritezero(s->start - addr, ofile);
1470 /* Write the section to the output file. */
1471 saa_fpwrite(s->contents, ofile);
1473 /* Keep track of the current file position */
1474 addr = s->start + s->length;
1478 /* Generate Intel hex file output */
1479 static int write_ith_record(unsigned int len, uint16_t addr,
1480 uint8_t type, void *data)
1482 char buf[1+2+4+2+255*2+2+2];
1483 char *p = buf;
1484 uint8_t csum, *dptr = data;
1485 unsigned int i;
1487 nasm_assert(len <= 255);
1489 csum = len + addr + (addr >> 8) + type;
1490 for (i = 0; i < len; i++)
1491 csum += dptr[i];
1492 csum = -csum;
1494 p += sprintf(p, ":%02X%04X%02X", len, addr, type);
1495 for (i = 0; i < len; i++)
1496 p += sprintf(p, "%02X", dptr[i]);
1497 p += sprintf(p, "%02X\n", csum);
1499 if (fwrite(buf, 1, p-buf, ofile) != (size_t)(p-buf))
1500 return -1;
1502 return 0;
1505 static void do_output_ith(void)
1507 uint8_t buf[32];
1508 struct Section *s;
1509 uint64_t addr, hiaddr, hilba;
1510 uint64_t length;
1511 unsigned int chunk;
1513 /* Write the progbits sections to the output file. */
1514 hilba = 0;
1515 list_for_each(s, sections) {
1516 /* Skip non-progbits sections */
1517 if (!(s->flags & TYPE_PROGBITS))
1518 continue;
1519 /* Skip zero-length sections */
1520 if (s->length == 0)
1521 continue;
1523 addr = s->start;
1524 length = s->length;
1525 saa_rewind(s->contents);
1527 while (length) {
1528 hiaddr = addr >> 16;
1529 if (hiaddr != hilba) {
1530 buf[0] = hiaddr >> 8;
1531 buf[1] = hiaddr;
1532 write_ith_record(2, 0, 4, buf);
1533 hilba = hiaddr;
1536 chunk = 32 - (addr & 31);
1537 if (length < chunk)
1538 chunk = length;
1540 saa_rnbytes(s->contents, buf, chunk);
1541 write_ith_record(chunk, (uint16_t)addr, 0, buf);
1543 addr += chunk;
1544 length -= chunk;
1548 /* Write closing record */
1549 write_ith_record(0, 0, 1, NULL);
1552 /* Generate Motorola S-records */
1553 static int write_srecord(unsigned int len, unsigned int alen,
1554 uint32_t addr, uint8_t type, void *data)
1556 char buf[2+2+8+255*2+2+2];
1557 char *p = buf;
1558 uint8_t csum, *dptr = data;
1559 unsigned int i;
1561 nasm_assert(len <= 255);
1563 switch (alen) {
1564 case 2:
1565 addr &= 0xffff;
1566 break;
1567 case 3:
1568 addr &= 0xffffff;
1569 break;
1570 case 4:
1571 break;
1572 default:
1573 nasm_assert(0);
1574 break;
1577 csum = (len+alen+1) + addr + (addr >> 8) + (addr >> 16) + (addr >> 24);
1578 for (i = 0; i < len; i++)
1579 csum += dptr[i];
1580 csum = 0xff-csum;
1582 p += sprintf(p, "S%c%02X%0*X", type, len+alen+1, alen*2, addr);
1583 for (i = 0; i < len; i++)
1584 p += sprintf(p, "%02X", dptr[i]);
1585 p += sprintf(p, "%02X\n", csum);
1587 if (fwrite(buf, 1, p-buf, ofile) != (size_t)(p-buf))
1588 return -1;
1590 return 0;
1593 static void do_output_srec(void)
1595 uint8_t buf[32];
1596 struct Section *s;
1597 uint64_t addr, maxaddr;
1598 uint64_t length;
1599 int alen;
1600 unsigned int chunk;
1601 char dtype, etype;
1603 maxaddr = 0;
1604 list_for_each(s, sections) {
1605 /* Skip non-progbits sections */
1606 if (!(s->flags & TYPE_PROGBITS))
1607 continue;
1608 /* Skip zero-length sections */
1609 if (s->length == 0)
1610 continue;
1612 addr = s->start + s->length - 1;
1613 if (addr > maxaddr)
1614 maxaddr = addr;
1617 if (maxaddr <= 0xffff) {
1618 alen = 2;
1619 dtype = '1'; /* S1 = 16-bit data */
1620 etype = '9'; /* S9 = 16-bit end */
1621 } else if (maxaddr <= 0xffffff) {
1622 alen = 3;
1623 dtype = '2'; /* S2 = 24-bit data */
1624 etype = '8'; /* S8 = 24-bit end */
1625 } else {
1626 alen = 4;
1627 dtype = '3'; /* S3 = 32-bit data */
1628 etype = '7'; /* S7 = 32-bit end */
1631 /* Write head record */
1632 write_srecord(0, 2, 0, '0', NULL);
1634 /* Write the progbits sections to the output file. */
1635 list_for_each(s, sections) {
1636 /* Skip non-progbits sections */
1637 if (!(s->flags & TYPE_PROGBITS))
1638 continue;
1639 /* Skip zero-length sections */
1640 if (s->length == 0)
1641 continue;
1643 addr = s->start;
1644 length = s->length;
1645 saa_rewind(s->contents);
1647 while (length) {
1648 chunk = 32 - (addr & 31);
1649 if (length < chunk)
1650 chunk = length;
1652 saa_rnbytes(s->contents, buf, chunk);
1653 write_srecord(chunk, alen, (uint32_t)addr, dtype, buf);
1655 addr += chunk;
1656 length -= chunk;
1660 /* Write closing record */
1661 write_srecord(0, alen, 0, etype, NULL);
1665 struct ofmt of_bin = {
1666 "flat-form binary files (e.g. DOS .COM, .SYS)",
1667 "bin",
1669 null_debug_arr,
1670 &null_debug_form,
1671 bin_stdmac,
1672 bin_init,
1673 bin_set_info,
1674 bin_out,
1675 bin_deflabel,
1676 bin_secname,
1677 bin_segbase,
1678 bin_directive,
1679 bin_filename,
1680 bin_cleanup
1683 struct ofmt of_ith = {
1684 "Intel hex",
1685 "ith",
1686 OFMT_TEXT,
1687 null_debug_arr,
1688 &null_debug_form,
1689 bin_stdmac,
1690 ith_init,
1691 bin_set_info,
1692 bin_out,
1693 bin_deflabel,
1694 bin_secname,
1695 bin_segbase,
1696 bin_directive,
1697 ith_filename,
1698 bin_cleanup
1701 struct ofmt of_srec = {
1702 "Motorola S-records",
1703 "srec",
1705 null_debug_arr,
1706 &null_debug_form,
1707 bin_stdmac,
1708 srec_init,
1709 bin_set_info,
1710 bin_out,
1711 bin_deflabel,
1712 bin_secname,
1713 bin_segbase,
1714 bin_directive,
1715 srec_filename,
1716 bin_cleanup
1719 #endif /* #ifdef OF_BIN */