NASM 2.07rc4
[nasm/avx512.git] / output / outbin.c
blob8942acfd6038c35a6ae476d0dab96bf485bd9aa9
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 *fp, *rf = NULL;
96 static efunc error;
97 static struct ofmt *my_ofmt;
98 static void (*do_output)(void);
100 /* Section flags keep track of which attributes the user has defined. */
101 #define START_DEFINED 0x001
102 #define ALIGN_DEFINED 0x002
103 #define FOLLOWS_DEFINED 0x004
104 #define VSTART_DEFINED 0x008
105 #define VALIGN_DEFINED 0x010
106 #define VFOLLOWS_DEFINED 0x020
107 #define TYPE_DEFINED 0x040
108 #define TYPE_PROGBITS 0x080
109 #define TYPE_NOBITS 0x100
111 /* This struct is used to keep track of symbols for map-file generation. */
112 static struct bin_label {
113 char *name;
114 struct bin_label *next;
115 } *no_seg_labels, **nsl_tail;
117 static struct Section {
118 char *name;
119 struct SAA *contents;
120 int64_t length; /* section length in bytes */
122 /* Section attributes */
123 int flags; /* see flag definitions above */
124 uint64_t align; /* section alignment */
125 uint64_t valign; /* notional section alignment */
126 uint64_t start; /* section start address */
127 uint64_t vstart; /* section virtual start address */
128 char *follows; /* the section that this one will follow */
129 char *vfollows; /* the section that this one will notionally follow */
130 int32_t start_index; /* NASM section id for non-relocated version */
131 int32_t vstart_index; /* the NASM section id */
133 struct bin_label *labels; /* linked-list of label handles for map output. */
134 struct bin_label **labels_end; /* Holds address of end of labels list. */
135 struct Section *ifollows; /* Points to previous section (implicit follows). */
136 struct Section *next; /* This links sections with a defined start address. */
138 /* The extended bin format allows for sections to have a "virtual"
139 * start address. This is accomplished by creating two sections:
140 * one beginning at the Load Memory Address and the other beginning
141 * at the Virtual Memory Address. The LMA section is only used to
142 * define the section.<section_name>.start label, but there isn't
143 * any other good way for us to handle that label.
146 } *sections, *last_section;
148 static struct Reloc {
149 struct Reloc *next;
150 int32_t posn;
151 int32_t bytes;
152 int32_t secref;
153 int32_t secrel;
154 struct Section *target;
155 } *relocs, **reloctail;
157 extern char *stdscan_bufptr;
159 static uint8_t format_mode; /* 0 = original bin, 1 = extended bin */
160 static int32_t current_section; /* only really needed if format_mode = 0 */
161 static uint64_t origin;
162 static int origin_defined;
164 /* Stuff we need for map-file generation. */
165 #define MAP_ORIGIN 1
166 #define MAP_SUMMARY 2
167 #define MAP_SECTIONS 4
168 #define MAP_SYMBOLS 8
169 static int map_control = 0;
170 static char *infile, *outfile;
172 extern macros_t bin_stdmac[];
174 static void add_reloc(struct Section *s, int32_t bytes, int32_t secref,
175 int32_t secrel)
177 struct Reloc *r;
179 r = *reloctail = nasm_malloc(sizeof(struct Reloc));
180 reloctail = &r->next;
181 r->next = NULL;
182 r->posn = s->length;
183 r->bytes = bytes;
184 r->secref = secref;
185 r->secrel = secrel;
186 r->target = s;
189 static struct Section *find_section_by_name(const char *name)
191 struct Section *s;
193 for (s = sections; s; s = s->next)
194 if (!strcmp(s->name, name))
195 break;
196 return s;
199 static struct Section *find_section_by_index(int32_t index)
201 struct Section *s;
203 for (s = sections; s; s = s->next)
204 if ((index == s->vstart_index) || (index == s->start_index))
205 break;
206 return s;
209 static struct Section *create_section(char *name)
210 { /* Create a new section. */
211 last_section->next = nasm_malloc(sizeof(struct Section));
212 last_section->next->ifollows = last_section;
213 last_section = last_section->next;
214 last_section->labels = NULL;
215 last_section->labels_end = &(last_section->labels);
217 /* Initialize section attributes. */
218 last_section->name = nasm_strdup(name);
219 last_section->contents = saa_init(1L);
220 last_section->follows = last_section->vfollows = 0;
221 last_section->length = 0;
222 last_section->flags = 0;
223 last_section->next = NULL;
225 /* Register our sections with NASM. */
226 last_section->vstart_index = seg_alloc();
227 last_section->start_index = seg_alloc();
228 return last_section;
231 static void bin_cleanup(int debuginfo)
233 struct Section *g, **gp;
234 struct Section *gs = NULL, **gsp;
235 struct Section *s, **sp;
236 struct Section *nobits = NULL, **nt;
237 struct Section *last_progbits;
238 struct bin_label *l;
239 struct Reloc *r;
240 uint64_t pend;
241 int h;
243 (void)debuginfo; /* placate optimizers */
245 #ifdef DEBUG
246 fprintf(stdout,
247 "bin_cleanup: Sections were initially referenced in this order:\n");
248 for (h = 0, s = sections; s; h++, s = s->next)
249 fprintf(stdout, "%i. %s\n", h, s->name);
250 #endif
252 /* Assembly has completed, so now we need to generate the output file.
253 * Step 1: Separate progbits and nobits sections into separate lists.
254 * Step 2: Sort the progbits sections into their output order.
255 * Step 3: Compute start addresses for all progbits sections.
256 * Step 4: Compute vstart addresses for all sections.
257 * Step 5: Apply relocations.
258 * Step 6: Write the sections' data to the output file.
259 * Step 7: Generate the map file.
260 * Step 8: Release all allocated memory.
263 /* To do: Smart section-type adaptation could leave some empty sections
264 * without a defined type (progbits/nobits). Won't fix now since this
265 * feature will be disabled. */
267 /* Step 1: Split progbits and nobits sections into separate lists. */
269 nt = &nobits;
270 /* Move nobits sections into a separate list. Also pre-process nobits
271 * sections' attributes. */
272 for (sp = &sections->next, s = sections->next; s; s = *sp) { /* Skip progbits sections. */
273 if (s->flags & TYPE_PROGBITS) {
274 sp = &s->next;
275 continue;
277 /* Do some special pre-processing on nobits sections' attributes. */
278 if (s->flags & (START_DEFINED | ALIGN_DEFINED | FOLLOWS_DEFINED)) { /* Check for a mixture of real and virtual section attributes. */
279 if (s->flags & (VSTART_DEFINED | VALIGN_DEFINED |
280 VFOLLOWS_DEFINED))
281 error(ERR_FATAL|ERR_NOFILE,
282 "cannot mix real and virtual attributes"
283 " in nobits section (%s)", s->name);
284 /* Real and virtual attributes mean the same thing for nobits sections. */
285 if (s->flags & START_DEFINED) {
286 s->vstart = s->start;
287 s->flags |= VSTART_DEFINED;
289 if (s->flags & ALIGN_DEFINED) {
290 s->valign = s->align;
291 s->flags |= VALIGN_DEFINED;
293 if (s->flags & FOLLOWS_DEFINED) {
294 s->vfollows = s->follows;
295 s->flags |= VFOLLOWS_DEFINED;
296 s->flags &= ~FOLLOWS_DEFINED;
299 /* Every section must have a start address. */
300 if (s->flags & VSTART_DEFINED) {
301 s->start = s->vstart;
302 s->flags |= START_DEFINED;
304 /* Move the section into the nobits list. */
305 *sp = s->next;
306 s->next = NULL;
307 *nt = s;
308 nt = &s->next;
311 /* Step 2: Sort the progbits sections into their output order. */
313 /* In Step 2 we move around sections in groups. A group
314 * begins with a section (group leader) that has a user-
315 * defined start address or follows section. The remainder
316 * of the group is made up of the sections that implicitly
317 * follow the group leader (i.e., they were defined after
318 * the group leader and were not given an explicit start
319 * address or follows section by the user). */
321 /* For anyone attempting to read this code:
322 * g (group) points to a group of sections, the first one of which has
323 * a user-defined start address or follows section.
324 * gp (g previous) holds the location of the pointer to g.
325 * gs (g scan) is a temp variable that we use to scan to the end of the group.
326 * gsp (gs previous) holds the location of the pointer to gs.
327 * nt (nobits tail) points to the nobits section-list tail.
330 /* Link all 'follows' groups to their proper position. To do
331 * this we need to know three things: the start of the group
332 * to relocate (g), the section it is following (s), and the
333 * end of the group we're relocating (gs). */
334 for (gp = &sections, g = sections; g; g = gs) { /* Find the next follows group that is out of place (g). */
335 if (!(g->flags & FOLLOWS_DEFINED)) {
336 while (g->next) {
337 if ((g->next->flags & FOLLOWS_DEFINED) &&
338 strcmp(g->name, g->next->follows))
339 break;
340 g = g->next;
342 if (!g->next)
343 break;
344 gp = &g->next;
345 g = g->next;
347 /* Find the section that this group follows (s). */
348 for (sp = &sections, s = sections;
349 s && strcmp(s->name, g->follows);
350 sp = &s->next, s = s->next) ;
351 if (!s)
352 error(ERR_FATAL|ERR_NOFILE, "section %s follows an invalid or"
353 " unknown section (%s)", g->name, g->follows);
354 if (s->next && (s->next->flags & FOLLOWS_DEFINED) &&
355 !strcmp(s->name, s->next->follows))
356 error(ERR_FATAL|ERR_NOFILE, "sections %s and %s can't both follow"
357 " section %s", g->name, s->next->name, s->name);
358 /* Find the end of the current follows group (gs). */
359 for (gsp = &g->next, gs = g->next;
360 gs && (gs != s) && !(gs->flags & START_DEFINED);
361 gsp = &gs->next, gs = gs->next) {
362 if (gs->next && (gs->next->flags & FOLLOWS_DEFINED) &&
363 strcmp(gs->name, gs->next->follows)) {
364 gsp = &gs->next;
365 gs = gs->next;
366 break;
369 /* Re-link the group after its follows section. */
370 *gsp = s->next;
371 s->next = g;
372 *gp = gs;
375 /* Link all 'start' groups to their proper position. Once
376 * again we need to know g, s, and gs (see above). The main
377 * difference is we already know g since we sort by moving
378 * groups from the 'unsorted' list into a 'sorted' list (g
379 * will always be the first section in the unsorted list). */
380 for (g = sections, sections = NULL; g; g = gs) { /* Find the section that we will insert this group before (s). */
381 for (sp = &sections, s = sections; s; sp = &s->next, s = s->next)
382 if ((s->flags & START_DEFINED) && (g->start < s->start))
383 break;
384 /* Find the end of the group (gs). */
385 for (gs = g->next, gsp = &g->next;
386 gs && !(gs->flags & START_DEFINED);
387 gsp = &gs->next, gs = gs->next) ;
388 /* Re-link the group before the target section. */
389 *sp = g;
390 *gsp = s;
393 /* Step 3: Compute start addresses for all progbits sections. */
395 /* Make sure we have an origin and a start address for the first section. */
396 if (origin_defined) {
397 if (sections->flags & START_DEFINED) {
398 /* Make sure this section doesn't begin before the origin. */
399 if (sections->start < origin)
400 error(ERR_FATAL|ERR_NOFILE, "section %s begins"
401 " before program origin", sections->name);
402 } else if (sections->flags & ALIGN_DEFINED) {
403 sections->start = ((origin + sections->align - 1) &
404 ~(sections->align - 1));
405 } else {
406 sections->start = origin;
408 } else {
409 if (!(sections->flags & START_DEFINED))
410 sections->start = 0;
411 origin = sections->start;
413 sections->flags |= START_DEFINED;
415 /* Make sure each section has an explicit start address. If it
416 * doesn't, then compute one based its alignment and the end of
417 * the previous section. */
418 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
419 * (has a defined start address, and is not zero length). */
420 if (g == s)
421 for (s = g->next;
422 s && ((s->length == 0) || !(s->flags & START_DEFINED));
423 s = s->next) ;
424 /* Compute the start address of this section, if necessary. */
425 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
426 if (!(g->flags & ALIGN_DEFINED)) {
427 g->align = 4;
428 g->flags |= ALIGN_DEFINED;
430 /* Set the section start address. */
431 g->start = (pend + g->align - 1) & ~(g->align - 1);
432 g->flags |= START_DEFINED;
434 /* Ugly special case for progbits sections' virtual attributes:
435 * If there is a defined valign, but no vstart and no vfollows, then
436 * we valign after the previous progbits section. This case doesn't
437 * really make much sense for progbits sections with a defined start
438 * address, but it is possible and we must do *something*.
439 * Not-so-ugly special case:
440 * If a progbits section has no virtual attributes, we set the
441 * vstart equal to the start address. */
442 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
443 if (g->flags & VALIGN_DEFINED)
444 g->vstart = (pend + g->valign - 1) & ~(g->valign - 1);
445 else
446 g->vstart = g->start;
447 g->flags |= VSTART_DEFINED;
449 /* Ignore zero-length sections. */
450 if (g->start < pend)
451 continue;
452 /* Compute the span of this section. */
453 pend = g->start + g->length;
454 /* Check for section overlap. */
455 if (s) {
456 if (s->start < origin)
457 error(ERR_FATAL|ERR_NOFILE, "section %s beings before program origin",
458 s->name);
459 if (g->start > s->start)
460 error(ERR_FATAL|ERR_NOFILE, "sections %s ~ %s and %s overlap!",
461 gs->name, g->name, s->name);
462 if (pend > s->start)
463 error(ERR_FATAL|ERR_NOFILE, "sections %s and %s overlap!",
464 g->name, s->name);
466 /* Remember this section as the latest >0 length section. */
467 gs = g;
470 /* Step 4: Compute vstart addresses for all sections. */
472 /* Attach the nobits sections to the end of the progbits sections. */
473 for (s = sections; s->next; s = s->next) ;
474 s->next = nobits;
475 last_progbits = s;
477 * Scan for sections that don't have a vstart address. If we find
478 * one we'll attempt to compute its vstart. If we can't compute
479 * the vstart, we leave it alone and come back to it in a
480 * subsequent scan. We continue scanning and re-scanning until
481 * we've gone one full cycle without computing any vstarts.
483 do { /* Do one full scan of the sections list. */
484 for (h = 0, g = sections; g; g = g->next) {
485 if (g->flags & VSTART_DEFINED)
486 continue;
487 /* Find the section that this one virtually follows. */
488 if (g->flags & VFOLLOWS_DEFINED) {
489 for (s = sections; s && strcmp(g->vfollows, s->name);
490 s = s->next) ;
491 if (!s)
492 error(ERR_FATAL|ERR_NOFILE,
493 "section %s vfollows unknown section (%s)",
494 g->name, g->vfollows);
495 } else if (g->ifollows != NULL)
496 for (s = sections; s && (s != g->ifollows); s = s->next) ;
497 /* The .bss section is the only one with ifollows = NULL.
498 In this case we implicitly follow the last progbits
499 section. */
500 else
501 s = last_progbits;
503 /* If the section we're following has a vstart, we can proceed. */
504 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
505 if (!(g->flags & VALIGN_DEFINED)) {
506 g->valign = 4;
507 g->flags |= VALIGN_DEFINED;
509 /* Compute the vstart address. */
510 g->vstart = (s->vstart + s->length + g->valign - 1)
511 & ~(g->valign - 1);
512 g->flags |= VSTART_DEFINED;
513 h++;
514 /* Start and vstart mean the same thing for nobits sections. */
515 if (g->flags & TYPE_NOBITS)
516 g->start = g->vstart;
519 } while (h);
521 /* Now check for any circular vfollows references, which will manifest
522 * themselves as sections without a defined vstart. */
523 for (h = 0, s = sections; s; s = s->next) {
524 if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
525 * no-no, but we'll throw a fatal one eventually so it's ok. */
526 error(ERR_NONFATAL, "cannot compute vstart for section %s",
527 s->name);
528 h++;
531 if (h)
532 error(ERR_FATAL|ERR_NOFILE, "circular vfollows path detected");
534 #ifdef DEBUG
535 fprintf(stdout,
536 "bin_cleanup: Confirm final section order for output file:\n");
537 for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
538 h++, s = s->next)
539 fprintf(stdout, "%i. %s\n", h, s->name);
540 #endif
542 /* Step 5: Apply relocations. */
544 /* Prepare the sections for relocating. */
545 for (s = sections; s; s = s->next)
546 saa_rewind(s->contents);
547 /* Apply relocations. */
548 for (r = relocs; r; r = r->next) {
549 uint8_t *p, *q, mydata[8];
550 int64_t l;
552 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
553 p = q = mydata;
554 l = *p++;
556 if (r->bytes > 1) {
557 l += ((int64_t)*p++) << 8;
558 if (r->bytes >= 4) {
559 l += ((int64_t)*p++) << 16;
560 l += ((int64_t)*p++) << 24;
562 if (r->bytes == 8) {
563 l += ((int64_t)*p++) << 32;
564 l += ((int64_t)*p++) << 40;
565 l += ((int64_t)*p++) << 48;
566 l += ((int64_t)*p++) << 56;
570 s = find_section_by_index(r->secref);
571 if (s) {
572 if (r->secref == s->start_index)
573 l += s->start;
574 else
575 l += s->vstart;
577 s = find_section_by_index(r->secrel);
578 if (s) {
579 if (r->secrel == s->start_index)
580 l -= s->start;
581 else
582 l -= s->vstart;
585 if (r->bytes >= 4)
586 WRITEDLONG(q, l);
587 else if (r->bytes == 2)
588 WRITESHORT(q, l);
589 else
590 *q++ = (uint8_t)(l & 0xFF);
591 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
594 /* Step 6: Write the section data to the output file. */
595 do_output();
596 fclose(fp); /* Done with the output file */
598 /* Step 7: Generate the map file. */
600 if (map_control) {
601 static const char not_defined[] = "not defined";
603 /* Display input and output file names. */
604 fprintf(rf, "\n- NASM Map file ");
605 for (h = 63; h; h--)
606 fputc('-', rf);
607 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
608 infile, outfile);
610 if (map_control & MAP_ORIGIN) { /* Display program origin. */
611 fprintf(rf, "-- Program origin ");
612 for (h = 61; h; h--)
613 fputc('-', rf);
614 fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
616 /* Display sections summary. */
617 if (map_control & MAP_SUMMARY) {
618 fprintf(rf, "-- Sections (summary) ");
619 for (h = 57; h; h--)
620 fputc('-', rf);
621 fprintf(rf, "\n\nVstart Start Stop "
622 "Length Class Name\n");
623 for (s = sections; s; s = s->next) {
624 fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
625 s->vstart, s->start, s->start + s->length,
626 s->length);
627 if (s->flags & TYPE_PROGBITS)
628 fprintf(rf, "progbits ");
629 else
630 fprintf(rf, "nobits ");
631 fprintf(rf, "%s\n", s->name);
633 fprintf(rf, "\n");
635 /* Display detailed section information. */
636 if (map_control & MAP_SECTIONS) {
637 fprintf(rf, "-- Sections (detailed) ");
638 for (h = 56; h; h--)
639 fputc('-', rf);
640 fprintf(rf, "\n\n");
641 for (s = sections; s; s = s->next) {
642 fprintf(rf, "---- Section %s ", s->name);
643 for (h = 65 - strlen(s->name); h; h--)
644 fputc('-', rf);
645 fprintf(rf, "\n\nclass: ");
646 if (s->flags & TYPE_PROGBITS)
647 fprintf(rf, "progbits");
648 else
649 fprintf(rf, "nobits");
650 fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
651 "\nalign: ", s->length, s->start);
652 if (s->flags & ALIGN_DEFINED)
653 fprintf(rf, "%16"PRIX64"", s->align);
654 else
655 fputs(not_defined, rf);
656 fprintf(rf, "\nfollows: ");
657 if (s->flags & FOLLOWS_DEFINED)
658 fprintf(rf, "%s", s->follows);
659 else
660 fputs(not_defined, rf);
661 fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
662 if (s->flags & VALIGN_DEFINED)
663 fprintf(rf, "%16"PRIX64"", s->valign);
664 else
665 fputs(not_defined, rf);
666 fprintf(rf, "\nvfollows: ");
667 if (s->flags & VFOLLOWS_DEFINED)
668 fprintf(rf, "%s", s->vfollows);
669 else
670 fputs(not_defined, rf);
671 fprintf(rf, "\n\n");
674 /* Display symbols information. */
675 if (map_control & MAP_SYMBOLS) {
676 int32_t segment;
677 int64_t offset;
679 fprintf(rf, "-- Symbols ");
680 for (h = 68; h; h--)
681 fputc('-', rf);
682 fprintf(rf, "\n\n");
683 if (no_seg_labels) {
684 fprintf(rf, "---- No Section ");
685 for (h = 63; h; h--)
686 fputc('-', rf);
687 fprintf(rf, "\n\nValue Name\n");
688 for (l = no_seg_labels; l; l = l->next) {
689 lookup_label(l->name, &segment, &offset);
690 fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
692 fprintf(rf, "\n\n");
694 for (s = sections; s; s = s->next) {
695 if (s->labels) {
696 fprintf(rf, "---- Section %s ", s->name);
697 for (h = 65 - strlen(s->name); h; h--)
698 fputc('-', rf);
699 fprintf(rf, "\n\nReal Virtual Name\n");
700 for (l = s->labels; l; l = l->next) {
701 lookup_label(l->name, &segment, &offset);
702 fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
703 s->start + offset, s->vstart + offset,
704 l->name);
706 fprintf(rf, "\n");
712 /* Close the report file. */
713 if (map_control && (rf != stdout) && (rf != stderr))
714 fclose(rf);
716 /* Step 8: Release all allocated memory. */
718 /* Free sections, label pointer structs, etc.. */
719 while (sections) {
720 s = sections;
721 sections = s->next;
722 saa_free(s->contents);
723 nasm_free(s->name);
724 if (s->flags & FOLLOWS_DEFINED)
725 nasm_free(s->follows);
726 if (s->flags & VFOLLOWS_DEFINED)
727 nasm_free(s->vfollows);
728 while (s->labels) {
729 l = s->labels;
730 s->labels = l->next;
731 nasm_free(l);
733 nasm_free(s);
736 /* Free no-section labels. */
737 while (no_seg_labels) {
738 l = no_seg_labels;
739 no_seg_labels = l->next;
740 nasm_free(l);
743 /* Free relocation structures. */
744 while (relocs) {
745 r = relocs->next;
746 nasm_free(relocs);
747 relocs = r;
751 static void bin_out(int32_t segto, const void *data,
752 enum out_type type, uint64_t size,
753 int32_t segment, int32_t wrt)
755 uint8_t *p, mydata[8];
756 struct Section *s;
758 if (wrt != NO_SEG) {
759 wrt = NO_SEG; /* continue to do _something_ */
760 error(ERR_NONFATAL, "WRT not supported by binary output format");
763 /* Handle absolute-assembly (structure definitions). */
764 if (segto == NO_SEG) {
765 if (type != OUT_RESERVE)
766 error(ERR_NONFATAL, "attempt to assemble code in"
767 " [ABSOLUTE] space");
768 return;
771 /* Find the segment we are targeting. */
772 s = find_section_by_index(segto);
773 if (!s)
774 error(ERR_PANIC, "code directed to nonexistent segment?");
776 /* "Smart" section-type adaptation code. */
777 if (!(s->flags & TYPE_DEFINED)) {
778 if (type == OUT_RESERVE)
779 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
780 else
781 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
784 if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
785 error(ERR_WARNING, "attempt to initialize memory in a"
786 " nobits section: ignored");
788 if (type == OUT_ADDRESS) {
789 if (segment != NO_SEG && !find_section_by_index(segment)) {
790 if (segment % 2)
791 error(ERR_NONFATAL, "binary output format does not support"
792 " segment base references");
793 else
794 error(ERR_NONFATAL, "binary output format does not support"
795 " external references");
796 segment = NO_SEG;
798 if (s->flags & TYPE_PROGBITS) {
799 if (segment != NO_SEG)
800 add_reloc(s, size, segment, -1L);
801 p = mydata;
802 WRITEADDR(p, *(int64_t *)data, size);
803 saa_wbytes(s->contents, mydata, size);
805 s->length += size;
806 } else if (type == OUT_RAWDATA) {
807 if (s->flags & TYPE_PROGBITS)
808 saa_wbytes(s->contents, data, size);
809 s->length += size;
810 } else if (type == OUT_RESERVE) {
811 if (s->flags & TYPE_PROGBITS) {
812 error(ERR_WARNING, "uninitialized space declared in"
813 " %s section: zeroing", s->name);
814 saa_wbytes(s->contents, NULL, size);
816 s->length += size;
817 } else if (type == OUT_REL2ADR || type == OUT_REL4ADR ||
818 type == OUT_REL8ADR) {
819 int64_t addr = *(int64_t *)data - size;
820 size = realsize(type, size);
821 if (segment != NO_SEG && !find_section_by_index(segment)) {
822 if (segment % 2)
823 error(ERR_NONFATAL, "binary output format does not support"
824 " segment base references");
825 else
826 error(ERR_NONFATAL, "binary output format does not support"
827 " external references");
828 segment = NO_SEG;
830 if (s->flags & TYPE_PROGBITS) {
831 add_reloc(s, size, segment, segto);
832 p = mydata;
833 WRITEADDR(p, addr - s->length, size);
834 saa_wbytes(s->contents, mydata, size);
836 s->length += size;
840 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
841 int is_global, char *special)
843 (void)segment; /* Don't warn that this parameter is unused */
844 (void)offset; /* Don't warn that this parameter is unused */
846 if (special)
847 error(ERR_NONFATAL, "binary format does not support any"
848 " special symbol types");
849 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
850 error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
851 else if (is_global == 2)
852 error(ERR_NONFATAL, "binary output format does not support common"
853 " variables");
854 else {
855 struct Section *s;
856 struct bin_label ***ltp;
858 /* Remember label definition so we can look it up later when
859 * creating the map file. */
860 s = find_section_by_index(segment);
861 if (s)
862 ltp = &(s->labels_end);
863 else
864 ltp = &nsl_tail;
865 (**ltp) = nasm_malloc(sizeof(struct bin_label));
866 (**ltp)->name = name;
867 (**ltp)->next = NULL;
868 *ltp = &((**ltp)->next);
873 /* These constants and the following function are used
874 * by bin_secname() to parse attribute assignments. */
876 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
877 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
878 ATTRIB_NOBITS, ATTRIB_PROGBITS
881 static int bin_read_attribute(char **line, int *attribute,
882 uint64_t *value)
884 expr *e;
885 int attrib_name_size;
886 struct tokenval tokval;
887 char *exp;
889 /* Skip whitespace. */
890 while (**line && nasm_isspace(**line))
891 (*line)++;
892 if (!**line)
893 return 0;
895 /* Figure out what attribute we're reading. */
896 if (!nasm_strnicmp(*line, "align=", 6)) {
897 *attribute = ATTRIB_ALIGN;
898 attrib_name_size = 6;
899 } else if (format_mode) {
900 if (!nasm_strnicmp(*line, "start=", 6)) {
901 *attribute = ATTRIB_START;
902 attrib_name_size = 6;
903 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
904 *attribute = ATTRIB_FOLLOWS;
905 *line += 8;
906 return 1;
907 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
908 *attribute = ATTRIB_VSTART;
909 attrib_name_size = 7;
910 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
911 *attribute = ATTRIB_VALIGN;
912 attrib_name_size = 7;
913 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
914 *attribute = ATTRIB_VFOLLOWS;
915 *line += 9;
916 return 1;
917 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
918 (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
919 *attribute = ATTRIB_NOBITS;
920 *line += 6;
921 return 1;
922 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
923 (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
924 *attribute = ATTRIB_PROGBITS;
925 *line += 8;
926 return 1;
927 } else
928 return 0;
929 } else
930 return 0;
932 /* Find the end of the expression. */
933 if ((*line)[attrib_name_size] != '(') {
934 /* Single term (no parenthesis). */
935 exp = *line += attrib_name_size;
936 while (**line && !nasm_isspace(**line))
937 (*line)++;
938 if (**line) {
939 **line = '\0';
940 (*line)++;
942 } else {
943 char c;
944 int pcount = 1;
946 /* Full expression (delimited by parenthesis) */
947 exp = *line += attrib_name_size + 1;
948 while (1) {
949 (*line) += strcspn(*line, "()'\"");
950 if (**line == '(') {
951 ++(*line);
952 ++pcount;
954 if (**line == ')') {
955 ++(*line);
956 --pcount;
957 if (!pcount)
958 break;
960 if ((**line == '"') || (**line == '\'')) {
961 c = **line;
962 while (**line) {
963 ++(*line);
964 if (**line == c)
965 break;
967 if (!**line) {
968 error(ERR_NONFATAL,
969 "invalid syntax in `section' directive");
970 return -1;
972 ++(*line);
974 if (!**line) {
975 error(ERR_NONFATAL, "expecting `)'");
976 return -1;
979 *(*line - 1) = '\0'; /* Terminate the expression. */
982 /* Check for no value given. */
983 if (!*exp) {
984 error(ERR_WARNING, "No value given to attribute in"
985 " `section' directive");
986 return -1;
989 /* Read and evaluate the expression. */
990 stdscan_reset();
991 stdscan_bufptr = exp;
992 tokval.t_type = TOKEN_INVALID;
993 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
994 if (e) {
995 if (!is_really_simple(e)) {
996 error(ERR_NONFATAL, "section attribute value must be"
997 " a critical expression");
998 return -1;
1000 } else {
1001 error(ERR_NONFATAL, "Invalid attribute value"
1002 " specified in `section' directive.");
1003 return -1;
1005 *value = (uint64_t)reloc_value(e);
1006 return 1;
1009 static void bin_assign_attributes(struct Section *sec, char *astring)
1011 int attribute, check;
1012 uint64_t value;
1013 char *p;
1015 while (1) { /* Get the next attribute. */
1016 check = bin_read_attribute(&astring, &attribute, &value);
1017 /* Skip bad attribute. */
1018 if (check == -1)
1019 continue;
1020 /* Unknown section attribute, so skip it and warn the user. */
1021 if (!check) {
1022 if (!*astring)
1023 break; /* End of line. */
1024 else {
1025 p = astring;
1026 while (*astring && !nasm_isspace(*astring))
1027 astring++;
1028 if (*astring) {
1029 *astring = '\0';
1030 astring++;
1032 error(ERR_WARNING, "ignoring unknown section attribute:"
1033 " \"%s\"", p);
1035 continue;
1038 switch (attribute) { /* Handle nobits attribute. */
1039 case ATTRIB_NOBITS:
1040 if ((sec->flags & TYPE_DEFINED)
1041 && (sec->flags & TYPE_PROGBITS))
1042 error(ERR_NONFATAL,
1043 "attempt to change section type"
1044 " from progbits to nobits");
1045 else
1046 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1047 continue;
1049 /* Handle progbits attribute. */
1050 case ATTRIB_PROGBITS:
1051 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1052 error(ERR_NONFATAL, "attempt to change section type"
1053 " from nobits to progbits");
1054 else
1055 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1056 continue;
1058 /* Handle align attribute. */
1059 case ATTRIB_ALIGN:
1060 if (!format_mode && (!strcmp(sec->name, ".text")))
1061 error(ERR_NONFATAL, "cannot specify an alignment"
1062 " to the .text section");
1063 else {
1064 if (!value || ((value - 1) & value))
1065 error(ERR_NONFATAL, "argument to `align' is not a"
1066 " power of two");
1067 else { /* Alignment is already satisfied if the previous
1068 * align value is greater. */
1069 if ((sec->flags & ALIGN_DEFINED)
1070 && (value < sec->align))
1071 value = sec->align;
1073 /* Don't allow a conflicting align value. */
1074 if ((sec->flags & START_DEFINED)
1075 && (sec->start & (value - 1)))
1076 error(ERR_NONFATAL,
1077 "`align' value conflicts "
1078 "with section start address");
1079 else {
1080 sec->align = value;
1081 sec->flags |= ALIGN_DEFINED;
1085 continue;
1087 /* Handle valign attribute. */
1088 case ATTRIB_VALIGN:
1089 if (!value || ((value - 1) & value))
1090 error(ERR_NONFATAL, "argument to `valign' is not a"
1091 " power of two");
1092 else { /* Alignment is already satisfied if the previous
1093 * align value is greater. */
1094 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1095 value = sec->valign;
1097 /* Don't allow a conflicting valign value. */
1098 if ((sec->flags & VSTART_DEFINED)
1099 && (sec->vstart & (value - 1)))
1100 error(ERR_NONFATAL,
1101 "`valign' value conflicts "
1102 "with `vstart' address");
1103 else {
1104 sec->valign = value;
1105 sec->flags |= VALIGN_DEFINED;
1108 continue;
1110 /* Handle start attribute. */
1111 case ATTRIB_START:
1112 if (sec->flags & FOLLOWS_DEFINED)
1113 error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1114 " section attributes");
1115 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1116 error(ERR_NONFATAL, "section start address redefined");
1117 else {
1118 sec->start = value;
1119 sec->flags |= START_DEFINED;
1120 if (sec->flags & ALIGN_DEFINED) {
1121 if (sec->start & (sec->align - 1))
1122 error(ERR_NONFATAL, "`start' address conflicts"
1123 " with section alignment");
1124 sec->flags ^= ALIGN_DEFINED;
1127 continue;
1129 /* Handle vstart attribute. */
1130 case ATTRIB_VSTART:
1131 if (sec->flags & VFOLLOWS_DEFINED)
1132 error(ERR_NONFATAL,
1133 "cannot combine `vstart' and `vfollows'"
1134 " section attributes");
1135 else if ((sec->flags & VSTART_DEFINED)
1136 && (value != sec->vstart))
1137 error(ERR_NONFATAL,
1138 "section virtual start address"
1139 " (vstart) redefined");
1140 else {
1141 sec->vstart = value;
1142 sec->flags |= VSTART_DEFINED;
1143 if (sec->flags & VALIGN_DEFINED) {
1144 if (sec->vstart & (sec->valign - 1))
1145 error(ERR_NONFATAL, "`vstart' address conflicts"
1146 " with `valign' value");
1147 sec->flags ^= VALIGN_DEFINED;
1150 continue;
1152 /* Handle follows attribute. */
1153 case ATTRIB_FOLLOWS:
1154 p = astring;
1155 astring += strcspn(astring, " \t");
1156 if (astring == p)
1157 error(ERR_NONFATAL, "expecting section name for `follows'"
1158 " attribute");
1159 else {
1160 *(astring++) = '\0';
1161 if (sec->flags & START_DEFINED)
1162 error(ERR_NONFATAL,
1163 "cannot combine `start' and `follows'"
1164 " section attributes");
1165 sec->follows = nasm_strdup(p);
1166 sec->flags |= FOLLOWS_DEFINED;
1168 continue;
1170 /* Handle vfollows attribute. */
1171 case ATTRIB_VFOLLOWS:
1172 if (sec->flags & VSTART_DEFINED)
1173 error(ERR_NONFATAL,
1174 "cannot combine `vstart' and `vfollows'"
1175 " section attributes");
1176 else {
1177 p = astring;
1178 astring += strcspn(astring, " \t");
1179 if (astring == p)
1180 error(ERR_NONFATAL,
1181 "expecting section name for `vfollows'"
1182 " attribute");
1183 else {
1184 *(astring++) = '\0';
1185 sec->vfollows = nasm_strdup(p);
1186 sec->flags |= VFOLLOWS_DEFINED;
1189 continue;
1194 static void bin_define_section_labels(void)
1196 static int labels_defined = 0;
1197 struct Section *sec;
1198 char *label_name;
1199 size_t base_len;
1201 if (labels_defined)
1202 return;
1203 for (sec = sections; sec; sec = sec->next) {
1204 base_len = strlen(sec->name) + 8;
1205 label_name = nasm_malloc(base_len + 8);
1206 strcpy(label_name, "section.");
1207 strcpy(label_name + 8, sec->name);
1209 /* section.<name>.start */
1210 strcpy(label_name + base_len, ".start");
1211 define_label(label_name, sec->start_index, 0L,
1212 NULL, 0, 0, my_ofmt, error);
1214 /* section.<name>.vstart */
1215 strcpy(label_name + base_len, ".vstart");
1216 define_label(label_name, sec->vstart_index, 0L,
1217 NULL, 0, 0, my_ofmt, error);
1219 nasm_free(label_name);
1221 labels_defined = 1;
1224 static int32_t bin_secname(char *name, int pass, int *bits)
1226 char *p;
1227 struct Section *sec;
1229 /* bin_secname is called with *name = NULL at the start of each
1230 * pass. Use this opportunity to establish the default section
1231 * (default is BITS-16 ".text" segment).
1233 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1234 origin_defined = 0;
1235 for (sec = sections; sec; sec = sec->next)
1236 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1237 ALIGN_DEFINED | VALIGN_DEFINED);
1239 /* Define section start and vstart labels. */
1240 if (format_mode && (pass != 1))
1241 bin_define_section_labels();
1243 /* Establish the default (.text) section. */
1244 *bits = 16;
1245 sec = find_section_by_name(".text");
1246 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1247 current_section = sec->vstart_index;
1248 return current_section;
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;
1266 } else if (!format_mode) {
1267 error(ERR_NONFATAL, "section name must be "
1268 ".text, .data, or .bss");
1269 return current_section;
1273 /* Handle attribute assignments. */
1274 if (pass != 1)
1275 bin_assign_attributes(sec, p);
1277 #ifndef ABIN_SMART_ADAPT
1278 /* The following line disables smart adaptation of
1279 * PROGBITS/NOBITS section types (it forces sections to
1280 * default to PROGBITS). */
1281 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1282 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1283 #endif
1285 /* Set the current section and return. */
1286 current_section = sec->vstart_index;
1287 return current_section;
1290 static int bin_directive(char *directive, char *args, int pass)
1292 /* Handle ORG directive */
1293 if (!nasm_stricmp(directive, "org")) {
1294 struct tokenval tokval;
1295 uint64_t value;
1296 expr *e;
1298 stdscan_reset();
1299 stdscan_bufptr = args;
1300 tokval.t_type = TOKEN_INVALID;
1301 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
1302 if (e) {
1303 if (!is_really_simple(e))
1304 error(ERR_NONFATAL, "org value must be a critical"
1305 " expression");
1306 else {
1307 value = reloc_value(e);
1308 /* Check for ORG redefinition. */
1309 if (origin_defined && (value != origin))
1310 error(ERR_NONFATAL, "program origin redefined");
1311 else {
1312 origin = value;
1313 origin_defined = 1;
1316 } else
1317 error(ERR_NONFATAL, "No or invalid offset specified"
1318 " in ORG directive.");
1319 return 1;
1322 /* The 'map' directive allows the user to generate section
1323 * and symbol information to stdout, stderr, or to a file. */
1324 else if (format_mode && !nasm_stricmp(directive, "map")) {
1325 char *p;
1327 if (pass != 1)
1328 return 1;
1329 args += strspn(args, " \t");
1330 while (*args) {
1331 p = args;
1332 args += strcspn(args, " \t");
1333 if (*args != '\0')
1334 *(args++) = '\0';
1335 if (!nasm_stricmp(p, "all"))
1336 map_control |=
1337 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1338 else if (!nasm_stricmp(p, "brief"))
1339 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1340 else if (!nasm_stricmp(p, "sections"))
1341 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1342 else if (!nasm_stricmp(p, "segments"))
1343 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1344 else if (!nasm_stricmp(p, "symbols"))
1345 map_control |= MAP_SYMBOLS;
1346 else if (!rf) {
1347 if (!nasm_stricmp(p, "stdout"))
1348 rf = stdout;
1349 else if (!nasm_stricmp(p, "stderr"))
1350 rf = stderr;
1351 else { /* Must be a filename. */
1352 rf = fopen(p, "wt");
1353 if (!rf) {
1354 error(ERR_WARNING, "unable to open map file `%s'",
1356 map_control = 0;
1357 return 1;
1360 } else
1361 error(ERR_WARNING, "map file already specified");
1363 if (map_control == 0)
1364 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1365 if (!rf)
1366 rf = stdout;
1367 return 1;
1369 return 0;
1372 static void bin_filename(char *inname, char *outname, efunc error)
1374 standard_extension(inname, outname, "", error);
1375 infile = inname;
1376 outfile = outname;
1379 static void ith_filename(char *inname, char *outname, efunc error)
1381 standard_extension(inname, outname, ".ith", error);
1382 infile = inname;
1383 outfile = outname;
1386 static void srec_filename(char *inname, char *outname, efunc error)
1388 standard_extension(inname, outname, ".srec", error);
1389 infile = inname;
1390 outfile = outname;
1393 static int32_t bin_segbase(int32_t segment)
1395 return segment;
1398 static int bin_set_info(enum geninfo type, char **val)
1400 (void)type;
1401 (void)val;
1402 return 0;
1405 static void binfmt_init(FILE *afp, efunc errfunc, ldfunc ldef, evalfunc eval);
1406 struct ofmt of_bin, of_ith, of_srec;
1407 static void do_output_bin(void);
1408 static void do_output_ith(void);
1409 static void do_output_srec(void);
1411 static void bin_init(FILE *afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1413 my_ofmt = &of_bin;
1414 do_output = do_output_bin;
1415 binfmt_init(afp, errfunc, ldef, eval);
1418 static void ith_init(FILE *afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1420 my_ofmt = &of_ith;
1421 do_output = do_output_ith;
1422 binfmt_init(afp, errfunc, ldef, eval);
1425 static void srec_init(FILE *afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1427 my_ofmt = &of_srec;
1428 do_output = do_output_srec;
1429 binfmt_init(afp, errfunc, ldef, eval);
1432 static void binfmt_init(FILE *afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1434 fp = afp;
1435 error = errfunc;
1437 (void)eval; /* Don't warn that this parameter is unused. */
1438 (void)ldef; /* Placate optimizers. */
1440 maxbits = 64; /* Support 64-bit Segments */
1441 relocs = NULL;
1442 reloctail = &relocs;
1443 origin_defined = 0;
1444 no_seg_labels = NULL;
1445 nsl_tail = &no_seg_labels;
1446 format_mode = 1; /* Extended bin format
1447 * (set this to zero for old bin format). */
1449 /* Create default section (.text). */
1450 sections = last_section = nasm_malloc(sizeof(struct Section));
1451 last_section->next = NULL;
1452 last_section->name = nasm_strdup(".text");
1453 last_section->contents = saa_init(1L);
1454 last_section->follows = last_section->vfollows = 0;
1455 last_section->ifollows = NULL;
1456 last_section->length = 0;
1457 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1458 last_section->labels = NULL;
1459 last_section->labels_end = &(last_section->labels);
1460 last_section->start_index = seg_alloc();
1461 last_section->vstart_index = current_section = seg_alloc();
1464 /* Generate binary file output */
1465 static void do_output_bin(void)
1467 struct Section *s;
1468 uint64_t addr = origin;
1470 /* Write the progbits sections to the output file. */
1471 for (s = sections; s; s = s->next) {
1472 /* Skip non-progbits sections */
1473 if (!(s->flags & TYPE_PROGBITS))
1474 continue;
1475 /* Skip zero-length sections */
1476 if (s->length == 0)
1477 continue;
1479 /* Pad the space between sections. */
1480 nasm_assert(addr <= s->start);
1481 fwritezero(s->start - addr, fp);
1483 /* Write the section to the output file. */
1484 saa_fpwrite(s->contents, fp);
1486 /* Keep track of the current file position */
1487 addr = s->start + s->length;
1491 /* Generate Intel hex file output */
1492 static int write_ith_record(unsigned int len, uint16_t addr,
1493 uint8_t type, void *data)
1495 char buf[1+2+4+2+255*2+2+2];
1496 char *p = buf;
1497 uint8_t csum, *dptr = data;
1498 unsigned int i;
1500 nasm_assert(len <= 255);
1502 csum = len + addr + (addr >> 8) + type;
1503 for (i = 0; i < len; i++)
1504 csum += dptr[i];
1505 csum = -csum;
1507 p += sprintf(p, ":%02X%04X%02X", len, addr, type);
1508 for (i = 0; i < len; i++)
1509 p += sprintf(p, "%02X", dptr[i]);
1510 p += sprintf(p, "%02X\n", csum);
1512 if (fwrite(buf, 1, p-buf, fp) != (size_t)(p-buf))
1513 return -1;
1515 return 0;
1518 static void do_output_ith(void)
1520 uint8_t buf[32];
1521 struct Section *s;
1522 uint64_t addr, hiaddr, hilba;
1523 uint64_t length;
1524 unsigned int chunk;
1526 /* Write the progbits sections to the output file. */
1527 hilba = 0;
1528 for (s = sections; s; s = s->next) {
1529 /* Skip non-progbits sections */
1530 if (!(s->flags & TYPE_PROGBITS))
1531 continue;
1532 /* Skip zero-length sections */
1533 if (s->length == 0)
1534 continue;
1536 addr = s->start;
1537 length = s->length;
1538 saa_rewind(s->contents);
1540 while (length) {
1541 hiaddr = addr >> 16;
1542 if (hiaddr != hilba) {
1543 buf[0] = hiaddr >> 8;
1544 buf[1] = hiaddr;
1545 write_ith_record(2, 0, 4, buf);
1546 hilba = hiaddr;
1549 chunk = 32 - (addr & 31);
1550 if (length < chunk)
1551 chunk = length;
1553 saa_rnbytes(s->contents, buf, chunk);
1554 write_ith_record(chunk, (uint16_t)addr, 0, buf);
1556 addr += chunk;
1557 length -= chunk;
1561 /* Write closing record */
1562 write_ith_record(0, 0, 1, NULL);
1565 /* Generate Motorola S-records */
1566 static int write_srecord(unsigned int len, unsigned int alen,
1567 uint32_t addr, uint8_t type, void *data)
1569 char buf[2+2+8+255*2+2+2];
1570 char *p = buf;
1571 uint8_t csum, *dptr = data;
1572 unsigned int i;
1574 nasm_assert(len <= 255);
1576 switch (alen) {
1577 case 2:
1578 addr &= 0xffff;
1579 break;
1580 case 3:
1581 addr &= 0xffffff;
1582 break;
1583 case 4:
1584 break;
1585 default:
1586 nasm_assert(0);
1587 break;
1590 csum = (len+alen+1) + addr + (addr >> 8) + (addr >> 16) + (addr >> 24);
1591 for (i = 0; i < len; i++)
1592 csum += dptr[i];
1593 csum = 0xff-csum;
1595 p += sprintf(p, "S%c%02X%0*X", type, len+alen+1, alen*2, addr);
1596 for (i = 0; i < len; i++)
1597 p += sprintf(p, "%02X", dptr[i]);
1598 p += sprintf(p, "%02X\n", csum);
1600 if (fwrite(buf, 1, p-buf, fp) != (size_t)(p-buf))
1601 return -1;
1603 return 0;
1606 static void do_output_srec(void)
1608 uint8_t buf[32];
1609 struct Section *s;
1610 uint64_t addr, maxaddr;
1611 uint64_t length;
1612 int alen;
1613 unsigned int chunk;
1614 char dtype, etype;
1616 maxaddr = 0;
1617 for (s = sections; s; s = s->next) {
1618 /* Skip non-progbits sections */
1619 if (!(s->flags & TYPE_PROGBITS))
1620 continue;
1621 /* Skip zero-length sections */
1622 if (s->length == 0)
1623 continue;
1625 addr = s->start + s->length - 1;
1626 if (addr > maxaddr)
1627 maxaddr = addr;
1630 if (maxaddr <= 0xffff) {
1631 alen = 2;
1632 dtype = '1'; /* S1 = 16-bit data */
1633 etype = '9'; /* S9 = 16-bit end */
1634 } else if (maxaddr <= 0xffffff) {
1635 alen = 3;
1636 dtype = '2'; /* S2 = 24-bit data */
1637 etype = '8'; /* S8 = 24-bit end */
1638 } else {
1639 alen = 4;
1640 dtype = '3'; /* S3 = 32-bit data */
1641 etype = '7'; /* S7 = 32-bit end */
1644 /* Write head record */
1645 write_srecord(0, 2, 0, '0', NULL);
1647 /* Write the progbits sections to the output file. */
1648 for (s = sections; s; s = s->next) {
1649 /* Skip non-progbits sections */
1650 if (!(s->flags & TYPE_PROGBITS))
1651 continue;
1652 /* Skip zero-length sections */
1653 if (s->length == 0)
1654 continue;
1656 addr = s->start;
1657 length = s->length;
1658 saa_rewind(s->contents);
1660 while (length) {
1661 chunk = 32 - (addr & 31);
1662 if (length < chunk)
1663 chunk = length;
1665 saa_rnbytes(s->contents, buf, chunk);
1666 write_srecord(chunk, alen, (uint32_t)addr, dtype, buf);
1668 addr += chunk;
1669 length -= chunk;
1673 /* Write closing record */
1674 write_srecord(0, alen, 0, etype, NULL);
1678 struct ofmt of_bin = {
1679 "flat-form binary files (e.g. DOS .COM, .SYS)",
1680 "bin",
1682 null_debug_arr,
1683 &null_debug_form,
1684 bin_stdmac,
1685 bin_init,
1686 bin_set_info,
1687 bin_out,
1688 bin_deflabel,
1689 bin_secname,
1690 bin_segbase,
1691 bin_directive,
1692 bin_filename,
1693 bin_cleanup
1696 struct ofmt of_ith = {
1697 "Intel hex",
1698 "ith",
1699 OFMT_TEXT,
1700 null_debug_arr,
1701 &null_debug_form,
1702 bin_stdmac,
1703 ith_init,
1704 bin_set_info,
1705 bin_out,
1706 bin_deflabel,
1707 bin_secname,
1708 bin_segbase,
1709 bin_directive,
1710 ith_filename,
1711 bin_cleanup
1714 struct ofmt of_srec = {
1715 "Motorola S-records",
1716 "srec",
1718 null_debug_arr,
1719 &null_debug_form,
1720 bin_stdmac,
1721 srec_init,
1722 bin_set_info,
1723 bin_out,
1724 bin_deflabel,
1725 bin_secname,
1726 bin_segbase,
1727 bin_directive,
1728 srec_filename,
1729 bin_cleanup
1732 #endif /* #ifdef OF_BIN */