NASM 2.10rc3
[nasm/avx512.git] / output / outbin.c
blob4012cc9c7e65a073bf05ed8be4e8fbd37fe141d7
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 uint64_t origin;
156 static int origin_defined;
158 /* Stuff we need for map-file generation. */
159 #define MAP_ORIGIN 1
160 #define MAP_SUMMARY 2
161 #define MAP_SECTIONS 4
162 #define MAP_SYMBOLS 8
163 static int map_control = 0;
164 static char *infile, *outfile;
166 extern macros_t bin_stdmac[];
168 static void add_reloc(struct Section *s, int32_t bytes, int32_t secref,
169 int32_t secrel)
171 struct Reloc *r;
173 r = *reloctail = nasm_malloc(sizeof(struct Reloc));
174 reloctail = &r->next;
175 r->next = NULL;
176 r->posn = s->length;
177 r->bytes = bytes;
178 r->secref = secref;
179 r->secrel = secrel;
180 r->target = s;
183 static struct Section *find_section_by_name(const char *name)
185 struct Section *s;
187 list_for_each(s, sections)
188 if (!strcmp(s->name, name))
189 break;
190 return s;
193 static struct Section *find_section_by_index(int32_t index)
195 struct Section *s;
197 list_for_each(s, sections)
198 if ((index == s->vstart_index) || (index == s->start_index))
199 break;
200 return s;
203 static struct Section *create_section(char *name)
204 { /* Create a new section. */
205 last_section->next = nasm_malloc(sizeof(struct Section));
206 last_section->next->ifollows = last_section;
207 last_section = last_section->next;
208 last_section->labels = NULL;
209 last_section->labels_end = &(last_section->labels);
211 /* Initialize section attributes. */
212 last_section->name = nasm_strdup(name);
213 last_section->contents = saa_init(1L);
214 last_section->follows = last_section->vfollows = 0;
215 last_section->length = 0;
216 last_section->flags = 0;
217 last_section->next = NULL;
219 /* Register our sections with NASM. */
220 last_section->vstart_index = seg_alloc();
221 last_section->start_index = seg_alloc();
222 return last_section;
225 static void bin_cleanup(int debuginfo)
227 struct Section *g, **gp;
228 struct Section *gs = NULL, **gsp;
229 struct Section *s, **sp;
230 struct Section *nobits = NULL, **nt;
231 struct Section *last_progbits;
232 struct bin_label *l;
233 struct Reloc *r;
234 uint64_t pend;
235 int h;
237 (void)debuginfo; /* placate optimizers */
239 #ifdef DEBUG
240 nasm_error(ERR_DEBUG,
241 "bin_cleanup: Sections were initially referenced in this order:\n");
242 for (h = 0, s = sections; s; h++, s = s->next)
243 fprintf(stdout, "%i. %s\n", h, s->name);
244 #endif
246 /* Assembly has completed, so now we need to generate the output file.
247 * Step 1: Separate progbits and nobits sections into separate lists.
248 * Step 2: Sort the progbits sections into their output order.
249 * Step 3: Compute start addresses for all progbits sections.
250 * Step 4: Compute vstart addresses for all sections.
251 * Step 5: Apply relocations.
252 * Step 6: Write the sections' data to the output file.
253 * Step 7: Generate the map file.
254 * Step 8: Release all allocated memory.
257 /* To do: Smart section-type adaptation could leave some empty sections
258 * without a defined type (progbits/nobits). Won't fix now since this
259 * feature will be disabled. */
261 /* Step 1: Split progbits and nobits sections into separate lists. */
263 nt = &nobits;
264 /* Move nobits sections into a separate list. Also pre-process nobits
265 * sections' attributes. */
266 for (sp = &sections->next, s = sections->next; s; s = *sp) { /* Skip progbits sections. */
267 if (s->flags & TYPE_PROGBITS) {
268 sp = &s->next;
269 continue;
271 /* Do some special pre-processing on nobits sections' attributes. */
272 if (s->flags & (START_DEFINED | ALIGN_DEFINED | FOLLOWS_DEFINED)) { /* Check for a mixture of real and virtual section attributes. */
273 if (s->flags & (VSTART_DEFINED | VALIGN_DEFINED |
274 VFOLLOWS_DEFINED))
275 nasm_error(ERR_FATAL|ERR_NOFILE,
276 "cannot mix real and virtual attributes"
277 " in nobits section (%s)", s->name);
278 /* Real and virtual attributes mean the same thing for nobits sections. */
279 if (s->flags & START_DEFINED) {
280 s->vstart = s->start;
281 s->flags |= VSTART_DEFINED;
283 if (s->flags & ALIGN_DEFINED) {
284 s->valign = s->align;
285 s->flags |= VALIGN_DEFINED;
287 if (s->flags & FOLLOWS_DEFINED) {
288 s->vfollows = s->follows;
289 s->flags |= VFOLLOWS_DEFINED;
290 s->flags &= ~FOLLOWS_DEFINED;
293 /* Every section must have a start address. */
294 if (s->flags & VSTART_DEFINED) {
295 s->start = s->vstart;
296 s->flags |= START_DEFINED;
298 /* Move the section into the nobits list. */
299 *sp = s->next;
300 s->next = NULL;
301 *nt = s;
302 nt = &s->next;
305 /* Step 2: Sort the progbits sections into their output order. */
307 /* In Step 2 we move around sections in groups. A group
308 * begins with a section (group leader) that has a user-
309 * defined start address or follows section. The remainder
310 * of the group is made up of the sections that implicitly
311 * follow the group leader (i.e., they were defined after
312 * the group leader and were not given an explicit start
313 * address or follows section by the user). */
315 /* For anyone attempting to read this code:
316 * g (group) points to a group of sections, the first one of which has
317 * a user-defined start address or follows section.
318 * gp (g previous) holds the location of the pointer to g.
319 * gs (g scan) is a temp variable that we use to scan to the end of the group.
320 * gsp (gs previous) holds the location of the pointer to gs.
321 * nt (nobits tail) points to the nobits section-list tail.
324 /* Link all 'follows' groups to their proper position. To do
325 * this we need to know three things: the start of the group
326 * to relocate (g), the section it is following (s), and the
327 * end of the group we're relocating (gs). */
328 for (gp = &sections, g = sections; g; g = gs) { /* Find the next follows group that is out of place (g). */
329 if (!(g->flags & FOLLOWS_DEFINED)) {
330 while (g->next) {
331 if ((g->next->flags & FOLLOWS_DEFINED) &&
332 strcmp(g->name, g->next->follows))
333 break;
334 g = g->next;
336 if (!g->next)
337 break;
338 gp = &g->next;
339 g = g->next;
341 /* Find the section that this group follows (s). */
342 for (sp = &sections, s = sections;
343 s && strcmp(s->name, g->follows);
344 sp = &s->next, s = s->next) ;
345 if (!s)
346 nasm_error(ERR_FATAL|ERR_NOFILE, "section %s follows an invalid or"
347 " unknown section (%s)", g->name, g->follows);
348 if (s->next && (s->next->flags & FOLLOWS_DEFINED) &&
349 !strcmp(s->name, s->next->follows))
350 nasm_error(ERR_FATAL|ERR_NOFILE, "sections %s and %s can't both follow"
351 " section %s", g->name, s->next->name, s->name);
352 /* Find the end of the current follows group (gs). */
353 for (gsp = &g->next, gs = g->next;
354 gs && (gs != s) && !(gs->flags & START_DEFINED);
355 gsp = &gs->next, gs = gs->next) {
356 if (gs->next && (gs->next->flags & FOLLOWS_DEFINED) &&
357 strcmp(gs->name, gs->next->follows)) {
358 gsp = &gs->next;
359 gs = gs->next;
360 break;
363 /* Re-link the group after its follows section. */
364 *gsp = s->next;
365 s->next = g;
366 *gp = gs;
369 /* Link all 'start' groups to their proper position. Once
370 * again we need to know g, s, and gs (see above). The main
371 * difference is we already know g since we sort by moving
372 * groups from the 'unsorted' list into a 'sorted' list (g
373 * will always be the first section in the unsorted list). */
374 for (g = sections, sections = NULL; g; g = gs) { /* Find the section that we will insert this group before (s). */
375 for (sp = &sections, s = sections; s; sp = &s->next, s = s->next)
376 if ((s->flags & START_DEFINED) && (g->start < s->start))
377 break;
378 /* Find the end of the group (gs). */
379 for (gs = g->next, gsp = &g->next;
380 gs && !(gs->flags & START_DEFINED);
381 gsp = &gs->next, gs = gs->next) ;
382 /* Re-link the group before the target section. */
383 *sp = g;
384 *gsp = s;
387 /* Step 3: Compute start addresses for all progbits sections. */
389 /* Make sure we have an origin and a start address for the first section. */
390 if (origin_defined) {
391 if (sections->flags & START_DEFINED) {
392 /* Make sure this section doesn't begin before the origin. */
393 if (sections->start < origin)
394 nasm_error(ERR_FATAL|ERR_NOFILE, "section %s begins"
395 " before program origin", sections->name);
396 } else if (sections->flags & ALIGN_DEFINED) {
397 sections->start = ALIGN(origin, sections->align);
398 } else {
399 sections->start = origin;
401 } else {
402 if (!(sections->flags & START_DEFINED))
403 sections->start = 0;
404 origin = sections->start;
406 sections->flags |= START_DEFINED;
408 /* Make sure each section has an explicit start address. If it
409 * doesn't, then compute one based its alignment and the end of
410 * the previous section. */
411 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
412 * (has a defined start address, and is not zero length). */
413 if (g == s)
414 for (s = g->next;
415 s && ((s->length == 0) || !(s->flags & START_DEFINED));
416 s = s->next) ;
417 /* Compute the start address of this section, if necessary. */
418 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
419 if (!(g->flags & ALIGN_DEFINED)) {
420 g->align = 4;
421 g->flags |= ALIGN_DEFINED;
423 /* Set the section start address. */
424 g->start = ALIGN(pend, g->align);
425 g->flags |= START_DEFINED;
427 /* Ugly special case for progbits sections' virtual attributes:
428 * If there is a defined valign, but no vstart and no vfollows, then
429 * we valign after the previous progbits section. This case doesn't
430 * really make much sense for progbits sections with a defined start
431 * address, but it is possible and we must do *something*.
432 * Not-so-ugly special case:
433 * If a progbits section has no virtual attributes, we set the
434 * vstart equal to the start address. */
435 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
436 if (g->flags & VALIGN_DEFINED)
437 g->vstart = ALIGN(pend, g->valign);
438 else
439 g->vstart = g->start;
440 g->flags |= VSTART_DEFINED;
442 /* Ignore zero-length sections. */
443 if (g->start < pend)
444 continue;
445 /* Compute the span of this section. */
446 pend = g->start + g->length;
447 /* Check for section overlap. */
448 if (s) {
449 if (s->start < origin)
450 nasm_error(ERR_FATAL|ERR_NOFILE, "section %s beings before program origin",
451 s->name);
452 if (g->start > s->start)
453 nasm_error(ERR_FATAL|ERR_NOFILE, "sections %s ~ %s and %s overlap!",
454 gs->name, g->name, s->name);
455 if (pend > s->start)
456 nasm_error(ERR_FATAL|ERR_NOFILE, "sections %s and %s overlap!",
457 g->name, s->name);
459 /* Remember this section as the latest >0 length section. */
460 gs = g;
463 /* Step 4: Compute vstart addresses for all sections. */
465 /* Attach the nobits sections to the end of the progbits sections. */
466 for (s = sections; s->next; s = s->next) ;
467 s->next = nobits;
468 last_progbits = s;
470 * Scan for sections that don't have a vstart address. If we find
471 * one we'll attempt to compute its vstart. If we can't compute
472 * the vstart, we leave it alone and come back to it in a
473 * subsequent scan. We continue scanning and re-scanning until
474 * we've gone one full cycle without computing any vstarts.
476 do { /* Do one full scan of the sections list. */
477 for (h = 0, g = sections; g; g = g->next) {
478 if (g->flags & VSTART_DEFINED)
479 continue;
480 /* Find the section that this one virtually follows. */
481 if (g->flags & VFOLLOWS_DEFINED) {
482 for (s = sections; s && strcmp(g->vfollows, s->name);
483 s = s->next) ;
484 if (!s)
485 nasm_error(ERR_FATAL|ERR_NOFILE,
486 "section %s vfollows unknown section (%s)",
487 g->name, g->vfollows);
488 } else if (g->ifollows != NULL)
489 for (s = sections; s && (s != g->ifollows); s = s->next) ;
490 /* The .bss section is the only one with ifollows = NULL.
491 In this case we implicitly follow the last progbits
492 section. */
493 else
494 s = last_progbits;
496 /* If the section we're following has a vstart, we can proceed. */
497 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
498 if (!(g->flags & VALIGN_DEFINED)) {
499 g->valign = 4;
500 g->flags |= VALIGN_DEFINED;
502 /* Compute the vstart address. */
503 g->vstart = ALIGN(s->vstart + s->length, g->valign);
504 g->flags |= VSTART_DEFINED;
505 h++;
506 /* Start and vstart mean the same thing for nobits sections. */
507 if (g->flags & TYPE_NOBITS)
508 g->start = g->vstart;
511 } while (h);
513 /* Now check for any circular vfollows references, which will manifest
514 * themselves as sections without a defined vstart. */
515 for (h = 0, s = sections; s; s = s->next) {
516 if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
517 * no-no, but we'll throw a fatal one eventually so it's ok. */
518 nasm_error(ERR_NONFATAL, "cannot compute vstart for section %s",
519 s->name);
520 h++;
523 if (h)
524 nasm_error(ERR_FATAL|ERR_NOFILE, "circular vfollows path detected");
526 #ifdef DEBUG
527 nasm_error(ERR_DEBUG,
528 "bin_cleanup: Confirm final section order for output file:\n");
529 for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
530 h++, s = s->next)
531 fprintf(stdout, "%i. %s\n", h, s->name);
532 #endif
534 /* Step 5: Apply relocations. */
536 /* Prepare the sections for relocating. */
537 list_for_each(s, sections)
538 saa_rewind(s->contents);
539 /* Apply relocations. */
540 list_for_each(r, relocs) {
541 uint8_t *p, mydata[8];
542 int64_t l;
543 int b;
545 nasm_assert(r->bytes <= 8);
547 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
548 p = mydata;
549 l = 0;
550 for (b = r->bytes - 1; b >= 0; b--)
551 l = (l << 8) + mydata[b];
553 s = find_section_by_index(r->secref);
554 if (s) {
555 if (r->secref == s->start_index)
556 l += s->start;
557 else
558 l += s->vstart;
560 s = find_section_by_index(r->secrel);
561 if (s) {
562 if (r->secrel == s->start_index)
563 l -= s->start;
564 else
565 l -= s->vstart;
568 WRITEADDR(p, l, r->bytes);
569 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
572 /* Step 6: Write the section data to the output file. */
573 do_output();
575 /* Step 7: Generate the map file. */
577 if (map_control) {
578 static const char not_defined[] = "not defined";
580 /* Display input and output file names. */
581 fprintf(rf, "\n- NASM Map file ");
582 for (h = 63; h; h--)
583 fputc('-', rf);
584 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
585 infile, outfile);
587 if (map_control & MAP_ORIGIN) { /* Display program origin. */
588 fprintf(rf, "-- Program origin ");
589 for (h = 61; h; h--)
590 fputc('-', rf);
591 fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
593 /* Display sections summary. */
594 if (map_control & MAP_SUMMARY) {
595 fprintf(rf, "-- Sections (summary) ");
596 for (h = 57; h; h--)
597 fputc('-', rf);
598 fprintf(rf, "\n\nVstart Start Stop "
599 "Length Class Name\n");
600 list_for_each(s, sections) {
601 fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
602 s->vstart, s->start, s->start + s->length,
603 s->length);
604 if (s->flags & TYPE_PROGBITS)
605 fprintf(rf, "progbits ");
606 else
607 fprintf(rf, "nobits ");
608 fprintf(rf, "%s\n", s->name);
610 fprintf(rf, "\n");
612 /* Display detailed section information. */
613 if (map_control & MAP_SECTIONS) {
614 fprintf(rf, "-- Sections (detailed) ");
615 for (h = 56; h; h--)
616 fputc('-', rf);
617 fprintf(rf, "\n\n");
618 list_for_each(s, sections) {
619 fprintf(rf, "---- Section %s ", s->name);
620 for (h = 65 - strlen(s->name); h; h--)
621 fputc('-', rf);
622 fprintf(rf, "\n\nclass: ");
623 if (s->flags & TYPE_PROGBITS)
624 fprintf(rf, "progbits");
625 else
626 fprintf(rf, "nobits");
627 fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
628 "\nalign: ", s->length, s->start);
629 if (s->flags & ALIGN_DEFINED)
630 fprintf(rf, "%16"PRIX64"", s->align);
631 else
632 fputs(not_defined, rf);
633 fprintf(rf, "\nfollows: ");
634 if (s->flags & FOLLOWS_DEFINED)
635 fprintf(rf, "%s", s->follows);
636 else
637 fputs(not_defined, rf);
638 fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
639 if (s->flags & VALIGN_DEFINED)
640 fprintf(rf, "%16"PRIX64"", s->valign);
641 else
642 fputs(not_defined, rf);
643 fprintf(rf, "\nvfollows: ");
644 if (s->flags & VFOLLOWS_DEFINED)
645 fprintf(rf, "%s", s->vfollows);
646 else
647 fputs(not_defined, rf);
648 fprintf(rf, "\n\n");
651 /* Display symbols information. */
652 if (map_control & MAP_SYMBOLS) {
653 int32_t segment;
654 int64_t offset;
656 fprintf(rf, "-- Symbols ");
657 for (h = 68; h; h--)
658 fputc('-', rf);
659 fprintf(rf, "\n\n");
660 if (no_seg_labels) {
661 fprintf(rf, "---- No Section ");
662 for (h = 63; h; h--)
663 fputc('-', rf);
664 fprintf(rf, "\n\nValue Name\n");
665 list_for_each(l, no_seg_labels) {
666 lookup_label(l->name, &segment, &offset);
667 fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
669 fprintf(rf, "\n\n");
671 list_for_each(s, sections) {
672 if (s->labels) {
673 fprintf(rf, "---- Section %s ", s->name);
674 for (h = 65 - strlen(s->name); h; h--)
675 fputc('-', rf);
676 fprintf(rf, "\n\nReal Virtual Name\n");
677 list_for_each(l, s->labels) {
678 lookup_label(l->name, &segment, &offset);
679 fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
680 s->start + offset, s->vstart + offset,
681 l->name);
683 fprintf(rf, "\n");
689 /* Close the report file. */
690 if (map_control && (rf != stdout) && (rf != stderr))
691 fclose(rf);
693 /* Step 8: Release all allocated memory. */
695 /* Free sections, label pointer structs, etc.. */
696 while (sections) {
697 s = sections;
698 sections = s->next;
699 saa_free(s->contents);
700 nasm_free(s->name);
701 if (s->flags & FOLLOWS_DEFINED)
702 nasm_free(s->follows);
703 if (s->flags & VFOLLOWS_DEFINED)
704 nasm_free(s->vfollows);
705 while (s->labels) {
706 l = s->labels;
707 s->labels = l->next;
708 nasm_free(l);
710 nasm_free(s);
713 /* Free no-section labels. */
714 while (no_seg_labels) {
715 l = no_seg_labels;
716 no_seg_labels = l->next;
717 nasm_free(l);
720 /* Free relocation structures. */
721 while (relocs) {
722 r = relocs->next;
723 nasm_free(relocs);
724 relocs = r;
728 static void bin_out(int32_t segto, const void *data,
729 enum out_type type, uint64_t size,
730 int32_t segment, int32_t wrt)
732 uint8_t *p, mydata[8];
733 struct Section *s;
735 if (wrt != NO_SEG) {
736 wrt = NO_SEG; /* continue to do _something_ */
737 nasm_error(ERR_NONFATAL, "WRT not supported by binary output format");
740 /* Handle absolute-assembly (structure definitions). */
741 if (segto == NO_SEG) {
742 if (type != OUT_RESERVE)
743 nasm_error(ERR_NONFATAL, "attempt to assemble code in"
744 " [ABSOLUTE] space");
745 return;
748 /* Find the segment we are targeting. */
749 s = find_section_by_index(segto);
750 if (!s)
751 nasm_error(ERR_PANIC, "code directed to nonexistent segment?");
753 /* "Smart" section-type adaptation code. */
754 if (!(s->flags & TYPE_DEFINED)) {
755 if (type == OUT_RESERVE)
756 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
757 else
758 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
761 if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
762 nasm_error(ERR_WARNING, "attempt to initialize memory in a"
763 " nobits section: ignored");
765 switch (type) {
766 case OUT_ADDRESS:
767 if (segment != NO_SEG && !find_section_by_index(segment)) {
768 if (segment % 2)
769 nasm_error(ERR_NONFATAL, "binary output format does not support"
770 " segment base references");
771 else
772 nasm_error(ERR_NONFATAL, "binary output format does not support"
773 " external references");
774 segment = NO_SEG;
776 if (s->flags & TYPE_PROGBITS) {
777 if (segment != NO_SEG)
778 add_reloc(s, size, segment, -1L);
779 p = mydata;
780 WRITEADDR(p, *(int64_t *)data, size);
781 saa_wbytes(s->contents, mydata, size);
783 break;
785 case OUT_RAWDATA:
786 if (s->flags & TYPE_PROGBITS)
787 saa_wbytes(s->contents, data, size);
788 break;
790 case OUT_RESERVE:
791 if (s->flags & TYPE_PROGBITS) {
792 nasm_error(ERR_WARNING, "uninitialized space declared in"
793 " %s section: zeroing", s->name);
794 saa_wbytes(s->contents, NULL, size);
796 break;
798 case OUT_REL1ADR:
799 case OUT_REL2ADR:
800 case OUT_REL4ADR:
801 case OUT_REL8ADR:
803 int64_t addr = *(int64_t *)data - size;
804 size = realsize(type, size);
805 if (segment != NO_SEG && !find_section_by_index(segment)) {
806 if (segment % 2)
807 nasm_error(ERR_NONFATAL, "binary output format does not support"
808 " segment base references");
809 else
810 nasm_error(ERR_NONFATAL, "binary output format does not support"
811 " external references");
812 segment = NO_SEG;
814 if (s->flags & TYPE_PROGBITS) {
815 add_reloc(s, size, segment, segto);
816 p = mydata;
817 WRITEADDR(p, addr - s->length, size);
818 saa_wbytes(s->contents, mydata, size);
820 break;
823 default:
824 nasm_error(ERR_NONFATAL, "unsupported relocation type %d\n", type);
825 break;
828 s->length += size;
831 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
832 int is_global, char *special)
834 (void)segment; /* Don't warn that this parameter is unused */
835 (void)offset; /* Don't warn that this parameter is unused */
837 if (special)
838 nasm_error(ERR_NONFATAL, "binary format does not support any"
839 " special symbol types");
840 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
841 nasm_error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
842 else if (is_global == 2)
843 nasm_error(ERR_NONFATAL, "binary output format does not support common"
844 " variables");
845 else {
846 struct Section *s;
847 struct bin_label ***ltp;
849 /* Remember label definition so we can look it up later when
850 * creating the map file. */
851 s = find_section_by_index(segment);
852 if (s)
853 ltp = &(s->labels_end);
854 else
855 ltp = &nsl_tail;
856 (**ltp) = nasm_malloc(sizeof(struct bin_label));
857 (**ltp)->name = name;
858 (**ltp)->next = NULL;
859 *ltp = &((**ltp)->next);
864 /* These constants and the following function are used
865 * by bin_secname() to parse attribute assignments. */
867 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
868 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
869 ATTRIB_NOBITS, ATTRIB_PROGBITS
872 static int bin_read_attribute(char **line, int *attribute,
873 uint64_t *value)
875 expr *e;
876 int attrib_name_size;
877 struct tokenval tokval;
878 char *exp;
880 /* Skip whitespace. */
881 while (**line && nasm_isspace(**line))
882 (*line)++;
883 if (!**line)
884 return 0;
886 /* Figure out what attribute we're reading. */
887 if (!nasm_strnicmp(*line, "align=", 6)) {
888 *attribute = ATTRIB_ALIGN;
889 attrib_name_size = 6;
890 } else {
891 if (!nasm_strnicmp(*line, "start=", 6)) {
892 *attribute = ATTRIB_START;
893 attrib_name_size = 6;
894 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
895 *attribute = ATTRIB_FOLLOWS;
896 *line += 8;
897 return 1;
898 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
899 *attribute = ATTRIB_VSTART;
900 attrib_name_size = 7;
901 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
902 *attribute = ATTRIB_VALIGN;
903 attrib_name_size = 7;
904 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
905 *attribute = ATTRIB_VFOLLOWS;
906 *line += 9;
907 return 1;
908 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
909 (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
910 *attribute = ATTRIB_NOBITS;
911 *line += 6;
912 return 1;
913 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
914 (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
915 *attribute = ATTRIB_PROGBITS;
916 *line += 8;
917 return 1;
918 } else
919 return 0;
922 /* Find the end of the expression. */
923 if ((*line)[attrib_name_size] != '(') {
924 /* Single term (no parenthesis). */
925 exp = *line += attrib_name_size;
926 while (**line && !nasm_isspace(**line))
927 (*line)++;
928 if (**line) {
929 **line = '\0';
930 (*line)++;
932 } else {
933 char c;
934 int pcount = 1;
936 /* Full expression (delimited by parenthesis) */
937 exp = *line += attrib_name_size + 1;
938 while (1) {
939 (*line) += strcspn(*line, "()'\"");
940 if (**line == '(') {
941 ++(*line);
942 ++pcount;
944 if (**line == ')') {
945 ++(*line);
946 --pcount;
947 if (!pcount)
948 break;
950 if ((**line == '"') || (**line == '\'')) {
951 c = **line;
952 while (**line) {
953 ++(*line);
954 if (**line == c)
955 break;
957 if (!**line) {
958 nasm_error(ERR_NONFATAL,
959 "invalid syntax in `section' directive");
960 return -1;
962 ++(*line);
964 if (!**line) {
965 nasm_error(ERR_NONFATAL, "expecting `)'");
966 return -1;
969 *(*line - 1) = '\0'; /* Terminate the expression. */
972 /* Check for no value given. */
973 if (!*exp) {
974 nasm_error(ERR_WARNING, "No value given to attribute in"
975 " `section' directive");
976 return -1;
979 /* Read and evaluate the expression. */
980 stdscan_reset();
981 stdscan_set(exp);
982 tokval.t_type = TOKEN_INVALID;
983 e = evaluate(stdscan, NULL, &tokval, NULL, 1, nasm_error, NULL);
984 if (e) {
985 if (!is_really_simple(e)) {
986 nasm_error(ERR_NONFATAL, "section attribute value must be"
987 " a critical expression");
988 return -1;
990 } else {
991 nasm_error(ERR_NONFATAL, "Invalid attribute value"
992 " specified in `section' directive.");
993 return -1;
995 *value = (uint64_t)reloc_value(e);
996 return 1;
999 static void bin_sectalign(int32_t seg, unsigned int value)
1001 struct Section *s = find_section_by_index(seg);
1003 if (!s || !is_power2(value))
1004 return;
1006 if (value > s->align)
1007 s->align = value;
1009 if (!(s->flags & ALIGN_DEFINED))
1010 s->flags |= ALIGN_DEFINED;
1013 static void bin_assign_attributes(struct Section *sec, char *astring)
1015 int attribute, check;
1016 uint64_t value;
1017 char *p;
1019 while (1) { /* Get the next attribute. */
1020 check = bin_read_attribute(&astring, &attribute, &value);
1021 /* Skip bad attribute. */
1022 if (check == -1)
1023 continue;
1024 /* Unknown section attribute, so skip it and warn the user. */
1025 if (!check) {
1026 if (!*astring)
1027 break; /* End of line. */
1028 else {
1029 p = astring;
1030 while (*astring && !nasm_isspace(*astring))
1031 astring++;
1032 if (*astring) {
1033 *astring = '\0';
1034 astring++;
1036 nasm_error(ERR_WARNING, "ignoring unknown section attribute:"
1037 " \"%s\"", p);
1039 continue;
1042 switch (attribute) { /* Handle nobits attribute. */
1043 case ATTRIB_NOBITS:
1044 if ((sec->flags & TYPE_DEFINED)
1045 && (sec->flags & TYPE_PROGBITS))
1046 nasm_error(ERR_NONFATAL,
1047 "attempt to change section type"
1048 " from progbits to nobits");
1049 else
1050 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1051 continue;
1053 /* Handle progbits attribute. */
1054 case ATTRIB_PROGBITS:
1055 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1056 nasm_error(ERR_NONFATAL, "attempt to change section type"
1057 " from nobits to progbits");
1058 else
1059 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1060 continue;
1062 /* Handle align attribute. */
1063 case ATTRIB_ALIGN:
1064 if (!value || ((value - 1) & value)) {
1065 nasm_error(ERR_NONFATAL,
1066 "argument to `align' is not a power of two");
1067 } else {
1069 * Alignment is already satisfied if
1070 * the previous align value is greater
1072 if ((sec->flags & ALIGN_DEFINED) && (value < sec->align))
1073 value = sec->align;
1075 /* Don't allow a conflicting align value. */
1076 if ((sec->flags & START_DEFINED) && (sec->start & (value - 1))) {
1077 nasm_error(ERR_NONFATAL,
1078 "`align' value conflicts with section start address");
1079 } else {
1080 sec->align = value;
1081 sec->flags |= ALIGN_DEFINED;
1084 continue;
1086 /* Handle valign attribute. */
1087 case ATTRIB_VALIGN:
1088 if (!value || ((value - 1) & value))
1089 nasm_error(ERR_NONFATAL, "argument to `valign' is not a"
1090 " power of two");
1091 else { /* Alignment is already satisfied if the previous
1092 * align value is greater. */
1093 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1094 value = sec->valign;
1096 /* Don't allow a conflicting valign value. */
1097 if ((sec->flags & VSTART_DEFINED)
1098 && (sec->vstart & (value - 1)))
1099 nasm_error(ERR_NONFATAL,
1100 "`valign' value conflicts "
1101 "with `vstart' address");
1102 else {
1103 sec->valign = value;
1104 sec->flags |= VALIGN_DEFINED;
1107 continue;
1109 /* Handle start attribute. */
1110 case ATTRIB_START:
1111 if (sec->flags & FOLLOWS_DEFINED)
1112 nasm_error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1113 " section attributes");
1114 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1115 nasm_error(ERR_NONFATAL, "section start address redefined");
1116 else {
1117 sec->start = value;
1118 sec->flags |= START_DEFINED;
1119 if (sec->flags & ALIGN_DEFINED) {
1120 if (sec->start & (sec->align - 1))
1121 nasm_error(ERR_NONFATAL, "`start' address conflicts"
1122 " with section alignment");
1123 sec->flags ^= ALIGN_DEFINED;
1126 continue;
1128 /* Handle vstart attribute. */
1129 case ATTRIB_VSTART:
1130 if (sec->flags & VFOLLOWS_DEFINED)
1131 nasm_error(ERR_NONFATAL,
1132 "cannot combine `vstart' and `vfollows'"
1133 " section attributes");
1134 else if ((sec->flags & VSTART_DEFINED)
1135 && (value != sec->vstart))
1136 nasm_error(ERR_NONFATAL,
1137 "section virtual start address"
1138 " (vstart) redefined");
1139 else {
1140 sec->vstart = value;
1141 sec->flags |= VSTART_DEFINED;
1142 if (sec->flags & VALIGN_DEFINED) {
1143 if (sec->vstart & (sec->valign - 1))
1144 nasm_error(ERR_NONFATAL, "`vstart' address conflicts"
1145 " with `valign' value");
1146 sec->flags ^= VALIGN_DEFINED;
1149 continue;
1151 /* Handle follows attribute. */
1152 case ATTRIB_FOLLOWS:
1153 p = astring;
1154 astring += strcspn(astring, " \t");
1155 if (astring == p)
1156 nasm_error(ERR_NONFATAL, "expecting section name for `follows'"
1157 " attribute");
1158 else {
1159 *(astring++) = '\0';
1160 if (sec->flags & START_DEFINED)
1161 nasm_error(ERR_NONFATAL,
1162 "cannot combine `start' and `follows'"
1163 " section attributes");
1164 sec->follows = nasm_strdup(p);
1165 sec->flags |= FOLLOWS_DEFINED;
1167 continue;
1169 /* Handle vfollows attribute. */
1170 case ATTRIB_VFOLLOWS:
1171 if (sec->flags & VSTART_DEFINED)
1172 nasm_error(ERR_NONFATAL,
1173 "cannot combine `vstart' and `vfollows'"
1174 " section attributes");
1175 else {
1176 p = astring;
1177 astring += strcspn(astring, " \t");
1178 if (astring == p)
1179 nasm_error(ERR_NONFATAL,
1180 "expecting section name for `vfollows'"
1181 " attribute");
1182 else {
1183 *(astring++) = '\0';
1184 sec->vfollows = nasm_strdup(p);
1185 sec->flags |= VFOLLOWS_DEFINED;
1188 continue;
1193 static void bin_define_section_labels(void)
1195 static int labels_defined = 0;
1196 struct Section *sec;
1197 char *label_name;
1198 size_t base_len;
1200 if (labels_defined)
1201 return;
1202 list_for_each(sec, sections) {
1203 base_len = strlen(sec->name) + 8;
1204 label_name = nasm_malloc(base_len + 8);
1205 strcpy(label_name, "section.");
1206 strcpy(label_name + 8, sec->name);
1208 /* section.<name>.start */
1209 strcpy(label_name + base_len, ".start");
1210 define_label(label_name, sec->start_index, 0L, NULL, 0, 0);
1212 /* section.<name>.vstart */
1213 strcpy(label_name + base_len, ".vstart");
1214 define_label(label_name, sec->vstart_index, 0L, NULL, 0, 0);
1216 nasm_free(label_name);
1218 labels_defined = 1;
1221 static int32_t bin_secname(char *name, int pass, int *bits)
1223 char *p;
1224 struct Section *sec;
1226 /* bin_secname is called with *name = NULL at the start of each
1227 * pass. Use this opportunity to establish the default section
1228 * (default is BITS-16 ".text" segment).
1230 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1231 origin_defined = 0;
1232 list_for_each(sec, sections)
1233 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1234 ALIGN_DEFINED | VALIGN_DEFINED);
1236 /* Define section start and vstart labels. */
1237 if (pass != 1)
1238 bin_define_section_labels();
1240 /* Establish the default (.text) section. */
1241 *bits = 16;
1242 sec = find_section_by_name(".text");
1243 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1244 return sec->vstart_index;
1247 /* Attempt to find the requested section. If it does not
1248 * exist, create it. */
1249 p = name;
1250 while (*p && !nasm_isspace(*p))
1251 p++;
1252 if (*p)
1253 *p++ = '\0';
1254 sec = find_section_by_name(name);
1255 if (!sec) {
1256 sec = create_section(name);
1257 if (!strcmp(name, ".data"))
1258 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1259 else if (!strcmp(name, ".bss")) {
1260 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1261 sec->ifollows = NULL;
1265 /* Handle attribute assignments. */
1266 if (pass != 1)
1267 bin_assign_attributes(sec, p);
1269 #ifndef ABIN_SMART_ADAPT
1270 /* The following line disables smart adaptation of
1271 * PROGBITS/NOBITS section types (it forces sections to
1272 * default to PROGBITS). */
1273 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1274 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1275 #endif
1277 return sec->vstart_index;
1280 static int bin_directive(enum directives directive, char *args, int pass)
1282 switch (directive) {
1283 case D_ORG:
1285 struct tokenval tokval;
1286 uint64_t value;
1287 expr *e;
1289 stdscan_reset();
1290 stdscan_set(args);
1291 tokval.t_type = TOKEN_INVALID;
1292 e = evaluate(stdscan, NULL, &tokval, NULL, 1, nasm_error, NULL);
1293 if (e) {
1294 if (!is_really_simple(e))
1295 nasm_error(ERR_NONFATAL, "org value must be a critical"
1296 " expression");
1297 else {
1298 value = reloc_value(e);
1299 /* Check for ORG redefinition. */
1300 if (origin_defined && (value != origin))
1301 nasm_error(ERR_NONFATAL, "program origin redefined");
1302 else {
1303 origin = value;
1304 origin_defined = 1;
1307 } else
1308 nasm_error(ERR_NONFATAL, "No or invalid offset specified"
1309 " in ORG directive.");
1310 return 1;
1312 case D_MAP:
1314 /* The 'map' directive allows the user to generate section
1315 * and symbol information to stdout, stderr, or to a file. */
1316 char *p;
1318 if (pass != 1)
1319 return 1;
1320 args += strspn(args, " \t");
1321 while (*args) {
1322 p = args;
1323 args += strcspn(args, " \t");
1324 if (*args != '\0')
1325 *(args++) = '\0';
1326 if (!nasm_stricmp(p, "all"))
1327 map_control |=
1328 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1329 else if (!nasm_stricmp(p, "brief"))
1330 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1331 else if (!nasm_stricmp(p, "sections"))
1332 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1333 else if (!nasm_stricmp(p, "segments"))
1334 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1335 else if (!nasm_stricmp(p, "symbols"))
1336 map_control |= MAP_SYMBOLS;
1337 else if (!rf) {
1338 if (!nasm_stricmp(p, "stdout"))
1339 rf = stdout;
1340 else if (!nasm_stricmp(p, "stderr"))
1341 rf = stderr;
1342 else { /* Must be a filename. */
1343 rf = fopen(p, "wt");
1344 if (!rf) {
1345 nasm_error(ERR_WARNING, "unable to open map file `%s'",
1347 map_control = 0;
1348 return 1;
1351 } else
1352 nasm_error(ERR_WARNING, "map file already specified");
1354 if (map_control == 0)
1355 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1356 if (!rf)
1357 rf = stdout;
1358 return 1;
1360 default:
1361 return 0;
1365 static void bin_filename(char *inname, char *outname)
1367 standard_extension(inname, outname, "");
1368 infile = inname;
1369 outfile = outname;
1372 static void ith_filename(char *inname, char *outname)
1374 standard_extension(inname, outname, ".ith");
1375 infile = inname;
1376 outfile = outname;
1379 static void srec_filename(char *inname, char *outname)
1381 standard_extension(inname, outname, ".srec");
1382 infile = inname;
1383 outfile = outname;
1386 static int32_t bin_segbase(int32_t segment)
1388 return segment;
1391 static int bin_set_info(enum geninfo type, char **val)
1393 (void)type;
1394 (void)val;
1395 return 0;
1398 struct ofmt of_bin, of_ith, of_srec;
1399 static void binfmt_init(void);
1400 static void do_output_bin(void);
1401 static void do_output_ith(void);
1402 static void do_output_srec(void);
1404 static void bin_init(void)
1406 do_output = do_output_bin;
1407 binfmt_init();
1410 static void ith_init(void)
1412 do_output = do_output_ith;
1413 binfmt_init();
1416 static void srec_init(void)
1418 do_output = do_output_srec;
1419 binfmt_init();
1422 static void binfmt_init(void)
1424 maxbits = 64; /* Support 64-bit Segments */
1425 relocs = NULL;
1426 reloctail = &relocs;
1427 origin_defined = 0;
1428 no_seg_labels = NULL;
1429 nsl_tail = &no_seg_labels;
1431 /* Create default section (.text). */
1432 sections = last_section = nasm_malloc(sizeof(struct Section));
1433 last_section->next = NULL;
1434 last_section->name = nasm_strdup(".text");
1435 last_section->contents = saa_init(1L);
1436 last_section->follows = last_section->vfollows = 0;
1437 last_section->ifollows = NULL;
1438 last_section->length = 0;
1439 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1440 last_section->labels = NULL;
1441 last_section->labels_end = &(last_section->labels);
1442 last_section->start_index = seg_alloc();
1443 last_section->vstart_index = seg_alloc();
1446 /* Generate binary file output */
1447 static void do_output_bin(void)
1449 struct Section *s;
1450 uint64_t addr = origin;
1452 /* Write the progbits sections to the output file. */
1453 list_for_each(s, sections) {
1454 /* Skip non-progbits sections */
1455 if (!(s->flags & TYPE_PROGBITS))
1456 continue;
1457 /* Skip zero-length sections */
1458 if (s->length == 0)
1459 continue;
1461 /* Pad the space between sections. */
1462 nasm_assert(addr <= s->start);
1463 fwritezero(s->start - addr, ofile);
1465 /* Write the section to the output file. */
1466 saa_fpwrite(s->contents, ofile);
1468 /* Keep track of the current file position */
1469 addr = s->start + s->length;
1473 /* Generate Intel hex file output */
1474 static int write_ith_record(unsigned int len, uint16_t addr,
1475 uint8_t type, void *data)
1477 char buf[1+2+4+2+255*2+2+2];
1478 char *p = buf;
1479 uint8_t csum, *dptr = data;
1480 unsigned int i;
1482 nasm_assert(len <= 255);
1484 csum = len + addr + (addr >> 8) + type;
1485 for (i = 0; i < len; i++)
1486 csum += dptr[i];
1487 csum = -csum;
1489 p += sprintf(p, ":%02X%04X%02X", len, addr, type);
1490 for (i = 0; i < len; i++)
1491 p += sprintf(p, "%02X", dptr[i]);
1492 p += sprintf(p, "%02X\n", csum);
1494 if (fwrite(buf, 1, p-buf, ofile) != (size_t)(p-buf))
1495 return -1;
1497 return 0;
1500 static void do_output_ith(void)
1502 uint8_t buf[32];
1503 struct Section *s;
1504 uint64_t addr, hiaddr, hilba;
1505 uint64_t length;
1506 unsigned int chunk;
1508 /* Write the progbits sections to the output file. */
1509 hilba = 0;
1510 list_for_each(s, sections) {
1511 /* Skip non-progbits sections */
1512 if (!(s->flags & TYPE_PROGBITS))
1513 continue;
1514 /* Skip zero-length sections */
1515 if (s->length == 0)
1516 continue;
1518 addr = s->start;
1519 length = s->length;
1520 saa_rewind(s->contents);
1522 while (length) {
1523 hiaddr = addr >> 16;
1524 if (hiaddr != hilba) {
1525 buf[0] = hiaddr >> 8;
1526 buf[1] = hiaddr;
1527 write_ith_record(2, 0, 4, buf);
1528 hilba = hiaddr;
1531 chunk = 32 - (addr & 31);
1532 if (length < chunk)
1533 chunk = length;
1535 saa_rnbytes(s->contents, buf, chunk);
1536 write_ith_record(chunk, (uint16_t)addr, 0, buf);
1538 addr += chunk;
1539 length -= chunk;
1543 /* Write closing record */
1544 write_ith_record(0, 0, 1, NULL);
1547 /* Generate Motorola S-records */
1548 static int write_srecord(unsigned int len, unsigned int alen,
1549 uint32_t addr, uint8_t type, void *data)
1551 char buf[2+2+8+255*2+2+2];
1552 char *p = buf;
1553 uint8_t csum, *dptr = data;
1554 unsigned int i;
1556 nasm_assert(len <= 255);
1558 switch (alen) {
1559 case 2:
1560 addr &= 0xffff;
1561 break;
1562 case 3:
1563 addr &= 0xffffff;
1564 break;
1565 case 4:
1566 break;
1567 default:
1568 nasm_assert(0);
1569 break;
1572 csum = (len+alen+1) + addr + (addr >> 8) + (addr >> 16) + (addr >> 24);
1573 for (i = 0; i < len; i++)
1574 csum += dptr[i];
1575 csum = 0xff-csum;
1577 p += sprintf(p, "S%c%02X%0*X", type, len+alen+1, alen*2, addr);
1578 for (i = 0; i < len; i++)
1579 p += sprintf(p, "%02X", dptr[i]);
1580 p += sprintf(p, "%02X\n", csum);
1582 if (fwrite(buf, 1, p-buf, ofile) != (size_t)(p-buf))
1583 return -1;
1585 return 0;
1588 static void do_output_srec(void)
1590 uint8_t buf[32];
1591 struct Section *s;
1592 uint64_t addr, maxaddr;
1593 uint64_t length;
1594 int alen;
1595 unsigned int chunk;
1596 char dtype, etype;
1598 maxaddr = 0;
1599 list_for_each(s, sections) {
1600 /* Skip non-progbits sections */
1601 if (!(s->flags & TYPE_PROGBITS))
1602 continue;
1603 /* Skip zero-length sections */
1604 if (s->length == 0)
1605 continue;
1607 addr = s->start + s->length - 1;
1608 if (addr > maxaddr)
1609 maxaddr = addr;
1612 if (maxaddr <= 0xffff) {
1613 alen = 2;
1614 dtype = '1'; /* S1 = 16-bit data */
1615 etype = '9'; /* S9 = 16-bit end */
1616 } else if (maxaddr <= 0xffffff) {
1617 alen = 3;
1618 dtype = '2'; /* S2 = 24-bit data */
1619 etype = '8'; /* S8 = 24-bit end */
1620 } else {
1621 alen = 4;
1622 dtype = '3'; /* S3 = 32-bit data */
1623 etype = '7'; /* S7 = 32-bit end */
1626 /* Write head record */
1627 write_srecord(0, 2, 0, '0', NULL);
1629 /* Write the progbits sections to the output file. */
1630 list_for_each(s, sections) {
1631 /* Skip non-progbits sections */
1632 if (!(s->flags & TYPE_PROGBITS))
1633 continue;
1634 /* Skip zero-length sections */
1635 if (s->length == 0)
1636 continue;
1638 addr = s->start;
1639 length = s->length;
1640 saa_rewind(s->contents);
1642 while (length) {
1643 chunk = 32 - (addr & 31);
1644 if (length < chunk)
1645 chunk = length;
1647 saa_rnbytes(s->contents, buf, chunk);
1648 write_srecord(chunk, alen, (uint32_t)addr, dtype, buf);
1650 addr += chunk;
1651 length -= chunk;
1655 /* Write closing record */
1656 write_srecord(0, alen, 0, etype, NULL);
1660 struct ofmt of_bin = {
1661 "flat-form binary files (e.g. DOS .COM, .SYS)",
1662 "bin",
1664 null_debug_arr,
1665 &null_debug_form,
1666 bin_stdmac,
1667 bin_init,
1668 bin_set_info,
1669 bin_out,
1670 bin_deflabel,
1671 bin_secname,
1672 bin_sectalign,
1673 bin_segbase,
1674 bin_directive,
1675 bin_filename,
1676 bin_cleanup
1679 struct ofmt of_ith = {
1680 "Intel hex",
1681 "ith",
1682 OFMT_TEXT,
1683 null_debug_arr,
1684 &null_debug_form,
1685 bin_stdmac,
1686 ith_init,
1687 bin_set_info,
1688 bin_out,
1689 bin_deflabel,
1690 bin_secname,
1691 bin_sectalign,
1692 bin_segbase,
1693 bin_directive,
1694 ith_filename,
1695 bin_cleanup
1698 struct ofmt of_srec = {
1699 "Motorola S-records",
1700 "srec",
1702 null_debug_arr,
1703 &null_debug_form,
1704 bin_stdmac,
1705 srec_init,
1706 bin_set_info,
1707 bin_out,
1708 bin_deflabel,
1709 bin_secname,
1710 bin_sectalign,
1711 bin_segbase,
1712 bin_directive,
1713 srec_filename,
1714 bin_cleanup
1717 #endif /* #ifdef OF_BIN */