Coverage Report

Created: 2026-01-12 07:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/capstonev5/arch/X86/X86DisassemblerDecoder.c
Line
Count
Source
1
/*===-- X86DisassemblerDecoder.c - Disassembler decoder ------------*- C -*-===*
2
 *
3
 *                     The LLVM Compiler Infrastructure
4
 *
5
 * This file is distributed under the University of Illinois Open Source
6
 * License. See LICENSE.TXT for details.
7
 *
8
 *===----------------------------------------------------------------------===*
9
 *
10
 * This file is part of the X86 Disassembler.
11
 * It contains the implementation of the instruction decoder.
12
 * Documentation for the disassembler can be found in X86Disassembler.h.
13
 *
14
 *===----------------------------------------------------------------------===*/
15
16
/* Capstone Disassembly Engine */
17
/* By Nguyen Anh Quynh <aquynh@gmail.com>, 2013-2019 */
18
19
#ifdef CAPSTONE_HAS_X86
20
21
#include <stdarg.h>   /* for va_*()       */
22
#if defined(CAPSTONE_HAS_OSXKERNEL)
23
#include <libkern/libkern.h>
24
#else
25
#include <stdlib.h>   /* for exit()       */
26
#endif
27
28
#include <string.h>
29
30
#include "../../cs_priv.h"
31
#include "../../utils.h"
32
33
#include "X86DisassemblerDecoder.h"
34
#include "X86Mapping.h"
35
36
/// Specifies whether a ModR/M byte is needed and (if so) which
37
/// instruction each possible value of the ModR/M byte corresponds to.  Once
38
/// this information is known, we have narrowed down to a single instruction.
39
struct ModRMDecision {
40
  uint8_t modrm_type;
41
  uint16_t instructionIDs;
42
};
43
44
/// Specifies which set of ModR/M->instruction tables to look at
45
/// given a particular opcode.
46
struct OpcodeDecision {
47
  struct ModRMDecision modRMDecisions[256];
48
};
49
50
/// Specifies which opcode->instruction tables to look at given
51
/// a particular context (set of attributes).  Since there are many possible
52
/// contexts, the decoder first uses CONTEXTS_SYM to determine which context
53
/// applies given a specific set of attributes.  Hence there are only IC_max
54
/// entries in this table, rather than 2^(ATTR_max).
55
struct ContextDecision {
56
  struct OpcodeDecision opcodeDecisions[IC_max];
57
};
58
59
#ifdef CAPSTONE_X86_REDUCE
60
#include "X86GenDisassemblerTables_reduce.inc"
61
#include "X86GenDisassemblerTables_reduce2.inc"
62
#include "X86Lookup16_reduce.inc"
63
#else
64
#include "X86GenDisassemblerTables.inc"
65
#include "X86GenDisassemblerTables2.inc"
66
#include "X86Lookup16.inc"
67
#endif
68
69
/*
70
 * contextForAttrs - Client for the instruction context table.  Takes a set of
71
 *   attributes and returns the appropriate decode context.
72
 *
73
 * @param attrMask  - Attributes, from the enumeration attributeBits.
74
 * @return          - The InstructionContext to use when looking up an
75
 *                    an instruction with these attributes.
76
 */
77
static InstructionContext contextForAttrs(uint16_t attrMask)
78
854k
{
79
854k
  return CONTEXTS_SYM[attrMask];
80
854k
}
81
82
/*
83
 * modRMRequired - Reads the appropriate instruction table to determine whether
84
 *   the ModR/M byte is required to decode a particular instruction.
85
 *
86
 * @param type        - The opcode type (i.e., how many bytes it has).
87
 * @param insnContext - The context for the instruction, as returned by
88
 *                      contextForAttrs.
89
 * @param opcode      - The last byte of the instruction's opcode, not counting
90
 *                      ModR/M extensions and escapes.
91
 * @return            - true if the ModR/M byte is required, false otherwise.
92
 */
93
static int modRMRequired(OpcodeType type,
94
    InstructionContext insnContext,
95
    uint16_t opcode)
96
854k
{
97
854k
  const struct OpcodeDecision *decision = NULL;
98
854k
  const uint8_t *indextable = NULL;
99
854k
  unsigned int index;
100
101
854k
  switch (type) {
102
0
    default: break;
103
664k
    case ONEBYTE:
104
664k
      decision = ONEBYTE_SYM;
105
664k
      indextable = index_x86DisassemblerOneByteOpcodes;
106
664k
      break;
107
95.6k
    case TWOBYTE:
108
95.6k
      decision = TWOBYTE_SYM;
109
95.6k
      indextable = index_x86DisassemblerTwoByteOpcodes;
110
95.6k
      break;
111
30.4k
    case THREEBYTE_38:
112
30.4k
      decision = THREEBYTE38_SYM;
113
30.4k
      indextable = index_x86DisassemblerThreeByte38Opcodes;
114
30.4k
      break;
115
46.2k
    case THREEBYTE_3A:
116
46.2k
      decision = THREEBYTE3A_SYM;
117
46.2k
      indextable = index_x86DisassemblerThreeByte3AOpcodes;
118
46.2k
      break;
119
0
#ifndef CAPSTONE_X86_REDUCE
120
12.9k
    case XOP8_MAP:
121
12.9k
      decision = XOP8_MAP_SYM;
122
12.9k
      indextable = index_x86DisassemblerXOP8Opcodes;
123
12.9k
      break;
124
1.81k
    case XOP9_MAP:
125
1.81k
      decision = XOP9_MAP_SYM;
126
1.81k
      indextable = index_x86DisassemblerXOP9Opcodes;
127
1.81k
      break;
128
553
    case XOPA_MAP:
129
553
      decision = XOPA_MAP_SYM;
130
553
      indextable = index_x86DisassemblerXOPAOpcodes;
131
553
      break;
132
1.52k
    case THREEDNOW_MAP:
133
      // 3DNow instructions always have ModRM byte
134
1.52k
      return true;
135
854k
#endif
136
854k
  }
137
138
  // return decision->opcodeDecisions[insnContext].modRMDecisions[opcode].modrm_type != MODRM_ONEENTRY;
139
852k
  index = indextable[insnContext];
140
852k
  if (index)
141
847k
    return decision[index - 1].modRMDecisions[opcode].modrm_type != MODRM_ONEENTRY;
142
4.78k
  else
143
4.78k
    return false;
144
852k
}
145
146
/*
147
 * decode - Reads the appropriate instruction table to obtain the unique ID of
148
 *   an instruction.
149
 *
150
 * @param type        - See modRMRequired().
151
 * @param insnContext - See modRMRequired().
152
 * @param opcode      - See modRMRequired().
153
 * @param modRM       - The ModR/M byte if required, or any value if not.
154
 * @return            - The UID of the instruction, or 0 on failure.
155
 */
156
static InstrUID decode(OpcodeType type,
157
                       InstructionContext insnContext,
158
                       uint8_t opcode,
159
                       uint8_t modRM)
160
852k
{
161
852k
  const struct ModRMDecision *dec = NULL;
162
852k
  unsigned int index;
163
852k
  static const struct OpcodeDecision emptyDecision = { 0 };
164
165
852k
  switch (type) {
166
0
    default: break; // never reach
167
663k
    case ONEBYTE:
168
      // dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
169
663k
      index = index_x86DisassemblerOneByteOpcodes[insnContext];
170
663k
      if (index)
171
663k
        dec = &ONEBYTE_SYM[index - 1].modRMDecisions[opcode];
172
331
      else
173
331
        dec = &emptyDecision.modRMDecisions[opcode];
174
663k
      break;
175
95.6k
    case TWOBYTE:
176
      //dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
177
95.6k
      index = index_x86DisassemblerTwoByteOpcodes[insnContext];
178
95.6k
      if (index)
179
94.5k
        dec = &TWOBYTE_SYM[index - 1].modRMDecisions[opcode];
180
1.10k
      else
181
1.10k
        dec = &emptyDecision.modRMDecisions[opcode];
182
95.6k
      break;
183
30.4k
    case THREEBYTE_38:
184
      // dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
185
30.4k
      index = index_x86DisassemblerThreeByte38Opcodes[insnContext];
186
30.4k
      if (index)
187
30.1k
        dec = &THREEBYTE38_SYM[index - 1].modRMDecisions[opcode];
188
302
      else
189
302
        dec = &emptyDecision.modRMDecisions[opcode];
190
30.4k
      break;
191
46.1k
    case THREEBYTE_3A:
192
      //dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
193
46.1k
      index = index_x86DisassemblerThreeByte3AOpcodes[insnContext];
194
46.1k
      if (index)
195
46.1k
        dec = &THREEBYTE3A_SYM[index - 1].modRMDecisions[opcode];
196
52
      else
197
52
        dec = &emptyDecision.modRMDecisions[opcode];
198
46.1k
      break;
199
0
#ifndef CAPSTONE_X86_REDUCE
200
12.9k
    case XOP8_MAP:
201
      // dec = &XOP8_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
202
12.9k
      index = index_x86DisassemblerXOP8Opcodes[insnContext];
203
12.9k
      if (index)
204
10.5k
        dec = &XOP8_MAP_SYM[index - 1].modRMDecisions[opcode];
205
2.36k
      else
206
2.36k
        dec = &emptyDecision.modRMDecisions[opcode];
207
12.9k
      break;
208
1.81k
    case XOP9_MAP:
209
      // dec = &XOP9_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
210
1.81k
      index = index_x86DisassemblerXOP9Opcodes[insnContext];
211
1.81k
      if (index)
212
1.32k
        dec = &XOP9_MAP_SYM[index - 1].modRMDecisions[opcode];
213
492
      else
214
492
        dec = &emptyDecision.modRMDecisions[opcode];
215
1.81k
      break;
216
553
    case XOPA_MAP:
217
      // dec = &XOPA_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
218
553
      index = index_x86DisassemblerXOPAOpcodes[insnContext];
219
553
      if (index)
220
406
        dec = &XOPA_MAP_SYM[index - 1].modRMDecisions[opcode];
221
147
      else
222
147
        dec = &emptyDecision.modRMDecisions[opcode];
223
553
      break;
224
1.52k
    case THREEDNOW_MAP:
225
      // dec = &THREEDNOW_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
226
1.52k
      index = index_x86Disassembler3DNowOpcodes[insnContext];
227
1.52k
      if (index)
228
1.00k
        dec = &THREEDNOW_MAP_SYM[index - 1].modRMDecisions[opcode];
229
512
      else
230
512
        dec = &emptyDecision.modRMDecisions[opcode];
231
1.52k
      break;
232
852k
#endif
233
852k
  }
234
235
852k
  switch (dec->modrm_type) {
236
0
    default:
237
      // debug("Corrupt table!  Unknown modrm_type");
238
0
      return 0;
239
366k
    case MODRM_ONEENTRY:
240
366k
      return modRMTable[dec->instructionIDs];
241
367k
    case MODRM_SPLITRM:
242
367k
      if (modFromModRM(modRM) == 0x3)
243
86.6k
        return modRMTable[dec->instructionIDs + 1];
244
281k
      return modRMTable[dec->instructionIDs];
245
96.2k
    case MODRM_SPLITREG:
246
96.2k
      if (modFromModRM(modRM) == 0x3)
247
31.2k
        return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3) + 8];
248
64.9k
      return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
249
22.1k
    case MODRM_SPLITMISC:
250
22.1k
      if (modFromModRM(modRM) == 0x3)
251
5.18k
        return modRMTable[dec->instructionIDs+(modRM & 0x3f) + 8];
252
16.9k
      return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
253
0
    case MODRM_FULL:
254
0
      return modRMTable[dec->instructionIDs+modRM];
255
852k
  }
256
852k
}
257
258
/*
259
 * specifierForUID - Given a UID, returns the name and operand specification for
260
 *   that instruction.
261
 *
262
 * @param uid - The unique ID for the instruction.  This should be returned by
263
 *              decode(); specifierForUID will not check bounds.
264
 * @return    - A pointer to the specification for that instruction.
265
 */
266
static const struct InstructionSpecifier *specifierForUID(InstrUID uid)
267
699k
{
268
699k
  return &INSTRUCTIONS_SYM[uid];
269
699k
}
270
271
/*
272
 * consumeByte - Uses the reader function provided by the user to consume one
273
 *   byte from the instruction's memory and advance the cursor.
274
 *
275
 * @param insn  - The instruction with the reader function to use.  The cursor
276
 *                for this instruction is advanced.
277
 * @param byte  - A pointer to a pre-allocated memory buffer to be populated
278
 *                with the data read.
279
 * @return      - 0 if the read was successful; nonzero otherwise.
280
 */
281
static int consumeByte(struct InternalInstruction* insn, uint8_t* byte)
282
2.40M
{
283
2.40M
  int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
284
285
2.40M
  if (!ret)
286
2.40M
    ++(insn->readerCursor);
287
288
2.40M
  return ret;
289
2.40M
}
290
291
/*
292
 * lookAtByte - Like consumeByte, but does not advance the cursor.
293
 *
294
 * @param insn  - See consumeByte().
295
 * @param byte  - See consumeByte().
296
 * @return      - See consumeByte().
297
 */
298
static int lookAtByte(struct InternalInstruction* insn, uint8_t* byte)
299
304k
{
300
304k
  return insn->reader(insn->readerArg, byte, insn->readerCursor);
301
304k
}
302
303
static void unconsumeByte(struct InternalInstruction* insn)
304
765k
{
305
765k
  insn->readerCursor--;
306
765k
}
307
308
#define CONSUME_FUNC(name, type)                                  \
309
119k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
119k
    type combined = 0;                                            \
311
119k
    unsigned offset;                                              \
312
374k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
256k
      uint8_t byte;                                               \
314
256k
      int ret = insn->reader(insn->readerArg,                     \
315
256k
                             &byte,                               \
316
256k
                             insn->readerCursor + offset);        \
317
256k
      if (ret)                                                    \
318
256k
        return ret;                                               \
319
256k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
255k
    }                                                             \
321
119k
    *ptr = combined;                                              \
322
118k
    insn->readerCursor += sizeof(type);                           \
323
118k
    return 0;                                                     \
324
119k
  }
X86DisassemblerDecoder.c:consumeInt8
Line
Count
Source
309
53.4k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
53.4k
    type combined = 0;                                            \
311
53.4k
    unsigned offset;                                              \
312
106k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
53.4k
      uint8_t byte;                                               \
