56a05e6d8e3cbef196197b4494b1a8e3ee3b3b7a
[platform/upstream/nasm.git] / assemble.c
1 /* assemble.c   code generation for the Netwide Assembler
2  *
3  * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
4  * Julian Hall. All rights reserved. The software is
5  * redistributable under the license given in the file "LICENSE"
6  * distributed in the NASM archive.
7  *
8  * the actual codes (C syntax, i.e. octal):
9  * \0            - terminates the code. (Unless it's a literal of course.)
10  * \1, \2, \3    - that many literal bytes follow in the code stream
11  * \4, \6        - the POP/PUSH (respectively) codes for CS, DS, ES, SS
12  *                 (POP is never used for CS) depending on operand 0
13  * \5, \7        - the second byte of POP/PUSH codes for FS, GS, depending
14  *                 on operand 0
15  * \10..\13      - a literal byte follows in the code stream, to be added
16  *                 to the register value of operand 0..3
17  * \14..\17      - a signed byte immediate operand, from operand 0..3
18  * \20..\23      - a byte immediate operand, from operand 0..3
19  * \24..\27      - an unsigned byte immediate operand, from operand 0..3
20  * \30..\33      - a word immediate operand, from operand 0..3
21  * \34..\37      - select between \3[0-3] and \4[0-3] depending on 16/32 bit
22  *                 assembly mode or the operand-size override on the operand
23  * \40..\43      - a long immediate operand, from operand 0..3
24  * \44..\47      - select between \3[0-3], \4[0-3] and \5[4-7]
25  *                 depending on the address size of the instruction.
26  * \50..\53      - a byte relative operand, from operand 0..3
27  * \54..\57      - a qword immediate operand, from operand 0..3
28  * \60..\63      - a word relative operand, from operand 0..3
29  * \64..\67      - select between \6[0-3] and \7[0-3] depending on 16/32 bit
30  *                 assembly mode or the operand-size override on the operand
31  * \70..\73      - a long relative operand, from operand 0..3
32  * \74..\77       - a word constant, from the _segment_ part of operand 0..3
33  * \1ab          - a ModRM, calculated on EA in operand a, with the spare
34  *                 field the register value of operand b.
35  * \140..\143    - an immediate word or signed byte for operand 0..3
36  * \144..\147    - or 2 (s-field) into opcode byte if operand 0..3
37  *                  is a signed byte rather than a word.  Opcode byte follows.
38  * \150..\153     - an immediate dword or signed byte for operand 0..3
39  * \154..\157    - or 2 (s-field) into opcode byte if operand 0..3
40  *                  is a signed byte rather than a dword.  Opcode byte follows.
41  * \160..\163    - this instruction uses DREX rather than REX, with the
42  *                 OC0 field set to 0, and the dest field taken from
43  *                 operand 0..3.
44  * \164..\167    - this instruction uses DREX rather than REX, with the
45  *                 OC0 field set to 1, and the dest field taken from
46  *                 operand 0..3.
47  * \170          - encodes the literal byte 0. (Some compilers don't take
48  *                 kindly to a zero byte in the _middle_ of a compile time
49  *                 string constant, so I had to put this hack in.)
50  * \171          - placement of DREX suffix in the absence of an EA
51  * \172\ab       - the register number from operand a in bits 7..4, with
52  *                 the 4-bit immediate from operand b in bits 0..3.
53  * \173\xab      - the register number from operand a in bits 7..4, with
54  *                 the value b in bits 0..3.
55  * \2ab          - a ModRM, calculated on EA in operand a, with the spare
56  *                 field equal to digit b.
57  * \250..\253    - same as \150..\153, except warn if the 64-bit operand
58  *                 is not equal to the truncated and sign-extended 32-bit
59  *                 operand; used for 32-bit immediates in 64-bit mode.
60  * \260..\263    - this instruction uses VEX rather than REX, with the
61  *                 V field taken from operand 0..3.
62  * \270          - this instruction uses VEX rather than REX, with the
63  *                 V field set to 1111b.
64  *
65  * VEX prefixes are followed by the sequence:
66  * \1mm\1wp        where mm is the M field; and wp is:
67  *                 01 0ww lpp
68  *                 ww = 0 for W = 0
69  *                 ww = 1 for W = 1
70  *                 ww = 2 for W used as REX.W
71  *
72  * \310          - indicates fixed 16-bit address size, i.e. optional 0x67.
73  * \311          - indicates fixed 32-bit address size, i.e. optional 0x67.
74  * \312          - (disassembler only) marker on LOOP, LOOPxx instructions.
75  * \313          - indicates fixed 64-bit address size, 0x67 invalid.
76  * \314          - (disassembler only) invalid with REX.B
77  * \315          - (disassembler only) invalid with REX.X
78  * \316          - (disassembler only) invalid with REX.R
79  * \317          - (disassembler only) invalid with REX.W
80  * \320          - indicates fixed 16-bit operand size, i.e. optional 0x66.
81  * \321          - indicates fixed 32-bit operand size, i.e. optional 0x66.
82  * \322          - indicates that this instruction is only valid when the
83  *                 operand size is the default (instruction to disassembler,
84  *                 generates no code in the assembler)
85  * \323          - indicates fixed 64-bit operand size, REX on extensions only.
86  * \324          - indicates 64-bit operand size requiring REX prefix.
87  * \330          - a literal byte follows in the code stream, to be added
88  *                 to the condition code value of the instruction.
89  * \331          - instruction not valid with REP prefix.  Hint for
90  *                 disassembler only; for SSE instructions.
91  * \332          - REP prefix (0xF2 byte) used as opcode extension.
92  * \333          - REP prefix (0xF3 byte) used as opcode extension.
93  * \334          - LOCK prefix used instead of REX.R
94  * \335          - disassemble a rep (0xF3 byte) prefix as repe not rep.
95  * \340          - reserve <operand 0> bytes of uninitialized storage.
96  *                 Operand 0 had better be a segmentless constant.
97  * \364          - operand-size prefix (0x66) not permitted
98  * \365          - address-size prefix (0x67) not permitted
99  * \366          - operand-size prefix (0x66) used as opcode extension
100  * \367          - address-size prefix (0x67) used as opcode extension
101  * \370,\371,\372 - match only if operand 0 meets byte jump criteria.
102  *                 370 is used for Jcc, 371 is used for JMP.
103  * \373          - assemble 0x03 if bits==16, 0x05 if bits==32;
104  *                 used for conditional jump over longer jump
105  */
106
107 #include "compiler.h"
108
109 #include <stdio.h>
110 #include <string.h>
111 #include <inttypes.h>
112
113 #include "nasm.h"
114 #include "nasmlib.h"
115 #include "assemble.h"
116 #include "insns.h"
117 #include "preproc.h"
118 #include "regflags.c"
119 #include "regvals.c"
120
121 typedef struct {
122     int sib_present;                 /* is a SIB byte necessary? */
123     int bytes;                       /* # of bytes of offset needed */
124     int size;                        /* lazy - this is sib+bytes+1 */
125     uint8_t modrm, sib, rex, rip;    /* the bytes themselves */
126 } ea;
127
128 static uint32_t cpu;            /* cpu level received from nasm.c */
129 static efunc errfunc;
130 static struct ofmt *outfmt;
131 static ListGen *list;
132
133 static int64_t calcsize(int32_t, int64_t, int, insn *, const char *);
134 static void gencode(int32_t, int64_t, int, insn *, const char *, int64_t);
135 static int matches(const struct itemplate *, insn *, int bits);
136 static int32_t regflag(const operand *);
137 static int32_t regval(const operand *);
138 static int rexflags(int, int32_t, int);
139 static int op_rexflags(const operand *, int);
140 static ea *process_ea(operand *, ea *, int, int, int, int32_t, int);
141 static void add_asp(insn *, int);
142
143 static int has_prefix(insn * ins, enum prefix_pos pos, enum prefixes prefix)
144 {
145     return ins->prefixes[pos] == prefix;
146 }
147
148 static void assert_no_prefix(insn * ins, enum prefix_pos pos)
149 {
150     if (ins->prefixes[pos])
151         errfunc(ERR_NONFATAL, "invalid %s prefix",
152                 prefix_name(ins->prefixes[pos]));
153 }
154
155 static const char *size_name(int size)
156 {
157     switch (size) {
158     case 1:
159         return "byte";
160     case 2:
161         return "word";
162     case 4:
163         return "dword";
164     case 8:
165         return "qword";
166     case 10:
167         return "tword";
168     case 16:
169         return "oword";
170     default:
171         return "???";
172     }
173 }
174
175 static void warn_overflow(int size, int64_t data)
176 {
177     if (size < 8) {
178         int64_t lim = ((int64_t)1 << (size*8))-1;
179
180         if (data < ~lim || data > lim)
181             errfunc(ERR_WARNING | ERR_WARN_NOV,
182                     "%s data exceeds bounds", size_name(size));
183     }
184 }
185 /*
186  * This routine wrappers the real output format's output routine,
187  * in order to pass a copy of the data off to the listing file
188  * generator at the same time.
189  */
190 static void out(int64_t offset, int32_t segto, const void *data,
191                 enum out_type type, uint64_t size,
192                 int32_t segment, int32_t wrt)
193 {
194     static int32_t lineno = 0;     /* static!!! */
195     static char *lnfname = NULL;
196     uint8_t p[8];
197
198     if (type == OUT_ADDRESS && segment == NO_SEG && wrt == NO_SEG) {
199         /*
200          * This is a non-relocated address, and we're going to
201          * convert it into RAWDATA format.
202          */
203         uint8_t *q = p;
204
205         if (size > 8) {
206             errfunc(ERR_PANIC, "OUT_ADDRESS with size > 8");
207             return;
208         }
209
210         WRITEADDR(q, *(int64_t *)data, size);
211         data = p;
212         type = OUT_RAWDATA;
213     }
214
215     list->output(offset, data, type, size);
216
217     /*
218      * this call to src_get determines when we call the
219      * debug-format-specific "linenum" function
220      * it updates lineno and lnfname to the current values
221      * returning 0 if "same as last time", -2 if lnfname
222      * changed, and the amount by which lineno changed,
223      * if it did. thus, these variables must be static
224      */
225
226     if (src_get(&lineno, &lnfname)) {
227         outfmt->current_dfmt->linenum(lnfname, lineno, segto);
228     }
229
230     outfmt->output(segto, data, type, size, segment, wrt);
231 }
232
233 static int jmp_match(int32_t segment, int64_t offset, int bits,
234                      insn * ins, const char *code)
235 {
236     int64_t isize;
237     uint8_t c = code[0];
238
239     if (c != 0370 && c != 0371)
240         return 0;
241     if (ins->oprs[0].opflags & OPFLAG_FORWARD) {
242         if ((optimizing < 0 || (ins->oprs[0].type & STRICT))
243             && c == 0370)
244             return 1;
245         else
246             return (pass0 == 0);        /* match a forward reference */
247     }
248     isize = calcsize(segment, offset, bits, ins, code);
249     if (ins->oprs[0].segment != segment)
250         return 0;
251     isize = ins->oprs[0].offset - offset - isize;       /* isize is now the delta */
252     if (isize >= -128L && isize <= 127L)
253         return 1;               /* it is byte size */
254
255     return 0;
256 }
257
258 int64_t assemble(int32_t segment, int64_t offset, int bits, uint32_t cp,
259               insn * instruction, struct ofmt *output, efunc error,
260               ListGen * listgen)
261 {
262     const struct itemplate *temp;
263     int j;
264     int size_prob;
265     int64_t insn_end;
266     int32_t itimes;
267     int64_t start = offset;
268     int64_t wsize = 0;             /* size for DB etc. */
269
270     errfunc = error;            /* to pass to other functions */
271     cpu = cp;
272     outfmt = output;            /* likewise */
273     list = listgen;             /* and again */
274
275     switch (instruction->opcode) {
276     case -1:
277         return 0;
278     case I_DB:
279         wsize = 1;
280         break;
281     case I_DW:
282         wsize = 2;
283         break;
284     case I_DD:
285         wsize = 4;
286         break;
287     case I_DQ:
288         wsize = 8;
289         break;
290     case I_DT:
291         wsize = 10;
292         break;
293     case I_DO:
294         wsize = 16;
295         break;
296     default:
297         break;
298     }
299
300     if (wsize) {
301         extop *e;
302         int32_t t = instruction->times;
303         if (t < 0)
304             errfunc(ERR_PANIC,
305                     "instruction->times < 0 (%ld) in assemble()", t);
306
307         while (t--) {           /* repeat TIMES times */
308             for (e = instruction->eops; e; e = e->next) {
309                 if (e->type == EOT_DB_NUMBER) {
310                     if (wsize == 1) {
311                         if (e->segment != NO_SEG)
312                             errfunc(ERR_NONFATAL,
313                                     "one-byte relocation attempted");
314                         else {
315                             uint8_t out_byte = e->offset;
316                             out(offset, segment, &out_byte,
317                                 OUT_RAWDATA, 1, NO_SEG, NO_SEG);
318                         }
319                     } else if (wsize > 8) {
320                         errfunc(ERR_NONFATAL, "integer supplied to a DT or DO"
321                                 " instruction");
322                     } else
323                         out(offset, segment, &e->offset,
324                             OUT_ADDRESS, wsize, e->segment, e->wrt);
325                     offset += wsize;
326                 } else if (e->type == EOT_DB_STRING) {
327                     int align;
328
329                     out(offset, segment, e->stringval,
330                         OUT_RAWDATA, e->stringlen, NO_SEG, NO_SEG);
331                     align = e->stringlen % wsize;
332
333                     if (align) {
334                         align = wsize - align;
335                         out(offset, segment,
336                             "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",
337                             OUT_RAWDATA, align, NO_SEG, NO_SEG);
338                     }
339                     offset += e->stringlen + align;
340                 }
341             }
342             if (t > 0 && t == instruction->times - 1) {
343                 /*
344                  * Dummy call to list->output to give the offset to the
345                  * listing module.
346                  */
347                 list->output(offset, NULL, OUT_RAWDATA, 0);
348                 list->uplevel(LIST_TIMES);
349             }
350         }
351         if (instruction->times > 1)
352             list->downlevel(LIST_TIMES);
353         return offset - start;
354     }
355
356     if (instruction->opcode == I_INCBIN) {
357         static char fname[FILENAME_MAX];
358         FILE *fp;
359         int32_t len;
360         char *prefix = "", *combine;
361         char **pPrevPath = NULL;
362
363         len = FILENAME_MAX - 1;
364         if (len > instruction->eops->stringlen)
365             len = instruction->eops->stringlen;
366         strncpy(fname, instruction->eops->stringval, len);
367         fname[len] = '\0';
368
369         while (1) {         /* added by alexfru: 'incbin' uses include paths */
370             combine = nasm_malloc(strlen(prefix) + len + 1);
371             strcpy(combine, prefix);
372             strcat(combine, fname);
373
374             if ((fp = fopen(combine, "rb")) != NULL) {
375                 nasm_free(combine);
376                 break;
377             }
378
379             nasm_free(combine);
380             pPrevPath = pp_get_include_path_ptr(pPrevPath);
381             if (pPrevPath == NULL)
382                 break;
383             prefix = *pPrevPath;
384         }
385
386         if (fp == NULL)
387             error(ERR_NONFATAL, "`incbin': unable to open file `%s'",
388                   fname);
389         else if (fseek(fp, 0L, SEEK_END) < 0)
390             error(ERR_NONFATAL, "`incbin': unable to seek on file `%s'",
391                   fname);
392         else {
393             static char buf[2048];
394             int32_t t = instruction->times;
395             int32_t base = 0;
396
397             len = ftell(fp);
398             if (instruction->eops->next) {
399                 base = instruction->eops->next->offset;
400                 len -= base;
401                 if (instruction->eops->next->next &&
402                     len > instruction->eops->next->next->offset)
403                     len = instruction->eops->next->next->offset;
404             }
405             /*
406              * Dummy call to list->output to give the offset to the
407              * listing module.
408              */
409             list->output(offset, NULL, OUT_RAWDATA, 0);
410             list->uplevel(LIST_INCBIN);
411             while (t--) {
412                 int32_t l;
413
414                 fseek(fp, base, SEEK_SET);
415                 l = len;
416                 while (l > 0) {
417                     int32_t m =
418                         fread(buf, 1, (l > (int32_t) sizeof(buf) ? (int32_t) sizeof(buf) : l),
419                               fp);
420                     if (!m) {
421                         /*
422                          * This shouldn't happen unless the file
423                          * actually changes while we are reading
424                          * it.
425                          */
426                         error(ERR_NONFATAL,
427                               "`incbin': unexpected EOF while"
428                               " reading file `%s'", fname);
429                         t = 0;  /* Try to exit cleanly */
430                         break;
431                     }
432                     out(offset, segment, buf, OUT_RAWDATA, m,
433                         NO_SEG, NO_SEG);
434                     l -= m;
435                 }
436             }
437             list->downlevel(LIST_INCBIN);
438             if (instruction->times > 1) {
439                 /*
440                  * Dummy call to list->output to give the offset to the
441                  * listing module.
442                  */
443                 list->output(offset, NULL, OUT_RAWDATA, 0);
444                 list->uplevel(LIST_TIMES);
445                 list->downlevel(LIST_TIMES);
446             }
447             fclose(fp);
448             return instruction->times * len;
449         }
450         return 0;               /* if we're here, there's an error */
451     }
452
453     /* Check to see if we need an address-size prefix */
454     add_asp(instruction, bits);
455
456     size_prob = false;
457
458     for (temp = nasm_instructions[instruction->opcode]; temp->opcode != -1; temp++){
459         int m = matches(temp, instruction, bits);
460
461         if (m == 99)
462             m += jmp_match(segment, offset, bits, instruction, temp->code);
463
464         if (m == 100) {         /* matches! */
465             const char *codes = temp->code;
466             int64_t insn_size = calcsize(segment, offset, bits,
467                                       instruction, codes);
468             itimes = instruction->times;
469             if (insn_size < 0)  /* shouldn't be, on pass two */
470                 error(ERR_PANIC, "errors made it through from pass one");
471             else
472                 while (itimes--) {
473                     for (j = 0; j < MAXPREFIX; j++) {
474                         uint8_t c = 0;
475                         switch (instruction->prefixes[j]) {
476                         case P_LOCK:
477                             c = 0xF0;
478                             break;
479                         case P_REPNE:
480                         case P_REPNZ:
481                             c = 0xF2;
482                             break;
483                         case P_REPE:
484                         case P_REPZ:
485                         case P_REP:
486                             c = 0xF3;
487                             break;
488                         case R_CS:
489                             if (bits == 64) {
490                                 error(ERR_WARNING,
491                                       "cs segment base generated, but will be ignored in 64-bit mode");
492                             }
493                             c = 0x2E;
494                             break;
495                         case R_DS:
496                             if (bits == 64) {
497                                 error(ERR_WARNING,
498                                       "ds segment base generated, but will be ignored in 64-bit mode");
499                             }
500                             c = 0x3E;
501                             break;
502                         case R_ES:
503                            if (bits == 64) {
504                                 error(ERR_WARNING,
505                                       "es segment base generated, but will be ignored in 64-bit mode");
506                            }
507                             c = 0x26;
508                             break;
509                         case R_FS:
510                             c = 0x64;
511                             break;
512                         case R_GS:
513                             c = 0x65;
514                             break;
515                         case R_SS:
516                             if (bits == 64) {
517                                 error(ERR_WARNING,
518                                       "ss segment base generated, but will be ignored in 64-bit mode");
519                             }
520                             c = 0x36;
521                             break;
522                         case R_SEGR6:
523                         case R_SEGR7:
524                             error(ERR_NONFATAL,
525                                   "segr6 and segr7 cannot be used as prefixes");
526                             break;
527                         case P_A16:
528                             if (bits == 64) {
529                                 error(ERR_NONFATAL,
530                                       "16-bit addressing is not supported "
531                                       "in 64-bit mode");
532                             } else if (bits != 16)
533                                 c = 0x67;
534                             break;
535                         case P_A32:
536                             if (bits != 32)
537                                 c = 0x67;
538                             break;
539                         case P_A64:
540                             if (bits != 64) {
541                                 error(ERR_NONFATAL,
542                                       "64-bit addressing is only supported "
543                                       "in 64-bit mode");
544                             }
545                             break;
546                         case P_ASP:
547                             c = 0x67;
548                             break;
549                         case P_O16:
550                             if (bits != 16)
551                                 c = 0x66;
552                             break;
553                         case P_O32:
554                             if (bits == 16)
555                                 c = 0x66;
556                             break;
557                         case P_O64:
558                             /* REX.W */
559                             break;
560                         case P_OSP:
561                             c = 0x66;
562                             break;
563                         case P_none:
564                             break;
565                         default:
566                             error(ERR_PANIC, "invalid instruction prefix");
567                         }
568                         if (c != 0) {
569                             out(offset, segment, &c, OUT_RAWDATA, 1,
570                                 NO_SEG, NO_SEG);
571                             offset++;
572                         }
573                     }
574                     insn_end = offset + insn_size;
575                     gencode(segment, offset, bits, instruction, codes,
576                             insn_end);
577                     offset += insn_size;
578                     if (itimes > 0 && itimes == instruction->times - 1) {
579                         /*
580                          * Dummy call to list->output to give the offset to the
581                          * listing module.
582                          */
583                         list->output(offset, NULL, OUT_RAWDATA, 0);
584                         list->uplevel(LIST_TIMES);
585                     }
586                 }
587             if (instruction->times > 1)
588                 list->downlevel(LIST_TIMES);
589             return offset - start;
590         } else if (m > 0 && m > size_prob) {
591             size_prob = m;
592         }
593 //        temp++;
594     }
595
596     if (temp->opcode == -1) {   /* didn't match any instruction */
597         switch (size_prob) {
598         case 1:
599             error(ERR_NONFATAL, "operation size not specified");
600             break;
601         case 2:
602             error(ERR_NONFATAL, "mismatch in operand sizes");
603             break;
604         case 3:
605             error(ERR_NONFATAL, "no instruction for this cpu level");
606             break;
607         case 4:
608             error(ERR_NONFATAL, "instruction not supported in 64-bit mode");
609             break;
610         default:
611             error(ERR_NONFATAL,
612                   "invalid combination of opcode and operands");
613             break;
614         }
615     }
616     return 0;
617 }
618
619 int64_t insn_size(int32_t segment, int64_t offset, int bits, uint32_t cp,
620                insn * instruction, efunc error)
621 {
622     const struct itemplate *temp;
623
624     errfunc = error;            /* to pass to other functions */
625     cpu = cp;
626
627     if (instruction->opcode == -1)
628         return 0;
629
630     if (instruction->opcode == I_DB || instruction->opcode == I_DW ||
631         instruction->opcode == I_DD || instruction->opcode == I_DQ ||
632         instruction->opcode == I_DT || instruction->opcode == I_DO) {
633         extop *e;
634         int32_t isize, osize, wsize = 0;   /* placate gcc */
635
636         isize = 0;
637         switch (instruction->opcode) {
638         case I_DB:
639             wsize = 1;
640             break;
641         case I_DW:
642             wsize = 2;
643             break;
644         case I_DD:
645             wsize = 4;
646             break;
647         case I_DQ:
648             wsize = 8;
649             break;
650         case I_DT:
651             wsize = 10;
652             break;
653         case I_DO:
654             wsize = 16;
655             break;
656         default:
657             break;
658         }
659
660         for (e = instruction->eops; e; e = e->next) {
661             int32_t align;
662
663             osize = 0;
664             if (e->type == EOT_DB_NUMBER)
665                 osize = 1;
666             else if (e->type == EOT_DB_STRING)
667                 osize = e->stringlen;
668
669             align = (-osize) % wsize;
670             if (align < 0)
671                 align += wsize;
672             isize += osize + align;
673         }
674         return isize * instruction->times;
675     }
676
677     if (instruction->opcode == I_INCBIN) {
678         char fname[FILENAME_MAX];
679         FILE *fp;
680         int32_t len;
681         char *prefix = "", *combine;
682         char **pPrevPath = NULL;
683
684         len = FILENAME_MAX - 1;
685         if (len > instruction->eops->stringlen)
686             len = instruction->eops->stringlen;
687         strncpy(fname, instruction->eops->stringval, len);
688         fname[len] = '\0';
689
690         /* added by alexfru: 'incbin' uses include paths */
691         while (1) {
692             combine = nasm_malloc(strlen(prefix) + len + 1);
693             strcpy(combine, prefix);
694             strcat(combine, fname);
695
696             if ((fp = fopen(combine, "rb")) != NULL) {
697                 nasm_free(combine);
698                 break;
699             }
700
701             nasm_free(combine);
702             pPrevPath = pp_get_include_path_ptr(pPrevPath);
703             if (pPrevPath == NULL)
704                 break;
705             prefix = *pPrevPath;
706         }
707
708         if (fp == NULL)
709             error(ERR_NONFATAL, "`incbin': unable to open file `%s'",
710                   fname);
711         else if (fseek(fp, 0L, SEEK_END) < 0)
712             error(ERR_NONFATAL, "`incbin': unable to seek on file `%s'",
713                   fname);
714         else {
715             len = ftell(fp);
716             fclose(fp);
717             if (instruction->eops->next) {
718                 len -= instruction->eops->next->offset;
719                 if (instruction->eops->next->next &&
720                     len > instruction->eops->next->next->offset) {
721                     len = instruction->eops->next->next->offset;
722                 }
723             }
724             return instruction->times * len;
725         }
726         return 0;               /* if we're here, there's an error */
727     }
728
729     /* Check to see if we need an address-size prefix */
730     add_asp(instruction, bits);
731
732     for (temp = nasm_instructions[instruction->opcode]; temp->opcode != -1; temp++) {
733         int m = matches(temp, instruction, bits);
734         if (m == 99)
735             m += jmp_match(segment, offset, bits, instruction, temp->code);
736
737         if (m == 100) {
738             /* we've matched an instruction. */
739             int64_t isize;
740             const char *codes = temp->code;
741             int j;
742
743             isize = calcsize(segment, offset, bits, instruction, codes);
744             if (isize < 0)
745                 return -1;
746             for (j = 0; j < MAXPREFIX; j++) {
747                 switch (instruction->prefixes[j]) {
748                 case P_A16:
749                     if (bits != 16)
750                         isize++;
751                     break;
752                 case P_A32:
753                     if (bits != 32)
754                         isize++;
755                     break;
756                 case P_O16:
757                     if (bits != 16)
758                         isize++;
759                     break;
760                 case P_O32:
761                     if (bits == 16)
762                         isize++;
763                     break;
764                 case P_A64:
765                 case P_O64:
766                 case P_none:
767                     break;
768                 default:
769                     isize++;
770                     break;
771                 }
772             }
773             return isize * instruction->times;
774         }
775     }
776     return -1;                  /* didn't match any instruction */
777 }
778
779 static bool possible_sbyte(insn * ins, int op)
780 {
781     return !(ins->forw_ref && ins->oprs[op].opflags) &&
782         optimizing >= 0 &&
783         !(ins->oprs[op].type & STRICT) &&
784         ins->oprs[op].wrt == NO_SEG && ins->oprs[op].segment == NO_SEG;
785 }
786
787 /* check that opn[op]  is a signed byte of size 16 or 32 */
788 static bool is_sbyte16(insn * ins, int op)
789 {
790     int16_t v;
791
792     if (!possible_sbyte(ins, op))
793         return false;
794
795     v = ins->oprs[op].offset;
796     return v >= -128 && v <= 127;
797 }
798
799 static bool is_sbyte32(insn * ins, int op)
800 {
801     int32_t v;
802
803     if (!possible_sbyte(ins, op))
804         return false;
805
806     v = ins->oprs[op].offset;
807     return v >= -128 && v <= 127;
808 }
809
810 /* check that  opn[op]  is a signed byte of size 32; warn if this is not
811    the original value when extended to 64 bits */
812 static bool is_sbyte64(insn * ins, int op)
813 {
814     int64_t v64;
815     int32_t v32;
816
817     /* dead in the water on forward reference or External */
818     if (!possible_sbyte(ins, op))
819         return false;
820
821     v64 = ins->oprs[op].offset;
822     v32 = (int32_t)v64;
823
824     warn_overflow(32, v64);
825
826     return v32 >= -128 && v32 <= 127;
827 }
828 static int64_t calcsize(int32_t segment, int64_t offset, int bits,
829                      insn * ins, const char *codes)
830 {
831     int64_t length = 0;
832     uint8_t c;
833     int rex_mask = ~0;
834     struct operand *opx;
835
836     ins->rex = 0;               /* Ensure REX is reset */
837
838     if (ins->prefixes[PPS_OSIZE] == P_O64)
839         ins->rex |= REX_W;
840
841     (void)segment;              /* Don't warn that this parameter is unused */
842     (void)offset;               /* Don't warn that this parameter is unused */
843
844     while (*codes) {
845         c = *codes++;
846         opx = &ins->oprs[c & 3];
847         switch (c) {
848         case 01:
849         case 02:
850         case 03:
851             codes += c, length += c;
852             break;
853         case 04:
854         case 05:
855         case 06:
856         case 07:
857             length++;
858             break;
859         case 010:
860         case 011:
861         case 012:
862         case 013:
863             ins->rex |=
864                 op_rexflags(opx, REX_B|REX_H|REX_P|REX_W);
865             codes++, length++;
866             break;
867         case 014:
868         case 015:
869         case 016:
870         case 017:
871             length++;
872             break;
873         case 020:
874         case 021:
875         case 022:
876         case 023:
877             length++;
878             break;
879         case 024:
880         case 025:
881         case 026:
882         case 027:
883             length++;
884             break;
885         case 030:
886         case 031:
887         case 032:
888         case 033:
889             length += 2;
890             break;
891         case 034:
892         case 035:
893         case 036:
894         case 037:
895             if (opx->type & (BITS16 | BITS32 | BITS64))
896                 length += (opx->type & BITS16) ? 2 : 4;
897             else
898                 length += (bits == 16) ? 2 : 4;
899             break;
900         case 040:
901         case 041:
902         case 042:
903         case 043:
904             length += 4;
905             break;
906         case 044:
907         case 045:
908         case 046:
909         case 047:
910             length += ins->addr_size >> 3;
911             break;
912         case 050:
913         case 051:
914         case 052:
915         case 053:
916             length++;
917             break;
918         case 054:
919         case 055:
920         case 056:
921         case 057:
922             length += 8; /* MOV reg64/imm */
923             break;
924         case 060:
925         case 061:
926         case 062:
927         case 063:
928             length += 2;
929             break;
930         case 064:
931         case 065:
932         case 066:
933         case 067:
934             if (opx->type & (BITS16 | BITS32 | BITS64))
935                 length += (opx->type & BITS16) ? 2 : 4;
936             else
937                 length += (bits == 16) ? 2 : 4;
938             break;
939         case 070:
940         case 071:
941         case 072:
942         case 073:
943             length += 4;
944             break;
945         case 074:
946         case 075:
947         case 076:
948         case 077:
949             length += 2;
950             break;
951         case 0140:
952         case 0141:
953         case 0142:
954         case 0143:
955             length += is_sbyte16(ins, c & 3) ? 1 : 2;
956             break;
957         case 0144:
958         case 0145:
959         case 0146:
960         case 0147:
961             codes++;
962             length++;
963             break;
964         case 0150:
965         case 0151:
966         case 0152:
967         case 0153:
968             length += is_sbyte32(ins, c & 3) ? 1 : 4;
969             break;
970         case 0154:
971         case 0155:
972         case 0156:
973         case 0157:
974             codes++;
975             length++;
976             break;
977         case 0160:
978         case 0161:
979         case 0162:
980         case 0163:
981             length++;
982             ins->rex |= REX_D;
983             ins->drexdst = regval(opx);
984             break;
985         case 0164:
986         case 0165:
987         case 0166:
988         case 0167:
989             length++;
990             ins->rex |= REX_D|REX_OC;
991             ins->drexdst = regval(opx);
992             break;
993         case 0170:
994             length++;
995             break;
996         case 0171:
997             break;
998         case 0172:
999         case 0173:
1000             codes++;
1001             length++;
1002             break;
1003         case 0250:
1004         case 0251:
1005         case 0252:
1006         case 0253:
1007             length += is_sbyte64(ins, c & 3) ? 1 : 4;
1008             break;
1009         case 0260:
1010         case 0261:
1011         case 0262:
1012         case 0263:
1013             length += 2;
1014             ins->rex |= REX_V;
1015             ins->drexdst = regval(opx);
1016             ins->vex_m = *codes++;
1017             ins->vex_wlp = *codes++;
1018             break;
1019         case 0270:
1020             length += 2;
1021             ins->rex |= REX_V;
1022             ins->drexdst = 0;
1023             ins->vex_m = *codes++;
1024             ins->vex_wlp = *codes++;
1025             break;
1026         case 0300:
1027         case 0301:
1028         case 0302:
1029         case 0303:
1030             break;
1031         case 0310:
1032             if (bits == 64)
1033                 return -1;
1034             length += (bits != 16) && !has_prefix(ins, PPS_ASIZE, P_A16);
1035             break;
1036         case 0311:
1037             length += (bits != 32) && !has_prefix(ins, PPS_ASIZE, P_A32);
1038             break;
1039         case 0312:
1040             break;
1041         case 0313:
1042             if (bits != 64 || has_prefix(ins, PPS_ASIZE, P_A16) ||
1043                 has_prefix(ins, PPS_ASIZE, P_A32))
1044                 return -1;
1045             break;
1046         case 0314:
1047         case 0315:
1048         case 0316:
1049         case 0317:
1050             break;
1051         case 0320:
1052             length += (bits != 16);
1053             break;
1054         case 0321:
1055             length += (bits == 16);
1056             break;
1057         case 0322:
1058             break;
1059         case 0323:
1060             rex_mask &= ~REX_W;
1061             break;
1062         case 0324:
1063             ins->rex |= REX_W;
1064             break;
1065         case 0330:
1066             codes++, length++;
1067             break;
1068         case 0331:
1069             break;
1070         case 0332:
1071         case 0333:
1072             length++;
1073             break;
1074         case 0334:
1075             ins->rex |= REX_L;
1076             break;
1077         case 0335:
1078             break;
1079         case 0340:
1080             if (ins->oprs[0].segment != NO_SEG)
1081                 errfunc(ERR_NONFATAL, "attempt to reserve non-constant"
1082                         " quantity of BSS space");
1083             else
1084                 length += ins->oprs[0].offset;
1085             break;
1086         case 0364:
1087         case 0365:
1088             break;
1089         case 0366:
1090         case 0367:
1091             length++;
1092             break;
1093         case 0370:
1094         case 0371:
1095         case 0372:
1096             break;
1097         case 0373:
1098             length++;
1099             break;
1100         default:               /* can't do it by 'case' statements */
1101             if (c >= 0100 && c <= 0277) {       /* it's an EA */
1102                 ea ea_data;
1103                 int rfield;
1104                 int32_t rflags;
1105                 ea_data.rex = 0;           /* Ensure ea.REX is initially 0 */
1106
1107                 if (c <= 0177) {
1108                     /* pick rfield from operand b */
1109                     rflags = regflag(&ins->oprs[c & 7]);
1110                     rfield = regvals[ins->oprs[c & 7].basereg];
1111                 } else {
1112                     rflags = 0;
1113                     rfield = c & 7;
1114                 }
1115
1116                 if (!process_ea
1117                     (&ins->oprs[(c >> 3) & 7], &ea_data, bits,
1118                      ins->addr_size, rfield, rflags, ins->forw_ref)) {
1119                     errfunc(ERR_NONFATAL, "invalid effective address");
1120                     return -1;
1121                 } else {
1122                     ins->rex |= ea_data.rex;
1123                     length += ea_data.size;
1124                 }
1125             } else {
1126                 errfunc(ERR_PANIC, "internal instruction table corrupt"
1127                         ": instruction code 0x%02X given", c);
1128             }
1129         }
1130     }
1131
1132     ins->rex &= rex_mask;
1133
1134     if (ins->rex & REX_V) {
1135         int bad32 = REX_R|REX_W|REX_X|REX_B;
1136
1137         if (ins->rex & REX_H) {
1138             errfunc(ERR_NONFATAL, "cannot use high register in vex instruction");
1139             return -1;
1140         }
1141         switch (ins->vex_wlp & 030) {
1142         case 000:
1143             ins->rex &= ~REX_W;
1144             break;
1145         case 010:
1146             ins->rex |= REX_W;
1147             bad32 &= ~REX_W;
1148             break;
1149         default:
1150             /* Follow REX_W */
1151             break;
1152         }
1153
1154         if (bits != 64 && ((ins->rex & bad32) || ins->drexdst > 7)) {
1155             errfunc(ERR_NONFATAL, "invalid operands in non-64-bit mode");
1156             return -1;
1157         }
1158         if (ins->vex_m != 1 || (ins->rex & (REX_W|REX_R|REX_B)))
1159             length += 3;
1160         else
1161             length += 2;
1162     } else if (ins->rex & REX_D) {
1163         if (ins->rex & REX_H) {
1164             errfunc(ERR_NONFATAL, "cannot use high register in drex instruction");
1165             return -1;
1166         }
1167         if (bits != 64 && ((ins->rex & (REX_R|REX_W|REX_X|REX_B)) ||
1168                            ins->drexdst > 7)) {
1169             errfunc(ERR_NONFATAL, "invalid operands in non-64-bit mode");
1170             return -1;
1171         }
1172         length++;
1173     } else if (ins->rex & REX_REAL) {
1174         if (ins->rex & REX_H) {
1175             errfunc(ERR_NONFATAL, "cannot use high register in rex instruction");
1176             return -1;
1177         } else if (bits == 64) {
1178             length++;
1179         } else if ((ins->rex & REX_L) &&
1180                    !(ins->rex & (REX_P|REX_W|REX_X|REX_B)) &&
1181                    cpu >= IF_X86_64) {
1182             /* LOCK-as-REX.R */
1183             assert_no_prefix(ins, PPS_LREP);
1184             length++;
1185         } else {
1186             errfunc(ERR_NONFATAL, "invalid operands in non-64-bit mode");
1187             return -1;
1188         }
1189     }
1190
1191     return length;
1192 }
1193
1194 #define EMIT_REX()                                                      \
1195     if (!(ins->rex & (REX_D|REX_V)) && (ins->rex & REX_REAL) && (bits == 64)) { \
1196         ins->rex = (ins->rex & REX_REAL)|REX_P;                         \
1197         out(offset, segment, &ins->rex, OUT_RAWDATA, 1, NO_SEG, NO_SEG); \
1198         ins->rex = 0;                                                   \
1199         offset += 1; \
1200     }
1201
1202 static void gencode(int32_t segment, int64_t offset, int bits,
1203                     insn * ins, const char *codes, int64_t insn_end)
1204 {
1205     static char condval[] = {   /* conditional opcodes */
1206         0x7, 0x3, 0x2, 0x6, 0x2, 0x4, 0xF, 0xD, 0xC, 0xE, 0x6, 0x2,
1207         0x3, 0x7, 0x3, 0x5, 0xE, 0xC, 0xD, 0xF, 0x1, 0xB, 0x9, 0x5,
1208         0x0, 0xA, 0xA, 0xB, 0x8, 0x4
1209     };
1210     uint8_t c;
1211     uint8_t bytes[4];
1212     int64_t size;
1213     int64_t data;
1214     struct operand *opx;
1215
1216     while (*codes) {
1217         c = *codes++;
1218         opx = &ins->oprs[c & 3];
1219         switch (c) {
1220         case 01:
1221         case 02:
1222         case 03:
1223             EMIT_REX();
1224             out(offset, segment, codes, OUT_RAWDATA, c, NO_SEG, NO_SEG);
1225             codes += c;
1226             offset += c;
1227             break;
1228
1229         case 04:
1230         case 06:
1231             switch (ins->oprs[0].basereg) {
1232             case R_CS:
1233                 bytes[0] = 0x0E + (c == 0x04 ? 1 : 0);
1234                 break;
1235             case R_DS:
1236                 bytes[0] = 0x1E + (c == 0x04 ? 1 : 0);
1237                 break;
1238             case R_ES:
1239                 bytes[0] = 0x06 + (c == 0x04 ? 1 : 0);
1240                 break;
1241             case R_SS:
1242                 bytes[0] = 0x16 + (c == 0x04 ? 1 : 0);
1243                 break;
1244             default:
1245                 errfunc(ERR_PANIC,
1246                         "bizarre 8086 segment register received");
1247             }
1248             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1249             offset++;
1250             break;
1251
1252         case 05:
1253         case 07:
1254             switch (ins->oprs[0].basereg) {
1255             case R_FS:
1256                 bytes[0] = 0xA0 + (c == 0x05 ? 1 : 0);
1257                 break;
1258             case R_GS:
1259                 bytes[0] = 0xA8 + (c == 0x05 ? 1 : 0);
1260                 break;
1261             default:
1262                 errfunc(ERR_PANIC,
1263                         "bizarre 386 segment register received");
1264             }
1265             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1266             offset++;
1267             break;
1268
1269         case 010:
1270         case 011:
1271         case 012:
1272         case 013:
1273             EMIT_REX();
1274             bytes[0] = *codes++ + ((regval(opx)) & 7);
1275             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1276             offset += 1;
1277             break;
1278
1279         case 014:
1280         case 015:
1281         case 016:
1282         case 017:
1283             /* XXX: warns for legitimate optimizer actions */
1284             if (opx->offset < -128 || opx->offset > 127) {
1285                 errfunc(ERR_WARNING | ERR_WARN_NOV,
1286                         "signed byte value exceeds bounds");
1287             }
1288
1289             if (opx->segment != NO_SEG) {
1290                 data = opx->offset;
1291                 out(offset, segment, &data, OUT_ADDRESS, 1,
1292                     opx->segment, opx->wrt);
1293             } else {
1294                 bytes[0] = opx->offset;
1295                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG,
1296                     NO_SEG);
1297             }
1298             offset += 1;
1299             break;
1300
1301         case 020:
1302         case 021:
1303         case 022:
1304         case 023:
1305             if (opx->offset < -256 || opx->offset > 255) {
1306                 errfunc(ERR_WARNING | ERR_WARN_NOV,
1307                         "byte value exceeds bounds");
1308             }
1309             if (opx->segment != NO_SEG) {
1310                 data = opx->offset;
1311                 out(offset, segment, &data, OUT_ADDRESS, 1,
1312                     opx->segment, opx->wrt);
1313             } else {
1314                 bytes[0] = opx->offset;
1315                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG,
1316                     NO_SEG);
1317             }
1318             offset += 1;
1319             break;
1320
1321         case 024:
1322         case 025:
1323         case 026:
1324         case 027:
1325             if (opx->offset < 0 || opx->offset > 255)
1326                 errfunc(ERR_WARNING | ERR_WARN_NOV,
1327                         "unsigned byte value exceeds bounds");
1328             if (opx->segment != NO_SEG) {
1329                 data = opx->offset;
1330                 out(offset, segment, &data, OUT_ADDRESS, 1,
1331                     opx->segment, opx->wrt);
1332             } else {
1333                 bytes[0] = opx->offset;
1334                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG,
1335                     NO_SEG);
1336             }
1337             offset += 1;
1338             break;
1339
1340         case 030:
1341         case 031:
1342         case 032:
1343         case 033:
1344             data = opx->offset;
1345             if (opx->segment == NO_SEG && opx->wrt == NO_SEG)
1346                 warn_overflow(2, data);
1347             out(offset, segment, &data, OUT_ADDRESS, 2,
1348                 opx->segment, opx->wrt);
1349             offset += 2;
1350             break;
1351
1352         case 034:
1353         case 035:
1354         case 036:
1355         case 037:
1356             if (opx->type & (BITS16 | BITS32))
1357                 size = (opx->type & BITS16) ? 2 : 4;
1358             else
1359                 size = (bits == 16) ? 2 : 4;
1360             data = opx->offset;
1361             if (opx->segment == NO_SEG && opx->wrt == NO_SEG)
1362                 warn_overflow(size, data);
1363             out(offset, segment, &data, OUT_ADDRESS, size,
1364                 opx->segment, opx->wrt);
1365             offset += size;
1366             break;
1367
1368         case 040:
1369         case 041:
1370         case 042:
1371         case 043:
1372             data = opx->offset;
1373             if (opx->segment == NO_SEG && opx->wrt == NO_SEG)
1374                 warn_overflow(4, data);
1375             out(offset, segment, &data, OUT_ADDRESS, 4,
1376                 opx->segment, opx->wrt);
1377             offset += 4;
1378             break;
1379
1380         case 044:
1381         case 045:
1382         case 046:
1383         case 047:
1384             data = opx->offset;
1385             size = ins->addr_size >> 3;
1386             if (opx->segment == NO_SEG &&
1387                 opx->wrt == NO_SEG)
1388                 warn_overflow(size, data);
1389             out(offset, segment, &data, OUT_ADDRESS, size,
1390                 opx->segment, opx->wrt);
1391             offset += size;
1392             break;
1393
1394         case 050:
1395         case 051:
1396         case 052:
1397         case 053:
1398             if (opx->segment != segment)
1399                 errfunc(ERR_NONFATAL,
1400                         "short relative jump outside segment");
1401             data = opx->offset - insn_end;
1402             if (data > 127 || data < -128)
1403                 errfunc(ERR_NONFATAL, "short jump is out of range");
1404             bytes[0] = data;
1405             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1406             offset += 1;
1407             break;
1408
1409         case 054:
1410         case 055:
1411         case 056:
1412         case 057:
1413             data = (int64_t)opx->offset;
1414             out(offset, segment, &data, OUT_ADDRESS, 8,
1415                 opx->segment, opx->wrt);
1416             offset += 8;
1417             break;
1418
1419         case 060:
1420         case 061:
1421         case 062:
1422         case 063:
1423             if (opx->segment != segment) {
1424                 data = opx->offset;
1425                 out(offset, segment, &data,
1426                     OUT_REL2ADR, insn_end - offset,
1427                     opx->segment, opx->wrt);
1428             } else {
1429                 data = opx->offset - insn_end;
1430                 out(offset, segment, &data,
1431                     OUT_ADDRESS, 2, NO_SEG, NO_SEG);
1432             }
1433             offset += 2;
1434             break;
1435
1436         case 064:
1437         case 065:
1438         case 066:
1439         case 067:
1440             if (opx->type & (BITS16 | BITS32 | BITS64))
1441                 size = (opx->type & BITS16) ? 2 : 4;
1442             else
1443                 size = (bits == 16) ? 2 : 4;
1444             if (opx->segment != segment) {
1445                 data = opx->offset;
1446                 out(offset, segment, &data,
1447                     size == 2 ? OUT_REL2ADR : OUT_REL4ADR,
1448                     insn_end - offset, opx->segment, opx->wrt);
1449             } else {
1450                 data = opx->offset - insn_end;
1451                 out(offset, segment, &data,
1452                     OUT_ADDRESS, size, NO_SEG, NO_SEG);
1453             }
1454             offset += size;
1455             break;
1456
1457         case 070:
1458         case 071:
1459         case 072:
1460         case 073:
1461             if (opx->segment != segment) {
1462                 data = opx->offset;
1463                 out(offset, segment, &data,
1464                     OUT_REL4ADR, insn_end - offset,
1465                     opx->segment, opx->wrt);
1466             } else {
1467                 data = opx->offset - insn_end;
1468                 out(offset, segment, &data,
1469                     OUT_ADDRESS, 4, NO_SEG, NO_SEG);
1470             }
1471             offset += 4;
1472             break;
1473
1474         case 074:
1475         case 075:
1476         case 076:
1477         case 077:
1478             if (opx->segment == NO_SEG)
1479                 errfunc(ERR_NONFATAL, "value referenced by FAR is not"
1480                         " relocatable");
1481             data = 0L;
1482             out(offset, segment, &data, OUT_ADDRESS, 2,
1483                 outfmt->segbase(1 + opx->segment),
1484                 opx->wrt);
1485             offset += 2;
1486             break;
1487
1488         case 0140:
1489         case 0141:
1490         case 0142:
1491         case 0143:
1492             data = opx->offset;
1493             if (is_sbyte16(ins, c & 3)) {
1494                 bytes[0] = data;
1495                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG,
1496                     NO_SEG);
1497                 offset++;
1498             } else {
1499                 if (opx->segment == NO_SEG &&
1500                     opx->wrt == NO_SEG)
1501                     warn_overflow(2, data);
1502                 out(offset, segment, &data, OUT_ADDRESS, 2,
1503                     opx->segment, opx->wrt);
1504                 offset += 2;
1505             }
1506             break;
1507
1508         case 0144:
1509         case 0145:
1510         case 0146:
1511         case 0147:
1512             EMIT_REX();
1513             bytes[0] = *codes++;
1514             if (is_sbyte16(ins, c & 3))
1515                 bytes[0] |= 2;  /* s-bit */
1516             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1517             offset++;
1518             break;
1519
1520         case 0150:
1521         case 0151:
1522         case 0152:
1523         case 0153:
1524             data = opx->offset;
1525             if (is_sbyte32(ins, c & 3)) {
1526                 bytes[0] = data;
1527                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG,
1528                     NO_SEG);
1529                 offset++;
1530             } else {
1531                 out(offset, segment, &data, OUT_ADDRESS, 4,
1532                     opx->segment, opx->wrt);
1533                 offset += 4;
1534             }
1535             break;
1536
1537         case 0154:
1538         case 0155:
1539         case 0156:
1540         case 0157:
1541             EMIT_REX();
1542             bytes[0] = *codes++;
1543             if (is_sbyte32(ins, c & 3))
1544                 bytes[0] |= 2;  /* s-bit */
1545             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1546             offset++;
1547             break;
1548
1549         case 0160:
1550         case 0161:
1551         case 0162:
1552         case 0163:
1553         case 0164:
1554         case 0165:
1555         case 0166:
1556         case 0167:
1557             break;
1558
1559         case 0170:
1560             EMIT_REX();
1561             bytes[0] = 0;
1562             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1563             offset += 1;
1564             break;
1565
1566         case 0171:
1567             bytes[0] =
1568                 (ins->drexdst << 4) |
1569                 (ins->rex & REX_OC ? 0x08 : 0) |
1570                 (ins->rex & (REX_R|REX_X|REX_B));
1571             ins->rex = 0;
1572             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1573             offset++;
1574             break;
1575
1576         case 0172:
1577             c = *codes++;
1578             opx = &ins->oprs[c >> 3];
1579             bytes[0] = regvals[opx->basereg] << 4;
1580             opx = &ins->oprs[c & 7];
1581             if (opx->segment != NO_SEG || opx->wrt != NO_SEG) {
1582                 errfunc(ERR_NONFATAL,
1583                         "non-absolute expression not permitted as argument %d",
1584                         c & 7);
1585             } else {
1586                 if (opx->offset & ~15) {
1587                     errfunc(ERR_WARNING | ERR_WARN_NOV,
1588                             "four-bit argument exceeds bounds");
1589                 }
1590                 bytes[0] |= opx->offset & 15;
1591             }
1592             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1593             offset++;
1594             break;
1595
1596         case 0173:
1597             c = *codes++;
1598             opx = &ins->oprs[c >> 4];
1599             bytes[0] = regvals[opx->basereg] << 4;
1600             bytes[0] |= c & 15;
1601             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1602             offset++;
1603             break;
1604
1605         case 0250:
1606         case 0251:
1607         case 0252:
1608         case 0253:
1609             data = opx->offset;
1610             /* is_sbyte32() is right here, we have already warned */
1611             if (is_sbyte32(ins, c & 3)) {
1612                 bytes[0] = data;
1613                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG,
1614                     NO_SEG);
1615                 offset++;
1616             } else {
1617                 out(offset, segment, &data, OUT_ADDRESS, 4,
1618                     opx->segment, opx->wrt);
1619                 offset += 4;
1620             }
1621             break;
1622
1623         case 0260:
1624         case 0261:
1625         case 0262:
1626         case 0263:
1627         case 0270:
1628             codes += 2;
1629             if (ins->vex_m != 1 || (ins->rex & (REX_W|REX_X|REX_B))) {
1630                 bytes[0] = 0xc4;
1631                 bytes[1] = ins->vex_m | ((~ins->rex & 7) << 5);
1632                 bytes[2] = ((ins->rex & REX_W) << (7-3)) |
1633                     ((~ins->drexdst & 15)<< 3) | (ins->vex_wlp & 07);
1634                 out(offset, segment, &bytes, OUT_RAWDATA, 3, NO_SEG, NO_SEG);
1635                 offset += 3;
1636             } else {
1637                 bytes[0] = 0xc5;
1638                 bytes[1] = ((~ins->rex & REX_R) << (7-2)) |
1639                     ((~ins->drexdst & 15) << 3) | (ins->vex_wlp & 07);
1640                 out(offset, segment, &bytes, OUT_RAWDATA, 2, NO_SEG, NO_SEG);
1641                 offset += 2;
1642             }
1643             break;
1644
1645         case 0300:
1646         case 0301:
1647         case 0302:
1648         case 0303:
1649             break;
1650
1651         case 0310:
1652             if (bits == 32 && !has_prefix(ins, PPS_ASIZE, P_A16)) {
1653                 *bytes = 0x67;
1654                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1655                 offset += 1;
1656             } else
1657                 offset += 0;
1658             break;
1659
1660         case 0311:
1661             if (bits != 32 && !has_prefix(ins, PPS_ASIZE, P_A32)) {
1662                 *bytes = 0x67;
1663                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1664                 offset += 1;
1665             } else
1666                 offset += 0;
1667             break;
1668
1669         case 0312:
1670             break;
1671
1672         case 0313:
1673             ins->rex = 0;
1674             break;
1675
1676         case 0314:
1677         case 0315:
1678         case 0316:
1679         case 0317:
1680             break;
1681
1682         case 0320:
1683             if (bits != 16) {
1684                 *bytes = 0x66;
1685                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1686                 offset += 1;
1687             } else
1688                 offset += 0;
1689             break;
1690
1691         case 0321:
1692             if (bits == 16) {
1693                 *bytes = 0x66;
1694                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1695                 offset += 1;
1696             } else
1697                 offset += 0;
1698             break;
1699
1700         case 0322:
1701         case 0323:
1702             break;
1703
1704         case 0324:
1705             ins->rex |= REX_W;
1706             break;
1707
1708         case 0330:
1709             *bytes = *codes++ ^ condval[ins->condition];
1710             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1711             offset += 1;
1712             break;
1713
1714         case 0331:
1715             break;
1716
1717         case 0332:
1718         case 0333:
1719             *bytes = c - 0332 + 0xF2;
1720             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1721             offset += 1;
1722             break;
1723
1724         case 0334:
1725             if (ins->rex & REX_R) {
1726                 *bytes = 0xF0;
1727                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1728                 offset += 1;
1729             }
1730             ins->rex &= ~(REX_L|REX_R);
1731             break;
1732
1733         case 0335:
1734             break;
1735
1736         case 0340:
1737             if (ins->oprs[0].segment != NO_SEG)
1738                 errfunc(ERR_PANIC, "non-constant BSS size in pass two");
1739             else {
1740                 int64_t size = ins->oprs[0].offset;
1741                 if (size > 0)
1742                     out(offset, segment, NULL,
1743                         OUT_RESERVE, size, NO_SEG, NO_SEG);
1744                 offset += size;
1745             }
1746             break;
1747
1748         case 0364:
1749         case 0365:
1750             break;
1751
1752         case 0366:
1753         case 0367:
1754             *bytes = c - 0366 + 0x66;
1755             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1756             offset += 1;
1757             break;
1758
1759         case 0370:
1760         case 0371:
1761         case 0372:
1762             break;
1763
1764         case 0373:
1765             *bytes = bits == 16 ? 3 : 5;
1766             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1767             offset += 1;
1768             break;
1769
1770         default:               /* can't do it by 'case' statements */
1771             if (c >= 0100 && c <= 0277) {       /* it's an EA */
1772                 ea ea_data;
1773                 int rfield;
1774                 int32_t rflags;
1775                 uint8_t *p;
1776                 int32_t s;
1777
1778                 if (c <= 0177) {
1779                     /* pick rfield from operand b */
1780                     rflags = regflag(&ins->oprs[c & 7]);
1781                     rfield = regvals[ins->oprs[c & 7].basereg];
1782                 } else {
1783                     /* rfield is constant */
1784                     rflags = 0;
1785                     rfield = c & 7;
1786                 }
1787
1788                 if (!process_ea
1789                     (&ins->oprs[(c >> 3) & 7], &ea_data, bits,
1790                      ins->addr_size, rfield, rflags, ins->forw_ref)) {
1791                     errfunc(ERR_NONFATAL, "invalid effective address");
1792                 }
1793
1794
1795                 p = bytes;
1796                 *p++ = ea_data.modrm;
1797                 if (ea_data.sib_present)
1798                     *p++ = ea_data.sib;
1799
1800                 /* DREX suffixes come between the SIB and the displacement */
1801                 if (ins->rex & REX_D) {
1802                     *p++ =
1803                         (ins->drexdst << 4) |
1804                         (ins->rex & REX_OC ? 0x08 : 0) |
1805                         (ins->rex & (REX_R|REX_X|REX_B));
1806                     ins->rex = 0;
1807                 }
1808
1809                 s = p - bytes;
1810                 out(offset, segment, bytes, OUT_RAWDATA, s, NO_SEG, NO_SEG);
1811
1812                 switch (ea_data.bytes) {
1813                 case 0:
1814                     break;
1815                 case 1:
1816                     if (ins->oprs[(c >> 3) & 7].segment != NO_SEG) {
1817                         data = ins->oprs[(c >> 3) & 7].offset;
1818                         out(offset, segment, &data, OUT_ADDRESS, 1,
1819                             ins->oprs[(c >> 3) & 7].segment,
1820                             ins->oprs[(c >> 3) & 7].wrt);
1821                     } else {
1822                         *bytes = ins->oprs[(c >> 3) & 7].offset;
1823                         out(offset, segment, bytes, OUT_RAWDATA, 1,
1824                             NO_SEG, NO_SEG);
1825                     }
1826                     s++;
1827                     break;
1828                 case 8:
1829                 case 2:
1830                 case 4:
1831                     data = ins->oprs[(c >> 3) & 7].offset;
1832                     warn_overflow(ea_data.bytes, data);
1833                     out(offset, segment, &data,
1834                         ea_data.rip ?  OUT_REL4ADR : OUT_ADDRESS,
1835                         ea_data.bytes,
1836                         ins->oprs[(c >> 3) & 7].segment,
1837                         ins->oprs[(c >> 3) & 7].wrt);
1838                     s += ea_data.bytes;
1839                     break;
1840                 }
1841                 offset += s;
1842             } else {
1843                 errfunc(ERR_PANIC, "internal instruction table corrupt"
1844                         ": instruction code 0x%02X given", c);
1845             }
1846         }
1847     }
1848 }
1849
1850 static int32_t regflag(const operand * o)
1851 {
1852     if (o->basereg < EXPR_REG_START || o->basereg >= REG_ENUM_LIMIT) {
1853         errfunc(ERR_PANIC, "invalid operand passed to regflag()");
1854     }
1855     return reg_flags[o->basereg];
1856 }
1857
1858 static int32_t regval(const operand * o)
1859 {
1860     if (o->basereg < EXPR_REG_START || o->basereg >= REG_ENUM_LIMIT) {
1861         errfunc(ERR_PANIC, "invalid operand passed to regval()");
1862     }
1863     return regvals[o->basereg];
1864 }
1865
1866 static int op_rexflags(const operand * o, int mask)
1867 {
1868     int32_t flags;
1869     int val;
1870
1871     if (o->basereg < EXPR_REG_START || o->basereg >= REG_ENUM_LIMIT) {
1872         errfunc(ERR_PANIC, "invalid operand passed to op_rexflags()");
1873     }
1874
1875     flags = reg_flags[o->basereg];
1876     val = regvals[o->basereg];
1877
1878     return rexflags(val, flags, mask);
1879 }
1880
1881 static int rexflags(int val, int32_t flags, int mask)
1882 {
1883     int rex = 0;
1884
1885     if (val >= 8)
1886         rex |= REX_B|REX_X|REX_R;
1887     if (flags & BITS64)
1888         rex |= REX_W;
1889     if (!(REG_HIGH & ~flags))   /* AH, CH, DH, BH */
1890         rex |= REX_H;
1891     else if (!(REG8 & ~flags) && val >= 4) /* SPL, BPL, SIL, DIL */
1892         rex |= REX_P;
1893
1894     return rex & mask;
1895 }
1896
1897 static int matches(const struct itemplate *itemp, insn * instruction, int bits)
1898 {
1899     int i, size[MAX_OPERANDS], asize, oprs, ret;
1900
1901     ret = 100;
1902
1903     /*
1904      * Check the opcode
1905      */
1906     if (itemp->opcode != instruction->opcode)
1907         return 0;
1908
1909     /*
1910      * Count the operands
1911      */
1912     if (itemp->operands != instruction->operands)
1913         return 0;
1914
1915     /*
1916      * Check that no spurious colons or TOs are present
1917      */
1918     for (i = 0; i < itemp->operands; i++)
1919         if (instruction->oprs[i].type & ~itemp->opd[i] & (COLON | TO))
1920             return 0;
1921
1922     /*
1923      * Process size flags
1924      */
1925     if (itemp->flags & IF_ARMASK) {
1926         memset(size, 0, sizeof size);
1927
1928         i = ((itemp->flags & IF_ARMASK) >> IF_ARSHFT) - 1;
1929
1930         switch (itemp->flags & IF_SMASK) {
1931         case IF_SB:
1932             size[i] = BITS8;
1933             break;
1934         case IF_SW:
1935             size[i] = BITS16;
1936             break;
1937         case IF_SD:
1938             size[i] = BITS32;
1939             break;
1940         case IF_SQ:
1941             size[i] = BITS64;
1942             break;
1943         case IF_SO:
1944             size[i] = BITS128;
1945             break;
1946         case IF_SZ:
1947             switch (bits) {
1948             case 16:
1949                 size[i] = BITS16;
1950                 break;
1951             case 32:
1952                 size[i] = BITS32;
1953                 break;
1954             case 64:
1955                 size[i] = BITS64;
1956                 break;
1957             }
1958             break;
1959         default:
1960             break;
1961         }
1962     } else {
1963         asize = 0;
1964         switch (itemp->flags & IF_SMASK) {
1965         case IF_SB:
1966             asize = BITS8;
1967             break;
1968         case IF_SW:
1969             asize = BITS16;
1970             break;
1971         case IF_SD:
1972             asize = BITS32;
1973             break;
1974         case IF_SQ:
1975             asize = BITS64;
1976             break;
1977         case IF_SO:
1978             asize = BITS128;
1979             break;
1980         case IF_SZ:
1981             switch (bits) {
1982             case 16:
1983                 asize = BITS16;
1984                 break;
1985             case 32:
1986                 asize = BITS32;
1987                 break;
1988             case 64:
1989                 asize = BITS64;
1990                 break;
1991             }
1992             break;
1993         default:
1994             break;
1995         }
1996         for (i = 0; i < MAX_OPERANDS; i++)
1997             size[i] = asize;
1998     }
1999
2000     /*
2001      * Check that the operand flags all match up
2002      */
2003     for (i = 0; i < itemp->operands; i++) {
2004         int32_t type = instruction->oprs[i].type;
2005         if (!(type & SIZE_MASK))
2006             type |= size[i];
2007
2008         if (itemp->opd[i] & SAME_AS) {
2009             int j = itemp->opd[i] & ~SAME_AS;
2010             if (type != instruction->oprs[j].type ||
2011                 instruction->oprs[i].basereg != instruction->oprs[j].basereg)
2012                 return 0;
2013         } else if (itemp->opd[i] & ~type ||
2014             ((itemp->opd[i] & SIZE_MASK) &&
2015              ((itemp->opd[i] ^ type) & SIZE_MASK))) {
2016             if ((itemp->opd[i] & ~type & ~SIZE_MASK) ||
2017                 (type & SIZE_MASK))
2018                 return 0;
2019             else
2020                 return 1;
2021         }
2022     }
2023
2024     /*
2025      * Check operand sizes
2026      */
2027     if (itemp->flags & (IF_SM | IF_SM2)) {
2028         oprs = (itemp->flags & IF_SM2 ? 2 : itemp->operands);
2029         asize = 0;
2030         for (i = 0; i < oprs; i++) {
2031             if ((asize = itemp->opd[i] & SIZE_MASK) != 0) {
2032                 int j;
2033                 for (j = 0; j < oprs; j++)
2034                     size[j] = asize;
2035                 break;
2036             }
2037         }
2038     } else {
2039         oprs = itemp->operands;
2040     }
2041
2042     for (i = 0; i < itemp->operands; i++) {
2043         if (!(itemp->opd[i] & SIZE_MASK) &&
2044             (instruction->oprs[i].type & SIZE_MASK & ~size[i]))
2045             return 2;
2046     }
2047
2048     /*
2049      * Check template is okay at the set cpu level
2050      */
2051     if (((itemp->flags & IF_PLEVEL) > cpu))
2052         return 3;
2053
2054     /*
2055      * Check if instruction is available in long mode
2056      */
2057     if ((itemp->flags & IF_NOLONG) && (bits == 64))
2058         return 4;
2059
2060     /*
2061      * Check if special handling needed for Jumps
2062      */
2063     if ((uint8_t)(itemp->code[0]) >= 0370)
2064         return 99;
2065
2066     return ret;
2067 }
2068
2069 static ea *process_ea(operand * input, ea * output, int bits,
2070                       int addrbits, int rfield, int32_t rflags, int forw_ref)
2071 {
2072     output->rip = false;
2073
2074     /* REX flags for the rfield operand */
2075     output->rex |= rexflags(rfield, rflags, REX_R|REX_P|REX_W|REX_H);
2076
2077     if (!(REGISTER & ~input->type)) {   /* register direct */
2078         int i;
2079         int32_t f;
2080
2081         if (input->basereg < EXPR_REG_START /* Verify as Register */
2082             || input->basereg >= REG_ENUM_LIMIT)
2083             return NULL;
2084         f = regflag(input);
2085         i = regvals[input->basereg];
2086
2087         if (REG_EA & ~f)
2088             return NULL;        /* Invalid EA register */
2089
2090         output->rex |= op_rexflags(input, REX_B|REX_P|REX_W|REX_H);
2091
2092         output->sib_present = false;             /* no SIB necessary */
2093         output->bytes = 0;  /* no offset necessary either */
2094         output->modrm = 0xC0 | ((rfield & 7) << 3) | (i & 7);
2095     } else {                    /* it's a memory reference */
2096         if (input->basereg == -1
2097             && (input->indexreg == -1 || input->scale == 0)) {
2098             /* it's a pure offset */
2099             if (bits == 64 && (~input->type & IP_REL)) {
2100               int scale, index, base;
2101               output->sib_present = true;
2102               scale = 0;
2103               index = 4;
2104               base = 5;
2105               output->sib = (scale << 6) | (index << 3) | base;
2106               output->bytes = 4;
2107               output->modrm = 4 | ((rfield & 7) << 3);
2108               output->rip = false;
2109             } else {
2110               output->sib_present = false;
2111               output->bytes = (addrbits != 16 ? 4 : 2);
2112               output->modrm = (addrbits != 16 ? 5 : 6) | ((rfield & 7) << 3);
2113               output->rip = bits == 64;
2114             }
2115         } else {                /* it's an indirection */
2116             int i = input->indexreg, b = input->basereg, s = input->scale;
2117             int32_t o = input->offset, seg = input->segment;
2118             int hb = input->hintbase, ht = input->hinttype;
2119             int t;
2120             int it, bt;
2121             int32_t ix, bx;     /* register flags */
2122
2123             if (s == 0)
2124                 i = -1;         /* make this easy, at least */
2125
2126             if (i >= EXPR_REG_START && i < REG_ENUM_LIMIT) {
2127                 it = regvals[i];
2128                 ix = reg_flags[i];
2129             } else {
2130                 it = -1;
2131                 ix = 0;
2132             }
2133
2134             if (b >= EXPR_REG_START && b < REG_ENUM_LIMIT) {
2135                 bt = regvals[b];
2136                 bx = reg_flags[b];
2137             } else {
2138                 bt = -1;
2139                 bx = 0;
2140             }
2141
2142             /* check for a 32/64-bit memory reference... */
2143             if ((ix|bx) & (BITS32|BITS64)) {
2144                 /* it must be a 32/64-bit memory reference. Firstly we have
2145                  * to check that all registers involved are type E/Rxx. */
2146                 int32_t sok = BITS32|BITS64;
2147
2148                 if (it != -1) {
2149                     if (!(REG64 & ~ix) || !(REG32 & ~ix))
2150                         sok &= ix;
2151                     else
2152                         return NULL;
2153                 }
2154
2155                 if (bt != -1) {
2156                     if (REG_GPR & ~bx)
2157                         return NULL; /* Invalid register */
2158                     if (~sok & bx & SIZE_MASK)
2159                         return NULL; /* Invalid size */
2160                     sok &= bx;
2161                 }
2162
2163                 /* While we're here, ensure the user didn't specify
2164                    WORD or QWORD. */
2165                 if (input->disp_size == 16 || input->disp_size == 64)
2166                     return NULL;
2167
2168                 if (addrbits == 16 ||
2169                     (addrbits == 32 && !(sok & BITS32)) ||
2170                     (addrbits == 64 && !(sok & BITS64)))
2171                     return NULL;
2172
2173                 /* now reorganize base/index */
2174                 if (s == 1 && bt != it && bt != -1 && it != -1 &&
2175                     ((hb == b && ht == EAH_NOTBASE)
2176                      || (hb == i && ht == EAH_MAKEBASE))) {
2177                     /* swap if hints say so */
2178                     t = bt, bt = it, it = t;
2179                     t = bx, bx = ix, ix = t;
2180                 }
2181                 if (bt == it)     /* convert EAX+2*EAX to 3*EAX */
2182                     bt = -1, bx = 0, s++;
2183                 if (bt == -1 && s == 1 && !(hb == it && ht == EAH_NOTBASE)) {
2184                     /* make single reg base, unless hint */
2185                     bt = it, bx = ix, it = -1, ix = 0;
2186                 }
2187                 if (((s == 2 && it != REG_NUM_ESP
2188                       && !(input->eaflags & EAF_TIMESTWO)) || s == 3
2189                      || s == 5 || s == 9) && bt == -1)
2190                     bt = it, bx = ix, s--; /* convert 3*EAX to EAX+2*EAX */
2191                 if (it == -1 && (bt & 7) != REG_NUM_ESP
2192                     && (input->eaflags & EAF_TIMESTWO))
2193                     it = bt, ix = bx, bt = -1, bx = 0, s = 1;
2194                 /* convert [NOSPLIT EAX] to sib format with 0x0 displacement */
2195                 if (s == 1 && it == REG_NUM_ESP) {
2196                     /* swap ESP into base if scale is 1 */
2197                     t = it, it = bt, bt = t;
2198                     t = ix, ix = bx, bx = t;
2199                 }
2200                 if (it == REG_NUM_ESP
2201                     || (s != 1 && s != 2 && s != 4 && s != 8 && it != -1))
2202                     return NULL;        /* wrong, for various reasons */
2203
2204                 output->rex |= rexflags(it, ix, REX_X);
2205                 output->rex |= rexflags(bt, bx, REX_B);
2206
2207                 if (it == -1 && (bt & 7) != REG_NUM_ESP) {
2208                     /* no SIB needed */
2209                     int mod, rm;
2210
2211                     if (bt == -1) {
2212                         rm = 5;
2213                         mod = 0;
2214                     } else {
2215                         rm = (bt & 7);
2216                         if (rm != REG_NUM_EBP && o == 0 &&
2217                                 seg == NO_SEG && !forw_ref &&
2218                                 !(input->eaflags &
2219                                   (EAF_BYTEOFFS | EAF_WORDOFFS)))
2220                             mod = 0;
2221                         else if (input->eaflags & EAF_BYTEOFFS ||
2222                                  (o >= -128 && o <= 127 && seg == NO_SEG
2223                                   && !forw_ref
2224                                   && !(input->eaflags & EAF_WORDOFFS)))
2225                             mod = 1;
2226                         else
2227                             mod = 2;
2228                     }
2229
2230                     output->sib_present = false;
2231                     output->bytes = (bt == -1 || mod == 2 ? 4 : mod);
2232                     output->modrm = (mod << 6) | ((rfield & 7) << 3) | rm;
2233                 } else {
2234                     /* we need a SIB */
2235                     int mod, scale, index, base;
2236
2237                     if (it == -1)
2238                         index = 4, s = 1;
2239                     else
2240                         index = (it & 7);
2241
2242                     switch (s) {
2243                     case 1:
2244                         scale = 0;
2245                         break;
2246                     case 2:
2247                         scale = 1;
2248                         break;
2249                     case 4:
2250                         scale = 2;
2251                         break;
2252                     case 8:
2253                         scale = 3;
2254                         break;
2255                     default:   /* then what the smeg is it? */
2256                         return NULL;    /* panic */
2257                     }
2258
2259                     if (bt == -1) {
2260                         base = 5;
2261                         mod = 0;
2262                     } else {
2263                         base = (bt & 7);
2264                         if (base != REG_NUM_EBP && o == 0 &&
2265                                     seg == NO_SEG && !forw_ref &&
2266                                     !(input->eaflags &
2267                                       (EAF_BYTEOFFS | EAF_WORDOFFS)))
2268                             mod = 0;
2269                         else if (input->eaflags & EAF_BYTEOFFS ||
2270                                  (o >= -128 && o <= 127 && seg == NO_SEG
2271                                   && !forw_ref
2272                                   && !(input->eaflags & EAF_WORDOFFS)))
2273                             mod = 1;
2274                         else
2275                             mod = 2;
2276                     }
2277
2278                     output->sib_present = true;
2279                     output->bytes =  (bt == -1 || mod == 2 ? 4 : mod);
2280                     output->modrm = (mod << 6) | ((rfield & 7) << 3) | 4;
2281                     output->sib = (scale << 6) | (index << 3) | base;
2282                 }
2283             } else {            /* it's 16-bit */
2284                 int mod, rm;
2285
2286                 /* check for 64-bit long mode */
2287                 if (addrbits == 64)
2288                     return NULL;
2289
2290                 /* check all registers are BX, BP, SI or DI */
2291                 if ((b != -1 && b != R_BP && b != R_BX && b != R_SI
2292                      && b != R_DI) || (i != -1 && i != R_BP && i != R_BX
2293                                        && i != R_SI && i != R_DI))
2294                     return NULL;
2295
2296                 /* ensure the user didn't specify DWORD/QWORD */
2297                 if (input->disp_size == 32 || input->disp_size == 64)
2298                     return NULL;
2299
2300                 if (s != 1 && i != -1)
2301                     return NULL;        /* no can do, in 16-bit EA */
2302                 if (b == -1 && i != -1) {
2303                     int tmp = b;
2304                     b = i;
2305                     i = tmp;
2306                 }               /* swap */
2307                 if ((b == R_SI || b == R_DI) && i != -1) {
2308                     int tmp = b;
2309                     b = i;
2310                     i = tmp;
2311                 }
2312                 /* have BX/BP as base, SI/DI index */
2313                 if (b == i)
2314                     return NULL;        /* shouldn't ever happen, in theory */
2315                 if (i != -1 && b != -1 &&
2316                     (i == R_BP || i == R_BX || b == R_SI || b == R_DI))
2317                     return NULL;        /* invalid combinations */
2318                 if (b == -1)    /* pure offset: handled above */
2319                     return NULL;        /* so if it gets to here, panic! */
2320
2321                 rm = -1;
2322                 if (i != -1)
2323                     switch (i * 256 + b) {
2324                     case R_SI * 256 + R_BX:
2325                         rm = 0;
2326                         break;
2327                     case R_DI * 256 + R_BX:
2328                         rm = 1;
2329                         break;
2330                     case R_SI * 256 + R_BP:
2331                         rm = 2;
2332                         break;
2333                     case R_DI * 256 + R_BP:
2334                         rm = 3;
2335                         break;
2336                 } else
2337                     switch (b) {
2338                     case R_SI:
2339                         rm = 4;
2340                         break;
2341                     case R_DI:
2342                         rm = 5;
2343                         break;
2344                     case R_BP:
2345                         rm = 6;
2346                         break;
2347                     case R_BX:
2348                         rm = 7;
2349                         break;
2350                     }
2351                 if (rm == -1)   /* can't happen, in theory */
2352                     return NULL;        /* so panic if it does */
2353
2354                 if (o == 0 && seg == NO_SEG && !forw_ref && rm != 6 &&
2355                     !(input->eaflags & (EAF_BYTEOFFS | EAF_WORDOFFS)))
2356                     mod = 0;
2357                 else if (input->eaflags & EAF_BYTEOFFS ||
2358                          (o >= -128 && o <= 127 && seg == NO_SEG
2359                           && !forw_ref
2360                           && !(input->eaflags & EAF_WORDOFFS)))
2361                     mod = 1;
2362                 else
2363                     mod = 2;
2364
2365                 output->sib_present = false;    /* no SIB - it's 16-bit */
2366                 output->bytes = mod;    /* bytes of offset needed */
2367                 output->modrm = (mod << 6) | ((rfield & 7) << 3) | rm;
2368             }
2369         }
2370     }
2371
2372     output->size = 1 + output->sib_present + output->bytes;
2373     return output;
2374 }
2375
2376 static void add_asp(insn *ins, int addrbits)
2377 {
2378     int j, valid;
2379     int defdisp;
2380
2381     valid = (addrbits == 64) ? 64|32 : 32|16;
2382
2383     switch (ins->prefixes[PPS_ASIZE]) {
2384     case P_A16:
2385         valid &= 16;
2386         break;
2387     case P_A32:
2388         valid &= 32;
2389         break;
2390     case P_A64:
2391         valid &= 64;
2392         break;
2393     case P_ASP:
2394         valid &= (addrbits == 32) ? 16 : 32;
2395         break;
2396     default:
2397         break;
2398     }
2399
2400     for (j = 0; j < ins->operands; j++) {
2401         if (!(MEMORY & ~ins->oprs[j].type)) {
2402             int32_t i, b;
2403
2404             /* Verify as Register */
2405             if (ins->oprs[j].indexreg < EXPR_REG_START
2406                 || ins->oprs[j].indexreg >= REG_ENUM_LIMIT)
2407                 i = 0;
2408             else
2409                 i = reg_flags[ins->oprs[j].indexreg];
2410
2411             /* Verify as Register */
2412             if (ins->oprs[j].basereg < EXPR_REG_START
2413                 || ins->oprs[j].basereg >= REG_ENUM_LIMIT)
2414                 b = 0;
2415             else
2416                 b = reg_flags[ins->oprs[j].basereg];
2417
2418             if (ins->oprs[j].scale == 0)
2419                 i = 0;
2420
2421             if (!i && !b) {
2422                 int ds = ins->oprs[j].disp_size;
2423                 if ((addrbits != 64 && ds > 8) ||
2424                     (addrbits == 64 && ds == 16))
2425                     valid &= ds;
2426             } else {
2427                 if (!(REG16 & ~b))
2428                     valid &= 16;
2429                 if (!(REG32 & ~b))
2430                     valid &= 32;
2431                 if (!(REG64 & ~b))
2432                     valid &= 64;
2433
2434                 if (!(REG16 & ~i))
2435                     valid &= 16;
2436                 if (!(REG32 & ~i))
2437                     valid &= 32;
2438                 if (!(REG64 & ~i))
2439                     valid &= 64;
2440             }
2441         }
2442     }
2443
2444     if (valid & addrbits) {
2445         ins->addr_size = addrbits;
2446     } else if (valid & ((addrbits == 32) ? 16 : 32)) {
2447         /* Add an address size prefix */
2448         enum prefixes pref = (addrbits == 32) ? P_A16 : P_A32;
2449         ins->prefixes[PPS_ASIZE] = pref;
2450         ins->addr_size = (addrbits == 32) ? 16 : 32;
2451     } else {
2452         /* Impossible... */
2453         errfunc(ERR_NONFATAL, "impossible combination of address sizes");
2454         ins->addr_size = addrbits; /* Error recovery */
2455     }
2456
2457     defdisp = ins->addr_size == 16 ? 16 : 32;
2458
2459     for (j = 0; j < ins->operands; j++) {
2460         if (!(MEM_OFFS & ~ins->oprs[j].type) &&
2461             (ins->oprs[j].disp_size ? ins->oprs[j].disp_size : defdisp)
2462             != ins->addr_size) {
2463             /* mem_offs sizes must match the address size; if not,
2464                strip the MEM_OFFS bit and match only EA instructions */
2465             ins->oprs[j].type &= ~(MEM_OFFS & ~MEMORY);
2466         }
2467     }
2468 }