Hash even backend-specific directives, unify null functions
[platform/upstream/nasm.git] / output / outobj.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  * outobj.c     output routines for the Netwide Assembler to produce
36  *              .OBJ object files
37  */
38
39 #include "compiler.h"
40
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <ctype.h>
45 #include <inttypes.h>
46
47 #include "nasm.h"
48 #include "nasmlib.h"
49 #include "stdscan.h"
50 #include "output/outform.h"
51 #include "output/outlib.h"
52
53 #ifdef OF_OBJ
54
55 /*
56  * outobj.c is divided into two sections.  The first section is low level
57  * routines for creating obj records;  It has nearly zero NASM specific
58  * code.  The second section is high level routines for processing calls and
59  * data structures from the rest of NASM into obj format.
60  *
61  * It should be easy (though not zero work) to lift the first section out for
62  * use as an obj file writer for some other assembler or compiler.
63  */
64
65 /*
66  * These routines are built around the ObjRecord data struture.  An ObjRecord
67  * holds an object file record that may be under construction or complete.
68  *
69  * A major function of these routines is to support continuation of an obj
70  * record into the next record when the maximum record size is exceeded.  The
71  * high level code does not need to worry about where the record breaks occur.
72  * It does need to do some minor extra steps to make the automatic continuation
73  * work.  Those steps may be skipped for records where the high level knows no
74  * continuation could be required.
75  *
76  * 1) An ObjRecord is allocated and cleared by obj_new, or an existing ObjRecord
77  *    is cleared by obj_clear.
78  *
79  * 2) The caller should fill in .type.
80  *
81  * 3) If the record is continuable and there is processing that must be done at
82  *    the start of each record then the caller should fill in .ori with the
83  *    address of the record initializer routine.
84  *
85  * 4) If the record is continuable and it should be saved (rather than emitted
86  *    immediately) as each record is done, the caller should set .up to be a
87  *    pointer to a location in which the caller keeps the master pointer to the
88  *    ObjRecord.  When the record is continued, the obj_bump routine will then
89  *    allocate a new ObjRecord structure and update the master pointer.
90  *
91  * 5) If the .ori field was used then the caller should fill in the .parm with
92  *    any data required by the initializer.
93  *
94  * 6) The caller uses the routines: obj_byte, obj_word, obj_rword, obj_dword,
95  *    obj_x, obj_index, obj_value and obj_name to fill in the various kinds of
96  *    data required for this record.
97  *
98  * 7) If the record is continuable, the caller should call obj_commit at each
99  *    point where breaking the record is permitted.
100  *
101  * 8) To write out the record, the caller should call obj_emit2.  If the
102  *    caller has called obj_commit for all data written then he can get slightly
103  *    faster code by calling obj_emit instead of obj_emit2.
104  *
105  * Most of these routines return an ObjRecord pointer.  This will be the input
106  * pointer most of the time and will be the new location if the ObjRecord
107  * moved as a result of the call.  The caller may ignore the return value in
108  * three cases:  It is a "Never Reallocates" routine;  or  The caller knows
109  * continuation is not possible;  or  The caller uses the master pointer for the
110  * next operation.
111  */
112
113 #define RECORD_MAX (1024-3)     /* maximal size of any record except type+reclen */
114 #define OBJ_PARMS  3            /* maximum .parm used by any .ori routine */
115
116 #define FIX_08_LOW      0x8000  /* location type for various fixup subrecords */
117 #define FIX_16_OFFSET   0x8400
118 #define FIX_16_SELECTOR 0x8800
119 #define FIX_32_POINTER  0x8C00
120 #define FIX_08_HIGH     0x9000
121 #define FIX_32_OFFSET   0xA400
122 #define FIX_48_POINTER  0xAC00
123
124 enum RecordID {                 /* record ID codes */
125
126     THEADR = 0x80,              /* module header */
127     COMENT = 0x88,              /* comment record */
128
129     LINNUM = 0x94,              /* line number record */
130     LNAMES = 0x96,              /* list of names */
131
132     SEGDEF = 0x98,              /* segment definition */
133     GRPDEF = 0x9A,              /* group definition */
134     EXTDEF = 0x8C,              /* external definition */
135     PUBDEF = 0x90,              /* public definition */
136     COMDEF = 0xB0,              /* common definition */
137
138     LEDATA = 0xA0,              /* logical enumerated data */
139     FIXUPP = 0x9C,              /* fixups (relocations) */
140     FIXU32 = 0x9D,              /* 32-bit fixups (relocations) */
141
142     MODEND = 0x8A,              /* module end */
143     MODE32 = 0x8B               /* module end for 32-bit objects */
144 };
145
146 enum ComentID {                 /* ID codes for comment records */
147
148     dEXTENDED = 0xA1,           /* tells that we are using translator-specific extensions */
149     dLINKPASS = 0xA2,           /* link pass 2 marker */
150     dTYPEDEF = 0xE3,            /* define a type */
151     dSYM = 0xE6,                /* symbol debug record */
152     dFILNAME = 0xE8,            /* file name record */
153     dCOMPDEF = 0xEA             /* compiler type info */
154 };
155
156 typedef struct ObjRecord ObjRecord;
157 typedef void ORI(ObjRecord * orp);
158
159 struct ObjRecord {
160     ORI *ori;                   /* Initialization routine           */
161     int used;                   /* Current data size                */
162     int committed;              /* Data size at last boundary       */
163     int x_size;                 /* (see obj_x)                      */
164     unsigned int type;          /* Record type                      */
165     ObjRecord *child;           /* Associated record below this one */
166     ObjRecord **up;             /* Master pointer to this ObjRecord */
167     ObjRecord *back;            /* Previous part of this record     */
168     uint32_t parm[OBJ_PARMS];      /* Parameters for ori routine       */
169     uint8_t buf[RECORD_MAX + 3];
170 };
171
172 static void obj_fwrite(ObjRecord * orp);
173 static void ori_ledata(ObjRecord * orp);
174 static void ori_pubdef(ObjRecord * orp);
175 static void ori_null(ObjRecord * orp);
176 static ObjRecord *obj_commit(ObjRecord * orp);
177
178 static bool obj_uppercase;       /* Flag: all names in uppercase */
179 static bool obj_use32;           /* Flag: at least one segment is 32-bit */
180
181 /*
182  * Clear an ObjRecord structure.  (Never reallocates).
183  * To simplify reuse of ObjRecord's, .type, .ori and .parm are not cleared.
184  */
185 static ObjRecord *obj_clear(ObjRecord * orp)
186 {
187     orp->used = 0;
188     orp->committed = 0;
189     orp->x_size = 0;
190     orp->child = NULL;
191     orp->up = NULL;
192     orp->back = NULL;
193     return (orp);
194 }
195
196 /*
197  * Emit an ObjRecord structure.  (Never reallocates).
198  * The record is written out preceeded (recursively) by its previous part (if
199  * any) and followed (recursively) by its child (if any).
200  * The previous part and the child are freed.  The main ObjRecord is cleared,
201  * not freed.
202  */
203 static ObjRecord *obj_emit(ObjRecord * orp)
204 {
205     if (orp->back) {
206         obj_emit(orp->back);
207         nasm_free(orp->back);
208     }
209
210     if (orp->committed)
211         obj_fwrite(orp);
212
213     if (orp->child) {
214         obj_emit(orp->child);
215         nasm_free(orp->child);
216     }
217
218     return (obj_clear(orp));
219 }
220
221 /*
222  * Commit and Emit a record.  (Never reallocates).
223  */
224 static ObjRecord *obj_emit2(ObjRecord * orp)
225 {
226     obj_commit(orp);
227     return (obj_emit(orp));
228 }
229
230 /*
231  * Allocate and clear a new ObjRecord;  Also sets .ori to ori_null
232  */
233 static ObjRecord *obj_new(void)
234 {
235     ObjRecord *orp;
236
237     orp = obj_clear(nasm_malloc(sizeof(ObjRecord)));
238     orp->ori = ori_null;
239     return (orp);
240 }
241
242 /*
243  * Advance to the next record because the existing one is full or its x_size
244  * is incompatible.
245  * Any uncommited data is moved into the next record.
246  */
247 static ObjRecord *obj_bump(ObjRecord * orp)
248 {
249     ObjRecord *nxt;
250     int used = orp->used;
251     int committed = orp->committed;
252
253     if (orp->up) {
254         *orp->up = nxt = obj_new();
255         nxt->ori = orp->ori;
256         nxt->type = orp->type;
257         nxt->up = orp->up;
258         nxt->back = orp;
259         memcpy(nxt->parm, orp->parm, sizeof(orp->parm));
260     } else
261         nxt = obj_emit(orp);
262
263     used -= committed;
264     if (used) {
265         nxt->committed = 1;
266         nxt->ori(nxt);
267         nxt->committed = nxt->used;
268         memcpy(nxt->buf + nxt->committed, orp->buf + committed, used);
269         nxt->used = nxt->committed + used;
270     }
271
272     return (nxt);
273 }
274
275 /*
276  * Advance to the next record if necessary to allow the next field to fit.
277  */
278 static ObjRecord *obj_check(ObjRecord * orp, int size)
279 {
280     if (orp->used + size > RECORD_MAX)
281         orp = obj_bump(orp);
282
283     if (!orp->committed) {
284         orp->committed = 1;
285         orp->ori(orp);
286         orp->committed = orp->used;
287     }
288
289     return (orp);
290 }
291
292 /*
293  * All data written so far is commited to the current record (won't be moved to
294  * the next record in case of continuation).
295  */
296 static ObjRecord *obj_commit(ObjRecord * orp)
297 {
298     orp->committed = orp->used;
299     return (orp);
300 }
301
302 /*
303  * Write a byte
304  */
305 static ObjRecord *obj_byte(ObjRecord * orp, uint8_t val)
306 {
307     orp = obj_check(orp, 1);
308     orp->buf[orp->used] = val;
309     orp->used++;
310     return (orp);
311 }
312
313 /*
314  * Write a word
315  */
316 static ObjRecord *obj_word(ObjRecord * orp, unsigned int val)
317 {
318     orp = obj_check(orp, 2);
319     orp->buf[orp->used] = val;
320     orp->buf[orp->used + 1] = val >> 8;
321     orp->used += 2;
322     return (orp);
323 }
324
325 /*
326  * Write a reversed word
327  */
328 static ObjRecord *obj_rword(ObjRecord * orp, unsigned int val)
329 {
330     orp = obj_check(orp, 2);
331     orp->buf[orp->used] = val >> 8;
332     orp->buf[orp->used + 1] = val;
333     orp->used += 2;
334     return (orp);
335 }
336
337 /*
338  * Write a dword
339  */
340 static ObjRecord *obj_dword(ObjRecord * orp, uint32_t val)
341 {
342     orp = obj_check(orp, 4);
343     orp->buf[orp->used] = val;
344     orp->buf[orp->used + 1] = val >> 8;
345     orp->buf[orp->used + 2] = val >> 16;
346     orp->buf[orp->used + 3] = val >> 24;
347     orp->used += 4;
348     return (orp);
349 }
350
351 /*
352  * All fields of "size x" in one obj record must be the same size (either 16
353  * bits or 32 bits).  There is a one bit flag in each record which specifies
354  * which.
355  * This routine is used to force the current record to have the desired
356  * x_size.  x_size is normally automatic (using obj_x), so that this
357  * routine should be used outside obj_x, only to provide compatibility with
358  * linkers that have bugs in their processing of the size bit.
359  */
360
361 static ObjRecord *obj_force(ObjRecord * orp, int x)
362 {
363     if (orp->x_size == (x ^ 48))
364         orp = obj_bump(orp);
365     orp->x_size = x;
366     return (orp);
367 }
368
369 /*
370  * This routine writes a field of size x.  The caller does not need to worry at
371  * all about whether 16-bits or 32-bits are required.
372  */
373 static ObjRecord *obj_x(ObjRecord * orp, uint32_t val)
374 {
375     if (orp->type & 1)
376         orp->x_size = 32;
377     if (val > 0xFFFF)
378         orp = obj_force(orp, 32);
379     if (orp->x_size == 32) {
380         ObjRecord *nxt = obj_dword(orp, val);
381         nxt->x_size = 32;       /* x_size is cleared when a record overflows */
382         return nxt;
383     }
384     orp->x_size = 16;
385     return (obj_word(orp, val));
386 }
387
388 /*
389  * Writes an index
390  */
391 static ObjRecord *obj_index(ObjRecord * orp, unsigned int val)
392 {
393     if (val < 128)
394         return (obj_byte(orp, val));
395     return (obj_word(orp, (val >> 8) | (val << 8) | 0x80));
396 }
397
398 /*
399  * Writes a variable length value
400  */
401 static ObjRecord *obj_value(ObjRecord * orp, uint32_t val)
402 {
403     if (val <= 128)
404         return (obj_byte(orp, val));
405     if (val <= 0xFFFF) {
406         orp = obj_byte(orp, 129);
407         return (obj_word(orp, val));
408     }
409     if (val <= 0xFFFFFF)
410         return (obj_dword(orp, (val << 8) + 132));
411     orp = obj_byte(orp, 136);
412     return (obj_dword(orp, val));
413 }
414
415 /*
416  * Writes a counted string
417  */
418 static ObjRecord *obj_name(ObjRecord * orp, const char *name)
419 {
420     int len = strlen(name);
421     uint8_t *ptr;
422
423     orp = obj_check(orp, len + 1);
424     ptr = orp->buf + orp->used;
425     *ptr++ = len;
426     orp->used += len + 1;
427     if (obj_uppercase)
428         while (--len >= 0) {
429             *ptr++ = toupper(*name);
430             name++;
431     } else
432         memcpy(ptr, name, len);
433     return (orp);
434 }
435
436 /*
437  * Initializer for an LEDATA record.
438  * parm[0] = offset
439  * parm[1] = segment index
440  * During the use of a LEDATA ObjRecord, parm[0] is constantly updated to
441  * represent the offset that would be required if the record were split at the
442  * last commit point.
443  * parm[2] is a copy of parm[0] as it was when the current record was initted.
444  */
445 static void ori_ledata(ObjRecord * orp)
446 {
447     obj_index(orp, orp->parm[1]);
448     orp->parm[2] = orp->parm[0];
449     obj_x(orp, orp->parm[0]);
450 }
451
452 /*
453  * Initializer for a PUBDEF record.
454  * parm[0] = group index
455  * parm[1] = segment index
456  * parm[2] = frame (only used when both indexes are zero)
457  */
458 static void ori_pubdef(ObjRecord * orp)
459 {
460     obj_index(orp, orp->parm[0]);
461     obj_index(orp, orp->parm[1]);
462     if (!(orp->parm[0] | orp->parm[1]))
463         obj_word(orp, orp->parm[2]);
464 }
465
466 /*
467  * Initializer for a LINNUM record.
468  * parm[0] = group index
469  * parm[1] = segment index
470  */
471 static void ori_linnum(ObjRecord * orp)
472 {
473     obj_index(orp, orp->parm[0]);
474     obj_index(orp, orp->parm[1]);
475 }
476
477 /*
478  * Initializer for a local vars record.
479  */
480 static void ori_local(ObjRecord * orp)
481 {
482     obj_byte(orp, 0x40);
483     obj_byte(orp, dSYM);
484 }
485
486 /*
487  * Null initializer for records that continue without any header info
488  */
489 static void ori_null(ObjRecord * orp)
490 {
491     (void)orp;                  /* Do nothing */
492 }
493
494 /*
495  * This concludes the low level section of outobj.c
496  */
497
498 static char obj_infile[FILENAME_MAX];
499
500 static efunc error;
501 static evalfunc evaluate;
502 static ldfunc deflabel;
503 static FILE *ofp;
504 static int32_t first_seg;
505 static bool any_segs;
506 static int passtwo;
507 static int arrindex;
508
509 #define GROUP_MAX 256           /* we won't _realistically_ have more
510                                  * than this many segs in a group */
511 #define EXT_BLKSIZ 256          /* block size for externals list */
512
513 struct Segment;                 /* need to know these structs exist */
514 struct Group;
515
516 struct LineNumber {
517     struct LineNumber *next;
518     struct Segment *segment;
519     int32_t offset;
520     int32_t lineno;
521 };
522
523 static struct FileName {
524     struct FileName *next;
525     char *name;
526     struct LineNumber *lnhead, **lntail;
527     int index;
528 } *fnhead, **fntail;
529
530 static struct Array {
531     struct Array *next;
532     unsigned size;
533     int basetype;
534 } *arrhead, **arrtail;
535
536 #define ARRAYBOT 31             /* magic number  for first array index */
537
538 static struct Public {
539     struct Public *next;
540     char *name;
541     int32_t offset;
542     int32_t segment;               /* only if it's far-absolute */
543     int type;                   /* only for local debug syms */
544 } *fpubhead, **fpubtail, *last_defined;
545
546 static struct External {
547     struct External *next;
548     char *name;
549     int32_t commonsize;
550     int32_t commonelem;            /* element size if FAR, else zero */
551     int index;                  /* OBJ-file external index */
552     enum {
553         DEFWRT_NONE,            /* no unusual default-WRT */
554         DEFWRT_STRING,          /* a string we don't yet understand */
555         DEFWRT_SEGMENT,         /* a segment */
556         DEFWRT_GROUP            /* a group */
557     } defwrt_type;
558     union {
559         char *string;
560         struct Segment *seg;
561         struct Group *grp;
562     } defwrt_ptr;
563     struct External *next_dws;  /* next with DEFWRT_STRING */
564 } *exthead, **exttail, *dws;
565
566 static int externals;
567
568 static struct ExtBack {
569     struct ExtBack *next;
570     struct External *exts[EXT_BLKSIZ];
571 } *ebhead, **ebtail;
572
573 static struct Segment {
574     struct Segment *next;
575     int32_t index;                 /* the NASM segment id */
576     int32_t obj_index;             /* the OBJ-file segment index */
577     struct Group *grp;          /* the group it beint32_ts to */
578     uint32_t currentpos;
579     int32_t align;                 /* can be SEG_ABS + absolute addr */
580     enum {
581         CMB_PRIVATE = 0,
582         CMB_PUBLIC = 2,
583         CMB_STACK = 5,
584         CMB_COMMON = 6
585     } combine;
586     bool use32;                 /* is this segment 32-bit? */
587     struct Public *pubhead, **pubtail, *lochead, **loctail;
588     char *name;
589     char *segclass, *overlay;   /* `class' is a C++ keyword :-) */
590     ObjRecord *orp;
591 } *seghead, **segtail, *obj_seg_needs_update;
592
593 static struct Group {
594     struct Group *next;
595     char *name;
596     int32_t index;                 /* NASM segment id */
597     int32_t obj_index;             /* OBJ-file group index */
598     int32_t nentries;              /* number of elements... */
599     int32_t nindices;              /* ...and number of index elts... */
600     union {
601         int32_t index;
602         char *name;
603     } segs[GROUP_MAX];          /* ...in this */
604 } *grphead, **grptail, *obj_grp_needs_update;
605
606 static struct ImpDef {
607     struct ImpDef *next;
608     char *extname;
609     char *libname;
610     unsigned int impindex;
611     char *impname;
612 } *imphead, **imptail;
613
614 static struct ExpDef {
615     struct ExpDef *next;
616     char *intname;
617     char *extname;
618     unsigned int ordinal;
619     int flags;
620 } *exphead, **exptail;
621
622 #define EXPDEF_FLAG_ORDINAL  0x80
623 #define EXPDEF_FLAG_RESIDENT 0x40
624 #define EXPDEF_FLAG_NODATA   0x20
625 #define EXPDEF_MASK_PARMCNT  0x1F
626
627 static int32_t obj_entry_seg, obj_entry_ofs;
628
629 struct ofmt of_obj;
630
631 /* The current segment */
632 static struct Segment *current_seg;
633
634 static int32_t obj_segment(char *, int, int *);
635 static void obj_write_file(int debuginfo);
636 static int obj_directive(enum directives, char *, int);
637
638 static void obj_init(FILE * fp, efunc errfunc, ldfunc ldef, evalfunc eval)
639 {
640     ofp = fp;
641     error = errfunc;
642     evaluate = eval;
643     deflabel = ldef;
644     first_seg = seg_alloc();
645     any_segs = false;
646     fpubhead = NULL;
647     fpubtail = &fpubhead;
648     exthead = NULL;
649     exttail = &exthead;
650     imphead = NULL;
651     imptail = &imphead;
652     exphead = NULL;
653     exptail = &exphead;
654     dws = NULL;
655     externals = 0;
656     ebhead = NULL;
657     ebtail = &ebhead;
658     seghead = obj_seg_needs_update = NULL;
659     segtail = &seghead;
660     grphead = obj_grp_needs_update = NULL;
661     grptail = &grphead;
662     obj_entry_seg = NO_SEG;
663     obj_uppercase = false;
664     obj_use32 = false;
665     passtwo = 0;
666     current_seg = NULL;
667 }
668
669 static int obj_set_info(enum geninfo type, char **val)
670 {
671     (void)type;
672     (void)val;
673
674     return 0;
675 }
676 static void obj_cleanup(int debuginfo)
677 {
678     obj_write_file(debuginfo);
679     of_obj.current_dfmt->cleanup();
680     fclose(ofp);
681     while (seghead) {
682         struct Segment *segtmp = seghead;
683         seghead = seghead->next;
684         while (segtmp->pubhead) {
685             struct Public *pubtmp = segtmp->pubhead;
686             segtmp->pubhead = pubtmp->next;
687             nasm_free(pubtmp->name);
688             nasm_free(pubtmp);
689         }
690         nasm_free(segtmp->segclass);
691         nasm_free(segtmp->overlay);
692         nasm_free(segtmp);
693     }
694     while (fpubhead) {
695         struct Public *pubtmp = fpubhead;
696         fpubhead = fpubhead->next;
697         nasm_free(pubtmp->name);
698         nasm_free(pubtmp);
699     }
700     while (exthead) {
701         struct External *exttmp = exthead;
702         exthead = exthead->next;
703         nasm_free(exttmp);
704     }
705     while (imphead) {
706         struct ImpDef *imptmp = imphead;
707         imphead = imphead->next;
708         nasm_free(imptmp->extname);
709         nasm_free(imptmp->libname);
710         nasm_free(imptmp->impname);     /* nasm_free won't mind if it's NULL */
711         nasm_free(imptmp);
712     }
713     while (exphead) {
714         struct ExpDef *exptmp = exphead;
715         exphead = exphead->next;
716         nasm_free(exptmp->extname);
717         nasm_free(exptmp->intname);
718         nasm_free(exptmp);
719     }
720     while (ebhead) {
721         struct ExtBack *ebtmp = ebhead;
722         ebhead = ebhead->next;
723         nasm_free(ebtmp);
724     }
725     while (grphead) {
726         struct Group *grptmp = grphead;
727         grphead = grphead->next;
728         nasm_free(grptmp);
729     }
730 }
731
732 static void obj_ext_set_defwrt(struct External *ext, char *id)
733 {
734     struct Segment *seg;
735     struct Group *grp;
736
737     for (seg = seghead; seg; seg = seg->next)
738         if (!strcmp(seg->name, id)) {
739             ext->defwrt_type = DEFWRT_SEGMENT;
740             ext->defwrt_ptr.seg = seg;
741             nasm_free(id);
742             return;
743         }
744
745     for (grp = grphead; grp; grp = grp->next)
746         if (!strcmp(grp->name, id)) {
747             ext->defwrt_type = DEFWRT_GROUP;
748             ext->defwrt_ptr.grp = grp;
749             nasm_free(id);
750             return;
751         }
752
753     ext->defwrt_type = DEFWRT_STRING;
754     ext->defwrt_ptr.string = id;
755     ext->next_dws = dws;
756     dws = ext;
757 }
758
759 static void obj_deflabel(char *name, int32_t segment,
760                          int64_t offset, int is_global, char *special)
761 {
762     /*
763      * We have three cases:
764      *
765      * (i) `segment' is a segment-base. If so, set the name field
766      * for the segment or group structure it refers to, and then
767      * return.
768      *
769      * (ii) `segment' is one of our segments, or a SEG_ABS segment.
770      * Save the label position for later output of a PUBDEF record.
771      * (Or a MODPUB, if we work out how.)
772      *
773      * (iii) `segment' is not one of our segments. Save the label
774      * position for later output of an EXTDEF, and also store a
775      * back-reference so that we can map later references to this
776      * segment number to the external index.
777      */
778     struct External *ext;
779     struct ExtBack *eb;
780     struct Segment *seg;
781     int i;
782     bool used_special = false;   /* have we used the special text? */
783
784 #if defined(DEBUG) && DEBUG>2
785     fprintf(stderr,
786             " obj_deflabel: %s, seg=%ld, off=%ld, is_global=%d, %s\n",
787             name, segment, offset, is_global, special);
788 #endif
789
790     /*
791      * If it's a special-retry from pass two, discard it.
792      */
793     if (is_global == 3)
794         return;
795
796     /*
797      * First check for the double-period, signifying something
798      * unusual.
799      */
800     if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
801         if (!strcmp(name, "..start")) {
802             obj_entry_seg = segment;
803             obj_entry_ofs = offset;
804             return;
805         }
806         error(ERR_NONFATAL, "unrecognised special symbol `%s'", name);
807     }
808
809     /*
810      * Case (i):
811      */
812     if (obj_seg_needs_update) {
813         obj_seg_needs_update->name = name;
814         return;
815     } else if (obj_grp_needs_update) {
816         obj_grp_needs_update->name = name;
817         return;
818     }
819     if (segment < SEG_ABS && segment != NO_SEG && segment % 2)
820         return;
821
822     if (segment >= SEG_ABS || segment == NO_SEG) {
823         /*
824          * SEG_ABS subcase of (ii).
825          */
826         if (is_global) {
827             struct Public *pub;
828
829             pub = *fpubtail = nasm_malloc(sizeof(*pub));
830             fpubtail = &pub->next;
831             pub->next = NULL;
832             pub->name = nasm_strdup(name);
833             pub->offset = offset;
834             pub->segment = (segment == NO_SEG ? 0 : segment & ~SEG_ABS);
835         }
836         if (special)
837             error(ERR_NONFATAL, "OBJ supports no special symbol features"
838                   " for this symbol type");
839         return;
840     }
841
842     /*
843      * If `any_segs' is still false, we might need to define a
844      * default segment, if they're trying to declare a label in
845      * `first_seg'.
846      */
847     if (!any_segs && segment == first_seg) {
848         int tempint;            /* ignored */
849         if (segment != obj_segment("__NASMDEFSEG", 2, &tempint))
850             error(ERR_PANIC, "strange segment conditions in OBJ driver");
851     }
852
853     for (seg = seghead; seg && is_global; seg = seg->next)
854         if (seg->index == segment) {
855             struct Public *loc = nasm_malloc(sizeof(*loc));
856             /*
857              * Case (ii). Maybe MODPUB someday?
858              */
859             *seg->pubtail = loc;
860             seg->pubtail = &loc->next;
861             loc->next = NULL;
862             loc->name = nasm_strdup(name);
863             loc->offset = offset;
864
865             if (special)
866                 error(ERR_NONFATAL,
867                       "OBJ supports no special symbol features"
868                       " for this symbol type");
869             return;
870         }
871
872     /*
873      * Case (iii).
874      */
875     if (is_global) {
876         ext = *exttail = nasm_malloc(sizeof(*ext));
877         ext->next = NULL;
878         exttail = &ext->next;
879         ext->name = name;
880         /* Place by default all externs into the current segment */
881         ext->defwrt_type = DEFWRT_NONE;
882
883 /* 28-Apr-2002 - John Coffman
884   The following code was introduced on 12-Aug-2000, and breaks fixups
885   on code passed thru the MSC 5.1 linker (3.66) and MSC 6.00A linker
886   (5.10).  It was introduced after FIXUP32 was added, and may be needed
887   for 32-bit segments.  The following will get 16-bit segments working
888   again, and maybe someone can correct the 'if' condition which is
889   actually needed.
890 */
891 #if 0
892         if (current_seg) {
893 #else
894         if (current_seg && current_seg->use32) {
895             if (current_seg->grp) {
896                 ext->defwrt_type = DEFWRT_GROUP;
897                 ext->defwrt_ptr.grp = current_seg->grp;
898             } else {
899                 ext->defwrt_type = DEFWRT_SEGMENT;
900                 ext->defwrt_ptr.seg = current_seg;
901             }
902         }
903 #endif
904
905         if (is_global == 2) {
906             ext->commonsize = offset;
907             ext->commonelem = 1;        /* default FAR */
908         } else
909             ext->commonsize = 0;
910     } else
911         return;
912
913     /*
914      * Now process the special text, if any, to find default-WRT
915      * specifications and common-variable element-size and near/far
916      * specifications.
917      */
918     while (special && *special) {
919         used_special = true;
920
921         /*
922          * We might have a default-WRT specification.
923          */
924         if (!nasm_strnicmp(special, "wrt", 3)) {
925             char *p;
926             int len;
927             special += 3;
928             special += strspn(special, " \t");
929             p = nasm_strndup(special, len = strcspn(special, ":"));
930             obj_ext_set_defwrt(ext, p);
931             special += len;
932             if (*special && *special != ':')
933                 error(ERR_NONFATAL, "`:' expected in special symbol"
934                       " text for `%s'", ext->name);
935             else if (*special == ':')
936                 special++;
937         }
938
939         /*
940          * The NEAR or FAR keywords specify nearness or
941          * farness. FAR gives default element size 1.
942          */
943         if (!nasm_strnicmp(special, "far", 3)) {
944             if (ext->commonsize)
945                 ext->commonelem = 1;
946             else
947                 error(ERR_NONFATAL,
948                       "`%s': `far' keyword may only be applied"
949                       " to common variables\n", ext->name);
950             special += 3;
951             special += strspn(special, " \t");
952         } else if (!nasm_strnicmp(special, "near", 4)) {
953             if (ext->commonsize)
954                 ext->commonelem = 0;
955             else
956                 error(ERR_NONFATAL,
957                       "`%s': `far' keyword may only be applied"
958                       " to common variables\n", ext->name);
959             special += 4;
960             special += strspn(special, " \t");
961         }
962
963         /*
964          * If it's a common, and anything else remains on the line
965          * before a further colon, evaluate it as an expression and
966          * use that as the element size. Forward references aren't
967          * allowed.
968          */
969         if (*special == ':')
970             special++;
971         else if (*special) {
972             if (ext->commonsize) {
973                 expr *e;
974                 struct tokenval tokval;
975
976                 stdscan_reset();
977                 stdscan_bufptr = special;
978                 tokval.t_type = TOKEN_INVALID;
979                 e = evaluate(stdscan, NULL, &tokval, NULL, 1, error, NULL);
980                 if (e) {
981                     if (!is_simple(e))
982                         error(ERR_NONFATAL, "cannot use relocatable"
983                               " expression as common-variable element size");
984                     else
985                         ext->commonelem = reloc_value(e);
986                 }
987                 special = stdscan_bufptr;
988             } else {
989                 error(ERR_NONFATAL,
990                       "`%s': element-size specifications only"
991                       " apply to common variables", ext->name);
992                 while (*special && *special != ':')
993                     special++;
994                 if (*special == ':')
995                     special++;
996             }
997         }
998     }
999
1000     i = segment / 2;
1001     eb = ebhead;
1002     if (!eb) {
1003         eb = *ebtail = nasm_malloc(sizeof(*eb));
1004         eb->next = NULL;
1005         ebtail = &eb->next;
1006     }
1007     while (i >= EXT_BLKSIZ) {
1008         if (eb && eb->next)
1009             eb = eb->next;
1010         else {
1011             eb = *ebtail = nasm_malloc(sizeof(*eb));
1012             eb->next = NULL;
1013             ebtail = &eb->next;
1014         }
1015         i -= EXT_BLKSIZ;
1016     }
1017     eb->exts[i] = ext;
1018     ext->index = ++externals;
1019
1020     if (special && !used_special)
1021         error(ERR_NONFATAL, "OBJ supports no special symbol features"
1022               " for this symbol type");
1023 }
1024
1025 /* forward declaration */
1026 static void obj_write_fixup(ObjRecord * orp, int bytes,
1027                             int segrel, int32_t seg, int32_t wrt,
1028                             struct Segment *segto);
1029
1030 static void obj_out(int32_t segto, const void *data,
1031                     enum out_type type, uint64_t size,
1032                     int32_t segment, int32_t wrt)
1033 {
1034     const uint8_t *ucdata;
1035     int32_t ldata;
1036     struct Segment *seg;
1037     ObjRecord *orp;
1038
1039     /*
1040      * handle absolute-assembly (structure definitions)
1041      */
1042     if (segto == NO_SEG) {
1043         if (type != OUT_RESERVE)
1044             error(ERR_NONFATAL, "attempt to assemble code in [ABSOLUTE]"
1045                   " space");
1046         return;
1047     }
1048
1049     /*
1050      * If `any_segs' is still false, we must define a default
1051      * segment.
1052      */
1053     if (!any_segs) {
1054         int tempint;            /* ignored */
1055         if (segto != obj_segment("__NASMDEFSEG", 2, &tempint))
1056             error(ERR_PANIC, "strange segment conditions in OBJ driver");
1057     }
1058
1059     /*
1060      * Find the segment we are targetting.
1061      */
1062     for (seg = seghead; seg; seg = seg->next)
1063         if (seg->index == segto)
1064             break;
1065     if (!seg)
1066         error(ERR_PANIC, "code directed to nonexistent segment?");
1067
1068     orp = seg->orp;
1069     orp->parm[0] = seg->currentpos;
1070
1071     if (type == OUT_RAWDATA) {
1072         ucdata = data;
1073         while (size > 0) {
1074             unsigned int len;
1075             orp = obj_check(seg->orp, 1);
1076             len = RECORD_MAX - orp->used;
1077             if (len > size)
1078                 len = size;
1079             memcpy(orp->buf + orp->used, ucdata, len);
1080             orp->committed = orp->used += len;
1081             orp->parm[0] = seg->currentpos += len;
1082             ucdata += len;
1083             size -= len;
1084         }
1085     } else if (type == OUT_ADDRESS || type == OUT_REL2ADR ||
1086                type == OUT_REL4ADR) {
1087         int rsize;
1088
1089         if (segment == NO_SEG && type != OUT_ADDRESS)
1090             error(ERR_NONFATAL, "relative call to absolute address not"
1091                   " supported by OBJ format");
1092         if (segment >= SEG_ABS)
1093             error(ERR_NONFATAL, "far-absolute relocations not supported"
1094                   " by OBJ format");
1095         ldata = *(int64_t *)data;
1096         if (type == OUT_REL2ADR) {
1097             ldata += (size - 2);
1098             size = 2;
1099         } else if (type == OUT_REL4ADR) {
1100             ldata += (size - 4);
1101             size = 4;
1102         }
1103         if (size == 2)
1104             orp = obj_word(orp, ldata);
1105         else
1106             orp = obj_dword(orp, ldata);
1107         rsize = size;
1108         if (segment < SEG_ABS && (segment != NO_SEG && segment % 2) &&
1109             size == 4) {
1110             /*
1111              * This is a 4-byte segment-base relocation such as
1112              * `MOV EAX,SEG foo'. OBJ format can't actually handle
1113              * these, but if the constant term has the 16 low bits
1114              * zero, we can just apply a 2-byte segment-base
1115              * relocation to the low word instead.
1116              */
1117             rsize = 2;
1118             if (ldata & 0xFFFF)
1119                 error(ERR_NONFATAL, "OBJ format cannot handle complex"
1120                       " dword-size segment base references");
1121         }
1122         if (segment != NO_SEG)
1123             obj_write_fixup(orp, rsize,
1124                             (type == OUT_ADDRESS ? 0x4000 : 0),
1125                             segment, wrt, seg);
1126         seg->currentpos += size;
1127     } else if (type == OUT_RESERVE) {
1128         if (orp->committed)
1129             orp = obj_bump(orp);
1130         seg->currentpos += size;
1131     }
1132     obj_commit(orp);
1133 }
1134
1135 static void obj_write_fixup(ObjRecord * orp, int bytes,
1136                             int segrel, int32_t seg, int32_t wrt,
1137                             struct Segment *segto)
1138 {
1139     unsigned locat;
1140     int method;
1141     int base;
1142     int32_t tidx, fidx;
1143     struct Segment *s = NULL;
1144     struct Group *g = NULL;
1145     struct External *e = NULL;
1146     ObjRecord *forp;
1147
1148     if (bytes == 1) {
1149         error(ERR_NONFATAL, "`obj' output driver does not support"
1150               " one-byte relocations");
1151         return;
1152     }
1153
1154     forp = orp->child;
1155     if (forp == NULL) {
1156         orp->child = forp = obj_new();
1157         forp->up = &(orp->child);
1158         /* We should choose between FIXUPP and FIXU32 record type */
1159         /* If we're targeting a 32-bit segment, use a FIXU32 record */
1160         if (segto->use32)
1161             forp->type = FIXU32;
1162         else
1163             forp->type = FIXUPP;
1164     }
1165
1166     if (seg % 2) {
1167         base = true;
1168         locat = FIX_16_SELECTOR;
1169         seg--;
1170         if (bytes != 2)
1171             error(ERR_PANIC, "OBJ: 4-byte segment base fixup got"
1172                   " through sanity check");
1173     } else {
1174         base = false;
1175         locat = (bytes == 2) ? FIX_16_OFFSET : FIX_32_OFFSET;
1176         if (!segrel)
1177             /*
1178              * There is a bug in tlink that makes it process self relative
1179              * fixups incorrectly if the x_size doesn't match the location
1180              * size.
1181              */
1182             forp = obj_force(forp, bytes << 3);
1183     }
1184
1185     forp = obj_rword(forp, locat | segrel | (orp->parm[0] - orp->parm[2]));
1186
1187     tidx = fidx = -1, method = 0;       /* placate optimisers */
1188
1189     /*
1190      * See if we can find the segment ID in our segment list. If
1191      * so, we have a T4 (LSEG) target.
1192      */
1193     for (s = seghead; s; s = s->next)
1194         if (s->index == seg)
1195             break;
1196     if (s)
1197         method = 4, tidx = s->obj_index;
1198     else {
1199         for (g = grphead; g; g = g->next)
1200             if (g->index == seg)
1201                 break;
1202         if (g)
1203             method = 5, tidx = g->obj_index;
1204         else {
1205             int32_t i = seg / 2;
1206             struct ExtBack *eb = ebhead;
1207             while (i >= EXT_BLKSIZ) {
1208                 if (eb)
1209                     eb = eb->next;
1210                 else
1211                     break;
1212                 i -= EXT_BLKSIZ;
1213             }
1214             if (eb)
1215                 method = 6, e = eb->exts[i], tidx = e->index;
1216             else
1217                 error(ERR_PANIC,
1218                       "unrecognised segment value in obj_write_fixup");
1219         }
1220     }
1221
1222     /*
1223      * If no WRT given, assume the natural default, which is method
1224      * F5 unless:
1225      *
1226      * - we are doing an OFFSET fixup for a grouped segment, in
1227      *   which case we require F1 (group).
1228      *
1229      * - we are doing an OFFSET fixup for an external with a
1230      *   default WRT, in which case we must honour the default WRT.
1231      */
1232     if (wrt == NO_SEG) {
1233         if (!base && s && s->grp)
1234             method |= 0x10, fidx = s->grp->obj_index;
1235         else if (!base && e && e->defwrt_type != DEFWRT_NONE) {
1236             if (e->defwrt_type == DEFWRT_SEGMENT)
1237                 method |= 0x00, fidx = e->defwrt_ptr.seg->obj_index;
1238             else if (e->defwrt_type == DEFWRT_GROUP)
1239                 method |= 0x10, fidx = e->defwrt_ptr.grp->obj_index;
1240             else {
1241                 error(ERR_NONFATAL, "default WRT specification for"
1242                       " external `%s' unresolved", e->name);
1243                 method |= 0x50, fidx = -1;      /* got to do _something_ */
1244             }
1245         } else
1246             method |= 0x50, fidx = -1;
1247     } else {
1248         /*
1249          * See if we can find the WRT-segment ID in our segment
1250          * list. If so, we have a F0 (LSEG) frame.
1251          */
1252         for (s = seghead; s; s = s->next)
1253             if (s->index == wrt - 1)
1254                 break;
1255         if (s)
1256             method |= 0x00, fidx = s->obj_index;
1257         else {
1258             for (g = grphead; g; g = g->next)
1259                 if (g->index == wrt - 1)
1260                     break;
1261             if (g)
1262                 method |= 0x10, fidx = g->obj_index;
1263             else {
1264                 int32_t i = wrt / 2;
1265                 struct ExtBack *eb = ebhead;
1266                 while (i >= EXT_BLKSIZ) {
1267                     if (eb)
1268                         eb = eb->next;
1269                     else
1270                         break;
1271                     i -= EXT_BLKSIZ;
1272                 }
1273                 if (eb)
1274                     method |= 0x20, fidx = eb->exts[i]->index;
1275                 else
1276                     error(ERR_PANIC,
1277                           "unrecognised WRT value in obj_write_fixup");
1278             }
1279         }
1280     }
1281
1282     forp = obj_byte(forp, method);
1283     if (fidx != -1)
1284         forp = obj_index(forp, fidx);
1285     forp = obj_index(forp, tidx);
1286     obj_commit(forp);
1287 }
1288
1289 static int32_t obj_segment(char *name, int pass, int *bits)
1290 {
1291     /*
1292      * We call the label manager here to define a name for the new
1293      * segment, and when our _own_ label-definition stub gets
1294      * called in return, it should register the new segment name
1295      * using the pointer it gets passed. That way we save memory,
1296      * by sponging off the label manager.
1297      */
1298 #if defined(DEBUG) && DEBUG>=3
1299     fprintf(stderr, " obj_segment: < %s >, pass=%d, *bits=%d\n",
1300             name, pass, *bits);
1301 #endif
1302     if (!name) {
1303         *bits = 16;
1304         current_seg = NULL;
1305         return first_seg;
1306     } else {
1307         struct Segment *seg;
1308         struct Group *grp;
1309         struct External **extp;
1310         int obj_idx, i, attrs;
1311         bool rn_error;
1312         char *p;
1313
1314         /*
1315          * Look for segment attributes.
1316          */
1317         attrs = 0;
1318         while (*name == '.')
1319             name++;             /* hack, but a documented one */
1320         p = name;
1321         while (*p && !nasm_isspace(*p))
1322             p++;
1323         if (*p) {
1324             *p++ = '\0';
1325             while (*p && nasm_isspace(*p))
1326                 *p++ = '\0';
1327         }
1328         while (*p) {
1329             while (*p && !nasm_isspace(*p))
1330                 p++;
1331             if (*p) {
1332                 *p++ = '\0';
1333                 while (*p && nasm_isspace(*p))
1334                     *p++ = '\0';
1335             }
1336
1337             attrs++;
1338         }
1339
1340         obj_idx = 1;
1341         for (seg = seghead; seg; seg = seg->next) {
1342             obj_idx++;
1343             if (!strcmp(seg->name, name)) {
1344                 if (attrs > 0 && pass == 1)
1345                     error(ERR_WARNING, "segment attributes specified on"
1346                           " redeclaration of segment: ignoring");
1347                 if (seg->use32)
1348                     *bits = 32;
1349                 else
1350                     *bits = 16;
1351                 current_seg = seg;
1352                 return seg->index;
1353             }
1354         }
1355
1356         *segtail = seg = nasm_malloc(sizeof(*seg));
1357         seg->next = NULL;
1358         segtail = &seg->next;
1359         seg->index = (any_segs ? seg_alloc() : first_seg);
1360         seg->obj_index = obj_idx;
1361         seg->grp = NULL;
1362         any_segs = true;
1363         seg->name = NULL;
1364         seg->currentpos = 0;
1365         seg->align = 1;         /* default */
1366         seg->use32 = false;     /* default */
1367         seg->combine = CMB_PUBLIC;      /* default */
1368         seg->segclass = seg->overlay = NULL;
1369         seg->pubhead = NULL;
1370         seg->pubtail = &seg->pubhead;
1371         seg->lochead = NULL;
1372         seg->loctail = &seg->lochead;
1373         seg->orp = obj_new();
1374         seg->orp->up = &(seg->orp);
1375         seg->orp->ori = ori_ledata;
1376         seg->orp->type = LEDATA;
1377         seg->orp->parm[1] = obj_idx;
1378
1379         /*
1380          * Process the segment attributes.
1381          */
1382         p = name;
1383         while (attrs--) {
1384             p += strlen(p);
1385             while (!*p)
1386                 p++;
1387
1388             /*
1389              * `p' contains a segment attribute.
1390              */
1391             if (!nasm_stricmp(p, "private"))
1392                 seg->combine = CMB_PRIVATE;
1393             else if (!nasm_stricmp(p, "public"))
1394                 seg->combine = CMB_PUBLIC;
1395             else if (!nasm_stricmp(p, "common"))
1396                 seg->combine = CMB_COMMON;
1397             else if (!nasm_stricmp(p, "stack"))
1398                 seg->combine = CMB_STACK;
1399             else if (!nasm_stricmp(p, "use16"))
1400                 seg->use32 = false;
1401             else if (!nasm_stricmp(p, "use32"))
1402                 seg->use32 = true;
1403             else if (!nasm_stricmp(p, "flat")) {
1404                 /*
1405                  * This segment is an OS/2 FLAT segment. That means
1406                  * that its default group is group FLAT, even if
1407                  * the group FLAT does not explicitly _contain_ the
1408                  * segment.
1409                  *
1410                  * When we see this, we must create the group
1411                  * `FLAT', containing no segments, if it does not
1412                  * already exist; then we must set the default
1413                  * group of this segment to be the FLAT group.
1414                  */
1415                 struct Group *grp;
1416                 for (grp = grphead; grp; grp = grp->next)
1417                     if (!strcmp(grp->name, "FLAT"))
1418                         break;
1419                 if (!grp) {
1420                     obj_directive(D_GROUP, "FLAT", 1);
1421                     for (grp = grphead; grp; grp = grp->next)
1422                         if (!strcmp(grp->name, "FLAT"))
1423                             break;
1424                     if (!grp)
1425                         error(ERR_PANIC, "failure to define FLAT?!");
1426                 }
1427                 seg->grp = grp;
1428             } else if (!nasm_strnicmp(p, "class=", 6))
1429                 seg->segclass = nasm_strdup(p + 6);
1430             else if (!nasm_strnicmp(p, "overlay=", 8))
1431                 seg->overlay = nasm_strdup(p + 8);
1432             else if (!nasm_strnicmp(p, "align=", 6)) {
1433                 seg->align = readnum(p + 6, &rn_error);
1434                 if (rn_error) {
1435                     seg->align = 1;
1436                     error(ERR_NONFATAL, "segment alignment should be"
1437                           " numeric");
1438                 }
1439                 switch ((int)seg->align) {
1440                 case 1:        /* BYTE */
1441                 case 2:        /* WORD */
1442                 case 4:        /* DWORD */
1443                 case 16:       /* PARA */
1444                 case 256:      /* PAGE */
1445                 case 4096:     /* PharLap extension */
1446                     break;
1447                 case 8:
1448                     error(ERR_WARNING,
1449                           "OBJ format does not support alignment"
1450                           " of 8: rounding up to 16");
1451                     seg->align = 16;
1452                     break;
1453                 case 32:
1454                 case 64:
1455                 case 128:
1456                     error(ERR_WARNING,
1457                           "OBJ format does not support alignment"
1458                           " of %d: rounding up to 256", seg->align);
1459                     seg->align = 256;
1460                     break;
1461                 case 512:
1462                 case 1024:
1463                 case 2048:
1464                     error(ERR_WARNING,
1465                           "OBJ format does not support alignment"
1466                           " of %d: rounding up to 4096", seg->align);
1467                     seg->align = 4096;
1468                     break;
1469                 default:
1470                     error(ERR_NONFATAL, "invalid alignment value %d",
1471                           seg->align);
1472                     seg->align = 1;
1473                     break;
1474                 }
1475             } else if (!nasm_strnicmp(p, "absolute=", 9)) {
1476                 seg->align = SEG_ABS + readnum(p + 9, &rn_error);
1477                 if (rn_error)
1478                     error(ERR_NONFATAL, "argument to `absolute' segment"
1479                           " attribute should be numeric");
1480             }
1481         }
1482
1483         /* We need to know whenever we have at least one 32-bit segment */
1484         obj_use32 |= seg->use32;
1485
1486         obj_seg_needs_update = seg;
1487         if (seg->align >= SEG_ABS)
1488             deflabel(name, NO_SEG, seg->align - SEG_ABS,
1489                      NULL, false, false, &of_obj, error);
1490         else
1491             deflabel(name, seg->index + 1, 0L,
1492                      NULL, false, false, &of_obj, error);
1493         obj_seg_needs_update = NULL;
1494
1495         /*
1496          * See if this segment is defined in any groups.
1497          */
1498         for (grp = grphead; grp; grp = grp->next) {
1499             for (i = grp->nindices; i < grp->nentries; i++) {
1500                 if (!strcmp(grp->segs[i].name, seg->name)) {
1501                     nasm_free(grp->segs[i].name);
1502                     grp->segs[i] = grp->segs[grp->nindices];
1503                     grp->segs[grp->nindices++].index = seg->obj_index;
1504                     if (seg->grp)
1505                         error(ERR_WARNING,
1506                               "segment `%s' is already part of"
1507                               " a group: first one takes precedence",
1508                               seg->name);
1509                     else
1510                         seg->grp = grp;
1511                 }
1512             }
1513         }
1514
1515         /*
1516          * Walk through the list of externals with unresolved
1517          * default-WRT clauses, and resolve any that point at this
1518          * segment.
1519          */
1520         extp = &dws;
1521         while (*extp) {
1522             if ((*extp)->defwrt_type == DEFWRT_STRING &&
1523                 !strcmp((*extp)->defwrt_ptr.string, seg->name)) {
1524                 nasm_free((*extp)->defwrt_ptr.string);
1525                 (*extp)->defwrt_type = DEFWRT_SEGMENT;
1526                 (*extp)->defwrt_ptr.seg = seg;
1527                 *extp = (*extp)->next_dws;
1528             } else
1529                 extp = &(*extp)->next_dws;
1530         }
1531
1532         if (seg->use32)
1533             *bits = 32;
1534         else
1535             *bits = 16;
1536         current_seg = seg;
1537         return seg->index;
1538     }
1539 }
1540
1541 static int obj_directive(enum directives directive, char *value, int pass)
1542 {
1543     switch (directive) {
1544     case D_GROUP:
1545     {
1546         char *p, *q, *v;
1547         if (pass == 1) {
1548             struct Group *grp;
1549             struct Segment *seg;
1550             struct External **extp;
1551             int obj_idx;
1552
1553             q = value;
1554             while (*q == '.')
1555                 q++;            /* hack, but a documented one */
1556             v = q;
1557             while (*q && !nasm_isspace(*q))
1558                 q++;
1559             if (nasm_isspace(*q)) {
1560                 *q++ = '\0';
1561                 while (*q && nasm_isspace(*q))
1562                     q++;
1563             }
1564             /*
1565              * Here we used to sanity-check the group directive to
1566              * ensure nobody tried to declare a group containing no
1567              * segments. However, OS/2 does this as standard
1568              * practice, so the sanity check has been removed.
1569              *
1570              * if (!*q) {
1571              *     error(ERR_NONFATAL,"GROUP directive contains no segments");
1572              *     return 1;
1573              * }
1574              */
1575
1576             obj_idx = 1;
1577             for (grp = grphead; grp; grp = grp->next) {
1578                 obj_idx++;
1579                 if (!strcmp(grp->name, v)) {
1580                     error(ERR_NONFATAL, "group `%s' defined twice", v);
1581                     return 1;
1582                 }
1583             }
1584
1585             *grptail = grp = nasm_malloc(sizeof(*grp));
1586             grp->next = NULL;
1587             grptail = &grp->next;
1588             grp->index = seg_alloc();
1589             grp->obj_index = obj_idx;
1590             grp->nindices = grp->nentries = 0;
1591             grp->name = NULL;
1592
1593             obj_grp_needs_update = grp;
1594             deflabel(v, grp->index + 1, 0L,
1595                      NULL, false, false, &of_obj, error);
1596             obj_grp_needs_update = NULL;
1597
1598             while (*q) {
1599                 p = q;
1600                 while (*q && !nasm_isspace(*q))
1601                     q++;
1602                 if (nasm_isspace(*q)) {
1603                     *q++ = '\0';
1604                     while (*q && nasm_isspace(*q))
1605                         q++;
1606                 }
1607                 /*
1608                  * Now p contains a segment name. Find it.
1609                  */
1610                 for (seg = seghead; seg; seg = seg->next)
1611                     if (!strcmp(seg->name, p))
1612                         break;
1613                 if (seg) {
1614                     /*
1615                      * We have a segment index. Shift a name entry
1616                      * to the end of the array to make room.
1617                      */
1618                     grp->segs[grp->nentries++] = grp->segs[grp->nindices];
1619                     grp->segs[grp->nindices++].index = seg->obj_index;
1620                     if (seg->grp)
1621                         error(ERR_WARNING,
1622                               "segment `%s' is already part of"
1623                               " a group: first one takes precedence",
1624                               seg->name);
1625                     else
1626                         seg->grp = grp;
1627                 } else {
1628                     /*
1629                      * We have an as-yet undefined segment.
1630                      * Remember its name, for later.
1631                      */
1632                     grp->segs[grp->nentries++].name = nasm_strdup(p);
1633                 }
1634             }
1635
1636             /*
1637              * Walk through the list of externals with unresolved
1638              * default-WRT clauses, and resolve any that point at
1639              * this group.
1640              */
1641             extp = &dws;
1642             while (*extp) {
1643                 if ((*extp)->defwrt_type == DEFWRT_STRING &&
1644                     !strcmp((*extp)->defwrt_ptr.string, grp->name)) {
1645                     nasm_free((*extp)->defwrt_ptr.string);
1646                     (*extp)->defwrt_type = DEFWRT_GROUP;
1647                     (*extp)->defwrt_ptr.grp = grp;
1648                     *extp = (*extp)->next_dws;
1649                 } else
1650                     extp = &(*extp)->next_dws;
1651             }
1652         }
1653         return 1;
1654     }
1655     case D_UPPERCASE:
1656         obj_uppercase = true;
1657         return 1;
1658
1659     case D_IMPORT:
1660     {
1661         char *q, *extname, *libname, *impname;
1662
1663         if (pass == 2)
1664             return 1;           /* ignore in pass two */
1665         extname = q = value;
1666         while (*q && !nasm_isspace(*q))
1667             q++;
1668         if (nasm_isspace(*q)) {
1669             *q++ = '\0';
1670             while (*q && nasm_isspace(*q))
1671                 q++;
1672         }
1673
1674         libname = q;
1675         while (*q && !nasm_isspace(*q))
1676             q++;
1677         if (nasm_isspace(*q)) {
1678             *q++ = '\0';
1679             while (*q && nasm_isspace(*q))
1680                 q++;
1681         }
1682
1683         impname = q;
1684
1685         if (!*extname || !*libname)
1686             error(ERR_NONFATAL, "`import' directive requires symbol name"
1687                   " and library name");
1688         else {
1689             struct ImpDef *imp;
1690             bool err = false;
1691
1692             imp = *imptail = nasm_malloc(sizeof(struct ImpDef));
1693             imptail = &imp->next;
1694             imp->next = NULL;
1695             imp->extname = nasm_strdup(extname);
1696             imp->libname = nasm_strdup(libname);
1697             imp->impindex = readnum(impname, &err);
1698             if (!*impname || err)
1699                 imp->impname = nasm_strdup(impname);
1700             else
1701                 imp->impname = NULL;
1702         }
1703
1704         return 1;
1705     }
1706     case D_EXPORT:
1707     {
1708         char *q, *extname, *intname, *v;
1709         struct ExpDef *export;
1710         int flags = 0;
1711         unsigned int ordinal = 0;
1712
1713         if (pass == 2)
1714             return 1;           /* ignore in pass two */
1715         intname = q = value;
1716         while (*q && !nasm_isspace(*q))
1717             q++;
1718         if (nasm_isspace(*q)) {
1719             *q++ = '\0';
1720             while (*q && nasm_isspace(*q))
1721                 q++;
1722         }
1723
1724         extname = q;
1725         while (*q && !nasm_isspace(*q))
1726             q++;
1727         if (nasm_isspace(*q)) {
1728             *q++ = '\0';
1729             while (*q && nasm_isspace(*q))
1730                 q++;
1731         }
1732
1733         if (!*intname) {
1734             error(ERR_NONFATAL, "`export' directive requires export name");
1735             return 1;
1736         }
1737         if (!*extname) {
1738             extname = intname;
1739             intname = "";
1740         }
1741         while (*q) {
1742             v = q;
1743             while (*q && !nasm_isspace(*q))
1744                 q++;
1745             if (nasm_isspace(*q)) {
1746                 *q++ = '\0';
1747                 while (*q && nasm_isspace(*q))
1748                     q++;
1749             }
1750             if (!nasm_stricmp(v, "resident"))
1751                 flags |= EXPDEF_FLAG_RESIDENT;
1752             else if (!nasm_stricmp(v, "nodata"))
1753                 flags |= EXPDEF_FLAG_NODATA;
1754             else if (!nasm_strnicmp(v, "parm=", 5)) {
1755                 bool err = false;
1756                 flags |= EXPDEF_MASK_PARMCNT & readnum(v + 5, &err);
1757                 if (err) {
1758                     error(ERR_NONFATAL,
1759                           "value `%s' for `parm' is non-numeric", v + 5);
1760                     return 1;
1761                 }
1762             } else {
1763                 bool err = false;
1764                 ordinal = readnum(v, &err);
1765                 if (err) {
1766                     error(ERR_NONFATAL,
1767                           "unrecognised export qualifier `%s'", v);
1768                     return 1;
1769                 }
1770                 flags |= EXPDEF_FLAG_ORDINAL;
1771             }
1772         }
1773
1774         export = *exptail = nasm_malloc(sizeof(struct ExpDef));
1775         exptail = &export->next;
1776         export->next = NULL;
1777         export->extname = nasm_strdup(extname);
1778         export->intname = nasm_strdup(intname);
1779         export->ordinal = ordinal;
1780         export->flags = flags;
1781
1782         return 1;
1783     }
1784     default:
1785         return 0;
1786     }
1787 }
1788
1789 static int32_t obj_segbase(int32_t segment)
1790 {
1791     struct Segment *seg;
1792
1793     /*
1794      * Find the segment in our list.
1795      */
1796     for (seg = seghead; seg; seg = seg->next)
1797         if (seg->index == segment - 1)
1798             break;
1799
1800     if (!seg) {
1801         /*
1802          * Might be an external with a default WRT.
1803          */
1804         int32_t i = segment / 2;
1805         struct ExtBack *eb = ebhead;
1806         struct External *e;
1807
1808         while (i >= EXT_BLKSIZ) {
1809             if (eb)
1810                 eb = eb->next;
1811             else
1812                 break;
1813             i -= EXT_BLKSIZ;
1814         }
1815         if (eb) {
1816             e = eb->exts[i];
1817             if (!e) {
1818                 nasm_assert(pass0 == 0);
1819                 /* Not available - can happen during optimization */
1820                 return NO_SEG;
1821             }
1822
1823             switch (e->defwrt_type) {
1824             case DEFWRT_NONE:
1825                 return segment; /* fine */
1826             case DEFWRT_SEGMENT:
1827                 return e->defwrt_ptr.seg->index + 1;
1828             case DEFWRT_GROUP:
1829                 return e->defwrt_ptr.grp->index + 1;
1830             default:
1831                 return NO_SEG;  /* can't tell what it is */
1832             }
1833         }
1834
1835         return segment;         /* not one of ours - leave it alone */
1836     }
1837
1838     if (seg->align >= SEG_ABS)
1839         return seg->align;      /* absolute segment */
1840     if (seg->grp)
1841         return seg->grp->index + 1;     /* grouped segment */
1842
1843     return segment;             /* no special treatment */
1844 }
1845
1846 static void obj_filename(char *inname, char *outname, efunc lerror)
1847 {
1848     strcpy(obj_infile, inname);
1849     standard_extension(inname, outname, ".obj", lerror);
1850 }
1851
1852 static void obj_write_file(int debuginfo)
1853 {
1854     struct Segment *seg, *entry_seg_ptr = 0;
1855     struct FileName *fn;
1856     struct LineNumber *ln;
1857     struct Group *grp;
1858     struct Public *pub, *loc;
1859     struct External *ext;
1860     struct ImpDef *imp;
1861     struct ExpDef *export;
1862     int lname_idx;
1863     ObjRecord *orp;
1864
1865     /*
1866      * Write the THEADR module header.
1867      */
1868     orp = obj_new();
1869     orp->type = THEADR;
1870     obj_name(orp, obj_infile);
1871     obj_emit2(orp);
1872
1873     /*
1874      * Write the NASM boast comment.
1875      */
1876     orp->type = COMENT;
1877     obj_rword(orp, 0);          /* comment type zero */
1878     obj_name(orp, nasm_comment);
1879     obj_emit2(orp);
1880
1881     orp->type = COMENT;
1882     /*
1883      * Write the IMPDEF records, if any.
1884      */
1885     for (imp = imphead; imp; imp = imp->next) {
1886         obj_rword(orp, 0xA0);   /* comment class A0 */
1887         obj_byte(orp, 1);       /* subfunction 1: IMPDEF */
1888         if (imp->impname)
1889             obj_byte(orp, 0);   /* import by name */
1890         else
1891             obj_byte(orp, 1);   /* import by ordinal */
1892         obj_name(orp, imp->extname);
1893         obj_name(orp, imp->libname);
1894         if (imp->impname)
1895             obj_name(orp, imp->impname);
1896         else
1897             obj_word(orp, imp->impindex);
1898         obj_emit2(orp);
1899     }
1900
1901     /*
1902      * Write the EXPDEF records, if any.
1903      */
1904     for (export = exphead; export; export = export->next) {
1905         obj_rword(orp, 0xA0);   /* comment class A0 */
1906         obj_byte(orp, 2);       /* subfunction 2: EXPDEF */
1907         obj_byte(orp, export->flags);
1908         obj_name(orp, export->extname);
1909         obj_name(orp, export->intname);
1910         if (export->flags & EXPDEF_FLAG_ORDINAL)
1911             obj_word(orp, export->ordinal);
1912         obj_emit2(orp);
1913     }
1914
1915     /* we're using extended OMF if we put in debug info */
1916     if (debuginfo) {
1917         orp->type = COMENT;
1918         obj_byte(orp, 0x40);
1919         obj_byte(orp, dEXTENDED);
1920         obj_emit2(orp);
1921     }
1922
1923     /*
1924      * Write the first LNAMES record, containing LNAME one, which
1925      * is null. Also initialize the LNAME counter.
1926      */
1927     orp->type = LNAMES;
1928     obj_byte(orp, 0);
1929     lname_idx = 1;
1930     /*
1931      * Write some LNAMES for the segment names
1932      */
1933     for (seg = seghead; seg; seg = seg->next) {
1934         orp = obj_name(orp, seg->name);
1935         if (seg->segclass)
1936             orp = obj_name(orp, seg->segclass);
1937         if (seg->overlay)
1938             orp = obj_name(orp, seg->overlay);
1939         obj_commit(orp);
1940     }
1941     /*
1942      * Write some LNAMES for the group names
1943      */
1944     for (grp = grphead; grp; grp = grp->next) {
1945         orp = obj_name(orp, grp->name);
1946         obj_commit(orp);
1947     }
1948     obj_emit(orp);
1949
1950     /*
1951      * Write the SEGDEF records.
1952      */
1953     orp->type = SEGDEF;
1954     for (seg = seghead; seg; seg = seg->next) {
1955         int acbp;
1956         uint32_t seglen = seg->currentpos;
1957
1958         acbp = (seg->combine << 2);     /* C field */
1959
1960         if (seg->use32)
1961             acbp |= 0x01;       /* P bit is Use32 flag */
1962         else if (seglen == 0x10000L) {
1963             seglen = 0;         /* This special case may be needed for old linkers */
1964             acbp |= 0x02;       /* B bit */
1965         }
1966
1967         /* A field */
1968         if (seg->align >= SEG_ABS)
1969             /* acbp |= 0x00 */ ;
1970         else if (seg->align >= 4096) {
1971             if (seg->align > 4096)
1972                 error(ERR_NONFATAL, "segment `%s' requires more alignment"
1973                       " than OBJ format supports", seg->name);
1974             acbp |= 0xC0;       /* PharLap extension */
1975         } else if (seg->align >= 256) {
1976             acbp |= 0x80;
1977         } else if (seg->align >= 16) {
1978             acbp |= 0x60;
1979         } else if (seg->align >= 4) {
1980             acbp |= 0xA0;
1981         } else if (seg->align >= 2) {
1982             acbp |= 0x40;
1983         } else
1984             acbp |= 0x20;
1985
1986         obj_byte(orp, acbp);
1987         if (seg->align & SEG_ABS) {
1988             obj_x(orp, seg->align - SEG_ABS);   /* Frame */
1989             obj_byte(orp, 0);   /* Offset */
1990         }
1991         obj_x(orp, seglen);
1992         obj_index(orp, ++lname_idx);
1993         obj_index(orp, seg->segclass ? ++lname_idx : 1);
1994         obj_index(orp, seg->overlay ? ++lname_idx : 1);
1995         obj_emit2(orp);
1996     }
1997
1998     /*
1999      * Write the GRPDEF records.
2000      */
2001     orp->type = GRPDEF;
2002     for (grp = grphead; grp; grp = grp->next) {
2003         int i;
2004
2005         if (grp->nindices != grp->nentries) {
2006             for (i = grp->nindices; i < grp->nentries; i++) {
2007                 error(ERR_NONFATAL, "group `%s' contains undefined segment"
2008                       " `%s'", grp->name, grp->segs[i].name);
2009                 nasm_free(grp->segs[i].name);
2010                 grp->segs[i].name = NULL;
2011             }
2012         }
2013         obj_index(orp, ++lname_idx);
2014         for (i = 0; i < grp->nindices; i++) {
2015             obj_byte(orp, 0xFF);
2016             obj_index(orp, grp->segs[i].index);
2017         }
2018         obj_emit2(orp);
2019     }
2020
2021     /*
2022      * Write the PUBDEF records: first the ones in the segments,
2023      * then the far-absolutes.
2024      */
2025     orp->type = PUBDEF;
2026     orp->ori = ori_pubdef;
2027     for (seg = seghead; seg; seg = seg->next) {
2028         orp->parm[0] = seg->grp ? seg->grp->obj_index : 0;
2029         orp->parm[1] = seg->obj_index;
2030         for (pub = seg->pubhead; pub; pub = pub->next) {
2031             orp = obj_name(orp, pub->name);
2032             orp = obj_x(orp, pub->offset);
2033             orp = obj_byte(orp, 0);     /* type index */
2034             obj_commit(orp);
2035         }
2036         obj_emit(orp);
2037     }
2038     orp->parm[0] = 0;
2039     orp->parm[1] = 0;
2040     for (pub = fpubhead; pub; pub = pub->next) {        /* pub-crawl :-) */
2041         if (orp->parm[2] != (uint32_t)pub->segment) {
2042             obj_emit(orp);
2043             orp->parm[2] = pub->segment;
2044         }
2045         orp = obj_name(orp, pub->name);
2046         orp = obj_x(orp, pub->offset);
2047         orp = obj_byte(orp, 0); /* type index */
2048         obj_commit(orp);
2049     }
2050     obj_emit(orp);
2051
2052     /*
2053      * Write the EXTDEF and COMDEF records, in order.
2054      */
2055     orp->ori = ori_null;
2056     for (ext = exthead; ext; ext = ext->next) {
2057         if (ext->commonsize == 0) {
2058             if (orp->type != EXTDEF) {
2059                 obj_emit(orp);
2060                 orp->type = EXTDEF;
2061             }
2062             orp = obj_name(orp, ext->name);
2063             orp = obj_index(orp, 0);
2064         } else {
2065             if (orp->type != COMDEF) {
2066                 obj_emit(orp);
2067                 orp->type = COMDEF;
2068             }
2069             orp = obj_name(orp, ext->name);
2070             orp = obj_index(orp, 0);
2071             if (ext->commonelem) {
2072                 orp = obj_byte(orp, 0x61);      /* far communal */
2073                 orp = obj_value(orp, (ext->commonsize / ext->commonelem));
2074                 orp = obj_value(orp, ext->commonelem);
2075             } else {
2076                 orp = obj_byte(orp, 0x62);      /* near communal */
2077                 orp = obj_value(orp, ext->commonsize);
2078             }
2079         }
2080         obj_commit(orp);
2081     }
2082     obj_emit(orp);
2083
2084     /*
2085      * Write a COMENT record stating that the linker's first pass
2086      * may stop processing at this point. Exception is if our
2087      * MODEND record specifies a start point, in which case,
2088      * according to some variants of the documentation, this COMENT
2089      * should be omitted. So we'll omit it just in case.
2090      * But, TASM puts it in all the time so if we are using
2091      * TASM debug stuff we are putting it in
2092      */
2093     if (debuginfo || obj_entry_seg == NO_SEG) {
2094         orp->type = COMENT;
2095         obj_byte(orp, 0x40);
2096         obj_byte(orp, dLINKPASS);
2097         obj_byte(orp, 1);
2098         obj_emit2(orp);
2099     }
2100
2101     /*
2102      * 1) put out the compiler type
2103      * 2) Put out the type info.  The only type we are using is near label #19
2104      */
2105     if (debuginfo) {
2106         int i;
2107         struct Array *arrtmp = arrhead;
2108         orp->type = COMENT;
2109         obj_byte(orp, 0x40);
2110         obj_byte(orp, dCOMPDEF);
2111         obj_byte(orp, 4);
2112         obj_byte(orp, 0);
2113         obj_emit2(orp);
2114
2115         obj_byte(orp, 0x40);
2116         obj_byte(orp, dTYPEDEF);
2117         obj_word(orp, 0x18);    /* type # for linking */
2118         obj_word(orp, 6);       /* size of type */
2119         obj_byte(orp, 0x2a);    /* absolute type for debugging */
2120         obj_emit2(orp);
2121         obj_byte(orp, 0x40);
2122         obj_byte(orp, dTYPEDEF);
2123         obj_word(orp, 0x19);    /* type # for linking */
2124         obj_word(orp, 0);       /* size of type */
2125         obj_byte(orp, 0x24);    /* absolute type for debugging */
2126         obj_byte(orp, 0);       /* near/far specifier */
2127         obj_emit2(orp);
2128         obj_byte(orp, 0x40);
2129         obj_byte(orp, dTYPEDEF);
2130         obj_word(orp, 0x1A);    /* type # for linking */
2131         obj_word(orp, 0);       /* size of type */
2132         obj_byte(orp, 0x24);    /* absolute type for debugging */
2133         obj_byte(orp, 1);       /* near/far specifier */
2134         obj_emit2(orp);
2135         obj_byte(orp, 0x40);
2136         obj_byte(orp, dTYPEDEF);
2137         obj_word(orp, 0x1b);    /* type # for linking */
2138         obj_word(orp, 0);       /* size of type */
2139         obj_byte(orp, 0x23);    /* absolute type for debugging */
2140         obj_byte(orp, 0);
2141         obj_byte(orp, 0);
2142         obj_byte(orp, 0);
2143         obj_emit2(orp);
2144         obj_byte(orp, 0x40);
2145         obj_byte(orp, dTYPEDEF);
2146         obj_word(orp, 0x1c);    /* type # for linking */
2147         obj_word(orp, 0);       /* size of type */
2148         obj_byte(orp, 0x23);    /* absolute type for debugging */
2149         obj_byte(orp, 0);
2150         obj_byte(orp, 4);
2151         obj_byte(orp, 0);
2152         obj_emit2(orp);
2153         obj_byte(orp, 0x40);
2154         obj_byte(orp, dTYPEDEF);
2155         obj_word(orp, 0x1d);    /* type # for linking */
2156         obj_word(orp, 0);       /* size of type */
2157         obj_byte(orp, 0x23);    /* absolute type for debugging */
2158         obj_byte(orp, 0);
2159         obj_byte(orp, 1);
2160         obj_byte(orp, 0);
2161         obj_emit2(orp);
2162         obj_byte(orp, 0x40);
2163         obj_byte(orp, dTYPEDEF);
2164         obj_word(orp, 0x1e);    /* type # for linking */
2165         obj_word(orp, 0);       /* size of type */
2166         obj_byte(orp, 0x23);    /* absolute type for debugging */
2167         obj_byte(orp, 0);
2168         obj_byte(orp, 5);
2169         obj_byte(orp, 0);
2170         obj_emit2(orp);
2171
2172         /* put out the array types */
2173         for (i = ARRAYBOT; i < arrindex; i++) {
2174             obj_byte(orp, 0x40);
2175             obj_byte(orp, dTYPEDEF);
2176             obj_word(orp, i);   /* type # for linking */
2177             obj_word(orp, arrtmp->size);        /* size of type */
2178             obj_byte(orp, 0x1A);        /* absolute type for debugging (array) */
2179             obj_byte(orp, arrtmp->basetype);    /* base type */
2180             obj_emit2(orp);
2181             arrtmp = arrtmp->next;
2182         }
2183     }
2184     /*
2185      * write out line number info with a LINNUM record
2186      * switch records when we switch segments, and output the
2187      * file in a pseudo-TASM fashion.  The record switch is naive; that
2188      * is that one file may have many records for the same segment
2189      * if there are lots of segment switches
2190      */
2191     if (fnhead && debuginfo) {
2192         seg = fnhead->lnhead->segment;
2193
2194         for (fn = fnhead; fn; fn = fn->next) {
2195             /* write out current file name */
2196             orp->type = COMENT;
2197             orp->ori = ori_null;
2198             obj_byte(orp, 0x40);
2199             obj_byte(orp, dFILNAME);
2200             obj_byte(orp, 0);
2201             obj_name(orp, fn->name);
2202             obj_dword(orp, 0);
2203             obj_emit2(orp);
2204
2205             /* write out line numbers this file */
2206
2207             orp->type = LINNUM;
2208             orp->ori = ori_linnum;
2209             for (ln = fn->lnhead; ln; ln = ln->next) {
2210                 if (seg != ln->segment) {
2211                     /* if we get here have to flush the buffer and start
2212                      * a new record for a new segment
2213                      */
2214                     seg = ln->segment;
2215                     obj_emit(orp);
2216                 }
2217                 orp->parm[0] = seg->grp ? seg->grp->obj_index : 0;
2218                 orp->parm[1] = seg->obj_index;
2219                 orp = obj_word(orp, ln->lineno);
2220                 orp = obj_x(orp, ln->offset);
2221                 obj_commit(orp);
2222             }
2223             obj_emit(orp);
2224         }
2225     }
2226     /*
2227      * we are going to locate the entry point segment now
2228      * rather than wait until the MODEND record, because,
2229      * then we can output a special symbol to tell where the
2230      * entry point is.
2231      *
2232      */
2233     if (obj_entry_seg != NO_SEG) {
2234         for (seg = seghead; seg; seg = seg->next) {
2235             if (seg->index == obj_entry_seg) {
2236                 entry_seg_ptr = seg;
2237                 break;
2238             }
2239         }
2240         if (!seg)
2241             error(ERR_NONFATAL, "entry point is not in this module");
2242     }
2243
2244     /*
2245      * get ready to put out symbol records
2246      */
2247     orp->type = COMENT;
2248     orp->ori = ori_local;
2249
2250     /*
2251      * put out a symbol for the entry point
2252      * no dots in this symbol, because, borland does
2253      * not (officially) support dots in label names
2254      * and I don't know what various versions of TLINK will do
2255      */
2256     if (debuginfo && obj_entry_seg != NO_SEG) {
2257         orp = obj_name(orp, "start_of_program");
2258         orp = obj_word(orp, 0x19);      /* type: near label */
2259         orp = obj_index(orp, seg->grp ? seg->grp->obj_index : 0);
2260         orp = obj_index(orp, seg->obj_index);
2261         orp = obj_x(orp, obj_entry_ofs);
2262         obj_commit(orp);
2263     }
2264
2265     /*
2266      * put out the local labels
2267      */
2268     for (seg = seghead; seg && debuginfo; seg = seg->next) {
2269         /* labels this seg */
2270         for (loc = seg->lochead; loc; loc = loc->next) {
2271             orp = obj_name(orp, loc->name);
2272             orp = obj_word(orp, loc->type);
2273             orp = obj_index(orp, seg->grp ? seg->grp->obj_index : 0);
2274             orp = obj_index(orp, seg->obj_index);
2275             orp = obj_x(orp, loc->offset);
2276             obj_commit(orp);
2277         }
2278     }
2279     if (orp->used)
2280         obj_emit(orp);
2281
2282     /*
2283      * Write the LEDATA/FIXUPP pairs.
2284      */
2285     for (seg = seghead; seg; seg = seg->next) {
2286         obj_emit(seg->orp);
2287         nasm_free(seg->orp);
2288     }
2289
2290     /*
2291      * Write the MODEND module end marker.
2292      */
2293     orp->type = obj_use32 ? MODE32 : MODEND;
2294     orp->ori = ori_null;
2295     if (entry_seg_ptr) {
2296         orp->type = entry_seg_ptr->use32 ? MODE32 : MODEND;
2297         obj_byte(orp, 0xC1);
2298         seg = entry_seg_ptr;
2299         if (seg->grp) {
2300             obj_byte(orp, 0x10);
2301             obj_index(orp, seg->grp->obj_index);
2302         } else {
2303             /*
2304              * the below changed to prevent TLINK crashing.
2305              * Previous more efficient version read:
2306              *
2307              *  obj_byte (orp, 0x50);
2308              */
2309             obj_byte(orp, 0x00);
2310             obj_index(orp, seg->obj_index);
2311         }
2312         obj_index(orp, seg->obj_index);
2313         obj_x(orp, obj_entry_ofs);
2314     } else
2315         obj_byte(orp, 0);
2316     obj_emit2(orp);
2317     nasm_free(orp);
2318 }
2319
2320 static void obj_fwrite(ObjRecord * orp)
2321 {
2322     unsigned int cksum, len;
2323     uint8_t *ptr;
2324
2325     cksum = orp->type;
2326     if (orp->x_size == 32)
2327         cksum |= 1;
2328     fputc(cksum, ofp);
2329     len = orp->committed + 1;
2330     cksum += (len & 0xFF) + ((len >> 8) & 0xFF);
2331     fwriteint16_t(len, ofp);
2332     fwrite(orp->buf, 1, len - 1, ofp);
2333     for (ptr = orp->buf; --len; ptr++)
2334         cksum += *ptr;
2335     fputc((-cksum) & 0xFF, ofp);
2336 }
2337
2338 extern macros_t obj_stdmac[];
2339
2340 void dbgbi_init(struct ofmt *of, void *id, FILE * fp, efunc error)
2341 {
2342     (void)of;
2343     (void)id;
2344     (void)fp;
2345     (void)error;
2346
2347     fnhead = NULL;
2348     fntail = &fnhead;
2349     arrindex = ARRAYBOT;
2350     arrhead = NULL;
2351     arrtail = &arrhead;
2352 }
2353 static void dbgbi_cleanup(void)
2354 {
2355     struct Segment *segtmp;
2356     while (fnhead) {
2357         struct FileName *fntemp = fnhead;
2358         while (fnhead->lnhead) {
2359             struct LineNumber *lntemp = fnhead->lnhead;
2360             fnhead->lnhead = lntemp->next;
2361             nasm_free(lntemp);
2362         }
2363         fnhead = fnhead->next;
2364         nasm_free(fntemp->name);
2365         nasm_free(fntemp);
2366     }
2367     for (segtmp = seghead; segtmp; segtmp = segtmp->next) {
2368         while (segtmp->lochead) {
2369             struct Public *loctmp = segtmp->lochead;
2370             segtmp->lochead = loctmp->next;
2371             nasm_free(loctmp->name);
2372             nasm_free(loctmp);
2373         }
2374     }
2375     while (arrhead) {
2376         struct Array *arrtmp = arrhead;
2377         arrhead = arrhead->next;
2378         nasm_free(arrtmp);
2379     }
2380 }
2381
2382 static void dbgbi_linnum(const char *lnfname, int32_t lineno, int32_t segto)
2383 {
2384     struct FileName *fn;
2385     struct LineNumber *ln;
2386     struct Segment *seg;
2387
2388     if (segto == NO_SEG)
2389         return;
2390
2391     /*
2392      * If `any_segs' is still false, we must define a default
2393      * segment.
2394      */
2395     if (!any_segs) {
2396         int tempint;            /* ignored */
2397         if (segto != obj_segment("__NASMDEFSEG", 2, &tempint))
2398             error(ERR_PANIC, "strange segment conditions in OBJ driver");
2399     }
2400
2401     /*
2402      * Find the segment we are targetting.
2403      */
2404     for (seg = seghead; seg; seg = seg->next)
2405         if (seg->index == segto)
2406             break;
2407     if (!seg)
2408         error(ERR_PANIC, "lineno directed to nonexistent segment?");
2409
2410 /*    for (fn = fnhead; fn; fn = fnhead->next) */
2411     for (fn = fnhead; fn; fn = fn->next)        /* fbk - Austin Lunnen - John Fine */
2412         if (!nasm_stricmp(lnfname, fn->name))
2413             break;
2414     if (!fn) {
2415         fn = nasm_malloc(sizeof(*fn));
2416         fn->name = nasm_malloc(strlen(lnfname) + 1);
2417         strcpy(fn->name, lnfname);
2418         fn->lnhead = NULL;
2419         fn->lntail = &fn->lnhead;
2420         fn->next = NULL;
2421         *fntail = fn;
2422         fntail = &fn->next;
2423     }
2424     ln = nasm_malloc(sizeof(*ln));
2425     ln->segment = seg;
2426     ln->offset = seg->currentpos;
2427     ln->lineno = lineno;
2428     ln->next = NULL;
2429     *fn->lntail = ln;
2430     fn->lntail = &ln->next;
2431
2432 }
2433 static void dbgbi_deflabel(char *name, int32_t segment,
2434                            int64_t offset, int is_global, char *special)
2435 {
2436     struct Segment *seg;
2437
2438     (void)special;
2439
2440     /*
2441      * If it's a special-retry from pass two, discard it.
2442      */
2443     if (is_global == 3)
2444         return;
2445
2446     /*
2447      * First check for the double-period, signifying something
2448      * unusual.
2449      */
2450     if (name[0] == '.' && name[1] == '.' && name[2] != '@') {
2451         return;
2452     }
2453
2454     /*
2455      * Case (i):
2456      */
2457     if (obj_seg_needs_update) {
2458         return;
2459     } else if (obj_grp_needs_update) {
2460         return;
2461     }
2462     if (segment < SEG_ABS && segment != NO_SEG && segment % 2)
2463         return;
2464
2465     if (segment >= SEG_ABS || segment == NO_SEG) {
2466         return;
2467     }
2468
2469     /*
2470      * If `any_segs' is still false, we might need to define a
2471      * default segment, if they're trying to declare a label in
2472      * `first_seg'.  But the label should exist due to a prior
2473      * call to obj_deflabel so we can skip that.
2474      */
2475
2476     for (seg = seghead; seg; seg = seg->next)
2477         if (seg->index == segment) {
2478             struct Public *loc = nasm_malloc(sizeof(*loc));
2479             /*
2480              * Case (ii). Maybe MODPUB someday?
2481              */
2482             last_defined = *seg->loctail = loc;
2483             seg->loctail = &loc->next;
2484             loc->next = NULL;
2485             loc->name = nasm_strdup(name);
2486             loc->offset = offset;
2487         }
2488 }
2489 static void dbgbi_typevalue(int32_t type)
2490 {
2491     int vsize;
2492     int elem = TYM_ELEMENTS(type);
2493     type = TYM_TYPE(type);
2494
2495     if (!last_defined)
2496         return;
2497
2498     switch (type) {
2499     case TY_BYTE:
2500         last_defined->type = 8; /* uint8_t */
2501         vsize = 1;
2502         break;
2503     case TY_WORD:
2504         last_defined->type = 10;        /* unsigned word */
2505         vsize = 2;
2506         break;
2507     case TY_DWORD:
2508         last_defined->type = 12;        /* unsigned dword */
2509         vsize = 4;
2510         break;
2511     case TY_FLOAT:
2512         last_defined->type = 14;        /* float */
2513         vsize = 4;
2514         break;
2515     case TY_QWORD:
2516         last_defined->type = 15;        /* qword */
2517         vsize = 8;
2518         break;
2519     case TY_TBYTE:
2520         last_defined->type = 16;        /* TBYTE */
2521         vsize = 10;
2522         break;
2523     default:
2524         last_defined->type = 0x19;      /*label */
2525         vsize = 0;
2526         break;
2527     }
2528
2529     if (elem > 1) {
2530         struct Array *arrtmp = nasm_malloc(sizeof(*arrtmp));
2531         int vtype = last_defined->type;
2532         arrtmp->size = vsize * elem;
2533         arrtmp->basetype = vtype;
2534         arrtmp->next = NULL;
2535         last_defined->type = arrindex++;
2536         *arrtail = arrtmp;
2537         arrtail = &(arrtmp->next);
2538     }
2539     last_defined = NULL;
2540 }
2541 static void dbgbi_output(int output_type, void *param)
2542 {
2543     (void)output_type;
2544     (void)param;
2545 }
2546 static struct dfmt borland_debug_form = {
2547     "Borland Debug Records",
2548     "borland",
2549     dbgbi_init,
2550     dbgbi_linnum,
2551     dbgbi_deflabel,
2552     null_debug_routine,
2553     dbgbi_typevalue,
2554     dbgbi_output,
2555     dbgbi_cleanup,
2556 };
2557
2558 static struct dfmt *borland_debug_arr[3] = {
2559     &borland_debug_form,
2560     &null_debug_form,
2561     NULL
2562 };
2563
2564 struct ofmt of_obj = {
2565     "MS-DOS 16-bit/32-bit OMF object files",
2566     "obj",
2567     0,
2568     borland_debug_arr,
2569     &borland_debug_form,
2570     obj_stdmac,
2571     obj_init,
2572     obj_set_info,
2573     obj_out,
2574     obj_deflabel,
2575     obj_segment,
2576     obj_segbase,
2577     obj_directive,
2578     obj_filename,
2579     obj_cleanup
2580 };
2581 #endif                          /* OF_OBJ */