314
53.4k
      int ret = insn->reader(insn->readerArg,                     \
315
53.4k
                             &byte,                               \
316
53.4k
                             insn->readerCursor + offset);        \
317
53.4k
      if (ret)                                                    \
318
53.4k
        return ret;                                               \
319
53.4k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
53.2k
    }                                                             \
321
53.4k
    *ptr = combined;                                              \
322
53.2k
    insn->readerCursor += sizeof(type);                           \
323
53.2k
    return 0;                                                     \
324
53.4k
  }
X86DisassemblerDecoder.c:consumeInt16
Line
Count
Source
309
11.6k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
11.6k
    type combined = 0;                                            \
311
11.6k
    unsigned offset;                                              \
312
34.6k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
23.1k
      uint8_t byte;                                               \
314
23.1k
      int ret = insn->reader(insn->readerArg,                     \
315
23.1k
                             &byte,                               \
316
23.1k
                             insn->readerCursor + offset);        \
317
23.1k
      if (ret)                                                    \
318
23.1k
        return ret;                                               \
319
23.1k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
23.0k
    }                                                             \
321
11.6k
    *ptr = combined;                                              \
322
11.5k
    insn->readerCursor += sizeof(type);                           \
323
11.5k
    return 0;                                                     \
324
11.6k
  }
X86DisassemblerDecoder.c:consumeInt32
Line
Count
Source
309
14.2k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
14.2k
    type combined = 0;                                            \
311
14.2k
    unsigned offset;                                              \
312
70.8k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
56.7k
      uint8_t byte;                                               \
314
56.7k
      int ret = insn->reader(insn->readerArg,                     \
315
56.7k
                             &byte,                               \
316
56.7k
                             insn->readerCursor + offset);        \
317
56.7k
      if (ret)                                                    \
318
56.7k
        return ret;                                               \
319
56.7k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
56.5k
    }                                                             \
321
14.2k
    *ptr = combined;                                              \
322
14.0k
    insn->readerCursor += sizeof(type);                           \
323
14.0k
    return 0;                                                     \
324
14.2k
  }
X86DisassemblerDecoder.c:consumeUInt16
Line
Count
Source
309
22.9k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
22.9k
    type combined = 0;                                            \
311
22.9k
    unsigned offset;                                              \
312
68.5k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
45.8k
      uint8_t byte;                                               \
314
45.8k
      int ret = insn->reader(insn->readerArg,                     \
315
45.8k
                             &byte,                               \
316
45.8k
                             insn->readerCursor + offset);        \
317
45.8k
      if (ret)                                                    \
318
45.8k
        return ret;                                               \
319
45.8k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
45.6k
    }                                                             \
321
22.9k
    *ptr = combined;                                              \
322
22.7k
    insn->readerCursor += sizeof(type);                           \
323
22.7k
    return 0;                                                     \
324
22.9k
  }
X86DisassemblerDecoder.c:consumeUInt32
Line
Count
Source
309
14.8k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
14.8k
    type combined = 0;                                            \
311
14.8k
    unsigned offset;                                              \
312
73.4k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
58.8k
      uint8_t byte;                                               \
314
58.8k
      int ret = insn->reader(insn->readerArg,                     \
315
58.8k
                             &byte,                               \
316
58.8k
                             insn->readerCursor + offset);        \
317
58.8k
      if (ret)                                                    \
318
58.8k
        return ret;                                               \
319
58.8k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
58.5k
    }                                                             \
321
14.8k
    *ptr = combined;                                              \
322
14.5k
    insn->readerCursor += sizeof(type);                           \
323
14.5k
    return 0;                                                     \
324
14.8k
  }
X86DisassemblerDecoder.c:consumeUInt64
Line
Count
Source
309
2.34k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
2.34k
    type combined = 0;                                            \
311
2.34k
    unsigned offset;                                              \
312
20.7k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
18.4k
      uint8_t byte;                                               \
314
18.4k
      int ret = insn->reader(insn->readerArg,                     \
315
18.4k
                             &byte,                               \
316
18.4k
                             insn->readerCursor + offset);        \
317
18.4k
      if (ret)                                                    \
318
18.4k
        return ret;                                               \
319
18.4k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
18.3k
    }                                                             \
321
2.34k
    *ptr = combined;                                              \
322
2.27k
    insn->readerCursor += sizeof(type);                           \
323
2.27k
    return 0;                                                     \
324
2.34k
  }
325
326
/*
327
 * consume* - Use the reader function provided by the user to consume data
328
 *   values of various sizes from the instruction's memory and advance the
329
 *   cursor appropriately.  These readers perform endian conversion.
330
 *
331
 * @param insn    - See consumeByte().
332
 * @param ptr     - A pointer to a pre-allocated memory of appropriate size to
333
 *                  be populated with the data read.
334
 * @return        - See consumeByte().
335
 */
336
CONSUME_FUNC(consumeInt8, int8_t)
337
CONSUME_FUNC(consumeInt16, int16_t)
338
CONSUME_FUNC(consumeInt32, int32_t)
339
CONSUME_FUNC(consumeUInt16, uint16_t)
340
CONSUME_FUNC(consumeUInt32, uint32_t)
341
CONSUME_FUNC(consumeUInt64, uint64_t)
342
343
static bool isREX(struct InternalInstruction *insn, uint8_t prefix)
344
633k
{
345
633k
  if (insn->mode == MODE_64BIT)
346
224k
    return prefix >= 0x40 && prefix <= 0x4f;
347
348
408k
  return false;
349
633k
}
350
351
/*
352
 * setPrefixPresent - Marks that a particular prefix is present as mandatory
353
 *
354
 * @param insn      - The instruction to be marked as having the prefix.
355
 * @param prefix    - The prefix that is present.
356
 */
357
static void setPrefixPresent(struct InternalInstruction *insn, uint8_t prefix)
358
137k
{
359
137k
  uint8_t nextByte;
360
361
137k
  switch (prefix) {
362
39.4k
    case 0xf0:  // LOCK
363
39.4k
      insn->hasLockPrefix = true;
364
39.4k
      insn->repeatPrefix = 0;
365
39.4k
      break;
366
367
30.3k
    case 0xf2:  // REPNE/REPNZ
368
53.0k
    case 0xf3:  // REP or REPE/REPZ
369
53.0k
      if (lookAtByte(insn, &nextByte))
370
43
        break;
371
      // TODO:
372
      //  1. There could be several 0x66
373
      //  2. if (nextByte == 0x66) and nextNextByte != 0x0f then
374
      //      it's not mandatory prefix
375
      //  3. if (nextByte >= 0x40 && nextByte <= 0x4f) it's REX and we need
376
      //     0x0f exactly after it to be mandatory prefix
377
53.0k
      if (isREX(insn, nextByte) || nextByte == 0x0f || nextByte == 0x66)
378
        // The last of 0xf2 /0xf3 is mandatory prefix
379
13.4k
        insn->mandatoryPrefix = prefix;
380
381
53.0k
      insn->repeatPrefix = prefix;
382
53.0k
      insn->hasLockPrefix = false;
383
53.0k
      break;
384
385
16.8k
    case 0x66:
386
16.8k
      if (lookAtByte(insn, &nextByte))
387
42
        break;
388
      // 0x66 can't overwrite existing mandatory prefix and should be ignored
389
16.8k
      if (!insn->mandatoryPrefix && (nextByte == 0x0f || isREX(insn, nextByte)))
390
5.49k
        insn->mandatoryPrefix = prefix;
391
16.8k
      break;
392
137k
  }
393
137k
}
394
395
/*
396
 * readPrefixes - Consumes all of an instruction's prefix bytes, and marks the
397
 *   instruction as having them.  Also sets the instruction's default operand,
398
 *   address, and other relevant data sizes to report operands correctly.
399
 *
400
 * @param insn  - The instruction whose prefixes are to be read.
401
 * @return      - 0 if the instruction could be read until the end of the prefix
402
 *                bytes, and no prefixes conflicted; nonzero otherwise.
403
 */
404
static int readPrefixes(struct InternalInstruction* insn)
405
613k
{
406
613k
  bool isPrefix = true;
407
613k
  uint8_t byte = 0;
408
613k
  uint8_t nextByte;
409
410
1.36M
  while (isPrefix) {
411
750k
    if (insn->mode == MODE_64BIT) {
412
      // eliminate consecutive redundant REX bytes in front
413
269k
      if (consumeByte(insn, &byte))
414
133
        return -1;
415
416
269k
      if ((byte & 0xf0) == 0x40) {
417
55.5k
        while(true) {
418
55.5k
          if (lookAtByte(insn, &byte))  // out of input code
419
107
            return -1;
420
55.4k
          if ((byte & 0xf0) == 0x40) {
421
            // another REX prefix, but we only remember the last one
422
6.36k
            if (consumeByte(insn, &byte))
423
0
              return -1;
424
6.36k
          } else
425
49.0k
            break;
426
55.4k
        }
427
428
        // recover the last REX byte if next byte is not a legacy prefix
429
49.0k
        switch (byte) {
430
1.52k
          case 0xf2:  /* REPNE/REPNZ */
431
2.75k
          case 0xf3:  /* REP or REPE/REPZ */
432
4.76k
          case 0xf0:  /* LOCK */
433
5.00k
          case 0x2e:  /* CS segment override -OR- Branch not taken */
434
5.20k
          case 0x36:  /* SS segment override -OR- Branch taken */
435
5.50k
          case 0x3e:  /* DS segment override */
436
5.81k
          case 0x26:  /* ES segment override */
437
5.93k
          case 0x64:  /* FS segment override */
438
6.14k
          case 0x65:  /* GS segment override */
439
6.54k
          case 0x66:  /* Operand-size override */
440
7.12k
          case 0x67:  /* Address-size override */
441
7.12k
            break;
442
41.9k
          default:    /* Not a prefix byte */
443
41.9k
            unconsumeByte(insn);
444
41.9k
            break;
445
49.0k
        }
446
220k
      } else {
447
220k
        unconsumeByte(insn);
448
220k
      }
449
269k
    }
450
451
    /* If we fail reading prefixes, just stop here and let the opcode reader deal with it */
452
750k
    if (consumeByte(insn, &byte))
453
156
      return -1;
454
455
749k
    if (insn->readerCursor - 1 == insn->startLocation
456
607k
        && (byte == 0xf2 || byte == 0xf3)) {
457
      // prefix requires next byte
458
44.1k
      if (lookAtByte(insn, &nextByte))
459
99
        return -1;
460
461
      /*
462
       * If the byte is 0xf2 or 0xf3, and any of the following conditions are
463
       * met:
464
       * - it is followed by a LOCK (0xf0) prefix
465
       * - it is followed by an xchg instruction
466
       * then it should be disassembled as a xacquire/xrelease not repne/rep.
467
       */
468
44.0k
      if (((nextByte == 0xf0) ||
469
42.6k
        ((nextByte & 0xfe) == 0x86 || (nextByte & 0xf8) == 0x90))) {
470
3.73k
        insn->xAcquireRelease = byte;
471
3.73k
      }
472
473
      /*
474
       * Also if the byte is 0xf3, and the following condition is met:
475
       * - it is followed by a "mov mem, reg" (opcode 0x88/0x89) or
476
       *                       "mov mem, imm" (opcode 0xc6/0xc7) instructions.
477
       * then it should be disassembled as an xrelease not rep.
478
       */
479
44.0k
      if (byte == 0xf3 && (nextByte == 0x88 || nextByte == 0x89 ||
480
18.9k
            nextByte == 0xc6 || nextByte == 0xc7)) {
481
545
        insn->xAcquireRelease = byte;
482
545
      }
483
484
44.0k
      if (isREX(insn, nextByte)) {
485
4.86k
        uint8_t nnextByte;
486
487
        // Go to REX prefix after the current one
488
4.86k
        if (consumeByte(insn, &nnextByte))
489
0
          return -1;
490
491
        // We should be able to read next byte after REX prefix
492
4.86k
        if (lookAtByte(insn, &nnextByte))
493
5
          return -1;
494
495
4.85k
        unconsumeByte(insn);
496
4.85k
      }
497
44.0k
    }
498
499
749k
    switch (byte) {
500
39.4k
      case 0xf0:  /* LOCK */
501
69.7k
      case 0xf2:  /* REPNE/REPNZ */
502
92.5k
      case 0xf3:  /* REP or REPE/REPZ */
503
        // only accept the last prefix
504
92.5k
        setPrefixPresent(insn, byte);
505
92.5k
        insn->prefix0 = byte;
506
92.5k
        break;
507
508
6.09k
      case 0x2e:  /* CS segment override -OR- Branch not taken */
509
7.64k
      case 0x36:  /* SS segment override -OR- Branch taken */
510
10.2k
      case 0x3e:  /* DS segment override */
511
12.4k
      case 0x26:  /* ES segment override */
512
15.6k
      case 0x64:  /* FS segment override */
513
19.7k
      case 0x65:  /* GS segment override */
514
19.7k
        switch (byte) {
515
6.09k
          case 0x2e:
516
6.09k
            insn->segmentOverride = SEG_OVERRIDE_CS;
517
6.09k
            insn->prefix1 = byte;
518
6.09k
            break;
519
1.55k
          case 0x36:
520
1.55k
            insn->segmentOverride = SEG_OVERRIDE_SS;
521
1.55k
            insn->prefix1 = byte;
522
1.55k
            break;
523
2.64k
          case 0x3e:
524
2.64k
            insn->segmentOverride = SEG_OVERRIDE_DS;
525
2.64k
            insn->prefix1 = byte;
526
2.64k
            break;
527
2.16k
          case 0x26:
528
2.16k
            insn->segmentOverride = SEG_OVERRIDE_ES;
529
2.16k
            insn->prefix1 = byte;
530
2.16k
            break;
531
3.21k
          case 0x64:
532
3.21k
            insn->segmentOverride = SEG_OVERRIDE_FS;
533
3.21k
            insn->prefix1 = byte;
534
3.21k
            break;
535
4.09k
          case 0x65:
536
4.09k
            insn->segmentOverride = SEG_OVERRIDE_GS;
537
4.09k
            insn->prefix1 = byte;
538
4.09k
            break;
539
0
          default:
540
            // debug("Unhandled override");
541
0
            return -1;
542
19.7k
        }
543
19.7k
        setPrefixPresent(insn, byte);
544
19.7k
        break;
545
546
16.8k
      case 0x66:  /* Operand-size override */
547
16.8k
        insn->hasOpSize = true;
548
16.8k
        setPrefixPresent(insn, byte);
549
16.8k
        insn->prefix2 = byte;
550
16.8k
        break;
551
552
7.93k
      case 0x67:  /* Address-size override */
553
7.93k
        insn->hasAdSize = true;
554
7.93k
        setPrefixPresent(insn, byte);
555
7.93k
        insn->prefix3 = byte;
556
7.93k
        break;
557
612k
      default:    /* Not a prefix byte */
558
612k
        isPrefix = false;
559
612k
        break;
560
749k
    }
561
749k
  }
562
563
612k
  insn->vectorExtensionType = TYPE_NO_VEX_XOP;
564
565
612k
  if (byte == 0x62) {
566
63.9k
    uint8_t byte1, byte2;
567
568
63.9k
    if (consumeByte(insn, &byte1)) {
569
      // dbgprintf(insn, "Couldn't read second byte of EVEX prefix");
570
70
      return -1;
571
70
    }
572
573
63.8k
    if (lookAtByte(insn, &byte2)) {
574
      // dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
575
81
      unconsumeByte(insn); /* unconsume byte1 */
576
81
      unconsumeByte(insn); /* unconsume byte  */
577
63.7k
    } else {
578
63.7k
      if ((insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) &&
579
57.7k
          ((~byte1 & 0xc) == 0xc) && ((byte2 & 0x4) == 0x4)) {
580
57.5k
        insn->vectorExtensionType = TYPE_EVEX;
581
57.5k
      } else {
582
6.23k
        unconsumeByte(insn); /* unconsume byte1 */
583
6.23k
        unconsumeByte(insn); /* unconsume byte  */
584
6.23k
      }
585
63.7k
    }
586
587
63.8k
    if (insn->vectorExtensionType == TYPE_EVEX) {
588
57.5k
      insn->vectorExtensionPrefix[0] = byte;
589
57.5k
      insn->vectorExtensionPrefix[1] = byte1;
590
57.5k
      if (consumeByte(insn, &insn->vectorExtensionPrefix[2])) {
591
        // dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
592
0
        return -1;
593
0
      }
594
595
57.5k
      if (consumeByte(insn, &insn->vectorExtensionPrefix[3])) {
596
        // dbgprintf(insn, "Couldn't read fourth byte of EVEX prefix");
597
24
        return -1;
598
24
      }
599
600
      /* We simulate the REX prefix for simplicity's sake */
601
57.5k
      if (insn->mode == MODE_64BIT) {
602
22.2k
        insn->rexPrefix = 0x40
603
22.2k
          | (wFromEVEX3of4(insn->vectorExtensionPrefix[2]) << 3)
604
22.2k
          | (rFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 2)
605
22.2k
          | (xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 1)
606
22.2k
          | (bFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 0);
607
22.2k
      }
608
609
      // dbgprintf(insn, "Found EVEX prefix 0x%hhx 0x%hhx 0x%hhx 0x%hhx",
610
      //    insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
611
      //    insn->vectorExtensionPrefix[2], insn->vectorExtensionPrefix[3]);
612
57.5k
    }
613
548k
  } else if (byte == 0xc4) {
614
5.39k
    uint8_t byte1;
615
616
5.39k
    if (lookAtByte(insn, &byte1)) {
617
      // dbgprintf(insn, "Couldn't read second byte of VEX");
618
9
      return -1;
619
9
    }
620
621
5.38k
    if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)
622
4.81k
      insn->vectorExtensionType = TYPE_VEX_3B;
623
571
    else
624
571
      unconsumeByte(insn);
625
626
5.38k
    if (insn->vectorExtensionType == TYPE_VEX_3B) {
627
4.81k
      insn->vectorExtensionPrefix[0] = byte;
628
4.81k
      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
629
4.81k
      consumeByte(insn, &insn->vectorExtensionPrefix[2]);
630
631
      /* We simulate the REX prefix for simplicity's sake */
632
4.81k
      if (insn->mode == MODE_64BIT)
633
3.12k
        insn->rexPrefix = 0x40
634
3.12k
          | (wFromVEX3of3(insn->vectorExtensionPrefix[2]) << 3)
635
3.12k
          | (rFromVEX2of3(insn->vectorExtensionPrefix[1]) << 2)
636
3.12k
          | (xFromVEX2of3(insn->vectorExtensionPrefix[1]) << 1)
637
3.12k
          | (bFromVEX2of3(insn->vectorExtensionPrefix[1]) << 0);
638
639
      // dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx 0x%hhx",
640
      //    insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
641
      //    insn->vectorExtensionPrefix[2]);
642
4.81k
    }
643
543k
  } else if (byte == 0xc5) {
644
11.4k
    uint8_t byte1;
645
646
11.4k
    if (lookAtByte(insn, &byte1)) {
647
      // dbgprintf(insn, "Couldn't read second byte of VEX");
648
10
      return -1;
649
10
    }
650
651
11.4k
    if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)
