Apply Nindent to all .c and .h files
[nasm/avx512.git] / output / outbin.c
blob5cadff0d914625cf17ce523b6c50e688b5d31928
1 /* outbin.c output routines for the Netwide Assembler to produce
2 * flat-form binary files
4 * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
5 * Julian Hall. All rights reserved. The software is
6 * redistributable under the licence given in the file "Licence"
7 * distributed in the NASM archive.
8 */
10 /* This is the extended version of NASM's original binary output
11 * format. It is backward compatible with the original BIN format,
12 * and contains support for multiple sections and advanced section
13 * ordering.
15 * Feature summary:
17 * - Users can create an arbitrary number of sections; they are not
18 * limited to just ".text", ".data", and ".bss".
20 * - Sections can be either progbits or nobits type.
22 * - You can specify that they be aligned at a certian boundary
23 * following the previous section ("align="), or positioned at an
24 * arbitrary byte-granular location ("start=").
26 * - You can specify a "virtual" start address for a section, which
27 * will be used for the calculation for all address references
28 * with respect to that section ("vstart=").
30 * - The ORG directive, as well as the section/segment directive
31 * arguments ("align=", "start=", "vstart="), can take a critical
32 * expression as their value. For example: "align=(1 << 12)".
34 * - You can generate map files using the 'map' directive.
38 /* Uncomment the following define if you want sections to adapt
39 * their progbits/nobits state depending on what type of
40 * instructions are issued, rather than defaulting to progbits.
41 * Note that this behavior violates the specification.
43 #define ABIN_SMART_ADAPT
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <ctype.h>
52 #include "nasm.h"
53 #include "nasmlib.h"
54 #include "labels.h"
55 #include "eval.h"
56 #include "outform.h"
58 #ifdef OF_BIN
60 struct ofmt *bin_get_ofmt(); /* Prototype goes here since no header file. */
62 static FILE *fp, *rf = NULL;
63 static efunc error;
65 /* Section flags keep track of which attributes the user has defined. */
66 #define START_DEFINED 0x001
67 #define ALIGN_DEFINED 0x002
68 #define FOLLOWS_DEFINED 0x004
69 #define VSTART_DEFINED 0x008
70 #define VALIGN_DEFINED 0x010
71 #define VFOLLOWS_DEFINED 0x020
72 #define TYPE_DEFINED 0x040
73 #define TYPE_PROGBITS 0x080
74 #define TYPE_NOBITS 0x100
76 /* This struct is used to keep track of symbols for map-file generation. */
77 static struct bin_label {
78 char *name;
79 struct bin_label *next;
80 } *no_seg_labels, **nsl_tail;
82 static struct Section {
83 char *name;
84 struct SAA *contents;
85 long length; /* section length in bytes */
87 /* Section attributes */
88 int flags; /* see flag definitions above */
89 unsigned long align; /* section alignment */
90 unsigned long valign; /* notional section alignment */
91 unsigned long start; /* section start address */
92 unsigned long vstart; /* section virtual start address */
93 char *follows; /* the section that this one will follow */
94 char *vfollows; /* the section that this one will notionally follow */
95 long start_index; /* NASM section id for non-relocated version */
96 long vstart_index; /* the NASM section id */
98 struct bin_label *labels; /* linked-list of label handles for map output. */
99 struct bin_label **labels_end; /* Holds address of end of labels list. */
100 struct Section *ifollows; /* Points to previous section (implicit follows). */
101 struct Section *next; /* This links sections with a defined start address. */
103 /* The extended bin format allows for sections to have a "virtual"
104 * start address. This is accomplished by creating two sections:
105 * one beginning at the Load Memory Address and the other beginning
106 * at the Virtual Memory Address. The LMA section is only used to
107 * define the section.<section_name>.start label, but there isn't
108 * any other good way for us to handle that label.
111 } *sections, *last_section;
113 static struct Reloc {
114 struct Reloc *next;
115 long posn;
116 long bytes;
117 long secref;
118 long secrel;
119 struct Section *target;
120 } *relocs, **reloctail;
122 extern char *stdscan_bufptr;
123 extern int lookup_label(char *label, long *segment, long *offset);
125 static unsigned char format_mode; /* 0 = original bin, 1 = extended bin */
126 static long current_section; /* only really needed if format_mode = 0 */
127 static unsigned long origin;
128 static int origin_defined;
130 /* Stuff we need for map-file generation. */
131 #define MAP_ORIGIN 1
132 #define MAP_SUMMARY 2
133 #define MAP_SECTIONS 4
134 #define MAP_SYMBOLS 8
135 static int map_control = 0;
136 static char *infile, *outfile;
138 static const char *bin_stdmac[] = {
139 "%define __SECT__ [section .text]",
140 "%imacro org 1+.nolist",
141 "[org %1]",
142 "%endmacro",
143 "%macro __NASM_CDecl__ 1",
144 "%endmacro",
145 NULL
148 static void add_reloc(struct Section *s, long bytes, long secref,
149 long secrel)
151 struct Reloc *r;
153 r = *reloctail = nasm_malloc(sizeof(struct Reloc));
154 reloctail = &r->next;
155 r->next = NULL;
156 r->posn = s->length;
157 r->bytes = bytes;
158 r->secref = secref;
159 r->secrel = secrel;
160 r->target = s;
163 static struct Section *find_section_by_name(const char *name)
165 struct Section *s;
167 for (s = sections; s; s = s->next)
168 if (!strcmp(s->name, name))
169 break;
170 return s;
173 static struct Section *find_section_by_index(long index)
175 struct Section *s;
177 for (s = sections; s; s = s->next)
178 if ((index == s->vstart_index) || (index == s->start_index))
179 break;
180 return s;
183 static struct Section *create_section(char *name)
184 { /* Create a new section. */
185 last_section->next = nasm_malloc(sizeof(struct Section));
186 last_section->next->ifollows = last_section;
187 last_section = last_section->next;
188 last_section->labels = NULL;
189 last_section->labels_end = &(last_section->labels);
191 /* Initialize section attributes. */
192 last_section->name = nasm_strdup(name);
193 last_section->contents = saa_init(1L);
194 last_section->follows = last_section->vfollows = 0;
195 last_section->length = 0;
196 last_section->flags = 0;
197 last_section->next = NULL;
199 /* Register our sections with NASM. */
200 last_section->vstart_index = seg_alloc();
201 last_section->start_index = seg_alloc();
202 return last_section;
205 static void bin_cleanup(int debuginfo)
207 struct Section *g, **gp;
208 struct Section *gs = NULL, **gsp;
209 struct Section *s, **sp;
210 struct Section *nobits = NULL, **nt;
211 struct Section *last_progbits;
212 struct bin_label *l;
213 struct Reloc *r;
214 unsigned long pend;
215 int h;
217 #ifdef DEBUG
218 fprintf(stdout,
219 "bin_cleanup: Sections were initially referenced in this order:\n");
220 for (h = 0, s = sections; s; h++, s = s->next)
221 fprintf(stdout, "%i. %s\n", h, s->name);
222 #endif
224 /* Assembly has completed, so now we need to generate the output file.
225 * Step 1: Separate progbits and nobits sections into separate lists.
226 * Step 2: Sort the progbits sections into their output order.
227 * Step 3: Compute start addresses for all progbits sections.
228 * Step 4: Compute vstart addresses for all sections.
229 * Step 5: Apply relocations.
230 * Step 6: Write the sections' data to the output file.
231 * Step 7: Generate the map file.
232 * Step 8: Release all allocated memory.
235 /* To do: Smart section-type adaptation could leave some empty sections
236 * without a defined type (progbits/nobits). Won't fix now since this
237 * feature will be disabled. */
239 /* Step 1: Split progbits and nobits sections into separate lists. */
241 nt = &nobits;
242 /* Move nobits sections into a separate list. Also pre-process nobits
243 * sections' attributes. */
244 for (sp = &sections->next, s = sections->next; s; s = *sp) { /* Skip progbits sections. */
245 if (s->flags & TYPE_PROGBITS) {
246 sp = &s->next;
247 continue;
249 /* Do some special pre-processing on nobits sections' attributes. */
250 if (s->flags & (START_DEFINED | ALIGN_DEFINED | FOLLOWS_DEFINED)) { /* Check for a mixture of real and virtual section attributes. */
251 if (s->
252 flags & (VSTART_DEFINED | VALIGN_DEFINED |
253 VFOLLOWS_DEFINED))
254 error(ERR_FATAL,
255 "cannot mix real and virtual attributes"
256 " in nobits section (%s)", s->name);
257 /* Real and virtual attributes mean the same thing for nobits sections. */
258 if (s->flags & START_DEFINED) {
259 s->vstart = s->start;
260 s->flags |= VSTART_DEFINED;
262 if (s->flags & ALIGN_DEFINED) {
263 s->valign = s->align;
264 s->flags |= VALIGN_DEFINED;
266 if (s->flags & FOLLOWS_DEFINED) {
267 s->vfollows = s->follows;
268 s->flags |= VFOLLOWS_DEFINED;
269 s->flags &= ~FOLLOWS_DEFINED;
272 /* Every section must have a start address. */
273 if (s->flags & VSTART_DEFINED) {
274 s->start = s->vstart;
275 s->flags |= START_DEFINED;
277 /* Move the section into the nobits list. */
278 *sp = s->next;
279 s->next = NULL;
280 *nt = s;
281 nt = &s->next;
284 /* Step 2: Sort the progbits sections into their output order. */
286 /* In Step 2 we move around sections in groups. A group
287 * begins with a section (group leader) that has a user-
288 * defined start address or follows section. The remainder
289 * of the group is made up of the sections that implicitly
290 * follow the group leader (i.e., they were defined after
291 * the group leader and were not given an explicit start
292 * address or follows section by the user). */
294 /* For anyone attempting to read this code:
295 * g (group) points to a group of sections, the first one of which has
296 * a user-defined start address or follows section.
297 * gp (g previous) holds the location of the pointer to g.
298 * gs (g scan) is a temp variable that we use to scan to the end of the group.
299 * gsp (gs previous) holds the location of the pointer to gs.
300 * nt (nobits tail) points to the nobits section-list tail.
303 /* Link all 'follows' groups to their proper position. To do
304 * this we need to know three things: the start of the group
305 * to relocate (g), the section it is following (s), and the
306 * end of the group we're relocating (gs). */
307 for (gp = &sections, g = sections; g; g = gs) { /* Find the next follows group that is out of place (g). */
308 if (!(g->flags & FOLLOWS_DEFINED)) {
309 while (g->next) {
310 if ((g->next->flags & FOLLOWS_DEFINED) &&
311 strcmp(g->name, g->next->follows))
312 break;
313 g = g->next;
315 if (!g->next)
316 break;
317 gp = &g->next;
318 g = g->next;
320 /* Find the section that this group follows (s). */
321 for (sp = &sections, s = sections;
322 s && strcmp(s->name, g->follows);
323 sp = &s->next, s = s->next) ;
324 if (!s)
325 error(ERR_FATAL, "section %s follows an invalid or"
326 " unknown section (%s)", g->name, g->follows);
327 if (s->next && (s->next->flags & FOLLOWS_DEFINED) &&
328 !strcmp(s->name, s->next->follows))
329 error(ERR_FATAL, "sections %s and %s can't both follow"
330 " section %s", g->name, s->next->name, s->name);
331 /* Find the end of the current follows group (gs). */
332 for (gsp = &g->next, gs = g->next;
333 gs && (gs != s) && !(gs->flags & START_DEFINED);
334 gsp = &gs->next, gs = gs->next) {
335 if (gs->next && (gs->next->flags & FOLLOWS_DEFINED) &&
336 strcmp(gs->name, gs->next->follows)) {
337 gsp = &gs->next;
338 gs = gs->next;
339 break;
342 /* Re-link the group after its follows section. */
343 *gsp = s->next;
344 s->next = g;
345 *gp = gs;
348 /* Link all 'start' groups to their proper position. Once
349 * again we need to know g, s, and gs (see above). The main
350 * difference is we already know g since we sort by moving
351 * groups from the 'unsorted' list into a 'sorted' list (g
352 * will always be the first section in the unsorted list). */
353 for (g = sections, sections = NULL; g; g = gs) { /* Find the section that we will insert this group before (s). */
354 for (sp = &sections, s = sections; s; sp = &s->next, s = s->next)
355 if ((s->flags & START_DEFINED) && (g->start < s->start))
356 break;
357 /* Find the end of the group (gs). */
358 for (gs = g->next, gsp = &g->next;
359 gs && !(gs->flags & START_DEFINED);
360 gsp = &gs->next, gs = gs->next) ;
361 /* Re-link the group before the target section. */
362 *sp = g;
363 *gsp = s;
366 /* Step 3: Compute start addresses for all progbits sections. */
368 /* Make sure we have an origin and a start address for the first section. */
369 if (origin_defined)
370 switch (sections->flags & (START_DEFINED | ALIGN_DEFINED)) {
371 case START_DEFINED | ALIGN_DEFINED:
372 case START_DEFINED:
373 /* Make sure this section doesn't begin before the origin. */
374 if (sections->start < origin)
375 error(ERR_FATAL, "section %s begins"
376 " before program origin", sections->name);
377 break;
378 case ALIGN_DEFINED:
379 sections->start = ((origin + sections->align - 1) &
380 ~(sections->align - 1));
381 break;
382 case 0:
383 sections->start = origin;
384 } else {
385 if (!(sections->flags & START_DEFINED))
386 sections->start = 0;
387 origin = sections->start;
389 sections->flags |= START_DEFINED;
391 /* Make sure each section has an explicit start address. If it
392 * doesn't, then compute one based its alignment and the end of
393 * the previous section. */
394 for (pend = sections->start, g = s = sections; g; g = g->next) { /* Find the next section that could cause an overlap situation
395 * (has a defined start address, and is not zero length). */
396 if (g == s)
397 for (s = g->next;
398 s && ((s->length == 0) || !(s->flags & START_DEFINED));
399 s = s->next) ;
400 /* Compute the start address of this section, if necessary. */
401 if (!(g->flags & START_DEFINED)) { /* Default to an alignment of 4 if unspecified. */
402 if (!(g->flags & ALIGN_DEFINED)) {
403 g->align = 4;
404 g->flags |= ALIGN_DEFINED;
406 /* Set the section start address. */
407 g->start = (pend + g->align - 1) & ~(g->align - 1);
408 g->flags |= START_DEFINED;
410 /* Ugly special case for progbits sections' virtual attributes:
411 * If there is a defined valign, but no vstart and no vfollows, then
412 * we valign after the previous progbits section. This case doesn't
413 * really make much sense for progbits sections with a defined start
414 * address, but it is possible and we must do *something*.
415 * Not-so-ugly special case:
416 * If a progbits section has no virtual attributes, we set the
417 * vstart equal to the start address. */
418 if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
419 if (g->flags & VALIGN_DEFINED)
420 g->vstart = (pend + g->valign - 1) & ~(g->valign - 1);
421 else
422 g->vstart = g->start;
423 g->flags |= VSTART_DEFINED;
425 /* Ignore zero-length sections. */
426 if (g->start < pend)
427 continue;
428 /* Compute the span of this section. */
429 pend = g->start + g->length;
430 /* Check for section overlap. */
431 if (s) {
432 if (g->start > s->start)
433 error(ERR_FATAL, "sections %s ~ %s and %s overlap!",
434 gs->name, g->name, s->name);
435 if (pend > s->start)
436 error(ERR_FATAL, "sections %s and %s overlap!",
437 g->name, s->name);
439 /* Remember this section as the latest >0 length section. */
440 gs = g;
443 /* Step 4: Compute vstart addresses for all sections. */
445 /* Attach the nobits sections to the end of the progbits sections. */
446 for (s = sections; s->next; s = s->next) ;
447 s->next = nobits;
448 last_progbits = s;
449 /* Scan for sections that don't have a vstart address. If we find one we'll
450 * attempt to compute its vstart. If we can't compute the vstart, we leave
451 * it alone and come back to it in a subsequent scan. We continue scanning
452 * and re-scanning until we've gone one full cycle without computing any
453 * vstarts. */
454 do { /* Do one full scan of the sections list. */
455 for (h = 0, g = sections; g; g = g->next) {
456 if (g->flags & VSTART_DEFINED)
457 continue;
458 /* Find the section that this one virtually follows. */
459 if (g->flags & VFOLLOWS_DEFINED) {
460 for (s = sections; s && strcmp(g->vfollows, s->name);
461 s = s->next) ;
462 if (!s)
463 error(ERR_FATAL,
464 "section %s vfollows unknown section (%s)",
465 g->name, g->vfollows);
466 } else if (g->ifollows != NULL)
467 for (s = sections; s && (s != g->ifollows); s = s->next) ;
468 /* The .bss section is the only one with ifollows = NULL. In this case we
469 * implicitly follow the last progbits section. */
470 else
471 s = last_progbits;
473 /* If the section we're following has a vstart, we can proceed. */
474 if (s->flags & VSTART_DEFINED) { /* Default to virtual alignment of four. */
475 if (!(g->flags & VALIGN_DEFINED)) {
476 g->valign = 4;
477 g->flags |= VALIGN_DEFINED;
479 /* Compute the vstart address. */
480 g->vstart =
481 (s->vstart + s->length + g->valign - 1) & ~(g->valign -
483 g->flags |= VSTART_DEFINED;
484 h++;
485 /* Start and vstart mean the same thing for nobits sections. */
486 if (g->flags & TYPE_NOBITS)
487 g->start = g->vstart;
490 } while (h);
492 /* Now check for any circular vfollows references, which will manifest
493 * themselves as sections without a defined vstart. */
494 for (h = 0, s = sections; s; s = s->next) {
495 if (!(s->flags & VSTART_DEFINED)) { /* Non-fatal errors after assembly has completed are generally a
496 * no-no, but we'll throw a fatal one eventually so it's ok. */
497 error(ERR_NONFATAL, "cannot compute vstart for section %s",
498 s->name);
499 h++;
502 if (h)
503 error(ERR_FATAL, "circular vfollows path detected");
505 #ifdef DEBUG
506 fprintf(stdout,
507 "bin_cleanup: Confirm final section order for output file:\n");
508 for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
509 h++, s = s->next)
510 fprintf(stdout, "%i. %s\n", h, s->name);
511 #endif
513 /* Step 5: Apply relocations. */
515 /* Prepare the sections for relocating. */
516 for (s = sections; s; s = s->next)
517 saa_rewind(s->contents);
518 /* Apply relocations. */
519 for (r = relocs; r; r = r->next) {
520 unsigned char *p, *q, mydata[4];
521 long l;
523 saa_fread(r->target->contents, r->posn, mydata, r->bytes);
524 p = q = mydata;
525 l = *p++;
527 if (r->bytes > 1) {
528 l += ((long)*p++) << 8;
529 if (r->bytes == 4) {
530 l += ((long)*p++) << 16;
531 l += ((long)*p++) << 24;
535 s = find_section_by_index(r->secref);
536 if (s) {
537 if (r->secref == s->start_index)
538 l += s->start;
539 else
540 l += s->vstart;
542 s = find_section_by_index(r->secrel);
543 if (s) {
544 if (r->secrel == s->start_index)
545 l -= s->start;
546 else
547 l -= s->vstart;
550 if (r->bytes == 4)
551 WRITELONG(q, l);
552 else if (r->bytes == 2)
553 WRITESHORT(q, l);
554 else
555 *q++ = (unsigned char)(l & 0xFF);
556 saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
559 /* Step 6: Write the section data to the output file. */
561 /* Write the progbits sections to the output file. */
562 for (pend = origin, s = sections; s && (s->flags & TYPE_PROGBITS); s = s->next) { /* Skip zero-length sections. */
563 if (s->length == 0)
564 continue;
565 /* Pad the space between sections. */
566 for (h = s->start - pend; h; h--)
567 fputc('\0', fp);
568 /* Write the section to the output file. */
569 if (s->length > 0)
570 saa_fpwrite(s->contents, fp);
571 pend = s->start + s->length;
573 /* Done writing the file, so close it. */
574 fclose(fp);
576 /* Step 7: Generate the map file. */
578 if (map_control) {
579 const char *not_defined = { "not defined" };
581 /* Display input and output file names. */
582 fprintf(rf, "\n- NASM Map file ");
583 for (h = 63; h; h--)
584 fputc('-', rf);
585 fprintf(rf, "\n\nSource file: %s\nOutput file: %s\n\n",
586 infile, outfile);
588 if (map_control & MAP_ORIGIN) { /* Display program origin. */
589 fprintf(rf, "-- Program origin ");
590 for (h = 61; h; h--)
591 fputc('-', rf);
592 fprintf(rf, "\n\n%08lX\n\n", origin);
594 /* Display sections summary. */
595 if (map_control & MAP_SUMMARY) {
596 fprintf(rf, "-- Sections (summary) ");
597 for (h = 57; h; h--)
598 fputc('-', rf);
599 fprintf(rf, "\n\nVstart Start Stop "
600 "Length Class Name\n");
601 for (s = sections; s; s = s->next) {
602 fprintf(rf, "%08lX %08lX %08lX %08lX ",
603 s->vstart, s->start, s->start + s->length,
604 s->length);
605 if (s->flags & TYPE_PROGBITS)
606 fprintf(rf, "progbits ");
607 else
608 fprintf(rf, "nobits ");
609 fprintf(rf, "%s\n", s->name);
611 fprintf(rf, "\n");
613 /* Display detailed section information. */
614 if (map_control & MAP_SECTIONS) {
615 fprintf(rf, "-- Sections (detailed) ");
616 for (h = 56; h; h--)
617 fputc('-', rf);
618 fprintf(rf, "\n\n");
619 for (s = sections; s; s = s->next) {
620 fprintf(rf, "---- Section %s ", s->name);
621 for (h = 65 - strlen(s->name); h; h--)
622 fputc('-', rf);
623 fprintf(rf, "\n\nclass: ");
624 if (s->flags & TYPE_PROGBITS)
625 fprintf(rf, "progbits");
626 else
627 fprintf(rf, "nobits");
628 fprintf(rf, "\nlength: %08lX\nstart: %08lX"
629 "\nalign: ", s->length, s->start);
630 if (s->flags & ALIGN_DEFINED)
631 fprintf(rf, "%08lX", s->align);
632 else
633 fprintf(rf, not_defined);
634 fprintf(rf, "\nfollows: ");
635 if (s->flags & FOLLOWS_DEFINED)
636 fprintf(rf, "%s", s->follows);
637 else
638 fprintf(rf, not_defined);
639 fprintf(rf, "\nvstart: %08lX\nvalign: ", s->vstart);
640 if (s->flags & VALIGN_DEFINED)
641 fprintf(rf, "%08lX", s->valign);
642 else
643 fprintf(rf, not_defined);
644 fprintf(rf, "\nvfollows: ");
645 if (s->flags & VFOLLOWS_DEFINED)
646 fprintf(rf, "%s", s->vfollows);
647 else
648 fprintf(rf, not_defined);
649 fprintf(rf, "\n\n");
652 /* Display symbols information. */
653 if (map_control & MAP_SYMBOLS) {
654 long segment, offset;
656 fprintf(rf, "-- Symbols ");
657 for (h = 68; h; h--)
658 fputc('-', rf);
659 fprintf(rf, "\n\n");
660 if (no_seg_labels) {
661 fprintf(rf, "---- No Section ");
662 for (h = 63; h; h--)
663 fputc('-', rf);
664 fprintf(rf, "\n\nValue Name\n");
665 for (l = no_seg_labels; l; l = l->next) {
666 lookup_label(l->name, &segment, &offset);
667 fprintf(rf, "%08lX %s\n", offset, l->name);
669 fprintf(rf, "\n\n");
671 for (s = sections; s; s = s->next) {
672 if (s->labels) {
673 fprintf(rf, "---- Section %s ", s->name);
674 for (h = 65 - strlen(s->name); h; h--)
675 fputc('-', rf);
676 fprintf(rf, "\n\nReal Virtual Name\n");
677 for (l = s->labels; l; l = l->next) {
678 lookup_label(l->name, &segment, &offset);
679 fprintf(rf, "%08lX %08lX %s\n",
680 s->start + offset, s->vstart + offset,
681 l->name);
683 fprintf(rf, "\n");
689 /* Close the report file. */
690 if (map_control && (rf != stdout) && (rf != stderr))
691 fclose(rf);
693 /* Step 8: Release all allocated memory. */
695 /* Free sections, label pointer structs, etc.. */
696 while (sections) {
697 s = sections;
698 sections = s->next;
699 saa_free(s->contents);
700 nasm_free(s->name);
701 if (s->flags & FOLLOWS_DEFINED)
702 nasm_free(s->follows);
703 if (s->flags & VFOLLOWS_DEFINED)
704 nasm_free(s->vfollows);
705 while (s->labels) {
706 l = s->labels;
707 s->labels = l->next;
708 nasm_free(l);
710 nasm_free(s);
713 /* Free no-section labels. */
714 while (no_seg_labels) {
715 l = no_seg_labels;
716 no_seg_labels = l->next;
717 nasm_free(l);
720 /* Free relocation structures. */
721 while (relocs) {
722 r = relocs->next;
723 nasm_free(relocs);
724 relocs = r;
728 static void bin_out(long segto, const void *data, unsigned long type,
729 long segment, long wrt)
731 unsigned char *p, mydata[4];
732 struct Section *s;
733 long realbytes;
735 if (wrt != NO_SEG) {
736 wrt = NO_SEG; /* continue to do _something_ */
737 error(ERR_NONFATAL, "WRT not supported by binary output format");
740 /* Handle absolute-assembly (structure definitions). */
741 if (segto == NO_SEG) {
742 if ((type & OUT_TYPMASK) != OUT_RESERVE)
743 error(ERR_NONFATAL, "attempt to assemble code in"
744 " [ABSOLUTE] space");
745 return;
748 /* Find the segment we are targeting. */
749 s = find_section_by_index(segto);
750 if (!s)
751 error(ERR_PANIC, "code directed to nonexistent segment?");
753 /* "Smart" section-type adaptation code. */
754 if (!(s->flags & TYPE_DEFINED)) {
755 if ((type & OUT_TYPMASK) == OUT_RESERVE)
756 s->flags |= TYPE_DEFINED | TYPE_NOBITS;
757 else
758 s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
761 if ((s->flags & TYPE_NOBITS) && ((type & OUT_TYPMASK) != OUT_RESERVE))
762 error(ERR_WARNING, "attempt to initialise memory in a"
763 " nobits section: ignored");
765 if ((type & OUT_TYPMASK) == OUT_ADDRESS) {
766 if (segment != NO_SEG && !find_section_by_index(segment)) {
767 if (segment % 2)
768 error(ERR_NONFATAL, "binary output format does not support"
769 " segment base references");
770 else
771 error(ERR_NONFATAL, "binary output format does not support"
772 " external references");
773 segment = NO_SEG;
775 if (s->flags & TYPE_PROGBITS) {
776 if (segment != NO_SEG)
777 add_reloc(s, type & OUT_SIZMASK, segment, -1L);
778 p = mydata;
779 if ((type & OUT_SIZMASK) == 4)
780 WRITELONG(p, *(long *)data);
781 else
782 WRITESHORT(p, *(long *)data);
783 saa_wbytes(s->contents, mydata, type & OUT_SIZMASK);
785 s->length += type & OUT_SIZMASK;
786 } else if ((type & OUT_TYPMASK) == OUT_RAWDATA) {
787 type &= OUT_SIZMASK;
788 if (s->flags & TYPE_PROGBITS)
789 saa_wbytes(s->contents, data, type);
790 s->length += type;
791 } else if ((type & OUT_TYPMASK) == OUT_RESERVE) {
792 type &= OUT_SIZMASK;
793 if (s->flags & TYPE_PROGBITS) {
794 error(ERR_WARNING, "uninitialised space declared in"
795 " %s section: zeroing", s->name);
796 saa_wbytes(s->contents, NULL, type);
798 s->length += type;
799 } else if ((type & OUT_TYPMASK) == OUT_REL2ADR ||
800 (type & OUT_TYPMASK) == OUT_REL4ADR) {
801 realbytes = ((type & OUT_TYPMASK) == OUT_REL4ADR ? 4 : 2);
802 if (segment != NO_SEG && !find_section_by_index(segment)) {
803 if (segment % 2)
804 error(ERR_NONFATAL, "binary output format does not support"
805 " segment base references");
806 else
807 error(ERR_NONFATAL, "binary output format does not support"
808 " external references");
809 segment = NO_SEG;
811 if (s->flags & TYPE_PROGBITS) {
812 add_reloc(s, realbytes, segment, segto);
813 p = mydata;
814 if (realbytes == 4)
815 WRITELONG(p, *(long *)data - realbytes - s->length);
816 else
817 WRITESHORT(p, *(long *)data - realbytes - s->length);
818 saa_wbytes(s->contents, mydata, realbytes);
820 s->length += realbytes;
824 static void bin_deflabel(char *name, long segment, long offset,
825 int is_global, char *special)
827 (void)segment; /* Don't warn that this parameter is unused */
828 (void)offset; /* Don't warn that this parameter is unused */
830 if (special)
831 error(ERR_NONFATAL, "binary format does not support any"
832 " special symbol types");
833 else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
834 error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
835 else if (is_global == 2)
836 error(ERR_NONFATAL, "binary output format does not support common"
837 " variables");
838 else {
839 struct Section *s;
840 struct bin_label ***ltp;
842 /* Remember label definition so we can look it up later when
843 * creating the map file. */
844 s = find_section_by_index(segment);
845 if (s)
846 ltp = &(s->labels_end);
847 else
848 ltp = &nsl_tail;
849 (**ltp) = nasm_malloc(sizeof(struct bin_label));
850 (**ltp)->name = name;
851 (**ltp)->next = NULL;
852 *ltp = &((**ltp)->next);
857 /* These constants and the following function are used
858 * by bin_secname() to parse attribute assignments. */
860 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
861 ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
862 ATTRIB_NOBITS, ATTRIB_PROGBITS
865 static int bin_read_attribute(char **line, int *attribute,
866 unsigned long *value)
868 expr *e;
869 int attrib_name_size;
870 struct tokenval tokval;
871 char *exp;
873 /* Skip whitespace. */
874 while (**line && isspace(**line))
875 (*line)++;
876 if (!**line)
877 return 0;
879 /* Figure out what attribute we're reading. */
880 if (!nasm_strnicmp(*line, "align=", 6)) {
881 *attribute = ATTRIB_ALIGN;
882 attrib_name_size = 6;
883 } else if (format_mode) {
884 if (!nasm_strnicmp(*line, "start=", 6)) {
885 *attribute = ATTRIB_START;
886 attrib_name_size = 6;
887 } else if (!nasm_strnicmp(*line, "follows=", 8)) {
888 *attribute = ATTRIB_FOLLOWS;
889 *line += 8;
890 return 1;
891 } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
892 *attribute = ATTRIB_VSTART;
893 attrib_name_size = 7;
894 } else if (!nasm_strnicmp(*line, "valign=", 7)) {
895 *attribute = ATTRIB_VALIGN;
896 attrib_name_size = 7;
897 } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
898 *attribute = ATTRIB_VFOLLOWS;
899 *line += 9;
900 return 1;
901 } else if (!nasm_strnicmp(*line, "nobits", 6) &&
902 (isspace((*line)[6]) || ((*line)[6] == '\0'))) {
903 *attribute = ATTRIB_NOBITS;
904 *line += 6;
905 return 1;
906 } else if (!nasm_strnicmp(*line, "progbits", 8) &&
907 (isspace((*line)[8]) || ((*line)[8] == '\0'))) {
908 *attribute = ATTRIB_PROGBITS;
909 *line += 8;
910 return 1;
911 } else
912 return 0;
913 } else
914 return 0;
916 /* Find the end of the expression. */
917 if ((*line)[attrib_name_size] != '(') {
918 /* Single term (no parenthesis). */
919 exp = *line += attrib_name_size;
920 while (**line && !isspace(**line))
921 (*line)++;
922 if (**line) {
923 **line = '\0';
924 (*line)++;
926 } else {
927 char c;
928 int pcount = 1;
930 /* Full expression (delimited by parenthesis) */
931 exp = *line += attrib_name_size + 1;
932 while (1) {
933 (*line) += strcspn(*line, "()'\"");
934 if (**line == '(') {
935 ++(*line);
936 ++pcount;
938 if (**line == ')') {
939 ++(*line);
940 --pcount;
941 if (!pcount)
942 break;
944 if ((**line == '"') || (**line == '\'')) {
945 c = **line;
946 while (**line) {
947 ++(*line);
948 if (**line == c)
949 break;
951 if (!**line) {
952 error(ERR_NONFATAL,
953 "invalid syntax in `section' directive");
954 return -1;
956 ++(*line);
958 if (!**line) {
959 error(ERR_NONFATAL, "expecting `)'");
960 return -1;
963 *(*line - 1) = '\0'; /* Terminate the expression. */
966 /* Check for no value given. */
967 if (!*exp) {
968 error(ERR_WARNING, "No value given to attribute in"
969 " `section' directive");
970 return -1;
973 /* Read and evaluate the expression. */
974 stdscan_reset();
975 stdscan_bufptr = exp;
976 tokval.t_type = TOKEN_INVALID;
977 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
978 if (e) {
979 if (!is_really_simple(e)) {
980 error(ERR_NONFATAL, "section attribute value must be"
981 " a critical expression");
982 return -1;
984 } else {
985 error(ERR_NONFATAL, "Invalid attribute value"
986 " specified in `section' directive.");
987 return -1;
989 *value = (unsigned long)reloc_value(e);
990 return 1;
993 static void bin_assign_attributes(struct Section *sec, char *astring)
995 int attribute, check;
996 unsigned long value;
997 char *p;
999 while (1) { /* Get the next attribute. */
1000 check = bin_read_attribute(&astring, &attribute, &value);
1001 /* Skip bad attribute. */
1002 if (check == -1)
1003 continue;
1004 /* Unknown section attribute, so skip it and warn the user. */
1005 if (!check) {
1006 if (!*astring)
1007 break; /* End of line. */
1008 else {
1009 p = astring;
1010 while (*astring && !isspace(*astring))
1011 astring++;
1012 if (*astring) {
1013 *astring = '\0';
1014 astring++;
1016 error(ERR_WARNING, "ignoring unknown section attribute:"
1017 " \"%s\"", p);
1019 continue;
1022 switch (attribute) { /* Handle nobits attribute. */
1023 case ATTRIB_NOBITS:
1024 if ((sec->flags & TYPE_DEFINED)
1025 && (sec->flags & TYPE_PROGBITS))
1026 error(ERR_NONFATAL,
1027 "attempt to change section type"
1028 " from progbits to nobits");
1029 else
1030 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1031 continue;
1033 /* Handle progbits attribute. */
1034 case ATTRIB_PROGBITS:
1035 if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1036 error(ERR_NONFATAL, "attempt to change section type"
1037 " from nobits to progbits");
1038 else
1039 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1040 continue;
1042 /* Handle align attribute. */
1043 case ATTRIB_ALIGN:
1044 if (!format_mode && (!strcmp(sec->name, ".text")))
1045 error(ERR_NONFATAL, "cannot specify an alignment"
1046 " to the .text section");
1047 else {
1048 if (!value || ((value - 1) & value))
1049 error(ERR_NONFATAL, "argument to `align' is not a"
1050 " power of two");
1051 else { /* Alignment is already satisfied if the previous
1052 * align value is greater. */
1053 if ((sec->flags & ALIGN_DEFINED)
1054 && (value < sec->align))
1055 value = sec->align;
1057 /* Don't allow a conflicting align value. */
1058 if ((sec->flags & START_DEFINED)
1059 && (sec->start & (value - 1)))
1060 error(ERR_NONFATAL,
1061 "`align' value conflicts "
1062 "with section start address");
1063 else {
1064 sec->align = value;
1065 sec->flags |= ALIGN_DEFINED;
1069 continue;
1071 /* Handle valign attribute. */
1072 case ATTRIB_VALIGN:
1073 if (!value || ((value - 1) & value))
1074 error(ERR_NONFATAL, "argument to `valign' is not a"
1075 " power of two");
1076 else { /* Alignment is already satisfied if the previous
1077 * align value is greater. */
1078 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1079 value = sec->valign;
1081 /* Don't allow a conflicting valign value. */
1082 if ((sec->flags & VSTART_DEFINED)
1083 && (sec->vstart & (value - 1)))
1084 error(ERR_NONFATAL,
1085 "`valign' value conflicts "
1086 "with `vstart' address");
1087 else {
1088 sec->valign = value;
1089 sec->flags |= VALIGN_DEFINED;
1092 continue;
1094 /* Handle start attribute. */
1095 case ATTRIB_START:
1096 if (sec->flags & FOLLOWS_DEFINED)
1097 error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1098 " section attributes");
1099 else if (value < 0)
1100 error(ERR_NONFATAL, "attempt to specify a negative"
1101 " section start address");
1102 else if ((sec->flags & START_DEFINED) && (value != sec->start))
1103 error(ERR_NONFATAL, "section start address redefined");
1104 else {
1105 sec->start = value;
1106 sec->flags |= START_DEFINED;
1107 if (sec->flags & ALIGN_DEFINED) {
1108 if (sec->start & (sec->align - 1))
1109 error(ERR_NONFATAL, "`start' address conflicts"
1110 " with section alignment");
1111 sec->flags ^= ALIGN_DEFINED;
1114 continue;
1116 /* Handle vstart attribute. */
1117 case ATTRIB_VSTART:
1118 if (sec->flags & VFOLLOWS_DEFINED)
1119 error(ERR_NONFATAL,
1120 "cannot combine `vstart' and `vfollows'"
1121 " section attributes");
1122 else if ((sec->flags & VSTART_DEFINED)
1123 && (value != sec->vstart))
1124 error(ERR_NONFATAL,
1125 "section virtual start address"
1126 " (vstart) redefined");
1127 else {
1128 sec->vstart = value;
1129 sec->flags |= VSTART_DEFINED;
1130 if (sec->flags & VALIGN_DEFINED) {
1131 if (sec->vstart & (sec->valign - 1))
1132 error(ERR_NONFATAL, "`vstart' address conflicts"
1133 " with `valign' value");
1134 sec->flags ^= VALIGN_DEFINED;
1137 continue;
1139 /* Handle follows attribute. */
1140 case ATTRIB_FOLLOWS:
1141 p = astring;
1142 astring += strcspn(astring, " \t");
1143 if (astring == p)
1144 error(ERR_NONFATAL, "expecting section name for `follows'"
1145 " attribute");
1146 else {
1147 *(astring++) = '\0';
1148 if (sec->flags & START_DEFINED)
1149 error(ERR_NONFATAL,
1150 "cannot combine `start' and `follows'"
1151 " section attributes");
1152 sec->follows = nasm_strdup(p);
1153 sec->flags |= FOLLOWS_DEFINED;
1155 continue;
1157 /* Handle vfollows attribute. */
1158 case ATTRIB_VFOLLOWS:
1159 if (sec->flags & VSTART_DEFINED)
1160 error(ERR_NONFATAL,
1161 "cannot combine `vstart' and `vfollows'"
1162 " section attributes");
1163 else {
1164 p = astring;
1165 astring += strcspn(astring, " \t");
1166 if (astring == p)
1167 error(ERR_NONFATAL,
1168 "expecting section name for `vfollows'"
1169 " attribute");
1170 else {
1171 *(astring++) = '\0';
1172 sec->vfollows = nasm_strdup(p);
1173 sec->flags |= VFOLLOWS_DEFINED;
1176 continue;
1181 static void bin_define_section_labels()
1183 static int labels_defined = 0;
1184 struct Section *sec;
1185 char *label_name;
1186 size_t base_len;
1188 if (labels_defined)
1189 return;
1190 for (sec = sections; sec; sec = sec->next) {
1191 base_len = strlen(sec->name) + 8;
1192 label_name = nasm_malloc(base_len + 8);
1193 strcpy(label_name, "section.");
1194 strcpy(label_name + 8, sec->name);
1196 /* section.<name>.start */
1197 strcpy(label_name + base_len, ".start");
1198 define_label(label_name, sec->start_index, 0L,
1199 NULL, 0, 0, bin_get_ofmt(), error);
1201 /* section.<name>.vstart */
1202 strcpy(label_name + base_len, ".vstart");
1203 define_label(label_name, sec->vstart_index, 0L,
1204 NULL, 0, 0, bin_get_ofmt(), error);
1206 nasm_free(label_name);
1208 labels_defined = 1;
1211 static long bin_secname(char *name, int pass, int *bits)
1213 char *p;
1214 struct Section *sec;
1216 /* bin_secname is called with *name = NULL at the start of each
1217 * pass. Use this opportunity to establish the default section
1218 * (default is BITS-16 ".text" segment).
1220 if (!name) { /* Reset ORG and section attributes at the start of each pass. */
1221 origin_defined = 0;
1222 for (sec = sections; sec; sec = sec->next)
1223 sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1224 ALIGN_DEFINED | VALIGN_DEFINED);
1226 /* Define section start and vstart labels. */
1227 if (format_mode && (pass != 1))
1228 bin_define_section_labels();
1230 /* Establish the default (.text) section. */
1231 *bits = 16;
1232 sec = find_section_by_name(".text");
1233 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1234 current_section = sec->vstart_index;
1235 return current_section;
1238 /* Attempt to find the requested section. If it does not
1239 * exist, create it. */
1240 p = name;
1241 while (*p && !isspace(*p))
1242 p++;
1243 if (*p)
1244 *p++ = '\0';
1245 sec = find_section_by_name(name);
1246 if (!sec) {
1247 sec = create_section(name);
1248 if (!strcmp(name, ".data"))
1249 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1250 else if (!strcmp(name, ".bss")) {
1251 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1252 sec->ifollows = NULL;
1253 } else if (!format_mode) {
1254 error(ERR_NONFATAL, "section name must be "
1255 ".text, .data, or .bss");
1256 return current_section;
1260 /* Handle attribute assignments. */
1261 if (pass != 1)
1262 bin_assign_attributes(sec, p);
1264 #ifndef ABIN_SMART_ADAPT
1265 /* The following line disables smart adaptation of
1266 * PROGBITS/NOBITS section types (it forces sections to
1267 * default to PROGBITS). */
1268 if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1269 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1270 #endif
1272 /* Set the current section and return. */
1273 current_section = sec->vstart_index;
1274 return current_section;
1277 static int bin_directive(char *directive, char *args, int pass)
1279 /* Handle ORG directive */
1280 if (!nasm_stricmp(directive, "org")) {
1281 struct tokenval tokval;
1282 unsigned long value;
1283 expr *e;
1285 stdscan_reset();
1286 stdscan_bufptr = args;
1287 tokval.t_type = TOKEN_INVALID;
1288 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
1289 if (e) {
1290 if (!is_really_simple(e))
1291 error(ERR_NONFATAL, "org value must be a critical"
1292 " expression");
1293 else {
1294 value = reloc_value(e);
1295 /* Check for ORG redefinition. */
1296 if (origin_defined && (value != origin))
1297 error(ERR_NONFATAL, "program origin redefined");
1298 else {
1299 origin = value;
1300 origin_defined = 1;
1303 } else
1304 error(ERR_NONFATAL, "No or invalid offset specified"
1305 " in ORG directive.");
1306 return 1;
1309 /* The 'map' directive allows the user to generate section
1310 * and symbol information to stdout, stderr, or to a file. */
1311 else if (format_mode && !nasm_stricmp(directive, "map")) {
1312 char *p;
1314 if (pass != 1)
1315 return 1;
1316 args += strspn(args, " \t");
1317 while (*args) {
1318 p = args;
1319 args += strcspn(args, " \t");
1320 if (*args != '\0')
1321 *(args++) = '\0';
1322 if (!nasm_stricmp(p, "all"))
1323 map_control |=
1324 MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1325 else if (!nasm_stricmp(p, "brief"))
1326 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1327 else if (!nasm_stricmp(p, "sections"))
1328 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1329 else if (!nasm_stricmp(p, "segments"))
1330 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1331 else if (!nasm_stricmp(p, "symbols"))
1332 map_control |= MAP_SYMBOLS;
1333 else if (!rf) {
1334 if (!nasm_stricmp(p, "stdout"))
1335 rf = stdout;
1336 else if (!nasm_stricmp(p, "stderr"))
1337 rf = stderr;
1338 else { /* Must be a filename. */
1339 rf = fopen(p, "wt");
1340 if (!rf) {
1341 error(ERR_WARNING, "unable to open map file `%s'",
1343 map_control = 0;
1344 return 1;
1347 } else
1348 error(ERR_WARNING, "map file already specified");
1350 if (map_control == 0)
1351 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1352 if (!rf)
1353 rf = stdout;
1354 return 1;
1356 return 0;
1359 static void bin_filename(char *inname, char *outname, efunc error)
1361 standard_extension(inname, outname, "", error);
1362 infile = inname;
1363 outfile = outname;
1366 static long bin_segbase(long segment)
1368 return segment;
1371 static int bin_set_info(enum geninfo type, char **val)
1373 return 0;
1376 static void bin_init(FILE * afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1378 fp = afp;
1379 error = errfunc;
1381 (void)eval; /* Don't warn that this parameter is unused. */
1382 (void)ldef; /* Placate optimizers. */
1384 relocs = NULL;
1385 reloctail = &relocs;
1386 origin_defined = 0;
1387 no_seg_labels = NULL;
1388 nsl_tail = &no_seg_labels;
1389 format_mode = 1; /* Extended bin format
1390 * (set this to zero for old bin format). */
1392 /* Create default section (.text). */
1393 sections = last_section = nasm_malloc(sizeof(struct Section));
1394 last_section->next = NULL;
1395 last_section->name = nasm_strdup(".text");
1396 last_section->contents = saa_init(1L);
1397 last_section->follows = last_section->vfollows = 0;
1398 last_section->ifollows = NULL;
1399 last_section->length = 0;
1400 last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1401 last_section->labels = NULL;
1402 last_section->labels_end = &(last_section->labels);
1403 last_section->start_index = seg_alloc();
1404 last_section->vstart_index = current_section = seg_alloc();
1407 struct ofmt of_bin = {
1408 "flat-form binary files (e.g. DOS .COM, .SYS)",
1409 "bin",
1410 NULL,
1411 null_debug_arr,
1412 &null_debug_form,
1413 bin_stdmac,
1414 bin_init,
1415 bin_set_info,
1416 bin_out,
1417 bin_deflabel,
1418 bin_secname,
1419 bin_segbase,
1420 bin_directive,
1421 bin_filename,
1422 bin_cleanup
1425 /* This is needed for bin_define_section_labels() */
1426 struct ofmt *bin_get_ofmt()
1428 return &of_bin;
1431 #endif /* #ifdef OF_BIN */