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