652
10.0k
      insn->vectorExtensionType = TYPE_VEX_2B;
653
1.39k
    else
654
1.39k
      unconsumeByte(insn);
655
656
11.4k
    if (insn->vectorExtensionType == TYPE_VEX_2B) {
657
10.0k
      insn->vectorExtensionPrefix[0] = byte;
658
10.0k
      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
659
660
10.0k
      if (insn->mode == MODE_64BIT)
661
1.89k
        insn->rexPrefix = 0x40
662
1.89k
          | (rFromVEX2of2(insn->vectorExtensionPrefix[1]) << 2);
663
664
10.0k
      switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
665
3.85k
        default:
666
3.85k
          break;
667
6.16k
        case VEX_PREFIX_66:
668
6.16k
          insn->hasOpSize = true;
669
6.16k
          break;
670
10.0k
      }
671
672
      // dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx",
673
      //    insn->vectorExtensionPrefix[0],
674
      //    insn->vectorExtensionPrefix[1]);
675
10.0k
    }
676
531k
  } else if (byte == 0x8f) {
677
7.29k
    uint8_t byte1;
678
679
7.29k
    if (lookAtByte(insn, &byte1)) {
680
      // dbgprintf(insn, "Couldn't read second byte of XOP");
681
9
      return -1;
682
9
    }
683
684
7.28k
    if ((byte1 & 0x38) != 0x0) /* 0 in these 3 bits is a POP instruction. */
685
6.57k
      insn->vectorExtensionType = TYPE_XOP;
686
708
    else
687
708
      unconsumeByte(insn);
688
689
7.28k
    if (insn->vectorExtensionType == TYPE_XOP) {
690
6.57k
      insn->vectorExtensionPrefix[0] = byte;
691
6.57k
      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
692
6.57k
      consumeByte(insn, &insn->vectorExtensionPrefix[2]);
693
694
      /* We simulate the REX prefix for simplicity's sake */
695
6.57k
      if (insn->mode == MODE_64BIT)
696
902
        insn->rexPrefix = 0x40
697
902
          | (wFromXOP3of3(insn->vectorExtensionPrefix[2]) << 3)
698
902
          | (rFromXOP2of3(insn->vectorExtensionPrefix[1]) << 2)
699
902
          | (xFromXOP2of3(insn->vectorExtensionPrefix[1]) << 1)
700
902
          | (bFromXOP2of3(insn->vectorExtensionPrefix[1]) << 0);
701
702
6.57k
      switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
703
6.55k
        default:
704
6.55k
          break;
705
6.55k
        case VEX_PREFIX_66:
706
16
          insn->hasOpSize = true;
707
16
          break;
708
6.57k
      }
709
710
      // dbgprintf(insn, "Found XOP prefix 0x%hhx 0x%hhx 0x%hhx",
711
      //    insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
712
      //    insn->vectorExtensionPrefix[2]);
713
6.57k
    }
714
524k
  } else if (isREX(insn, byte)) {
715
41.9k
    if (lookAtByte(insn, &nextByte))
716
0
      return -1;
717
718
41.9k
    insn->rexPrefix = byte;
719
    // dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
720
41.9k
  } else
721
482k
    unconsumeByte(insn);
722
723
612k
  if (insn->mode == MODE_16BIT) {
724
212k
    insn->registerSize = (insn->hasOpSize ? 4 : 2);
725
212k
    insn->addressSize = (insn->hasAdSize ? 4 : 2);
726
212k
    insn->displacementSize = (insn->hasAdSize ? 4 : 2);
727
212k
    insn->immediateSize = (insn->hasOpSize ? 4 : 2);
728
212k
    insn->immSize = (insn->hasOpSize ? 4 : 2);
729
400k
  } else if (insn->mode == MODE_32BIT) {
730
192k
    insn->registerSize = (insn->hasOpSize ? 2 : 4);
731
192k
    insn->addressSize = (insn->hasAdSize ? 2 : 4);
732
192k
    insn->displacementSize = (insn->hasAdSize ? 2 : 4);
733
192k
    insn->immediateSize = (insn->hasOpSize ? 2 : 4);
734
192k
    insn->immSize = (insn->hasOpSize ? 2 : 4);
735
208k
  } else if (insn->mode == MODE_64BIT) {
736
208k
    if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
737
44.7k
      insn->registerSize       = 8;
738
44.7k
      insn->addressSize = (insn->hasAdSize ? 4 : 8);
739
44.7k
      insn->displacementSize   = 4;
740
44.7k
      insn->immediateSize      = 4;
741
44.7k
      insn->immSize      = 4;
742
163k
    } else {
743
163k
      insn->registerSize = (insn->hasOpSize ? 2 : 4);
744
163k
      insn->addressSize = (insn->hasAdSize ? 4 : 8);
745
163k
      insn->displacementSize = (insn->hasOpSize ? 2 : 4);
746
163k
      insn->immediateSize = (insn->hasOpSize ? 2 : 4);
747
163k
      insn->immSize      = (insn->hasOpSize ? 4 : 8);
748
163k
    }
749
208k
  }
750
751
612k
  return 0;
752
612k
}
753
754
static int readModRM(struct InternalInstruction* insn);
755
756
/*
757
 * readOpcode - Reads the opcode (excepting the ModR/M byte in the case of
758
 *   extended or escape opcodes).
759
 *
760
 * @param insn  - The instruction whose opcode is to be read.
761
 * @return      - 0 if the opcode could be read successfully; nonzero otherwise.
762
 */
763
static int readOpcode(struct InternalInstruction* insn)
764
612k
{
765
612k
  uint8_t current;
766
767
  // dbgprintf(insn, "readOpcode()");
768
769
612k
  insn->opcodeType = ONEBYTE;
770
771
612k
  if (insn->vectorExtensionType == TYPE_EVEX) {
772
57.5k
    switch (mmFromEVEX2of4(insn->vectorExtensionPrefix[1])) {
773
4
      default:
774
        // dbgprintf(insn, "Unhandled mm field for instruction (0x%hhx)",
775
        //    mmFromEVEX2of4(insn->vectorExtensionPrefix[1]));
776
4
        return -1;
777
16.2k
      case VEX_LOB_0F:
778
16.2k
        insn->opcodeType = TWOBYTE;
779
16.2k
        return consumeByte(insn, &insn->opcode);
780
16.1k
      case VEX_LOB_0F38:
781
16.1k
        insn->opcodeType = THREEBYTE_38;
782
16.1k
        return consumeByte(insn, &insn->opcode);
783
25.1k
      case VEX_LOB_0F3A:
784
25.1k
        insn->opcodeType = THREEBYTE_3A;
785
25.1k
        return consumeByte(insn, &insn->opcode);
786
57.5k
    }
787
555k
  } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
788
4.81k
    switch (mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])) {
789
14
      default:
790
        // dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
791
        //    mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
792
14
        return -1;
793
1.33k
      case VEX_LOB_0F:
794
        //insn->twoByteEscape = 0x0f;
795
1.33k
        insn->opcodeType = TWOBYTE;
796
1.33k
        return consumeByte(insn, &insn->opcode);
797
2.18k
      case VEX_LOB_0F38:
798
        //insn->twoByteEscape = 0x0f;
799
2.18k
        insn->opcodeType = THREEBYTE_38;
800
2.18k
        return consumeByte(insn, &insn->opcode);
801
1.28k
      case VEX_LOB_0F3A:
802
        //insn->twoByteEscape = 0x0f;
803
1.28k
        insn->opcodeType = THREEBYTE_3A;
804
1.28k
        return consumeByte(insn, &insn->opcode);
805
4.81k
    }
806
550k
  } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
807
    //insn->twoByteEscape = 0x0f;
808
10.0k
    insn->opcodeType = TWOBYTE;
809
10.0k
    return consumeByte(insn, &insn->opcode);
810
540k
  } else if (insn->vectorExtensionType == TYPE_XOP) {
811
6.57k
    switch (mmmmmFromXOP2of3(insn->vectorExtensionPrefix[1])) {
812
36
      default:
813
        // dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
814
        //    mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
815
36
        return -1;
816
5.73k
      case XOP_MAP_SELECT_8:
817
5.73k
        insn->opcodeType = XOP8_MAP;
818
5.73k
        return consumeByte(insn, &insn->opcode);
819
662
      case XOP_MAP_SELECT_9:
820
662
        insn->opcodeType = XOP9_MAP;
821
662
        return consumeByte(insn, &insn->opcode);
822
143
      case XOP_MAP_SELECT_A:
823
143
        insn->opcodeType = XOPA_MAP;
824
143
        return consumeByte(insn, &insn->opcode);
825
6.57k
    }
826
6.57k
  }
827
828
533k
  if (consumeByte(insn, &current))
829
0
    return -1;
830
831
    // save this first byte for MOVcr, MOVdr, MOVrc, MOVrd
832
533k
    insn->firstByte = current;
833
834
533k
  if (current == 0x0f) {
835
    // dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
836
41.2k
    insn->twoByteEscape = current;
837
838
41.2k
    if (consumeByte(insn, &current))
839
75
      return -1;
840
841
41.1k
    if (current == 0x38) {
842
      // dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
843
1.07k
      if (consumeByte(insn, &current))
844
2
        return -1;
845
846
1.07k
      insn->opcodeType = THREEBYTE_38;
847
40.0k
    } else if (current == 0x3a) {
848
      // dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
849
327
      if (consumeByte(insn, &current))
850
1
        return -1;
851
852
326
      insn->opcodeType = THREEBYTE_3A;
853
39.7k
    } else if (current == 0x0f) {
854
      // dbgprintf(insn, "Found a 3dnow escape prefix (0x%hhx)", current);
855
      // Consume operands before the opcode to comply with the 3DNow encoding
856
779
      if (readModRM(insn))
857
1
        return -1;
858
859
778
      if (consumeByte(insn, &current))
860
2
        return -1;
861
862
776
      insn->opcodeType = THREEDNOW_MAP;
863
38.9k
    } else {
864
      // dbgprintf(insn, "Didn't find a three-byte escape prefix");
865
38.9k
      insn->opcodeType = TWOBYTE;
866
38.9k
    }
867
492k
  } else if (insn->mandatoryPrefix)
