BR3189064: Fixes for VEXTRACTF128, VMASKMOVPS
[nasm/avx512.git] / output / outbin.c
blob97a29a8917d3e6bfc59b2f21e8149fd009785374
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->align = 0;
218 last_section->valign = 0;
219 last_section->start = 0;
220 last_section->vstart = 0;
221 last_section->next = NULL;
223 /* Register our sections with NASM. */
224 last_section->vstart_index = seg_alloc();
225 last_section->start_index = seg_alloc();
226 return last_section;
229 static void bin_cleanup(int debuginfo)
231 struct Section *g, **gp;
232 struct Section *gs = NULL, **gsp;
233 struct Section *s, **sp;
234 struct Section *nobits = NULL, **nt;
235 struct Section *last_progbits;
236 struct bin_label *l;
237 struct Reloc *r;
238 uint64_t pend;
239 int h;
241 (void)debuginfo; /* placate optimizers */
243 #ifdef DEBUG
244 nasm_error(ERR_DEBUG,
245 "bin_cleanup: Sections were initially referenced in this order:\n");
246 for (h = 0, s = sections; s; h++, s = s->next)
247 fprintf(stdout, "%i. %s\n", h, s->name);
248 #endif
250 /* Assembly has completed, so now we need to generate the output file.
251 * Step 1: Separate progbits and nobits sections into separate lists.
252 * Step 2: Sort the progbits sections into their output order.
253 * Step 3: Compute start addresses for all progbits sections.
254 * Step 4: Compute vstart addresses for all sections.
255 * Step 5: Apply relocations.
256 * Step 6: Write the sections' data to the output file.
257 * Step 7: Generate the map file.
258 * Step 8: Release all allocated memory.
261 /* To do: Smart section-type adaptation could leave some empty sections
262 * without a defined type (progbits/nobits). Won't fix now since this
263 * feature will be disabled. */
265 /* Step 1: Split progbits and nobits sections into separate lists. */
267 nt = &nobits;
268 /* Move nobits sections into a separate list. Also pre-process nobits
269 * sections' attributes. */
270 for (sp = &sections->next, s = sections->next; s; s = *sp) { /* Skip progbits sections. */
271 if (s->flags & TYPE_PROGBITS) {
272 sp = &s->next;
273 continue;
275 /* Do some special pre-processing on nobits sections' attributes. */
276 if (s->flags & (START_DEFINED | ALIGN_DEFINED | FOLLOWS_DEFINED)) { /* Check for a mixture of real and virtual section attributes. */
277 if (s->flags & (VSTART_DEFINED | VALIGN_DEFINED |
278 VFOLLOWS_DEFINED))
279 nasm_error(ERR_FATAL|ERR_NOFILE,
280 "cannot mix real and virtual attributes"
281 " in nobits section (%s)", s->name);
282 /* Real and virtual attributes mean the same thing for nobits sections. */
283 if (s->flags & START_DEFINED) {
284 s->vstart = s->start;
285 s->flags |= VSTART_DEFINED;
287 if (s->flags & ALIGN_DEFINED) {
288 s->valign = s->align;
289 s->flags |= VALIGN_DEFINED;
291 if (s->flags & FOLLOWS_DEFINED) {
292 s->vfollows = s->follows;
293 s->flags |= VFOLLOWS_DEFINED;
294 s->flags &= ~FOLLOWS_DEFINED;
297 /* Every section must have a start address. */
298 if (s->flags & VSTART_DEFINED) {
299 s->start = s->vstart;
300 s->flags |= START_DEFINED;
302 /* Move the section into the nobits list. */
303 *sp = s->next;
304 s->next = NULL;
305 *nt = s;
306 nt = &s->next;
309 /* Step 2: Sort the progbits sections into their output order. */
311 /* In Step 2 we move around sections in groups. A group
312 * begins with a section (group leader) that has a user-
313 * defined start address or follows section. The remainder
314 * of the group is made up of the sections that implicitly
315 * follow the group leader (i.e., they were defined after
316 * the group leader and were not given an explicit start
317 * address or follows section by the user). */
319 /* For anyone attempting to read this code:
320 * g (group) points to a group of sections, the first one of which has
321 * a user-defined start address or follows section.
322 * gp (g previous) holds the location of the pointer to g.
323 * gs (g scan) is a temp variable that we use to scan to the end of the group.
324 * gsp (gs previous) holds the location of the pointer to gs.
325 * nt (nobits tail) points to the nobits section-list tail.
328 /* Link all 'follows' groups to their proper position. To do
329 * this we need to know three things: the start of the group
330 * to relocate (g), the section it is following (s), and the
331 * end of the group we're relocating (gs). */
332 for (gp = &sections, g = sections; g; g = gs) { /* Find the next follows group that is out of place (g). */
333 if (!(g->flags & FOLLOWS_DEFINED)) {
334 while (g->next) {
335 if ((g->next->flags & FOLLOWS_DEFINED) &&
336 strcmp(g->name, g->next->follows))
337 break;
338 g = g->next;
340 if (!g->next)
341 break;
342 gp = &g->next;
343 g = g->next;
345 /* Find the section that this group follows (s). */
346 for (sp = &sections, s = sections;
347 s && strcmp(s->name, g->follows);
348 sp = &s->next, s = s->next) ;
349 if (!s)
350 nasm_error(ERR_FATAL|ERR_NOFILE, "section %s follows an invalid or"
351 " unknown section (%s)", g->name, g->follows);
352 if (s->next && (s->next->flags & FOLLOWS_DEFINED) &&
353 !strcmp(s->name, s->next->follows))
354 nasm_error(ERR_FATAL|ERR_NOFILE, "sections %s and %s can't both follow"
355 " section %s", g->name, s->next->name, s->name);
356 /* Find the end of the current follows group (gs). */
357 for (gsp = &g->next, gs = g->next;
358 gs && (gs != s) && !(gs->flags & START_DEFINED);
359 gsp = &gs->next, gs = gs->next) {
360 if (gs->next && (gs->next->flags & FOLLOWS_DEFINED) &&
361 strcmp(gs->name, gs->next->follows)) {
362 gsp = &gs->next;
363 gs = gs->next;
364 break;
367 /* Re-link the group after its follows section. */
368 *gsp = s->next;
369 s->next = g;
370 *gp = gs;
373 /* Link all 'start' groups to their proper position. Once
374 * again we need to know g, s, and gs (see above). The main
375 * difference is we already know g since we sort by moving
376 * groups from the 'unsorted' list into a 'sorted' list (g
377 * will always be the first section in the unsorted list). */
378 for (g = sections, sections = NULL; g; g = gs) { /* Find the section that we will insert this group before (s). */
379 for (sp = &sections, s = sections; s; sp = &s->next, s = s->next)
380 if ((s->flags & START_DEFINED) && (g->start < s->start))
381 break;
382 /* Find the end of the group (gs). */
383 for (gs = g->next, gsp = &g->next;
384 gs && !(gs->flags & START_DEFINED);
385 gsp = &gs->next, gs = gs->next) ;
386 /* Re-link the group before the target section. */
387 *sp = g;
388 *gsp = s;
391 /* Step 3: Compute start addresses for all progbits sections. */
393 /* Make sure we have an origin and a start address for the first section. */
394 if (origin_defined) {
395 if (sections->flags & START_DEFINED) {
396 /* Make sure this section doesn't begin before the origin. */
397 if (sections->start < origin)
398 nasm_error(ERR_FATAL|ERR_NOFILE, "section %s begins"
399 " before program origin", sections->name);
400 } else if (sections->flags & ALIGN_DEFINED) {
401 sections->start = ALIGN(origin, sections->align);
402 } else {
403 sections->start = origin;
405 } else {
406 if (!(sections->flags & START_DEFINED))
407 sections->start = 0;
408 origin = sections->start;
410 sections->flags |= START_DEFINED;
412 /* Make sure each section has an explicit start address. If it
413 * doesn't, then compute one based its alignment and the end of
414 * the previous section. */
415 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
416 * (has a defined start address, and is not zero length). */
417 if (g == s)
418 for (s = g->next;
419 s && ((s->length == 0) || !(s->flags & START_DEFINED));
420 s = s->next) ;
421 /* Compute the start address of this section, if necessary. */
422 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
423 if (!(g->flags & ALIGN_DEFINED)) {
424 g->align = 4;
425 g->flags |= ALIGN_DEFINED;
427 /* Set the section start address. */
428 g->start = ALIGN(pend, g->align);
429 g->flags |= START_DEFINED;
431 /* Ugly special case for progbits sections' virtual attributes:
432 * If there is a defined valign, but no vstart and no vfollows, then
433 * we valign after the previous progbits section. This case doesn't
434 * really make much sense for progbits sections with a defined start
435 * address, but it is possible and we must do *something*.
436 * Not-so-ugly special case:
437 * If a progbits section has no virtual attributes, we set the
438 * vstart equal to the start address. */
439 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
440 if (g->flags & VALIGN_DEFINED)
441 g->vstart = ALIGN(pend, g->valign);
442 else
443 g->vstart = g->start;
444 g->flags |= VSTART_DEFINED;
446 /* Ignore zero-length sections. */
447 if (g->start < pend)
448 continue;
449 /* Compute the span of this section. */
450 pend = g->start + g->length;
451 /* Check for section overlap. */
452 if (s) {
453 if (s->start < origin)
454 nasm_error(ERR_FATAL|ERR_NOFILE, "section %s beings before program origin",
455 s->name);
456 if (g->start > s->start)
457 nasm_error(ERR_FATAL|ERR_NOFILE, "sections %s ~ %s and %s overlap!",
458 gs->name, g->name, s->name);
459 if (pend > s->start)
460 nasm_error(ERR_FATAL|ERR_NOFILE, "sections %s and %s overlap!",
461 g->name, s->name);
463 /* Remember this section as the latest >0 length section. */
464 gs = g;
467 /* Step 4: Compute vstart addresses for all sections. */
469 /* Attach the nobits sections to the end of the progbits sections. */
470 for (s = sections; s->next; s = s->next) ;
471 s->next = nobits;
472 last_progbits = s;
474 * Scan for sections that don't have a vstart address. If we find
475 * one we'll attempt to compute its vstart. If we can't compute
476 * the vstart, we leave it alone and come back to it in a
477 * subsequent scan. We continue scanning and re-scanning until
478 * we've gone one full cycle without computing any vstarts.
480 do { /* Do one full scan of the sections list. */
481 for (h = 0, g = sections; g; g = g->next) {
482 if (g->flags & VSTART_DEFINED)
483 continue;
484 /* Find the section that this one virtually follows. */
485 if (g->flags & VFOLLOWS_DEFINED) {
486 for (s = sections; s && strcmp(g->vfollows, s->name);
487 s = s->next) ;
488 if (!s)
489 nasm_error(ERR_FATAL|ERR_NOFILE,
490 "section %s vfollows unknown section (%s)",
491 g->name, g->vfollows);
492 } else if (g->ifollows != NULL)
493 for (s = sections; s && (s != g->ifollows); s = s->next) ;
494 /* The .bss section is the only one with ifollows = NULL.
495 In this case we implicitly follow the last progbits
496 section. */
497 else
498 s = last_progbits;
500 /* If the section we're following has a vstart, we can proceed. */
501 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
502 if (!(g->flags & VALIGN_DEFINED)) {
503 g->valign = 4;
504 g->flags |= VALIGN_DEFINED;
506 /* Compute the vstart address. */
507 g->vstart = ALIGN(s->vstart + s->length, g->valign);
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, mydata[8];
546 int64_t l;
547 int b;
549 nasm_assert(r->bytes <= 8);
551 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
552 p = mydata;
553 l = 0;
554 for (b = r->bytes - 1; b >= 0; b--)
555 l = (l << 8) + mydata[b];
557 s = find_section_by_index(r->secref);
558 if (s) {
559 if (r->secref == s->start_index)
560 l += s->start;
561 else
562 l += s->vstart;
564 s = find_section_by_index(r->secrel);
565 if (s) {
566 if (r->secrel == s->start_index)
567 l -= s->start;
568 else
569 l -= s->vstart;
572 WRITEADDR(p, l, r->bytes);
573 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
576 /* Step 6: Write the section data to the output file. */
577 do_output();
579 /* Step 7: Generate the map file. */
581 if (map_control) {
582 static const char not_defined[] = "not defined";
584 /* Display input and output file names. */
585 fprintf(rf, "\n- NASM Map file ");
586 for (h = 63; h; h--)
587 fputc('-', rf);
588 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
589 infile, outfile);
591 if (map_control & MAP_ORIGIN) { /* Display program origin. */
592 fprintf(rf, "-- Program origin ");
593 for (h = 61; h; h--)
594 fputc('-', rf);
595 fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
597 /* Display sections summary. */
598 if (map_control & MAP_SUMMARY) {
599 fprintf(rf, "-- Sections (summary) ");
600 for (h = 57; h; h--)
601 fputc('-', rf);
602 fprintf(rf, "\n\nVstart Start Stop "
603 "Length Class Name\n");
604 list_for_each(s, sections) {
605 fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
606 s->vstart, s->start, s->start + s->length,
607 s->length);
608 if (s->flags & TYPE_PROGBITS)
609 fprintf(rf, "progbits ");
610 else
611 fprintf(rf, "nobits ");
612 fprintf(rf, "%s\n", s->name);
614 fprintf(rf, "\n");
616 /* Display detailed section information. */
617 if (map_control & MAP_SECTIONS) {
618 fprintf(rf, "-- Sections (detailed) ");
619 for (h = 56; h; h--)
620 fputc('-', rf);
621 fprintf(rf, "\n\n");
622 list_for_each(s, sections) {
623 fprintf(rf, "---- Section %s ", s->name);
624 for (h = 65 - strlen(s->name); h; h--)
625 fputc('-', rf);
626 fprintf(rf, "\n\nclass: ");
627 if (s->flags & TYPE_PROGBITS)
628 fprintf(rf, "progbits");
629 else
630 fprintf(rf, "nobits");
631 fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
632 "\nalign: ", s->length, s->start);
633 if (s->flags & ALIGN_DEFINED)
634 fprintf(rf, "%16"PRIX64"", s->align);
635 else
636 fputs(not_defined, rf);
637 fprintf(rf, "\nfollows: ");
638 if (s->flags & FOLLOWS_DEFINED)
639 fprintf(rf, "%s", s->follows);
640 else
641 fputs(not_defined, rf);
642 fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
643 if (s->flags & VALIGN_DEFINED)
644 fprintf(rf, "%16"PRIX64"", s->valign);
645 else
646 fputs(not_defined, rf);
647 fprintf(rf, "\nvfollows: ");
648 if (s->flags & VFOLLOWS_DEFINED)
649 fprintf(rf, "%s", s->vfollows);
650 else
651 fputs(not_defined, rf);
652 fprintf(rf, "\n\n");
655 /* Display symbols information. */
656 if (map_control & MAP_SYMBOLS) {
657 int32_t segment;
658 int64_t offset;
660 fprintf(rf, "-- Symbols ");
661 for (h = 68; h; h--)
662 fputc('-', rf);
663 fprintf(rf, "\n\n");
664 if (no_seg_labels) {
665 fprintf(rf, "---- No Section ");
666 for (h = 63; h; h--)
667 fputc('-', rf);
668 fprintf(rf, "\n\nValue Name\n");
669 list_for_each(l, no_seg_labels) {
670 lookup_label(l->name, &segment, &offset);
671 fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
673 fprintf(rf, "\n\n");
675 list_for_each(s, sections) {
676 if (s->labels) {
677 fprintf(rf, "---- Section %s ", s->name);
678 for (h = 65 - strlen(s->name); h; h--)
679 fputc('-', rf);
680 fprintf(rf, "\n\nReal Virtual Name\n");
681 list_for_each(l, s->labels) {
682 lookup_label(l->name, &segment, &offset);
683 fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
684 s->start + offset, s->vstart + offset,
685 l->name);
687 fprintf(rf, "\n");
693 /* Close the report file. */
694 if (map_control && (rf != stdout) && (rf != stderr))
695 fclose(rf);
697 /* Step 8: Release all allocated memory. */
699 /* Free sections, label pointer structs, etc.. */
700 while (sections) {
701 s = sections;
702 sections = s->next;
703 saa_free(s->contents);
704 nasm_free(s->name);
705 if (s->flags & FOLLOWS_DEFINED)
706 nasm_free(s->follows);
707 if (s->flags & VFOLLOWS_DEFINED)
708 nasm_free(s->vfollows);
709 while (s->labels) {
710 l = s->labels;
711 s->labels = l->next;
712 nasm_free(l);
714 nasm_free(s);
717 /* Free no-section labels. */
718 while (no_seg_labels) {
719 l = no_seg_labels;
720 no_seg_labels = l->next;
721 nasm_free(l);
724 /* Free relocation structures. */
725 while (relocs) {
726 r = relocs->next;
727 nasm_free(relocs);
728 relocs = r;
732 static void bin_out(int32_t segto, const void *data,
733 enum out_type type, uint64_t size,
734 int32_t segment, int32_t wrt)
736 uint8_t *p, mydata[8];
737 struct Section *s;
739 if (wrt != NO_SEG) {
740 wrt = NO_SEG; /* continue to do _something_ */
741 nasm_error(ERR_NONFATAL, "WRT not supported by binary output format");
744 /* Handle absolute-assembly (structure definitions). */
745 if (segto == NO_SEG) {
746 if (type != OUT_RESERVE)
747 nasm_error(ERR_NONFATAL, "attempt to assemble code in"
748 " [ABSOLUTE] space");
749 return;
752 /* Find the segment we are targeting. */
753 s = find_section_by_index(segto);
754 if (!s)
755 nasm_error(ERR_PANIC, "code directed to nonexistent segment?");
757 /* "Smart" section-type adaptation code. */
758 if (!(s->flags & TYPE_DEFINED)) {
759 if (type == OUT_RESERVE)
760 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
761 else
762 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
765 if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
766 nasm_error(ERR_WARNING, "attempt to initialize memory in a"
767 " nobits section: ignored");
769 switch (type) {
770 case OUT_ADDRESS:
771 if (segment != NO_SEG && !find_section_by_index(segment)) {
772 if (segment % 2)
773 nasm_error(ERR_NONFATAL, "binary output format does not support"
774 " segment base references");
775 else
776 nasm_error(ERR_NONFATAL, "binary output format does not support"
777 " external references");
778 segment = NO_SEG;
780 if (s->flags & TYPE_PROGBITS) {
781 if (segment != NO_SEG)
782 add_reloc(s, size, segment, -1L);
783 p = mydata;
784 WRITEADDR(p, *(int64_t *)data, size);
785 saa_wbytes(s->contents, mydata, size);
787 break;
789 case OUT_RAWDATA:
790 if (s->flags & TYPE_PROGBITS)
791 saa_wbytes(s->contents, data, size);
792 break;
794 case OUT_RESERVE:
795 if (s->flags & TYPE_PROGBITS) {
796 nasm_error(ERR_WARNING, "uninitialized space declared in"
797 " %s section: zeroing", s->name);
798 saa_wbytes(s->contents, NULL, size);
800 break;
802 case OUT_REL1ADR:
803 case OUT_REL2ADR:
804 case OUT_REL4ADR:
805 case OUT_REL8ADR:
807 int64_t addr = *(int64_t *)data - size;
808 size = realsize(type, size);
809 if (segment != NO_SEG && !find_section_by_index(segment)) {
810 if (segment % 2)
811 nasm_error(ERR_NONFATAL, "binary output format does not support"
812 " segment base references");
813 else
814 nasm_error(ERR_NONFATAL, "binary output format does not support"
815 " external references");
816 segment = NO_SEG;
818 if (s->flags & TYPE_PROGBITS) {
819 add_reloc(s, size, segment, segto);
820 p = mydata;
821 WRITEADDR(p, addr - s->length, size);
822 saa_wbytes(s->contents, mydata, size);
824 break;
827 default:
828 nasm_error(ERR_NONFATAL, "unsupported relocation type %d\n", type);
829 break;
832 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 {
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;
926 /* Find the end of the expression. */
927 if ((*line)[attrib_name_size] != '(') {
928 /* Single term (no parenthesis). */
929 exp = *line += attrib_name_size;
930 while (**line && !nasm_isspace(**line))
931 (*line)++;
932 if (**line) {
933 **line = '\0';
934 (*line)++;
936 } else {
937 char c;
938 int pcount = 1;
940 /* Full expression (delimited by parenthesis) */
941 exp = *line += attrib_name_size + 1;
942 while (1) {
943 (*line) += strcspn(*line, "()'\"");
944 if (**line == '(') {
945 ++(*line);
946 ++pcount;
948 if (**line == ')') {
949 ++(*line);
950 --pcount;
951 if (!pcount)
952 break;
954 if ((**line == '"') || (**line == '\'')) {
955 c = **line;
956 while (**line) {
957 ++(*line);
958 if (**line == c)
959 break;
961 if (!**line) {
962 nasm_error(ERR_NONFATAL,
963 "invalid syntax in `section' directive");
964 return -1;
966 ++(*line);
968 if (!**line) {
969 nasm_error(ERR_NONFATAL, "expecting `)'");
970 return -1;
973 *(*line - 1) = '\0'; /* Terminate the expression. */
976 /* Check for no value given. */
977 if (!*exp) {
978 nasm_error(ERR_WARNING, "No value given to attribute in"
979 " `section' directive");
980 return -1;
983 /* Read and evaluate the expression. */
984 stdscan_reset();
985 stdscan_set(exp);
986 tokval.t_type = TOKEN_INVALID;
987 e = evaluate(stdscan, NULL, &tokval, NULL, 1, nasm_error, NULL);
988 if (e) {
989 if (!is_really_simple(e)) {
990 nasm_error(ERR_NONFATAL, "section attribute value must be"
991 " a critical expression");
992 return -1;
994 } else {
995 nasm_error(ERR_NONFATAL, "Invalid attribute value"
996 " specified in `section' directive.");
997 return -1;
999 *value = (uint64_t)reloc_value(e);
1000 return 1;
1003 static void bin_sectalign(int32_t seg, unsigned int value)
1005 struct Section *s = find_section_by_index(seg);
1007 if (!s || !is_power2(value))
1008 return;
1010 if (value > s->align)
1011 s->align = value;
1013 if (!(s->flags & ALIGN_DEFINED))
1014 s->flags |= ALIGN_DEFINED;
1017 static void bin_assign_attributes(struct Section *sec, char *astring)
1019 int attribute, check;
1020 uint64_t value;
1021 char *p;
1023 while (1) { /* Get the next attribute. */
1024 check = bin_read_attribute(&astring, &attribute, &value);
1025 /* Skip bad attribute. */
1026 if (check == -1)
1027 continue;
1028 /* Unknown section attribute, so skip it and warn the user. */
1029 if (!check) {
1030 if (!*astring)
1031 break; /* End of line. */
1032 else {
1033 p = astring;
1034 while (*astring && !nasm_isspace(*astring))
1035 astring++;
1036 if (*astring) {
1037 *astring = '\0';
1038 astring++;
1040 nasm_error(ERR_WARNING, "ignoring unknown section attribute:"
1041 " \"%s\"", p);
1043 continue;
1046 switch (attribute) { /* Handle nobits attribute. */
1047 case ATTRIB_NOBITS:
1048 if ((sec->flags & TYPE_DEFINED)
1049 && (sec->flags & TYPE_PROGBITS))
1050 nasm_error(ERR_NONFATAL,
1051 "attempt to change section type"
1052 " from progbits to nobits");
1053 else
1054 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1055 continue;
1057 /* Handle progbits attribute. */
1058 case ATTRIB_PROGBITS:
1059 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1060 nasm_error(ERR_NONFATAL, "attempt to change section type"
1061 " from nobits to progbits");
1062 else
1063 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1064 continue;
1066 /* Handle align attribute. */
1067 case ATTRIB_ALIGN:
1068 if (!value || ((value - 1) & value)) {
1069 nasm_error(ERR_NONFATAL,
1070 "argument to `align' is not a power of two");
1071 } else {
1073 * Alignment is already satisfied if
1074 * the previous align value is greater
1076 if ((sec->flags & ALIGN_DEFINED) && (value < sec->align))
1077 value = sec->align;
1079 /* Don't allow a conflicting align value. */
1080 if ((sec->flags & START_DEFINED) && (sec->start & (value - 1))) {
1081 nasm_error(ERR_NONFATAL,
1082 "`align' value conflicts with section start address");
1083 } else {
1084 sec->align = value;
1085 sec->flags |= ALIGN_DEFINED;
1088 continue;
1090 /* Handle valign attribute. */
1091 case ATTRIB_VALIGN:
1092 if (!value || ((value - 1) & value))
1093 nasm_error(ERR_NONFATAL, "argument to `valign' is not a"
1094 " power of two");
1095 else { /* Alignment is already satisfied if the previous
1096 * align value is greater. */
1097 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1098 value = sec->valign;
1100 /* Don't allow a conflicting valign value. */
1101 if ((sec->flags & VSTART_DEFINED)
1102 && (sec->vstart & (value - 1)))
1103 nasm_error(ERR_NONFATAL,
1104 "`valign' value conflicts "
1105 "with `vstart' address");
1106 else {
1107 sec->valign = value;
1108 sec->flags |= VALIGN_DEFINED;
1111 continue;
1113 /* Handle start attribute. */
1114 case ATTRIB_START:
1115 if (sec->flags & FOLLOWS_DEFINED)
1116 nasm_error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1117 " section attributes");
1118 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1119 nasm_error(ERR_NONFATAL, "section start address redefined");
1120 else {
1121 sec->start = value;
1122 sec->flags |= START_DEFINED;
1123 if (sec->flags & ALIGN_DEFINED) {
1124 if (sec->start & (sec->align - 1))
1125 nasm_error(ERR_NONFATAL, "`start' address conflicts"
1126 " with section alignment");
1127 sec->flags ^= ALIGN_DEFINED;
1130 continue;
1132 /* Handle vstart attribute. */
1133 case ATTRIB_VSTART:
1134 if (sec->flags & VFOLLOWS_DEFINED)
1135 nasm_error(ERR_NONFATAL,
1136 "cannot combine `vstart' and `vfollows'"
1137 " section attributes");
1138 else if ((sec->flags & VSTART_DEFINED)
1139 && (value != sec->vstart))
1140 nasm_error(ERR_NONFATAL,
1141 "section virtual start address"
1142 " (vstart) redefined");
1143 else {
1144 sec->vstart = value;
1145 sec->flags |= VSTART_DEFINED;
1146 if (sec->flags & VALIGN_DEFINED) {
1147 if (sec->vstart & (sec->valign - 1))
1148 nasm_error(ERR_NONFATAL, "`vstart' address conflicts"
1149 " with `valign' value");
1150 sec->flags ^= VALIGN_DEFINED;
1153 continue;
1155 /* Handle follows attribute. */
1156 case ATTRIB_FOLLOWS:
1157 p = astring;
1158 astring += strcspn(astring, " \t");
1159 if (astring == p)
1160 nasm_error(ERR_NONFATAL, "expecting section name for `follows'"
1161 " attribute");
1162 else {
1163 *(astring++) = '\0';
1164 if (sec->flags & START_DEFINED)
1165 nasm_error(ERR_NONFATAL,
1166 "cannot combine `start' and `follows'"
1167 " section attributes");
1168 sec->follows = nasm_strdup(p);
1169 sec->flags |= FOLLOWS_DEFINED;
1171 continue;
1173 /* Handle vfollows attribute. */
1174 case ATTRIB_VFOLLOWS:
1175 if (sec->flags & VSTART_DEFINED)
1176 nasm_error(ERR_NONFATAL,
1177 "cannot combine `vstart' and `vfollows'"
1178 " section attributes");
1179 else {
1180 p = astring;
1181 astring += strcspn(astring, " \t");
1182 if (astring == p)
1183 nasm_error(ERR_NONFATAL,
1184 "expecting section name for `vfollows'"
1185 " attribute");
1186 else {
1187 *(astring++) = '\0';
1188 sec->vfollows = nasm_strdup(p);
1189 sec->flags |= VFOLLOWS_DEFINED;
1192 continue;
1197 static void bin_define_section_labels(void)
1199 static int labels_defined = 0;
1200 struct Section *sec;
1201 char *label_name;
1202 size_t base_len;
1204 if (labels_defined)
1205 return;
1206 list_for_each(sec, sections) {
1207 base_len = strlen(sec->name) + 8;
1208 label_name = nasm_malloc(base_len + 8);
1209 strcpy(label_name, "section.");
1210 strcpy(label_name + 8, sec->name);
1212 /* section.<name>.start */
1213 strcpy(label_name + base_len, ".start");
1214 define_label(label_name, sec->start_index, 0L, NULL, 0, 0);
1216 /* section.<name>.vstart */
1217 strcpy(label_name + base_len, ".vstart");
1218 define_label(label_name, sec->vstart_index, 0L, NULL, 0, 0);
1220 nasm_free(label_name);
1222 labels_defined = 1;
1225 static int32_t bin_secname(char *name, int pass, int *bits)
1227 char *p;
1228 struct Section *sec;
1230 /* bin_secname is called with *name = NULL at the start of each
1231 * pass. Use this opportunity to establish the default section
1232 * (default is BITS-16 ".text" segment).
1234 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1235 origin_defined = 0;
1236 list_for_each(sec, sections)
1237 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1238 ALIGN_DEFINED | VALIGN_DEFINED);
1240 /* Define section start and vstart labels. */
1241 if (pass != 1)
1242 bin_define_section_labels();
1244 /* Establish the default (.text) section. */
1245 *bits = 16;
1246 sec = find_section_by_name(".text");
1247 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1248 return sec->vstart_index;
1251 /* Attempt to find the requested section. If it does not
1252 * exist, create it. */
1253 p = name;
1254 while (*p && !nasm_isspace(*p))
1255 p++;
1256 if (*p)
1257 *p++ = '\0';
1258 sec = find_section_by_name(name);
1259 if (!sec) {
1260 sec = create_section(name);
1261 if (!strcmp(name, ".data"))
1262 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1263 else if (!strcmp(name, ".bss")) {
1264 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1265 sec->ifollows = NULL;
1269 /* Handle attribute assignments. */
1270 if (pass != 1)
1271 bin_assign_attributes(sec, p);
1273 #ifndef ABIN_SMART_ADAPT
1274 /* The following line disables smart adaptation of
1275 * PROGBITS/NOBITS section types (it forces sections to
1276 * default to PROGBITS). */
1277 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1278 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1279 #endif
1281 return sec->vstart_index;
1284 static int bin_directive(enum directives directive, char *args, int pass)
1286 switch (directive) {
1287 case D_ORG:
1289 struct tokenval tokval;
1290 uint64_t value;
1291 expr *e;
1293 stdscan_reset();
1294 stdscan_set(args);
1295 tokval.t_type = TOKEN_INVALID;
1296 e = evaluate(stdscan, NULL, &tokval, NULL, 1, nasm_error, NULL);
1297 if (e) {
1298 if (!is_really_simple(e))
1299 nasm_error(ERR_NONFATAL, "org value must be a critical"
1300 " expression");
1301 else {
1302 value = reloc_value(e);
1303 /* Check for ORG redefinition. */
1304 if (origin_defined && (value != origin))
1305 nasm_error(ERR_NONFATAL, "program origin redefined");
1306 else {
1307 origin = value;
1308 origin_defined = 1;
1311 } else
1312 nasm_error(ERR_NONFATAL, "No or invalid offset specified"
1313 " in ORG directive.");
1314 return 1;
1316 case D_MAP:
1318 /* The 'map' directive allows the user to generate section
1319 * and symbol information to stdout, stderr, or to a file. */
1320 char *p;
1322 if (pass != 1)
1323 return 1;
1324 args += strspn(args, " \t");
1325 while (*args) {
1326 p = args;
1327 args += strcspn(args, " \t");
1328 if (*args != '\0')
1329 *(args++) = '\0';
1330 if (!nasm_stricmp(p, "all"))
1331 map_control |=
1332 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1333 else if (!nasm_stricmp(p, "brief"))
1334 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1335 else if (!nasm_stricmp(p, "sections"))
1336 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1337 else if (!nasm_stricmp(p, "segments"))
1338 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1339 else if (!nasm_stricmp(p, "symbols"))
1340 map_control |= MAP_SYMBOLS;
1341 else if (!rf) {
1342 if (!nasm_stricmp(p, "stdout"))
1343 rf = stdout;
1344 else if (!nasm_stricmp(p, "stderr"))
1345 rf = stderr;
1346 else { /* Must be a filename. */
1347 rf = fopen(p, "wt");
1348 if (!rf) {
1349 nasm_error(ERR_WARNING, "unable to open map file `%s'",
1351 map_control = 0;
1352 return 1;
1355 } else
1356 nasm_error(ERR_WARNING, "map file already specified");
1358 if (map_control == 0)
1359 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1360 if (!rf)
1361 rf = stdout;
1362 return 1;
1364 default:
1365 return 0;
1369 static void bin_filename(char *inname, char *outname)
1371 standard_extension(inname, outname, "");
1372 infile = inname;
1373 outfile = outname;
1376 static void ith_filename(char *inname, char *outname)
1378 standard_extension(inname, outname, ".ith");
1379 infile = inname;
1380 outfile = outname;
1383 static void srec_filename(char *inname, char *outname)
1385 standard_extension(inname, outname, ".srec");
1386 infile = inname;
1387 outfile = outname;
1390 static int32_t bin_segbase(int32_t segment)
1392 return segment;
1395 static int bin_set_info(enum geninfo type, char **val)
1397 (void)type;
1398 (void)val;
1399 return 0;
1402 struct ofmt of_bin, of_ith, of_srec;
1403 static void binfmt_init(void);
1404 static void do_output_bin(void);
1405 static void do_output_ith(void);
1406 static void do_output_srec(void);
1408 static void bin_init(void)
1410 do_output = do_output_bin;
1411 binfmt_init();
1414 static void ith_init(void)
1416 do_output = do_output_ith;
1417 binfmt_init();
1420 static void srec_init(void)
1422 do_output = do_output_srec;
1423 binfmt_init();
1426 static void binfmt_init(void)
1428 maxbits = 64; /* Support 64-bit Segments */
1429 relocs = NULL;
1430 reloctail = &relocs;
1431 origin_defined = 0;
1432 no_seg_labels = NULL;
1433 nsl_tail = &no_seg_labels;
1435 /* Create default section (.text). */
1436 sections = last_section = nasm_malloc(sizeof(struct Section));
1437 last_section->next = NULL;
1438 last_section->name = nasm_strdup(".text");
1439 last_section->contents = saa_init(1L);
1440 last_section->follows = last_section->vfollows = 0;
1441 last_section->ifollows = NULL;
1442 last_section->length = 0;
1443 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1444 last_section->labels = NULL;
1445 last_section->labels_end = &(last_section->labels);
1446 last_section->start_index = seg_alloc();
1447 last_section->vstart_index = seg_alloc();
1450 /* Generate binary file output */
1451 static void do_output_bin(void)
1453 struct Section *s;
1454 uint64_t addr = origin;
1456 /* Write the progbits sections to the output file. */
1457 list_for_each(s, sections) {
1458 /* Skip non-progbits sections */
1459 if (!(s->flags & TYPE_PROGBITS))
1460 continue;
1461 /* Skip zero-length sections */
1462 if (s->length == 0)
1463 continue;
1465 /* Pad the space between sections. */
1466 nasm_assert(addr <= s->start);
1467 fwritezero(s->start - addr, ofile);
1469 /* Write the section to the output file. */
1470 saa_fpwrite(s->contents, ofile);
1472 /* Keep track of the current file position */
1473 addr = s->start + s->length;
1477 /* Generate Intel hex file output */
1478 static int write_ith_record(unsigned int len, uint16_t addr,
1479 uint8_t type, void *data)
1481 char buf[1+2+4+2+255*2+2+2];
1482 char *p = buf;
1483 uint8_t csum, *dptr = data;
1484 unsigned int i;
1486 nasm_assert(len <= 255);
1488 csum = len + addr + (addr >> 8) + type;
1489 for (i = 0; i < len; i++)
1490 csum += dptr[i];
1491 csum = -csum;
1493 p += sprintf(p, ":%02X%04X%02X", len, addr, type);
1494 for (i = 0; i < len; i++)
1495 p += sprintf(p, "%02X", dptr[i]);
1496 p += sprintf(p, "%02X\n", csum);
1498 if (fwrite(buf, 1, p-buf, ofile) != (size_t)(p-buf))
1499 return -1;
1501 return 0;
1504 static void do_output_ith(void)
1506 uint8_t buf[32];
1507 struct Section *s;
1508 uint64_t addr, hiaddr, hilba;
1509 uint64_t length;
1510 unsigned int chunk;
1512 /* Write the progbits sections to the output file. */
1513 hilba = 0;
1514 list_for_each(s, sections) {
1515 /* Skip non-progbits sections */
1516 if (!(s->flags & TYPE_PROGBITS))
1517 continue;
1518 /* Skip zero-length sections */
1519 if (s->length == 0)
1520 continue;
1522 addr = s->start;
1523 length = s->length;
1524 saa_rewind(s->contents);
1526 while (length) {
1527 hiaddr = addr >> 16;
1528 if (hiaddr != hilba) {
1529 buf[0] = hiaddr >> 8;
1530 buf[1] = hiaddr;
1531 write_ith_record(2, 0, 4, buf);
1532 hilba = hiaddr;
1535 chunk = 32 - (addr & 31);
1536 if (length < chunk)
1537 chunk = length;
1539 saa_rnbytes(s->contents, buf, chunk);
1540 write_ith_record(chunk, (uint16_t)addr, 0, buf);
1542 addr += chunk;
1543 length -= chunk;
1547 /* Write closing record */
1548 write_ith_record(0, 0, 1, NULL);
1551 /* Generate Motorola S-records */
1552 static int write_srecord(unsigned int len, unsigned int alen,
1553 uint32_t addr, uint8_t type, void *data)
1555 char buf[2+2+8+255*2+2+2];
1556 char *p = buf;
1557 uint8_t csum, *dptr = data;
1558 unsigned int i;
1560 nasm_assert(len <= 255);
1562 switch (alen) {
1563 case 2:
1564 addr &= 0xffff;
1565 break;
1566 case 3:
1567 addr &= 0xffffff;
1568 break;
1569 case 4:
1570 break;
1571 default:
1572 nasm_assert(0);
1573 break;
1576 csum = (len+alen+1) + addr + (addr >> 8) + (addr >> 16) + (addr >> 24);
1577 for (i = 0; i < len; i++)
1578 csum += dptr[i];
1579 csum = 0xff-csum;
1581 p += sprintf(p, "S%c%02X%0*X", type, len+alen+1, alen*2, addr);
1582 for (i = 0; i < len; i++)
1583 p += sprintf(p, "%02X", dptr[i]);
1584 p += sprintf(p, "%02X\n", csum);
1586 if (fwrite(buf, 1, p-buf, ofile) != (size_t)(p-buf))
1587 return -1;
1589 return 0;
1592 static void do_output_srec(void)
1594 uint8_t buf[32];
1595 struct Section *s;
1596 uint64_t addr, maxaddr;
1597 uint64_t length;
1598 int alen;
1599 unsigned int chunk;
1600 char dtype, etype;
1602 maxaddr = 0;
1603 list_for_each(s, sections) {
1604 /* Skip non-progbits sections */
1605 if (!(s->flags & TYPE_PROGBITS))
1606 continue;
1607 /* Skip zero-length sections */
1608 if (s->length == 0)
1609 continue;
1611 addr = s->start + s->length - 1;
1612 if (addr > maxaddr)
1613 maxaddr = addr;
1616 if (maxaddr <= 0xffff) {
1617 alen = 2;
1618 dtype = '1'; /* S1 = 16-bit data */
1619 etype = '9'; /* S9 = 16-bit end */
1620 } else if (maxaddr <= 0xffffff) {
1621 alen = 3;
1622 dtype = '2'; /* S2 = 24-bit data */
1623 etype = '8'; /* S8 = 24-bit end */
1624 } else {
1625 alen = 4;
1626 dtype = '3'; /* S3 = 32-bit data */
1627 etype = '7'; /* S7 = 32-bit end */
1630 /* Write head record */
1631 write_srecord(0, 2, 0, '0', NULL);
1633 /* Write the progbits sections to the output file. */
1634 list_for_each(s, sections) {
1635 /* Skip non-progbits sections */
1636 if (!(s->flags & TYPE_PROGBITS))
1637 continue;
1638 /* Skip zero-length sections */
1639 if (s->length == 0)
1640 continue;
1642 addr = s->start;
1643 length = s->length;
1644 saa_rewind(s->contents);
1646 while (length) {
1647 chunk = 32 - (addr & 31);
1648 if (length < chunk)
1649 chunk = length;
1651 saa_rnbytes(s->contents, buf, chunk);
1652 write_srecord(chunk, alen, (uint32_t)addr, dtype, buf);
1654 addr += chunk;
1655 length -= chunk;
1659 /* Write closing record */
1660 write_srecord(0, alen, 0, etype, NULL);
1664 struct ofmt of_bin = {
1665 "flat-form binary files (e.g. DOS .COM, .SYS)",
1666 "bin",
1668 null_debug_arr,
1669 &null_debug_form,
1670 bin_stdmac,
1671 bin_init,
1672 bin_set_info,
1673 bin_out,
1674 bin_deflabel,
1675 bin_secname,
1676 bin_sectalign,
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_sectalign,
1696 bin_segbase,
1697 bin_directive,
1698 ith_filename,
1699 bin_cleanup
1702 struct ofmt of_srec = {
1703 "Motorola S-records",
1704 "srec",
1706 null_debug_arr,
1707 &null_debug_form,
1708 bin_stdmac,
1709 srec_init,
1710 bin_set_info,
1711 bin_out,
1712 bin_deflabel,
1713 bin_secname,
1714 bin_sectalign,
1715 bin_segbase,
1716 bin_directive,
1717 srec_filename,
1718 bin_cleanup
1721 #endif /* #ifdef OF_BIN */