Hash even backend-specific directives, unify null functions
[platform/upstream/nasm.git] / output / outbin.c
1 /* ----------------------------------------------------------------------- *
2  *   
3  *   Copyright 1996-2009 The NASM Authors - All Rights Reserved
4  *   See the file AUTHORS included with the NASM distribution for
5  *   the specific copyright holders.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following
9  *   conditions are met:
10  *
11  *   * Redistributions of source code must retain the above copyright
12  *     notice, this list of conditions and the following disclaimer.
13  *   * Redistributions in binary form must reproduce the above
14  *     copyright notice, this list of conditions and the following
15  *     disclaimer in the documentation and/or other materials provided
16  *     with the distribution.
17  *     
18  *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19  *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20  *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21  *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23  *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24  *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25  *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29  *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30  *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  * ----------------------------------------------------------------------- */
33
34 /* 
35  * outbin.c output routines for the Netwide Assembler to produce
36  *    flat-form binary files
37  */
38
39 /* This is the extended version of NASM's original binary output
40  * format.  It is backward compatible with the original BIN format,
41  * and contains support for multiple sections and advanced section
42  * ordering.
43  *
44  * Feature summary:
45  *
46  * - Users can create an arbitrary number of sections; they are not
47  *   limited to just ".text", ".data", and ".bss".
48  *
49  * - Sections can be either progbits or nobits type.
50  *
51  * - You can specify that they be aligned at a certian boundary
52  *   following the previous section ("align="), or positioned at an
53  *   arbitrary byte-granular location ("start=").
54  *
55  * - You can specify a "virtual" start address for a section, which
56  *   will be used for the calculation for all address references
57  *   with respect to that section ("vstart=").
58  *
59  * - The ORG directive, as well as the section/segment directive
60  *   arguments ("align=", "start=", "vstart="), can take a critical
61  *   expression as their value.  For example: "align=(1 << 12)".
62  *
63  * - You can generate map files using the 'map' directive.
64  *
65  */
66
67 /* Uncomment the following define if you want sections to adapt
68  * their progbits/nobits state depending on what type of
69  * instructions are issued, rather than defaulting to progbits.
70  * Note that this behavior violates the specification.
71
72 #define ABIN_SMART_ADAPT
73
74 */
75
76 #include "compiler.h"
77
78 #include <stdio.h>
79 #include <stdlib.h>
80 #include <string.h>
81 #include <ctype.h>
82 #include <inttypes.h>
83
84 #include "nasm.h"
85 #include "nasmlib.h"
86 #include "saa.h"
87 #include "stdscan.h"
88 #include "labels.h"
89 #include "eval.h"
90 #include "output/outform.h"
91 #include "output/outlib.h"
92
93 #ifdef OF_BIN
94
95 static FILE *fp, *rf = NULL;
96 static efunc error;
97 static struct ofmt *my_ofmt;
98 static void (*do_output)(void);
99
100 /* Section flags keep track of which attributes the user has defined. */
101 #define START_DEFINED       0x001
102 #define ALIGN_DEFINED       0x002
103 #define FOLLOWS_DEFINED     0x004
104 #define VSTART_DEFINED      0x008
105 #define VALIGN_DEFINED      0x010
106 #define VFOLLOWS_DEFINED    0x020
107 #define TYPE_DEFINED        0x040
108 #define TYPE_PROGBITS       0x080
109 #define TYPE_NOBITS         0x100
110
111 /* This struct is used to keep track of symbols for map-file generation. */
112 static struct bin_label {
113     char *name;
114     struct bin_label *next;
115 } *no_seg_labels, **nsl_tail;
116
117 static struct Section {
118     char *name;
119     struct SAA *contents;
120     int64_t length;                /* section length in bytes */
121
122 /* Section attributes */
123     int flags;                  /* see flag definitions above */
124     uint64_t align;        /* section alignment */
125     uint64_t valign;       /* notional section alignment */
126     uint64_t start;        /* section start address */
127     uint64_t vstart;       /* section virtual start address */
128     char *follows;              /* the section that this one will follow */
129     char *vfollows;             /* the section that this one will notionally follow */
130     int32_t start_index;           /* NASM section id for non-relocated version */
131     int32_t vstart_index;          /* the NASM section id */
132
133     struct bin_label *labels;   /* linked-list of label handles for map output. */
134     struct bin_label **labels_end;      /* Holds address of end of labels list. */
135     struct Section *ifollows;   /* Points to previous section (implicit follows). */
136     struct Section *next;       /* This links sections with a defined start address. */
137
138 /* The extended bin format allows for sections to have a "virtual"
139  * start address.  This is accomplished by creating two sections:
140  * one beginning at the Load Memory Address and the other beginning
141  * at the Virtual Memory Address.  The LMA section is only used to
142  * define the section.<section_name>.start label, but there isn't
143  * any other good way for us to handle that label.
144  */
145
146 } *sections, *last_section;
147
148 static struct Reloc {
149     struct Reloc *next;
150     int32_t posn;
151     int32_t bytes;
152     int32_t secref;
153     int32_t secrel;
154     struct Section *target;
155 } *relocs, **reloctail;
156
157 extern char *stdscan_bufptr;
158
159 static uint8_t format_mode;       /* 0 = original bin, 1 = extended bin */
160 static int32_t current_section;    /* only really needed if format_mode = 0 */
161 static uint64_t origin;
162 static int origin_defined;
163
164 /* Stuff we need for map-file generation. */
165 #define MAP_ORIGIN       1
166 #define MAP_SUMMARY      2
167 #define MAP_SECTIONS     4
168 #define MAP_SYMBOLS      8
169 static int map_control = 0;
170 static char *infile, *outfile;
171
172 extern macros_t bin_stdmac[];
173
174 static void add_reloc(struct Section *s, int32_t bytes, int32_t secref,
175                       int32_t secrel)
176 {
177     struct Reloc *r;
178
179     r = *reloctail = nasm_malloc(sizeof(struct Reloc));
180     reloctail = &r->next;
181     r->next = NULL;
182     r->posn = s->length;
183     r->bytes = bytes;
184     r->secref = secref;
185     r->secrel = secrel;
186     r->target = s;
187 }
188
189 static struct Section *find_section_by_name(const char *name)
190 {
191     struct Section *s;
192
193     for (s = sections; s; s = s->next)
194         if (!strcmp(s->name, name))
195             break;
196     return s;
197 }
198
199 static struct Section *find_section_by_index(int32_t index)
200 {
201     struct Section *s;
202
203     for (s = sections; s; s = s->next)
204         if ((index == s->vstart_index) || (index == s->start_index))
205             break;
206     return s;
207 }
208
209 static struct Section *create_section(char *name)
210 {                               /* Create a new section. */
211     last_section->next = nasm_malloc(sizeof(struct Section));
212     last_section->next->ifollows = last_section;
213     last_section = last_section->next;
214     last_section->labels = NULL;
215     last_section->labels_end = &(last_section->labels);
216
217     /* Initialize section attributes. */
218     last_section->name = nasm_strdup(name);
219     last_section->contents = saa_init(1L);
220     last_section->follows = last_section->vfollows = 0;
221     last_section->length = 0;
222     last_section->flags = 0;
223     last_section->next = NULL;
224
225     /* Register our sections with NASM. */
226     last_section->vstart_index = seg_alloc();
227     last_section->start_index = seg_alloc();
228     return last_section;
229 }
230
231 static void bin_cleanup(int debuginfo)
232 {
233     struct Section *g, **gp;
234     struct Section *gs = NULL, **gsp;
235     struct Section *s, **sp;
236     struct Section *nobits = NULL, **nt;
237     struct Section *last_progbits;
238     struct bin_label *l;
239     struct Reloc *r;
240     uint64_t pend;
241     int h;
242
243     (void)debuginfo;      /* placate optimizers */
244
245 #ifdef DEBUG
246     fprintf(stdout,
247             "bin_cleanup: Sections were initially referenced in this order:\n");
248     for (h = 0, s = sections; s; h++, s = s->next)
249         fprintf(stdout, "%i. %s\n", h, s->name);
250 #endif
251
252     /* Assembly has completed, so now we need to generate the output file.
253      * Step 1: Separate progbits and nobits sections into separate lists.
254      * Step 2: Sort the progbits sections into their output order.
255      * Step 3: Compute start addresses for all progbits sections.
256      * Step 4: Compute vstart addresses for all sections.
257      * Step 5: Apply relocations.
258      * Step 6: Write the sections' data to the output file.
259      * Step 7: Generate the map file.
260      * Step 8: Release all allocated memory.
261      */
262
263     /* To do: Smart section-type adaptation could leave some empty sections
264      * without a defined type (progbits/nobits).  Won't fix now since this
265      * feature will be disabled.  */
266
267     /* Step 1: Split progbits and nobits sections into separate lists. */
268
269     nt = &nobits;
270     /* Move nobits sections into a separate list.  Also pre-process nobits
271      * sections' attributes. */
272     for (sp = &sections->next, s = sections->next; s; s = *sp) {        /* Skip progbits sections. */
273         if (s->flags & TYPE_PROGBITS) {
274             sp = &s->next;
275             continue;
276         }
277         /* Do some special pre-processing on nobits sections' attributes. */
278         if (s->flags & (START_DEFINED | ALIGN_DEFINED | FOLLOWS_DEFINED)) {     /* Check for a mixture of real and virtual section attributes. */
279             if (s->flags & (VSTART_DEFINED | VALIGN_DEFINED |
280                             VFOLLOWS_DEFINED))
281                 error(ERR_FATAL|ERR_NOFILE,
282                       "cannot mix real and virtual attributes"
283                       " in nobits section (%s)", s->name);
284             /* Real and virtual attributes mean the same thing for nobits sections. */
285             if (s->flags & START_DEFINED) {
286                 s->vstart = s->start;
287                 s->flags |= VSTART_DEFINED;
288             }
289             if (s->flags & ALIGN_DEFINED) {
290                 s->valign = s->align;
291                 s->flags |= VALIGN_DEFINED;
292             }
293             if (s->flags & FOLLOWS_DEFINED) {
294                 s->vfollows = s->follows;
295                 s->flags |= VFOLLOWS_DEFINED;
296                 s->flags &= ~FOLLOWS_DEFINED;
297             }
298         }
299         /* Every section must have a start address. */
300         if (s->flags & VSTART_DEFINED) {
301             s->start = s->vstart;
302             s->flags |= START_DEFINED;
303         }
304         /* Move the section into the nobits list. */
305         *sp = s->next;
306         s->next = NULL;
307         *nt = s;
308         nt = &s->next;
309     }
310
311     /* Step 2: Sort the progbits sections into their output order. */
312
313     /* In Step 2 we move around sections in groups.  A group
314      * begins with a section (group leader) that has a user-
315      * defined start address or follows section.  The remainder
316      * of the group is made up of the sections that implicitly
317      * follow the group leader (i.e., they were defined after
318      * the group leader and were not given an explicit start
319      * address or follows section by the user). */
320
321     /* For anyone attempting to read this code:
322      * g (group) points to a group of sections, the first one of which has
323      *   a user-defined start address or follows section.
324      * gp (g previous) holds the location of the pointer to g.
325      * gs (g scan) is a temp variable that we use to scan to the end of the group.
326      * gsp (gs previous) holds the location of the pointer to gs.
327      * nt (nobits tail) points to the nobits section-list tail.
328      */
329
330     /* Link all 'follows' groups to their proper position.  To do
331      * this we need to know three things: the start of the group
332      * to relocate (g), the section it is following (s), and the
333      * end of the group we're relocating (gs). */
334     for (gp = &sections, g = sections; g; g = gs) {     /* Find the next follows group that is out of place (g). */
335         if (!(g->flags & FOLLOWS_DEFINED)) {
336             while (g->next) {
337                 if ((g->next->flags & FOLLOWS_DEFINED) &&
338                     strcmp(g->name, g->next->follows))
339                     break;
340                 g = g->next;
341             }
342             if (!g->next)
343                 break;
344             gp = &g->next;
345             g = g->next;
346         }
347         /* Find the section that this group follows (s). */
348         for (sp = &sections, s = sections;
349              s && strcmp(s->name, g->follows);
350              sp = &s->next, s = s->next) ;
351         if (!s)
352             error(ERR_FATAL|ERR_NOFILE, "section %s follows an invalid or"
353                   " unknown section (%s)", g->name, g->follows);
354         if (s->next && (s->next->flags & FOLLOWS_DEFINED) &&
355             !strcmp(s->name, s->next->follows))
356             error(ERR_FATAL|ERR_NOFILE, "sections %s and %s can't both follow"
357                   " section %s", g->name, s->next->name, s->name);
358         /* Find the end of the current follows group (gs). */
359         for (gsp = &g->next, gs = g->next;
360              gs && (gs != s) && !(gs->flags & START_DEFINED);
361              gsp = &gs->next, gs = gs->next) {
362             if (gs->next && (gs->next->flags & FOLLOWS_DEFINED) &&
363                 strcmp(gs->name, gs->next->follows)) {
364                 gsp = &gs->next;
365                 gs = gs->next;
366                 break;
367             }
368         }
369         /* Re-link the group after its follows section. */
370         *gsp = s->next;
371         s->next = g;
372         *gp = gs;
373     }
374
375     /* Link all 'start' groups to their proper position.  Once
376      * again we need to know g, s, and gs (see above).  The main
377      * difference is we already know g since we sort by moving
378      * groups from the 'unsorted' list into a 'sorted' list (g
379      * will always be the first section in the unsorted list). */
380     for (g = sections, sections = NULL; g; g = gs) {    /* Find the section that we will insert this group before (s). */
381         for (sp = &sections, s = sections; s; sp = &s->next, s = s->next)
382             if ((s->flags & START_DEFINED) && (g->start < s->start))
383                 break;
384         /* Find the end of the group (gs). */
385         for (gs = g->next, gsp = &g->next;
386              gs && !(gs->flags & START_DEFINED);
387              gsp = &gs->next, gs = gs->next) ;
388         /* Re-link the group before the target section. */
389         *sp = g;
390         *gsp = s;
391     }
392
393     /* Step 3: Compute start addresses for all progbits sections. */
394
395     /* Make sure we have an origin and a start address for the first section. */
396     if (origin_defined) {
397         if (sections->flags & START_DEFINED) {
398             /* Make sure this section doesn't begin before the origin. */
399             if (sections->start < origin)
400                 error(ERR_FATAL|ERR_NOFILE, "section %s begins"
401                       " before program origin", sections->name);
402         } else if (sections->flags & ALIGN_DEFINED) {
403             sections->start = ((origin + sections->align - 1) &
404                                ~(sections->align - 1));
405         } else {
406             sections->start = origin;
407         }
408     } else {
409         if (!(sections->flags & START_DEFINED))
410             sections->start = 0;
411         origin = sections->start;
412     }
413     sections->flags |= START_DEFINED;
414
415     /* Make sure each section has an explicit start address.  If it
416      * doesn't, then compute one based its alignment and the end of
417      * the previous section. */
418     for (pend = sections->start, g = s = sections; g; g = g->next) {    /* Find the next section that could cause an overlap situation
419                                                                          * (has a defined start address, and is not zero length). */
420         if (g == s)
421             for (s = g->next;
422                  s && ((s->length == 0) || !(s->flags & START_DEFINED));
423                  s = s->next) ;
424         /* Compute the start address of this section, if necessary. */
425         if (!(g->flags & START_DEFINED)) {      /* Default to an alignment of 4 if unspecified. */
426             if (!(g->flags & ALIGN_DEFINED)) {
427                 g->align = 4;
428                 g->flags |= ALIGN_DEFINED;
429             }
430             /* Set the section start address. */
431             g->start = (pend + g->align - 1) & ~(g->align - 1);
432             g->flags |= START_DEFINED;
433         }
434         /* Ugly special case for progbits sections' virtual attributes:
435          *   If there is a defined valign, but no vstart and no vfollows, then
436          *   we valign after the previous progbits section.  This case doesn't
437          *   really make much sense for progbits sections with a defined start
438          *   address, but it is possible and we must do *something*.
439          * Not-so-ugly special case:
440          *   If a progbits section has no virtual attributes, we set the
441          *   vstart equal to the start address.  */
442         if (!(g->flags & (VSTART_DEFINED | VFOLLOWS_DEFINED))) {
443             if (g->flags & VALIGN_DEFINED)
444                 g->vstart = (pend + g->valign - 1) & ~(g->valign - 1);
445             else
446                 g->vstart = g->start;
447             g->flags |= VSTART_DEFINED;
448         }
449         /* Ignore zero-length sections. */
450         if (g->start < pend)
451             continue;
452         /* Compute the span of this section. */
453         pend = g->start + g->length;
454         /* Check for section overlap. */
455         if (s) {
456             if (s->start < origin)
457                 error(ERR_FATAL|ERR_NOFILE, "section %s beings before program origin",
458                       s->name);
459             if (g->start > s->start)
460                 error(ERR_FATAL|ERR_NOFILE, "sections %s ~ %s and %s overlap!",
461                       gs->name, g->name, s->name);
462             if (pend > s->start)
463                 error(ERR_FATAL|ERR_NOFILE, "sections %s and %s overlap!",
464                       g->name, s->name);
465         }
466         /* Remember this section as the latest >0 length section. */
467         gs = g;
468     }
469
470     /* Step 4: Compute vstart addresses for all sections. */
471
472     /* Attach the nobits sections to the end of the progbits sections. */
473     for (s = sections; s->next; s = s->next) ;
474     s->next = nobits;
475     last_progbits = s;
476     /*
477      * Scan for sections that don't have a vstart address.  If we find
478      * one we'll attempt to compute its vstart.  If we can't compute
479      * the vstart, we leave it alone and come back to it in a
480      * subsequent scan.  We continue scanning and re-scanning until
481      * we've gone one full cycle without computing any vstarts.
482      */
483     do {                        /* Do one full scan of the sections list. */
484         for (h = 0, g = sections; g; g = g->next) {
485             if (g->flags & VSTART_DEFINED)
486                 continue;
487             /* Find the section that this one virtually follows.  */
488             if (g->flags & VFOLLOWS_DEFINED) {
489                 for (s = sections; s && strcmp(g->vfollows, s->name);
490                      s = s->next) ;
491                 if (!s)
492                     error(ERR_FATAL|ERR_NOFILE,
493                           "section %s vfollows unknown section (%s)",
494                           g->name, g->vfollows);
495             } else if (g->ifollows != NULL)
496                 for (s = sections; s && (s != g->ifollows); s = s->next) ;
497             /* The .bss section is the only one with ifollows = NULL.
498                In this case we implicitly follow the last progbits
499                section.  */
500             else
501                 s = last_progbits;
502
503             /* If the section we're following has a vstart, we can proceed. */
504             if (s->flags & VSTART_DEFINED) {    /* Default to virtual alignment of four. */
505                 if (!(g->flags & VALIGN_DEFINED)) {
506                     g->valign = 4;
507                     g->flags |= VALIGN_DEFINED;
508                 }
509                 /* Compute the vstart address. */
510                 g->vstart = (s->vstart + s->length + g->valign - 1)
511                     & ~(g->valign - 1);
512                g->flags |= VSTART_DEFINED;
513                 h++;
514                 /* Start and vstart mean the same thing for nobits sections. */
515                 if (g->flags & TYPE_NOBITS)
516                     g->start = g->vstart;
517             }
518         }
519     } while (h);
520
521     /* Now check for any circular vfollows references, which will manifest
522      * themselves as sections without a defined vstart. */
523     for (h = 0, s = sections; s; s = s->next) {
524         if (!(s->flags & VSTART_DEFINED)) {     /* Non-fatal errors after assembly has completed are generally a
525                                                  * no-no, but we'll throw a fatal one eventually so it's ok.  */
526             error(ERR_NONFATAL, "cannot compute vstart for section %s",
527                   s->name);
528             h++;
529         }
530     }
531     if (h)
532         error(ERR_FATAL|ERR_NOFILE, "circular vfollows path detected");
533
534 #ifdef DEBUG
535     fprintf(stdout,
536             "bin_cleanup: Confirm final section order for output file:\n");
537     for (h = 0, s = sections; s && (s->flags & TYPE_PROGBITS);
538          h++, s = s->next)
539         fprintf(stdout, "%i. %s\n", h, s->name);
540 #endif
541
542     /* Step 5: Apply relocations. */
543
544     /* Prepare the sections for relocating. */
545     for (s = sections; s; s = s->next)
546         saa_rewind(s->contents);
547     /* Apply relocations. */
548     for (r = relocs; r; r = r->next) {
549         uint8_t *p, *q, mydata[8];
550         int64_t l;
551
552         saa_fread(r->target->contents, r->posn, mydata, r->bytes);
553         p = q = mydata;
554         l = *p++;
555
556         if (r->bytes > 1) {
557             l += ((int64_t)*p++) << 8;
558             if (r->bytes >= 4) {
559                 l += ((int64_t)*p++) << 16;
560                 l += ((int64_t)*p++) << 24;
561             }
562             if (r->bytes == 8) {
563                 l += ((int64_t)*p++) << 32;
564                 l += ((int64_t)*p++) << 40;
565                 l += ((int64_t)*p++) << 48;
566                 l += ((int64_t)*p++) << 56;
567             }
568         }
569
570         s = find_section_by_index(r->secref);
571         if (s) {
572             if (r->secref == s->start_index)
573                 l += s->start;
574             else
575                 l += s->vstart;
576         }
577         s = find_section_by_index(r->secrel);
578         if (s) {
579             if (r->secrel == s->start_index)
580                 l -= s->start;
581             else
582                 l -= s->vstart;
583         }
584
585         if (r->bytes >= 4)
586             WRITEDLONG(q, l);
587         else if (r->bytes == 2)
588             WRITESHORT(q, l);
589         else
590             *q++ = (uint8_t)(l & 0xFF);
591         saa_fwrite(r->target->contents, r->posn, mydata, r->bytes);
592     }
593
594     /* Step 6: Write the section data to the output file. */
595     do_output();
596
597     /* Step 7: Generate the map file. */
598
599     if (map_control) {
600         static const char not_defined[] = "not defined";
601
602         /* Display input and output file names. */
603         fprintf(rf, "\n- NASM Map file ");
604         for (h = 63; h; h--)
605             fputc('-', rf);
606         fprintf(rf, "\n\nSource file:  %s\nOutput file:  %s\n\n",
607                 infile, outfile);
608
609         if (map_control & MAP_ORIGIN) { /* Display program origin. */
610             fprintf(rf, "-- Program origin ");
611             for (h = 61; h; h--)
612                 fputc('-', rf);
613             fprintf(rf, "\n\n%08"PRIX64"\n\n", origin);
614         }
615         /* Display sections summary. */
616         if (map_control & MAP_SUMMARY) {
617             fprintf(rf, "-- Sections (summary) ");
618             for (h = 57; h; h--)
619                 fputc('-', rf);
620             fprintf(rf, "\n\nVstart            Start             Stop              "
621                     "Length    Class     Name\n");
622             for (s = sections; s; s = s->next) {
623                 fprintf(rf, "%16"PRIX64"  %16"PRIX64"  %16"PRIX64"  %08"PRIX64"  ",
624                         s->vstart, s->start, s->start + s->length,
625                         s->length);
626                 if (s->flags & TYPE_PROGBITS)
627                     fprintf(rf, "progbits  ");
628                 else
629                     fprintf(rf, "nobits    ");
630                 fprintf(rf, "%s\n", s->name);
631             }
632             fprintf(rf, "\n");
633         }
634         /* Display detailed section information. */
635         if (map_control & MAP_SECTIONS) {
636             fprintf(rf, "-- Sections (detailed) ");
637             for (h = 56; h; h--)
638                 fputc('-', rf);
639             fprintf(rf, "\n\n");
640             for (s = sections; s; s = s->next) {
641                 fprintf(rf, "---- Section %s ", s->name);
642                 for (h = 65 - strlen(s->name); h; h--)
643                     fputc('-', rf);
644                 fprintf(rf, "\n\nclass:     ");
645                 if (s->flags & TYPE_PROGBITS)
646                     fprintf(rf, "progbits");
647                 else
648                     fprintf(rf, "nobits");
649                 fprintf(rf, "\nlength:    %16"PRIX64"\nstart:     %16"PRIX64""
650                         "\nalign:     ", s->length, s->start);
651                 if (s->flags & ALIGN_DEFINED)
652                     fprintf(rf, "%16"PRIX64"", s->align);
653                 else
654                     fputs(not_defined, rf);
655                 fprintf(rf, "\nfollows:   ");
656                 if (s->flags & FOLLOWS_DEFINED)
657                     fprintf(rf, "%s", s->follows);
658                 else
659                     fputs(not_defined, rf);
660                 fprintf(rf, "\nvstart:    %16"PRIX64"\nvalign:    ", s->vstart);
661                 if (s->flags & VALIGN_DEFINED)
662                     fprintf(rf, "%16"PRIX64"", s->valign);
663                 else
664                     fputs(not_defined, rf);
665                 fprintf(rf, "\nvfollows:  ");
666                 if (s->flags & VFOLLOWS_DEFINED)
667                     fprintf(rf, "%s", s->vfollows);
668                 else
669                     fputs(not_defined, rf);
670                 fprintf(rf, "\n\n");
671             }
672         }
673         /* Display symbols information. */
674         if (map_control & MAP_SYMBOLS) {
675             int32_t segment;
676             int64_t offset;
677
678             fprintf(rf, "-- Symbols ");
679             for (h = 68; h; h--)
680                 fputc('-', rf);
681             fprintf(rf, "\n\n");
682             if (no_seg_labels) {
683                 fprintf(rf, "---- No Section ");
684                 for (h = 63; h; h--)
685                     fputc('-', rf);
686                 fprintf(rf, "\n\nValue     Name\n");
687                 for (l = no_seg_labels; l; l = l->next) {
688                     lookup_label(l->name, &segment, &offset);
689                     fprintf(rf, "%08"PRIX64"  %s\n", offset, l->name);
690                 }
691                 fprintf(rf, "\n\n");
692             }
693             for (s = sections; s; s = s->next) {
694                 if (s->labels) {
695                     fprintf(rf, "---- Section %s ", s->name);
696                     for (h = 65 - strlen(s->name); h; h--)
697                         fputc('-', rf);
698                     fprintf(rf, "\n\nReal              Virtual           Name\n");
699                     for (l = s->labels; l; l = l->next) {
700                         lookup_label(l->name, &segment, &offset);
701                         fprintf(rf, "%16"PRIX64"  %16"PRIX64"  %s\n",
702                                 s->start + offset, s->vstart + offset,
703                                 l->name);
704                     }
705                     fprintf(rf, "\n");
706                 }
707             }
708         }
709     }
710
711     /* Close the report file. */
712     if (map_control && (rf != stdout) && (rf != stderr))
713         fclose(rf);
714
715     /* Step 8: Release all allocated memory. */
716
717     /* Free sections, label pointer structs, etc.. */
718     while (sections) {
719         s = sections;
720         sections = s->next;
721         saa_free(s->contents);
722         nasm_free(s->name);
723         if (s->flags & FOLLOWS_DEFINED)
724             nasm_free(s->follows);
725         if (s->flags & VFOLLOWS_DEFINED)
726             nasm_free(s->vfollows);
727         while (s->labels) {
728             l = s->labels;
729             s->labels = l->next;
730             nasm_free(l);
731         }
732         nasm_free(s);
733     }
734
735     /* Free no-section labels. */
736     while (no_seg_labels) {
737         l = no_seg_labels;
738         no_seg_labels = l->next;
739         nasm_free(l);
740     }
741
742     /* Free relocation structures. */
743     while (relocs) {
744         r = relocs->next;
745         nasm_free(relocs);
746         relocs = r;
747     }
748 }
749
750 static void bin_out(int32_t segto, const void *data,
751                     enum out_type type, uint64_t size,
752                     int32_t segment, int32_t wrt)
753 {
754     uint8_t *p, mydata[8];
755     struct Section *s;
756
757     if (wrt != NO_SEG) {
758         wrt = NO_SEG;           /* continue to do _something_ */
759         error(ERR_NONFATAL, "WRT not supported by binary output format");
760     }
761
762     /* Handle absolute-assembly (structure definitions). */
763     if (segto == NO_SEG) {
764         if (type != OUT_RESERVE)
765             error(ERR_NONFATAL, "attempt to assemble code in"
766                   " [ABSOLUTE] space");
767         return;
768     }
769
770     /* Find the segment we are targeting. */
771     s = find_section_by_index(segto);
772     if (!s)
773         error(ERR_PANIC, "code directed to nonexistent segment?");
774
775     /* "Smart" section-type adaptation code. */
776     if (!(s->flags & TYPE_DEFINED)) {
777         if (type == OUT_RESERVE)
778             s->flags |= TYPE_DEFINED | TYPE_NOBITS;
779         else
780             s->flags |= TYPE_DEFINED | TYPE_PROGBITS;
781     }
782
783     if ((s->flags & TYPE_NOBITS) && (type != OUT_RESERVE))
784         error(ERR_WARNING, "attempt to initialize memory in a"
785               " nobits section: ignored");
786
787     if (type == OUT_ADDRESS) {
788         if (segment != NO_SEG && !find_section_by_index(segment)) {
789             if (segment % 2)
790                 error(ERR_NONFATAL, "binary output format does not support"
791                       " segment base references");
792             else
793                 error(ERR_NONFATAL, "binary output format does not support"
794                       " external references");
795             segment = NO_SEG;
796         }
797         if (s->flags & TYPE_PROGBITS) {
798             if (segment != NO_SEG)
799                 add_reloc(s, size, segment, -1L);
800             p = mydata;
801             WRITEADDR(p, *(int64_t *)data, size);
802             saa_wbytes(s->contents, mydata, size);
803         }
804         s->length += size;
805     } else if (type == OUT_RAWDATA) {
806         if (s->flags & TYPE_PROGBITS)
807             saa_wbytes(s->contents, data, size);
808         s->length += size;
809     } else if (type == OUT_RESERVE) {
810         if (s->flags & TYPE_PROGBITS) {
811             error(ERR_WARNING, "uninitialized space declared in"
812                   " %s section: zeroing", s->name);
813             saa_wbytes(s->contents, NULL, size);
814         }
815         s->length += size;
816     } else if (type == OUT_REL2ADR || type == OUT_REL4ADR ||
817                type == OUT_REL8ADR) {
818         int64_t addr = *(int64_t *)data - size;
819         size = realsize(type, size);
820         if (segment != NO_SEG && !find_section_by_index(segment)) {
821             if (segment % 2)
822                 error(ERR_NONFATAL, "binary output format does not support"
823                       " segment base references");
824             else
825                 error(ERR_NONFATAL, "binary output format does not support"
826                       " external references");
827             segment = NO_SEG;
828         }
829         if (s->flags & TYPE_PROGBITS) {
830             add_reloc(s, size, segment, segto);
831             p = mydata;
832             WRITEADDR(p, addr - s->length, size);
833             saa_wbytes(s->contents, mydata, size);
834         }
835         s->length += size;
836     }
837 }
838
839 static void bin_deflabel(char *name, int32_t segment, int64_t offset,
840                          int is_global, char *special)
841 {
842     (void)segment;              /* Don't warn that this parameter is unused */
843     (void)offset;               /* Don't warn that this parameter is unused */
844
845     if (special)
846         error(ERR_NONFATAL, "binary format does not support any"
847               " special symbol types");
848     else if (name[0] == '.' && name[1] == '.' && name[2] != '@')
849         error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
850     else if (is_global == 2)
851         error(ERR_NONFATAL, "binary output format does not support common"
852               " variables");
853     else {
854         struct Section *s;
855         struct bin_label ***ltp;
856
857         /* Remember label definition so we can look it up later when
858          * creating the map file. */
859         s = find_section_by_index(segment);
860         if (s)
861             ltp = &(s->labels_end);
862         else
863             ltp = &nsl_tail;
864         (**ltp) = nasm_malloc(sizeof(struct bin_label));
865         (**ltp)->name = name;
866         (**ltp)->next = NULL;
867         *ltp = &((**ltp)->next);
868     }
869
870 }
871
872 /* These constants and the following function are used
873  * by bin_secname() to parse attribute assignments. */
874
875 enum { ATTRIB_START, ATTRIB_ALIGN, ATTRIB_FOLLOWS,
876     ATTRIB_VSTART, ATTRIB_VALIGN, ATTRIB_VFOLLOWS,
877     ATTRIB_NOBITS, ATTRIB_PROGBITS
878 };
879
880 static int bin_read_attribute(char **line, int *attribute,
881                               uint64_t *value)
882 {
883     expr *e;
884     int attrib_name_size;
885     struct tokenval tokval;
886     char *exp;
887
888     /* Skip whitespace. */
889     while (**line && nasm_isspace(**line))
890         (*line)++;
891     if (!**line)
892         return 0;
893
894     /* Figure out what attribute we're reading. */
895     if (!nasm_strnicmp(*line, "align=", 6)) {
896         *attribute = ATTRIB_ALIGN;
897         attrib_name_size = 6;
898     } else if (format_mode) {
899         if (!nasm_strnicmp(*line, "start=", 6)) {
900             *attribute = ATTRIB_START;
901             attrib_name_size = 6;
902         } else if (!nasm_strnicmp(*line, "follows=", 8)) {
903             *attribute = ATTRIB_FOLLOWS;
904             *line += 8;
905             return 1;
906         } else if (!nasm_strnicmp(*line, "vstart=", 7)) {
907             *attribute = ATTRIB_VSTART;
908             attrib_name_size = 7;
909         } else if (!nasm_strnicmp(*line, "valign=", 7)) {
910             *attribute = ATTRIB_VALIGN;
911             attrib_name_size = 7;
912         } else if (!nasm_strnicmp(*line, "vfollows=", 9)) {
913             *attribute = ATTRIB_VFOLLOWS;
914             *line += 9;
915             return 1;
916         } else if (!nasm_strnicmp(*line, "nobits", 6) &&
917                    (nasm_isspace((*line)[6]) || ((*line)[6] == '\0'))) {
918             *attribute = ATTRIB_NOBITS;
919             *line += 6;
920             return 1;
921         } else if (!nasm_strnicmp(*line, "progbits", 8) &&
922                    (nasm_isspace((*line)[8]) || ((*line)[8] == '\0'))) {
923             *attribute = ATTRIB_PROGBITS;
924             *line += 8;
925             return 1;
926         } else
927             return 0;
928     } else
929         return 0;
930
931     /* Find the end of the expression. */
932     if ((*line)[attrib_name_size] != '(') {
933         /* Single term (no parenthesis). */
934         exp = *line += attrib_name_size;
935         while (**line && !nasm_isspace(**line))
936             (*line)++;
937         if (**line) {
938             **line = '\0';
939             (*line)++;
940         }
941     } else {
942         char c;
943         int pcount = 1;
944
945         /* Full expression (delimited by parenthesis) */
946         exp = *line += attrib_name_size + 1;
947         while (1) {
948             (*line) += strcspn(*line, "()'\"");
949             if (**line == '(') {
950                 ++(*line);
951                 ++pcount;
952             }
953             if (**line == ')') {
954                 ++(*line);
955                 --pcount;
956                 if (!pcount)
957                     break;
958             }
959             if ((**line == '"') || (**line == '\'')) {
960                 c = **line;
961                 while (**line) {
962                     ++(*line);
963                     if (**line == c)
964                         break;
965                 }
966                 if (!**line) {
967                     error(ERR_NONFATAL,
968                           "invalid syntax in `section' directive");
969                     return -1;
970                 }
971                 ++(*line);
972             }
973             if (!**line) {
974                 error(ERR_NONFATAL, "expecting `)'");
975                 return -1;
976             }
977         }
978         *(*line - 1) = '\0';    /* Terminate the expression. */
979     }
980
981     /* Check for no value given. */
982     if (!*exp) {
983         error(ERR_WARNING, "No value given to attribute in"
984               " `section' directive");
985         return -1;
986     }
987
988     /* Read and evaluate the expression. */
989     stdscan_reset();
990     stdscan_bufptr = exp;
991     tokval.t_type = TOKEN_INVALID;
992     e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
993     if (e) {
994         if (!is_really_simple(e)) {
995             error(ERR_NONFATAL, "section attribute value must be"
996                   " a critical expression");
997             return -1;
998         }
999     } else {
1000         error(ERR_NONFATAL, "Invalid attribute value"
1001               " specified in `section' directive.");
1002         return -1;
1003     }
1004     *value = (uint64_t)reloc_value(e);
1005     return 1;
1006 }
1007
1008 static void bin_assign_attributes(struct Section *sec, char *astring)
1009 {
1010     int attribute, check;
1011     uint64_t value;
1012     char *p;
1013
1014     while (1) {                 /* Get the next attribute. */
1015         check = bin_read_attribute(&astring, &attribute, &value);
1016         /* Skip bad attribute. */
1017         if (check == -1)
1018             continue;
1019         /* Unknown section attribute, so skip it and warn the user. */
1020         if (!check) {
1021             if (!*astring)
1022                 break;          /* End of line. */
1023             else {
1024                 p = astring;
1025                 while (*astring && !nasm_isspace(*astring))
1026                     astring++;
1027                 if (*astring) {
1028                     *astring = '\0';
1029                     astring++;
1030                 }
1031                 error(ERR_WARNING, "ignoring unknown section attribute:"
1032                       " \"%s\"", p);
1033             }
1034             continue;
1035         }
1036
1037         switch (attribute) {    /* Handle nobits attribute. */
1038         case ATTRIB_NOBITS:
1039             if ((sec->flags & TYPE_DEFINED)
1040                 && (sec->flags & TYPE_PROGBITS))
1041                 error(ERR_NONFATAL,
1042                       "attempt to change section type"
1043                       " from progbits to nobits");
1044             else
1045                 sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1046             continue;
1047
1048             /* Handle progbits attribute. */
1049         case ATTRIB_PROGBITS:
1050             if ((sec->flags & TYPE_DEFINED) && (sec->flags & TYPE_NOBITS))
1051                 error(ERR_NONFATAL, "attempt to change section type"
1052                       " from nobits to progbits");
1053             else
1054                 sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1055             continue;
1056
1057             /* Handle align attribute. */
1058         case ATTRIB_ALIGN:
1059             if (!format_mode && (!strcmp(sec->name, ".text")))
1060                 error(ERR_NONFATAL, "cannot specify an alignment"
1061                       " to the .text section");
1062             else {
1063                 if (!value || ((value - 1) & value))
1064                     error(ERR_NONFATAL, "argument to `align' is not a"
1065                           " power of two");
1066                 else {          /* Alignment is already satisfied if the previous
1067                                  * align value is greater. */
1068                     if ((sec->flags & ALIGN_DEFINED)
1069                         && (value < sec->align))
1070                         value = sec->align;
1071
1072                     /* Don't allow a conflicting align value. */
1073                     if ((sec->flags & START_DEFINED)
1074                         && (sec->start & (value - 1)))
1075                         error(ERR_NONFATAL,
1076                               "`align' value conflicts "
1077                               "with section start address");
1078                     else {
1079                         sec->align = value;
1080                         sec->flags |= ALIGN_DEFINED;
1081                     }
1082                 }
1083             }
1084             continue;
1085
1086             /* Handle valign attribute. */
1087         case ATTRIB_VALIGN:
1088             if (!value || ((value - 1) & value))
1089                 error(ERR_NONFATAL, "argument to `valign' is not a"
1090                       " power of two");
1091             else {              /* Alignment is already satisfied if the previous
1092                                  * align value is greater. */
1093                 if ((sec->flags & VALIGN_DEFINED) && (value < sec->valign))
1094                     value = sec->valign;
1095
1096                 /* Don't allow a conflicting valign value. */
1097                 if ((sec->flags & VSTART_DEFINED)
1098                     && (sec->vstart & (value - 1)))
1099                     error(ERR_NONFATAL,
1100                           "`valign' value conflicts "
1101                           "with `vstart' address");
1102                 else {
1103                     sec->valign = value;
1104                     sec->flags |= VALIGN_DEFINED;
1105                 }
1106             }
1107             continue;
1108
1109             /* Handle start attribute. */
1110         case ATTRIB_START:
1111             if (sec->flags & FOLLOWS_DEFINED)
1112                 error(ERR_NONFATAL, "cannot combine `start' and `follows'"
1113                       " section attributes");
1114             else if ((sec->flags & START_DEFINED) && (value != sec->start))
1115                 error(ERR_NONFATAL, "section start address redefined");
1116             else {
1117                 sec->start = value;
1118                 sec->flags |= START_DEFINED;
1119                 if (sec->flags & ALIGN_DEFINED) {
1120                     if (sec->start & (sec->align - 1))
1121                         error(ERR_NONFATAL, "`start' address conflicts"
1122                               " with section alignment");
1123                     sec->flags ^= ALIGN_DEFINED;
1124                 }
1125             }
1126             continue;
1127
1128             /* Handle vstart attribute. */
1129         case ATTRIB_VSTART:
1130             if (sec->flags & VFOLLOWS_DEFINED)
1131                 error(ERR_NONFATAL,
1132                       "cannot combine `vstart' and `vfollows'"
1133                       " section attributes");
1134             else if ((sec->flags & VSTART_DEFINED)
1135                      && (value != sec->vstart))
1136                 error(ERR_NONFATAL,
1137                       "section virtual start address"
1138                       " (vstart) redefined");
1139             else {
1140                 sec->vstart = value;
1141                 sec->flags |= VSTART_DEFINED;
1142                 if (sec->flags & VALIGN_DEFINED) {
1143                     if (sec->vstart & (sec->valign - 1))
1144                         error(ERR_NONFATAL, "`vstart' address conflicts"
1145                               " with `valign' value");
1146                     sec->flags ^= VALIGN_DEFINED;
1147                 }
1148             }
1149             continue;
1150
1151             /* Handle follows attribute. */
1152         case ATTRIB_FOLLOWS:
1153             p = astring;
1154             astring += strcspn(astring, " \t");
1155             if (astring == p)
1156                 error(ERR_NONFATAL, "expecting section name for `follows'"
1157                       " attribute");
1158             else {
1159                 *(astring++) = '\0';
1160                 if (sec->flags & START_DEFINED)
1161                     error(ERR_NONFATAL,
1162                           "cannot combine `start' and `follows'"
1163                           " section attributes");
1164                 sec->follows = nasm_strdup(p);
1165                 sec->flags |= FOLLOWS_DEFINED;
1166             }
1167             continue;
1168
1169             /* Handle vfollows attribute. */
1170         case ATTRIB_VFOLLOWS:
1171             if (sec->flags & VSTART_DEFINED)
1172                 error(ERR_NONFATAL,
1173                       "cannot combine `vstart' and `vfollows'"
1174                       " section attributes");
1175             else {
1176                 p = astring;
1177                 astring += strcspn(astring, " \t");
1178                 if (astring == p)
1179                     error(ERR_NONFATAL,
1180                           "expecting section name for `vfollows'"
1181                           " attribute");
1182                 else {
1183                     *(astring++) = '\0';
1184                     sec->vfollows = nasm_strdup(p);
1185                     sec->flags |= VFOLLOWS_DEFINED;
1186                 }
1187             }
1188             continue;
1189         }
1190     }
1191 }
1192
1193 static void bin_define_section_labels(void)
1194 {
1195     static int labels_defined = 0;
1196     struct Section *sec;
1197     char *label_name;
1198     size_t base_len;
1199
1200     if (labels_defined)
1201         return;
1202     for (sec = sections; sec; sec = sec->next) {
1203         base_len = strlen(sec->name) + 8;
1204         label_name = nasm_malloc(base_len + 8);
1205         strcpy(label_name, "section.");
1206         strcpy(label_name + 8, sec->name);
1207
1208         /* section.<name>.start */
1209         strcpy(label_name + base_len, ".start");
1210         define_label(label_name, sec->start_index, 0L,
1211                      NULL, 0, 0, my_ofmt, error);
1212
1213         /* section.<name>.vstart */
1214         strcpy(label_name + base_len, ".vstart");
1215         define_label(label_name, sec->vstart_index, 0L,
1216                      NULL, 0, 0, my_ofmt, error);
1217
1218         nasm_free(label_name);
1219     }
1220     labels_defined = 1;
1221 }
1222
1223 static int32_t bin_secname(char *name, int pass, int *bits)
1224 {
1225     char *p;
1226     struct Section *sec;
1227
1228     /* bin_secname is called with *name = NULL at the start of each
1229      * pass.  Use this opportunity to establish the default section
1230      * (default is BITS-16 ".text" segment).
1231      */
1232     if (!name) {                /* Reset ORG and section attributes at the start of each pass. */
1233         origin_defined = 0;
1234         for (sec = sections; sec; sec = sec->next)
1235             sec->flags &= ~(START_DEFINED | VSTART_DEFINED |
1236                             ALIGN_DEFINED | VALIGN_DEFINED);
1237
1238         /* Define section start and vstart labels. */
1239         if (format_mode && (pass != 1))
1240             bin_define_section_labels();
1241
1242         /* Establish the default (.text) section. */
1243         *bits = 16;
1244         sec = find_section_by_name(".text");
1245         sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1246         current_section = sec->vstart_index;
1247         return current_section;
1248     }
1249
1250     /* Attempt to find the requested section.  If it does not
1251      * exist, create it. */
1252     p = name;
1253     while (*p && !nasm_isspace(*p))
1254         p++;
1255     if (*p)
1256         *p++ = '\0';
1257     sec = find_section_by_name(name);
1258     if (!sec) {
1259         sec = create_section(name);
1260         if (!strcmp(name, ".data"))
1261             sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1262         else if (!strcmp(name, ".bss")) {
1263             sec->flags |= TYPE_DEFINED | TYPE_NOBITS;
1264             sec->ifollows = NULL;
1265         } else if (!format_mode) {
1266             error(ERR_NONFATAL, "section name must be "
1267                   ".text, .data, or .bss");
1268             return current_section;
1269         }
1270     }
1271
1272     /* Handle attribute assignments. */
1273     if (pass != 1)
1274         bin_assign_attributes(sec, p);
1275
1276 #ifndef ABIN_SMART_ADAPT
1277     /* The following line disables smart adaptation of
1278      * PROGBITS/NOBITS section types (it forces sections to
1279      * default to PROGBITS). */
1280     if ((pass != 1) && !(sec->flags & TYPE_DEFINED))
1281         sec->flags |= TYPE_DEFINED | TYPE_PROGBITS;
1282 #endif
1283
1284     /* Set the current section and return. */
1285     current_section = sec->vstart_index;
1286     return current_section;
1287 }
1288
1289 static int bin_directive(enum directives directive, char *args, int pass)
1290 {
1291     switch (directive) {
1292     case D_ORG:
1293     {
1294         struct tokenval tokval;
1295         uint64_t value;
1296         expr *e;
1297
1298         stdscan_reset();
1299         stdscan_bufptr = args;
1300         tokval.t_type = TOKEN_INVALID;
1301         e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
1302         if (e) {
1303             if (!is_really_simple(e))
1304                 error(ERR_NONFATAL, "org value must be a critical"
1305                       " expression");
1306             else {
1307                 value = reloc_value(e);
1308                 /* Check for ORG redefinition. */
1309                 if (origin_defined && (value != origin))
1310                     error(ERR_NONFATAL, "program origin redefined");
1311                 else {
1312                     origin = value;
1313                     origin_defined = 1;
1314                 }
1315             }
1316         } else
1317             error(ERR_NONFATAL, "No or invalid offset specified"
1318                   " in ORG directive.");
1319         return 1;
1320     }
1321     case D_MAP:
1322     {
1323     /* The 'map' directive allows the user to generate section
1324      * and symbol information to stdout, stderr, or to a file. */
1325         char *p;
1326         
1327         if (pass != 1)
1328             return 1;
1329         args += strspn(args, " \t");
1330         while (*args) {
1331             p = args;
1332             args += strcspn(args, " \t");
1333             if (*args != '\0')
1334                 *(args++) = '\0';
1335             if (!nasm_stricmp(p, "all"))
1336                 map_control |=
1337                     MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS | MAP_SYMBOLS;
1338             else if (!nasm_stricmp(p, "brief"))
1339                 map_control |= MAP_ORIGIN | MAP_SUMMARY;
1340             else if (!nasm_stricmp(p, "sections"))
1341                 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1342             else if (!nasm_stricmp(p, "segments"))
1343                 map_control |= MAP_ORIGIN | MAP_SUMMARY | MAP_SECTIONS;
1344             else if (!nasm_stricmp(p, "symbols"))
1345                 map_control |= MAP_SYMBOLS;
1346             else if (!rf) {
1347                 if (!nasm_stricmp(p, "stdout"))
1348                     rf = stdout;
1349                 else if (!nasm_stricmp(p, "stderr"))
1350                     rf = stderr;
1351                 else {          /* Must be a filename. */
1352                     rf = fopen(p, "wt");
1353                     if (!rf) {
1354                         error(ERR_WARNING, "unable to open map file `%s'",
1355                               p);
1356                         map_control = 0;
1357                         return 1;
1358                     }
1359                 }
1360             } else
1361                 error(ERR_WARNING, "map file already specified");
1362         }
1363         if (map_control == 0)
1364             map_control |= MAP_ORIGIN | MAP_SUMMARY;
1365         if (!rf)
1366             rf = stdout;
1367         return 1;
1368     }
1369     default:
1370         return 0;
1371     }
1372 }
1373
1374 static void bin_filename(char *inname, char *outname, efunc error)
1375 {
1376     standard_extension(inname, outname, "", error);
1377     infile = inname;
1378     outfile = outname;
1379 }
1380
1381 static void ith_filename(char *inname, char *outname, efunc error)
1382 {
1383     standard_extension(inname, outname, ".ith", error);
1384     infile = inname;
1385     outfile = outname;
1386 }
1387
1388 static void srec_filename(char *inname, char *outname, efunc error)
1389 {
1390     standard_extension(inname, outname, ".srec", error);
1391     infile = inname;
1392     outfile = outname;
1393 }
1394
1395 static int32_t bin_segbase(int32_t segment)
1396 {
1397     return segment;
1398 }
1399
1400 static int bin_set_info(enum geninfo type, char **val)
1401 {
1402     (void)type;
1403     (void)val;
1404     return 0;
1405 }
1406
1407 static void binfmt_init(FILE *afp, efunc errfunc, ldfunc ldef, evalfunc eval);
1408 struct ofmt of_bin, of_ith, of_srec;
1409 static void do_output_bin(void);
1410 static void do_output_ith(void);
1411 static void do_output_srec(void);
1412
1413 static void bin_init(FILE *afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1414 {
1415     my_ofmt   = &of_bin;
1416     do_output = do_output_bin;
1417     binfmt_init(afp, errfunc, ldef, eval);
1418 }
1419
1420 static void ith_init(FILE *afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1421 {
1422     my_ofmt   = &of_ith;
1423     do_output = do_output_ith;
1424     binfmt_init(afp, errfunc, ldef, eval);
1425 }    
1426     
1427 static void srec_init(FILE *afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1428 {
1429     my_ofmt   = &of_srec;
1430     do_output = do_output_srec;
1431     binfmt_init(afp, errfunc, ldef, eval);
1432 }
1433
1434 static void binfmt_init(FILE *afp, efunc errfunc, ldfunc ldef, evalfunc eval)
1435 {
1436     fp = afp;
1437     error = errfunc;
1438
1439     (void)eval;                 /* Don't warn that this parameter is unused. */
1440     (void)ldef;                 /* Placate optimizers. */
1441
1442     maxbits = 64;               /* Support 64-bit Segments */
1443     relocs = NULL;
1444     reloctail = &relocs;
1445     origin_defined = 0;
1446     no_seg_labels = NULL;
1447     nsl_tail = &no_seg_labels;
1448     format_mode = 1;            /* Extended bin format
1449                                  * (set this to zero for old bin format). */
1450
1451     /* Create default section (.text). */
1452     sections = last_section = nasm_malloc(sizeof(struct Section));
1453     last_section->next = NULL;
1454     last_section->name = nasm_strdup(".text");
1455     last_section->contents = saa_init(1L);
1456     last_section->follows = last_section->vfollows = 0;
1457     last_section->ifollows = NULL;
1458     last_section->length = 0;
1459     last_section->flags = TYPE_DEFINED | TYPE_PROGBITS;
1460     last_section->labels = NULL;
1461     last_section->labels_end = &(last_section->labels);
1462     last_section->start_index = seg_alloc();
1463     last_section->vstart_index = current_section = seg_alloc();
1464 }
1465
1466 /* Generate binary file output */
1467 static void do_output_bin(void)
1468 {
1469     struct Section *s;
1470     uint64_t addr = origin;
1471
1472     /* Write the progbits sections to the output file. */
1473     for (s = sections; s; s = s->next) {
1474         /* Skip non-progbits sections */
1475         if (!(s->flags & TYPE_PROGBITS))
1476             continue;
1477         /* Skip zero-length sections */
1478         if (s->length == 0)
1479             continue;
1480
1481         /* Pad the space between sections. */
1482         nasm_assert(addr <= s->start);
1483         fwritezero(s->start - addr, fp);
1484
1485         /* Write the section to the output file. */
1486         saa_fpwrite(s->contents, fp);
1487         
1488         /* Keep track of the current file position */
1489         addr = s->start + s->length;
1490     }
1491 }
1492
1493 /* Generate Intel hex file output */
1494 static int write_ith_record(unsigned int len, uint16_t addr,
1495                             uint8_t type, void *data)
1496 {
1497     char buf[1+2+4+2+255*2+2+2];
1498     char *p = buf;
1499     uint8_t csum, *dptr = data;
1500     unsigned int i;
1501
1502     nasm_assert(len <= 255);
1503
1504     csum = len + addr + (addr >> 8) + type;
1505     for (i = 0; i < len; i++)
1506         csum += dptr[i];
1507     csum = -csum;
1508
1509     p += sprintf(p, ":%02X%04X%02X", len, addr, type);
1510     for (i = 0; i < len; i++)
1511         p += sprintf(p, "%02X", dptr[i]);
1512     p += sprintf(p, "%02X\n", csum);
1513
1514     if (fwrite(buf, 1, p-buf, fp) != (size_t)(p-buf))
1515         return -1;
1516
1517     return 0;
1518 }
1519
1520 static void do_output_ith(void)
1521 {
1522     uint8_t buf[32];
1523     struct Section *s;
1524     uint64_t addr, hiaddr, hilba;
1525     uint64_t length;
1526     unsigned int chunk;
1527
1528     /* Write the progbits sections to the output file. */
1529     hilba = 0;
1530     for (s = sections; s; s = s->next) {
1531         /* Skip non-progbits sections */
1532         if (!(s->flags & TYPE_PROGBITS))
1533             continue;
1534         /* Skip zero-length sections */
1535         if (s->length == 0)
1536             continue;
1537
1538         addr   = s->start;
1539         length = s->length;
1540         saa_rewind(s->contents);
1541
1542         while (length) {
1543             hiaddr = addr >> 16;
1544             if (hiaddr != hilba) {
1545                 buf[0] = hiaddr >> 8;
1546                 buf[1] = hiaddr;
1547                 write_ith_record(2, 0, 4, buf);
1548                 hilba = hiaddr;
1549             }
1550
1551             chunk = 32 - (addr & 31);
1552             if (length < chunk)
1553                 chunk = length;
1554
1555             saa_rnbytes(s->contents, buf, chunk);
1556             write_ith_record(chunk, (uint16_t)addr, 0, buf);
1557
1558             addr += chunk;
1559             length -= chunk;
1560         }
1561     }
1562
1563     /* Write closing record */
1564     write_ith_record(0, 0, 1, NULL);
1565 }
1566
1567 /* Generate Motorola S-records */
1568 static int write_srecord(unsigned int len,  unsigned int alen,
1569                          uint32_t addr, uint8_t type, void *data)
1570 {
1571     char buf[2+2+8+255*2+2+2];
1572     char *p = buf;
1573     uint8_t csum, *dptr = data;
1574     unsigned int i;
1575
1576     nasm_assert(len <= 255);
1577
1578     switch (alen) {
1579     case 2:
1580         addr &= 0xffff;
1581         break;
1582     case 3:
1583         addr &= 0xffffff;
1584         break;
1585     case 4:
1586         break;
1587     default:
1588         nasm_assert(0);
1589         break;
1590     }
1591
1592     csum = (len+alen+1) + addr + (addr >> 8) + (addr >> 16) + (addr >> 24);
1593     for (i = 0; i < len; i++)
1594         csum += dptr[i];
1595     csum = 0xff-csum;
1596
1597     p += sprintf(p, "S%c%02X%0*X", type, len+alen+1, alen*2, addr);
1598     for (i = 0; i < len; i++)
1599         p += sprintf(p, "%02X", dptr[i]);
1600     p += sprintf(p, "%02X\n", csum);
1601
1602     if (fwrite(buf, 1, p-buf, fp) != (size_t)(p-buf))
1603         return -1;
1604
1605     return 0;
1606 }
1607
1608 static void do_output_srec(void)
1609 {
1610     uint8_t buf[32];
1611     struct Section *s;
1612     uint64_t addr, maxaddr;
1613     uint64_t length;
1614     int alen;
1615     unsigned int chunk;
1616     char dtype, etype;
1617
1618     maxaddr = 0;
1619     for (s = sections; s; s = s->next) {
1620         /* Skip non-progbits sections */
1621         if (!(s->flags & TYPE_PROGBITS))
1622             continue;
1623         /* Skip zero-length sections */
1624         if (s->length == 0)
1625             continue;
1626
1627         addr = s->start + s->length - 1;
1628         if (addr > maxaddr)
1629             maxaddr = addr;
1630     }
1631
1632     if (maxaddr <= 0xffff) {
1633         alen  = 2;
1634         dtype = '1';            /* S1 = 16-bit data */
1635         etype = '9';            /* S9 = 16-bit end */
1636     } else if (maxaddr <= 0xffffff) {
1637         alen = 3;
1638         dtype = '2';            /* S2 = 24-bit data */
1639         etype = '8';            /* S8 = 24-bit end */
1640     } else {
1641         alen = 4;
1642         dtype = '3';            /* S3 = 32-bit data */
1643         etype = '7';            /* S7 = 32-bit end */
1644     }
1645
1646     /* Write head record */
1647     write_srecord(0, 2, 0, '0', NULL);
1648
1649     /* Write the progbits sections to the output file. */
1650     for (s = sections; s; s = s->next) {
1651         /* Skip non-progbits sections */
1652         if (!(s->flags & TYPE_PROGBITS))
1653             continue;
1654         /* Skip zero-length sections */
1655         if (s->length == 0)
1656             continue;
1657
1658         addr   = s->start;
1659         length = s->length;
1660         saa_rewind(s->contents);
1661
1662         while (length) {
1663             chunk = 32 - (addr & 31);
1664             if (length < chunk)
1665                 chunk = length;
1666
1667             saa_rnbytes(s->contents, buf, chunk);
1668             write_srecord(chunk, alen, (uint32_t)addr, dtype, buf);
1669
1670             addr += chunk;
1671             length -= chunk;
1672         }
1673     }
1674
1675     /* Write closing record */
1676     write_srecord(0, alen, 0, etype, NULL);
1677 }
1678
1679
1680 struct ofmt of_bin = {
1681     "flat-form binary files (e.g. DOS .COM, .SYS)",
1682     "bin",
1683     0,
1684     null_debug_arr,
1685     &null_debug_form,
1686     bin_stdmac,
1687     bin_init,
1688     bin_set_info,
1689     bin_out,
1690     bin_deflabel,
1691     bin_secname,
1692     bin_segbase,
1693     bin_directive,
1694     bin_filename,
1695     bin_cleanup
1696 };
1697
1698 struct ofmt of_ith = {
1699     "Intel hex",
1700     "ith",
1701     OFMT_TEXT,
1702     null_debug_arr,
1703     &null_debug_form,
1704     bin_stdmac,
1705     ith_init,
1706     bin_set_info,
1707     bin_out,
1708     bin_deflabel,
1709     bin_secname,
1710     bin_segbase,
1711     bin_directive,
1712     ith_filename,
1713     bin_cleanup
1714 };
1715
1716 struct ofmt of_srec = {
1717     "Motorola S-records",
1718     "srec",
1719     0,
1720     null_debug_arr,
1721     &null_debug_form,
1722     bin_stdmac,
1723     srec_init,
1724     bin_set_info,
1725     bin_out,
1726     bin_deflabel,
1727     bin_secname,
1728     bin_segbase,
1729     bin_directive,
1730     srec_filename,
1731     bin_cleanup
1732 };
1733
1734 #endif                          /* #ifdef OF_BIN */