868
    // The opcode with mandatory prefix must start with opcode escape.
869
    // If not it's legacy repeat prefix
870
6.98k
    insn->mandatoryPrefix = 0;
871
872
  /*
873
   * At this point we have consumed the full opcode.
874
   * Anything we consume from here on must be unconsumed.
875
   */
876
877
533k
  insn->opcode = current;
878
879
533k
  return 0;
880
533k
}
881
882
// Hacky for FEMMS
883
#define GET_INSTRINFO_ENUM
884
#ifndef CAPSTONE_X86_REDUCE
885
#include "X86GenInstrInfo.inc"
886
#else
887
#include "X86GenInstrInfo_reduce.inc"
888
#endif
889
890
/*
891
 * getIDWithAttrMask - Determines the ID of an instruction, consuming
892
 *   the ModR/M byte as appropriate for extended and escape opcodes,
893
 *   and using a supplied attribute mask.
894
 *
895
 * @param instructionID - A pointer whose target is filled in with the ID of the
896
 *                        instruction.
897
 * @param insn          - The instruction whose ID is to be determined.
898
 * @param attrMask      - The attribute mask to search.
899
 * @return              - 0 if the ModR/M could be read when needed or was not
900
 *                        needed; nonzero otherwise.
901
 */
902
static int getIDWithAttrMask(uint16_t *instructionID,
903
                             struct InternalInstruction* insn,
904
                             uint16_t attrMask)
905
854k
{
906
854k
  bool hasModRMExtension;
907
908
854k
  InstructionContext instructionClass = contextForAttrs(attrMask);
909
910
854k
  hasModRMExtension = modRMRequired(insn->opcodeType,
911
854k
      instructionClass,
912
854k
      insn->opcode);
913
914
854k
  if (hasModRMExtension) {
915
488k
    if (readModRM(insn))
916
1.60k
      return -1;
917
918
486k
    *instructionID = decode(insn->opcodeType,
919
486k
        instructionClass,
920
486k
        insn->opcode,
921
486k
        insn->modRM);
922
486k
  } else {
923
365k
    *instructionID = decode(insn->opcodeType,
924
365k
        instructionClass,
925
365k
        insn->opcode,
926
365k
        0);
927
365k
  }
928
929
852k
  return 0;
930
854k
}
931
932
/*
933
 * is16BitEquivalent - Determines whether two instruction names refer to
934
 * equivalent instructions but one is 16-bit whereas the other is not.
935
 *
936
 * @param orig  - The instruction ID that is not 16-bit
937
 * @param equiv - The instruction ID that is 16-bit
938
 */
939
static bool is16BitEquivalent(unsigned orig, unsigned equiv)
940
190k
{
941
190k
  size_t i;
942
190k
  uint16_t idx;
943
944
190k
  if ((idx = x86_16_bit_eq_lookup[orig]) != 0) {
945
93.5k
    for (i = idx - 1; i < ARR_SIZE(x86_16_bit_eq_tbl) && x86_16_bit_eq_tbl[i].first == orig; i++) {
946
91.3k
      if (x86_16_bit_eq_tbl[i].second == equiv)
947
89.0k
        return true;
948
91.3k
    }
949
91.3k
  }
950
951
101k
  return false;
952
190k
}
953
954
/*
955
 * is64Bit - Determines whether this instruction is a 64-bit instruction.
956
 *
957
 * @param name - The instruction that is not 16-bit
958
 */
959
static bool is64Bit(uint16_t id)
960
18.0k
{
961
18.0k
  unsigned int i = find_insn(id);
962
18.0k
  if (i != -1) {
963
17.9k
    return insns[i].is64bit;
964
17.9k
  }
965
966
  // not found??
967
63
  return false;
968
18.0k
}
969
970
/*
971
 * getID - Determines the ID of an instruction, consuming the ModR/M byte as
972
 *   appropriate for extended and escape opcodes.  Determines the attributes and
973
 *   context for the instruction before doing so.
974
 *
975
 * @param insn  - The instruction whose ID is to be determined.
976
 * @return      - 0 if the ModR/M could be read when needed or was not needed;
977
 *                nonzero otherwise.
978
 */
979
static int getID(struct InternalInstruction *insn)
980
612k
{
981
612k
  uint16_t attrMask;
982
612k
  uint16_t instructionID;
983
984
612k
  attrMask = ATTR_NONE;
985
986
612k
  if (insn->mode == MODE_64BIT)
987
208k
    attrMask |= ATTR_64BIT;
988
989
612k
  if (insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
990
78.8k
    attrMask |= (insn->vectorExtensionType == TYPE_EVEX) ? ATTR_EVEX : ATTR_VEX;
991
992
78.8k
    if (insn->vectorExtensionType == TYPE_EVEX) {
993
57.4k
      switch (ppFromEVEX3of4(insn->vectorExtensionPrefix[2])) {
994
48.8k
        case VEX_PREFIX_66:
995
48.8k
          attrMask |= ATTR_OPSIZE;
996
48.8k
          break;
997
2.09k
        case VEX_PREFIX_F3:
998
2.09k
          attrMask |= ATTR_XS;
999
2.09k
          break;
1000
2.07k
        case VEX_PREFIX_F2:
1001
2.07k
          attrMask |= ATTR_XD;
1002
2.07k
          break;
1003
57.4k
      }
1004
1005
57.4k
      if (zFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1006
6.32k
        attrMask |= ATTR_EVEXKZ;
1007
57.4k
      if (bFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1008
20.9k
        attrMask |= ATTR_EVEXB;
1009
57.4k
      if (aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1010
38.1k
        attrMask |= ATTR_EVEXK;
1011
57.4k
      if (lFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1012
29.8k
        attrMask |= ATTR_EVEXL;
1013
57.4k
      if (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
1014
25.7k
        attrMask |= ATTR_EVEXL2;
1015
57.4k
    } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
1016
4.78k
      switch (ppFromVEX3of3(insn->vectorExtensionPrefix[2])) {
1017
3.43k
        case VEX_PREFIX_66:
1018
3.43k
          attrMask |= ATTR_OPSIZE;
1019
3.43k
          break;
1020
85
        case VEX_PREFIX_F3:
1021
85
          attrMask |= ATTR_XS;
1022
85
          break;
1023
527
        case VEX_PREFIX_F2:
1024
527
          attrMask |= ATTR_XD;
1025
527
          break;
1026
4.78k
      }
1027
1028
4.78k
      if (lFromVEX3of3(insn->vectorExtensionPrefix[2]))
1029
2.18k
        attrMask |= ATTR_VEXL;
1030
16.5k
    } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
1031
10.0k
      switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
1032
6.15k
        case VEX_PREFIX_66:
1033
6.15k
          attrMask |= ATTR_OPSIZE;
1034
6.15k
          break;
1035
777
        case VEX_PREFIX_F3:
1036
777
          attrMask |= ATTR_XS;
1037
777
          break;
1038
744
        case VEX_PREFIX_F2:
1039
744
          attrMask |= ATTR_XD;
1040
744
          break;
1041
10.0k
      }
1042
1043
10.0k
      if (lFromVEX2of2(insn->vectorExtensionPrefix[1]))
1044
7.46k
        attrMask |= ATTR_VEXL;
1045
10.0k
    } else if (insn->vectorExtensionType == TYPE_XOP) {
1046
6.52k
      switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
1047
10
        case VEX_PREFIX_66:
1048
10
          attrMask |= ATTR_OPSIZE;
1049
10
          break;
1050
2
        case VEX_PREFIX_F3:
1051
2
          attrMask |= ATTR_XS;
1052
2
          break;
1053
10
        case VEX_PREFIX_F2:
1054
10
          attrMask |= ATTR_XD;
1055
10
          break;
1056
6.52k
      }
1057
1058
6.52k
      if (lFromXOP3of3(insn->vectorExtensionPrefix[2]))
1059
622
        attrMask |= ATTR_VEXL;
1060
6.52k
    } else {
1061
0
      return -1;
1062
0
    }
1063
533k
  } else if (!insn->mandatoryPrefix) {
1064
    // If we don't have mandatory prefix we should use legacy prefixes here
1065
522k
    if (insn->hasOpSize && (insn->mode != MODE_16BIT))
1066
9.35k
      attrMask |= ATTR_OPSIZE;
1067
522k
    if (insn->hasAdSize)
1068
4.86k
      attrMask |= ATTR_ADSIZE;
1069
522k
    if (insn->opcodeType == ONEBYTE) {
1070
492k
      if (insn->repeatPrefix == 0xf3 && (insn->opcode == 0x90))
1071
        // Special support for PAUSE
1072
356
        attrMask |= ATTR_XS;
1073
492k
    } else {
1074
29.6k
      if (insn->repeatPrefix == 0xf2)
1075
425
        attrMask |= ATTR_XD;
1076
29.2k
      else if (insn->repeatPrefix == 0xf3)
1077
536
        attrMask |= ATTR_XS;
1078
29.6k
    }
1079
522k
  } else {
1080
11.4k
    switch (insn->mandatoryPrefix) {
1081
4.40k
      case 0xf2:
1082
4.40k
        attrMask |= ATTR_XD;
1083
4.40k
        break;
1084
3.16k
      case 0xf3:
1085
3.16k
        attrMask |= ATTR_XS;
1086
3.16k
        break;
1087
3.89k
      case 0x66:
1088
3.89k
        if (insn->mode != MODE_16BIT)
1089
3.14k
          attrMask |= ATTR_OPSIZE;
1090
3.89k
        break;
1091
0
      case 0x67:
1092
0
        attrMask |= ATTR_ADSIZE;
1093
0
        break;
1094
11.4k
    }
1095
1096
11.4k
  }
1097
1098
612k
  if (insn->rexPrefix & 0x08) {
1099
44.6k
    attrMask |= ATTR_REXW;
1100
44.6k
    attrMask &= ~ATTR_ADSIZE;
1101
44.6k
  }
1102
1103
  /*
1104
   * JCXZ/JECXZ need special handling for 16-bit mode because the meaning
1105
   * of the AdSize prefix is inverted w.r.t. 32-bit mode.
1106
   */
1107
612k
  if (insn->mode == MODE_16BIT && insn->opcodeType == ONEBYTE &&
1108
175k
      insn->opcode == 0xE3)
1109
788
    attrMask ^= ATTR_ADSIZE;
1110
1111
  /*
1112
   * In 64-bit mode all f64 superscripted opcodes ignore opcode size prefix
1113
   * CALL/JMP/JCC instructions need to ignore 0x66 and consume 4 bytes
1114
   */
1115
612k
  if ((insn->mode == MODE_64BIT) && insn->hasOpSize) {
1116
9.81k
    switch (insn->opcode) {
1117
379
      case 0xE8:
1118
667
      case 0xE9:
1119
        // Take care of psubsb and other mmx instructions.
1120
667
        if (insn->opcodeType == ONEBYTE) {
1121
251
          attrMask ^= ATTR_OPSIZE;
1122
251
          insn->immediateSize = 4;
1123
251
          insn->displacementSize = 4;
1124
251
        }
1125
667
        break;
1126
313
      case 0x82:
1127
525
      case 0x83:
1128
1.22k
      case 0x84:
1129
1.43k
      case 0x85:
1130
1.77k
      case 0x86:
1131
1.99k
      case 0x87:
1132
2.19k
      case 0x88:
1133
2.45k
      case 0x89:
1134
2.64k
      case 0x8A:
1135
2.87k
      case 0x8B:
1136
3.16k
      case 0x8C:
1137
3.39k
      case 0x8D:
1138
3.63k
      case 0x8E:
1139
3.83k
      case 0x8F:
1140
        // Take care of lea and three byte ops.
1141
3.83k
        if (insn->opcodeType == TWOBYTE) {
1142
399
          attrMask ^= ATTR_OPSIZE;
1143
399
          insn->immediateSize = 4;
1144
399
          insn->displacementSize = 4;
1145
399
        }
1146
3.83k
        break;
1147
9.81k
    }
1148
9.81k
  }
1149
1150
  /* The following clauses compensate for limitations of the tables. */
1151
612k
  if (insn->mode != MODE_64BIT &&
1152
404k
      insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
1153
50.6k
    if (getIDWithAttrMask(&instructionID, insn, attrMask)) {
1154
17
      return -1;
1155
17
    }
1156
1157
    /*
1158
     * The tables can't distinquish between cases where the W-bit is used to
1159
     * select register size and cases where its a required part of the opcode.
1160
     */
1161
50.6k
    if ((insn->vectorExtensionType == TYPE_EVEX &&
1162
35.2k
          wFromEVEX3of4(insn->vectorExtensionPrefix[2])) ||
1163
33.2k
        (insn->vectorExtensionType == TYPE_VEX_3B &&
1164
1.68k
         wFromVEX3of3(insn->vectorExtensionPrefix[2])) ||
1165
32.7k
        (insn->vectorExtensionType == TYPE_XOP &&
1166
18.0k
         wFromXOP3of3(insn->vectorExtensionPrefix[2]))) {
1167
18.0k
      uint16_t instructionIDWithREXW;
1168
1169
18.0k
      if (getIDWithAttrMask(&instructionIDWithREXW,
1170
18.0k
            insn, attrMask | ATTR_REXW)) {
1171
1
        insn->instructionID = instructionID;
1172
1
        insn->spec = specifierForUID(instructionID);
1173
1
        return 0;
1174
1
      }
1175
1176
      // If not a 64-bit instruction. Switch the opcode.
1177
18.0k
      if (!is64Bit(instructionIDWithREXW)) {
1178
17.2k
        insn->instructionID = instructionIDWithREXW;
1179
17.2k
        insn->spec = specifierForUID(instructionIDWithREXW);
1180
1181
17.2k
        return 0;
1182
17.2k
      }
1183
18.0k
    }
1184
50.6k
  }
1185
1186
  /*
1187
   * Absolute moves, umonitor, and movdir64b need special handling.
1188
   * -For 16-bit mode because the meaning of the AdSize and OpSize prefixes are
1189
   *  inverted w.r.t.
1190
   * -For 32-bit mode we need to ensure the ADSIZE prefix is observed in
1191
   *  any position.
1192
   */
1193
595k
  if ((insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0)) ||
1194
588k
      (insn->opcodeType == TWOBYTE && (insn->opcode == 0xAE)) ||
1195
588k
      (insn->opcodeType == THREEBYTE_38 && insn->opcode == 0xF8)) {
1196
    /* Make sure we observed the prefixes in any position. */
1197
7.05k
    if (insn->hasAdSize)
1198
362
      attrMask |= ATTR_ADSIZE;
1199
1200
7.05k
    if (insn->hasOpSize)
1201
475
      attrMask |= ATTR_OPSIZE;
1202
1203
    /* In 16-bit, invert the attributes. */
1204
7.05k
    if (insn->mode == MODE_16BIT) {
1205
3.11k
      attrMask ^= ATTR_ADSIZE;
1206
1207
      /* The OpSize attribute is only valid with the absolute moves. */
1208
3.11k
      if (insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0))
1209
2.63k
        attrMask ^= ATTR_OPSIZE;
1210
3.11k
    }
1211
1212
7.05k
    if (getIDWithAttrMask(&instructionID, insn, attrMask)) {
1213
6
      return -1;
1214
6
    }
1215
1216
7.04k
    insn->instructionID = instructionID;
1217
7.04k
    insn->spec = specifierForUID(instructionID);
1218
1219
7.04k
    return 0;
1220
7.05k
  }
