Debian Codegraph @

output/outbin.c

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