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