1221
588k
  if (getIDWithAttrMask(&instructionID, insn, attrMask)) {
1222
1.57k
    return -1;
1223
1.57k
  }
1224
1225
586k
  if ((insn->mode == MODE_16BIT || insn->hasOpSize) &&
1226
215k
      !(attrMask & ATTR_OPSIZE)) {
1227
    /*
1228
     * The instruction tables make no distinction between instructions that
1229
     * allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
1230
     * particular spot (i.e., many MMX operations).  In general we're
1231
     * conservative, but in the specific case where OpSize is present but not
1232
     * in the right place we check if there's a 16-bit operation.
1233
     */
1234
190k
    const struct InstructionSpecifier *spec;
1235
190k
    uint16_t instructionIDWithOpsize;
1236
1237
190k
    spec = specifierForUID(instructionID);
1238
1239
190k
    if (getIDWithAttrMask(&instructionIDWithOpsize,
1240
190k
          insn,
1241
190k
          attrMask | ATTR_OPSIZE)) {
1242
      /*
1243
       * ModRM required with OpSize but not present; give up and return version
1244
       * without OpSize set
1245
       */
1246
1
      insn->instructionID = instructionID;
1247
1
      insn->spec = spec;
1248
1249
1
      return 0;
1250
1
    }
1251
1252
190k
    if (is16BitEquivalent(instructionID, instructionIDWithOpsize) &&
1253
89.0k
        (insn->mode == MODE_16BIT) ^ insn->hasOpSize) {
1254
88.2k
      insn->instructionID = instructionIDWithOpsize;
1255
88.2k
      insn->spec = specifierForUID(instructionIDWithOpsize);
1256
101k
    } else {
1257
101k
      insn->instructionID = instructionID;
1258
101k
      insn->spec = spec;
1259
101k
    }
1260
1261
190k
    return 0;
1262
190k
  }
1263
1264
396k
  if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
1265
1.93k
      insn->rexPrefix & 0x01) {
1266
    /*
1267
     * NOOP shouldn't decode as NOOP if REX.b is set. Instead
1268
     * it should decode as XCHG %r8, %eax.
1269
     */
1270
229
    const struct InstructionSpecifier *spec;
1271
229
    uint16_t instructionIDWithNewOpcode;
1272
229
    const struct InstructionSpecifier *specWithNewOpcode;
1273
1274
229
    spec = specifierForUID(instructionID);
1275
1276
    /* Borrow opcode from one of the other XCHGar opcodes */
1277
229
    insn->opcode = 0x91;
1278
1279
229
    if (getIDWithAttrMask(&instructionIDWithNewOpcode, insn, attrMask)) {
1280
0
      insn->opcode = 0x90;
1281
1282
0
      insn->instructionID = instructionID;
1283
0
      insn->spec = spec;
1284
1285
0
      return 0;
1286
0
    }
1287
1288
229
    specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
1289
1290
    /* Change back */
1291
229
    insn->opcode = 0x90;
1292
1293
229
    insn->instructionID = instructionIDWithNewOpcode;
1294
229
    insn->spec = specWithNewOpcode;
1295
1296
229
    return 0;
1297
229
  }
1298
1299
396k
  insn->instructionID = instructionID;
1300
396k
  insn->spec = specifierForUID(insn->instructionID);
1301
1302
396k
  return 0;
1303
396k
}
1304
1305
/*
1306
 * readSIB - Consumes the SIB byte to determine addressing information for an
1307
 *   instruction.
1308
 *
1309
 * @param insn  - The instruction whose SIB byte is to be read.
1310
 * @return      - 0 if the SIB byte was successfully read; nonzero otherwise.
1311
 */
1312
static int readSIB(struct InternalInstruction* insn)
1313
17.7k
{
1314
17.7k
  SIBBase sibBaseBase = SIB_BASE_NONE;
1315
17.7k
  uint8_t index, base;
1316
1317
  // dbgprintf(insn, "readSIB()");
1318
1319
17.7k
  if (insn->consumedSIB)
1320
0
    return 0;
1321
1322
17.7k
  insn->consumedSIB = true;
1323
1324
17.7k
  switch (insn->addressSize) {
1325
0
    case 2:
1326
      // dbgprintf(insn, "SIB-based addressing doesn't work in 16-bit mode");
1327
0
      return -1;
1328
8.14k
    case 4:
1329
8.14k
      insn->sibIndexBase = SIB_INDEX_EAX;
1330
8.14k
      sibBaseBase = SIB_BASE_EAX;
1331
8.14k
      break;
1332
9.56k
    case 8:
1333
9.56k
      insn->sibIndexBase = SIB_INDEX_RAX;
1334
9.56k
      sibBaseBase = SIB_BASE_RAX;
1335
9.56k
      break;
1336
17.7k
  }
1337
1338
17.7k
  if (consumeByte(insn, &insn->sib))
1339
26
    return -1;
1340
1341
17.6k
  index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
1342
1343
17.6k
  if (index == 0x4) {
1344
3.02k
    insn->sibIndex = SIB_INDEX_NONE;
1345
14.6k
  } else {
1346
14.6k
    insn->sibIndex = (SIBIndex)(insn->sibIndexBase + index);
1347
14.6k
  }
1348
1349
17.6k
  insn->sibScale = 1 << scaleFromSIB(insn->sib);
1350
1351
17.6k
  base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
1352
1353
17.6k
  switch (base) {
1354
2.04k
    case 0x5:
1355
2.49k
    case 0xd:
1356
2.49k
      switch (modFromModRM(insn->modRM)) {
1357
1.14k
        case 0x0:
1358
1.14k
          insn->eaDisplacement = EA_DISP_32;
1359
1.14k
          insn->sibBase = SIB_BASE_NONE;
1360
1.14k
          break;
1361
1.10k
        case 0x1:
1362
1.10k
          insn->eaDisplacement = EA_DISP_8;
1363
1.10k
          insn->sibBase = (SIBBase)(sibBaseBase + base);
1364
1.10k
          break;
1365
241
        case 0x2:
1366
241
          insn->eaDisplacement = EA_DISP_32;
1367
241
          insn->sibBase = (SIBBase)(sibBaseBase + base);
1368
241
          break;
1369
0
        case 0x3:
1370
          // debug("Cannot have Mod = 0b11 and a SIB byte");
1371
0
          return -1;
1372
2.49k
      }
1373
2.49k
      break;
1374
15.1k
    default:
1375
15.1k
      insn->sibBase = (SIBBase)(sibBaseBase + base);
1376
15.1k
      break;
1377
17.6k
  }
1378
1379
17.6k
  return 0;
1380
17.6k
}
1381
1382
/*
1383
 * readDisplacement - Consumes the displacement of an instruction.
1384
 *
1385
 * @param insn  - The instruction whose displacement is to be read.
1386
 * @return      - 0 if the displacement byte was successfully read; nonzero
1387
 *                otherwise.
1388
 */
1389
static int readDisplacement(struct InternalInstruction* insn)
1390
115k
{
1391
115k
  int8_t d8;
1392
115k
  int16_t d16;
1393
115k
  int32_t d32;
1394
1395
  // dbgprintf(insn, "readDisplacement()");
1396
1397
115k
  if (insn->consumedDisplacement)
1398
0
    return 0;
1399
1400
115k
  insn->consumedDisplacement = true;
1401
115k
  insn->displacementOffset = insn->readerCursor - insn->startLocation;
1402
1403
115k
  switch (insn->eaDisplacement) {
1404
35.8k
    case EA_DISP_NONE:
1405
35.8k
      insn->consumedDisplacement = false;
1406
35.8k
      break;
1407
53.4k
    case EA_DISP_8:
1408
53.4k
      if (consumeInt8(insn, &d8))
1409
136
        return -1;
1410
53.2k
      insn->displacement = d8;
1411
53.2k
      break;
1412
11.6k
    case EA_DISP_16:
1413
11.6k
      if (consumeInt16(insn, &d16))
1414
70
        return -1;
1415
11.5k
      insn->displacement = d16;
1416
11.5k
      break;
1417
14.2k
    case EA_DISP_32:
1418
14.2k
      if (consumeInt32(insn, &d32))
1419
190
        return -1;
1420
14.0k
      insn->displacement = d32;
1421
14.0k
      break;
1422
115k
  }
1423
1424
1425
114k
  return 0;
1426
115k
}
1427
1428
/*
1429
 * readModRM - Consumes all addressing information (ModR/M byte, SIB byte, and
1430
 *   displacement) for an instruction and interprets it.
1431
 *
1432
 * @param insn  - The instruction whose addressing information is to be read.
1433
 * @return      - 0 if the information was successfully read; nonzero otherwise.
1434
 */
1435
static int readModRM(struct InternalInstruction* insn)
1436
1.10M
{
1437
1.10M
  uint8_t mod, rm, reg, evexrm;
1438
1439
  // dbgprintf(insn, "readModRM()");
1440
1441
1.10M
  if (insn->consumedModRM)
1442
746k
    return 0;
1443
1444
353k
  insn->modRMOffset = (uint8_t)(insn->readerCursor - insn->startLocation);
1445
1446
353k
  if (consumeByte(insn, &insn->modRM))
1447
1.18k
    return -1;
1448
1449
352k
  insn->consumedModRM = true;
1450
1451
  // save original ModRM for later reference
1452
352k
  insn->orgModRM = insn->modRM;
1453
1454
  // handle MOVcr, MOVdr, MOVrc, MOVrd by pretending they have MRM.mod = 3
1455
352k
  if ((insn->firstByte == 0x0f && insn->opcodeType == TWOBYTE) &&
1456
37.3k
      (insn->opcode >= 0x20 && insn->opcode <= 0x23 ))
1457
1.02k
    insn->modRM |= 0xC0;
1458
1459
352k
  mod = modFromModRM(insn->modRM);
1460
352k
  rm  = rmFromModRM(insn->modRM);
1461
352k
  reg = regFromModRM(insn->modRM);
1462
1463
  /*
1464
   * This goes by insn->registerSize to pick the correct register, which messes
1465
   * up if we're using (say) XMM or 8-bit register operands.  That gets fixed in
1466
   * fixupReg().
1467
   */
1468
352k
  switch (insn->registerSize) {
1469
123k
    case 2:
1470
123k
      insn->regBase = MODRM_REG_AX;
1471
123k
      insn->eaRegBase = EA_REG_AX;
1472
123k
      break;
1473
193k
    case 4:
1474
193k
      insn->regBase = MODRM_REG_EAX;
1475
193k
      insn->eaRegBase = EA_REG_EAX;
1476
193k
      break;
1477
35.8k
    case 8:
1478
35.8k
      insn->regBase = MODRM_REG_RAX;
1479
35.8k
      insn->eaRegBase = EA_REG_RAX;
1480
35.8k
      break;
1481
352k
  }
1482
1483
352k
  reg |= rFromREX(insn->rexPrefix) << 3;
1484
352k
  rm  |= bFromREX(insn->rexPrefix) << 3;
1485
1486
352k
  evexrm = 0;
1487
352k
  if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT) {
1488
22.1k
    reg |= r2FromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1489
22.1k
    evexrm = xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1490
22.1k
  }
1491
1492
352k
  insn->reg = (Reg)(insn->regBase + reg);
