Properly keep track of the base of relative relocations
[nasm.git] / asm / assemble.c
blobcaed64f015abef4ed13f852945c9754de6421c27
1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2017 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
9 * conditions are met:
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * ----------------------------------------------------------------------- */
35 * assemble.c code generation for the Netwide Assembler
37 * Bytecode specification
38 * ----------------------
41 * Codes Mnemonic Explanation
43 * \0 terminates the code. (Unless it's a literal of course.)
44 * \1..\4 that many literal bytes follow in the code stream
45 * \5 add 4 to the primary operand number (b, low octdigit)
46 * \6 add 4 to the secondary operand number (a, middle octdigit)
47 * \7 add 4 to both the primary and the secondary operand number
48 * \10..\13 a literal byte follows in the code stream, to be added
49 * to the register value of operand 0..3
50 * \14..\17 the position of index register operand in MIB (BND insns)
51 * \20..\23 ib a byte immediate operand, from operand 0..3
52 * \24..\27 ib,u a zero-extended byte immediate operand, from operand 0..3
53 * \30..\33 iw a word immediate operand, from operand 0..3
54 * \34..\37 iwd select between \3[0-3] and \4[0-3] depending on 16/32 bit
55 * assembly mode or the operand-size override on the operand
56 * \40..\43 id a long immediate operand, from operand 0..3
57 * \44..\47 iwdq select between \3[0-3], \4[0-3] and \5[4-7]
58 * depending on the address size of the instruction.
59 * \50..\53 rel8 a byte relative operand, from operand 0..3
60 * \54..\57 iq a qword immediate operand, from operand 0..3
61 * \60..\63 rel16 a word relative operand, from operand 0..3
62 * \64..\67 rel select between \6[0-3] and \7[0-3] depending on 16/32 bit
63 * assembly mode or the operand-size override on the operand
64 * \70..\73 rel32 a long relative operand, from operand 0..3
65 * \74..\77 seg a word constant, from the _segment_ part of operand 0..3
66 * \1ab a ModRM, calculated on EA in operand a, with the spare
67 * field the register value of operand b.
68 * \172\ab the register number from operand a in bits 7..4, with
69 * the 4-bit immediate from operand b in bits 3..0.
70 * \173\xab the register number from operand a in bits 7..4, with
71 * the value b in bits 3..0.
72 * \174..\177 the register number from operand 0..3 in bits 7..4, and
73 * an arbitrary value in bits 3..0 (assembled as zero.)
74 * \2ab a ModRM, calculated on EA in operand a, with the spare
75 * field equal to digit b.
77 * \240..\243 this instruction uses EVEX rather than REX or VEX/XOP, with the
78 * V field taken from operand 0..3.
79 * \250 this instruction uses EVEX rather than REX or VEX/XOP, with the
80 * V field set to 1111b.
82 * EVEX prefixes are followed by the sequence:
83 * \cm\wlp\tup where cm is:
84 * cc 00m mmm
85 * c = 2 for EVEX and mmmm is the M field (EVEX.P0[3:0])
86 * and wlp is:
87 * 00 wwl lpp
88 * [l0] ll = 0 (.128, .lz)
89 * [l1] ll = 1 (.256)
90 * [l2] ll = 2 (.512)
91 * [lig] ll = 3 for EVEX.L'L don't care (always assembled as 0)
93 * [w0] ww = 0 for W = 0
94 * [w1] ww = 1 for W = 1
95 * [wig] ww = 2 for W don't care (always assembled as 0)
96 * [ww] ww = 3 for W used as REX.W
98 * [p0] pp = 0 for no prefix
99 * [60] pp = 1 for legacy prefix 60
100 * [f3] pp = 2
101 * [f2] pp = 3
103 * tup is tuple type for Disp8*N from %tuple_codes in insns.pl
104 * (compressed displacement encoding)
106 * \254..\257 id,s a signed 32-bit operand to be extended to 64 bits.
107 * \260..\263 this instruction uses VEX/XOP rather than REX, with the
108 * V field taken from operand 0..3.
109 * \270 this instruction uses VEX/XOP rather than REX, with the
110 * V field set to 1111b.
112 * VEX/XOP prefixes are followed by the sequence:
113 * \tmm\wlp where mm is the M field; and wlp is:
114 * 00 wwl lpp
115 * [l0] ll = 0 for L = 0 (.128, .lz)
116 * [l1] ll = 1 for L = 1 (.256)
117 * [lig] ll = 2 for L don't care (always assembled as 0)
119 * [w0] ww = 0 for W = 0
120 * [w1 ] ww = 1 for W = 1
121 * [wig] ww = 2 for W don't care (always assembled as 0)
122 * [ww] ww = 3 for W used as REX.W
124 * t = 0 for VEX (C4/C5), t = 1 for XOP (8F).
126 * \271 hlexr instruction takes XRELEASE (F3) with or without lock
127 * \272 hlenl instruction takes XACQUIRE/XRELEASE with or without lock
128 * \273 hle instruction takes XACQUIRE/XRELEASE with lock only
129 * \274..\277 ib,s a byte immediate operand, from operand 0..3, sign-extended
130 * to the operand size (if o16/o32/o64 present) or the bit size
131 * \310 a16 indicates fixed 16-bit address size, i.e. optional 0x67.
132 * \311 a32 indicates fixed 32-bit address size, i.e. optional 0x67.
133 * \312 adf (disassembler only) invalid with non-default address size.
134 * \313 a64 indicates fixed 64-bit address size, 0x67 invalid.
135 * \314 norexb (disassembler only) invalid with REX.B
136 * \315 norexx (disassembler only) invalid with REX.X
137 * \316 norexr (disassembler only) invalid with REX.R
138 * \317 norexw (disassembler only) invalid with REX.W
139 * \320 o16 indicates fixed 16-bit operand size, i.e. optional 0x66.
140 * \321 o32 indicates fixed 32-bit operand size, i.e. optional 0x66.
141 * \322 odf indicates that this instruction is only valid when the
142 * operand size is the default (instruction to disassembler,
143 * generates no code in the assembler)
144 * \323 o64nw indicates fixed 64-bit operand size, REX on extensions only.
145 * \324 o64 indicates 64-bit operand size requiring REX prefix.
146 * \325 nohi instruction which always uses spl/bpl/sil/dil
147 * \326 nof3 instruction not valid with 0xF3 REP prefix. Hint for
148 disassembler only; for SSE instructions.
149 * \330 a literal byte follows in the code stream, to be added
150 * to the condition code value of the instruction.
151 * \331 norep instruction not valid with REP prefix. Hint for
152 * disassembler only; for SSE instructions.
153 * \332 f2i REP prefix (0xF2 byte) used as opcode extension.
154 * \333 f3i REP prefix (0xF3 byte) used as opcode extension.
155 * \334 rex.l LOCK prefix used as REX.R (used in non-64-bit mode)
156 * \335 repe disassemble a rep (0xF3 byte) prefix as repe not rep.
157 * \336 mustrep force a REP(E) prefix (0xF3) even if not specified.
158 * \337 mustrepne force a REPNE prefix (0xF2) even if not specified.
159 * \336-\337 are still listed as prefixes in the disassembler.
160 * \340 resb reserve <operand 0> bytes of uninitialized storage.
161 * Operand 0 had better be a segmentless constant.
162 * \341 wait this instruction needs a WAIT "prefix"
163 * \360 np no SSE prefix (== \364\331)
164 * \361 66 SSE prefix (== \366\331)
165 * \364 !osp operand-size prefix (0x66) not permitted
166 * \365 !asp address-size prefix (0x67) not permitted
167 * \366 operand-size prefix (0x66) used as opcode extension
168 * \367 address-size prefix (0x67) used as opcode extension
169 * \370,\371 jcc8 match only if operand 0 meets byte jump criteria.
170 * jmp8 370 is used for Jcc, 371 is used for JMP.
171 * \373 jlen assemble 0x03 if bits==16, 0x05 if bits==32;
172 * used for conditional jump over longer jump
173 * \374 vsibx|vm32x|vm64x this instruction takes an XMM VSIB memory EA
174 * \375 vsiby|vm32y|vm64y this instruction takes an YMM VSIB memory EA
175 * \376 vsibz|vm32z|vm64z this instruction takes an ZMM VSIB memory EA
178 #include "compiler.h"
180 #include <stdio.h>
181 #include <string.h>
182 #include <stdlib.h>
184 #include "nasm.h"
185 #include "nasmlib.h"
186 #include "assemble.h"
187 #include "insns.h"
188 #include "tables.h"
189 #include "disp8.h"
190 #include "listing.h"
192 enum match_result {
194 * Matching errors. These should be sorted so that more specific
195 * errors come later in the sequence.
197 MERR_INVALOP,
198 MERR_OPSIZEMISSING,
199 MERR_OPSIZEMISMATCH,
200 MERR_BRNUMMISMATCH,
201 MERR_BADCPU,
202 MERR_BADMODE,
203 MERR_BADHLE,
204 MERR_ENCMISMATCH,
205 MERR_BADBND,
206 MERR_BADREPNE,
208 * Matching success; the conditional ones first
210 MOK_JUMP, /* Matching OK but needs jmp_match() */
211 MOK_GOOD /* Matching unconditionally OK */
214 typedef struct {
215 enum ea_type type; /* what kind of EA is this? */
216 int sib_present; /* is a SIB byte necessary? */
217 int bytes; /* # of bytes of offset needed */
218 int size; /* lazy - this is sib+bytes+1 */
219 uint8_t modrm, sib, rex, rip; /* the bytes themselves */
220 int8_t disp8; /* compressed displacement for EVEX */
221 } ea;
223 #define GEN_SIB(scale, index, base) \
224 (((scale) << 6) | ((index) << 3) | ((base)))
226 #define GEN_MODRM(mod, reg, rm) \
227 (((mod) << 6) | (((reg) & 7) << 3) | ((rm) & 7))
229 static iflag_t cpu; /* cpu level received from nasm.c */
231 static int64_t calcsize(int32_t, int64_t, int, insn *,
232 const struct itemplate *);
233 static int emit_prefix(struct out_data *data, const int bits, insn *ins);
234 static void gencode(struct out_data *data, insn *ins);
235 static enum match_result find_match(const struct itemplate **tempp,
236 insn *instruction,
237 int32_t segment, int64_t offset, int bits);
238 static enum match_result matches(const struct itemplate *, insn *, int bits);
239 static opflags_t regflag(const operand *);
240 static int32_t regval(const operand *);
241 static int rexflags(int, opflags_t, int);
242 static int op_rexflags(const operand *, int);
243 static int op_evexflags(const operand *, int, uint8_t);
244 static void add_asp(insn *, int);
246 static enum ea_type process_ea(operand *, ea *, int, int, opflags_t, insn *);
248 static inline bool absolute_op(const struct operand *o)
250 return o->segment == NO_SEG && o->wrt == NO_SEG &&
251 !(o->opflags & OPFLAG_RELATIVE);
254 static int has_prefix(insn * ins, enum prefix_pos pos, int prefix)
256 return ins->prefixes[pos] == prefix;
259 static void assert_no_prefix(insn * ins, enum prefix_pos pos)
261 if (ins->prefixes[pos])
262 nasm_error(ERR_NONFATAL, "invalid %s prefix",
263 prefix_name(ins->prefixes[pos]));
266 static const char *size_name(int size)
268 switch (size) {
269 case 1:
270 return "byte";
271 case 2:
272 return "word";
273 case 4:
274 return "dword";
275 case 8:
276 return "qword";
277 case 10:
278 return "tword";
279 case 16:
280 return "oword";
281 case 32:
282 return "yword";
283 case 64:
284 return "zword";
285 default:
286 return "???";
290 static void warn_overflow(int pass, int size)
292 nasm_error(ERR_WARNING | pass | ERR_WARN_NOV,
293 "%s data exceeds bounds", size_name(size));
296 static void warn_overflow_const(int64_t data, int size)
298 if (overflow_general(data, size))
299 warn_overflow(ERR_PASS1, size);
302 static void warn_overflow_opd(const struct operand *o, int size)
304 if (absolute_op(o)) {
305 if (overflow_general(o->offset, size))
306 warn_overflow(ERR_PASS2, size);
310 static void warn_overflow_out(int64_t data, int size, enum out_sign sign)
312 bool err;
314 switch (sign) {
315 case OUT_WRAP:
316 err = overflow_general(data, size);
317 break;
318 case OUT_SIGNED:
319 err = overflow_signed(data, size);
320 break;
321 case OUT_UNSIGNED:
322 err = overflow_unsigned(data, size);
323 break;
324 default:
325 panic();
326 break;
329 if (err)
330 warn_overflow(ERR_PASS2, size);
334 * This routine wrappers the real output format's output routine,
335 * in order to pass a copy of the data off to the listing file
336 * generator at the same time, flatten unnecessary relocations,
337 * and verify backend compatibility.
339 static void out(struct out_data *data)
341 static int32_t lineno = 0; /* static!!! */
342 static const char *lnfname = NULL;
343 int asize;
344 const int amax = ofmt->maxbits >> 3; /* Maximum address size in bytes */
345 union {
346 uint8_t b[8];
347 uint64_t q;
348 } xdata;
349 uint64_t size = data->size;
350 int64_t addrval;
352 if (!data->size)
353 return; /* Nothing to do */
356 * Convert addresses to RAWDATA if possible
357 * XXX: not all backends want this for global symbols!!!!
359 switch (data->type) {
360 case OUT_ADDRESS:
361 addrval = data->toffset;
362 goto address;
364 case OUT_RELADDR:
365 addrval = data->toffset - data->relbase;
366 goto address;
368 address:
369 asize = data->size;
370 nasm_assert(asize <= 8);
371 if (data->tsegment == NO_SEG && data->twrt == NO_SEG) {
372 uint8_t *q = xdata.b;
374 warn_overflow_out(addrval, asize, data->sign);
376 WRITEADDR(q, addrval, asize);
377 data->data = xdata.b;
378 data->type = OUT_RAWDATA;
379 asize = 0; /* No longer an address */
381 break;
383 default:
384 asize = 0; /* Not an address */
385 break;
388 lfmt->output(data);
391 * this call to src_get determines when we call the
392 * debug-format-specific "linenum" function
393 * it updates lineno and lnfname to the current values
394 * returning 0 if "same as last time", -2 if lnfname
395 * changed, and the amount by which lineno changed,
396 * if it did. thus, these variables must be static
399 if (src_get(&lineno, &lnfname))
400 dfmt->linenum(lnfname, lineno, data->segment);
402 if (asize && asize > amax) {
403 if (data->type != OUT_ADDRESS || data->sign == OUT_SIGNED) {
404 nasm_error(ERR_NONFATAL,
405 "%d-bit signed relocation unsupported by output format %s\n",
406 asize << 3, ofmt->shortname);
407 } else {
408 nasm_error(ERR_WARNING | ERR_WARN_ZEXTRELOC,
409 "%d-bit unsigned relocation zero-extended from %d bits\n",
410 asize << 3, ofmt->maxbits);
411 data->size = amax;
412 ofmt->output(data);
413 data->insoffs += amax;
414 data->offset += amax;
415 data->size = size = asize - amax;
417 data->data = zero_buffer;
418 data->type = OUT_RAWDATA;
421 ofmt->output(data);
422 data->offset += size;
423 data->insoffs += size;
426 static inline void out_rawdata(struct out_data *data, const void *rawdata,
427 size_t size)
429 data->type = OUT_RAWDATA;
430 data->data = rawdata;
431 data->size = size;
432 out(data);
435 static void out_rawbyte(struct out_data *data, uint8_t byte)
437 data->type = OUT_RAWDATA;
438 data->data = &byte;
439 data->size = 1;
440 out(data);
443 static inline void out_reserve(struct out_data *data, uint64_t size)
445 data->type = OUT_RESERVE;
446 data->size = size;
447 out(data);
450 static inline void out_imm(struct out_data *data, const struct operand *opx,
451 int size, enum out_sign sign)
453 data->type =
454 (opx->opflags & OPFLAG_RELATIVE) ? OUT_RELADDR : OUT_ADDRESS;
455 data->sign = sign;
456 data->size = size;
457 data->toffset = opx->offset;
458 data->tsegment = opx->segment;
459 data->twrt = opx->wrt;
461 * XXX: improve this if at some point in the future we can
462 * distinguish the subtrahend in expressions like [foo - bar]
463 * where bar is a symbol in the current segment. However, at the
464 * current point, if OPFLAG_RELATIVE is set that subtraction has
465 * already occurred.
467 data->relbase = 0;
468 out(data);
471 static void out_reladdr(struct out_data *data, const struct operand *opx,
472 int size)
474 if (opx->opflags & OPFLAG_RELATIVE)
475 nasm_error(ERR_NONFATAL, "invalid use of self-relative expression");
477 data->type = OUT_RELADDR;
478 data->sign = OUT_SIGNED;
479 data->size = size;
480 data->toffset = opx->offset;
481 data->tsegment = opx->segment;
482 data->twrt = opx->wrt;
483 data->relbase = data->offset + (data->inslen - data->insoffs);
484 out(data);
487 static inline void out_segment(struct out_data *data,
488 const struct operand *opx)
490 data->type = OUT_SEGMENT;
491 data->sign = OUT_UNSIGNED;
492 data->size = 2;
493 data->toffset = opx->offset;
494 data->tsegment = ofmt->segbase(opx->segment + 1);
495 data->twrt = opx->wrt;
496 out(data);
499 static bool jmp_match(int32_t segment, int64_t offset, int bits,
500 insn * ins, const struct itemplate *temp)
502 int64_t isize;
503 const uint8_t *code = temp->code;
504 uint8_t c = code[0];
505 bool is_byte;
507 if (((c & ~1) != 0370) || (ins->oprs[0].type & STRICT))
508 return false;
509 if (!optimizing)
510 return false;
511 if (optimizing < 0 && c == 0371)
512 return false;
514 isize = calcsize(segment, offset, bits, ins, temp);
516 if (ins->oprs[0].opflags & OPFLAG_UNKNOWN)
517 /* Be optimistic in pass 1 */
518 return true;
520 if (ins->oprs[0].segment != segment)
521 return false;
523 isize = ins->oprs[0].offset - offset - isize; /* isize is delta */
524 is_byte = (isize >= -128 && isize <= 127); /* is it byte size? */
526 if (is_byte && c == 0371 && ins->prefixes[PPS_REP] == P_BND) {
527 /* jmp short (opcode eb) cannot be used with bnd prefix. */
528 ins->prefixes[PPS_REP] = P_none;
529 nasm_error(ERR_WARNING | ERR_WARN_BND | ERR_PASS2 ,
530 "jmp short does not init bnd regs - bnd prefix dropped.");
533 return is_byte;
536 /* This is totally just a wild guess what is reasonable... */
537 #define INCBIN_MAX_BUF (ZERO_BUF_SIZE * 16)
539 int64_t assemble(int32_t segment, int64_t start, int bits, iflag_t cp,
540 insn * instruction)
542 struct out_data data;
543 const struct itemplate *temp;
544 enum match_result m;
545 int32_t itimes;
546 int64_t wsize; /* size for DB etc. */
548 cpu = cp;
550 nasm_zero(&data);
551 data.offset = start;
552 data.segment = segment;
553 data.itemp = NULL;
554 data.sign = OUT_WRAP;
555 data.bits = bits;
557 wsize = idata_bytes(instruction->opcode);
558 if (wsize == -1)
559 return 0;
561 if (wsize) {
562 extop *e;
563 int32_t t = instruction->times;
564 if (t < 0)
565 nasm_panic(0, "instruction->times < 0 (%"PRId32") in assemble()", t);
567 while (t--) { /* repeat TIMES times */
568 list_for_each(e, instruction->eops) {
569 if (e->type == EOT_DB_NUMBER) {
570 if (wsize > 8) {
571 nasm_error(ERR_NONFATAL,
572 "integer supplied to a DT, DO or DY"
573 " instruction");
574 } else {
575 data.insoffs = 0;
576 data.type = e->relative ? OUT_RELADDR : OUT_ADDRESS;
577 data.inslen = data.size = wsize;
578 data.toffset = e->offset;
579 data.tsegment = e->segment;
580 data.twrt = e->wrt;
581 data.relbase = 0;
582 out(&data);
584 } else if (e->type == EOT_DB_STRING ||
585 e->type == EOT_DB_STRING_FREE) {
586 int align = e->stringlen % wsize;
587 if (align)
588 align = wsize - align;
590 data.insoffs = 0;
591 data.inslen = e->stringlen + align;
593 out_rawdata(&data, e->stringval, e->stringlen);
594 out_rawdata(&data, zero_buffer, align);
597 if (t > 0 && t == instruction->times - 1) {
598 lfmt->set_offset(data.offset);
599 lfmt->uplevel(LIST_TIMES);
602 if (instruction->times > 1)
603 lfmt->downlevel(LIST_TIMES);
604 } else if (instruction->opcode == I_INCBIN) {
605 const char *fname = instruction->eops->stringval;
606 FILE *fp;
607 size_t t = instruction->times;
608 off_t base = 0;
609 off_t len;
610 const void *map = NULL;
611 char *buf = NULL;
612 size_t blk = 0; /* Buffered I/O block size */
613 size_t m = 0; /* Bytes last read */
615 fp = nasm_open_read(fname, NF_BINARY|NF_FORMAP);
616 if (!fp) {
617 nasm_error(ERR_NONFATAL, "`incbin': unable to open file `%s'",
618 fname);
619 goto done;
622 len = nasm_file_size(fp);
624 if (len == (off_t)-1) {
625 nasm_error(ERR_NONFATAL, "`incbin': unable to get length of file `%s'",
626 fname);
627 goto close_done;
630 if (instruction->eops->next) {
631 base = instruction->eops->next->offset;
632 if (base >= len) {
633 len = 0;
634 } else {
635 len -= base;
636 if (instruction->eops->next->next &&
637 len > (off_t)instruction->eops->next->next->offset)
638 len = (off_t)instruction->eops->next->next->offset;
642 lfmt->set_offset(data.offset);
643 lfmt->uplevel(LIST_INCBIN);
645 if (!len)
646 goto end_incbin;
648 /* Try to map file data */
649 map = nasm_map_file(fp, base, len);
650 if (!map) {
651 blk = len < (off_t)INCBIN_MAX_BUF ? (size_t)len : INCBIN_MAX_BUF;
652 buf = nasm_malloc(blk);
655 while (t--) {
657 * Consider these irrelevant for INCBIN, since it is fully
658 * possible that these might be (way) bigger than an int
659 * can hold; there is, however, no reason to widen these
660 * types just for INCBIN. data.inslen == 0 signals to the
661 * backend that these fields are meaningless, if at all
662 * needed.
664 data.insoffs = 0;
665 data.inslen = 0;
667 if (map) {
668 out_rawdata(&data, map, len);
669 } else if ((off_t)m == len) {
670 out_rawdata(&data, buf, len);
671 } else {
672 off_t l = len;
674 if (fseeko(fp, base, SEEK_SET) < 0 || ferror(fp)) {
675 nasm_error(ERR_NONFATAL,
676 "`incbin': unable to seek on file `%s'",
677 fname);
678 goto end_incbin;
680 while (l > 0) {
681 m = fread(buf, 1, l < (off_t)blk ? (size_t)l : blk, fp);
682 if (!m || feof(fp)) {
684 * This shouldn't happen unless the file
685 * actually changes while we are reading
686 * it.
688 nasm_error(ERR_NONFATAL,
689 "`incbin': unexpected EOF while"
690 " reading file `%s'", fname);
691 goto end_incbin;
693 out_rawdata(&data, buf, m);
694 l -= m;
698 end_incbin:
699 lfmt->downlevel(LIST_INCBIN);
700 if (instruction->times > 1) {
701 lfmt->set_offset(data.offset);
702 lfmt->uplevel(LIST_TIMES);
703 lfmt->downlevel(LIST_TIMES);
705 if (ferror(fp)) {
706 nasm_error(ERR_NONFATAL,
707 "`incbin': error while"
708 " reading file `%s'", fname);
710 close_done:
711 if (buf)
712 nasm_free(buf);
713 if (map)
714 nasm_unmap_file(map, len);
715 fclose(fp);
716 done:
718 } else {
719 /* "Real" instruction */
721 /* Check to see if we need an address-size prefix */
722 add_asp(instruction, bits);
724 m = find_match(&temp, instruction, data.segment, data.offset, bits);
726 if (m == MOK_GOOD) {
727 /* Matches! */
728 int64_t insn_size = calcsize(data.segment, data.offset,
729 bits, instruction, temp);
730 itimes = instruction->times;
731 if (insn_size < 0) /* shouldn't be, on pass two */
732 nasm_panic(0, "errors made it through from pass one");
734 data.itemp = temp;
735 data.bits = bits;
737 while (itimes--) {
738 data.insoffs = 0;
739 data.inslen = insn_size;
741 gencode(&data, instruction);
742 nasm_assert(data.insoffs == insn_size);
744 if (itimes > 0 && itimes == instruction->times - 1) {
745 lfmt->set_offset(data.offset);
746 lfmt->uplevel(LIST_TIMES);
749 if (instruction->times > 1)
750 lfmt->downlevel(LIST_TIMES);
751 } else {
752 /* No match */
753 switch (m) {
754 case MERR_OPSIZEMISSING:
755 nasm_error(ERR_NONFATAL, "operation size not specified");
756 break;
757 case MERR_OPSIZEMISMATCH:
758 nasm_error(ERR_NONFATAL, "mismatch in operand sizes");
759 break;
760 case MERR_BRNUMMISMATCH:
761 nasm_error(ERR_NONFATAL,
762 "mismatch in the number of broadcasting elements");
763 break;
764 case MERR_BADCPU:
765 nasm_error(ERR_NONFATAL, "no instruction for this cpu level");
766 break;
767 case MERR_BADMODE:
768 nasm_error(ERR_NONFATAL, "instruction not supported in %d-bit mode",
769 bits);
770 break;
771 case MERR_ENCMISMATCH:
772 nasm_error(ERR_NONFATAL, "specific encoding scheme not available");
773 break;
774 case MERR_BADBND:
775 nasm_error(ERR_NONFATAL, "bnd prefix is not allowed");
776 break;
777 case MERR_BADREPNE:
778 nasm_error(ERR_NONFATAL, "%s prefix is not allowed",
779 (has_prefix(instruction, PPS_REP, P_REPNE) ?
780 "repne" : "repnz"));
781 break;
782 default:
783 nasm_error(ERR_NONFATAL,
784 "invalid combination of opcode and operands");
785 break;
789 return data.offset - start;
792 int64_t insn_size(int32_t segment, int64_t offset, int bits, iflag_t cp,
793 insn * instruction)
795 const struct itemplate *temp;
796 enum match_result m;
798 cpu = cp;
800 if (instruction->opcode == I_none)
801 return 0;
803 if (instruction->opcode == I_DB || instruction->opcode == I_DW ||
804 instruction->opcode == I_DD || instruction->opcode == I_DQ ||
805 instruction->opcode == I_DT || instruction->opcode == I_DO ||
806 instruction->opcode == I_DY) {
807 extop *e;
808 int32_t isize, osize, wsize;
810 isize = 0;
811 wsize = idata_bytes(instruction->opcode);
813 list_for_each(e, instruction->eops) {
814 int32_t align;
816 osize = 0;
817 if (e->type == EOT_DB_NUMBER) {
818 osize = 1;
819 warn_overflow_const(e->offset, wsize);
820 } else if (e->type == EOT_DB_STRING ||
821 e->type == EOT_DB_STRING_FREE)
822 osize = e->stringlen;
824 align = (-osize) % wsize;
825 if (align < 0)
826 align += wsize;
827 isize += osize + align;
829 return isize;
832 if (instruction->opcode == I_INCBIN) {
833 const char *fname = instruction->eops->stringval;
834 off_t len;
836 len = nasm_file_size_by_path(fname);
837 if (len == (off_t)-1) {
838 nasm_error(ERR_NONFATAL, "`incbin': unable to get length of file `%s'",
839 fname);
840 return 0;
843 if (instruction->eops->next) {
844 if (len <= (off_t)instruction->eops->next->offset) {
845 len = 0;
846 } else {
847 len -= instruction->eops->next->offset;
848 if (instruction->eops->next->next &&
849 len > (off_t)instruction->eops->next->next->offset) {
850 len = (off_t)instruction->eops->next->next->offset;
855 return len;
858 /* Check to see if we need an address-size prefix */
859 add_asp(instruction, bits);
861 m = find_match(&temp, instruction, segment, offset, bits);
862 if (m == MOK_GOOD) {
863 /* we've matched an instruction. */
864 return calcsize(segment, offset, bits, instruction, temp);
865 } else {
866 return -1; /* didn't match any instruction */
870 static void bad_hle_warn(const insn * ins, uint8_t hleok)
872 enum prefixes rep_pfx = ins->prefixes[PPS_REP];
873 enum whatwarn { w_none, w_lock, w_inval } ww;
874 static const enum whatwarn warn[2][4] =
876 { w_inval, w_inval, w_none, w_lock }, /* XACQUIRE */
877 { w_inval, w_none, w_none, w_lock }, /* XRELEASE */
879 unsigned int n;
881 n = (unsigned int)rep_pfx - P_XACQUIRE;
882 if (n > 1)
883 return; /* Not XACQUIRE/XRELEASE */
885 ww = warn[n][hleok];
886 if (!is_class(MEMORY, ins->oprs[0].type))
887 ww = w_inval; /* HLE requires operand 0 to be memory */
889 switch (ww) {
890 case w_none:
891 break;
893 case w_lock:
894 if (ins->prefixes[PPS_LOCK] != P_LOCK) {
895 nasm_error(ERR_WARNING | ERR_WARN_HLE | ERR_PASS2,
896 "%s with this instruction requires lock",
897 prefix_name(rep_pfx));
899 break;
901 case w_inval:
902 nasm_error(ERR_WARNING | ERR_WARN_HLE | ERR_PASS2,
903 "%s invalid with this instruction",
904 prefix_name(rep_pfx));
905 break;
909 /* Common construct */
910 #define case3(x) case (x): case (x)+1: case (x)+2
911 #define case4(x) case3(x): case (x)+3
913 static int64_t calcsize(int32_t segment, int64_t offset, int bits,
914 insn * ins, const struct itemplate *temp)
916 const uint8_t *codes = temp->code;
917 int64_t length = 0;
918 uint8_t c;
919 int rex_mask = ~0;
920 int op1, op2;
921 struct operand *opx;
922 uint8_t opex = 0;
923 enum ea_type eat;
924 uint8_t hleok = 0;
925 bool lockcheck = true;
926 enum reg_enum mib_index = R_none; /* For a separate index MIB reg form */
928 ins->rex = 0; /* Ensure REX is reset */
929 eat = EA_SCALAR; /* Expect a scalar EA */
930 memset(ins->evex_p, 0, 3); /* Ensure EVEX is reset */
932 if (ins->prefixes[PPS_OSIZE] == P_O64)
933 ins->rex |= REX_W;
935 (void)segment; /* Don't warn that this parameter is unused */
936 (void)offset; /* Don't warn that this parameter is unused */
938 while (*codes) {
939 c = *codes++;
940 op1 = (c & 3) + ((opex & 1) << 2);
941 op2 = ((c >> 3) & 3) + ((opex & 2) << 1);
942 opx = &ins->oprs[op1];
943 opex = 0; /* For the next iteration */
945 switch (c) {
946 case4(01):
947 codes += c, length += c;
948 break;
950 case3(05):
951 opex = c;
952 break;
954 case4(010):
955 ins->rex |=
956 op_rexflags(opx, REX_B|REX_H|REX_P|REX_W);
957 codes++, length++;
958 break;
960 case4(014):
961 /* this is an index reg of MIB operand */
962 mib_index = opx->basereg;
963 break;
965 case4(020):
966 case4(024):
967 length++;
968 break;
970 case4(030):
971 length += 2;
972 break;
974 case4(034):
975 if (opx->type & (BITS16 | BITS32 | BITS64))
976 length += (opx->type & BITS16) ? 2 : 4;
977 else
978 length += (bits == 16) ? 2 : 4;
979 break;
981 case4(040):
982 length += 4;
983 break;
985 case4(044):
986 length += ins->addr_size >> 3;
987 break;
989 case4(050):
990 length++;
991 break;
993 case4(054):
994 length += 8; /* MOV reg64/imm */
995 break;
997 case4(060):
998 length += 2;
999 break;
1001 case4(064):
1002 if (opx->type & (BITS16 | BITS32 | BITS64))
1003 length += (opx->type & BITS16) ? 2 : 4;
1004 else
1005 length += (bits == 16) ? 2 : 4;
1006 break;
1008 case4(070):
1009 length += 4;
1010 break;
1012 case4(074):
1013 length += 2;
1014 break;
1016 case 0172:
1017 case 0173:
1018 codes++;
1019 length++;
1020 break;
1022 case4(0174):
1023 length++;
1024 break;
1026 case4(0240):
1027 ins->rex |= REX_EV;
1028 ins->vexreg = regval(opx);
1029 ins->evex_p[2] |= op_evexflags(opx, EVEX_P2VP, 2); /* High-16 NDS */
1030 ins->vex_cm = *codes++;
1031 ins->vex_wlp = *codes++;
1032 ins->evex_tuple = (*codes++ - 0300);
1033 break;
1035 case 0250:
1036 ins->rex |= REX_EV;
1037 ins->vexreg = 0;
1038 ins->vex_cm = *codes++;
1039 ins->vex_wlp = *codes++;
1040 ins->evex_tuple = (*codes++ - 0300);
1041 break;
1043 case4(0254):
1044 length += 4;
1045 break;
1047 case4(0260):
1048 ins->rex |= REX_V;
1049 ins->vexreg = regval(opx);
1050 ins->vex_cm = *codes++;
1051 ins->vex_wlp = *codes++;
1052 break;
1054 case 0270:
1055 ins->rex |= REX_V;
1056 ins->vexreg = 0;
1057 ins->vex_cm = *codes++;
1058 ins->vex_wlp = *codes++;
1059 break;
1061 case3(0271):
1062 hleok = c & 3;
1063 break;
1065 case4(0274):
1066 length++;
1067 break;
1069 case4(0300):
1070 break;
1072 case 0310:
1073 if (bits == 64)
1074 return -1;
1075 length += (bits != 16) && !has_prefix(ins, PPS_ASIZE, P_A16);
1076 break;
1078 case 0311:
1079 length += (bits != 32) && !has_prefix(ins, PPS_ASIZE, P_A32);
1080 break;
1082 case 0312:
1083 break;
1085 case 0313:
1086 if (bits != 64 || has_prefix(ins, PPS_ASIZE, P_A16) ||
1087 has_prefix(ins, PPS_ASIZE, P_A32))
1088 return -1;
1089 break;
1091 case4(0314):
1092 break;
1094 case 0320:
1096 enum prefixes pfx = ins->prefixes[PPS_OSIZE];
1097 if (pfx == P_O16)
1098 break;
1099 if (pfx != P_none)
1100 nasm_error(ERR_WARNING | ERR_PASS2, "invalid operand size prefix");
1101 else
1102 ins->prefixes[PPS_OSIZE] = P_O16;
1103 break;
1106 case 0321:
1108 enum prefixes pfx = ins->prefixes[PPS_OSIZE];
1109 if (pfx == P_O32)
1110 break;
1111 if (pfx != P_none)
1112 nasm_error(ERR_WARNING | ERR_PASS2, "invalid operand size prefix");
1113 else
1114 ins->prefixes[PPS_OSIZE] = P_O32;
1115 break;
1118 case 0322:
1119 break;
1121 case 0323:
1122 rex_mask &= ~REX_W;
1123 break;
1125 case 0324:
1126 ins->rex |= REX_W;
1127 break;
1129 case 0325:
1130 ins->rex |= REX_NH;
1131 break;
1133 case 0326:
1134 break;
1136 case 0330:
1137 codes++, length++;
1138 break;
1140 case 0331:
1141 break;
1143 case 0332:
1144 case 0333:
1145 length++;
1146 break;
1148 case 0334:
1149 ins->rex |= REX_L;
1150 break;
1152 case 0335:
1153 break;
1155 case 0336:
1156 if (!ins->prefixes[PPS_REP])
1157 ins->prefixes[PPS_REP] = P_REP;
1158 break;
1160 case 0337:
1161 if (!ins->prefixes[PPS_REP])
1162 ins->prefixes[PPS_REP] = P_REPNE;
1163 break;
1165 case 0340:
1166 if (!absolute_op(&ins->oprs[0]))
1167 nasm_error(ERR_NONFATAL, "attempt to reserve non-constant"
1168 " quantity of BSS space");
1169 else if (ins->oprs[0].opflags & OPFLAG_FORWARD)
1170 nasm_error(ERR_WARNING | ERR_PASS1,
1171 "forward reference in RESx can have unpredictable results");
1172 else
1173 length += ins->oprs[0].offset;
1174 break;
1176 case 0341:
1177 if (!ins->prefixes[PPS_WAIT])
1178 ins->prefixes[PPS_WAIT] = P_WAIT;
1179 break;
1181 case 0360:
1182 break;
1184 case 0361:
1185 length++;
1186 break;
1188 case 0364:
1189 case 0365:
1190 break;
1192 case 0366:
1193 case 0367:
1194 length++;
1195 break;
1197 case 0370:
1198 case 0371:
1199 break;
1201 case 0373:
1202 length++;
1203 break;
1205 case 0374:
1206 eat = EA_XMMVSIB;
1207 break;
1209 case 0375:
1210 eat = EA_YMMVSIB;
1211 break;
1213 case 0376:
1214 eat = EA_ZMMVSIB;
1215 break;
1217 case4(0100):
1218 case4(0110):
1219 case4(0120):
1220 case4(0130):
1221 case4(0200):
1222 case4(0204):
1223 case4(0210):
1224 case4(0214):
1225 case4(0220):
1226 case4(0224):
1227 case4(0230):
1228 case4(0234):
1230 ea ea_data;
1231 int rfield;
1232 opflags_t rflags;
1233 struct operand *opy = &ins->oprs[op2];
1234 struct operand *op_er_sae;
1236 ea_data.rex = 0; /* Ensure ea.REX is initially 0 */
1238 if (c <= 0177) {
1239 /* pick rfield from operand b (opx) */
1240 rflags = regflag(opx);
1241 rfield = nasm_regvals[opx->basereg];
1242 } else {
1243 rflags = 0;
1244 rfield = c & 7;
1247 /* EVEX.b1 : evex_brerop contains the operand position */
1248 op_er_sae = (ins->evex_brerop >= 0 ?
1249 &ins->oprs[ins->evex_brerop] : NULL);
1251 if (op_er_sae && (op_er_sae->decoflags & (ER | SAE))) {
1252 /* set EVEX.b */
1253 ins->evex_p[2] |= EVEX_P2B;
1254 if (op_er_sae->decoflags & ER) {
1255 /* set EVEX.RC (rounding control) */
1256 ins->evex_p[2] |= ((ins->evex_rm - BRC_RN) << 5)
1257 & EVEX_P2RC;
1259 } else {
1260 /* set EVEX.L'L (vector length) */
1261 ins->evex_p[2] |= ((ins->vex_wlp << (5 - 2)) & EVEX_P2LL);
1262 ins->evex_p[1] |= ((ins->vex_wlp << (7 - 4)) & EVEX_P1W);
1263 if (opy->decoflags & BRDCAST_MASK) {
1264 /* set EVEX.b */
1265 ins->evex_p[2] |= EVEX_P2B;
1269 if (itemp_has(temp, IF_MIB)) {
1270 opy->eaflags |= EAF_MIB;
1272 * if a separate form of MIB (ICC style) is used,
1273 * the index reg info is merged into mem operand
1275 if (mib_index != R_none) {
1276 opy->indexreg = mib_index;
1277 opy->scale = 1;
1278 opy->hintbase = mib_index;
1279 opy->hinttype = EAH_NOTBASE;
1283 if (process_ea(opy, &ea_data, bits,
1284 rfield, rflags, ins) != eat) {
1285 nasm_error(ERR_NONFATAL, "invalid effective address");
1286 return -1;
1287 } else {
1288 ins->rex |= ea_data.rex;
1289 length += ea_data.size;
1292 break;
1294 default:
1295 nasm_panic(0, "internal instruction table corrupt"
1296 ": instruction code \\%o (0x%02X) given", c, c);
1297 break;
1301 ins->rex &= rex_mask;
1303 if (ins->rex & REX_NH) {
1304 if (ins->rex & REX_H) {
1305 nasm_error(ERR_NONFATAL, "instruction cannot use high registers");
1306 return -1;
1308 ins->rex &= ~REX_P; /* Don't force REX prefix due to high reg */
1311 switch (ins->prefixes[PPS_VEX]) {
1312 case P_EVEX:
1313 if (!(ins->rex & REX_EV))
1314 return -1;
1315 break;
1316 case P_VEX3:
1317 case P_VEX2:
1318 if (!(ins->rex & REX_V))
1319 return -1;
1320 break;
1321 default:
1322 break;
1325 if (ins->rex & (REX_V | REX_EV)) {
1326 int bad32 = REX_R|REX_W|REX_X|REX_B;
1328 if (ins->rex & REX_H) {
1329 nasm_error(ERR_NONFATAL, "cannot use high register in AVX instruction");
1330 return -1;
1332 switch (ins->vex_wlp & 060) {
1333 case 000:
1334 case 040:
1335 ins->rex &= ~REX_W;
1336 break;
1337 case 020:
1338 ins->rex |= REX_W;
1339 bad32 &= ~REX_W;
1340 break;
1341 case 060:
1342 /* Follow REX_W */
1343 break;
1346 if (bits != 64 && ((ins->rex & bad32) || ins->vexreg > 7)) {
1347 nasm_error(ERR_NONFATAL, "invalid operands in non-64-bit mode");
1348 return -1;
1349 } else if (!(ins->rex & REX_EV) &&
1350 ((ins->vexreg > 15) || (ins->evex_p[0] & 0xf0))) {
1351 nasm_error(ERR_NONFATAL, "invalid high-16 register in non-AVX-512");
1352 return -1;
1354 if (ins->rex & REX_EV)
1355 length += 4;
1356 else if (ins->vex_cm != 1 || (ins->rex & (REX_W|REX_X|REX_B)) ||
1357 ins->prefixes[PPS_VEX] == P_VEX3)
1358 length += 3;
1359 else
1360 length += 2;
1361 } else if (ins->rex & REX_MASK) {
1362 if (ins->rex & REX_H) {
1363 nasm_error(ERR_NONFATAL, "cannot use high register in rex instruction");
1364 return -1;
1365 } else if (bits == 64) {
1366 length++;
1367 } else if ((ins->rex & REX_L) &&
1368 !(ins->rex & (REX_P|REX_W|REX_X|REX_B)) &&
1369 iflag_ffs(&cpu) >= IF_X86_64) {
1370 /* LOCK-as-REX.R */
1371 assert_no_prefix(ins, PPS_LOCK);
1372 lockcheck = false; /* Already errored, no need for warning */
1373 length++;
1374 } else {
1375 nasm_error(ERR_NONFATAL, "invalid operands in non-64-bit mode");
1376 return -1;
1380 if (has_prefix(ins, PPS_LOCK, P_LOCK) && lockcheck &&
1381 (!itemp_has(temp,IF_LOCK) || !is_class(MEMORY, ins->oprs[0].type))) {
1382 nasm_error(ERR_WARNING | ERR_WARN_LOCK | ERR_PASS2 ,
1383 "instruction is not lockable");
1386 bad_hle_warn(ins, hleok);
1389 * when BND prefix is set by DEFAULT directive,
1390 * BND prefix is added to every appropriate instruction line
1391 * unless it is overridden by NOBND prefix.
1393 if (globalbnd &&
1394 (itemp_has(temp, IF_BND) && !has_prefix(ins, PPS_REP, P_NOBND)))
1395 ins->prefixes[PPS_REP] = P_BND;
1398 * Add length of legacy prefixes
1400 length += emit_prefix(NULL, bits, ins);
1402 return length;
1405 static inline void emit_rex(struct out_data *data, insn *ins)
1407 if (data->bits == 64) {
1408 if ((ins->rex & REX_MASK) &&
1409 !(ins->rex & (REX_V | REX_EV)) &&
1410 !ins->rex_done) {
1411 uint8_t rex = (ins->rex & REX_MASK) | REX_P;
1412 out_rawbyte(data, rex);
1413 ins->rex_done = true;
1418 static int emit_prefix(struct out_data *data, const int bits, insn *ins)
1420 int bytes = 0;
1421 int j;
1423 for (j = 0; j < MAXPREFIX; j++) {
1424 uint8_t c = 0;
1425 switch (ins->prefixes[j]) {
1426 case P_WAIT:
1427 c = 0x9B;
1428 break;
1429 case P_LOCK:
1430 c = 0xF0;
1431 break;
1432 case P_REPNE:
1433 case P_REPNZ:
1434 case P_XACQUIRE:
1435 case P_BND:
1436 c = 0xF2;
1437 break;
1438 case P_REPE:
1439 case P_REPZ:
1440 case P_REP:
1441 case P_XRELEASE:
1442 c = 0xF3;
1443 break;
1444 case R_CS:
1445 if (bits == 64) {
1446 nasm_error(ERR_WARNING | ERR_PASS2,
1447 "cs segment base generated, but will be ignored in 64-bit mode");
1449 c = 0x2E;
1450 break;
1451 case R_DS:
1452 if (bits == 64) {
1453 nasm_error(ERR_WARNING | ERR_PASS2,
1454 "ds segment base generated, but will be ignored in 64-bit mode");
1456 c = 0x3E;
1457 break;
1458 case R_ES:
1459 if (bits == 64) {
1460 nasm_error(ERR_WARNING | ERR_PASS2,
1461 "es segment base generated, but will be ignored in 64-bit mode");
1463 c = 0x26;
1464 break;
1465 case R_FS:
1466 c = 0x64;
1467 break;
1468 case R_GS:
1469 c = 0x65;
1470 break;
1471 case R_SS:
1472 if (bits == 64) {
1473 nasm_error(ERR_WARNING | ERR_PASS2,
1474 "ss segment base generated, but will be ignored in 64-bit mode");
1476 c = 0x36;
1477 break;
1478 case R_SEGR6:
1479 case R_SEGR7:
1480 nasm_error(ERR_NONFATAL,
1481 "segr6 and segr7 cannot be used as prefixes");
1482 break;
1483 case P_A16:
1484 if (bits == 64) {
1485 nasm_error(ERR_NONFATAL,
1486 "16-bit addressing is not supported "
1487 "in 64-bit mode");
1488 } else if (bits != 16)
1489 c = 0x67;
1490 break;
1491 case P_A32:
1492 if (bits != 32)
1493 c = 0x67;
1494 break;
1495 case P_A64:
1496 if (bits != 64) {
1497 nasm_error(ERR_NONFATAL,
1498 "64-bit addressing is only supported "
1499 "in 64-bit mode");
1501 break;
1502 case P_ASP:
1503 c = 0x67;
1504 break;
1505 case P_O16:
1506 if (bits != 16)
1507 c = 0x66;
1508 break;
1509 case P_O32:
1510 if (bits == 16)
1511 c = 0x66;
1512 break;
1513 case P_O64:
1514 /* REX.W */
1515 break;
1516 case P_OSP:
1517 c = 0x66;
1518 break;
1519 case P_EVEX:
1520 case P_VEX3:
1521 case P_VEX2:
1522 case P_NOBND:
1523 case P_none:
1524 break;
1525 default:
1526 nasm_panic(0, "invalid instruction prefix");
1528 if (c) {
1529 if (data)
1530 out_rawbyte(data, c);
1531 bytes++;
1534 return bytes;
1537 static void gencode(struct out_data *data, insn *ins)
1539 uint8_t c;
1540 uint8_t bytes[4];
1541 int64_t size;
1542 int op1, op2;
1543 struct operand *opx;
1544 const uint8_t *codes = data->itemp->code;
1545 uint8_t opex = 0;
1546 enum ea_type eat = EA_SCALAR;
1547 int r;
1548 const int bits = data->bits;
1550 ins->rex_done = false;
1552 emit_prefix(data, bits, ins);
1554 while (*codes) {
1555 c = *codes++;
1556 op1 = (c & 3) + ((opex & 1) << 2);
1557 op2 = ((c >> 3) & 3) + ((opex & 2) << 1);
1558 opx = &ins->oprs[op1];
1559 opex = 0; /* For the next iteration */
1562 switch (c) {
1563 case 01:
1564 case 02:
1565 case 03:
1566 case 04:
1567 emit_rex(data, ins);
1568 out_rawdata(data, codes, c);
1569 codes += c;
1570 break;
1572 case 05:
1573 case 06:
1574 case 07:
1575 opex = c;
1576 break;
1578 case4(010):
1579 emit_rex(data, ins);
1580 out_rawbyte(data, *codes++ + (regval(opx) & 7));
1581 break;
1583 case4(014):
1584 break;
1586 case4(020):
1587 if (opx->offset < -256 || opx->offset > 255)
1588 nasm_error(ERR_WARNING | ERR_PASS2 | ERR_WARN_NOV,
1589 "byte value exceeds bounds");
1590 out_imm(data, opx, 1, OUT_WRAP);
1591 break;
1593 case4(024):
1594 if (opx->offset < 0 || opx->offset > 255)
1595 nasm_error(ERR_WARNING | ERR_PASS2 | ERR_WARN_NOV,
1596 "unsigned byte value exceeds bounds");
1597 out_imm(data, opx, 1, OUT_UNSIGNED);
1598 break;
1600 case4(030):
1601 warn_overflow_opd(opx, 2);
1602 out_imm(data, opx, 2, OUT_WRAP);
1603 break;
1605 case4(034):
1606 if (opx->type & (BITS16 | BITS32))
1607 size = (opx->type & BITS16) ? 2 : 4;
1608 else
1609 size = (bits == 16) ? 2 : 4;
1610 warn_overflow_opd(opx, size);
1611 out_imm(data, opx, size, OUT_WRAP);
1612 break;
1614 case4(040):
1615 warn_overflow_opd(opx, 4);
1616 out_imm(data, opx, 4, OUT_WRAP);
1617 break;
1619 case4(044):
1620 size = ins->addr_size >> 3;
1621 warn_overflow_opd(opx, size);
1622 out_imm(data, opx, size, OUT_WRAP);
1623 break;
1625 case4(050):
1626 if (opx->segment == data->segment) {
1627 int64_t delta = opx->offset - data->offset
1628 - (data->inslen - data->insoffs);
1629 if (delta > 127 || delta < -128)
1630 nasm_error(ERR_NONFATAL, "short jump is out of range");
1632 out_reladdr(data, opx, 1);
1633 break;
1635 case4(054):
1636 out_imm(data, opx, 8, OUT_WRAP);
1637 break;
1639 case4(060):
1640 out_reladdr(data, opx, 2);
1641 break;
1643 case4(064):
1644 if (opx->type & (BITS16 | BITS32 | BITS64))
1645 size = (opx->type & BITS16) ? 2 : 4;
1646 else
1647 size = (bits == 16) ? 2 : 4;
1649 out_reladdr(data, opx, size);
1650 break;
1652 case4(070):
1653 out_reladdr(data, opx, 4);
1654 break;
1656 case4(074):
1657 if (opx->segment == NO_SEG)
1658 nasm_error(ERR_NONFATAL, "value referenced by FAR is not"
1659 " relocatable");
1660 out_segment(data, opx);
1661 break;
1663 case 0172:
1665 int mask = ins->prefixes[PPS_VEX] == P_EVEX ? 7 : 15;
1666 const struct operand *opy;
1668 c = *codes++;
1669 opx = &ins->oprs[c >> 3];
1670 opy = &ins->oprs[c & 7];
1671 if (!absolute_op(opy)) {
1672 nasm_error(ERR_NONFATAL,
1673 "non-absolute expression not permitted as argument %d",
1674 c & 7);
1675 } else if (opy->offset & ~mask) {
1676 nasm_error(ERR_WARNING | ERR_PASS2 | ERR_WARN_NOV,
1677 "is4 argument exceeds bounds");
1679 c = opy->offset & mask;
1680 goto emit_is4;
1683 case 0173:
1684 c = *codes++;
1685 opx = &ins->oprs[c >> 4];
1686 c &= 15;
1687 goto emit_is4;
1689 case4(0174):
1690 c = 0;
1691 emit_is4:
1692 r = nasm_regvals[opx->basereg];
1693 out_rawbyte(data, (r << 4) | ((r & 0x10) >> 1) | c);
1694 break;
1696 case4(0254):
1697 if (absolute_op(opx) &&
1698 (int32_t)opx->offset != (int64_t)opx->offset) {
1699 nasm_error(ERR_WARNING | ERR_PASS2 | ERR_WARN_NOV,
1700 "signed dword immediate exceeds bounds");
1702 out_imm(data, opx, 4, OUT_SIGNED);
1703 break;
1705 case4(0240):
1706 case 0250:
1707 codes += 3;
1708 ins->evex_p[2] |= op_evexflags(&ins->oprs[0],
1709 EVEX_P2Z | EVEX_P2AAA, 2);
1710 ins->evex_p[2] ^= EVEX_P2VP; /* 1's complement */
1711 bytes[0] = 0x62;
1712 /* EVEX.X can be set by either REX or EVEX for different reasons */
1713 bytes[1] = ((((ins->rex & 7) << 5) |
1714 (ins->evex_p[0] & (EVEX_P0X | EVEX_P0RP))) ^ 0xf0) |
1715 (ins->vex_cm & EVEX_P0MM);
1716 bytes[2] = ((ins->rex & REX_W) << (7 - 3)) |
1717 ((~ins->vexreg & 15) << 3) |
1718 (1 << 2) | (ins->vex_wlp & 3);
1719 bytes[3] = ins->evex_p[2];
1720 out_rawdata(data, bytes, 4);
1721 break;
1723 case4(0260):
1724 case 0270:
1725 codes += 2;
1726 if (ins->vex_cm != 1 || (ins->rex & (REX_W|REX_X|REX_B)) ||
1727 ins->prefixes[PPS_VEX] == P_VEX3) {
1728 bytes[0] = (ins->vex_cm >> 6) ? 0x8f : 0xc4;
1729 bytes[1] = (ins->vex_cm & 31) | ((~ins->rex & 7) << 5);
1730 bytes[2] = ((ins->rex & REX_W) << (7-3)) |
1731 ((~ins->vexreg & 15)<< 3) | (ins->vex_wlp & 07);
1732 out_rawdata(data, bytes, 3);
1733 } else {
1734 bytes[0] = 0xc5;
1735 bytes[1] = ((~ins->rex & REX_R) << (7-2)) |
1736 ((~ins->vexreg & 15) << 3) | (ins->vex_wlp & 07);
1737 out_rawdata(data, bytes, 2);
1739 break;
1741 case 0271:
1742 case 0272:
1743 case 0273:
1744 break;
1746 case4(0274):
1748 uint64_t uv, um;
1749 int s;
1751 if (ins->rex & REX_W)
1752 s = 64;
1753 else if (ins->prefixes[PPS_OSIZE] == P_O16)
1754 s = 16;
1755 else if (ins->prefixes[PPS_OSIZE] == P_O32)
1756 s = 32;
1757 else
1758 s = bits;
1760 um = (uint64_t)2 << (s-1);
1761 uv = opx->offset;
1763 if (uv > 127 && uv < (uint64_t)-128 &&
1764 (uv < um-128 || uv > um-1)) {
1765 /* If this wasn't explicitly byte-sized, warn as though we
1766 * had fallen through to the imm16/32/64 case.
1768 nasm_error(ERR_WARNING | ERR_PASS2 | ERR_WARN_NOV,
1769 "%s value exceeds bounds",
1770 (opx->type & BITS8) ? "signed byte" :
1771 s == 16 ? "word" :
1772 s == 32 ? "dword" :
1773 "signed dword");
1775 out_imm(data, opx, 1, OUT_WRAP); /* XXX: OUT_SIGNED? */
1776 break;
1779 case4(0300):
1780 break;
1782 case 0310:
1783 if (bits == 32 && !has_prefix(ins, PPS_ASIZE, P_A16))
1784 out_rawbyte(data, 0x67);
1785 break;
1787 case 0311:
1788 if (bits != 32 && !has_prefix(ins, PPS_ASIZE, P_A32))
1789 out_rawbyte(data, 0x67);
1790 break;
1792 case 0312:
1793 break;
1795 case 0313:
1796 ins->rex = 0;
1797 break;
1799 case4(0314):
1800 break;
1802 case 0320:
1803 case 0321:
1804 break;
1806 case 0322:
1807 case 0323:
1808 break;
1810 case 0324:
1811 ins->rex |= REX_W;
1812 break;
1814 case 0325:
1815 break;
1817 case 0326:
1818 break;
1820 case 0330:
1821 out_rawbyte(data, *codes++ ^ get_cond_opcode(ins->condition));
1822 break;
1824 case 0331:
1825 break;
1827 case 0332:
1828 case 0333:
1829 out_rawbyte(data, c - 0332 + 0xF2);
1830 break;
1832 case 0334:
1833 if (ins->rex & REX_R)
1834 out_rawbyte(data, 0xF0);
1835 ins->rex &= ~(REX_L|REX_R);
1836 break;
1838 case 0335:
1839 break;
1841 case 0336:
1842 case 0337:
1843 break;
1845 case 0340:
1846 if (ins->oprs[0].segment != NO_SEG)
1847 nasm_panic(0, "non-constant BSS size in pass two");
1849 out_reserve(data, ins->oprs[0].offset);
1850 break;
1852 case 0341:
1853 break;
1855 case 0360:
1856 break;
1858 case 0361:
1859 out_rawbyte(data, 0x66);
1860 break;
1862 case 0364:
1863 case 0365:
1864 break;
1866 case 0366:
1867 case 0367:
1868 out_rawbyte(data, c - 0366 + 0x66);
1869 break;
1871 case3(0370):
1872 break;
1874 case 0373:
1875 out_rawbyte(data, bits == 16 ? 3 : 5);
1876 break;
1878 case 0374:
1879 eat = EA_XMMVSIB;
1880 break;
1882 case 0375:
1883 eat = EA_YMMVSIB;
1884 break;
1886 case 0376:
1887 eat = EA_ZMMVSIB;
1888 break;
1890 case4(0100):
1891 case4(0110):
1892 case4(0120):
1893 case4(0130):
1894 case4(0200):
1895 case4(0204):
1896 case4(0210):
1897 case4(0214):
1898 case4(0220):
1899 case4(0224):
1900 case4(0230):
1901 case4(0234):
1903 ea ea_data;
1904 int rfield;
1905 opflags_t rflags;
1906 uint8_t *p;
1907 struct operand *opy = &ins->oprs[op2];
1909 if (c <= 0177) {
1910 /* pick rfield from operand b (opx) */
1911 rflags = regflag(opx);
1912 rfield = nasm_regvals[opx->basereg];
1913 } else {
1914 /* rfield is constant */
1915 rflags = 0;
1916 rfield = c & 7;
1919 if (process_ea(opy, &ea_data, bits,
1920 rfield, rflags, ins) != eat)
1921 nasm_error(ERR_NONFATAL, "invalid effective address");
1923 p = bytes;
1924 *p++ = ea_data.modrm;
1925 if (ea_data.sib_present)
1926 *p++ = ea_data.sib;
1927 out_rawdata(data, bytes, p - bytes);
1930 * Make sure the address gets the right offset in case
1931 * the line breaks in the .lst file (BR 1197827)
1934 if (ea_data.bytes) {
1935 /* use compressed displacement, if available */
1936 if (ea_data.disp8) {
1937 out_rawbyte(data, ea_data.disp8);
1938 } else if (ea_data.rip) {
1939 out_reladdr(data, opy, ea_data.bytes);
1940 } else {
1941 int asize = ins->addr_size >> 3;
1943 if (overflow_general(opy->offset, asize) ||
1944 signed_bits(opy->offset, ins->addr_size) !=
1945 signed_bits(opy->offset, ea_data.bytes << 3))
1946 warn_overflow(ERR_PASS2, ea_data.bytes);
1948 out_imm(data, opy, ea_data.bytes,
1949 (asize > ea_data.bytes) ? OUT_SIGNED : OUT_UNSIGNED);
1953 break;
1955 default:
1956 nasm_panic(0, "internal instruction table corrupt"
1957 ": instruction code \\%o (0x%02X) given", c, c);
1958 break;
1963 static opflags_t regflag(const operand * o)
1965 if (!is_register(o->basereg))
1966 nasm_panic(0, "invalid operand passed to regflag()");
1967 return nasm_reg_flags[o->basereg];
1970 static int32_t regval(const operand * o)
1972 if (!is_register(o->basereg))
1973 nasm_panic(0, "invalid operand passed to regval()");
1974 return nasm_regvals[o->basereg];
1977 static int op_rexflags(const operand * o, int mask)
1979 opflags_t flags;
1980 int val;
1982 if (!is_register(o->basereg))
1983 nasm_panic(0, "invalid operand passed to op_rexflags()");
1985 flags = nasm_reg_flags[o->basereg];
1986 val = nasm_regvals[o->basereg];
1988 return rexflags(val, flags, mask);
1991 static int rexflags(int val, opflags_t flags, int mask)
1993 int rex = 0;
1995 if (val >= 0 && (val & 8))
1996 rex |= REX_B|REX_X|REX_R;
1997 if (flags & BITS64)
1998 rex |= REX_W;
1999 if (!(REG_HIGH & ~flags)) /* AH, CH, DH, BH */
2000 rex |= REX_H;
2001 else if (!(REG8 & ~flags) && val >= 4) /* SPL, BPL, SIL, DIL */
2002 rex |= REX_P;
2004 return rex & mask;
2007 static int evexflags(int val, decoflags_t deco,
2008 int mask, uint8_t byte)
2010 int evex = 0;
2012 switch (byte) {
2013 case 0:
2014 if (val >= 0 && (val & 16))
2015 evex |= (EVEX_P0RP | EVEX_P0X);
2016 break;
2017 case 2:
2018 if (val >= 0 && (val & 16))
2019 evex |= EVEX_P2VP;
2020 if (deco & Z)
2021 evex |= EVEX_P2Z;
2022 if (deco & OPMASK_MASK)
2023 evex |= deco & EVEX_P2AAA;
2024 break;
2026 return evex & mask;
2029 static int op_evexflags(const operand * o, int mask, uint8_t byte)
2031 int val;
2033 val = nasm_regvals[o->basereg];
2035 return evexflags(val, o->decoflags, mask, byte);
2038 static enum match_result find_match(const struct itemplate **tempp,
2039 insn *instruction,
2040 int32_t segment, int64_t offset, int bits)
2042 const struct itemplate *temp;
2043 enum match_result m, merr;
2044 opflags_t xsizeflags[MAX_OPERANDS];
2045 bool opsizemissing = false;
2046 int8_t broadcast = instruction->evex_brerop;
2047 int i;
2049 /* broadcasting uses a different data element size */
2050 for (i = 0; i < instruction->operands; i++)
2051 if (i == broadcast)
2052 xsizeflags[i] = instruction->oprs[i].decoflags & BRSIZE_MASK;
2053 else
2054 xsizeflags[i] = instruction->oprs[i].type & SIZE_MASK;
2056 merr = MERR_INVALOP;
2058 for (temp = nasm_instructions[instruction->opcode];
2059 temp->opcode != I_none; temp++) {
2060 m = matches(temp, instruction, bits);
2061 if (m == MOK_JUMP) {
2062 if (jmp_match(segment, offset, bits, instruction, temp))
2063 m = MOK_GOOD;
2064 else
2065 m = MERR_INVALOP;
2066 } else if (m == MERR_OPSIZEMISSING && !itemp_has(temp, IF_SX)) {
2068 * Missing operand size and a candidate for fuzzy matching...
2070 for (i = 0; i < temp->operands; i++)
2071 if (i == broadcast)
2072 xsizeflags[i] |= temp->deco[i] & BRSIZE_MASK;
2073 else
2074 xsizeflags[i] |= temp->opd[i] & SIZE_MASK;
2075 opsizemissing = true;
2077 if (m > merr)
2078 merr = m;
2079 if (merr == MOK_GOOD)
2080 goto done;
2083 /* No match, but see if we can get a fuzzy operand size match... */
2084 if (!opsizemissing)
2085 goto done;
2087 for (i = 0; i < instruction->operands; i++) {
2089 * We ignore extrinsic operand sizes on registers, so we should
2090 * never try to fuzzy-match on them. This also resolves the case
2091 * when we have e.g. "xmmrm128" in two different positions.
2093 if (is_class(REGISTER, instruction->oprs[i].type))
2094 continue;
2096 /* This tests if xsizeflags[i] has more than one bit set */
2097 if ((xsizeflags[i] & (xsizeflags[i]-1)))
2098 goto done; /* No luck */
2100 if (i == broadcast) {
2101 instruction->oprs[i].decoflags |= xsizeflags[i];
2102 instruction->oprs[i].type |= (xsizeflags[i] == BR_BITS32 ?
2103 BITS32 : BITS64);
2104 } else {
2105 instruction->oprs[i].type |= xsizeflags[i]; /* Set the size */
2109 /* Try matching again... */
2110 for (temp = nasm_instructions[instruction->opcode];
2111 temp->opcode != I_none; temp++) {
2112 m = matches(temp, instruction, bits);
2113 if (m == MOK_JUMP) {
2114 if (jmp_match(segment, offset, bits, instruction, temp))
2115 m = MOK_GOOD;
2116 else
2117 m = MERR_INVALOP;
2119 if (m > merr)
2120 merr = m;
2121 if (merr == MOK_GOOD)
2122 goto done;
2125 done:
2126 *tempp = temp;
2127 return merr;
2130 static uint8_t get_broadcast_num(opflags_t opflags, opflags_t brsize)
2132 unsigned int opsize = (opflags & SIZE_MASK) >> SIZE_SHIFT;
2133 uint8_t brcast_num;
2135 if (brsize > BITS64)
2136 nasm_error(ERR_FATAL,
2137 "size of broadcasting element is greater than 64 bits");
2140 * The shift term is to take care of the extra BITS80 inserted
2141 * between BITS64 and BITS128.
2143 brcast_num = ((opsize / (BITS64 >> SIZE_SHIFT)) * (BITS64 / brsize))
2144 >> (opsize > (BITS64 >> SIZE_SHIFT));
2146 return brcast_num;
2149 static enum match_result matches(const struct itemplate *itemp,
2150 insn *instruction, int bits)
2152 opflags_t size[MAX_OPERANDS], asize;
2153 bool opsizemissing = false;
2154 int i, oprs;
2157 * Check the opcode
2159 if (itemp->opcode != instruction->opcode)
2160 return MERR_INVALOP;
2163 * Count the operands
2165 if (itemp->operands != instruction->operands)
2166 return MERR_INVALOP;
2169 * Is it legal?
2171 if (!(optimizing > 0) && itemp_has(itemp, IF_OPT))
2172 return MERR_INVALOP;
2175 * {evex} available?
2177 switch (instruction->prefixes[PPS_VEX]) {
2178 case P_EVEX:
2179 if (!itemp_has(itemp, IF_EVEX))
2180 return MERR_ENCMISMATCH;
2181 break;
2182 case P_VEX3:
2183 case P_VEX2:
2184 if (!itemp_has(itemp, IF_VEX))
2185 return MERR_ENCMISMATCH;
2186 break;
2187 default:
2188 break;
2192 * Check that no spurious colons or TOs are present
2194 for (i = 0; i < itemp->operands; i++)
2195 if (instruction->oprs[i].type & ~itemp->opd[i] & (COLON | TO))
2196 return MERR_INVALOP;
2199 * Process size flags
2201 switch (itemp_smask(itemp)) {
2202 case IF_GENBIT(IF_SB):
2203 asize = BITS8;
2204 break;
2205 case IF_GENBIT(IF_SW):
2206 asize = BITS16;
2207 break;
2208 case IF_GENBIT(IF_SD):
2209 asize = BITS32;
2210 break;
2211 case IF_GENBIT(IF_SQ):
2212 asize = BITS64;
2213 break;
2214 case IF_GENBIT(IF_SO):
2215 asize = BITS128;
2216 break;
2217 case IF_GENBIT(IF_SY):
2218 asize = BITS256;
2219 break;
2220 case IF_GENBIT(IF_SZ):
2221 asize = BITS512;
2222 break;
2223 case IF_GENBIT(IF_SIZE):
2224 switch (bits) {
2225 case 16:
2226 asize = BITS16;
2227 break;
2228 case 32:
2229 asize = BITS32;
2230 break;
2231 case 64:
2232 asize = BITS64;
2233 break;
2234 default:
2235 asize = 0;
2236 break;
2238 break;
2239 default:
2240 asize = 0;
2241 break;
2244 if (itemp_armask(itemp)) {
2245 /* S- flags only apply to a specific operand */
2246 i = itemp_arg(itemp);
2247 memset(size, 0, sizeof size);
2248 size[i] = asize;
2249 } else {
2250 /* S- flags apply to all operands */
2251 for (i = 0; i < MAX_OPERANDS; i++)
2252 size[i] = asize;
2256 * Check that the operand flags all match up,
2257 * it's a bit tricky so lets be verbose:
2259 * 1) Find out the size of operand. If instruction
2260 * doesn't have one specified -- we're trying to
2261 * guess it either from template (IF_S* flag) or
2262 * from code bits.
2264 * 2) If template operand do not match the instruction OR
2265 * template has an operand size specified AND this size differ
2266 * from which instruction has (perhaps we got it from code bits)
2267 * we are:
2268 * a) Check that only size of instruction and operand is differ
2269 * other characteristics do match
2270 * b) Perhaps it's a register specified in instruction so
2271 * for such a case we just mark that operand as "size
2272 * missing" and this will turn on fuzzy operand size
2273 * logic facility (handled by a caller)
2275 for (i = 0; i < itemp->operands; i++) {
2276 opflags_t type = instruction->oprs[i].type;
2277 decoflags_t deco = instruction->oprs[i].decoflags;
2278 bool is_broadcast = deco & BRDCAST_MASK;
2279 uint8_t brcast_num = 0;
2280 opflags_t template_opsize, insn_opsize;
2282 if (!(type & SIZE_MASK))
2283 type |= size[i];
2285 insn_opsize = type & SIZE_MASK;
2286 if (!is_broadcast) {
2287 template_opsize = itemp->opd[i] & SIZE_MASK;
2288 } else {
2289 decoflags_t deco_brsize = itemp->deco[i] & BRSIZE_MASK;
2291 * when broadcasting, the element size depends on
2292 * the instruction type. decorator flag should match.
2295 if (deco_brsize) {
2296 template_opsize = (deco_brsize == BR_BITS32 ? BITS32 : BITS64);
2297 /* calculate the proper number : {1to<brcast_num>} */
2298 brcast_num = get_broadcast_num(itemp->opd[i], template_opsize);
2299 } else {
2300 template_opsize = 0;
2304 if ((itemp->opd[i] & ~type & ~SIZE_MASK) ||
2305 (deco & ~itemp->deco[i] & ~BRNUM_MASK)) {
2306 return MERR_INVALOP;
2307 } else if (template_opsize) {
2308 if (template_opsize != insn_opsize) {
2309 if (insn_opsize) {
2310 return MERR_INVALOP;
2311 } else if (!is_class(REGISTER, type)) {
2313 * Note: we don't honor extrinsic operand sizes for registers,
2314 * so "missing operand size" for a register should be
2315 * considered a wildcard match rather than an error.
2317 opsizemissing = true;
2319 } else if (is_broadcast &&
2320 (brcast_num !=
2321 (2U << ((deco & BRNUM_MASK) >> BRNUM_SHIFT)))) {
2323 * broadcasting opsize matches but the number of repeated memory
2324 * element does not match.
2325 * if 64b double precision float is broadcasted to ymm (256b),
2326 * broadcasting decorator must be {1to4}.
2328 return MERR_BRNUMMISMATCH;
2333 if (opsizemissing)
2334 return MERR_OPSIZEMISSING;
2337 * Check operand sizes
2339 if (itemp_has(itemp, IF_SM) || itemp_has(itemp, IF_SM2)) {
2340 oprs = (itemp_has(itemp, IF_SM2) ? 2 : itemp->operands);
2341 for (i = 0; i < oprs; i++) {
2342 asize = itemp->opd[i] & SIZE_MASK;
2343 if (asize) {
2344 for (i = 0; i < oprs; i++)
2345 size[i] = asize;
2346 break;
2349 } else {
2350 oprs = itemp->operands;
2353 for (i = 0; i < itemp->operands; i++) {
2354 if (!(itemp->opd[i] & SIZE_MASK) &&
2355 (instruction->oprs[i].type & SIZE_MASK & ~size[i]))
2356 return MERR_OPSIZEMISMATCH;
2360 * Check template is okay at the set cpu level
2362 if (iflag_cmp_cpu_level(&insns_flags[itemp->iflag_idx], &cpu) > 0)
2363 return MERR_BADCPU;
2366 * Verify the appropriate long mode flag.
2368 if (itemp_has(itemp, (bits == 64 ? IF_NOLONG : IF_LONG)))
2369 return MERR_BADMODE;
2372 * If we have a HLE prefix, look for the NOHLE flag
2374 if (itemp_has(itemp, IF_NOHLE) &&
2375 (has_prefix(instruction, PPS_REP, P_XACQUIRE) ||
2376 has_prefix(instruction, PPS_REP, P_XRELEASE)))
2377 return MERR_BADHLE;
2380 * Check if special handling needed for Jumps
2382 if ((itemp->code[0] & ~1) == 0370)
2383 return MOK_JUMP;
2386 * Check if BND prefix is allowed.
2387 * Other 0xF2 (REPNE/REPNZ) prefix is prohibited.
2389 if (!itemp_has(itemp, IF_BND) &&
2390 (has_prefix(instruction, PPS_REP, P_BND) ||
2391 has_prefix(instruction, PPS_REP, P_NOBND)))
2392 return MERR_BADBND;
2393 else if (itemp_has(itemp, IF_BND) &&
2394 (has_prefix(instruction, PPS_REP, P_REPNE) ||
2395 has_prefix(instruction, PPS_REP, P_REPNZ)))
2396 return MERR_BADREPNE;
2398 return MOK_GOOD;
2402 * Check if ModR/M.mod should/can be 01.
2403 * - EAF_BYTEOFFS is set
2404 * - offset can fit in a byte when EVEX is not used
2405 * - offset can be compressed when EVEX is used
2407 #define IS_MOD_01() (input->eaflags & EAF_BYTEOFFS || \
2408 (o >= -128 && o <= 127 && \
2409 seg == NO_SEG && !forw_ref && \
2410 !(input->eaflags & EAF_WORDOFFS) && \
2411 !(ins->rex & REX_EV)) || \
2412 (ins->rex & REX_EV && \
2413 is_disp8n(input, ins, &output->disp8)))
2415 static enum ea_type process_ea(operand *input, ea *output, int bits,
2416 int rfield, opflags_t rflags, insn *ins)
2418 bool forw_ref = !!(input->opflags & OPFLAG_UNKNOWN);
2419 int addrbits = ins->addr_size;
2420 int eaflags = input->eaflags;
2422 output->type = EA_SCALAR;
2423 output->rip = false;
2424 output->disp8 = 0;
2426 /* REX flags for the rfield operand */
2427 output->rex |= rexflags(rfield, rflags, REX_R | REX_P | REX_W | REX_H);
2428 /* EVEX.R' flag for the REG operand */
2429 ins->evex_p[0] |= evexflags(rfield, 0, EVEX_P0RP, 0);
2431 if (is_class(REGISTER, input->type)) {
2433 * It's a direct register.
2435 if (!is_register(input->basereg))
2436 goto err;
2438 if (!is_reg_class(REG_EA, input->basereg))
2439 goto err;
2441 /* broadcasting is not available with a direct register operand. */
2442 if (input->decoflags & BRDCAST_MASK) {
2443 nasm_error(ERR_NONFATAL, "Broadcasting not allowed from a register");
2444 goto err;
2447 output->rex |= op_rexflags(input, REX_B | REX_P | REX_W | REX_H);
2448 ins->evex_p[0] |= op_evexflags(input, EVEX_P0X, 0);
2449 output->sib_present = false; /* no SIB necessary */
2450 output->bytes = 0; /* no offset necessary either */
2451 output->modrm = GEN_MODRM(3, rfield, nasm_regvals[input->basereg]);
2452 } else {
2454 * It's a memory reference.
2457 /* Embedded rounding or SAE is not available with a mem ref operand. */
2458 if (input->decoflags & (ER | SAE)) {
2459 nasm_error(ERR_NONFATAL,
2460 "Embedded rounding is available only with reg-reg op.");
2461 return -1;
2464 if (input->basereg == -1 &&
2465 (input->indexreg == -1 || input->scale == 0)) {
2467 * It's a pure offset.
2469 if (bits == 64 && ((input->type & IP_REL) == IP_REL)) {
2470 if (input->segment == NO_SEG || (input->opflags & OPFLAG_RELATIVE)) {
2471 nasm_error(ERR_WARNING | ERR_PASS2, "absolute address can not be RIP-relative");
2472 input->type &= ~IP_REL;
2473 input->type |= MEMORY;
2477 if (bits == 64 &&
2478 !(IP_REL & ~input->type) && (eaflags & EAF_MIB)) {
2479 nasm_error(ERR_NONFATAL, "RIP-relative addressing is prohibited for mib.");
2480 return -1;
2483 if (eaflags & EAF_BYTEOFFS ||
2484 (eaflags & EAF_WORDOFFS &&
2485 input->disp_size != (addrbits != 16 ? 32 : 16))) {
2486 nasm_error(ERR_WARNING | ERR_PASS1, "displacement size ignored on absolute address");
2489 if (bits == 64 && (~input->type & IP_REL)) {
2490 output->sib_present = true;
2491 output->sib = GEN_SIB(0, 4, 5);
2492 output->bytes = 4;
2493 output->modrm = GEN_MODRM(0, rfield, 4);
2494 output->rip = false;
2495 } else {
2496 output->sib_present = false;
2497 output->bytes = (addrbits != 16 ? 4 : 2);
2498 output->modrm = GEN_MODRM(0, rfield, (addrbits != 16 ? 5 : 6));
2499 output->rip = bits == 64;
2501 } else {
2503 * It's an indirection.
2505 int i = input->indexreg, b = input->basereg, s = input->scale;
2506 int32_t seg = input->segment;
2507 int hb = input->hintbase, ht = input->hinttype;
2508 int t, it, bt; /* register numbers */
2509 opflags_t x, ix, bx; /* register flags */
2511 if (s == 0)
2512 i = -1; /* make this easy, at least */
2514 if (is_register(i)) {
2515 it = nasm_regvals[i];
2516 ix = nasm_reg_flags[i];
2517 } else {
2518 it = -1;
2519 ix = 0;
2522 if (is_register(b)) {
2523 bt = nasm_regvals[b];
2524 bx = nasm_reg_flags[b];
2525 } else {
2526 bt = -1;
2527 bx = 0;
2530 /* if either one are a vector register... */
2531 if ((ix|bx) & (XMMREG|YMMREG|ZMMREG) & ~REG_EA) {
2532 opflags_t sok = BITS32 | BITS64;
2533 int32_t o = input->offset;
2534 int mod, scale, index, base;
2537 * For a vector SIB, one has to be a vector and the other,
2538 * if present, a GPR. The vector must be the index operand.
2540 if (it == -1 || (bx & (XMMREG|YMMREG|ZMMREG) & ~REG_EA)) {
2541 if (s == 0)
2542 s = 1;
2543 else if (s != 1)
2544 goto err;
2546 t = bt, bt = it, it = t;
2547 x = bx, bx = ix, ix = x;
2550 if (bt != -1) {
2551 if (REG_GPR & ~bx)
2552 goto err;
2553 if (!(REG64 & ~bx) || !(REG32 & ~bx))
2554 sok &= bx;
2555 else
2556 goto err;
2560 * While we're here, ensure the user didn't specify
2561 * WORD or QWORD
2563 if (input->disp_size == 16 || input->disp_size == 64)
2564 goto err;
2566 if (addrbits == 16 ||
2567 (addrbits == 32 && !(sok & BITS32)) ||
2568 (addrbits == 64 && !(sok & BITS64)))
2569 goto err;
2571 output->type = ((ix & ZMMREG & ~REG_EA) ? EA_ZMMVSIB
2572 : ((ix & YMMREG & ~REG_EA)
2573 ? EA_YMMVSIB : EA_XMMVSIB));
2575 output->rex |= rexflags(it, ix, REX_X);
2576 output->rex |= rexflags(bt, bx, REX_B);
2577 ins->evex_p[2] |= evexflags(it, 0, EVEX_P2VP, 2);
2579 index = it & 7; /* it is known to be != -1 */
2581 switch (s) {
2582 case 1:
2583 scale = 0;
2584 break;
2585 case 2:
2586 scale = 1;
2587 break;
2588 case 4:
2589 scale = 2;
2590 break;
2591 case 8:
2592 scale = 3;
2593 break;
2594 default: /* then what the smeg is it? */
2595 goto err; /* panic */
2598 if (bt == -1) {
2599 base = 5;
2600 mod = 0;
2601 } else {
2602 base = (bt & 7);
2603 if (base != REG_NUM_EBP && o == 0 &&
2604 seg == NO_SEG && !forw_ref &&
2605 !(eaflags & (EAF_BYTEOFFS | EAF_WORDOFFS)))
2606 mod = 0;
2607 else if (IS_MOD_01())
2608 mod = 1;
2609 else
2610 mod = 2;
2613 output->sib_present = true;
2614 output->bytes = (bt == -1 || mod == 2 ? 4 : mod);
2615 output->modrm = GEN_MODRM(mod, rfield, 4);
2616 output->sib = GEN_SIB(scale, index, base);
2617 } else if ((ix|bx) & (BITS32|BITS64)) {
2619 * it must be a 32/64-bit memory reference. Firstly we have
2620 * to check that all registers involved are type E/Rxx.
2622 opflags_t sok = BITS32 | BITS64;
2623 int32_t o = input->offset;
2625 if (it != -1) {
2626 if (!(REG64 & ~ix) || !(REG32 & ~ix))
2627 sok &= ix;
2628 else
2629 goto err;
2632 if (bt != -1) {
2633 if (REG_GPR & ~bx)
2634 goto err; /* Invalid register */
2635 if (~sok & bx & SIZE_MASK)
2636 goto err; /* Invalid size */
2637 sok &= bx;
2641 * While we're here, ensure the user didn't specify
2642 * WORD or QWORD
2644 if (input->disp_size == 16 || input->disp_size == 64)
2645 goto err;
2647 if (addrbits == 16 ||
2648 (addrbits == 32 && !(sok & BITS32)) ||
2649 (addrbits == 64 && !(sok & BITS64)))
2650 goto err;
2652 /* now reorganize base/index */
2653 if (s == 1 && bt != it && bt != -1 && it != -1 &&
2654 ((hb == b && ht == EAH_NOTBASE) ||
2655 (hb == i && ht == EAH_MAKEBASE))) {
2656 /* swap if hints say so */
2657 t = bt, bt = it, it = t;
2658 x = bx, bx = ix, ix = x;
2661 if (bt == -1 && s == 1 && !(hb == i && ht == EAH_NOTBASE)) {
2662 /* make single reg base, unless hint */
2663 bt = it, bx = ix, it = -1, ix = 0;
2665 if (eaflags & EAF_MIB) {
2666 /* only for mib operands */
2667 if (it == -1 && (hb == b && ht == EAH_NOTBASE)) {
2669 * make a single reg index [reg*1].
2670 * gas uses this form for an explicit index register.
2672 it = bt, ix = bx, bt = -1, bx = 0, s = 1;
2674 if ((ht == EAH_SUMMED) && bt == -1) {
2675 /* separate once summed index into [base, index] */
2676 bt = it, bx = ix, s--;
2678 } else {
2679 if (((s == 2 && it != REG_NUM_ESP &&
2680 (!(eaflags & EAF_TIMESTWO) || (ht == EAH_SUMMED))) ||
2681 s == 3 || s == 5 || s == 9) && bt == -1) {
2682 /* convert 3*EAX to EAX+2*EAX */
2683 bt = it, bx = ix, s--;
2685 if (it == -1 && (bt & 7) != REG_NUM_ESP &&
2686 (eaflags & EAF_TIMESTWO) &&
2687 (hb == b && ht == EAH_NOTBASE)) {
2689 * convert [NOSPLIT EAX*1]
2690 * to sib format with 0x0 displacement - [EAX*1+0].
2692 it = bt, ix = bx, bt = -1, bx = 0, s = 1;
2695 if (s == 1 && it == REG_NUM_ESP) {
2696 /* swap ESP into base if scale is 1 */
2697 t = it, it = bt, bt = t;
2698 x = ix, ix = bx, bx = x;
2700 if (it == REG_NUM_ESP ||
2701 (s != 1 && s != 2 && s != 4 && s != 8 && it != -1))
2702 goto err; /* wrong, for various reasons */
2704 output->rex |= rexflags(it, ix, REX_X);
2705 output->rex |= rexflags(bt, bx, REX_B);
2707 if (it == -1 && (bt & 7) != REG_NUM_ESP) {
2708 /* no SIB needed */
2709 int mod, rm;
2711 if (bt == -1) {
2712 rm = 5;
2713 mod = 0;
2714 } else {
2715 rm = (bt & 7);
2716 if (rm != REG_NUM_EBP && o == 0 &&
2717 seg == NO_SEG && !forw_ref &&
2718 !(eaflags & (EAF_BYTEOFFS | EAF_WORDOFFS)))
2719 mod = 0;
2720 else if (IS_MOD_01())
2721 mod = 1;
2722 else
2723 mod = 2;
2726 output->sib_present = false;
2727 output->bytes = (bt == -1 || mod == 2 ? 4 : mod);
2728 output->modrm = GEN_MODRM(mod, rfield, rm);
2729 } else {
2730 /* we need a SIB */
2731 int mod, scale, index, base;
2733 if (it == -1)
2734 index = 4, s = 1;
2735 else
2736 index = (it & 7);
2738 switch (s) {
2739 case 1:
2740 scale = 0;
2741 break;
2742 case 2:
2743 scale = 1;
2744 break;
2745 case 4:
2746 scale = 2;
2747 break;
2748 case 8:
2749 scale = 3;
2750 break;
2751 default: /* then what the smeg is it? */
2752 goto err; /* panic */
2755 if (bt == -1) {
2756 base = 5;
2757 mod = 0;
2758 } else {
2759 base = (bt & 7);
2760 if (base != REG_NUM_EBP && o == 0 &&
2761 seg == NO_SEG && !forw_ref &&
2762 !(eaflags & (EAF_BYTEOFFS | EAF_WORDOFFS)))
2763 mod = 0;
2764 else if (IS_MOD_01())
2765 mod = 1;
2766 else
2767 mod = 2;
2770 output->sib_present = true;
2771 output->bytes = (bt == -1 || mod == 2 ? 4 : mod);
2772 output->modrm = GEN_MODRM(mod, rfield, 4);
2773 output->sib = GEN_SIB(scale, index, base);
2775 } else { /* it's 16-bit */
2776 int mod, rm;
2777 int16_t o = input->offset;
2779 /* check for 64-bit long mode */
2780 if (addrbits == 64)
2781 goto err;
2783 /* check all registers are BX, BP, SI or DI */
2784 if ((b != -1 && b != R_BP && b != R_BX && b != R_SI && b != R_DI) ||
2785 (i != -1 && i != R_BP && i != R_BX && i != R_SI && i != R_DI))
2786 goto err;
2788 /* ensure the user didn't specify DWORD/QWORD */
2789 if (input->disp_size == 32 || input->disp_size == 64)
2790 goto err;
2792 if (s != 1 && i != -1)
2793 goto err; /* no can do, in 16-bit EA */
2794 if (b == -1 && i != -1) {
2795 int tmp = b;
2796 b = i;
2797 i = tmp;
2798 } /* swap */
2799 if ((b == R_SI || b == R_DI) && i != -1) {
2800 int tmp = b;
2801 b = i;
2802 i = tmp;
2804 /* have BX/BP as base, SI/DI index */
2805 if (b == i)
2806 goto err; /* shouldn't ever happen, in theory */
2807 if (i != -1 && b != -1 &&
2808 (i == R_BP || i == R_BX || b == R_SI || b == R_DI))
2809 goto err; /* invalid combinations */
2810 if (b == -1) /* pure offset: handled above */
2811 goto err; /* so if it gets to here, panic! */
2813 rm = -1;
2814 if (i != -1)
2815 switch (i * 256 + b) {
2816 case R_SI * 256 + R_BX:
2817 rm = 0;
2818 break;
2819 case R_DI * 256 + R_BX:
2820 rm = 1;
2821 break;
2822 case R_SI * 256 + R_BP:
2823 rm = 2;
2824 break;
2825 case R_DI * 256 + R_BP:
2826 rm = 3;
2827 break;
2828 } else
2829 switch (b) {
2830 case R_SI:
2831 rm = 4;
2832 break;
2833 case R_DI:
2834 rm = 5;
2835 break;
2836 case R_BP:
2837 rm = 6;
2838 break;
2839 case R_BX:
2840 rm = 7;
2841 break;
2843 if (rm == -1) /* can't happen, in theory */
2844 goto err; /* so panic if it does */
2846 if (o == 0 && seg == NO_SEG && !forw_ref && rm != 6 &&
2847 !(eaflags & (EAF_BYTEOFFS | EAF_WORDOFFS)))
2848 mod = 0;
2849 else if (IS_MOD_01())
2850 mod = 1;
2851 else
2852 mod = 2;
2854 output->sib_present = false; /* no SIB - it's 16-bit */
2855 output->bytes = mod; /* bytes of offset needed */
2856 output->modrm = GEN_MODRM(mod, rfield, rm);
2861 output->size = 1 + output->sib_present + output->bytes;
2862 return output->type;
2864 err:
2865 return output->type = EA_INVALID;
2868 static void add_asp(insn *ins, int addrbits)
2870 int j, valid;
2871 int defdisp;
2873 valid = (addrbits == 64) ? 64|32 : 32|16;
2875 switch (ins->prefixes[PPS_ASIZE]) {
2876 case P_A16:
2877 valid &= 16;
2878 break;
2879 case P_A32:
2880 valid &= 32;
2881 break;
2882 case P_A64:
2883 valid &= 64;
2884 break;
2885 case P_ASP:
2886 valid &= (addrbits == 32) ? 16 : 32;
2887 break;
2888 default:
2889 break;
2892 for (j = 0; j < ins->operands; j++) {
2893 if (is_class(MEMORY, ins->oprs[j].type)) {
2894 opflags_t i, b;
2896 /* Verify as Register */
2897 if (!is_register(ins->oprs[j].indexreg))
2898 i = 0;
2899 else
2900 i = nasm_reg_flags[ins->oprs[j].indexreg];
2902 /* Verify as Register */
2903 if (!is_register(ins->oprs[j].basereg))
2904 b = 0;
2905 else
2906 b = nasm_reg_flags[ins->oprs[j].basereg];
2908 if (ins->oprs[j].scale == 0)
2909 i = 0;
2911 if (!i && !b) {
2912 int ds = ins->oprs[j].disp_size;
2913 if ((addrbits != 64 && ds > 8) ||
2914 (addrbits == 64 && ds == 16))
2915 valid &= ds;
2916 } else {
2917 if (!(REG16 & ~b))
2918 valid &= 16;
2919 if (!(REG32 & ~b))
2920 valid &= 32;
2921 if (!(REG64 & ~b))
2922 valid &= 64;
2924 if (!(REG16 & ~i))
2925 valid &= 16;
2926 if (!(REG32 & ~i))
2927 valid &= 32;
2928 if (!(REG64 & ~i))
2929 valid &= 64;
2934 if (valid & addrbits) {
2935 ins->addr_size = addrbits;
2936 } else if (valid & ((addrbits == 32) ? 16 : 32)) {
2937 /* Add an address size prefix */
2938 ins->prefixes[PPS_ASIZE] = (addrbits == 32) ? P_A16 : P_A32;;
2939 ins->addr_size = (addrbits == 32) ? 16 : 32;
2940 } else {
2941 /* Impossible... */
2942 nasm_error(ERR_NONFATAL, "impossible combination of address sizes");
2943 ins->addr_size = addrbits; /* Error recovery */
2946 defdisp = ins->addr_size == 16 ? 16 : 32;
2948 for (j = 0; j < ins->operands; j++) {
2949 if (!(MEM_OFFS & ~ins->oprs[j].type) &&
2950 (ins->oprs[j].disp_size ? ins->oprs[j].disp_size : defdisp) != ins->addr_size) {
2952 * mem_offs sizes must match the address size; if not,
2953 * strip the MEM_OFFS bit and match only EA instructions
2955 ins->oprs[j].type &= ~(MEM_OFFS & ~MEMORY);