nasmlib/file.c: Windows _chsize_s() *returns* errno
[nasm.git] / output / outbin.c
blob3e1ec28662711f77e0aab6fece5edeac929fb427
1 /* ----------------------------------------------------------------------- *
2 *
3 * Copyright 1996-2013 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>
83 #include "nasm.h"
84 #include "nasmlib.h"
85 #include "saa.h"
86 #include "stdscan.h"
87 #include "labels.h"
88 #include "eval.h"
89 #include "output/outform.h"
90 #include "output/outlib.h"
92 #ifdef OF_BIN
94 static FILE *rf = NULL;
95 static void (*do_output)(void);
97 /* Section flags keep track of which attributes the user has defined. */
98 #define START_DEFINED 0x001
99 #define ALIGN_DEFINED 0x002
100 #define FOLLOWS_DEFINED 0x004
101 #define VSTART_DEFINED 0x008
102 #define VALIGN_DEFINED 0x010
103 #define VFOLLOWS_DEFINED 0x020
104 #define TYPE_DEFINED 0x040
105 #define TYPE_PROGBITS 0x080
106 #define TYPE_NOBITS 0x100
108 /* This struct is used to keep track of symbols for map-file generation. */
109 static struct bin_label {
110 char *name;
111 struct bin_label *next;
112 } *no_seg_labels, **nsl_tail;
114 static struct Section {
115 char *name;
116 struct SAA *contents;
117 int64_t length; /* section length in bytes */
119 /* Section attributes */
120 int flags; /* see flag definitions above */
121 uint64_t align; /* section alignment */
122 uint64_t valign; /* notional section alignment */
123 uint64_t start; /* section start address */
124 uint64_t vstart; /* section virtual start address */
125 char *follows; /* the section that this one will follow */
126 char *vfollows; /* the section that this one will notionally follow */
127 int32_t start_index; /* NASM section id for non-relocated version */
128 int32_t vstart_index; /* the NASM section id */
130 struct bin_label *labels; /* linked-list of label handles for map output. */
131 struct bin_label **labels_end; /* Holds address of end of labels list. */
132 struct Section *prev; /* Points to previous section (implicit follows). */
133 struct Section *next; /* This links sections with a defined start address. */
135 /* The extended bin format allows for sections to have a "virtual"
136 * start address. This is accomplished by creating two sections:
137 * one beginning at the Load Memory Address and the other beginning
138 * at the Virtual Memory Address. The LMA section is only used to
139 * define the section.<section_name>.start label, but there isn't
140 * any other good way for us to handle that label.
143 } *sections, *last_section;
145 static struct Reloc {
146 struct Reloc *next;
147 int32_t posn;
148 int32_t bytes;
149 int32_t secref;
150 int32_t secrel;
151 struct Section *target;
152 } *relocs, **reloctail;
154 static uint64_t origin;
155 static int origin_defined;
157 /* Stuff we need for map-file generation. */
158 #define MAP_ORIGIN 1
159 #define MAP_SUMMARY 2
160 #define MAP_SECTIONS 4
161 #define MAP_SYMBOLS 8
162 static int map_control = 0;
163 static char *infile, *outfile;
165 extern macros_t bin_stdmac[];
167 static void add_reloc(struct Section *s, int32_t bytes, int32_t secref,
168 int32_t secrel)
170 struct Reloc *r;
172 r = *reloctail = nasm_malloc(sizeof(struct Reloc));
173 reloctail = &r->next;
174 r->next = NULL;
175 r->posn = s->length;
176 r->bytes = bytes;
177 r->secref = secref;
178 r->secrel = secrel;
179 r->target = s;
182 static struct Section *find_section_by_name(const char *name)
184 struct Section *s;
186 list_for_each(s, sections)
187 if (!strcmp(s->name, name))
188 break;
189 return s;
192 static struct Section *find_section_by_index(int32_t index)
194 struct Section *s;
196 list_for_each(s, sections)
197 if ((index == s->vstart_index) || (index == s->start_index))
198 break;
199 return s;
202 static struct Section *create_section(char *name)
204 struct Section *s = nasm_zalloc(sizeof(*s));
206 s->prev = last_section;
207 s->name = nasm_strdup(name);
208 s->labels_end = &(s->labels);
209 s->contents = saa_init(1L);
211 /* Register our sections with NASM. */
212 s->vstart_index = seg_alloc();
213 s->start_index = seg_alloc();
215 /* FIXME: Append to a tail, we need some helper */
216 last_section->next = s;
217 last_section = s;
219 return last_section;
222 static void bin_cleanup(void)
224 struct Section *g, **gp;
225 struct Section *gs = NULL, **gsp;
226 struct Section *s, **sp;
227 struct Section *nobits = NULL, **nt;
228 struct Section *last_progbits;
229 struct bin_label *l;
230 struct Reloc *r;
231 uint64_t pend;
232 int h;
234 #ifdef DEBUG
235 nasm_error(ERR_DEBUG,
236 "bin_cleanup: Sections were initially referenced in this order:\n");
237 for (h = 0, s = sections; s; h++, s = s->next)
238 fprintf(stdout, "%i. %s\n", h, s->name);
239 #endif
241 /* Assembly has completed, so now we need to generate the output file.
242 * Step 1: Separate progbits and nobits sections into separate lists.
243 * Step 2: Sort the progbits sections into their output order.
244 * Step 3: Compute start addresses for all progbits sections.
245 * Step 4: Compute vstart addresses for all sections.
246 * Step 5: Apply relocations.
247 * Step 6: Write the sections' data to the output file.
248 * Step 7: Generate the map file.
249 * Step 8: Release all allocated memory.
252 /* To do: Smart section-type adaptation could leave some empty sections
253 * without a defined type (progbits/nobits). Won't fix now since this
254 * feature will be disabled. */
256 /* Step 1: Split progbits and nobits sections into separate lists. */
258 nt = &nobits;
259 /* Move nobits sections into a separate list. Also pre-process nobits
260 * sections' attributes. */
261 for (sp = &sections->next, s = sections->next; s; s = *sp) { /* Skip progbits sections. */
262 if (s->flags & TYPE_PROGBITS) {
263 sp = &s->next;
264 continue;
266 /* Do some special pre-processing on nobits sections' attributes. */
267 if (s->flags & (START_DEFINED | ALIGN_DEFINED | FOLLOWS_DEFINED)) { /* Check for a mixture of real and virtual section attributes. */
268 if (s->flags & (VSTART_DEFINED | VALIGN_DEFINED |
269 VFOLLOWS_DEFINED))
270 nasm_fatal(ERR_NOFILE,
271 "cannot mix real and virtual attributes"
272 " in nobits section (%s)", s->name);
273 /* Real and virtual attributes mean the same thing for nobits sections. */
274 if (s->flags & START_DEFINED) {
275 s->vstart = s->start;
276 s->flags |= VSTART_DEFINED;
278 if (s->flags & ALIGN_DEFINED) {
279 s->valign = s->align;
280 s->flags |= VALIGN_DEFINED;
282 if (s->flags & FOLLOWS_DEFINED) {
283 s->vfollows = s->follows;
284 s->flags |= VFOLLOWS_DEFINED;
285 s->flags &= ~FOLLOWS_DEFINED;
288 /* Every section must have a start address. */
289 if (s->flags & VSTART_DEFINED) {
290 s->start = s->vstart;
291 s->flags |= START_DEFINED;
293 /* Move the section into the nobits list. */
294 *sp = s->next;
295 s->next = NULL;
296 *nt = s;
297 nt = &s->next;
300 /* Step 2: Sort the progbits sections into their output order. */
302 /* In Step 2 we move around sections in groups. A group
303 * begins with a section (group leader) that has a user-
304 * defined start address or follows section. The remainder
305 * of the group is made up of the sections that implicitly
306 * follow the group leader (i.e., they were defined after
307 * the group leader and were not given an explicit start
308 * address or follows section by the user). */
310 /* For anyone attempting to read this code:
311 * g (group) points to a group of sections, the first one of which has
312 * a user-defined start address or follows section.
313 * gp (g previous) holds the location of the pointer to g.
314 * gs (g scan) is a temp variable that we use to scan to the end of the group.
315 * gsp (gs previous) holds the location of the pointer to gs.
316 * nt (nobits tail) points to the nobits section-list tail.
319 /* Link all 'follows' groups to their proper position. To do
320 * this we need to know three things: the start of the group
321 * to relocate (g), the section it is following (s), and the
322 * end of the group we're relocating (gs). */
323 for (gp = &sections, g = sections; g; g = gs) { /* Find the next follows group that is out of place (g). */
324 if (!(g->flags & FOLLOWS_DEFINED)) {
325 while (g->next) {
326 if ((g->next->flags & FOLLOWS_DEFINED) &&
327 strcmp(g->name, g->next->follows))
328 break;
329 g = g->next;
331 if (!g->next)
332 break;
333 gp = &g->next;
334 g = g->next;
336 /* Find the section that this group follows (s). */
337 for (sp = &sections, s = sections;
338 s && strcmp(s->name, g->follows);
339 sp = &s->next, s = s->next) ;
340 if (!s)
341 nasm_fatal(ERR_NOFILE, "section %s follows an invalid or"
342 " unknown section (%s)", g->name, g->follows);
343 if (s->next && (s->next->flags & FOLLOWS_DEFINED) &&
344 !strcmp(s->name, s->next->follows))
345 nasm_fatal(ERR_NOFILE, "sections %s and %s can't both follow"
346 " section %s", g->name, s->next->name, s->name);
347 /* Find the end of the current follows group (gs). */
348 for (gsp = &g->next, gs = g->next;
349 gs && (gs != s) && !(gs->flags & START_DEFINED);
350 gsp = &gs->next, gs = gs->next) {
351 if (gs->next && (gs->next->flags & FOLLOWS_DEFINED) &&
352 strcmp(gs->name, gs->next->follows)) {
353 gsp = &gs->next;
354 gs = gs->next;
355 break;
358 /* Re-link the group after its follows section. */
359 *gsp = s->next;
360 s->next = g;
361 *gp = gs;
364 /* Link all 'start' groups to their proper position. Once
365 * again we need to know g, s, and gs (see above). The main
366 * difference is we already know g since we sort by moving
367 * groups from the 'unsorted' list into a 'sorted' list (g
368 * will always be the first section in the unsorted list). */
369 for (g = sections, sections = NULL; g; g = gs) { /* Find the section that we will insert this group before (s). */
370 for (sp = &sections, s = sections; s; sp = &s->next, s = s->next)
371 if ((s->flags & START_DEFINED) && (g->start < s->start))
372 break;
373 /* Find the end of the group (gs). */
374 for (gs = g->next, gsp = &g->next;
375 gs && !(gs->flags & START_DEFINED);
376 gsp = &gs->next, gs = gs->next) ;
377 /* Re-link the group before the target section. */
378 *sp = g;
379 *gsp = s;
382 /* Step 3: Compute start addresses for all progbits sections. */
384 /* Make sure we have an origin and a start address for the first section. */
385 if (origin_defined) {
386 if (sections->flags & START_DEFINED) {
387 /* Make sure this section doesn't begin before the origin. */
388 if (sections->start < origin)
389 nasm_fatal(ERR_NOFILE, "section %s begins"
390 " before program origin", sections->name);
391 } else if (sections->flags & ALIGN_DEFINED) {
392 sections->start = ALIGN(origin, sections->align);
393 } else {
394 sections->start = origin;
396 } else {
397 if (!(sections->flags & START_DEFINED))
398 sections->start = 0;
399 origin = sections->start;
401 sections->flags |= START_DEFINED;
403 /* Make sure each section has an explicit start address. If it
404 * doesn't, then compute one based its alignment and the end of
405 * the previous section. */
406 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
407 * (has a defined start address, and is not zero length). */
408 if (g == s)
409 for (s = g->next;
410 s && ((s->length == 0) || !(s->flags & START_DEFINED));
411 s = s->next) ;
412 /* Compute the start address of this section, if necessary. */
413 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
414 if (!(g->flags & ALIGN_DEFINED)) {
415 g->align = 4;
416 g->flags |= ALIGN_DEFINED;
418 /* Set the section start address. */
419 g->start = ALIGN(pend, g->align);
420 g->flags |= START_DEFINED;
422 /* Ugly special case for progbits sections' virtual attributes:
423 * If there is a defined valign, but no vstart and no vfollows, then
424 * we valign after the previous progbits section. This case doesn't
425 * really make much sense for progbits sections with a defined start
426 * address, but it is possible and we must do *something*.
427 * Not-so-ugly special case:
428 * If a progbits section has no virtual attributes, we set the
429 * vstart equal to the start address. */
430 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
431 if (g->flags & VALIGN_DEFINED)
432 g->vstart = ALIGN(pend, g->valign);
433 else
434 g->vstart = g->start;
435 g->flags |= VSTART_DEFINED;
437 /* Ignore zero-length sections. */
438 if (g->start < pend)
439 continue;
440 /* Compute the span of this section. */
441 pend = g->start + g->length;
442 /* Check for section overlap. */
443 if (s) {
444 if (s->start < origin)
445 nasm_fatal(ERR_NOFILE, "section %s beings before program origin",
446 s->name);
447 if (g->start > s->start)
448 nasm_fatal(ERR_NOFILE, "sections %s ~ %s and %s overlap!",
449 gs->name, g->name, s->name);
450 if (pend > s->start)
451 nasm_fatal(ERR_NOFILE, "sections %s and %s overlap!",
452 g->name, s->name);
454 /* Remember this section as the latest >0 length section. */
455 gs = g;
458 /* Step 4: Compute vstart addresses for all sections. */
460 /* Attach the nobits sections to the end of the progbits sections. */
461 for (s = sections; s->next; s = s->next) ;
462 s->next = nobits;
463 last_progbits = s;
465 * Scan for sections that don't have a vstart address. If we find
466 * one we'll attempt to compute its vstart. If we can't compute
467 * the vstart, we leave it alone and come back to it in a
468 * subsequent scan. We continue scanning and re-scanning until
469 * we've gone one full cycle without computing any vstarts.
471 do { /* Do one full scan of the sections list. */
472 for (h = 0, g = sections; g; g = g->next) {
473 if (g->flags & VSTART_DEFINED)
474 continue;
475 /* Find the section that this one virtually follows. */
476 if (g->flags & VFOLLOWS_DEFINED) {
477 for (s = sections; s && strcmp(g->vfollows, s->name);
478 s = s->next) ;
479 if (!s)
480 nasm_fatal(ERR_NOFILE,
481 "section %s vfollows unknown section (%s)",
482 g->name, g->vfollows);
483 } else if (g->prev != NULL)
484 for (s = sections; s && (s != g->prev); s = s->next) ;
485 /* The .bss section is the only one with prev = NULL.
486 In this case we implicitly follow the last progbits
487 section. */
488 else
489 s = last_progbits;
491 /* If the section we're following has a vstart, we can proceed. */
492 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
493 if (!(g->flags & VALIGN_DEFINED)) {
494 g->valign = 4;
495 g->flags |= VALIGN_DEFINED;
497 /* Compute the vstart address. */
498 g->vstart = ALIGN(s->vstart + s->length, g->valign);
499 g->flags |= VSTART_DEFINED;
500 h++;
501 /* Start and vstart mean the same thing for nobits sections. */
502 if (g->flags & TYPE_NOBITS)
503 g->start = g->vstart;
506 } while (h);
508 /* Now check for any circular vfollows references, which will manifest
509 * themselves as sections without a defined vstart. */
510 for (h = 0, s = sections; s; s = s->next) {
511 if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
512 * no-no, but we'll throw a fatal one eventually so it's ok. */
513 nasm_error(ERR_NONFATAL, "cannot compute vstart for section %s",
514 s->name);
515 h++;
518 if (h)
519 nasm_fatal(ERR_NOFILE, "circular vfollows path detected");
521 #ifdef DEBUG
522 nasm_error(ERR_DEBUG,
523 "bin_cleanup: Confirm final section order for output file:\n");
524 for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
525 h++, s = s->next)
526 fprintf(stdout, "%i. %s\n", h, s->name);
527 #endif
529 /* Step 5: Apply relocations. */
531 /* Prepare the sections for relocating. */
532 list_for_each(s, sections)
533 saa_rewind(s->contents);
534 /* Apply relocations. */
535 list_for_each(r, relocs) {
536 uint8_t *p, mydata[8];
537 int64_t l;
538 int b;
540 nasm_assert(r->bytes <= 8);
542 memset(mydata, 0, sizeof(mydata));
544 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
545 p = mydata;
546 l = 0;
547 for (b = r->bytes - 1; b >= 0; b--)
548 l = (l << 8) + mydata[b];
550 s = find_section_by_index(r->secref);
551 if (s) {
552 if (r->secref == s->start_index)
553 l += s->start;
554 else
555 l += s->vstart;
557 s = find_section_by_index(r->secrel);
558 if (s) {
559 if (r->secrel == s->start_index)
560 l -= s->start;
561 else
562 l -= s->vstart;
565 WRITEADDR(p, l, r->bytes);
566 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
569 /* Step 6: Write the section data to the output file. */
570 do_output();
572 /* Step 7: Generate the map file. */
574 if (map_control) {
575 static const char not_defined[] = "not defined";
577 /* Display input and output file names. */
578 fprintf(rf, "\n- NASM Map file ");
579 for (h = 63; h; h--)
580 fputc('-', rf);
581 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
582 infile, outfile);
584 if (map_control & MAP_ORIGIN) { /* Display program origin. */
585 fprintf(rf, "-- Program origin ");
586 for (h = 61; h; h--)
587 fputc('-', rf);
588 fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
590 /* Display sections summary. */
591 if (map_control & MAP_SUMMARY) {
592 fprintf(rf, "-- Sections (summary) ");
593 for (h = 57; h; h--)
594 fputc('-', rf);
595 fprintf(rf, "\n\nVstart Start Stop "
596 "Length Class Name\n");
597 list_for_each(s, sections) {
598 fprintf(rf, "%16"PRIX64" %16"PRIX64" %16"PRIX64" %08"PRIX64" ",
599 s->vstart, s->start, s->start + s->length,
600 s->length);
601 if (s->flags & TYPE_PROGBITS)
602 fprintf(rf, "progbits ");
603 else
604 fprintf(rf, "nobits ");
605 fprintf(rf, "%s\n", s->name);
607 fprintf(rf, "\n");
609 /* Display detailed section information. */
610 if (map_control & MAP_SECTIONS) {
611 fprintf(rf, "-- Sections (detailed) ");
612 for (h = 56; h; h--)
613 fputc('-', rf);
614 fprintf(rf, "\n\n");
615 list_for_each(s, sections) {
616 fprintf(rf, "---- Section %s ", s->name);
617 for (h = 65 - strlen(s->name); h; h--)
618 fputc('-', rf);
619 fprintf(rf, "\n\nclass: ");
620 if (s->flags & TYPE_PROGBITS)
621 fprintf(rf, "progbits");
622 else
623 fprintf(rf, "nobits");
624 fprintf(rf, "\nlength: %16"PRIX64"\nstart: %16"PRIX64""
625 "\nalign: ", s->length, s->start);
626 if (s->flags & ALIGN_DEFINED)
627 fprintf(rf, "%16"PRIX64"", s->align);
628 else
629 fputs(not_defined, rf);
630 fprintf(rf, "\nfollows: ");
631 if (s->flags & FOLLOWS_DEFINED)
632 fprintf(rf, "%s", s->follows);
633 else
634 fputs(not_defined, rf);
635 fprintf(rf, "\nvstart: %16"PRIX64"\nvalign: ", s->vstart);
636 if (s->flags & VALIGN_DEFINED)
637 fprintf(rf, "%16"PRIX64"", s->valign);
638 else
639 fputs(not_defined, rf);
640 fprintf(rf, "\nvfollows: ");
641 if (s->flags & VFOLLOWS_DEFINED)
642 fprintf(rf, "%s", s->vfollows);
643 else
644 fputs(not_defined, rf);
645 fprintf(rf, "\n\n");
648 /* Display symbols information. */
649 if (map_control & MAP_SYMBOLS) {
650 int32_t segment;
651 int64_t offset;
653 fprintf(rf, "-- Symbols ");
654 for (h = 68; h; h--)
655 fputc('-', rf);
656 fprintf(rf, "\n\n");
657 if (no_seg_labels) {
658 fprintf(rf, "---- No Section ");
659 for (h = 63; h; h--)
660 fputc('-', rf);
661 fprintf(rf, "\n\nValue Name\n");
662 list_for_each(l, no_seg_labels) {
663 lookup_label(l->name, &segment, &offset);
664 fprintf(rf, "%08"PRIX64" %s\n", offset, l->name);
666 fprintf(rf, "\n\n");
668 list_for_each(s, sections) {
669 if (s->labels) {
670 fprintf(rf, "---- Section %s ", s->name);
671 for (h = 65 - strlen(s->name); h; h--)
672 fputc('-', rf);
673 fprintf(rf, "\n\nReal Virtual Name\n");
674 list_for_each(l, s->labels) {
675 lookup_label(l->name, &segment, &offset);
676 fprintf(rf, "%16"PRIX64" %16"PRIX64" %s\n",
677 s->start + offset, s->vstart + offset,
678 l->name);
680 fprintf(rf, "\n");
686 /* Close the report file. */
687 if (map_control && (rf != stdout) && (rf != stderr))
688 fclose(rf);
690 /* Step 8: Release all allocated memory. */
692 /* Free sections, label pointer structs, etc.. */
693 while (sections) {
694 s = sections;
695 sections = s->next;
696 saa_free(s->contents);
697 nasm_free(s->name);
698 if (s->flags & FOLLOWS_DEFINED)
699 nasm_free(s->follows);
700 if (s->flags & VFOLLOWS_DEFINED)
701 nasm_free(s->vfollows);
702 while (s->labels) {
703 l = s->labels;
704 s->labels = l->next;
705 nasm_free(l);
707 nasm_free(s);
710 /* Free no-section labels. */
711 while (no_seg_labels) {
712 l = no_seg_labels;
713 no_seg_labels = l->next;
714 nasm_free(l);
717 /* Free relocation structures. */
718 while (relocs) {
719 r = relocs->next;
720 nasm_free(relocs);
721 relocs = r;
725 static void bin_out(int32_t segto, const void *data,
726 enum out_type type, uint64_t size,
727 int32_t segment, int32_t wrt)
729 uint8_t *p, mydata[8];
730 struct Section *s;
732 if (wrt != NO_SEG) {
733 wrt = NO_SEG; /* continue to do _something_ */
734 nasm_error(ERR_NONFATAL, "WRT not supported by binary output format");
737 /* Handle absolute-assembly (structure definitions). */
738 if (segto == NO_SEG) {
739 if (type != OUT_RESERVE)
740 nasm_error(ERR_NONFATAL, "attempt to assemble code in"
741 " [ABSOLUTE] space");
742 return;
745 /* Find the segment we are targeting. */
746 s = find_section_by_index(segto);
747 if (!s)
748 nasm_panic(0, "code directed to nonexistent segment?");
750 /* "Smart" section-type adaptation code. */
751 if (!(s->flags & TYPE_DEFINED)) {
752 if (type == OUT_RESERVE)
753 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
754 else
755 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
758 if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
759 nasm_error(ERR_WARNING, "attempt to initialize memory in a"
760 " nobits section: ignored");
762 switch (type) {
763 case OUT_ADDRESS:
765 int asize = abs((int)size);
767 if (segment != NO_SEG && !find_section_by_index(segment)) {
768 if (segment % 2)
769 nasm_error(ERR_NONFATAL, "binary output format does not support"
770 " segment base references");
771 else
772 nasm_error(ERR_NONFATAL, "binary output format does not support"
773 " external references");
774 segment = NO_SEG;
776 if (s->flags & TYPE_PROGBITS) {
777 if (segment != NO_SEG)
778 add_reloc(s, asize, segment, -1L);
779 p = mydata;
780 WRITEADDR(p, *(int64_t *)data, asize);
781 saa_wbytes(s->contents, mydata, asize);
785 * Reassign size with sign dropped, we will need it
786 * for section length calculation.
788 size = asize;
789 break;
792 case OUT_RAWDATA:
793 if (s->flags & TYPE_PROGBITS)
794 saa_wbytes(s->contents, data, size);
795 break;
797 case OUT_RESERVE:
798 if (s->flags & TYPE_PROGBITS) {
799 nasm_error(ERR_WARNING, "uninitialized space declared in"
800 " %s section: zeroing", s->name);
801 saa_wbytes(s->contents, NULL, size);
803 break;
805 case OUT_REL1ADR:
806 case OUT_REL2ADR:
807 case OUT_REL4ADR:
808 case OUT_REL8ADR:
810 int64_t addr = *(int64_t *)data - size;
811 size = realsize(type, size);
812 if (segment != NO_SEG && !find_section_by_index(segment)) {
813 if (segment % 2)
814 nasm_error(ERR_NONFATAL, "binary output format does not support"
815 " segment base references");
816 else
817 nasm_error(ERR_NONFATAL, "binary output format does not support"
818 " external references");
819 segment = NO_SEG;
821 if (s->flags & TYPE_PROGBITS) {
822 add_reloc(s, size, segment, segto);
823 p = mydata;
824 WRITEADDR(p, addr - s->length, size);
825 saa_wbytes(s->contents, mydata, size);
827 break;
830 default:
831 nasm_error(ERR_NONFATAL, "unsupported relocation type %d\n", type);
832 break;
835 s->length += size;
838 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
839 int is_global, char *special)
841 (void)segment; /* Don't warn that this parameter is unused */
842 (void)offset; /* Don't warn that this parameter is unused */
844 if (special)
845 nasm_error(ERR_NONFATAL, "binary format does not support any"
846 " special symbol types");
847 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
848 nasm_error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
849 else if (is_global == 2)
850 nasm_error(ERR_NONFATAL, "binary output format does not support common"
851 " variables");
852 else {
853 struct Section *s;
854 struct bin_label ***ltp;
856 /* Remember label definition so we can look it up later when
857 * creating the map file. */
858 s = find_section_by_index(segment);
859 if (s)
860 ltp = &(s->labels_end);
861 else
862 ltp = &nsl_tail;
863 (**ltp) = nasm_malloc(sizeof(struct bin_label));
864 (**ltp)->name = name;
865 (**ltp)->next = NULL;
866 *ltp = &((**ltp)->next);
871 /* These constants and the following function are used
872 * by bin_secname() to parse attribute assignments. */
874 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
875 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
876 ATTRIB_NOBITS, ATTRIB_PROGBITS
879 static int bin_read_attribute(char **line, int *attribute,
880 uint64_t *value)
882 expr *e;
883 int attrib_name_size;
884 struct tokenval tokval;
885 char *exp;
887 /* Skip whitespace. */
888 while (**line && nasm_isspace(**line))
889 (*line)++;
890 if (!**line)
891 return 0;
893 /* Figure out what attribute we're reading. */
894 if (!nasm_strnicmp(*line, "align=", 6)) {
895 *attribute = ATTRIB_ALIGN;
896 attrib_name_size = 6;
897 } else {
898 if (!nasm_strnicmp(*line, "start=", 6)) {
899 *attribute = ATTRIB_START;
900 attrib_name_size = 6;
901 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
902 *attribute = ATTRIB_FOLLOWS;
903 *line += 8;
904 return 1;
905 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
906 *attribute = ATTRIB_VSTART;
907 attrib_name_size = 7;
908 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
909 *attribute = ATTRIB_VALIGN;
910 attrib_name_size = 7;
911 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
912 *attribute = ATTRIB_VFOLLOWS;
913 *line += 9;
914 return 1;
915 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
916 (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
917 *attribute = ATTRIB_NOBITS;
918 *line += 6;
919 return 1;
920 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
921 (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
922 *attribute = ATTRIB_PROGBITS;
923 *line += 8;
924 return 1;
925 } else
926 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_set(exp);
989 tokval.t_type = TOKEN_INVALID;
990 e = evaluate(stdscan, NULL, &tokval, NULL, 1, 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_sectalign(int32_t seg, unsigned int value)
1008 struct Section *s = find_section_by_index(seg);
1010 if (!s || !is_power2(value))
1011 return;
1013 if (value > s->align)
1014 s->align = value;
1016 if (!(s->flags & ALIGN_DEFINED))
1017 s->flags |= ALIGN_DEFINED;
1020 static void bin_assign_attributes(struct Section *sec, char *astring)
1022 int attribute, check;
1023 uint64_t value;
1024 char *p;
1026 while (1) { /* Get the next attribute. */
1027 check = bin_read_attribute(&astring, &attribute, &value);
1028 /* Skip bad attribute. */
1029 if (check == -1)
1030 continue;
1031 /* Unknown section attribute, so skip it and warn the user. */
1032 if (!check) {
1033 if (!*astring)
1034 break; /* End of line. */
1035 else {
1036 p = astring;
1037 while (*astring && !nasm_isspace(*astring))
1038 astring++;
1039 if (*astring) {
1040 *astring = '\0';
1041 astring++;
1043 nasm_error(ERR_WARNING, "ignoring unknown section attribute:"
1044 " \"%s\"", p);
1046 continue;
1049 switch (attribute) { /* Handle nobits attribute. */
1050 case ATTRIB_NOBITS:
1051 if ((sec->flags & TYPE_DEFINED)
1052 && (sec->flags & TYPE_PROGBITS))
1053 nasm_error(ERR_NONFATAL,
1054 "attempt to change section type"
1055 " from progbits to nobits");
1056 else
1057 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1058 continue;
1060 /* Handle progbits attribute. */
1061 case ATTRIB_PROGBITS:
1062 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1063 nasm_error(ERR_NONFATAL, "attempt to change section type"
1064 " from nobits to progbits");
1065 else
1066 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1067 continue;
1069 /* Handle align attribute. */
1070 case ATTRIB_ALIGN:
1071 if (!value || ((value - 1) & value)) {
1072 nasm_error(ERR_NONFATAL,
1073 "argument to `align' is not a power of two");
1074 } else {
1076 * Alignment is already satisfied if
1077 * the previous align value is greater
1079 if ((sec->flags & ALIGN_DEFINED) && (value < sec->align))
1080 value = sec->align;
1082 /* Don't allow a conflicting align value. */
1083 if ((sec->flags & START_DEFINED) && (sec->start & (value - 1))) {
1084 nasm_error(ERR_NONFATAL,
1085 "`align' value conflicts with section start address");
1086 } else {
1087 sec->align = value;
1088 sec->flags |= ALIGN_DEFINED;
1091 continue;
1093 /* Handle valign attribute. */
1094 case ATTRIB_VALIGN:
1095 if (!value || ((value - 1) & value))
1096 nasm_error(ERR_NONFATAL, "argument to `valign' is not a"
1097 " power of two");
1098 else { /* Alignment is already satisfied if the previous
1099 * align value is greater. */
1100 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1101 value = sec->valign;
1103 /* Don't allow a conflicting valign value. */
1104 if ((sec->flags & VSTART_DEFINED)
1105 && (sec->vstart & (value - 1)))
1106 nasm_error(ERR_NONFATAL,
1107 "`valign' value conflicts "
1108 "with `vstart' address");
1109 else {
1110 sec->valign = value;
1111 sec->flags |= VALIGN_DEFINED;
1114 continue;
1116 /* Handle start attribute. */
1117 case ATTRIB_START:
1118 if (sec->flags & FOLLOWS_DEFINED)
1119 nasm_error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1120 " section attributes");
1121 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1122 nasm_error(ERR_NONFATAL, "section start address redefined");
1123 else {
1124 sec->start = value;
1125 sec->flags |= START_DEFINED;
1126 if (sec->flags & ALIGN_DEFINED) {
1127 if (sec->start & (sec->align - 1))
1128 nasm_error(ERR_NONFATAL, "`start' address conflicts"
1129 " with section alignment");
1130 sec->flags ^= ALIGN_DEFINED;
1133 continue;
1135 /* Handle vstart attribute. */
1136 case ATTRIB_VSTART:
1137 if (sec->flags & VFOLLOWS_DEFINED)
1138 nasm_error(ERR_NONFATAL,
1139 "cannot combine `vstart' and `vfollows'"
1140 " section attributes");
1141 else if ((sec->flags & VSTART_DEFINED)
1142 && (value != sec->vstart))
1143 nasm_error(ERR_NONFATAL,
1144 "section virtual start address"
1145 " (vstart) redefined");
1146 else {
1147 sec->vstart = value;
1148 sec->flags |= VSTART_DEFINED;
1149 if (sec->flags & VALIGN_DEFINED) {
1150 if (sec->vstart & (sec->valign - 1))
1151 nasm_error(ERR_NONFATAL, "`vstart' address conflicts"
1152 " with `valign' value");
1153 sec->flags ^= VALIGN_DEFINED;
1156 continue;
1158 /* Handle follows attribute. */
1159 case ATTRIB_FOLLOWS:
1160 p = astring;
1161 astring += strcspn(astring, " \t");
1162 if (astring == p)
1163 nasm_error(ERR_NONFATAL, "expecting section name for `follows'"
1164 " attribute");
1165 else {
1166 *(astring++) = '\0';
1167 if (sec->flags & START_DEFINED)
1168 nasm_error(ERR_NONFATAL,
1169 "cannot combine `start' and `follows'"
1170 " section attributes");
1171 sec->follows = nasm_strdup(p);
1172 sec->flags |= FOLLOWS_DEFINED;
1174 continue;
1176 /* Handle vfollows attribute. */
1177 case ATTRIB_VFOLLOWS:
1178 if (sec->flags & VSTART_DEFINED)
1179 nasm_error(ERR_NONFATAL,
1180 "cannot combine `vstart' and `vfollows'"
1181 " section attributes");
1182 else {
1183 p = astring;
1184 astring += strcspn(astring, " \t");
1185 if (astring == p)
1186 nasm_error(ERR_NONFATAL,
1187 "expecting section name for `vfollows'"
1188 " attribute");
1189 else {
1190 *(astring++) = '\0';
1191 sec->vfollows = nasm_strdup(p);
1192 sec->flags |= VFOLLOWS_DEFINED;
1195 continue;
1200 static void bin_define_section_labels(void)
1202 static int labels_defined = 0;
1203 struct Section *sec;
1204 char *label_name;
1205 size_t base_len;
1207 if (labels_defined)
1208 return;
1209 list_for_each(sec, sections) {
1210 base_len = strlen(sec->name) + 8;
1211 label_name = nasm_malloc(base_len + 8);
1212 strcpy(label_name, "section.");
1213 strcpy(label_name + 8, sec->name);
1215 /* section.<name>.start */
1216 strcpy(label_name + base_len, ".start");
1217 define_label(label_name, sec->start_index, 0L, NULL, 0, 0);
1219 /* section.<name>.vstart */
1220 strcpy(label_name + base_len, ".vstart");
1221 define_label(label_name, sec->vstart_index, 0L, NULL, 0, 0);
1223 nasm_free(label_name);
1225 labels_defined = 1;
1228 static int32_t bin_secname(char *name, int pass, int *bits)
1230 char *p;
1231 struct Section *sec;
1233 /* bin_secname is called with *name = NULL at the start of each
1234 * pass. Use this opportunity to establish the default section
1235 * (default is BITS-16 ".text" segment).
1237 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1238 origin_defined = 0;
1239 list_for_each(sec, sections)
1240 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1241 ALIGN_DEFINED | VALIGN_DEFINED);
1243 /* Define section start and vstart labels. */
1244 if (pass != 1)
1245 bin_define_section_labels();
1247 /* Establish the default (.text) section. */
1248 *bits = 16;
1249 sec = find_section_by_name(".text");
1250 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1251 return sec->vstart_index;
1254 /* Attempt to find the requested section. If it does not
1255 * exist, create it. */
1256 p = name;
1257 while (*p && !nasm_isspace(*p))
1258 p++;
1259 if (*p)
1260 *p++ = '\0';
1261 sec = find_section_by_name(name);
1262 if (!sec) {
1263 sec = create_section(name);
1264 if (!strcmp(name, ".data"))
1265 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1266 else if (!strcmp(name, ".bss")) {
1267 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1268 sec->prev = NULL;
1272 /* Handle attribute assignments. */
1273 if (pass != 1)
1274 bin_assign_attributes(sec, p);
1276 #ifndef ABIN_SMART_ADAPT
1277 /* The following line disables smart adaptation of
1278 * PROGBITS/NOBITS section types (it forces sections to
1279 * default to PROGBITS). */
1280 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1281 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1282 #endif
1284 return sec->vstart_index;
1287 static int bin_directive(enum directives directive, char *args, int pass)
1289 switch (directive) {
1290 case D_ORG:
1292 struct tokenval tokval;
1293 uint64_t value;
1294 expr *e;
1296 stdscan_reset();
1297 stdscan_set(args);
1298 tokval.t_type = TOKEN_INVALID;
1299 e = evaluate(stdscan, NULL, &tokval, NULL, 1, NULL);
1300 if (e) {
1301 if (!is_really_simple(e))
1302 nasm_error(ERR_NONFATAL, "org value must be a critical"
1303 " expression");
1304 else {
1305 value = reloc_value(e);
1306 /* Check for ORG redefinition. */
1307 if (origin_defined && (value != origin))
1308 nasm_error(ERR_NONFATAL, "program origin redefined");
1309 else {
1310 origin = value;
1311 origin_defined = 1;
1314 } else
1315 nasm_error(ERR_NONFATAL, "No or invalid offset specified"
1316 " in ORG directive.");
1317 return 1;
1319 case D_MAP:
1321 /* The 'map' directive allows the user to generate section
1322 * and symbol information to stdout, stderr, or to a file. */
1323 char *p;
1325 if (pass != 1)
1326 return 1;
1327 args += strspn(args, " \t");
1328 while (*args) {
1329 p = args;
1330 args += strcspn(args, " \t");
1331 if (*args != '\0')
1332 *(args++) = '\0';
1333 if (!nasm_stricmp(p, "all"))
1334 map_control |=
1335 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1336 else if (!nasm_stricmp(p, "brief"))
1337 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1338 else if (!nasm_stricmp(p, "sections"))
1339 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1340 else if (!nasm_stricmp(p, "segments"))
1341 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1342 else if (!nasm_stricmp(p, "symbols"))
1343 map_control |= MAP_SYMBOLS;
1344 else if (!rf) {
1345 if (!nasm_stricmp(p, "stdout"))
1346 rf = stdout;
1347 else if (!nasm_stricmp(p, "stderr"))
1348 rf = stderr;
1349 else { /* Must be a filename. */
1350 rf = fopen(p, "wt");
1351 if (!rf) {
1352 nasm_error(ERR_WARNING, "unable to open map file `%s'",
1354 map_control = 0;
1355 return 1;
1358 } else
1359 nasm_error(ERR_WARNING, "map file already specified");
1361 if (map_control == 0)
1362 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1363 if (!rf)
1364 rf = stdout;
1365 return 1;
1367 default:
1368 return 0;
1372 static void bin_filename(char *inname, char *outname)
1374 standard_extension(inname, outname, "");
1375 infile = inname;
1376 outfile = outname;
1379 static void ith_filename(char *inname, char *outname)
1381 standard_extension(inname, outname, ".ith");
1382 infile = inname;
1383 outfile = outname;
1386 static void srec_filename(char *inname, char *outname)
1388 standard_extension(inname, outname, ".srec");
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 const struct ofmt of_bin, of_ith, of_srec;
1406 static void binfmt_init(void);
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(void)
1413 do_output = do_output_bin;
1414 binfmt_init();
1417 static void ith_init(void)
1419 do_output = do_output_ith;
1420 binfmt_init();
1423 static void srec_init(void)
1425 do_output = do_output_srec;
1426 binfmt_init();
1429 static void binfmt_init(void)
1431 relocs = NULL;
1432 reloctail = &relocs;
1433 origin_defined = 0;
1434 no_seg_labels = NULL;
1435 nsl_tail = &no_seg_labels;
1437 /* Create default section (.text). */
1438 sections = last_section = nasm_zalloc(sizeof(struct Section));
1439 last_section->name = nasm_strdup(".text");
1440 last_section->contents = saa_init(1L);
1441 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1442 last_section->labels_end = &(last_section->labels);
1443 last_section->start_index = seg_alloc();
1444 last_section->vstart_index = seg_alloc();
1447 /* Generate binary file output */
1448 static void do_output_bin(void)
1450 struct Section *s;
1451 uint64_t addr = origin;
1453 /* Write the progbits sections to the output file. */
1454 list_for_each(s, sections) {
1455 /* Skip non-progbits sections */
1456 if (!(s->flags & TYPE_PROGBITS))
1457 continue;
1458 /* Skip zero-length sections */
1459 if (s->length == 0)
1460 continue;
1462 /* Pad the space between sections. */
1463 nasm_assert(addr <= s->start);
1464 fwritezero(s->start - addr, ofile);
1466 /* Write the section to the output file. */
1467 saa_fpwrite(s->contents, ofile);
1469 /* Keep track of the current file position */
1470 addr = s->start + s->length;
1474 /* Generate Intel hex file output */
1475 static void write_ith_record(unsigned int len, uint16_t addr,
1476 uint8_t type, void *data)
1478 char buf[1+2+4+2+255*2+2+2];
1479 char *p = buf;
1480 uint8_t csum, *dptr = data;
1481 unsigned int i;
1483 nasm_assert(len <= 255);
1485 csum = len + addr + (addr >> 8) + type;
1486 for (i = 0; i < len; i++)
1487 csum += dptr[i];
1488 csum = -csum;
1490 p += sprintf(p, ":%02X%04X%02X", len, addr, type);
1491 for (i = 0; i < len; i++)
1492 p += sprintf(p, "%02X", dptr[i]);
1493 p += sprintf(p, "%02X\n", csum);
1495 nasm_write(buf, p-buf, ofile);
1498 static void do_output_ith(void)
1500 uint8_t buf[32];
1501 struct Section *s;
1502 uint64_t addr, hiaddr, hilba;
1503 uint64_t length;
1504 unsigned int chunk;
1506 /* Write the progbits sections to the output file. */
1507 hilba = 0;
1508 list_for_each(s, sections) {
1509 /* Skip non-progbits sections */
1510 if (!(s->flags & TYPE_PROGBITS))
1511 continue;
1512 /* Skip zero-length sections */
1513 if (s->length == 0)
1514 continue;
1516 addr = s->start;
1517 length = s->length;
1518 saa_rewind(s->contents);
1520 while (length) {
1521 hiaddr = addr >> 16;
1522 if (hiaddr != hilba) {
1523 buf[0] = hiaddr >> 8;
1524 buf[1] = hiaddr;
1525 write_ith_record(2, 0, 4, buf);
1526 hilba = hiaddr;
1529 chunk = 32 - (addr & 31);
1530 if (length < chunk)
1531 chunk = length;
1533 saa_rnbytes(s->contents, buf, chunk);
1534 write_ith_record(chunk, (uint16_t)addr, 0, buf);
1536 addr += chunk;
1537 length -= chunk;
1541 /* Write closing record */
1542 write_ith_record(0, 0, 1, NULL);
1545 /* Generate Motorola S-records */
1546 static void write_srecord(unsigned int len, unsigned int alen,
1547 uint32_t addr, uint8_t type, void *data)
1549 char buf[2+2+8+255*2+2+2];
1550 char *p = buf;
1551 uint8_t csum, *dptr = data;
1552 unsigned int i;
1554 nasm_assert(len <= 255);
1556 switch (alen) {
1557 case 2:
1558 addr &= 0xffff;
1559 break;
1560 case 3:
1561 addr &= 0xffffff;
1562 break;
1563 case 4:
1564 break;
1565 default:
1566 nasm_assert(0);
1567 break;
1570 csum = (len+alen+1) + addr + (addr >> 8) + (addr >> 16) + (addr >> 24);
1571 for (i = 0; i < len; i++)
1572 csum += dptr[i];
1573 csum = 0xff-csum;
1575 p += sprintf(p, "S%c%02X%0*X", type, len+alen+1, alen*2, addr);
1576 for (i = 0; i < len; i++)
1577 p += sprintf(p, "%02X", dptr[i]);
1578 p += sprintf(p, "%02X\n", csum);
1580 nasm_write(buf, p-buf, ofile);
1583 static void do_output_srec(void)
1585 uint8_t buf[32];
1586 struct Section *s;
1587 uint64_t addr, maxaddr;
1588 uint64_t length;
1589 int alen;
1590 unsigned int chunk;
1591 char dtype, etype;
1593 maxaddr = 0;
1594 list_for_each(s, sections) {
1595 /* Skip non-progbits sections */
1596 if (!(s->flags & TYPE_PROGBITS))
1597 continue;
1598 /* Skip zero-length sections */
1599 if (s->length == 0)
1600 continue;
1602 addr = s->start + s->length - 1;
1603 if (addr > maxaddr)
1604 maxaddr = addr;
1607 if (maxaddr <= 0xffff) {
1608 alen = 2;
1609 dtype = '1'; /* S1 = 16-bit data */
1610 etype = '9'; /* S9 = 16-bit end */
1611 } else if (maxaddr <= 0xffffff) {
1612 alen = 3;
1613 dtype = '2'; /* S2 = 24-bit data */
1614 etype = '8'; /* S8 = 24-bit end */
1615 } else {
1616 alen = 4;
1617 dtype = '3'; /* S3 = 32-bit data */
1618 etype = '7'; /* S7 = 32-bit end */
1621 /* Write head record */
1622 write_srecord(0, 2, 0, '0', NULL);
1624 /* Write the progbits sections to the output file. */
1625 list_for_each(s, sections) {
1626 /* Skip non-progbits sections */
1627 if (!(s->flags & TYPE_PROGBITS))
1628 continue;
1629 /* Skip zero-length sections */
1630 if (s->length == 0)
1631 continue;
1633 addr = s->start;
1634 length = s->length;
1635 saa_rewind(s->contents);
1637 while (length) {
1638 chunk = 32 - (addr & 31);
1639 if (length < chunk)
1640 chunk = length;
1642 saa_rnbytes(s->contents, buf, chunk);
1643 write_srecord(chunk, alen, (uint32_t)addr, dtype, buf);
1645 addr += chunk;
1646 length -= chunk;
1650 /* Write closing record */
1651 write_srecord(0, alen, 0, etype, NULL);
1655 const struct ofmt of_bin = {
1656 "flat-form binary files (e.g. DOS .COM, .SYS)",
1657 "bin",
1660 null_debug_arr,
1661 &null_debug_form,
1662 bin_stdmac,
1663 bin_init,
1664 bin_set_info,
1665 bin_out,
1666 bin_deflabel,
1667 bin_secname,
1668 bin_sectalign,
1669 bin_segbase,
1670 bin_directive,
1671 bin_filename,
1672 bin_cleanup
1675 const struct ofmt of_ith = {
1676 "Intel hex",
1677 "ith",
1678 OFMT_TEXT,
1680 null_debug_arr,
1681 &null_debug_form,
1682 bin_stdmac,
1683 ith_init,
1684 bin_set_info,
1685 bin_out,
1686 bin_deflabel,
1687 bin_secname,
1688 bin_sectalign,
1689 bin_segbase,
1690 bin_directive,
1691 ith_filename,
1692 bin_cleanup
1695 const struct ofmt of_srec = {
1696 "Motorola S-records",
1697 "srec",
1698 OFMT_TEXT,
1700 null_debug_arr,
1701 &null_debug_form,
1702 bin_stdmac,
1703 srec_init,
1704 bin_set_info,
1705 bin_out,
1706 bin_deflabel,
1707 bin_secname,
1708 bin_sectalign,
1709 bin_segbase,
1710 bin_directive,
1711 srec_filename,
1712 bin_cleanup
1715 #endif /* #ifdef OF_BIN */