1493
1494
352k
  switch (insn->addressSize) {
1495
115k
    case 2: {
1496
115k
      EABase eaBaseBase = EA_BASE_BX_SI;
1497
1498
115k
      switch (mod) {
1499
65.7k
        case 0x0:
1500
65.7k
          if (rm == 0x6) {
1501
3.25k
            insn->eaBase = EA_BASE_NONE;
1502
3.25k
            insn->eaDisplacement = EA_DISP_16;
1503
3.25k
            if (readDisplacement(insn))
1504
13
              return -1;
1505
62.5k
          } else {
1506
62.5k
            insn->eaBase = (EABase)(eaBaseBase + rm);
1507
62.5k
            insn->eaDisplacement = EA_DISP_NONE;
1508
62.5k
          }
1509
65.7k
          break;
1510
65.7k
        case 0x1:
1511
16.1k
          insn->eaBase = (EABase)(eaBaseBase + rm);
1512
16.1k
          insn->eaDisplacement = EA_DISP_8;
1513
16.1k
          insn->displacementSize = 1;
1514
16.1k
          if (readDisplacement(insn))
1515
36
            return -1;
1516
16.0k
          break;
1517
16.0k
        case 0x2:
1518
8.34k
          insn->eaBase = (EABase)(eaBaseBase + rm);
1519
8.34k
          insn->eaDisplacement = EA_DISP_16;
1520
8.34k
          if (readDisplacement(insn))
1521
57
            return -1;
1522
8.28k
          break;
1523
24.8k
        case 0x3:
1524
24.8k
          insn->eaBase = (EABase)(insn->eaRegBase + rm);
1525
24.8k
          if (readDisplacement(insn))
1526
0
            return -1;
1527
24.8k
          break;
1528
115k
      }
1529
114k
      break;
1530
115k
    }
1531
1532
114k
    case 4:
1533
237k
    case 8: {
1534
237k
      EABase eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1535
1536
237k
      switch (mod) {
1537
0
        default: break;
1538
122k
        case 0x0:
1539
122k
          insn->eaDisplacement = EA_DISP_NONE; /* readSIB may override this */
1540
          // In determining whether RIP-relative mode is used (rm=5),
1541
          // or whether a SIB byte is present (rm=4),
1542
          // the extension bits (REX.b and EVEX.x) are ignored.
1543
122k
          switch (rm & 7) {
1544
12.1k
            case 0x4: // SIB byte is present
1545
12.1k
              insn->eaBase = (insn->addressSize == 4 ?
1546
6.08k
                  EA_BASE_sib : EA_BASE_sib64);
1547
12.1k
              if (readSIB(insn) || readDisplacement(insn))
1548
13
                return -1;
1549
12.1k
              break;
1550
12.1k
            case 0x5: // RIP-relative
1551
2.67k
              insn->eaBase = EA_BASE_NONE;
1552
2.67k
              insn->eaDisplacement = EA_DISP_32;
1553
2.67k
              if (readDisplacement(insn))
1554
30
                return -1;
1555
2.64k
              break;
1556
108k
            default:
1557
108k
              insn->eaBase = (EABase)(eaBaseBase + rm);
1558
108k
              break;
1559
122k
          }
1560
122k
          break;
1561
122k
        case 0x1:
1562
37.3k
          insn->displacementSize = 1;
1563
          /* FALLTHROUGH */
1564
47.7k
        case 0x2:
1565
47.7k
          insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1566
47.7k
          switch (rm & 7) {
1567
5.55k
            case 0x4: // SIB byte is present
1568
5.55k
              insn->eaBase = EA_BASE_sib;
1569
5.55k
              if (readSIB(insn) || readDisplacement(insn))
1570
47
                return -1;
1571
5.51k
              break;
1572
42.2k
            default:
1573
42.2k
              insn->eaBase = (EABase)(eaBaseBase + rm);
1574
42.2k
              if (readDisplacement(insn))
1575
226
                return -1;
1576
41.9k
              break;
1577
47.7k
          }
1578
47.5k
          break;
1579
67.1k
        case 0x3:
1580
67.1k
          insn->eaDisplacement = EA_DISP_NONE;
1581
67.1k
          insn->eaBase = (EABase)(insn->eaRegBase + rm + evexrm);
1582
67.1k
          break;
1583
237k
      }
1584
1585
237k
      break;
1586
237k
    }
1587
352k
  } /* switch (insn->addressSize) */
1588
1589
352k
  return 0;
1590
352k
}
1591
1592
#define GENERIC_FIXUP_FUNC(name, base, prefix, mask)      \
1593
  static uint16_t name(struct InternalInstruction *insn,  \
1594
                       OperandType type,                  \
1595
                       uint8_t index,                     \
1596
407k
                       uint8_t *valid) {                  \
1597
407k
    *valid = 1;                                           \
1598
407k
    switch (type) {                                       \
1599
0
    default:                                              \
1600
0
      *valid = 0;                                         \
1601
0
      return 0;                                           \
1602
82.6k
    case TYPE_Rv:                                         \
1603
82.6k
      return base + index;                                \
1604
112k
    case TYPE_R8:                                         \
1605
112k
      index &= mask;                                      \
1606
112k
      if (index > 0xf)                                    \
1607
112k
        *valid = 0;                                       \
1608
112k
      if (insn->rexPrefix &&                              \
1609
112k
         index >= 4 && index <= 7) {                      \
1610
1.80k
        return prefix##_SPL + (index - 4);                \
1611
111k
      } else {                                            \
1612
111k
        return prefix##_AL + index;                       \
1613
111k
      }                                                   \
1614
112k
    case TYPE_R16:                                        \
1615
4.11k
      index &= mask;                                      \
1616
4.11k
      if (index > 0xf)                                    \
1617
4.11k
        *valid = 0;                                       \
1618
4.11k
      return prefix##_AX + index;                         \
1619
112k
    case TYPE_R32:                                        \
1620
2.10k
      index &= mask;                                      \
1621
2.10k
      if (index > 0xf)                                    \
1622
2.10k
        *valid = 0;                                       \
1623
2.10k
      return prefix##_EAX + index;                        \
1624
112k
    case TYPE_R64:                                        \
1625
12.5k
      index &= mask;                                      \
1626
12.5k
      if (index > 0xf)                                    \
1627
12.5k
        *valid = 0;                                       \
1628
12.5k
      return prefix##_RAX + index;                        \
1629
112k
    case TYPE_ZMM:                                        \
1630
38.9k
      return prefix##_ZMM0 + index;                       \
1631
112k
    case TYPE_YMM:                                        \
1632
36.9k
      return prefix##_YMM0 + index;                       \
1633
112k
    case TYPE_XMM:                                        \
1634
71.4k
      return prefix##_XMM0 + index;                       \
1635
112k
    case TYPE_VK:                                         \
1636
32.2k
      index &= 0xf;                                       \
1637
32.2k
      if (index > 7)                                      \
1638
32.2k
        *valid = 0;                                       \
1639
32.2k
      return prefix##_K0 + index;                         \
1640
112k
    case TYPE_MM64:                                       \
1641
6.00k
      return prefix##_MM0 + (index & 0x7);                \
1642
112k
    case TYPE_SEGMENTREG:                                 \
1643
1.11k
      if ((index & 7) > 5)                                \
1644
1.11k
        *valid = 0;                                       \
1645
1.11k
      return prefix##_ES + (index & 7);                   \
1646
112k
    case TYPE_DEBUGREG:                                   \
1647
662
      return prefix##_DR0 + index;                        \
1648
112k
    case TYPE_CONTROLREG:                                 \
1649
366
      return prefix##_CR0 + index;                        \
1650
112k
    case TYPE_BNDR:                                       \
1651
5.35k
      if (index > 3)                                      \
1652
5.35k
        *valid = 0;                                       \
1653
5.35k
      return prefix##_BND0 + index;                       \
1654
112k
    case TYPE_MVSIBX:                                     \
1655
0
      return prefix##_XMM0 + index;                       \
1656
112k
    case TYPE_MVSIBY:                                     \
1657
0
      return prefix##_YMM0 + index;                       \
1658
112k
    case TYPE_MVSIBZ:                                     \
1659
0
      return prefix##_ZMM0 + index;                       \
1660
407k
    }                                                     \
1661
407k
  }
X86DisassemblerDecoder.c:fixupRegValue
Line
Count
Source
1596
318k
                       uint8_t *valid) {                  \
1597
318k
    *valid = 1;                                           \
1598
318k
    switch (type) {                                       \
1599
0
    default:                                              \
1600
0
      *valid = 0;                                         \
1601
0
      return 0;                                           \
1602
61.4k
    case TYPE_Rv:                                         \
1603
61.4k
      return base + index;                                \
1604
89.4k
    case TYPE_R8:                                         \
1605
89.4k
      index &= mask;                                      \
1606
89.4k
      if (index > 0xf)                                    \
1607
89.4k
        *valid = 0;                                       \
1608
89.4k
      if (insn->rexPrefix &&                              \
1609
89.4k
         index >= 4 && index <= 7) {                      \
1610
1.16k
        return prefix##_SPL + (index - 4);                \
1611
88.3k
      } else {                                            \
1612
88.3k
        return prefix##_AL + index;                       \
1613
88.3k
      }                                                   \
1614
89.4k
    case TYPE_R16:                                        \
1615
2.85k
      index &= mask;                                      \
1616
2.85k
      if (index > 0xf)                                    \
1617
2.85k
        *valid = 0;                                       \
1618
2.85k
      return prefix##_AX + index;                         \
1619
89.4k
    case TYPE_R32:                                        \
1620
805
      index &= mask;                                      \
1621
805
      if (index > 0xf)                                    \
1622
805
        *valid = 0;                                       \
1623
805
      return prefix##_EAX + index;                        \
1624
89.4k
    case TYPE_R64:                                        \
1625
6.61k
      index &= mask;                                      \
1626
6.61k
      if (index > 0xf)                                    \
1627
6.61k
        *valid = 0;                                       \
1628
6.61k
      return prefix##_RAX + index;                        \
1629
89.4k
    case TYPE_ZMM:                                        \
1630
30.7k
      return prefix##_ZMM0 + index;                       \
1631
89.4k
    case TYPE_YMM:                                        \
1632
29.4k
      return prefix##_YMM0 + index;                       \
1633
89.4k
    case TYPE_XMM:                                        \
1634
57.6k
      return prefix##_XMM0 + index;                       \
1635
89.4k
    case TYPE_VK:                                         \
1636
29.6k
      index &= 0xf;                                       \
1637
29.6k
      if (index > 7)                                      \
1638
29.6k
        *valid = 0;                                       \
1639
29.6k
      return prefix##_K0 + index;                         \
1640
89.4k
    case TYPE_MM64:                                       \
1641
3.36k
      return prefix##_MM0 + (index & 0x7);                \
1642
89.4k
    case TYPE_SEGMENTREG:                                 \
1643
1.11k
      if ((index & 7) > 5)                                \
1644
1.11k
        *valid = 0;                                       \
1645
1.11k
      return prefix##_ES + (index & 7);                   \
1646
89.4k
    case TYPE_DEBUGREG:                                   \
1647
662
      return prefix##_DR0 + index;                        \
1648
89.4k
    case TYPE_CONTROLREG:                                 \
1649
366
      return prefix##_CR0 + index;                        \
1650
89.4k
    case TYPE_BNDR:                                       \
1651
4.80k
      if (index > 3)                                      \
1652
4.80k
        *valid = 0;                                       \
1653
4.80k
      return prefix##_BND0 + index;                       \
1654
89.4k
    case TYPE_MVSIBX:                                     \
1655
0
      return prefix##_XMM0 + index;                       \
1656
89.4k
    case TYPE_MVSIBY:                                     \
1657
0
      return prefix##_YMM0 + index;                       \
1658
89.4k
    case TYPE_MVSIBZ:                                     \
1659
0
      return prefix##_ZMM0 + index;                       \
1660
318k
    }                                                     \
1661
318k
  }
X86DisassemblerDecoder.c:fixupRMValue
Line
Count
Source
1596
88.4k
                       uint8_t *valid) {                  \
1597
88.4k
    *valid = 1;                                           \
1598
88.4k
    switch (type) {                                       \
1599
0
    default:                                              \
1600
0
      *valid = 0;                                         \
1601
0
      return 0;                                           \
1602
21.2k
    case TYPE_Rv:                                         \
1603
21.2k
      return base + index;                                \
1604
23.4k
    case TYPE_R8:                                         \
1605
23.4k
      index &= mask;                                      \
1606
23.4k
      if (index > 0xf)                                    \
1607
23.4k
        *valid = 0;                                       \
1608
23.4k
      if (insn->rexPrefix &&                              \
1609
23.4k
         index >= 4 && index <= 7) {                      \
1610
638
        return prefix##_SPL + (index - 4);                \
1611
22.8k
      } else {                                            \
1612
22.8k
        return prefix##_AL + index;                       \
1613
22.8k
      }                                                   \
1614
23.4k
    case TYPE_R16:                                        \
1615
1.26k
      index &= mask;                                      \
1616
1.26k
      if (index > 0xf)                                    \
1617
1.26k
        *valid = 0;                                       \
1618
1.26k
      return prefix##_AX + index;                         \
1619
23.4k
    case TYPE_R32:                                        \
1620
1.29k
      index &= mask;                                      \
1621
1.29k
      if (index > 0xf)                                    \
1622
1.29k
        *valid = 0;                                       \
1623
1.29k
      return prefix##_EAX + index;                        \
1624
23.4k
    case TYPE_R64:                                        \
1625
5.89k
      index &= mask;                                      \
1626
5.89k
      if (index > 0xf)                                    \
1627
5.89k
        *valid = 0;                                       \
1628
5.89k
      return prefix##_RAX + index;                        \
1629
23.4k
    case TYPE_ZMM:                                        \
1630
8.18k
      return prefix##_ZMM0 + index;                       \
1631
23.4k
    case TYPE_YMM:                                        \
1632
7.46k
      return prefix##_YMM0 + index;                       \
1633
23.4k
    case TYPE_XMM:                                        \
1634
13.8k
      return prefix##_XMM0 + index;                       \
1635
23.4k
    case TYPE_VK:                                         \
1636
2.62k
      index &= 0xf;                                       \
1637
2.62k
      if (index > 7)                                      \
1638
2.62k
        *valid = 0;                                       \
1639
2.62k
      return prefix##_K0 + index;                         \
1640
23.4k
    case TYPE_MM64:                                       \
1641
2.63k
      return prefix##_MM0 + (index & 0x7);                \
1642
23.4k
    case TYPE_SEGMENTREG:                                 \
1643
0
      if ((index & 7) > 5)                                \
1644
0
        *valid = 0;                                       \
1645
0
      return prefix##_ES + (index & 7);                   \
1646
23.4k
    case TYPE_DEBUGREG:                                   \
1647
0
      return prefix##_DR0 + index;                        \
1648
23.4k
    case TYPE_CONTROLREG:                                 \
1649
0
      return prefix##_CR0 + index;                        \
1650
23.4k
    case TYPE_BNDR:                                       \
1651
547
      if (index > 3)                                      \
1652
547
        *valid = 0;                                       \
1653
547
      return prefix##_BND0 + index;                       \
1654
23.4k
    case TYPE_MVSIBX:                                     \
1655
0
      return prefix##_XMM0 + index;                       \
1656
23.4k
    case TYPE_MVSIBY:                                     \
1657
0
      return prefix##_YMM0 + index;                       \
1658
23.4k
    case TYPE_MVSIBZ:                                     \
1659
0
      return prefix##_ZMM0 + index;                       \
1660
88.4k
    }                                                     \
1661
88.4k
  }
1662
1663
/*
1664
 * fixup*Value - Consults an operand type to determine the meaning of the
1665
 *   reg or R/M field.  If the operand is an XMM operand, for example, an
1666
 *   operand would be XMM0 instead of AX, which readModRM() would otherwise
1667
 *   misinterpret it as.
1668
 *
1669
 * @param insn  - The instruction containing the operand.
1670
 * @param type  - The operand type.
1671
 * @param index - The existing value of the field as reported by readModRM().
1672
 * @param valid - The address of a uint8_t.  The target is set to 1 if the
1673
 *                field is valid for the register class; 0 if not.
1674
 * @return      - The proper value.
1675
 */
