Add strlcpy() function
[nasm/nasm.git] / output / outbin.c
blob89c8ecf956e1dcf4a740ecc2f27f3d690f542fa9
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 extern char *stdscan_bufptr;
157 static uint8_t format_mode; /* 0 = original bin, 1 = extended bin */
158 static int32_t current_section; /* only really needed if format_mode = 0 */
159 static uint64_t origin;
160 static int origin_defined;
162 /* Stuff we need for map-file generation. */
163 #define MAP_ORIGIN 1
164 #define MAP_SUMMARY 2
165 #define MAP_SECTIONS 4
166 #define MAP_SYMBOLS 8
167 static int map_control = 0;
168 static char *infile, *outfile;
170 extern macros_t bin_stdmac[];
172 static void add_reloc(struct Section *s, int32_t bytes, int32_t secref,
173 int32_t secrel)
175 struct Reloc *r;
177 r = *reloctail = nasm_malloc(sizeof(struct Reloc));
178 reloctail = &r->next;
179 r->next = NULL;
180 r->posn = s->length;
181 r->bytes = bytes;
182 r->secref = secref;
183 r->secrel = secrel;
184 r->target = s;
187 static struct Section *find_section_by_name(const char *name)
189 struct Section *s;
191 list_for_each(s, sections)
192 if (!strcmp(s->name, name))
193 break;
194 return s;
197 static struct Section *find_section_by_index(int32_t index)
199 struct Section *s;
201 list_for_each(s, sections)
202 if ((index == s->vstart_index) || (index == s->start_index))
203 break;
204 return s;
207 static struct Section *create_section(char *name)
208 { /* Create a new section. */
209 last_section->next = nasm_malloc(sizeof(struct Section));
210 last_section->next->ifollows = last_section;
211 last_section = last_section->next;
212 last_section->labels = NULL;
213 last_section->labels_end = &(last_section->labels);
215 /* Initialize section attributes. */
216 last_section->name = nasm_strdup(name);
217 last_section->contents = saa_init(1L);
218 last_section->follows = last_section->vfollows = 0;
219 last_section->length = 0;
220 last_section->flags = 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 fprintf(stdout,
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 = ((origin + sections->align - 1) &
402 ~(sections->align - 1));
403 } else {
404 sections->start = origin;
406 } else {
407 if (!(sections->flags & START_DEFINED))
408 sections->start = 0;
409 origin = sections->start;
411 sections->flags |= START_DEFINED;
413 /* Make sure each section has an explicit start address. If it
414 * doesn't, then compute one based its alignment and the end of
415 * the previous section. */
416 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
417 * (has a defined start address, and is not zero length). */
418 if (g == s)
419 for (s = g->next;
420 s && ((s->length == 0) || !(s->flags & START_DEFINED));
421 s = s->next) ;
422 /* Compute the start address of this section, if necessary. */
423 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
424 if (!(g->flags & ALIGN_DEFINED)) {
425 g->align = 4;
426 g->flags |= ALIGN_DEFINED;
428 /* Set the section start address. */
429 g->start = (pend + g->align - 1) & ~(g->align - 1);
430 g->flags |= START_DEFINED;
432 /* Ugly special case for progbits sections' virtual attributes:
433 * If there is a defined valign, but no vstart and no vfollows, then
434 * we valign after the previous progbits section. This case doesn't
435 * really make much sense for progbits sections with a defined start
436 * address, but it is possible and we must do *something*.
437 * Not-so-ugly special case:
438 * If a progbits section has no virtual attributes, we set the
439 * vstart equal to the start address. */
440 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
441 if (g->flags & VALIGN_DEFINED)
442 g->vstart = (pend + g->valign - 1) & ~(g->valign - 1);
443 else
444 g->vstart = g->start;
445 g->flags |= VSTART_DEFINED;
447 /* Ignore zero-length sections. */
448 if (g->start < pend)
449 continue;
450 /* Compute the span of this section. */
451 pend = g->start + g->length;
452 /* Check for section overlap. */
453 if (s) {
454 if (s->start < origin)
455 nasm_error(ERR_FATAL|ERR_NOFILE, "section %s beings before program origin",
456 s->name);
457 if (g->start > s->start)
458 nasm_error(ERR_FATAL|ERR_NOFILE, "sections %s ~ %s and %s overlap!",
459 gs->name, g->name, s->name);
460 if (pend > s->start)
461 nasm_error(ERR_FATAL|ERR_NOFILE, "sections %s and %s overlap!",
462 g->name, s->name);
464 /* Remember this section as the latest >0 length section. */
465 gs = g;
468 /* Step 4: Compute vstart addresses for all sections. */
470 /* Attach the nobits sections to the end of the progbits sections. */
471 for (s = sections; s->next; s = s->next) ;
472 s->next = nobits;
473 last_progbits = s;
475 * Scan for sections that don't have a vstart address. If we find
476 * one we'll attempt to compute its vstart. If we can't compute
477 * the vstart, we leave it alone and come back to it in a
478 * subsequent scan. We continue scanning and re-scanning until
479 * we've gone one full cycle without computing any vstarts.
481 do { /* Do one full scan of the sections list. */
482 for (h = 0, g = sections; g; g = g->next) {
483 if (g->flags & VSTART_DEFINED)
484 continue;
485 /* Find the section that this one virtually follows. */
486 if (g->flags & VFOLLOWS_DEFINED) {
487 for (s = sections; s && strcmp(g->vfollows, s->name);
488 s = s->next) ;
489 if (!s)
490 nasm_error(ERR_FATAL|ERR_NOFILE,
491 "section %s vfollows unknown section (%s)",
492 g->name, g->vfollows);
493 } else if (g->ifollows != NULL)
494 for (s = sections; s && (s != g->ifollows); s = s->next) ;
495 /* The .bss section is the only one with ifollows = NULL.
496 In this case we implicitly follow the last progbits
497 section. */
498 else
499 s = last_progbits;
501 /* If the section we're following has a vstart, we can proceed. */
502 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
503 if (!(g->flags & VALIGN_DEFINED)) {
504 g->valign = 4;
505 g->flags |= VALIGN_DEFINED;
507 /* Compute the vstart address. */
508 g->vstart = (s->vstart + s->length + g->valign - 1)
509 & ~(g->valign - 1);
510 g->flags |= VSTART_DEFINED;
511 h++;
512 /* Start and vstart mean the same thing for nobits sections. */
513 if (g->flags & TYPE_NOBITS)
514 g->start = g->vstart;
517 } while (h);
519 /* Now check for any circular vfollows references, which will manifest
520 * themselves as sections without a defined vstart. */
521 for (h = 0, s = sections; s; s = s->next) {
522 if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
523 * no-no, but we'll throw a fatal one eventually so it's ok. */
524 nasm_error(ERR_NONFATAL, "cannot compute vstart for section %s",
525 s->name);
526 h++;
529 if (h)
530 nasm_error(ERR_FATAL|ERR_NOFILE, "circular vfollows path detected");
532 #ifdef DEBUG
533 fprintf(stdout,
534 "bin_cleanup: Confirm final section order for output file:\n");
535 for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
536 h++, s = s->next)
537 fprintf(stdout, "%i. %s\n", h, s->name);
538 #endif
540 /* Step 5: Apply relocations. */
542 /* Prepare the sections for relocating. */
543 list_for_each(s, sections)
544 saa_rewind(s->contents);
545 /* Apply relocations. */
546 list_for_each(r, relocs) {
547 uint8_t *p, *q, mydata[8];
548 int64_t l;
550 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
551 p = q = mydata;
552 l = *p++;
554 if (r->bytes > 1) {
555 l += ((int64_t)*p++) << 8;
556 if (r->bytes >= 4) {
557 l += ((int64_t)*p++) << 16;
558 l += ((int64_t)*p++) << 24;
560 if (r->bytes == 8) {
561 l += ((int64_t)*p++) << 32;
562 l += ((int64_t)*p++) << 40;
563 l += ((int64_t)*p++) << 48;
564 l += ((int64_t)*p++) << 56;
568 s = find_section_by_index(r->secref);
569 if (s) {
570 if (r->secref == s->start_index)
571 l += s->start;
572 else
573 l += s->vstart;
575 s = find_section_by_index(r->secrel);
576 if (s) {
577 if (r->secrel == s->start_index)
578 l -= s->start;
579 else
580 l -= s->vstart;
583 if (r->bytes >= 4)
584 WRITEDLONG(q, l);
585 else if (r->bytes == 2)
586 WRITESHORT(q, l);
587 else
588 *q++ = (uint8_t)(l & 0xFF);
589 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
592 /* Step 6: Write the section data to the output file. */
593 do_output();
595 /* Step 7: Generate the map file. */
597 if (map_control) {
598 static const char not_defined[] = "not defined";
600 /* Display input and output file names. */
601 fprintf(rf, "\n- NASM Map file ");
602 for (h = 63; h; h--)
603 fputc('-', rf);
604 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
605 infile, outfile);
607 if (map_control & MAP_ORIGIN) { /* Display program origin. */
608 fprintf(rf, "-- Program origin ");
609 for (h = 61; h; h--)
610 fputc('-', rf);
611 fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
613 /* Display sections summary. */
614 if (map_control & MAP_SUMMARY) {
615 fprintf(rf, "-- Sections (summary) ");
616 for (h = 57; h; h--)
617 fputc('-', rf);
618 fprintf(rf, "\n\nVstart Start Stop "
619 "Length Class Name\n");
620 list_for_each(s, sections) {
621 fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
622 s->vstart, s->start, s->start + s->length,
623 s->length);
624 if (s->flags & TYPE_PROGBITS)
625 fprintf(rf, "progbits ");
626 else
627 fprintf(rf, "nobits ");
628 fprintf(rf, "%s\n", s->name);
630 fprintf(rf, "\n");
632 /* Display detailed section information. */
633 if (map_control & MAP_SECTIONS) {
634 fprintf(rf, "-- Sections (detailed) ");
635 for (h = 56; h; h--)
636 fputc('-', rf);
637 fprintf(rf, "\n\n");
638 list_for_each(s, sections) {
639 fprintf(rf, "---- Section %s ", s->name);
640 for (h = 65 - strlen(s->name); h; h--)
641 fputc('-', rf);
642 fprintf(rf, "\n\nclass: ");
643 if (s->flags & TYPE_PROGBITS)
644 fprintf(rf, "progbits");
645 else
646 fprintf(rf, "nobits");
647 fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
648 "\nalign: ", s->length, s->start);
649 if (s->flags & ALIGN_DEFINED)
650 fprintf(rf, "%16"PRIX64"", s->align);
651 else
652 fputs(not_defined, rf);
653 fprintf(rf, "\nfollows: ");
654 if (s->flags & FOLLOWS_DEFINED)
655 fprintf(rf, "%s", s->follows);
656 else
657 fputs(not_defined, rf);
658 fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
659 if (s->flags & VALIGN_DEFINED)
660 fprintf(rf, "%16"PRIX64"", s->valign);
661 else
662 fputs(not_defined, rf);
663 fprintf(rf, "\nvfollows: ");
664 if (s->flags & VFOLLOWS_DEFINED)
665 fprintf(rf, "%s", s->vfollows);
666 else
667 fputs(not_defined, rf);
668 fprintf(rf, "\n\n");
671 /* Display symbols information. */
672 if (map_control & MAP_SYMBOLS) {
673 int32_t segment;
674 int64_t offset;
676 fprintf(rf, "-- Symbols ");
677 for (h = 68; h; h--)
678 fputc('-', rf);
679 fprintf(rf, "\n\n");
680 if (no_seg_labels) {
681 fprintf(rf, "---- No Section ");
682 for (h = 63; h; h--)
683 fputc('-', rf);
684 fprintf(rf, "\n\nValue Name\n");
685 list_for_each(l, no_seg_labels) {
686 lookup_label(l->name, &segment, &offset);
687 fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
689 fprintf(rf, "\n\n");
691 list_for_each(s, sections) {
692 if (s->labels) {
693 fprintf(rf, "---- Section %s ", s->name);
694 for (h = 65 - strlen(s->name); h; h--)
695 fputc('-', rf);
696 fprintf(rf, "\n\nReal Virtual Name\n");
697 list_for_each(l, s->labels) {
698 lookup_label(l->name, &segment, &offset);
699 fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
700 s->start + offset, s->vstart + offset,
701 l->name);
703 fprintf(rf, "\n");
709 /* Close the report file. */
710 if (map_control && (rf != stdout) && (rf != stderr))
711 fclose(rf);
713 /* Step 8: Release all allocated memory. */
715 /* Free sections, label pointer structs, etc.. */
716 while (sections) {
717 s = sections;
718 sections = s->next;
719 saa_free(s->contents);
720 nasm_free(s->name);
721 if (s->flags & FOLLOWS_DEFINED)
722 nasm_free(s->follows);
723 if (s->flags & VFOLLOWS_DEFINED)
724 nasm_free(s->vfollows);
725 while (s->labels) {
726 l = s->labels;
727 s->labels = l->next;
728 nasm_free(l);
730 nasm_free(s);
733 /* Free no-section labels. */
734 while (no_seg_labels) {
735 l = no_seg_labels;
736 no_seg_labels = l->next;
737 nasm_free(l);
740 /* Free relocation structures. */
741 while (relocs) {
742 r = relocs->next;
743 nasm_free(relocs);
744 relocs = r;
748 static void bin_out(int32_t segto, const void *data,
749 enum out_type type, uint64_t size,
750 int32_t segment, int32_t wrt)
752 uint8_t *p, mydata[8];
753 struct Section *s;
755 if (wrt != NO_SEG) {
756 wrt = NO_SEG; /* continue to do _something_ */
757 nasm_error(ERR_NONFATAL, "WRT not supported by binary output format");
760 /* Handle absolute-assembly (structure definitions). */
761 if (segto == NO_SEG) {
762 if (type != OUT_RESERVE)
763 nasm_error(ERR_NONFATAL, "attempt to assemble code in"
764 " [ABSOLUTE] space");
765 return;
768 /* Find the segment we are targeting. */
769 s = find_section_by_index(segto);
770 if (!s)
771 nasm_error(ERR_PANIC, "code directed to nonexistent segment?");
773 /* "Smart" section-type adaptation code. */
774 if (!(s->flags & TYPE_DEFINED)) {
775 if (type == OUT_RESERVE)
776 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
777 else
778 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
781 if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
782 nasm_error(ERR_WARNING, "attempt to initialize memory in a"
783 " nobits section: ignored");
785 if (type == OUT_ADDRESS) {
786 if (segment != NO_SEG && !find_section_by_index(segment)) {
787 if (segment % 2)
788 nasm_error(ERR_NONFATAL, "binary output format does not support"
789 " segment base references");
790 else
791 nasm_error(ERR_NONFATAL, "binary output format does not support"
792 " external references");
793 segment = NO_SEG;
795 if (s->flags & TYPE_PROGBITS) {
796 if (segment != NO_SEG)
797 add_reloc(s, size, segment, -1L);
798 p = mydata;
799 WRITEADDR(p, *(int64_t *)data, size);
800 saa_wbytes(s->contents, mydata, size);
802 s->length += size;
803 } else if (type == OUT_RAWDATA) {
804 if (s->flags & TYPE_PROGBITS)
805 saa_wbytes(s->contents, data, size);
806 s->length += size;
807 } else if (type == OUT_RESERVE) {
808 if (s->flags & TYPE_PROGBITS) {
809 nasm_error(ERR_WARNING, "uninitialized space declared in"
810 " %s section: zeroing", s->name);
811 saa_wbytes(s->contents, NULL, size);
813 s->length += size;
814 } else if (type == OUT_REL2ADR || type == OUT_REL4ADR ||
815 type == OUT_REL8ADR) {
816 int64_t addr = *(int64_t *)data - size;
817 size = realsize(type, size);
818 if (segment != NO_SEG && !find_section_by_index(segment)) {
819 if (segment % 2)
820 nasm_error(ERR_NONFATAL, "binary output format does not support"
821 " segment base references");
822 else
823 nasm_error(ERR_NONFATAL, "binary output format does not support"
824 " external references");
825 segment = NO_SEG;
827 if (s->flags & TYPE_PROGBITS) {
828 add_reloc(s, size, segment, segto);
829 p = mydata;
830 WRITEADDR(p, addr - s->length, size);
831 saa_wbytes(s->contents, mydata, size);
833 s->length += size;
837 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
838 int is_global, char *special)
840 (void)segment; /* Don't warn that this parameter is unused */
841 (void)offset; /* Don't warn that this parameter is unused */
843 if (special)
844 nasm_error(ERR_NONFATAL, "binary format does not support any"
845 " special symbol types");
846 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
847 nasm_error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
848 else if (is_global == 2)
849 nasm_error(ERR_NONFATAL, "binary output format does not support common"
850 " variables");
851 else {
852 struct Section *s;
853 struct bin_label ***ltp;
855 /* Remember label definition so we can look it up later when
856 * creating the map file. */
857 s = find_section_by_index(segment);
858 if (s)
859 ltp = &(s->labels_end);
860 else
861 ltp = &nsl_tail;
862 (**ltp) = nasm_malloc(sizeof(struct bin_label));
863 (**ltp)->name = name;
864 (**ltp)->next = NULL;
865 *ltp = &((**ltp)->next);
870 /* These constants and the following function are used
871 * by bin_secname() to parse attribute assignments. */
873 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
874 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
875 ATTRIB_NOBITS, ATTRIB_PROGBITS
878 static int bin_read_attribute(char **line, int *attribute,
879 uint64_t *value)
881 expr *e;
882 int attrib_name_size;
883 struct tokenval tokval;
884 char *exp;
886 /* Skip whitespace. */
887 while (**line && nasm_isspace(**line))
888 (*line)++;
889 if (!**line)
890 return 0;
892 /* Figure out what attribute we're reading. */
893 if (!nasm_strnicmp(*line, "align=", 6)) {
894 *attribute = ATTRIB_ALIGN;
895 attrib_name_size = 6;
896 } else if (format_mode) {
897 if (!nasm_strnicmp(*line, "start=", 6)) {
898 *attribute = ATTRIB_START;
899 attrib_name_size = 6;
900 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
901 *attribute = ATTRIB_FOLLOWS;
902 *line += 8;
903 return 1;
904 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
905 *attribute = ATTRIB_VSTART;
906 attrib_name_size = 7;
907 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
908 *attribute = ATTRIB_VALIGN;
909 attrib_name_size = 7;
910 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
911 *attribute = ATTRIB_VFOLLOWS;
912 *line += 9;
913 return 1;
914 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
915 (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
916 *attribute = ATTRIB_NOBITS;
917 *line += 6;
918 return 1;
919 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
920 (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
921 *attribute = ATTRIB_PROGBITS;
922 *line += 8;
923 return 1;
924 } else
925 return 0;
926 } else
927 return 0;
929 /* Find the end of the expression. */
930 if ((*line)[attrib_name_size] != '(') {
931 /* Single term (no parenthesis). */
932 exp = *line += attrib_name_size;
933 while (**line && !nasm_isspace(**line))
934 (*line)++;
935 if (**line) {
936 **line = '\0';
937 (*line)++;
939 } else {
940 char c;
941 int pcount = 1;
943 /* Full expression (delimited by parenthesis) */
944 exp = *line += attrib_name_size + 1;
945 while (1) {
946 (*line) += strcspn(*line, "()'\"");
947 if (**line == '(') {
948 ++(*line);
949 ++pcount;
951 if (**line == ')') {
952 ++(*line);
953 --pcount;
954 if (!pcount)
955 break;
957 if ((**line == '"') || (**line == '\'')) {
958 c = **line;
959 while (**line) {
960 ++(*line);
961 if (**line == c)
962 break;
964 if (!**line) {
965 nasm_error(ERR_NONFATAL,
966 "invalid syntax in `section' directive");
967 return -1;
969 ++(*line);
971 if (!**line) {
972 nasm_error(ERR_NONFATAL, "expecting `)'");
973 return -1;
976 *(*line - 1) = '\0'; /* Terminate the expression. */
979 /* Check for no value given. */
980 if (!*exp) {
981 nasm_error(ERR_WARNING, "No value given to attribute in"
982 " `section' directive");
983 return -1;
986 /* Read and evaluate the expression. */
987 stdscan_reset();
988 stdscan_bufptr = exp;
989 tokval.t_type = TOKEN_INVALID;
990 e = evaluate(stdscan, NULL, &tokval, NULL, 1, nasm_error, NULL);
991 if (e) {
992 if (!is_really_simple(e)) {
993 nasm_error(ERR_NONFATAL, "section attribute value must be"
994 " a critical expression");
995 return -1;
997 } else {
998 nasm_error(ERR_NONFATAL, "Invalid attribute value"
999 " specified in `section' directive.");
1000 return -1;
1002 *value = (uint64_t)reloc_value(e);
1003 return 1;
1006 static void bin_assign_attributes(struct Section *sec, char *astring)
1008 int attribute, check;
1009 uint64_t value;
1010 char *p;
1012 while (1) { /* Get the next attribute. */
1013 check = bin_read_attribute(&astring, &attribute, &value);
1014 /* Skip bad attribute. */
1015 if (check == -1)
1016 continue;
1017 /* Unknown section attribute, so skip it and warn the user. */
1018 if (!check) {
1019 if (!*astring)
1020 break; /* End of line. */
1021 else {
1022 p = astring;
1023 while (*astring && !nasm_isspace(*astring))
1024 astring++;
1025 if (*astring) {
1026 *astring = '\0';
1027 astring++;
1029 nasm_error(ERR_WARNING, "ignoring unknown section attribute:"
1030 " \"%s\"", p);
1032 continue;
1035 switch (attribute) { /* Handle nobits attribute. */
1036 case ATTRIB_NOBITS:
1037 if ((sec->flags & TYPE_DEFINED)
1038 && (sec->flags & TYPE_PROGBITS))
1039 nasm_error(ERR_NONFATAL,
1040 "attempt to change section type"
1041 " from progbits to nobits");
1042 else
1043 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1044 continue;
1046 /* Handle progbits attribute. */
1047 case ATTRIB_PROGBITS:
1048 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1049 nasm_error(ERR_NONFATAL, "attempt to change section type"
1050 " from nobits to progbits");
1051 else
1052 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1053 continue;
1055 /* Handle align attribute. */
1056 case ATTRIB_ALIGN:
1057 if (!format_mode && (!strcmp(sec->name, ".text")))
1058 nasm_error(ERR_NONFATAL, "cannot specify an alignment"
1059 " to the .text section");
1060 else {
1061 if (!value || ((value - 1) & value))
1062 nasm_error(ERR_NONFATAL, "argument to `align' is not a"
1063 " power of two");
1064 else { /* Alignment is already satisfied if the previous
1065 * align value is greater. */
1066 if ((sec->flags & ALIGN_DEFINED)
1067 && (value < sec->align))
1068 value = sec->align;
1070 /* Don't allow a conflicting align value. */
1071 if ((sec->flags & START_DEFINED)
1072 && (sec->start & (value - 1)))
1073 nasm_error(ERR_NONFATAL,
1074 "`align' value conflicts "
1075 "with section start address");
1076 else {
1077 sec->align = value;
1078 sec->flags |= ALIGN_DEFINED;
1082 continue;
1084 /* Handle valign attribute. */
1085 case ATTRIB_VALIGN:
1086 if (!value || ((value - 1) & value))
1087 nasm_error(ERR_NONFATAL, "argument to `valign' is not a"
1088 " power of two");
1089 else { /* Alignment is already satisfied if the previous
1090 * align value is greater. */
1091 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1092 value = sec->valign;
1094 /* Don't allow a conflicting valign value. */
1095 if ((sec->flags & VSTART_DEFINED)
1096 && (sec->vstart & (value - 1)))
1097 nasm_error(ERR_NONFATAL,
1098 "`valign' value conflicts "
1099 "with `vstart' address");
1100 else {
1101 sec->valign = value;
1102 sec->flags |= VALIGN_DEFINED;
1105 continue;
1107 /* Handle start attribute. */
1108 case ATTRIB_START:
1109 if (sec->flags & FOLLOWS_DEFINED)
1110 nasm_error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1111 " section attributes");
1112 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1113 nasm_error(ERR_NONFATAL, "section start address redefined");
1114 else {
1115 sec->start = value;
1116 sec->flags |= START_DEFINED;
1117 if (sec->flags & ALIGN_DEFINED) {
1118 if (sec->start & (sec->align - 1))
1119 nasm_error(ERR_NONFATAL, "`start' address conflicts"
1120 " with section alignment");
1121 sec->flags ^= ALIGN_DEFINED;
1124 continue;
1126 /* Handle vstart attribute. */
1127 case ATTRIB_VSTART:
1128 if (sec->flags & VFOLLOWS_DEFINED)
1129 nasm_error(ERR_NONFATAL,
1130 "cannot combine `vstart' and `vfollows'"
1131 " section attributes");
1132 else if ((sec->flags & VSTART_DEFINED)
1133 && (value != sec->vstart))
1134 nasm_error(ERR_NONFATAL,
1135 "section virtual start address"
1136 " (vstart) redefined");
1137 else {
1138 sec->vstart = value;
1139 sec->flags |= VSTART_DEFINED;
1140 if (sec->flags & VALIGN_DEFINED) {
1141 if (sec->vstart & (sec->valign - 1))
1142 nasm_error(ERR_NONFATAL, "`vstart' address conflicts"
1143 " with `valign' value");
1144 sec->flags ^= VALIGN_DEFINED;
1147 continue;
1149 /* Handle follows attribute. */
1150 case ATTRIB_FOLLOWS:
1151 p = astring;
1152 astring += strcspn(astring, " \t");
1153 if (astring == p)
1154 nasm_error(ERR_NONFATAL, "expecting section name for `follows'"
1155 " attribute");
1156 else {
1157 *(astring++) = '\0';
1158 if (sec->flags & START_DEFINED)
1159 nasm_error(ERR_NONFATAL,
1160 "cannot combine `start' and `follows'"
1161 " section attributes");
1162 sec->follows = nasm_strdup(p);
1163 sec->flags |= FOLLOWS_DEFINED;
1165 continue;
1167 /* Handle vfollows attribute. */
1168 case ATTRIB_VFOLLOWS:
1169 if (sec->flags & VSTART_DEFINED)
1170 nasm_error(ERR_NONFATAL,
1171 "cannot combine `vstart' and `vfollows'"
1172 " section attributes");
1173 else {
1174 p = astring;
1175 astring += strcspn(astring, " \t");
1176 if (astring == p)
1177 nasm_error(ERR_NONFATAL,
1178 "expecting section name for `vfollows'"
1179 " attribute");
1180 else {
1181 *(astring++) = '\0';
1182 sec->vfollows = nasm_strdup(p);
1183 sec->flags |= VFOLLOWS_DEFINED;
1186 continue;
1191 static void bin_define_section_labels(void)
1193 static int labels_defined = 0;
1194 struct Section *sec;
1195 char *label_name;
1196 size_t base_len;
1198 if (labels_defined)
1199 return;
1200 list_for_each(sec, sections) {
1201 base_len = strlen(sec->name) + 8;
1202 label_name = nasm_malloc(base_len + 8);
1203 strcpy(label_name, "section.");
1204 strcpy(label_name + 8, sec->name);
1206 /* section.<name>.start */
1207 strcpy(label_name + base_len, ".start");
1208 define_label(label_name, sec->start_index, 0L, NULL, 0, 0);
1210 /* section.<name>.vstart */
1211 strcpy(label_name + base_len, ".vstart");
1212 define_label(label_name, sec->vstart_index, 0L, NULL, 0, 0);
1214 nasm_free(label_name);
1216 labels_defined = 1;
1219 static int32_t bin_secname(char *name, int pass, int *bits)
1221 char *p;
1222 struct Section *sec;
1224 /* bin_secname is called with *name = NULL at the start of each
1225 * pass. Use this opportunity to establish the default section
1226 * (default is BITS-16 ".text" segment).
1228 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1229 origin_defined = 0;
1230 list_for_each(sec, sections)
1231 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1232 ALIGN_DEFINED | VALIGN_DEFINED);
1234 /* Define section start and vstart labels. */
1235 if (format_mode && (pass != 1))
1236 bin_define_section_labels();
1238 /* Establish the default (.text) section. */
1239 *bits = 16;
1240 sec = find_section_by_name(".text");
1241 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1242 current_section = sec->vstart_index;
1243 return current_section;
1246 /* Attempt to find the requested section. If it does not
1247 * exist, create it. */
1248 p = name;
1249 while (*p && !nasm_isspace(*p))
1250 p++;
1251 if (*p)
1252 *p++ = '\0';
1253 sec = find_section_by_name(name);
1254 if (!sec) {
1255 sec = create_section(name);
1256 if (!strcmp(name, ".data"))
1257 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1258 else if (!strcmp(name, ".bss")) {
1259 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1260 sec->ifollows = NULL;
1261 } else if (!format_mode) {
1262 nasm_error(ERR_NONFATAL, "section name must be "
1263 ".text, .data, or .bss");
1264 return current_section;
1268 /* Handle attribute assignments. */
1269 if (pass != 1)
1270 bin_assign_attributes(sec, p);
1272 #ifndef ABIN_SMART_ADAPT
1273 /* The following line disables smart adaptation of
1274 * PROGBITS/NOBITS section types (it forces sections to
1275 * default to PROGBITS). */
1276 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1277 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1278 #endif
1280 /* Set the current section and return. */
1281 current_section = sec->vstart_index;
1282 return current_section;
1285 static int bin_directive(enum directives directive, char *args, int pass)
1287 switch (directive) {
1288 case D_ORG:
1290 struct tokenval tokval;
1291 uint64_t value;
1292 expr *e;
1294 stdscan_reset();
1295 stdscan_bufptr = args;
1296 tokval.t_type = TOKEN_INVALID;
1297 e = evaluate(stdscan, NULL, &tokval, NULL, 1, nasm_error, NULL);
1298 if (e) {
1299 if (!is_really_simple(e))
1300 nasm_error(ERR_NONFATAL, "org value must be a critical"
1301 " expression");
1302 else {
1303 value = reloc_value(e);
1304 /* Check for ORG redefinition. */
1305 if (origin_defined && (value != origin))
1306 nasm_error(ERR_NONFATAL, "program origin redefined");
1307 else {
1308 origin = value;
1309 origin_defined = 1;
1312 } else
1313 nasm_error(ERR_NONFATAL, "No or invalid offset specified"
1314 " in ORG directive.");
1315 return 1;
1317 case D_MAP:
1319 /* The 'map' directive allows the user to generate section
1320 * and symbol information to stdout, stderr, or to a file. */
1321 char *p;
1323 if (pass != 1)
1324 return 1;
1325 args += strspn(args, " \t");
1326 while (*args) {
1327 p = args;
1328 args += strcspn(args, " \t");
1329 if (*args != '\0')
1330 *(args++) = '\0';
1331 if (!nasm_stricmp(p, "all"))
1332 map_control |=
1333 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1334 else if (!nasm_stricmp(p, "brief"))
1335 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1336 else if (!nasm_stricmp(p, "sections"))
1337 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1338 else if (!nasm_stricmp(p, "segments"))
1339 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1340 else if (!nasm_stricmp(p, "symbols"))
1341 map_control |= MAP_SYMBOLS;
1342 else if (!rf) {
1343 if (!nasm_stricmp(p, "stdout"))
1344 rf = stdout;
1345 else if (!nasm_stricmp(p, "stderr"))
1346 rf = stderr;
1347 else { /* Must be a filename. */
1348 rf = fopen(p, "wt");
1349 if (!rf) {
1350 nasm_error(ERR_WARNING, "unable to open map file `%s'",
1352 map_control = 0;
1353 return 1;
1356 } else
1357 nasm_error(ERR_WARNING, "map file already specified");
1359 if (map_control == 0)
1360 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1361 if (!rf)
1362 rf = stdout;
1363 return 1;
1365 default:
1366 return 0;
1370 static void bin_filename(char *inname, char *outname)
1372 standard_extension(inname, outname, "");
1373 infile = inname;
1374 outfile = outname;
1377 static void ith_filename(char *inname, char *outname)
1379 standard_extension(inname, outname, ".ith");
1380 infile = inname;
1381 outfile = outname;
1384 static void srec_filename(char *inname, char *outname)
1386 standard_extension(inname, outname, ".srec");
1387 infile = inname;
1388 outfile = outname;
1391 static int32_t bin_segbase(int32_t segment)
1393 return segment;
1396 static int bin_set_info(enum geninfo type, char **val)
1398 (void)type;
1399 (void)val;
1400 return 0;
1403 struct ofmt of_bin, of_ith, of_srec;
1404 static void binfmt_init(void);
1405 static void do_output_bin(void);
1406 static void do_output_ith(void);
1407 static void do_output_srec(void);
1409 static void bin_init(void)
1411 do_output = do_output_bin;
1412 binfmt_init();
1415 static void ith_init(void)
1417 do_output = do_output_ith;
1418 binfmt_init();
1421 static void srec_init(void)
1423 do_output = do_output_srec;
1424 binfmt_init();
1427 static void binfmt_init(void)
1429 maxbits = 64; /* Support 64-bit Segments */
1430 relocs = NULL;
1431 reloctail = &relocs;
1432 origin_defined = 0;
1433 no_seg_labels = NULL;
1434 nsl_tail = &no_seg_labels;
1435 format_mode = 1; /* Extended bin format
1436 * (set this to zero for old bin format). */
1438 /* Create default section (.text). */
1439 sections = last_section = nasm_malloc(sizeof(struct Section));
1440 last_section->next = NULL;
1441 last_section->name = nasm_strdup(".text");
1442 last_section->contents = saa_init(1L);
1443 last_section->follows = last_section->vfollows = 0;
1444 last_section->ifollows = NULL;
1445 last_section->length = 0;
1446 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1447 last_section->labels = NULL;
1448 last_section->labels_end = &(last_section->labels);
1449 last_section->start_index = seg_alloc();
1450 last_section->vstart_index = current_section = seg_alloc();
1453 /* Generate binary file output */
1454 static void do_output_bin(void)
1456 struct Section *s;
1457 uint64_t addr = origin;
1459 /* Write the progbits sections to the output file. */
1460 list_for_each(s, sections) {
1461 /* Skip non-progbits sections */
1462 if (!(s->flags & TYPE_PROGBITS))
1463 continue;
1464 /* Skip zero-length sections */
1465 if (s->length == 0)
1466 continue;
1468 /* Pad the space between sections. */
1469 nasm_assert(addr <= s->start);
1470 fwritezero(s->start - addr, ofile);
1472 /* Write the section to the output file. */
1473 saa_fpwrite(s->contents, ofile);
1475 /* Keep track of the current file position */
1476 addr = s->start + s->length;
1480 /* Generate Intel hex file output */
1481 static int write_ith_record(unsigned int len, uint16_t addr,
1482 uint8_t type, void *data)
1484 char buf[1+2+4+2+255*2+2+2];
1485 char *p = buf;
1486 uint8_t csum, *dptr = data;
1487 unsigned int i;
1489 nasm_assert(len <= 255);
1491 csum = len + addr + (addr >> 8) + type;
1492 for (i = 0; i < len; i++)
1493 csum += dptr[i];
1494 csum = -csum;
1496 p += sprintf(p, ":%02X%04X%02X", len, addr, type);
1497 for (i = 0; i < len; i++)
1498 p += sprintf(p, "%02X", dptr[i]);
1499 p += sprintf(p, "%02X\n", csum);
1501 if (fwrite(buf, 1, p-buf, ofile) != (size_t)(p-buf))
1502 return -1;
1504 return 0;
1507 static void do_output_ith(void)
1509 uint8_t buf[32];
1510 struct Section *s;
1511 uint64_t addr, hiaddr, hilba;
1512 uint64_t length;
1513 unsigned int chunk;
1515 /* Write the progbits sections to the output file. */
1516 hilba = 0;
1517 list_for_each(s, sections) {
1518 /* Skip non-progbits sections */
1519 if (!(s->flags & TYPE_PROGBITS))
1520 continue;
1521 /* Skip zero-length sections */
1522 if (s->length == 0)
1523 continue;
1525 addr = s->start;
1526 length = s->length;
1527 saa_rewind(s->contents);
1529 while (length) {
1530 hiaddr = addr >> 16;
1531 if (hiaddr != hilba) {
1532 buf[0] = hiaddr >> 8;
1533 buf[1] = hiaddr;
1534 write_ith_record(2, 0, 4, buf);
1535 hilba = hiaddr;
1538 chunk = 32 - (addr & 31);
1539 if (length < chunk)
1540 chunk = length;
1542 saa_rnbytes(s->contents, buf, chunk);
1543 write_ith_record(chunk, (uint16_t)addr, 0, buf);
1545 addr += chunk;
1546 length -= chunk;
1550 /* Write closing record */
1551 write_ith_record(0, 0, 1, NULL);
1554 /* Generate Motorola S-records */
1555 static int write_srecord(unsigned int len, unsigned int alen,
1556 uint32_t addr, uint8_t type, void *data)
1558 char buf[2+2+8+255*2+2+2];
1559 char *p = buf;
1560 uint8_t csum, *dptr = data;
1561 unsigned int i;
1563 nasm_assert(len <= 255);
1565 switch (alen) {
1566 case 2:
1567 addr &= 0xffff;
1568 break;
1569 case 3:
1570 addr &= 0xffffff;
1571 break;
1572 case 4:
1573 break;
1574 default:
1575 nasm_assert(0);
1576 break;
1579 csum = (len+alen+1) + addr + (addr >> 8) + (addr >> 16) + (addr >> 24);
1580 for (i = 0; i < len; i++)
1581 csum += dptr[i];
1582 csum = 0xff-csum;
1584 p += sprintf(p, "S%c%02X%0*X", type, len+alen+1, alen*2, addr);
1585 for (i = 0; i < len; i++)
1586 p += sprintf(p, "%02X", dptr[i]);
1587 p += sprintf(p, "%02X\n", csum);
1589 if (fwrite(buf, 1, p-buf, ofile) != (size_t)(p-buf))
1590 return -1;
1592 return 0;
1595 static void do_output_srec(void)
1597 uint8_t buf[32];
1598 struct Section *s;
1599 uint64_t addr, maxaddr;
1600 uint64_t length;
1601 int alen;
1602 unsigned int chunk;
1603 char dtype, etype;
1605 maxaddr = 0;
1606 list_for_each(s, sections) {
1607 /* Skip non-progbits sections */
1608 if (!(s->flags & TYPE_PROGBITS))
1609 continue;
1610 /* Skip zero-length sections */
1611 if (s->length == 0)
1612 continue;
1614 addr = s->start + s->length - 1;
1615 if (addr > maxaddr)
1616 maxaddr = addr;
1619 if (maxaddr <= 0xffff) {
1620 alen = 2;
1621 dtype = '1'; /* S1 = 16-bit data */
1622 etype = '9'; /* S9 = 16-bit end */
1623 } else if (maxaddr <= 0xffffff) {
1624 alen = 3;
1625 dtype = '2'; /* S2 = 24-bit data */
1626 etype = '8'; /* S8 = 24-bit end */
1627 } else {
1628 alen = 4;
1629 dtype = '3'; /* S3 = 32-bit data */
1630 etype = '7'; /* S7 = 32-bit end */
1633 /* Write head record */
1634 write_srecord(0, 2, 0, '0', NULL);
1636 /* Write the progbits sections to the output file. */
1637 list_for_each(s, sections) {
1638 /* Skip non-progbits sections */
1639 if (!(s->flags & TYPE_PROGBITS))
1640 continue;
1641 /* Skip zero-length sections */
1642 if (s->length == 0)
1643 continue;
1645 addr = s->start;
1646 length = s->length;
1647 saa_rewind(s->contents);
1649 while (length) {
1650 chunk = 32 - (addr & 31);
1651 if (length < chunk)
1652 chunk = length;
1654 saa_rnbytes(s->contents, buf, chunk);
1655 write_srecord(chunk, alen, (uint32_t)addr, dtype, buf);
1657 addr += chunk;
1658 length -= chunk;
1662 /* Write closing record */
1663 write_srecord(0, alen, 0, etype, NULL);
1667 struct ofmt of_bin = {
1668 "flat-form binary files (e.g. DOS .COM, .SYS)",
1669 "bin",
1671 null_debug_arr,
1672 &null_debug_form,
1673 bin_stdmac,
1674 bin_init,
1675 bin_set_info,
1676 bin_out,
1677 bin_deflabel,
1678 bin_secname,
1679 bin_segbase,
1680 bin_directive,
1681 bin_filename,
1682 bin_cleanup
1685 struct ofmt of_ith = {
1686 "Intel hex",
1687 "ith",
1688 OFMT_TEXT,
1689 null_debug_arr,
1690 &null_debug_form,
1691 bin_stdmac,
1692 ith_init,
1693 bin_set_info,
1694 bin_out,
1695 bin_deflabel,
1696 bin_secname,
1697 bin_segbase,
1698 bin_directive,
1699 ith_filename,
1700 bin_cleanup
1703 struct ofmt of_srec = {
1704 "Motorola S-records",
1705 "srec",
1707 null_debug_arr,
1708 &null_debug_form,
1709 bin_stdmac,
1710 srec_init,
1711 bin_set_info,
1712 bin_out,
1713 bin_deflabel,
1714 bin_secname,
1715 bin_segbase,
1716 bin_directive,
1717 srec_filename,
1718 bin_cleanup
1721 #endif /* #ifdef OF_BIN */