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