1676
GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase, MODRM_REG, 0x1f)
1677
GENERIC_FIXUP_FUNC(fixupRMValue, insn->eaRegBase, EA_REG, 0xf)
1678
1679
/*
1680
 * fixupReg - Consults an operand specifier to determine which of the
1681
 *   fixup*Value functions to use in correcting readModRM()'ss interpretation.
1682
 *
1683
 * @param insn  - See fixup*Value().
1684
 * @param op    - The operand specifier.
1685
 * @return      - 0 if fixup was successful; -1 if the register returned was
1686
 *                invalid for its class.
1687
 */
1688
static int fixupReg(struct InternalInstruction *insn,
1689
                    const struct OperandSpecifier *op)
1690
662k
{
1691
662k
  uint8_t valid;
1692
1693
662k
  switch ((OperandEncoding)op->encoding) {
1694
0
    default:
1695
      // debug("Expected a REG or R/M encoding in fixupReg");
1696
0
      return -1;
1697
56.7k
    case ENCODING_VVVV:
1698
56.7k
      insn->vvvv = (Reg)fixupRegValue(insn,
1699
56.7k
          (OperandType)op->type,
1700
56.7k
          insn->vvvv,
1701
56.7k
          &valid);
1702
56.7k
      if (!valid)
1703
1
        return -1;
1704
56.7k
      break;
1705
262k
    case ENCODING_REG:
1706
262k
      insn->reg = (Reg)fixupRegValue(insn,
1707
262k
          (OperandType)op->type,
1708
262k
          insn->reg - insn->regBase,
1709
262k
          &valid);
1710
262k
      if (!valid)
1711
11
        return -1;
1712
262k
      break;
1713
2.20M
    CASE_ENCODING_RM:
1714
2.20M
      if (insn->eaBase >= insn->eaRegBase) {
1715
88.4k
        insn->eaBase = (EABase)fixupRMValue(insn,
1716
88.4k
            (OperandType)op->type,
1717
88.4k
            insn->eaBase - insn->eaRegBase,
1718
88.4k
            &valid);
1719
88.4k
        if (!valid)
1720
2
          return -1;
1721
88.4k
      }
1722
343k
      break;
1723
662k
  }
1724
1725
662k
  return 0;
1726
662k
}
1727
1728
/*
1729
 * readOpcodeRegister - Reads an operand from the opcode field of an
1730
 *   instruction and interprets it appropriately given the operand width.
1731
 *   Handles AddRegFrm instructions.
1732
 *
1733
 * @param insn  - the instruction whose opcode field is to be read.
1734
 * @param size  - The width (in bytes) of the register being specified.
1735
 *                1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1736
 *                RAX.
1737
 * @return      - 0 on success; nonzero otherwise.
1738
 */
1739
static int readOpcodeRegister(struct InternalInstruction* insn, uint8_t size)
1740
57.0k
{
1741
57.0k
  if (size == 0)
1742
43.4k
    size = insn->registerSize;
1743
1744
57.0k
  switch (size) {
1745
4.86k
    case 1:
1746
4.86k
      insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
1747
4.86k
            | (insn->opcode & 7)));
1748
4.86k
      if (insn->rexPrefix &&
1749
719
          insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1750
445
          insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1751
214
        insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1752
214
            + (insn->opcodeRegister - MODRM_REG_AL - 4));
1753
214
      }
1754
1755
4.86k
      break;
1756
21.8k
    case 2:
1757
21.8k
      insn->opcodeRegister = (Reg)(MODRM_REG_AX
1758
21.8k
          + ((bFromREX(insn->rexPrefix) << 3)
1759
21.8k
            | (insn->opcode & 7)));
1760
21.8k
      break;
1761
21.3k
    case 4:
1762
21.3k
      insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1763
21.3k
          + ((bFromREX(insn->rexPrefix) << 3)
1764
21.3k
            | (insn->opcode & 7)));
1765
21.3k
      break;
1766
8.89k
    case 8:
1767
8.89k
      insn->opcodeRegister = (Reg)(MODRM_REG_RAX
1768
8.89k
          + ((bFromREX(insn->rexPrefix) << 3)
1769
8.89k
            | (insn->opcode & 7)));
1770
8.89k
      break;
1771
57.0k
  }
1772
1773
57.0k
  return 0;
1774
57.0k
}
1775
1776
/*
1777
 * readImmediate - Consumes an immediate operand from an instruction, given the
1778
 *   desired operand size.
1779
 *
1780
 * @param insn  - The instruction whose operand is to be read.
1781
 * @param size  - The width (in bytes) of the operand.
1782
 * @return      - 0 if the immediate was successfully consumed; nonzero
1783
 *                otherwise.
1784
 */
1785
static int readImmediate(struct InternalInstruction* insn, uint8_t size)
1786
177k
{
1787
177k
  uint8_t imm8;
1788
177k
  uint16_t imm16;
1789
177k
  uint32_t imm32;
1790
177k
  uint64_t imm64;
1791
1792
177k
  if (insn->numImmediatesConsumed == 2) {
1793
    // debug("Already consumed two immediates");
1794
0
    return -1;
1795
0
  }
1796
1797
177k
  if (size == 0)
1798
0
    size = insn->immediateSize;
1799
177k
  else
1800
177k
    insn->immediateSize = size;
1801
1802
177k
  insn->immediateOffset = insn->readerCursor - insn->startLocation;
1803
1804
177k
  switch (size) {
1805
137k
    case 1:
1806
137k
      if (consumeByte(insn, &imm8))
1807
509
        return -1;
1808
1809
136k
      insn->immediates[insn->numImmediatesConsumed] = imm8;
1810
136k
      break;
1811
22.9k
    case 2:
1812
22.9k
      if (consumeUInt16(insn, &imm16))
1813
214
        return -1;
1814
1815
22.7k
      insn->immediates[insn->numImmediatesConsumed] = imm16;
1816
22.7k
      break;
1817
14.8k
    case 4:
1818
14.8k
      if (consumeUInt32(insn, &imm32))
1819
313
        return -1;
1820
1821
14.5k
      insn->immediates[insn->numImmediatesConsumed] = imm32;
1822
14.5k
      break;
1823
2.34k
    case 8:
1824
2.34k
      if (consumeUInt64(insn, &imm64))
1825
64
        return -1;
1826
2.27k
      insn->immediates[insn->numImmediatesConsumed] = imm64;
1827
2.27k
      break;
1828
177k
  }
1829
1830
176k
  insn->numImmediatesConsumed++;
1831
1832
176k
  return 0;
1833
177k
}
1834
1835
/*
1836
 * readVVVV - Consumes vvvv from an instruction if it has a VEX prefix.
1837
 *
1838
 * @param insn  - The instruction whose operand is to be read.
1839
 * @return      - 0 if the vvvv was successfully consumed; nonzero
1840
 *                otherwise.
1841
 */
1842
static int readVVVV(struct InternalInstruction* insn)
1843
609k
{
1844
609k
  int vvvv;
1845
1846
609k
  if (insn->vectorExtensionType == TYPE_EVEX)
1847
57.2k
    vvvv = (v2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 4 |
1848
57.2k
        vvvvFromEVEX3of4(insn->vectorExtensionPrefix[2]));
1849
552k
  else if (insn->vectorExtensionType == TYPE_VEX_3B)
1850
4.75k
    vvvv = vvvvFromVEX3of3(insn->vectorExtensionPrefix[2]);
1851
547k
  else if (insn->vectorExtensionType == TYPE_VEX_2B)
1852
9.96k
    vvvv = vvvvFromVEX2of2(insn->vectorExtensionPrefix[1]);
1853
537k
  else if (insn->vectorExtensionType == TYPE_XOP)
1854
6.47k
    vvvv = vvvvFromXOP3of3(insn->vectorExtensionPrefix[2]);
1855
531k
  else
1856
531k
    return -1;
1857
1858
78.4k
  if (insn->mode != MODE_64BIT)
1859
50.4k
    vvvv &= 0xf; // Can only clear bit 4. Bit 3 must be cleared later.
1860
1861
78.4k
  insn->vvvv = (Reg)vvvv;
1862
1863
78.4k
  return 0;
1864
609k
}
1865
1866
/*
1867
 * readMaskRegister - Reads an mask register from the opcode field of an
1868
 *   instruction.
1869
 *
1870
 * @param insn    - The instruction whose opcode field is to be read.
1871
 * @return        - 0 on success; nonzero otherwise.
1872
 */
1873
static int readMaskRegister(struct InternalInstruction* insn)
1874
39.1k
{
1875
39.1k
  if (insn->vectorExtensionType != TYPE_EVEX)
1876
0
    return -1;
1877
1878
39.1k
  insn->writemask = (Reg)(aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]));
1879
1880
39.1k
  return 0;
1881
39.1k
}
1882
1883
/*
1884
 * readOperands - Consults the specifier for an instruction and consumes all
1885
 *   operands for that instruction, interpreting them as it goes.
1886
 *
1887
 * @param insn  - The instruction whose operands are to be read and interpreted.
1888
 * @return      - 0 if all operands could be read; nonzero otherwise.
1889
 */
