nasmlib/file.c: Windows _chsize_s() *returns* errno
[nasm.git] / output / outrdf2.c
blobcfd72789ffea3d9f22965f9804468e41d1afe6cd
1 /* ----------------------------------------------------------------------- *
2 *
3 * Copyright 1996-2013 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
9 * conditions are met:
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * ----------------------------------------------------------------------- */
35 * outrdf2.c output routines for the Netwide Assembler to produce
36 * RDOFF version 2 format object files, which Julian originally
37 * planned to use it in his MOSCOW operating system.
40 #include "compiler.h"
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <ctype.h>
46 #include <assert.h>
48 #include "nasm.h"
49 #include "nasmlib.h"
50 #include "saa.h"
51 #include "output/outform.h"
52 #include "output/outlib.h"
54 /* VERBOSE_WARNINGS: define this to add some extra warnings... */
55 #define VERBOSE_WARNINGS
57 #ifdef OF_RDF2
59 #include "rdoff/rdoff.h"
61 /* This signature is written to start of RDOFF files */
62 static const char *RDOFF2Id = RDOFF2_SIGNATURE;
64 /* Note that whenever a segment is referred to in the RDOFF file, its number
65 * is always half of the segment number that NASM uses to refer to it; this
66 * is because NASM only allocates even numbered segments, so as to not
67 * waste any of the 16 bits of segment number written to the file - this
68 * allows up to 65533 external labels to be defined; otherwise it would be
69 * 32764. */
71 #define COUNT_SEGTYPES 9
73 static char *segmenttypes[COUNT_SEGTYPES] = {
74 "null", "text", "code", "data",
75 "comment", "lcomment", "pcomment",
76 "symdebug", "linedebug"
79 static int segmenttypenumbers[COUNT_SEGTYPES] = {
80 0, 1, 1, 2, 3, 4, 5, 6, 7
83 /* code for managing buffers needed to separate code and data into individual
84 * sections until they are ready to be written to the file.
85 * We'd better hope that it all fits in memory else we're buggered... */
87 #define BUF_BLOCK_LEN 4088 /* selected to match page size (4096)
88 * on 80x86 machines for efficiency */
90 /***********************************************************************
91 * Actual code to deal with RDOFF2 ouput format begins here...
94 /* global variables set during the initialisation phase */
96 static struct SAA *seg[RDF_MAXSEGS]; /* seg 0 = code, seg 1 = data */
97 static struct SAA *header; /* relocation/import/export records */
99 static struct seginfo {
100 char *segname;
101 int segnumber;
102 uint16_t segtype;
103 uint16_t segreserved;
104 int32_t seglength;
105 } segments[RDF_MAXSEGS];
107 static int nsegments;
109 static int32_t bsslength;
110 static int32_t headerlength;
112 static void rdf2_init(void)
114 int segtext, segdata, segbss;
116 /* set up the initial segments */
117 segments[0].segname = ".text";
118 segments[0].segnumber = 0;
119 segments[0].segtype = 1;
120 segments[0].segreserved = 0;
121 segments[0].seglength = 0;
123 segments[1].segname = ".data";
124 segments[1].segnumber = 1;
125 segments[1].segtype = 2;
126 segments[1].segreserved = 0;
127 segments[1].seglength = 0;
129 segments[2].segname = ".bss";
130 segments[2].segnumber = 2;
131 segments[2].segtype = 0xFFFF; /* reserved - should never be produced */
132 segments[2].segreserved = 0;
133 segments[2].seglength = 0;
135 nsegments = 3;
137 seg[0] = saa_init(1L);
138 seg[1] = saa_init(1L);
139 seg[2] = NULL; /* special case! */
141 header = saa_init(1L);
143 segtext = seg_alloc();
144 segdata = seg_alloc();
145 segbss = seg_alloc();
146 if (segtext != 0 || segdata != 2 || segbss != 4)
147 nasm_panic(0,
148 "rdf segment numbers not allocated as expected (%d,%d,%d)",
149 segtext, segdata, segbss);
150 bsslength = 0;
151 headerlength = 0;
154 static int32_t rdf2_section_names(char *name, int pass, int *bits)
156 int i;
157 bool err;
158 char *p, *q;
159 int code = -1;
160 int reserved = 0;
162 (void)pass;
165 * Default is 32 bits, in the text segment.
167 if (!name) {
168 *bits = 32;
169 return 0;
172 /* look for segment type code following segment name */
173 p = name;
174 while (*p && !nasm_isspace(*p))
175 p++;
176 if (*p) { /* we're now in whitespace */
177 *p++ = '\0';
178 while (*p && nasm_isspace(80))
179 *p++ = '\0';
181 if (*p) { /* we're now in an attribute value */
183 * see if we have an optional ',number' following the type code
185 if ((q = strchr(p, ','))) {
186 *q++ = '\0';
188 reserved = readnum(q, &err);
189 if (err) {
190 nasm_error(ERR_NONFATAL,
191 "value following comma must be numeric");
192 reserved = 0;
196 * check it against the text strings in segmenttypes
199 for (i = 0; i < COUNT_SEGTYPES; i++)
200 if (!nasm_stricmp(p, segmenttypes[i])) {
201 code = segmenttypenumbers[i];
202 break;
204 if (code == -1) { /* didn't find anything */
205 code = readnum(p, &err);
206 if (err) {
207 nasm_error(ERR_NONFATAL, "unrecognised RDF segment type (%s)",
209 code = 3;
213 for (i = 0; i < nsegments; i++) {
214 if (!strcmp(name, segments[i].segname)) {
215 if (code != -1 || reserved != 0)
216 nasm_error(ERR_NONFATAL, "segment attributes specified on"
217 " redeclaration of segment");
218 return segments[i].segnumber * 2;
222 /* declaring a new segment! */
224 if (code == -1) {
225 nasm_error(ERR_NONFATAL, "new segment declared without type code");
226 code = 3;
228 if (nsegments == RDF_MAXSEGS) {
229 nasm_fatal(0, "reached compiled-in maximum segment limit (%d)",
230 RDF_MAXSEGS);
231 return NO_SEG;
234 segments[nsegments].segname = nasm_strdup(name);
235 i = seg_alloc();
236 if (i % 2 != 0)
237 nasm_panic(0, "seg_alloc() returned odd number");
238 segments[nsegments].segnumber = i >> 1;
239 segments[nsegments].segtype = code;
240 segments[nsegments].segreserved = reserved;
241 segments[nsegments].seglength = 0;
243 seg[nsegments] = saa_init(1L);
245 return i;
249 * Write relocation record
251 static void write_reloc_rec(struct RelocRec *r)
253 char buf[4], *b;
255 if (r->refseg != (uint16_t) NO_SEG && (r->refseg & 1)) /* segment base ref */
256 r->type = RDFREC_SEGRELOC;
258 r->refseg >>= 1; /* adjust segment nos to RDF rather than NASM */
260 saa_wbytes(header, &r->type, 1);
261 saa_wbytes(header, &r->reclen, 1);
262 saa_wbytes(header, &r->segment, 1);
263 b = buf;
264 WRITELONG(b, r->offset);
265 saa_wbytes(header, buf, 4);
266 saa_wbytes(header, &r->length, 1);
267 b = buf;
268 WRITESHORT(b, r->refseg);
269 saa_wbytes(header, buf, 2);
270 headerlength += r->reclen + 2;
274 * Write export record
276 static void write_export_rec(struct ExportRec *r)
278 char buf[4], *b;
280 r->segment >>= 1;
282 saa_wbytes(header, &r->type, 1);
283 saa_wbytes(header, &r->reclen, 1);
284 saa_wbytes(header, &r->flags, 1);
285 saa_wbytes(header, &r->segment, 1);
286 b = buf;
287 WRITELONG(b, r->offset);
288 saa_wbytes(header, buf, 4);
289 saa_wbytes(header, r->label, strlen(r->label) + 1);
290 headerlength += r->reclen + 2;
293 static void write_import_rec(struct ImportRec *r)
295 char buf[4], *b;
297 r->segment >>= 1;
299 saa_wbytes(header, &r->type, 1);
300 saa_wbytes(header, &r->reclen, 1);
301 saa_wbytes(header, &r->flags, 1);
302 b = buf;
303 WRITESHORT(b, r->segment);
304 saa_wbytes(header, buf, 2);
305 saa_wbytes(header, r->label, strlen(r->label) + 1);
306 headerlength += r->reclen + 2;
310 * Write BSS record
312 static void write_bss_rec(struct BSSRec *r)
314 char buf[4], *b;
316 saa_wbytes(header, &r->type, 1);
317 saa_wbytes(header, &r->reclen, 1);
318 b = buf;
319 WRITELONG(b, r->amount);
320 saa_wbytes(header, buf, 4);
321 headerlength += r->reclen + 2;
325 * Write common variable record
327 static void write_common_rec(struct CommonRec *r)
329 char buf[4], *b;
331 r->segment >>= 1;
333 saa_wbytes(header, &r->type, 1);
334 saa_wbytes(header, &r->reclen, 1);
335 b = buf;
336 WRITESHORT(b, r->segment);
337 saa_wbytes(header, buf, 2);
338 b = buf;
339 WRITELONG(b, r->size);
340 saa_wbytes(header, buf, 4);
341 b = buf;
342 WRITESHORT(b, r->align);
343 saa_wbytes(header, buf, 2);
344 saa_wbytes(header, r->label, strlen(r->label) + 1);
345 headerlength += r->reclen + 2;
349 * Write library record
351 static void write_dll_rec(struct DLLRec *r)
353 saa_wbytes(header, &r->type, 1);
354 saa_wbytes(header, &r->reclen, 1);
355 saa_wbytes(header, r->libname, strlen(r->libname) + 1);
356 headerlength += r->reclen + 2;
360 * Write module name record
362 static void write_modname_rec(struct ModRec *r)
364 saa_wbytes(header, &r->type, 1);
365 saa_wbytes(header, &r->reclen, 1);
366 saa_wbytes(header, r->modname, strlen(r->modname) + 1);
367 headerlength += r->reclen + 2;
371 * Handle export, import and common records.
373 static void rdf2_deflabel(char *name, int32_t segment, int64_t offset,
374 int is_global, char *special)
376 struct ExportRec r;
377 struct ImportRec ri;
378 struct CommonRec ci;
379 static int farsym = 0;
380 static int i;
381 char symflags = 0;
382 int len;
384 /* Check if the label length is OK */
385 if ((len = strlen(name)) >= EXIM_LABEL_MAX) {
386 nasm_error(ERR_NONFATAL, "label size exceeds %d bytes", EXIM_LABEL_MAX);
387 return;
389 if (!len) {
390 nasm_error(ERR_NONFATAL, "zero-length label");
391 return;
394 if (is_global == 2) {
395 /* Common variable */
396 ci.type = RDFREC_COMMON;
397 ci.size = offset;
398 ci.segment = segment;
399 strcpy(ci.label, name);
400 ci.reclen = 9 + len;
401 ci.align = 0;
404 * Check the special text to see if it's a valid number and power
405 * of two; if so, store it as the alignment for the common variable.
407 if (special) {
408 bool err;
409 ci.align = readnum(special, &err);
410 if (err)
411 nasm_error(ERR_NONFATAL, "alignment constraint `%s' is not a"
412 " valid number", special);
413 else if ((ci.align | (ci.align - 1)) != 2 * ci.align - 1)
414 nasm_error(ERR_NONFATAL, "alignment constraint `%s' is not a"
415 " power of two", special);
417 write_common_rec(&ci);
420 /* We don't care about local labels or fix-up hints */
421 if (is_global != 1)
422 return;
424 if (special) {
425 while (*special == ' ' || *special == '\t')
426 special++;
428 if (!nasm_strnicmp(special, "export", 6)) {
429 special += 6;
430 symflags |= SYM_GLOBAL;
431 } else if (!nasm_strnicmp(special, "import", 6)) {
432 special += 6;
433 symflags |= SYM_IMPORT;
436 if (*special) {
437 while (nasm_isspace(*special))
438 special++;
439 if (!nasm_stricmp(special, "far")) {
440 farsym = 1;
441 } else if (!nasm_stricmp(special, "near")) {
442 farsym = 0;
443 } else if (!nasm_stricmp(special, "proc") ||
444 !nasm_stricmp(special, "function")) {
445 symflags |= SYM_FUNCTION;
446 } else if (!nasm_stricmp(special, "data") ||
447 !nasm_stricmp(special, "object")) {
448 symflags |= SYM_DATA;
449 } else
450 nasm_error(ERR_NONFATAL, "unrecognised symbol type `%s'",
451 special);
455 if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
456 nasm_error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
457 return;
460 for (i = 0; i < nsegments; i++) {
461 if (segments[i].segnumber == segment >> 1)
462 break;
465 if (i >= nsegments) { /* EXTERN declaration */
466 ri.type = farsym ? RDFREC_FARIMPORT : RDFREC_IMPORT;
467 if (symflags & SYM_GLOBAL)
468 nasm_error(ERR_NONFATAL,
469 "symbol type conflict - EXTERN cannot be EXPORT");
470 ri.flags = symflags;
471 ri.segment = segment;
472 strcpy(ri.label, name);
473 ri.reclen = 4 + len;
474 write_import_rec(&ri);
475 } else if (is_global) {
476 r.type = RDFREC_GLOBAL; /* GLOBAL declaration */
477 if (symflags & SYM_IMPORT)
478 nasm_error(ERR_NONFATAL,
479 "symbol type conflict - GLOBAL cannot be IMPORT");
480 r.flags = symflags;
481 r.segment = segment;
482 r.offset = offset;
483 strcpy(r.label, name);
484 r.reclen = 7 + len;
485 write_export_rec(&r);
489 static void membufwrite(int segment, const void *data, int bytes)
491 int i;
492 char buf[4], *b;
494 for (i = 0; i < nsegments; i++) {
495 if (segments[i].segnumber == segment)
496 break;
498 if (i == nsegments)
499 nasm_panic(0, "can't find segment %d", segment);
501 if (bytes < 0) {
502 b = buf;
503 if (bytes == -2)
504 WRITESHORT(b, *(int16_t *)data);
505 else
506 WRITELONG(b, *(int32_t *)data);
507 data = buf;
508 bytes = -bytes;
510 segments[i].seglength += bytes;
511 saa_wbytes(seg[i], data, bytes);
514 static int getsegmentlength(int segment)
516 int i;
517 for (i = 0; i < nsegments; i++) {
518 if (segments[i].segnumber == segment)
519 break;
521 if (i == nsegments)
522 nasm_panic(0, "can't find segment %d", segment);
524 return segments[i].seglength;
527 static void rdf2_out(int32_t segto, const void *data,
528 enum out_type type, uint64_t size,
529 int32_t segment, int32_t wrt)
531 struct RelocRec rr;
532 uint8_t databuf[8], *pd;
533 int seg;
535 if (segto == NO_SEG) {
536 if (type != OUT_RESERVE)
537 nasm_error(ERR_NONFATAL,
538 "attempt to assemble code in ABSOLUTE space");
539 return;
542 segto >>= 1; /* convert NASM segment no to RDF number */
544 for (seg = 0; seg < nsegments; seg++) {
545 if (segments[seg].segnumber == segto)
546 break;
548 if (seg >= nsegments) {
549 nasm_error(ERR_NONFATAL,
550 "specified segment not supported by rdf output format");
551 return;
554 if (wrt != NO_SEG) {
555 wrt = NO_SEG; /* continue to do _something_ */
556 nasm_error(ERR_NONFATAL, "WRT not supported by rdf output format");
559 if (segto == 2 && type != OUT_RESERVE) {
560 nasm_error(ERR_NONFATAL, "BSS segments may not be initialized");
562 /* just reserve the space for now... */
564 if (type == OUT_REL2ADR)
565 size = 2;
566 else
567 size = 4;
568 type = OUT_RESERVE;
571 if (type == OUT_RESERVE) {
572 if (segto == 2) /* BSS segment space reserverd */
573 bsslength += size;
574 else
575 while (size--)
576 membufwrite(segto, databuf, 1);
577 } else if (type == OUT_RAWDATA) {
578 if (segment != NO_SEG)
579 nasm_panic(0, "OUT_RAWDATA with other than NO_SEG");
581 membufwrite(segto, data, size);
582 } else if (type == OUT_ADDRESS) {
583 int asize = abs((int)size);
585 /* if segment == NO_SEG then we are writing an address of an
586 object within the same segment - do not produce reloc rec. */
588 /* FIXME - is this behaviour sane? at first glance it doesn't
589 appear to be. Must test this thoroughly...! */
591 if (segment != NO_SEG) {
592 /* it's an address, so we must write a relocation record */
594 rr.type = RDFREC_RELOC; /* type signature */
595 rr.reclen = 8;
596 rr.segment = segto; /* segment we're currently in */
597 rr.offset = getsegmentlength(segto); /* current offset */
598 rr.length = asize; /* length of reference */
599 rr.refseg = segment; /* segment referred to */
600 write_reloc_rec(&rr);
603 pd = databuf; /* convert address to little-endian */
604 WRITEADDR(pd, *(int64_t *)data, asize);
605 membufwrite(segto, databuf, asize);
606 } else if (type == OUT_REL2ADR) {
607 if (segment == segto)
608 nasm_panic(0, "intra-segment OUT_REL2ADR");
610 rr.reclen = 8;
611 rr.offset = getsegmentlength(segto); /* current offset */
612 rr.length = 2; /* length of reference */
613 rr.refseg = segment; /* segment referred to (will be >>1'd) */
615 if (segment != NO_SEG && segment % 2) {
616 rr.type = RDFREC_SEGRELOC;
617 rr.segment = segto; /* memory base refs *aren't ever* relative! */
618 write_reloc_rec(&rr);
620 /* what do we put in the code? Simply the data. This should almost
621 * always be zero, unless someone's doing segment arithmetic...
623 rr.offset = *(int64_t *)data;
624 } else {
625 rr.type = RDFREC_RELOC; /* type signature */
626 rr.segment = segto + 64; /* segment we're currently in + rel flag */
627 write_reloc_rec(&rr);
629 /* work out what to put in the code: offset of the end of this operand,
630 * subtracted from any data specified, so that loader can just add
631 * address of imported symbol onto it to get address relative to end of
632 * instruction: import_address + data(offset) - end_of_instrn */
634 rr.offset = *(int32_t *)data - (rr.offset + size);
637 membufwrite(segto, &rr.offset, -2);
638 } else if (type == OUT_REL4ADR) {
639 if ((segment == segto) && (globalbits != 64))
640 nasm_panic(0, "intra-segment OUT_REL4ADR");
641 if (segment != NO_SEG && segment % 2) {
642 nasm_panic(0, "erm... 4 byte segment base ref?");
645 rr.type = RDFREC_RELOC; /* type signature */
646 rr.segment = segto + 64; /* segment we're currently in + rel tag */
647 rr.offset = getsegmentlength(segto); /* current offset */
648 rr.length = 4; /* length of reference */
649 rr.refseg = segment; /* segment referred to */
650 rr.reclen = 8;
651 write_reloc_rec(&rr);
653 rr.offset = *(int64_t *)data - (rr.offset + size);
655 membufwrite(segto, &rr.offset, -4);
659 static void rdf2_cleanup(void)
661 int32_t l;
662 struct BSSRec bs;
663 int i;
665 /* should write imported & exported symbol declarations to header here */
667 /* generate the output file... */
668 nasm_write(RDOFF2Id, 6, ofile); /* file type magic number */
670 if (bsslength != 0) { /* reserve BSS */
671 bs.type = RDFREC_BSS;
672 bs.amount = bsslength;
673 bs.reclen = 4;
674 write_bss_rec(&bs);
678 * calculate overall length of the output object
680 l = headerlength + 4;
682 for (i = 0; i < nsegments; i++) {
683 if (i == 2)
684 continue; /* skip BSS segment */
685 l += 10 + segments[i].seglength;
687 l += 10; /* null segment */
689 fwriteint32_t(l, ofile);
691 fwriteint32_t(headerlength, ofile);
692 saa_fpwrite(header, ofile); /* dump header */
693 saa_free(header);
695 for (i = 0; i < nsegments; i++) {
696 if (i == 2)
697 continue;
699 fwriteint16_t(segments[i].segtype, ofile);
700 fwriteint16_t(segments[i].segnumber, ofile);
701 fwriteint16_t(segments[i].segreserved, ofile);
702 fwriteint32_t(segments[i].seglength, ofile);
704 saa_fpwrite(seg[i], ofile);
705 saa_free(seg[i]);
708 /* null segment - write 10 bytes of zero */
709 fwriteint32_t(0, ofile);
710 fwriteint32_t(0, ofile);
711 fwriteint16_t(0, ofile);
714 static int32_t rdf2_segbase(int32_t segment)
716 return segment;
720 * Handle RDOFF2 specific directives
722 static int rdf2_directive(enum directives directive, char *value, int pass)
724 size_t n;
726 switch (directive) {
727 case D_LIBRARY:
728 n = strlen(value);
729 if (n >= MODLIB_NAME_MAX) {
730 nasm_error(ERR_NONFATAL, "name size exceeds %d bytes", MODLIB_NAME_MAX);
731 return 1;
733 if (pass == 1) {
734 struct DLLRec r;
735 r.type = RDFREC_DLL;
736 r.reclen = n + 1;
737 strcpy(r.libname, value);
738 write_dll_rec(&r);
740 return 1;
742 case D_MODULE:
743 if ((n = strlen(value)) >= MODLIB_NAME_MAX) {
744 nasm_error(ERR_NONFATAL, "name size exceeds %d bytes", MODLIB_NAME_MAX);
745 return 1;
747 if (pass == 1) {
748 struct ModRec r;
749 r.type = RDFREC_MODNAME;
750 r.reclen = n + 1;
751 strcpy(r.modname, value);
752 write_modname_rec(&r);
754 return 1;
756 default:
757 return 0;
761 static void rdf2_filename(char *inname, char *outname)
763 standard_extension(inname, outname, ".rdf");
766 extern macros_t rdf2_stdmac[];
768 static int rdf2_set_info(enum geninfo type, char **val)
770 (void)type;
771 (void)val;
772 return 0;
775 const struct ofmt of_rdf2 = {
776 "Relocatable Dynamic Object File Format v2.0",
777 "rdf",
780 null_debug_arr,
781 &null_debug_form,
782 rdf2_stdmac,
783 rdf2_init,
784 rdf2_set_info,
785 rdf2_out,
786 rdf2_deflabel,
787 rdf2_section_names,
788 null_sectalign,
789 rdf2_segbase,
790 rdf2_directive,
791 rdf2_filename,
792 rdf2_cleanup
795 #endif /* OF_RDF2 */