1890
static int readOperands(struct InternalInstruction* insn)
1891
609k
{
1892
609k
  int hasVVVV, needVVVV;
1893
609k
  int sawRegImm = 0;
1894
609k
  int i;
1895
1896
  /* If non-zero vvvv specified, need to make sure one of the operands
1897
     uses it. */
1898
609k
  hasVVVV = !readVVVV(insn);
1899
609k
  needVVVV = hasVVVV && (insn->vvvv != 0);
1900
1901
4.26M
  for (i = 0; i < X86_MAX_OPERANDS; ++i) {
1902
3.65M
    const OperandSpecifier *op = &x86OperandSets[insn->spec->operands][i];
1903
3.65M
    switch (op->encoding) {
1904
2.50M
      case ENCODING_NONE:
1905
2.52M
      case ENCODING_SI:
1906
2.56M
      case ENCODING_DI:
1907
2.56M
        break;
1908
1909
26.9k
      CASE_ENCODING_VSIB:
1910
        // VSIB can use the V2 bit so check only the other bits.
1911
26.9k
        if (needVVVV)
1912
2.99k
          needVVVV = hasVVVV & ((insn->vvvv & 0xf) != 0);
1913
1914
26.9k
        if (readModRM(insn))
1915
0
          return -1;
1916
1917
        // Reject if SIB wasn't used.
1918
4.98k
        if (insn->eaBase != EA_BASE_sib && insn->eaBase != EA_BASE_sib64)
1919
14
          return -1;
1920
1921
        // If sibIndex was set to SIB_INDEX_NONE, index offset is 4.
1922
4.96k
        if (insn->sibIndex == SIB_INDEX_NONE)
1923
267
          insn->sibIndex = (SIBIndex)(insn->sibIndexBase + 4);
1924
1925
        // If EVEX.v2 is set this is one of the 16-31 registers.
1926
4.96k
        if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT &&
1927
2.61k
            v2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
1928
2.13k
          insn->sibIndex = (SIBIndex)(insn->sibIndex + 16);
1929
1930
        // Adjust the index register to the correct size.
1931
4.96k
        switch (op->type) {
1932
0
          default:
1933
            // debug("Unhandled VSIB index type");
1934
0
            return -1;
1935
1.80k
          case TYPE_MVSIBX:
1936
1.80k
            insn->sibIndex = (SIBIndex)(SIB_INDEX_XMM0 +
1937
1.80k
                (insn->sibIndex - insn->sibIndexBase));
1938
1.80k
            break;
1939
1.64k
          case TYPE_MVSIBY:
1940
1.64k
            insn->sibIndex = (SIBIndex)(SIB_INDEX_YMM0 +
1941
1.64k
                (insn->sibIndex - insn->sibIndexBase));
1942
1.64k
            break;
1943
1.52k
          case TYPE_MVSIBZ:
1944
1.52k
            insn->sibIndex = (SIBIndex)(SIB_INDEX_ZMM0 +
1945
1.52k
                (insn->sibIndex - insn->sibIndexBase));
1946
1.52k
            break;
1947
4.96k
        }
1948
1949
        // Apply the AVX512 compressed displacement scaling factor.
1950
4.96k
        if (op->encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1951
404
          insn->displacement *= 1 << (op->encoding - ENCODING_VSIB);
1952
4.96k
        break;
1953
1954
262k
      case ENCODING_REG:
1955
4.04M
      CASE_ENCODING_RM:
1956
4.04M
        if (readModRM(insn))
1957
0
          return -1;
1958
1959
605k
        if (fixupReg(insn, op))
1960
13
          return -1;
1961
1962
        // Apply the AVX512 compressed displacement scaling factor.
1963
605k
        if (op->encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1964
52.8k
          insn->displacement *= 1 << (op->encoding - ENCODING_RM);
1965
605k
        break;
1966
1967
137k
      case ENCODING_IB:
1968
137k
        if (sawRegImm) {
1969
          /* Saw a register immediate so don't read again and instead split the
1970
             previous immediate.  FIXME: This is a hack. */
1971
753
          insn->immediates[insn->numImmediatesConsumed] =
1972
753
            insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1973
753
          ++insn->numImmediatesConsumed;
1974
753
          break;
1975
753
        }
1976
137k
        if (readImmediate(insn, 1))
1977
509
          return -1;
1978
136k
        if (op->type == TYPE_XMM || op->type == TYPE_YMM)
1979
1.08k
          sawRegImm = 1;
1980
136k
        break;
1981
1982
7.43k
      case ENCODING_IW:
1983
7.43k
        if (readImmediate(insn, 2))
1984
54
          return -1;
1985
7.38k
        break;
1986
1987
7.38k
      case ENCODING_ID:
1988
3.44k
        if (readImmediate(insn, 4))
1989
57
          return -1;
1990
3.38k
        break;
1991
1992
3.38k
      case ENCODING_IO:
1993
530
        if (readImmediate(insn, 8))
1994
12
          return -1;
1995
518
        break;
1996
1997
22.5k
      case ENCODING_Iv:
1998
22.5k
        if (readImmediate(insn, insn->immediateSize))
1999
367
          return -1;
2000
22.2k
        break;
2001
2002
22.2k
      case ENCODING_Ia:
2003
6.19k
        if (readImmediate(insn, insn->addressSize))
2004
101
          return -1;
2005
        /* Direct memory-offset (moffset) immediate will get mapped
2006
           to memory operand later. We want the encoding info to
2007
           reflect that as well. */
2008
6.09k
        insn->displacementOffset = insn->immediateOffset;
2009
6.09k
        insn->consumedDisplacement = true;
2010
6.09k
        insn->displacementSize = insn->immediateSize;
2011
6.09k
        insn->displacement = insn->immediates[insn->numImmediatesConsumed - 1];
2012
6.09k
        insn->immediateOffset = 0;
2013
6.09k
        insn->immediateSize = 0;
2014
6.09k
        break;
2015
2016
2.65k
      case ENCODING_IRC:
2017
2.65k
        insn->RC = (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 1) |
2018
2.65k
          lFromEVEX4of4(insn->vectorExtensionPrefix[3]);
2019
2.65k
        break;
2020
2021
4.86k
      case ENCODING_RB:
2022
4.86k
        if (readOpcodeRegister(insn, 1))
2023
0
          return -1;
2024
4.86k
        break;
2025
2026
4.86k
      case ENCODING_RW:
2027
0
        if (readOpcodeRegister(insn, 2))
2028
0
          return -1;
2029
0
        break;
2030
2031
0
      case ENCODING_RD:
2032
0
        if (readOpcodeRegister(insn, 4))
2033
0
          return -1;
2034
0
        break;
2035
2036
8.70k
      case ENCODING_RO:
2037
8.70k
        if (readOpcodeRegister(insn, 8))
2038
0
          return -1;
2039
8.70k
        break;
2040
2041
43.4k
      case ENCODING_Rv:
2042
43.4k
        if (readOpcodeRegister(insn, 0))
2043
0
          return -1;
2044
43.4k
        break;
2045
2046
43.4k
      case ENCODING_FP:
2047
2.38k
        break;
2048
2049
56.7k
      case ENCODING_VVVV:
2050
56.7k
        if (!hasVVVV)
2051
0
          return -1;
2052
2053
56.7k
        needVVVV = 0; /* Mark that we have found a VVVV operand. */
2054
2055
56.7k
        if (insn->mode != MODE_64BIT)
2056
35.3k
          insn->vvvv = (Reg)(insn->vvvv & 0x7);
2057
2058
56.7k
        if (fixupReg(insn, op))
2059
1
          return -1;
2060
56.7k
        break;
2061
2062
56.7k
      case ENCODING_WRITEMASK:
2063
39.1k
        if (readMaskRegister(insn))
2064
0
          return -1;
2065
39.1k
        break;
2066
2067
143k
      case ENCODING_DUP:
2068
143k
        break;
2069
2070
0
      default:
2071
        // dbgprintf(insn, "Encountered an operand with an unknown encoding.");
2072
0
        return -1;
2073
3.65M
    }
2074
3.65M
  }
2075
2076
  /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
2077
608k
  if (needVVVV)
2078
11
    return -1;
2079
2080
608k
  return 0;
2081
608k
}
2082
2083
// return True if instruction is illegal to use with prefixes
2084
// This also check & fix the isPrefixNN when a prefix is irrelevant.
2085
static bool checkPrefix(struct InternalInstruction *insn)
2086
609k
{
2087
  // LOCK prefix
2088
609k
  if (insn->hasLockPrefix) {
2089
33.9k
    switch(insn->instructionID) {
2090
185
      default:
2091
        // invalid LOCK
2092
185
        return true;
2093
2094
      // nop dword [rax]
2095
66
      case X86_NOOPL:
2096
2097
      // DEC
2098
262
      case X86_DEC16m:
2099
466
      case X86_DEC32m:
2100
664
      case X86_DEC64m:
2101
741
      case X86_DEC8m:
2102
2103
      // ADC
2104
826
      case X86_ADC16mi:
2105
1.02k
      case X86_ADC16mi8:
2106
1.23k
      case X86_ADC16mr:
2107
1.44k
      case X86_ADC32mi:
2108
1.67k
      case X86_ADC32mi8:
2109
1.90k
      case X86_ADC32mr:
2110
2.10k
      case X86_ADC64mi32:
2111
2.72k
      case X86_ADC64mi8:
2112
2.92k
      case X86_ADC64mr:
2113
3.26k
      case X86_ADC8mi:
2114
3.50k
      case X86_ADC8mi8:
2115
3.62k
      case X86_ADC8mr:
2116
3.84k
      case X86_ADC8rm:
2117
4.06k
      case X86_ADC16rm:
2118
4.56k
      case X86_ADC32rm:
2119
4.63k
      case X86_ADC64rm:
2120
2121
      // ADD
2122
4.86k
      case X86_ADD16mi:
2123
5.08k
      case X86_ADD16mi8:
2124
5.34k
      case X86_ADD16mr:
2125
5.57k
      case X86_ADD32mi:
2126
5.81k
      case X86_ADD32mi8:
2127
6.12k
      case X86_ADD32mr:
2128
6.36k
      case X86_ADD64mi32:
2129
6.60k
      case X86_ADD64mi8:
2130
6.73k
      case X86_ADD64mr:
2131
6.96k
      case X86_ADD8mi:
2132
7.06k
      case X86_ADD8mi8:
2133
7.79k
      case X86_ADD8mr:
2134
8.00k
      case X86_ADD8rm:
2135
8.22k
      case X86_ADD16rm:
2136
8.42k
      case X86_ADD32rm:
2137
8.62k
      case X86_ADD64rm:
2138
2139
      // AND
2140
8.84k
      case X86_AND16mi:
2141
9.05k
      case X86_AND16mi8:
2142
9.28k
      case X86_AND16mr:
2143
9.49k
      case X86_AND32mi:
2144
9.79k
      case X86_AND32mi8:
2145
10.0k
      case X86_AND32mr:
2146
10.1k
      case X86_AND64mi32:
2147
10.2k
      case X86_AND64mi8:
2148
10.4k
      case X86_AND64mr:
2149
10.6k
      case X86_AND8mi:
2150
10.8k
      case X86_AND8mi8:
2151
11.1k
      case X86_AND8mr:
2152
11.3k
      case X86_AND8rm:
2153
11.5k
      case X86_AND16rm:
2154
11.7k
      case X86_AND32rm:
2155
11.9k
      case X86_AND64rm:
2156
2157
      // BTC
2158
12.1k
      case X86_BTC16mi8:
2159
12.3k
      case X86_BTC16mr:
2160
12.5k
      case X86_BTC32mi8:
2161
12.6k
      case X86_BTC32mr:
2162
12.8k
      case X86_BTC64mi8:
2163
12.9k
      case X86_BTC64mr:
2164
2165
      // BTR
2166
13.1k
      case X86_BTR16mi8:
2167
13.3k
      case X86_BTR16mr:
2168
13.4k
      case X86_BTR32mi8:
2169
13.6k
      case X86_BTR32mr:
2170
13.6k
      case X86_BTR64mi8:
2171
13.8k
      case X86_BTR64mr:
2172
2173
      // BTS
2174
14.1k
      case X86_BTS16mi8:
2175
14.3k
      case X86_BTS16mr:
2176
14.5k
      case X86_BTS32mi8:
2177
14.7k
      case X86_BTS32mr:
2178
15.0k
      case X86_BTS64mi8:
2179
15.1k
      case X86_BTS64mr:
2180
2181
      // CMPXCHG
2182
15.7k
      case X86_CMPXCHG16B:
2183
16.0k
      case X86_CMPXCHG16rm:
2184
16.2k
      case X86_CMPXCHG32rm:
2185
16.3k
      case X86_CMPXCHG64rm:
2186
16.4k
      case X86_CMPXCHG8rm:
2187
16.5k
      case X86_CMPXCHG8B:
2188
2189
      // INC
2190
16.7k
      case X86_INC16m:
2191
17.0k
      case X86_INC32m:
2192
17.1k
      case X86_INC64m:
2193
17.3k
      case X86_INC8m:
2194
2195
      // NEG
2196
17.5k
      case X86_NEG16m:
2197
17.7k
      case X86_NEG32m:
2198
17.8k
      case X86_NEG64m:
2199
18.0k
      case X86_NEG8m:
2200
2201
      // NOT
2202
18.2k
      case X86_NOT16m:
2203
18.4k
      case X86_NOT32m:
2204
18.7k
      case X86_NOT64m:
2205
18.8k
      case X86_NOT8m:
2206
2207
      // OR
2208
19.0k
      case X86_OR16mi:
2209
19.2k
      case X86_OR16mi8:
2210
19.4k
      case X86_OR16mr:
2211
19.6k
      case X86_OR32mi:
2212
19.8k
      case X86_OR32mi8:
2213
20.0k
      case X86_OR32mr:
2214
20.4k
      case X86_OR64mi32:
2215
20.5k
      case X86_OR64mi8:
2216
20.7k
      case X86_OR64mr:
2217
21.0k
      case X86_OR8mi8:
2218
21.2k
      case X86_OR8mi:
2219
21.4k
      case X86_OR8mr:
2220
21.8k
      case X86_OR8rm:
2221
22.0k
      case X86_OR16rm:
2222
22.2k
      case X86_OR32rm:
2223
22.4k
      case X86_OR64rm:
2224
2225
      // SBB
2226
22.6k
      case X86_SBB16mi:
2227
22.8k
      case X86_SBB16mi8:
2228
23.0k
      case X86_SBB16mr:
2229
23.2k
      case X86_SBB32mi:
2230
23.4k
      case X86_SBB32mi8:
2231
23.7k
      case X86_SBB32mr:
2232
23.9k
      case X86_SBB64mi32:
2233
24.0k
      case X86_SBB64mi8:
2234
24.2k
      case X86_SBB64mr:
2235
24.5k
      case X86_SBB8mi:
2236
24.7k
      case X86_SBB8mi8:
2237
24.9k
      case X86_SBB8mr:
2238
2239
      // SUB
2240
25.0k
      case X86_SUB16mi:
2241
25.2k
      case X86_SUB16mi8:
2242
25.4k
      case X86_SUB16mr:
2243
25.5k
      case X86_SUB32mi:
2244
25.7k
      case X86_SUB32mi8:
2245
26.0k
      case X86_SUB32mr:
2246
26.2k
      case X86_SUB64mi32:
2247
26.4k
      case X86_SUB64mi8:
2248
26.7k
      case X86_SUB64mr:
2249
26.9k
      case X86_SUB8mi8:
2250
27.1k
      case X86_SUB8mi:
2251
27.3k
      case X86_SUB8mr:
2252
27.7k
      case X86_SUB8rm:
2253
27.9k
      case X86_SUB16rm:
2254
28.1k
      case X86_SUB32rm:
2255
28.1k
      case X86_SUB64rm:
2256
2257
      // XADD
2258
28.3k
      case X86_XADD16rm:
2259
28.5k
      case X86_XADD32rm:
2260
28.7k
      case X86_XADD64rm:
2261
28.8k
      case X86_XADD8rm:
2262
2263
      // XCHG
2264
29.0k
      case X86_XCHG16rm:
2265
29.3k
      case X86_XCHG32rm:
2266
29.5k
      case X86_XCHG64rm:
2267
29.9k
      case X86_XCHG8rm:
2268
2269
      // XOR
2270
30.1k
      case X86_XOR16mi:
2271
30.3k
      case X86_XOR16mi8:
2272
30.5k
      case X86_XOR16mr:
2273
30.6k
      case X86_XOR32mi:
2274
30.8k
      case X86_XOR32mi8:
2275
31.1k
      case X86_XOR32mr:
2276
31.2k
      case X86_XOR64mi32:
2277
31.4k
      case X86_XOR64mi8:
2278
31.9k
      case X86_XOR64mr:
2279
32.1k
      case X86_XOR8mi8:
2280
32.4k
      case X86_XOR8mi:
2281
32.7k
      case X86_XOR8mr:
2282
33.0k
      case X86_XOR8rm:
2283
33.2k
      case X86_XOR16rm:
2284
33.4k
      case X86_XOR32rm:
2285
33.7k
      case X86_XOR64rm:
2286
2287
        // this instruction can be used with LOCK prefix
2288
33.7k
        return false;
2289
33.9k
    }
2290
33.9k
  }
2291
2292
#if 0
2293
  // REPNE prefix
2294
  if (insn->repeatPrefix) {
2295
    // 0xf2 can be a part of instruction encoding, but not really a prefix.
2296
    // In such a case, clear it.
2297
    if (insn->twoByteEscape == 0x0f) {
2298
      insn->prefix0 = 0;
2299
    }
2300
  }
2301
#endif
2302
2303
  // no invalid prefixes
2304
575k
  return false;
2305
609k
}
2306
2307
/*
2308
 * decodeInstruction - Reads and interprets a full instruction provided by the
2309
 *   user.
2310
 *
2311
 * @param insn      - A pointer to the instruction to be populated.  Must be
2312
 *                    pre-allocated.
2313
 * @param reader    - The function to be used to read the instruction's bytes.
2314
 * @param readerArg - A generic argument to be passed to the reader to store
2315
 *                    any internal state.
2316
 * @param startLoc  - The address (in the reader's address space) of the first
2317
 *                    byte in the instruction.
2318
 * @param mode      - The mode (real mode, IA-32e, or IA-32e in 64-bit mode) to
2319
 *                    decode the instruction in.
2320
 * @return          - 0 if instruction is valid; nonzero if not.
2321
 */
2322
int decodeInstruction(struct InternalInstruction *insn,
2323
    byteReader_t reader,
2324
    const void *readerArg,
2325
    uint64_t startLoc,
2326
    DisassemblerMode mode)
2327
613k
{
2328
613k
  insn->reader = reader;
2329
613k
  insn->readerArg = readerArg;
2330
613k
  insn->startLocation = startLoc;
2331
613k
  insn->readerCursor = startLoc;
2332
613k
  insn->mode = mode;
2333
613k
  insn->numImmediatesConsumed = 0;
2334
2335
613k
  if (readPrefixes(insn) ||
2336
612k
      readOpcode(insn) ||
2337
612k
      getID(insn) ||
2338
610k
      insn->instructionID == 0 ||
2339
609k
      checkPrefix(insn) ||
2340
609k
      readOperands(insn))
2341
4.79k
    return -1;
2342
2343
608k
  insn->length = (size_t)(insn->readerCursor - insn->startLocation);
2344
2345
  // instruction length must be <= 15 to be valid
2346
608k
  if (insn->length > 15)
2347
22
    return -1;
2348
2349
608k
  if (insn->operandSize == 0)
2350
608k
    insn->operandSize = insn->registerSize;
2351
2352
608k
  insn->operands = &x86OperandSets[insn->spec->operands][0];
2353
2354
608k
  return 0;
2355
608k
}
2356
2357
#endif
2358