Coverage Report

Created: 2025-07-01 07:03

/src/capstonenext/arch/X86/X86DisassemblerDecoder.c
Line
Count
Source (jump to first uncovered line)
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
1.66M
{
79
1.66M
  return CONTEXTS_SYM[attrMask];
80
1.66M
}
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
1.66M
{
97
1.66M
  const struct OpcodeDecision *decision = NULL;
98
1.66M
  const uint8_t *indextable = NULL;
99
1.66M
  unsigned int index;
100
101
1.66M
  switch (type) {
102
0
    default: break;
103
1.46M
    case ONEBYTE:
104
1.46M
      decision = ONEBYTE_SYM;
105
1.46M
      indextable = index_x86DisassemblerOneByteOpcodes;
106
1.46M
      break;
107
107k
    case TWOBYTE:
108
107k
      decision = TWOBYTE_SYM;
109
107k
      indextable = index_x86DisassemblerTwoByteOpcodes;
110
107k
      break;
111
31.2k
    case THREEBYTE_38:
112
31.2k
      decision = THREEBYTE38_SYM;
113
31.2k
      indextable = index_x86DisassemblerThreeByte38Opcodes;
114
31.2k
      break;
115
42.3k
    case THREEBYTE_3A:
116
42.3k
      decision = THREEBYTE3A_SYM;
117
42.3k
      indextable = index_x86DisassemblerThreeByte3AOpcodes;
118
42.3k
      break;
119
0
#ifndef CAPSTONE_X86_REDUCE
120
13.8k
    case XOP8_MAP:
121
13.8k
      decision = XOP8_MAP_SYM;
122
13.8k
      indextable = index_x86DisassemblerXOP8Opcodes;
123
13.8k
      break;
124
1.31k
    case XOP9_MAP:
125
1.31k
      decision = XOP9_MAP_SYM;
126
1.31k
      indextable = index_x86DisassemblerXOP9Opcodes;
127
1.31k
      break;
128
211
    case XOPA_MAP:
129
211
      decision = XOPA_MAP_SYM;
130
211
      indextable = index_x86DisassemblerXOPAOpcodes;
131
211
      break;
132
459
    case THREEDNOW_MAP:
133
      // 3DNow instructions always have ModRM byte
134
459
      return true;
135
1.66M
#endif
136
1.66M
  }
137
138
  // return decision->opcodeDecisions[insnContext].modRMDecisions[opcode].modrm_type != MODRM_ONEENTRY;
139
1.65M
  index = indextable[insnContext];
140
1.65M
  if (index)
141
1.65M
    return decision[index - 1].modRMDecisions[opcode].modrm_type != MODRM_ONEENTRY;
142
5.33k
  else
143
5.33k
    return false;
144
1.65M
}
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
1.65M
{
161
1.65M
  const struct ModRMDecision *dec = NULL;
162
1.65M
  unsigned int index;
163
1.65M
  static const struct OpcodeDecision emptyDecision = { 0 };
164
165
1.65M
  switch (type) {
166
0
    default: break; // never reach
167
1.46M
    case ONEBYTE:
168
      // dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
169
1.46M
      index = index_x86DisassemblerOneByteOpcodes[insnContext];
170
1.46M
      if (index)
171
1.46M
        dec = &ONEBYTE_SYM[index - 1].modRMDecisions[opcode];
172
176
      else
173
176
        dec = &emptyDecision.modRMDecisions[opcode];
174
1.46M
      break;
175
107k
    case TWOBYTE:
176
      //dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
177
107k
      index = index_x86DisassemblerTwoByteOpcodes[insnContext];
178
107k
      if (index)
179
105k
        dec = &TWOBYTE_SYM[index - 1].modRMDecisions[opcode];
180
1.73k
      else
181
1.73k
        dec = &emptyDecision.modRMDecisions[opcode];
182
107k
      break;
183
31.2k
    case THREEBYTE_38:
184
      // dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
185
31.2k
      index = index_x86DisassemblerThreeByte38Opcodes[insnContext];
186
31.2k
      if (index)
187
30.8k
        dec = &THREEBYTE38_SYM[index - 1].modRMDecisions[opcode];
188
374
      else
189
374
        dec = &emptyDecision.modRMDecisions[opcode];
190
31.2k
      break;
191
42.3k
    case THREEBYTE_3A:
192
      //dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
193
42.3k
      index = index_x86DisassemblerThreeByte3AOpcodes[insnContext];
194
42.3k
      if (index)
195
42.1k
        dec = &THREEBYTE3A_SYM[index - 1].modRMDecisions[opcode];
196
201
      else
197
201
        dec = &emptyDecision.modRMDecisions[opcode];
198
42.3k
      break;
199
0
#ifndef CAPSTONE_X86_REDUCE
200
13.8k
    case XOP8_MAP:
201
      // dec = &XOP8_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
202
13.8k
      index = index_x86DisassemblerXOP8Opcodes[insnContext];
203
13.8k
      if (index)
204
11.3k
        dec = &XOP8_MAP_SYM[index - 1].modRMDecisions[opcode];
205
2.48k
      else
206
2.48k
        dec = &emptyDecision.modRMDecisions[opcode];
207
13.8k
      break;
208
1.31k
    case XOP9_MAP:
209
      // dec = &XOP9_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
210
1.31k
      index = index_x86DisassemblerXOP9Opcodes[insnContext];
211
1.31k
      if (index)
212
1.00k
        dec = &XOP9_MAP_SYM[index - 1].modRMDecisions[opcode];
213
306
      else
214
306
        dec = &emptyDecision.modRMDecisions[opcode];
215
1.31k
      break;
216
211
    case XOPA_MAP:
217
      // dec = &XOPA_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
218
211
      index = index_x86DisassemblerXOPAOpcodes[insnContext];
219
211
      if (index)
220
151
        dec = &XOPA_MAP_SYM[index - 1].modRMDecisions[opcode];
221
60
      else
222
60
        dec = &emptyDecision.modRMDecisions[opcode];
223
211
      break;
224
459
    case THREEDNOW_MAP:
225
      // dec = &THREEDNOW_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
226
459
      index = index_x86Disassembler3DNowOpcodes[insnContext];
227
459
      if (index)
228
447
        dec = &THREEDNOW_MAP_SYM[index - 1].modRMDecisions[opcode];
229
12
      else
230
12
        dec = &emptyDecision.modRMDecisions[opcode];
231
459
      break;
232
1.65M
#endif
233
1.65M
  }
234
235
1.65M
  switch (dec->modrm_type) {
236
0
    default:
237
      // debug("Corrupt table!  Unknown modrm_type");
238
0
      return 0;
239
817k
    case MODRM_ONEENTRY:
240
817k
      return modRMTable[dec->instructionIDs];
241
660k
    case MODRM_SPLITRM:
242
660k
      if (modFromModRM(modRM) == 0x3)
243
123k
        return modRMTable[dec->instructionIDs + 1];
244
536k
      return modRMTable[dec->instructionIDs];
245
150k
    case MODRM_SPLITREG:
246
150k
      if (modFromModRM(modRM) == 0x3)
247
56.1k
        return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3) + 8];
248
94.1k
      return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
249
29.7k
    case MODRM_SPLITMISC:
250
29.7k
      if (modFromModRM(modRM) == 0x3)
251
10.7k
        return modRMTable[dec->instructionIDs+(modRM & 0x3f) + 8];
252
18.9k
      return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
253
0
    case MODRM_FULL:
254
0
      return modRMTable[dec->instructionIDs+modRM];
255
1.65M
  }
256
1.65M
}
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
1.39M
{
268
1.39M
  return &INSTRUCTIONS_SYM[uid];
269
1.39M
}
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
4.27M
{
283
4.27M
  int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
284
285
4.27M
  if (!ret)
286
4.26M
    ++(insn->readerCursor);
287
288
4.27M
  return ret;
289
4.27M
}
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
396k
{
300
396k
  return insn->reader(insn->readerArg, byte, insn->readerCursor);
301
396k
}
302
303
static void unconsumeByte(struct InternalInstruction* insn)
304
1.57M
{
305
1.57M
  insn->readerCursor--;
306
1.57M
}
307
308
#define CONSUME_FUNC(name, type)                                  \
309
233k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
233k
    type combined = 0;                                            \
311
233k
    unsigned offset;                                              \
312
750k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
518k
      uint8_t byte;                                               \
314
518k
      int ret = insn->reader(insn->readerArg,                     \
315
518k
                             &byte,                               \
316
518k
                             insn->readerCursor + offset);        \
317
518k
      if (ret)                                                    \
318
518k
        return ret;                                               \
319
518k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
517k
    }                                                             \
321
233k
    *ptr = combined;                                              \
322
231k
    insn->readerCursor += sizeof(type);                           \
323
231k
    return 0;                                                     \
324
233k
  }
X86DisassemblerDecoder.c:consumeInt8
Line
Count
Source
309
95.0k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
95.0k
    type combined = 0;                                            \
311
95.0k
    unsigned offset;                                              \
312
189k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
95.0k
      uint8_t byte;                                               \
314
95.0k
      int ret = insn->reader(insn->readerArg,                     \
315
95.0k
                             &byte,                               \
316
95.0k
                             insn->readerCursor + offset);        \
317
95.0k
      if (ret)                                                    \
318
95.0k
        return ret;                                               \
319
95.0k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
94.7k
    }                                                             \
321
95.0k
    *ptr = combined;                                              \
322
94.7k
    insn->readerCursor += sizeof(type);                           \
323
94.7k
    return 0;                                                     \
324
95.0k
  }
X86DisassemblerDecoder.c:consumeInt16
Line
Count
Source
309
26.3k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
26.3k
    type combined = 0;                                            \
311
26.3k
    unsigned offset;                                              \
312
78.9k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
52.7k
      uint8_t byte;                                               \
314
52.7k
      int ret = insn->reader(insn->readerArg,                     \
315
52.7k
                             &byte,                               \
316
52.7k
                             insn->readerCursor + offset);        \
317
52.7k
      if (ret)                                                    \
318
52.7k
        return ret;                                               \
319
52.7k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
52.6k
    }                                                             \
321
26.3k
    *ptr = combined;                                              \
322
26.2k
    insn->readerCursor += sizeof(type);                           \
323
26.2k
    return 0;                                                     \
324
26.3k
  }
X86DisassemblerDecoder.c:consumeInt32
Line
Count
Source
309
30.7k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
30.7k
    type combined = 0;                                            \
311
30.7k
    unsigned offset;                                              \
312
152k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
122k
      uint8_t byte;                                               \
314
122k
      int ret = insn->reader(insn->readerArg,                     \
315
122k
                             &byte,                               \
316
122k
                             insn->readerCursor + offset);        \
317
122k
      if (ret)                                                    \
318
122k
        return ret;                                               \
319
122k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
122k
    }                                                             \
321
30.7k
    *ptr = combined;                                              \
322
30.4k
    insn->readerCursor += sizeof(type);                           \
323
30.4k
    return 0;                                                     \
324
30.7k
  }
X86DisassemblerDecoder.c:consumeUInt16
Line
Count
Source
309
45.8k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
45.8k
    type combined = 0;                                            \
311
45.8k
    unsigned offset;                                              \
312
137k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
91.6k
      uint8_t byte;                                               \
314
91.6k
      int ret = insn->reader(insn->readerArg,                     \
315
91.6k
                             &byte,                               \
316
91.6k
                             insn->readerCursor + offset);        \
317
91.6k
      if (ret)                                                    \
318
91.6k
        return ret;                                               \
319
91.6k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
91.3k
    }                                                             \
321
45.8k
    *ptr = combined;                                              \
322
45.5k
    insn->readerCursor += sizeof(type);                           \
323
45.5k
    return 0;                                                     \
324
45.8k
  }
X86DisassemblerDecoder.c:consumeUInt32
Line
Count
Source
309
30.8k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
30.8k
    type combined = 0;                                            \
311
30.8k
    unsigned offset;                                              \
312
152k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
122k
      uint8_t byte;                                               \
314
122k
      int ret = insn->reader(insn->readerArg,                     \
315
122k
                             &byte,                               \
316
122k
                             insn->readerCursor + offset);        \
317
122k
      if (ret)                                                    \
318
122k
        return ret;                                               \
319
122k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
121k
    }                                                             \
321
30.8k
    *ptr = combined;                                              \
322
30.2k
    insn->readerCursor += sizeof(type);                           \
323
30.2k
    return 0;                                                     \
324
30.8k
  }
X86DisassemblerDecoder.c:consumeUInt64
Line
Count
Source
309
4.39k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
4.39k
    type combined = 0;                                            \
311
4.39k
    unsigned offset;                                              \
312
39.0k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
34.7k
      uint8_t byte;                                               \
314
34.7k
      int ret = insn->reader(insn->readerArg,                     \
315
34.7k
                             &byte,                               \
316
34.7k
                             insn->readerCursor + offset);        \
317
34.7k
      if (ret)                                                    \
318
34.7k
        return ret;                                               \
319
34.7k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
34.6k
    }                                                             \
321
4.39k
    *ptr = combined;                                              \
322
4.29k
    insn->readerCursor += sizeof(type);                           \
323
4.29k
    return 0;                                                     \
324
4.39k
  }
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
1.27M
{
345
1.27M
  if (insn->mode == MODE_64BIT)
346
441k
    return prefix >= 0x40 && prefix <= 0x4f;
347
348
838k
  return false;
349
1.27M
}
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
201k
{
359
201k
  uint8_t nextByte;
360
361
201k
  switch (prefix) {
362
45.1k
    case 0xf0:  // LOCK
363
45.1k
      insn->hasLockPrefix = true;
364
45.1k
      insn->repeatPrefix = 0;
365
45.1k
      break;
366
367
48.0k
    case 0xf2:  // REPNE/REPNZ
368
79.8k
    case 0xf3:  // REP or REPE/REPZ
369
79.8k
      if (lookAtByte(insn, &nextByte))
370
56
        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
79.8k
      if (isREX(insn, nextByte) || nextByte == 0x0f || nextByte == 0x66)
378
        // The last of 0xf2 /0xf3 is mandatory prefix
379
17.8k
        insn->mandatoryPrefix = prefix;
380
381
79.8k
      insn->repeatPrefix = prefix;
382
79.8k
      insn->hasLockPrefix = false;
383
79.8k
      break;
384
385
25.7k
    case 0x66:
386
25.7k
      if (lookAtByte(insn, &nextByte))
387
63
        break;
388
      // 0x66 can't overwrite existing mandatory prefix and should be ignored
389
25.6k
      if (!insn->mandatoryPrefix && (nextByte == 0x0f || isREX(insn, nextByte)))
390
5.11k
        insn->mandatoryPrefix = prefix;
391
25.6k
      break;
392
201k
  }
393
201k
}
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
1.21M
{
406
1.21M
  bool isPrefix = true;
407
1.21M
  uint8_t byte = 0;
408
1.21M
  uint8_t nextByte;
409
410
2.63M
  while (isPrefix) {
411
1.41M
    if (insn->mode == MODE_64BIT) {
412
      // eliminate consecutive redundant REX bytes in front
413
493k
      if (consumeByte(insn, &byte))
414
227
        return -1;
415
416
493k
      if ((byte & 0xf0) == 0x40) {
417
77.3k
        while(true) {
418
77.3k
          if (lookAtByte(insn, &byte))  // out of input code
419
171
            return -1;
420
77.2k
          if ((byte & 0xf0) == 0x40) {
421
            // another REX prefix, but we only remember the last one
422
13.8k
            if (consumeByte(insn, &byte))
423
0
              return -1;
424
13.8k
          } else
425
63.3k
            break;
426
77.2k
        }
427
428
        // recover the last REX byte if next byte is not a legacy prefix
429
63.3k
        switch (byte) {
430
1.73k
          case 0xf2:  /* REPNE/REPNZ */
431
3.42k
          case 0xf3:  /* REP or REPE/REPZ */
432
5.00k
          case 0xf0:  /* LOCK */
433
5.54k
          case 0x2e:  /* CS segment override -OR- Branch not taken */
434
5.98k
          case 0x36:  /* SS segment override -OR- Branch taken */
435
6.26k
          case 0x3e:  /* DS segment override */
436
6.71k
          case 0x26:  /* ES segment override */
437
7.17k
          case 0x64:  /* FS segment override */
438
7.54k
          case 0x65:  /* GS segment override */
439
8.38k
          case 0x66:  /* Operand-size override */
440
9.26k
          case 0x67:  /* Address-size override */
441
9.26k
            break;
442
54.1k
          default:    /* Not a prefix byte */
443
54.1k
            unconsumeByte(insn);
444
54.1k
            break;
445
63.3k
        }
446
430k
      } else {
447
430k
        unconsumeByte(insn);
448
430k
      }
449
493k
    }
450
451
    /* If we fail reading prefixes, just stop here and let the opcode reader deal with it */
452
1.41M
    if (consumeByte(insn, &byte))
453
219
      return -1;
454
455
1.41M
    if (insn->readerCursor - 1 == insn->startLocation
456
1.41M
        && (byte == 0xf2 || byte == 0xf3)) {
457
      // prefix requires next byte
458
59.6k
      if (lookAtByte(insn, &nextByte))
459
137
        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
59.5k
      if (((nextByte == 0xf0) ||
469
59.5k
        ((nextByte & 0xfe) == 0x86 || (nextByte & 0xf8) == 0x90))) {
470
4.12k
        insn->xAcquireRelease = byte;
471
4.12k
      }
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
59.5k
      if (byte == 0xf3 && (nextByte == 0x88 || nextByte == 0x89 ||
480
25.0k
            nextByte == 0xc6 || nextByte == 0xc7)) {
481
814
        insn->xAcquireRelease = byte;
482
814
      }
483
484
59.5k
      if (isREX(insn, nextByte)) {
485
5.63k
        uint8_t nnextByte;
486
487
        // Go to REX prefix after the current one
488
5.63k
        if (consumeByte(insn, &nnextByte))
489
0
          return -1;
490
491
        // We should be able to read next byte after REX prefix
492
5.63k
        if (lookAtByte(insn, &nnextByte))
493
10
          return -1;
494
495
5.62k
        unconsumeByte(insn);
496
5.62k
      }
497
59.5k
    }
498
499
1.41M
    switch (byte) {
500
45.1k
      case 0xf0:  /* LOCK */
501
93.1k
      case 0xf2:  /* REPNE/REPNZ */
502
125k
      case 0xf3:  /* REP or REPE/REPZ */
503
        // only accept the last prefix
504
125k
        setPrefixPresent(insn, byte);
505
125k
        insn->prefix0 = byte;
506
125k
        break;
507
508
10.2k
      case 0x2e:  /* CS segment override -OR- Branch not taken */
509
14.0k
      case 0x36:  /* SS segment override -OR- Branch taken */
510
19.7k
      case 0x3e:  /* DS segment override */
511
25.6k
      case 0x26:  /* ES segment override */
512
33.6k
      case 0x64:  /* FS segment override */
513
40.3k
      case 0x65:  /* GS segment override */
514
40.3k
        switch (byte) {
515
10.2k
          case 0x2e:
516
10.2k
            insn->segmentOverride = SEG_OVERRIDE_CS;
517
10.2k
            insn->prefix1 = byte;
518
10.2k
            break;
519
3.84k
          case 0x36:
520
3.84k
            insn->segmentOverride = SEG_OVERRIDE_SS;
521
3.84k
            insn->prefix1 = byte;
522
3.84k
            break;
523
5.72k
          case 0x3e:
524
5.72k
            insn->segmentOverride = SEG_OVERRIDE_DS;
525
5.72k
            insn->prefix1 = byte;
526
5.72k
            break;
527
5.83k
          case 0x26:
528
5.83k
            insn->segmentOverride = SEG_OVERRIDE_ES;
529
5.83k
            insn->prefix1 = byte;
530
5.83k
            break;
531
8.04k
          case 0x64:
532
8.04k
            insn->segmentOverride = SEG_OVERRIDE_FS;
533
8.04k
            insn->prefix1 = byte;
534
8.04k
            break;
535
6.74k
          case 0x65:
536
6.74k
            insn->segmentOverride = SEG_OVERRIDE_GS;
537
6.74k
            insn->prefix1 = byte;
538
6.74k
            break;
539
0
          default:
540
            // debug("Unhandled override");
541
0
            return -1;
542
40.3k
        }
543
40.3k
        setPrefixPresent(insn, byte);
544
40.3k
        break;
545
546
25.7k
      case 0x66:  /* Operand-size override */
547
25.7k
        insn->hasOpSize = true;
548
25.7k
        setPrefixPresent(insn, byte);
549
25.7k
        insn->prefix2 = byte;
550
25.7k
        break;
551
552
10.0k
      case 0x67:  /* Address-size override */
553
10.0k
        insn->hasAdSize = true;
554
10.0k
        setPrefixPresent(insn, byte);
555
10.0k
        insn->prefix3 = byte;
556
10.0k
        break;
557
1.21M
      default:    /* Not a prefix byte */
558
1.21M
        isPrefix = false;
559
1.21M
        break;
560
1.41M
    }
561
1.41M
  }
562
563
1.21M
  insn->vectorExtensionType = TYPE_NO_VEX_XOP;
564
565
1.21M
  if (byte == 0x62) {
566
61.3k
    uint8_t byte1, byte2;
567
568
61.3k
    if (consumeByte(insn, &byte1)) {
569
      // dbgprintf(insn, "Couldn't read second byte of EVEX prefix");
570
76
      return -1;
571
76
    }
572
573
61.2k
    if (lookAtByte(insn, &byte2)) {
574
      // dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
575
96
      unconsumeByte(insn); /* unconsume byte1 */
576
96
      unconsumeByte(insn); /* unconsume byte  */
577
61.1k
    } else {
578
61.1k
      if ((insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) &&
579
61.1k
          ((~byte1 & 0xc) == 0xc) && ((byte2 & 0x4) == 0x4)) {
580
53.3k
        insn->vectorExtensionType = TYPE_EVEX;
581
53.3k
      } else {
582
7.83k
        unconsumeByte(insn); /* unconsume byte1 */
583
7.83k
        unconsumeByte(insn); /* unconsume byte  */
584
7.83k
      }
585
61.1k
    }
586
587
61.2k
    if (insn->vectorExtensionType == TYPE_EVEX) {
588
53.3k
      insn->vectorExtensionPrefix[0] = byte;
589
53.3k
      insn->vectorExtensionPrefix[1] = byte1;
590
53.3k
      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
53.3k
      if (consumeByte(insn, &insn->vectorExtensionPrefix[3])) {
596
        // dbgprintf(insn, "Couldn't read fourth byte of EVEX prefix");
597
31
        return -1;
598
31
      }
599
600
      /* We simulate the REX prefix for simplicity's sake */
601
53.3k
      if (insn->mode == MODE_64BIT) {
602
22.6k
        insn->rexPrefix = 0x40
603
22.6k
          | (wFromEVEX3of4(insn->vectorExtensionPrefix[2]) << 3)
604
22.6k
          | (rFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 2)
605
22.6k
          | (xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 1)
606
22.6k
          | (bFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 0);
607
22.6k
      }
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
53.3k
    }
613
1.15M
  } else if (byte == 0xc4) {
614
9.78k
    uint8_t byte1;
615
616
9.78k
    if (lookAtByte(insn, &byte1)) {
617
      // dbgprintf(insn, "Couldn't read second byte of VEX");
618
12
      return -1;
619
12
    }
620
621
9.77k
    if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)
622
7.64k
      insn->vectorExtensionType = TYPE_VEX_3B;
623
2.13k
    else
624
2.13k
      unconsumeByte(insn);
625
626
9.77k
    if (insn->vectorExtensionType == TYPE_VEX_3B) {
627
7.64k
      insn->vectorExtensionPrefix[0] = byte;
628
7.64k
      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
629
7.64k
      consumeByte(insn, &insn->vectorExtensionPrefix[2]);
630
631
      /* We simulate the REX prefix for simplicity's sake */
632
7.64k
      if (insn->mode == MODE_64BIT)
633
4.30k
        insn->rexPrefix = 0x40
634
4.30k
          | (wFromVEX3of3(insn->vectorExtensionPrefix[2]) << 3)
635
4.30k
          | (rFromVEX2of3(insn->vectorExtensionPrefix[1]) << 2)
636
4.30k
          | (xFromVEX2of3(insn->vectorExtensionPrefix[1]) << 1)
637
4.30k
          | (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
7.64k
    }
643
1.14M
  } else if (byte == 0xc5) {
644
14.4k
    uint8_t byte1;
645
646
14.4k
    if (lookAtByte(insn, &byte1)) {
647
      // dbgprintf(insn, "Couldn't read second byte of VEX");
648
32
      return -1;
649
32
    }
650
651
14.4k
    if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)
652
11.7k
      insn->vectorExtensionType = TYPE_VEX_2B;
653
2.69k
    else
654
2.69k
      unconsumeByte(insn);
655
656
14.4k
    if (insn->vectorExtensionType == TYPE_VEX_2B) {
657
11.7k
      insn->vectorExtensionPrefix[0] = byte;
658
11.7k
      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
659
660
11.7k
      if (insn->mode == MODE_64BIT)
661
2.79k
        insn->rexPrefix = 0x40
662
2.79k
          | (rFromVEX2of2(insn->vectorExtensionPrefix[1]) << 2);
663
664
11.7k
      switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
665
6.09k
        default:
666
6.09k
          break;
667
6.09k
        case VEX_PREFIX_66:
668
5.62k
          insn->hasOpSize = true;
669
5.62k
          break;
670
11.7k
      }
671
672
      // dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx",
673
      //    insn->vectorExtensionPrefix[0],
674
      //    insn->vectorExtensionPrefix[1]);
675
11.7k
    }
676
1.12M
  } else if (byte == 0x8f) {
677
8.47k
    uint8_t byte1;
678
679
8.47k
    if (lookAtByte(insn, &byte1)) {
680
      // dbgprintf(insn, "Couldn't read second byte of XOP");
681
12
      return -1;
682
12
    }
683
684
8.46k
    if ((byte1 & 0x38) != 0x0) /* 0 in these 3 bits is a POP instruction. */
685
7.26k
      insn->vectorExtensionType = TYPE_XOP;
686
1.20k
    else
687
1.20k
      unconsumeByte(insn);
688
689
8.46k
    if (insn->vectorExtensionType == TYPE_XOP) {
690
7.26k
      insn->vectorExtensionPrefix[0] = byte;
691
7.26k
      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
692
7.26k
      consumeByte(insn, &insn->vectorExtensionPrefix[2]);
693
694
      /* We simulate the REX prefix for simplicity's sake */
695
7.26k
      if (insn->mode == MODE_64BIT)
696
1.99k
        insn->rexPrefix = 0x40
697
1.99k
          | (wFromXOP3of3(insn->vectorExtensionPrefix[2]) << 3)
698
1.99k
          | (rFromXOP2of3(insn->vectorExtensionPrefix[1]) << 2)
699
1.99k
          | (xFromXOP2of3(insn->vectorExtensionPrefix[1]) << 1)
700
1.99k
          | (bFromXOP2of3(insn->vectorExtensionPrefix[1]) << 0);
701
702
7.26k
      switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
703
7.24k
        default:
704
7.24k
          break;
705
7.24k
        case VEX_PREFIX_66:
706
23
          insn->hasOpSize = true;
707
23
          break;
708
7.26k
      }
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
7.26k
    }
714
1.12M
  } else if (isREX(insn, byte)) {
715
54.1k
    if (lookAtByte(insn, &nextByte))
716
0
      return -1;
717
718
54.1k
    insn->rexPrefix = byte;
719
    // dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
720
54.1k
  } else
721
1.06M
    unconsumeByte(insn);
722
723
1.21M
  if (insn->mode == MODE_16BIT) {
724
418k
    insn->registerSize = (insn->hasOpSize ? 4 : 2);
725
418k
    insn->addressSize = (insn->hasAdSize ? 4 : 2);
726
418k
    insn->displacementSize = (insn->hasAdSize ? 4 : 2);
727
418k
    insn->immediateSize = (insn->hasOpSize ? 4 : 2);
728
418k
    insn->immSize = (insn->hasOpSize ? 4 : 2);
729
796k
  } else if (insn->mode == MODE_32BIT) {
730
385k
    insn->registerSize = (insn->hasOpSize ? 2 : 4);
731
385k
    insn->addressSize = (insn->hasAdSize ? 2 : 4);
732
385k
    insn->displacementSize = (insn->hasAdSize ? 2 : 4);
733
385k
    insn->immediateSize = (insn->hasOpSize ? 2 : 4);
734
385k
    insn->immSize = (insn->hasOpSize ? 2 : 4);
735
410k
  } else if (insn->mode == MODE_64BIT) {
736
410k
    if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
737
52.3k
      insn->registerSize       = 8;
738
52.3k
      insn->addressSize = (insn->hasAdSize ? 4 : 8);
739
52.3k
      insn->displacementSize   = 4;
740
52.3k
      insn->immediateSize      = 4;
741
52.3k
      insn->immSize      = 4;
742
358k
    } else {
743
358k
      insn->registerSize = (insn->hasOpSize ? 2 : 4);
744
358k
      insn->addressSize = (insn->hasAdSize ? 4 : 8);
745
358k
      insn->displacementSize = (insn->hasOpSize ? 2 : 4);
746
358k
      insn->immediateSize = (insn->hasOpSize ? 2 : 4);
747
358k
      insn->immSize      = (insn->hasOpSize ? 4 : 8);
748
358k
    }
749
410k
  }
750
751
1.21M
  return 0;
752
1.21M
}
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
1.21M
{
765
1.21M
  uint8_t current;
766
767
  // dbgprintf(insn, "readOpcode()");
768
769
1.21M
  insn->opcodeType = ONEBYTE;
770
771
1.21M
  if (insn->vectorExtensionType == TYPE_EVEX) {
772
53.3k
    switch (mmFromEVEX2of4(insn->vectorExtensionPrefix[1])) {
773
5
      default:
774
        // dbgprintf(insn, "Unhandled mm field for instruction (0x%hhx)",
775
        //    mmFromEVEX2of4(insn->vectorExtensionPrefix[1]));
776
5
        return -1;
777
14.9k
      case VEX_LOB_0F:
778
14.9k
        insn->opcodeType = TWOBYTE;
779
14.9k
        return consumeByte(insn, &insn->opcode);
780
16.6k
      case VEX_LOB_0F38:
781
16.6k
        insn->opcodeType = THREEBYTE_38;
782
16.6k
        return consumeByte(insn, &insn->opcode);
783
21.7k
      case VEX_LOB_0F3A:
784
21.7k
        insn->opcodeType = THREEBYTE_3A;
785
21.7k
        return consumeByte(insn, &insn->opcode);
786
53.3k
    }
787
1.16M
  } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
788
7.64k
    switch (mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])) {
789
41
      default:
790
        // dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
791
        //    mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
792
41
        return -1;
793
1.68k
      case VEX_LOB_0F:
794
        //insn->twoByteEscape = 0x0f;
795
1.68k
        insn->opcodeType = TWOBYTE;
796
1.68k
        return consumeByte(insn, &insn->opcode);
797
3.82k
      case VEX_LOB_0F38:
798
        //insn->twoByteEscape = 0x0f;
799
3.82k
        insn->opcodeType = THREEBYTE_38;
800
3.82k
        return consumeByte(insn, &insn->opcode);
801
2.08k
      case VEX_LOB_0F3A:
802
        //insn->twoByteEscape = 0x0f;
803
2.08k
        insn->opcodeType = THREEBYTE_3A;
804
2.08k
        return consumeByte(insn, &insn->opcode);
805
7.64k
    }
806
1.15M
  } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
807
    //insn->twoByteEscape = 0x0f;
808
11.7k
    insn->opcodeType = TWOBYTE;
809
11.7k
    return consumeByte(insn, &insn->opcode);
810
1.14M
  } else if (insn->vectorExtensionType == TYPE_XOP) {
811
7.26k
    switch (mmmmmFromXOP2of3(insn->vectorExtensionPrefix[1])) {
812
41
      default:
813
        // dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
814
        //    mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
815
41
        return -1;
816
6.62k
      case XOP_MAP_SELECT_8:
817
6.62k
        insn->opcodeType = XOP8_MAP;
818
6.62k
        return consumeByte(insn, &insn->opcode);
819
531
      case XOP_MAP_SELECT_9:
820
531
        insn->opcodeType = XOP9_MAP;
821
531
        return consumeByte(insn, &insn->opcode);
822
67
      case XOP_MAP_SELECT_A:
823
67
        insn->opcodeType = XOPA_MAP;
824
67
        return consumeByte(insn, &insn->opcode);
825
7.26k
    }
826
7.26k
  }
827
828
1.13M
  if (consumeByte(insn, &current))
829
0
    return -1;
830
831
    // save this first byte for MOVcr, MOVdr, MOVrc, MOVrd
832
1.13M
    insn->firstByte = current;
833
834
1.13M
  if (current == 0x0f) {
835
    // dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
836
47.2k
    insn->twoByteEscape = current;
837
838
47.2k
    if (consumeByte(insn, &current))
839
100
      return -1;
840
841
47.1k
    if (current == 0x38) {
842
      // dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
843
751
      if (consumeByte(insn, &current))
844
5
        return -1;
845
846
746
      insn->opcodeType = THREEBYTE_38;
847
46.4k
    } else if (current == 0x3a) {
848
      // dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
849
266
      if (consumeByte(insn, &current))
850
1
        return -1;
851
852
265
      insn->opcodeType = THREEBYTE_3A;
853
46.1k
    } 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
278
      if (readModRM(insn))
857
7
        return -1;
858
859
271
      if (consumeByte(insn, &current))
860
2
        return -1;
861
862
269
      insn->opcodeType = THREEDNOW_MAP;
863
45.8k
    } else {
864
      // dbgprintf(insn, "Didn't find a three-byte escape prefix");
865
45.8k
      insn->opcodeType = TWOBYTE;
866
45.8k
    }
867
1.08M
  } else if (insn->mandatoryPrefix)
868
    // The opcode with mandatory prefix must start with opcode escape.
869
    // If not it's legacy repeat prefix
870
9.68k
    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
1.13M
  insn->opcode = current;
878
879
1.13M
  return 0;
880
1.13M
}
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
1.66M
{
906
1.66M
  bool hasModRMExtension;
907
908
1.66M
  InstructionContext instructionClass = contextForAttrs(attrMask);
909
910
1.66M
  hasModRMExtension = modRMRequired(insn->opcodeType,
911
1.66M
      instructionClass,
912
1.66M
      insn->opcode);
913
914
1.66M
  if (hasModRMExtension) {
915
843k
    if (readModRM(insn))
916
2.78k
      return -1;
917
918
840k
    *instructionID = decode(insn->opcodeType,
919
840k
        instructionClass,
920
840k
        insn->opcode,
921
840k
        insn->modRM);
922
840k
  } else {
923
817k
    *instructionID = decode(insn->opcodeType,
924
817k
        instructionClass,
925
817k
        insn->opcode,
926
817k
        0);
927
817k
  }
928
929
1.65M
  return 0;
930
1.66M
}
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
396k
{
941
396k
  size_t i;
942
396k
  uint16_t idx;
943
944
396k
  if ((idx = x86_16_bit_eq_lookup[orig]) != 0) {
945
197k
    for (i = idx - 1; i < ARR_SIZE(x86_16_bit_eq_tbl) && x86_16_bit_eq_tbl[i].first == orig; i++) {
946
191k
      if (x86_16_bit_eq_tbl[i].second == equiv)
947
185k
        return true;
948
191k
    }
949
191k
  }
950
951
210k
  return false;
952
396k
}
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
17.2k
{
961
17.2k
  unsigned int i = find_insn(id);
962
17.2k
  if (i != -1) {
963
17.1k
    return insns[i].is64bit;
964
17.1k
  }
965
966
  // not found??
967
76
  return false;
968
17.2k
}
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
1.21M
{
981
1.21M
  uint16_t attrMask;
982
1.21M
  uint16_t instructionID;
983
984
1.21M
  attrMask = ATTR_NONE;
985
986
1.21M
  if (insn->mode == MODE_64BIT)
987
410k
    attrMask |= ATTR_64BIT;
988
989
1.21M
  if (insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
990
79.7k
    attrMask |= (insn->vectorExtensionType == TYPE_EVEX) ? ATTR_EVEX : ATTR_VEX;
991
992
79.7k
    if (insn->vectorExtensionType == TYPE_EVEX) {
993
53.2k
      switch (ppFromEVEX3of4(insn->vectorExtensionPrefix[2])) {
994
45.0k
        case VEX_PREFIX_66:
995
45.0k
          attrMask |= ATTR_OPSIZE;
996
45.0k
          break;
997
1.48k
        case VEX_PREFIX_F3:
998
1.48k
          attrMask |= ATTR_XS;
999
1.48k
          break;
1000
1.81k
        case VEX_PREFIX_F2:
1001
1.81k
          attrMask |= ATTR_XD;
1002
1.81k
          break;
1003
53.2k
      }
1004
1005
53.2k
      if (zFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1006
5.20k
        attrMask |= ATTR_EVEXKZ;
1007
53.2k
      if (bFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1008
18.0k
        attrMask |= ATTR_EVEXB;
1009
53.2k
      if (aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1010
37.1k
        attrMask |= ATTR_EVEXK;
1011
53.2k
      if (lFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1012
26.1k
        attrMask |= ATTR_EVEXL;
1013
53.2k
      if (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
1014
26.9k
        attrMask |= ATTR_EVEXL2;
1015
53.2k
    } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
1016
7.58k
      switch (ppFromVEX3of3(insn->vectorExtensionPrefix[2])) {
1017
6.43k
        case VEX_PREFIX_66:
1018
6.43k
          attrMask |= ATTR_OPSIZE;
1019
6.43k
          break;
1020
265
        case VEX_PREFIX_F3:
1021
265
          attrMask |= ATTR_XS;
1022
265
          break;
1023
498
        case VEX_PREFIX_F2:
1024
498
          attrMask |= ATTR_XD;
1025
498
          break;
1026
7.58k
      }
1027
1028
7.58k
      if (lFromVEX3of3(insn->vectorExtensionPrefix[2]))
1029
3.21k
        attrMask |= ATTR_VEXL;
1030
18.8k
    } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
1031
11.6k
      switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
1032
5.61k
        case VEX_PREFIX_66:
1033
5.61k
          attrMask |= ATTR_OPSIZE;
1034
5.61k
          break;
1035
1.76k
        case VEX_PREFIX_F3:
1036
1.76k
          attrMask |= ATTR_XS;
1037
1.76k
          break;
1038
1.88k
        case VEX_PREFIX_F2:
1039
1.88k
          attrMask |= ATTR_XD;
1040
1.88k
          break;
1041
11.6k
      }
1042
1043
11.6k
      if (lFromVEX2of2(insn->vectorExtensionPrefix[1]))
1044
7.34k
        attrMask |= ATTR_VEXL;
1045
11.6k
    } else if (insn->vectorExtensionType == TYPE_XOP) {
1046
7.20k
      switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
1047
13
        case VEX_PREFIX_66:
1048
13
          attrMask |= ATTR_OPSIZE;
1049
13
          break;
1050
11
        case VEX_PREFIX_F3:
1051
11
          attrMask |= ATTR_XS;
1052
11
          break;
1053
19
        case VEX_PREFIX_F2:
1054
19
          attrMask |= ATTR_XD;
1055
19
          break;
1056
7.20k
      }
1057
1058
7.20k
      if (lFromXOP3of3(insn->vectorExtensionPrefix[2]))
1059
135
        attrMask |= ATTR_VEXL;
1060
7.20k
    } else {
1061
0
      return -1;
1062
0
    }
1063
1.13M
  } else if (!insn->mandatoryPrefix) {
1064
    // If we don't have mandatory prefix we should use legacy prefixes here
1065
1.12M
    if (insn->hasOpSize && (insn->mode != MODE_16BIT))
1066
12.1k
      attrMask |= ATTR_OPSIZE;
1067
1.12M
    if (insn->hasAdSize)
1068
7.18k
      attrMask |= ATTR_ADSIZE;
1069
1.12M
    if (insn->opcodeType == ONEBYTE) {
1070
1.08M
      if (insn->repeatPrefix == 0xf3 && (insn->opcode == 0x90))
1071
        // Special support for PAUSE
1072
250
        attrMask |= ATTR_XS;
1073
1.08M
    } else {
1074
34.7k
      if (insn->repeatPrefix == 0xf2)
1075
693
        attrMask |= ATTR_XD;
1076
34.0k
      else if (insn->repeatPrefix == 0xf3)
1077
317
        attrMask |= ATTR_XS;
1078
34.7k
    }
1079
1.12M
  } else {
1080
12.3k
    switch (insn->mandatoryPrefix) {
1081
4.29k
      case 0xf2:
1082
4.29k
        attrMask |= ATTR_XD;
1083
4.29k
        break;
1084
4.81k
      case 0xf3:
1085
4.81k
        attrMask |= ATTR_XS;
1086
4.81k
        break;
1087
3.28k
      case 0x66:
1088
3.28k
        if (insn->mode != MODE_16BIT)
1089
2.58k
          attrMask |= ATTR_OPSIZE;
1090
3.28k
        break;
1091
0
      case 0x67:
1092
0
        attrMask |= ATTR_ADSIZE;
1093
0
        break;
1094
12.3k
    }
1095
1096
12.3k
  }
1097
1098
1.21M
  if (insn->rexPrefix & 0x08) {
1099
52.3k
    attrMask |= ATTR_REXW;
1100
52.3k
    attrMask &= ~ATTR_ADSIZE;
1101
52.3k
  }
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
1.21M
  if (insn->mode == MODE_16BIT && insn->opcodeType == ONEBYTE &&
1108
1.21M
      insn->opcode == 0xE3)
1109
1.91k
    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
1.21M
  if ((insn->mode == MODE_64BIT) && insn->hasOpSize) {
1116
10.7k
    switch (insn->opcode) {
1117
95
      case 0xE8:
1118
416
      case 0xE9:
1119
        // Take care of psubsb and other mmx instructions.
1120
416
        if (insn->opcodeType == ONEBYTE) {
1121
333
          attrMask ^= ATTR_OPSIZE;
1122
333
          insn->immediateSize = 4;
1123
333
          insn->displacementSize = 4;
1124
333
        }
1125
416
        break;
1126
36
      case 0x82:
1127
231
      case 0x83:
1128
303
      case 0x84:
1129
826
      case 0x85:
1130
1.16k
      case 0x86:
1131
1.63k
      case 0x87:
1132
1.86k
      case 0x88:
1133
1.91k
      case 0x89:
1134
2.06k
      case 0x8A:
1135
2.25k
      case 0x8B:
1136
2.40k
      case 0x8C:
1137
2.52k
      case 0x8D:
1138
2.85k
      case 0x8E:
1139
3.11k
      case 0x8F:
1140
        // Take care of lea and three byte ops.
1141
3.11k
        if (insn->opcodeType == TWOBYTE) {
1142
78
          attrMask ^= ATTR_OPSIZE;
1143
78
          insn->immediateSize = 4;
1144
78
          insn->displacementSize = 4;
1145
78
        }
1146
3.11k
        break;
1147
10.7k
    }
1148
10.7k
  }
1149
1150
  /* The following clauses compensate for limitations of the tables. */
1151
1.21M
  if (insn->mode != MODE_64BIT &&
1152
1.21M
      insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
1153
48.1k
    if (getIDWithAttrMask(&instructionID, insn, attrMask)) {
1154
32
      return -1;
1155
32
    }
1156
1157
    /*
1158
     * The tables can't distinguish between cases where the W-bit is used to
1159
     * select register size and cases where it's a required part of the opcode.
1160
     */
1161
48.0k
    if ((insn->vectorExtensionType == TYPE_EVEX &&
1162
48.0k
          wFromEVEX3of4(insn->vectorExtensionPrefix[2])) ||
1163
48.0k
        (insn->vectorExtensionType == TYPE_VEX_3B &&
1164
32.7k
         wFromVEX3of3(insn->vectorExtensionPrefix[2])) ||
1165
48.0k
        (insn->vectorExtensionType == TYPE_XOP &&
1166
31.0k
         wFromXOP3of3(insn->vectorExtensionPrefix[2]))) {
1167
17.2k
      uint16_t instructionIDWithREXW;
1168
1169
17.2k
      if (getIDWithAttrMask(&instructionIDWithREXW,
1170
17.2k
            insn, attrMask | ATTR_REXW)) {
1171
8
        insn->instructionID = instructionID;
1172
8
        insn->spec = specifierForUID(instructionID);
1173
8
        return 0;
1174
8
      }
1175
1176
      // If not a 64-bit instruction. Switch the opcode.
1177
17.2k
      if (!is64Bit(instructionIDWithREXW)) {
1178
16.2k
        insn->instructionID = instructionIDWithREXW;
1179
16.2k
        insn->spec = specifierForUID(instructionIDWithREXW);
1180
1181
16.2k
        return 0;
1182
16.2k
      }
1183
17.2k
    }
1184
48.0k
  }
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
1.19M
  if ((insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0)) ||
1194
1.19M
      (insn->opcodeType == TWOBYTE && (insn->opcode == 0xAE)) ||
1195
1.19M
      (insn->opcodeType == THREEBYTE_38 && insn->opcode == 0xF8)) {
1196
    /* Make sure we observed the prefixes in any position. */
1197
13.9k
    if (insn->hasAdSize)
1198
333
      attrMask |= ATTR_ADSIZE;
1199
1200
13.9k
    if (insn->hasOpSize)
1201
310
      attrMask |= ATTR_OPSIZE;
1202
1203
    /* In 16-bit, invert the attributes. */
1204
13.9k
    if (insn->mode == MODE_16BIT) {
1205
6.19k
      attrMask ^= ATTR_ADSIZE;
1206
1207
      /* The OpSize attribute is only valid with the absolute moves. */
1208
6.19k
      if (insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0))
1209
5.69k
        attrMask ^= ATTR_OPSIZE;
1210
6.19k
    }
1211
1212
13.9k
    if (getIDWithAttrMask(&instructionID, insn, attrMask)) {
1213
9
      return -1;
1214
9
    }
1215
1216
13.9k
    insn->instructionID = instructionID;
1217
13.9k
    insn->spec = specifierForUID(instructionID);
1218
1219
13.9k
    return 0;
1220
13.9k
  }
1221
1.18M
  if (getIDWithAttrMask(&instructionID, insn, attrMask)) {
1222
2.72k
    return -1;
1223
2.72k
  }
1224
1225
1.18M
  if ((insn->mode == MODE_16BIT || insn->hasOpSize) &&
1226
1.18M
      !(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
396k
    const struct InstructionSpecifier *spec;
1235
396k
    uint16_t instructionIDWithOpsize;
1236
1237
396k
    spec = specifierForUID(instructionID);
1238
1239
396k
    if (getIDWithAttrMask(&instructionIDWithOpsize,
1240
396k
          insn,
1241
396k
          attrMask | ATTR_OPSIZE)) {
1242
      /*
1243
       * ModRM required with OpSize but not present; give up and return version
1244
       * without OpSize set
1245
       */
1246
7
      insn->instructionID = instructionID;
1247
7
      insn->spec = spec;
1248
1249
7
      return 0;
1250
7
    }
1251
1252
396k
    if (is16BitEquivalent(instructionID, instructionIDWithOpsize) &&
1253
396k
        (insn->mode == MODE_16BIT) ^ insn->hasOpSize) {
1254
184k
      insn->instructionID = instructionIDWithOpsize;
1255
184k
      insn->spec = specifierForUID(instructionIDWithOpsize);
1256
212k
    } else {
1257
212k
      insn->instructionID = instructionID;
1258
212k
      insn->spec = spec;
1259
212k
    }
1260
1261
396k
    return 0;
1262
396k
  }
1263
1264
785k
  if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
1265
785k
      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
268
    const struct InstructionSpecifier *spec;
1271
268
    uint16_t instructionIDWithNewOpcode;
1272
268
    const struct InstructionSpecifier *specWithNewOpcode;
1273
1274
268
    spec = specifierForUID(instructionID);
1275
1276
    /* Borrow opcode from one of the other XCHGar opcodes */
1277
268
    insn->opcode = 0x91;
1278
1279
268
    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
268
    specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
1289
1290
    /* Change back */
1291
268
    insn->opcode = 0x90;
1292
1293
268
    insn->instructionID = instructionIDWithNewOpcode;
1294
268
    insn->spec = specWithNewOpcode;
1295
1296
268
    return 0;
1297
268
  }
1298
1299
785k
  insn->instructionID = instructionID;
1300
785k
  insn->spec = specifierForUID(insn->instructionID);
1301
1302
785k
  return 0;
1303
785k
}
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
29.6k
{
1314
29.6k
  SIBBase sibBaseBase = SIB_BASE_NONE;
1315
29.6k
  uint8_t index, base;
1316
1317
  // dbgprintf(insn, "readSIB()");
1318
1319
29.6k
  if (insn->consumedSIB)
1320
0
    return 0;
1321
1322
29.6k
  insn->consumedSIB = true;
1323
1324
29.6k
  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
13.4k
    case 4:
1329
13.4k
      insn->sibIndexBase = SIB_INDEX_EAX;
1330
13.4k
      sibBaseBase = SIB_BASE_EAX;
1331
13.4k
      break;
1332
16.2k
    case 8:
1333
16.2k
      insn->sibIndexBase = SIB_INDEX_RAX;
1334
16.2k
      sibBaseBase = SIB_BASE_RAX;
1335
16.2k
      break;
1336
29.6k
  }
1337
1338
29.6k
  if (consumeByte(insn, &insn->sib))
1339
79
    return -1;
1340
1341
29.5k
  index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
1342
1343
29.5k
  if (index == 0x4) {
1344
5.58k
    insn->sibIndex = SIB_INDEX_NONE;
1345
24.0k
  } else {
1346
24.0k
    insn->sibIndex = (SIBIndex)(insn->sibIndexBase + index);
1347
24.0k
  }
1348
1349
29.5k
  insn->sibScale = 1 << scaleFromSIB(insn->sib);
1350
1351
29.5k
  base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
1352
1353
29.5k
  switch (base) {
1354
2.86k
    case 0x5:
1355
3.18k
    case 0xd:
1356
3.18k
      switch (modFromModRM(insn->modRM)) {
1357
1.59k
        case 0x0:
1358
1.59k
          insn->eaDisplacement = EA_DISP_32;
1359
1.59k
          insn->sibBase = SIB_BASE_NONE;
1360
1.59k
          break;
1361
1.29k
        case 0x1:
1362
1.29k
          insn->eaDisplacement = EA_DISP_8;
1363
1.29k
          insn->sibBase = (SIBBase)(sibBaseBase + base);
1364
1.29k
          break;
1365
297
        case 0x2:
1366
297
          insn->eaDisplacement = EA_DISP_32;
1367
297
          insn->sibBase = (SIBBase)(sibBaseBase + base);
1368
297
          break;
1369
0
        case 0x3:
1370
          // debug("Cannot have Mod = 0b11 and a SIB byte");
1371
0
          return -1;
1372
3.18k
      }
1373
3.18k
      break;
1374
26.3k
    default:
1375
26.3k
      insn->sibBase = (SIBBase)(sibBaseBase + base);
1376
26.3k
      break;
1377
29.5k
  }
1378
1379
29.5k
  return 0;
1380
29.5k
}
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
209k
{
1391
209k
  int8_t d8;
1392
209k
  int16_t d16;
1393
209k
  int32_t d32;
1394
1395
  // dbgprintf(insn, "readDisplacement()");
1396
1397
209k
  if (insn->consumedDisplacement)
1398
0
    return 0;
1399
1400
209k
  insn->consumedDisplacement = true;
1401
209k
  insn->displacementOffset = insn->readerCursor - insn->startLocation;
1402
1403
209k
  switch (insn->eaDisplacement) {
1404
57.4k
    case EA_DISP_NONE:
1405
57.4k
      insn->consumedDisplacement = false;
1406
57.4k
      break;
1407
95.0k
    case EA_DISP_8:
1408
95.0k
      if (consumeInt8(insn, &d8))
1409
250
        return -1;
1410
94.7k
      insn->displacement = d8;
1411
94.7k
      break;
1412
26.3k
    case EA_DISP_16:
1413
26.3k
      if (consumeInt16(insn, &d16))
1414
110
        return -1;
1415
26.2k
      insn->displacement = d16;
1416
26.2k
      break;
1417
30.7k
    case EA_DISP_32:
1418
30.7k
      if (consumeInt32(insn, &d32))
1419
345
        return -1;
1420
30.4k
      insn->displacement = d32;
1421
30.4k
      break;
1422
209k
  }
1423
1424
1425
208k
  return 0;
1426
209k
}
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.92M
{
1437
1.92M
  uint8_t mod, rm, reg, evexrm;
1438
1439
  // dbgprintf(insn, "readModRM()");
1440
1441
1.92M
  if (insn->consumedModRM)
1442
1.30M
    return 0;
1443
1444
618k
  insn->modRMOffset = (uint8_t)(insn->readerCursor - insn->startLocation);
1445
1446
618k
  if (consumeByte(insn, &insn->modRM))
1447
2.00k
    return -1;
1448
1449
616k
  insn->consumedModRM = true;
1450
1451
  // save original ModRM for later reference
1452
616k
  insn->orgModRM = insn->modRM;
1453
1454
  // handle MOVcr, MOVdr, MOVrc, MOVrd by pretending they have MRM.mod = 3
1455
616k
  if ((insn->firstByte == 0x0f && insn->opcodeType == TWOBYTE) &&
1456
616k
      (insn->opcode >= 0x20 && insn->opcode <= 0x23 ))
1457
1.28k
    insn->modRM |= 0xC0;
1458
1459
616k
  mod = modFromModRM(insn->modRM);
1460
616k
  rm  = rmFromModRM(insn->modRM);
1461
616k
  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
616k
  switch (insn->registerSize) {
1469
215k
    case 2:
1470
215k
      insn->regBase = MODRM_REG_AX;
1471
215k
      insn->eaRegBase = EA_REG_AX;
1472
215k
      break;
1473
361k
    case 4:
1474
361k
      insn->regBase = MODRM_REG_EAX;
1475
361k
      insn->eaRegBase = EA_REG_EAX;
1476
361k
      break;
1477
39.2k
    case 8:
1478
39.2k
      insn->regBase = MODRM_REG_RAX;
1479
39.2k
      insn->eaRegBase = EA_REG_RAX;
1480
39.2k
      break;
1481
616k
  }
1482
1483
616k
  reg |= rFromREX(insn->rexPrefix) << 3;
1484
616k
  rm  |= bFromREX(insn->rexPrefix) << 3;
1485
1486
616k
  evexrm = 0;
1487
616k
  if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT) {
1488
22.5k
    reg |= r2FromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1489
22.5k
    evexrm = xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1490
22.5k
  }
1491
1492
616k
  insn->reg = (Reg)(insn->regBase + reg);
1493
1494
616k
  switch (insn->addressSize) {
1495
204k
    case 2: {
1496
204k
      EABase eaBaseBase = EA_BASE_BX_SI;
1497
1498
204k
      switch (mod) {
1499
115k
        case 0x0:
1500
115k
          if (rm == 0x6) {
1501
6.46k
            insn->eaBase = EA_BASE_NONE;
1502
6.46k
            insn->eaDisplacement = EA_DISP_16;
1503
6.46k
            if (readDisplacement(insn))
1504
22
              return -1;
1505
109k
          } else {
1506
109k
            insn->eaBase = (EABase)(eaBaseBase + rm);
1507
109k
            insn->eaDisplacement = EA_DISP_NONE;
1508
109k
          }
1509
115k
          break;
1510
115k
        case 0x1:
1511
29.0k
          insn->eaBase = (EABase)(eaBaseBase + rm);
1512
29.0k
          insn->eaDisplacement = EA_DISP_8;
1513
29.0k
          insn->displacementSize = 1;
1514
29.0k
          if (readDisplacement(insn))
1515
83
            return -1;
1516
28.9k
          break;
1517
28.9k
        case 0x2:
1518
19.9k
          insn->eaBase = (EABase)(eaBaseBase + rm);
1519
19.9k
          insn->eaDisplacement = EA_DISP_16;
1520
19.9k
          if (readDisplacement(insn))
1521
88
            return -1;
1522
19.8k
          break;
1523
40.4k
        case 0x3:
1524
40.4k
          insn->eaBase = (EABase)(insn->eaRegBase + rm);
1525
40.4k
          if (readDisplacement(insn))
1526
0
            return -1;
1527
40.4k
          break;
1528
204k
      }
1529
204k
      break;
1530
204k
    }
1531
1532
204k
    case 4:
1533
411k
    case 8: {
1534
411k
      EABase eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1535
1536
411k
      switch (mod) {
1537
0
        default: break;
1538
217k
        case 0x0:
1539
217k
          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
217k
          switch (rm & 7) {
1544
18.6k
            case 0x4: // SIB byte is present
1545
18.6k
              insn->eaBase = (insn->addressSize == 4 ?
1546
10.7k
                  EA_BASE_sib : EA_BASE_sib64);
1547
18.6k
              if (readSIB(insn) || readDisplacement(insn))
1548
46
                return -1;
1549
18.6k
              break;
1550
18.6k
            case 0x5: // RIP-relative
1551
5.10k
              insn->eaBase = EA_BASE_NONE;
1552
5.10k
              insn->eaDisplacement = EA_DISP_32;
1553
5.10k
              if (readDisplacement(insn))
1554
57
                return -1;
1555
5.04k
              break;
1556
194k
            default:
1557
194k
              insn->eaBase = (EABase)(eaBaseBase + rm);
1558
194k
              break;
1559
217k
          }
1560
217k
          break;
1561
217k
        case 0x1:
1562
66.0k
          insn->displacementSize = 1;
1563
          /* FALLTHROUGH */
1564
90.1k
        case 0x2:
1565
90.1k
          insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1566
90.1k
          switch (rm & 7) {
1567
11.0k
            case 0x4: // SIB byte is present
1568
11.0k
              insn->eaBase = EA_BASE_sib;
1569
11.0k
              if (readSIB(insn) || readDisplacement(insn))
1570
83
                return -1;
1571
10.9k
              break;
1572
79.1k
            default:
1573
79.1k
              insn->eaBase = (EABase)(eaBaseBase + rm);
1574
79.1k
              if (readDisplacement(insn))
1575
405
                return -1;
1576
78.7k
              break;
1577
90.1k
          }
1578
89.6k
          break;
1579
103k
        case 0x3:
1580
103k
          insn->eaDisplacement = EA_DISP_NONE;
1581
103k
          insn->eaBase = (EABase)(insn->eaRegBase + rm + evexrm);
1582
103k
          break;
1583
411k
      }
1584
1585
410k
      break;
1586
411k
    }
1587
616k
  } /* switch (insn->addressSize) */
1588
1589
615k
  return 0;
1590
616k
}
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
671k
                       uint8_t *valid) {                  \
1597
671k
    *valid = 1;                                           \
1598
671k
    switch (type) {                                       \
1599
0
    default:                                              \
1600
0
      *valid = 0;                                         \
1601
0
      return 0;                                           \
1602
163k
    case TYPE_Rv:                                         \
1603
163k
      return base + index;                                \
1604
276k
    case TYPE_R8:                                         \
1605
276k
      index &= mask;                                      \
1606
276k
      if (index > 0xf)                                    \
1607
276k
        *valid = 0;                                       \
1608
276k
      if (insn->rexPrefix &&                              \
1609
276k
         index >= 4 && index <= 7) {                      \
1610
2.28k
        return prefix##_SPL + (index - 4);                \
1611
274k
      } else {                                            \
1612
274k
        return prefix##_AL + index;                       \
1613
274k
      }                                                   \
1614
276k
    case TYPE_R16:                                        \
1615
8.62k
      index &= mask;                                      \
1616
8.62k
      if (index > 0xf)                                    \
1617
8.62k
        *valid = 0;                                       \
1618
8.62k
      return prefix##_AX + index;                         \
1619
276k
    case TYPE_R32:                                        \
1620
2.36k
      index &= mask;                                      \
1621
2.36k
      if (index > 0xf)                                    \
1622
2.36k
        *valid = 0;                                       \
1623
2.36k
      return prefix##_EAX + index;                        \
1624
276k
    case TYPE_R64:                                        \
1625
16.1k
      index &= mask;                                      \
1626
16.1k
      if (index > 0xf)                                    \
1627
16.1k
        *valid = 0;                                       \
1628
16.1k
      return prefix##_RAX + index;                        \
1629
276k
    case TYPE_ZMM:                                        \
1630
41.4k
      return prefix##_ZMM0 + index;                       \
1631
276k
    case TYPE_YMM:                                        \
1632
35.9k
      return prefix##_YMM0 + index;                       \
1633
276k
    case TYPE_XMM:                                        \
1634
80.2k
      return prefix##_XMM0 + index;                       \
1635
276k
    case TYPE_VK:                                         \
1636
26.5k
      index &= 0xf;                                       \
1637
26.5k
      if (index > 7)                                      \
1638
26.5k
        *valid = 0;                                       \
1639
26.5k
      return prefix##_K0 + index;                         \
1640
276k
    case TYPE_MM64:                                       \
1641
9.39k
      return prefix##_MM0 + (index & 0x7);                \
1642
276k
    case TYPE_SEGMENTREG:                                 \
1643
2.58k
      if ((index & 7) > 5)                                \
1644
2.58k
        *valid = 0;                                       \
1645
2.58k
      return prefix##_ES + (index & 7);                   \
1646
276k
    case TYPE_DEBUGREG:                                   \
1647
654
      return prefix##_DR0 + index;                        \
1648
276k
    case TYPE_CONTROLREG:                                 \
1649
632
      return prefix##_CR0 + index;                        \
1650
276k
    case TYPE_BNDR:                                       \
1651
6.95k
      if (index > 3)                                      \
1652
6.95k
        *valid = 0;                                       \
1653
6.95k
      return prefix##_BND0 + index;                       \
1654
276k
    case TYPE_MVSIBX:                                     \
1655
0
      return prefix##_XMM0 + index;                       \
1656
276k
    case TYPE_MVSIBY:                                     \
1657
0
      return prefix##_YMM0 + index;                       \
1658
276k
    case TYPE_MVSIBZ:                                     \
1659
0
      return prefix##_ZMM0 + index;                       \
1660
671k
    }                                                     \
1661
671k
  }
X86DisassemblerDecoder.c:fixupRegValue
Line
Count
Source
1596
538k
                       uint8_t *valid) {                  \
1597
538k
    *valid = 1;                                           \
1598
538k
    switch (type) {                                       \
1599
0
    default:                                              \
1600
0
      *valid = 0;                                         \
1601
0
      return 0;                                           \
1602
123k
    case TYPE_Rv:                                         \
1603
123k
      return base + index;                                \
1604
229k
    case TYPE_R8:                                         \
1605
229k
      index &= mask;                                      \
1606
229k
      if (index > 0xf)                                    \
1607
229k
        *valid = 0;                                       \
1608
229k
      if (insn->rexPrefix &&                              \
1609
229k
         index >= 4 && index <= 7) {                      \
1610
1.47k
        return prefix##_SPL + (index - 4);                \
1611
228k
      } else {                                            \
1612
228k
        return prefix##_AL + index;                       \
1613
228k
      }                                                   \
1614
229k
    case TYPE_R16:                                        \
1615
6.48k
      index &= mask;                                      \
1616
6.48k
      if (index > 0xf)                                    \
1617
6.48k
        *valid = 0;                                       \
1618
6.48k
      return prefix##_AX + index;                         \
1619
229k
    case TYPE_R32:                                        \
1620
858
      index &= mask;                                      \
1621
858
      if (index > 0xf)                                    \
1622
858
        *valid = 0;                                       \
1623
858
      return prefix##_EAX + index;                        \
1624
229k
    case TYPE_R64:                                        \
1625
10.4k
      index &= mask;                                      \
1626
10.4k
      if (index > 0xf)                                    \
1627
10.4k
        *valid = 0;                                       \
1628
10.4k
      return prefix##_RAX + index;                        \
1629
229k
    case TYPE_ZMM:                                        \
1630
33.4k
      return prefix##_ZMM0 + index;                       \
1631
229k
    case TYPE_YMM:                                        \
1632
28.2k
      return prefix##_YMM0 + index;                       \
1633
229k
    case TYPE_XMM:                                        \
1634
64.2k
      return prefix##_XMM0 + index;                       \
1635
229k
    case TYPE_VK:                                         \
1636
24.9k
      index &= 0xf;                                       \
1637
24.9k
      if (index > 7)                                      \
1638
24.9k
        *valid = 0;                                       \
1639
24.9k
      return prefix##_K0 + index;                         \
1640
229k
    case TYPE_MM64:                                       \
1641
6.14k
      return prefix##_MM0 + (index & 0x7);                \
1642
229k
    case TYPE_SEGMENTREG:                                 \
1643
2.58k
      if ((index & 7) > 5)                                \
1644
2.58k
        *valid = 0;                                       \
1645
2.58k
      return prefix##_ES + (index & 7);                   \
1646
229k
    case TYPE_DEBUGREG:                                   \
1647
654
      return prefix##_DR0 + index;                        \
1648
229k
    case TYPE_CONTROLREG:                                 \
1649
632
      return prefix##_CR0 + index;                        \
1650
229k
    case TYPE_BNDR:                                       \
1651
6.47k
      if (index > 3)                                      \
1652
6.47k
        *valid = 0;                                       \
1653
6.47k
      return prefix##_BND0 + index;                       \
1654
229k
    case TYPE_MVSIBX:                                     \
1655
0
      return prefix##_XMM0 + index;                       \
1656
229k
    case TYPE_MVSIBY:                                     \
1657
0
      return prefix##_YMM0 + index;                       \
1658
229k
    case TYPE_MVSIBZ:                                     \
1659
0
      return prefix##_ZMM0 + index;                       \
1660
538k
    }                                                     \
1661
538k
  }
X86DisassemblerDecoder.c:fixupRMValue
Line
Count
Source
1596
133k
                       uint8_t *valid) {                  \
1597
133k
    *valid = 1;                                           \
1598
133k
    switch (type) {                                       \
1599
0
    default:                                              \
1600
0
      *valid = 0;                                         \
1601
0
      return 0;                                           \
1602
40.2k
    case TYPE_Rv:                                         \
1603
40.2k
      return base + index;                                \
1604
46.9k
    case TYPE_R8:                                         \
1605
46.9k
      index &= mask;                                      \
1606
46.9k
      if (index > 0xf)                                    \
1607
46.9k
        *valid = 0;                                       \
1608
46.9k
      if (insn->rexPrefix &&                              \
1609
46.9k
         index >= 4 && index <= 7) {                      \
1610
807
        return prefix##_SPL + (index - 4);                \
1611
46.1k
      } else {                                            \
1612
46.1k
        return prefix##_AL + index;                       \
1613
46.1k
      }                                                   \
1614
46.9k
    case TYPE_R16:                                        \
1615
2.13k
      index &= mask;                                      \
1616
2.13k
      if (index > 0xf)                                    \
1617
2.13k
        *valid = 0;                                       \
1618
2.13k
      return prefix##_AX + index;                         \
1619
46.9k
    case TYPE_R32:                                        \
1620
1.50k
      index &= mask;                                      \
1621
1.50k
      if (index > 0xf)                                    \
1622
1.50k
        *valid = 0;                                       \
1623
1.50k
      return prefix##_EAX + index;                        \
1624
46.9k
    case TYPE_R64:                                        \
1625
5.70k
      index &= mask;                                      \
1626
5.70k
      if (index > 0xf)                                    \
1627
5.70k
        *valid = 0;                                       \
1628
5.70k
      return prefix##_RAX + index;                        \
1629
46.9k
    case TYPE_ZMM:                                        \
1630
8.00k
      return prefix##_ZMM0 + index;                       \
1631
46.9k
    case TYPE_YMM:                                        \
1632
7.70k
      return prefix##_YMM0 + index;                       \
1633
46.9k
    case TYPE_XMM:                                        \
1634
16.0k
      return prefix##_XMM0 + index;                       \
1635
46.9k
    case TYPE_VK:                                         \
1636
1.67k
      index &= 0xf;                                       \
1637
1.67k
      if (index > 7)                                      \
1638
1.67k
        *valid = 0;                                       \
1639
1.67k
      return prefix##_K0 + index;                         \
1640
46.9k
    case TYPE_MM64:                                       \
1641
3.24k
      return prefix##_MM0 + (index & 0x7);                \
1642
46.9k
    case TYPE_SEGMENTREG:                                 \
1643
0
      if ((index & 7) > 5)                                \
1644
0
        *valid = 0;                                       \
1645
0
      return prefix##_ES + (index & 7);                   \
1646
46.9k
    case TYPE_DEBUGREG:                                   \
1647
0
      return prefix##_DR0 + index;                        \
1648
46.9k
    case TYPE_CONTROLREG:                                 \
1649
0
      return prefix##_CR0 + index;                        \
1650
46.9k
    case TYPE_BNDR:                                       \
1651
483
      if (index > 3)                                      \
1652
483
        *valid = 0;                                       \
1653
483
      return prefix##_BND0 + index;                       \
1654
46.9k
    case TYPE_MVSIBX:                                     \
1655
0
      return prefix##_XMM0 + index;                       \
1656
46.9k
    case TYPE_MVSIBY:                                     \
1657
0
      return prefix##_YMM0 + index;                       \
1658
46.9k
    case TYPE_MVSIBZ:                                     \
1659
0
      return prefix##_ZMM0 + index;                       \
1660
133k
    }                                                     \
1661
133k
  }
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
1.13M
{
1691
1.13M
  uint8_t valid;
1692
1693
1.13M
  switch ((OperandEncoding)op->encoding) {
1694
0
    default:
1695
      // debug("Expected a REG or R/M encoding in fixupReg");
1696
0
      return -1;
1697
58.3k
    case ENCODING_VVVV:
1698
58.3k
      insn->vvvv = (Reg)fixupRegValue(insn,
1699
58.3k
          (OperandType)op->type,
1700
58.3k
          insn->vvvv,
1701
58.3k
          &valid);
1702
58.3k
      if (!valid)
1703
3
        return -1;
1704
58.3k
      break;
1705
479k
    case ENCODING_REG:
1706
479k
      insn->reg = (Reg)fixupRegValue(insn,
1707
479k
          (OperandType)op->type,
1708
479k
          insn->reg - insn->regBase,
1709
479k
          &valid);
1710
479k
      if (!valid)
1711
27
        return -1;
1712
479k
      break;
1713
4.00M
    CASE_ENCODING_RM:
1714
4.00M
      if (insn->eaBase >= insn->eaRegBase) {
1715
133k
        insn->eaBase = (EABase)fixupRMValue(insn,
1716
133k
            (OperandType)op->type,
1717
133k
            insn->eaBase - insn->eaRegBase,
1718
133k
            &valid);
1719
133k
        if (!valid)
1720
4
          return -1;
1721
133k
      }
1722
598k
      break;
1723
1.13M
  }
1724
1725
1.13M
  return 0;
1726
1.13M
}
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
136k
{
1741
136k
  if (size == 0)
1742
100k
    size = insn->registerSize;
1743
1744
136k
  switch (size) {
1745
13.3k
    case 1:
1746
13.3k
      insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
1747
13.3k
            | (insn->opcode & 7)));
1748
13.3k
      if (insn->rexPrefix &&
1749
13.3k
          insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1750
13.3k
          insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1751
514
        insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1752
514
            + (insn->opcodeRegister - MODRM_REG_AL - 4));
1753
514
      }
1754
1755
13.3k
      break;
1756
44.6k
    case 2:
1757
44.6k
      insn->opcodeRegister = (Reg)(MODRM_REG_AX
1758
44.6k
          + ((bFromREX(insn->rexPrefix) << 3)
1759
44.6k
            | (insn->opcode & 7)));
1760
44.6k
      break;
1761
55.8k
    case 4:
1762
55.8k
      insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1763
55.8k
          + ((bFromREX(insn->rexPrefix) << 3)
1764
55.8k
            | (insn->opcode & 7)));
1765
55.8k
      break;
1766
22.8k
    case 8:
1767
22.8k
      insn->opcodeRegister = (Reg)(MODRM_REG_RAX
1768
22.8k
          + ((bFromREX(insn->rexPrefix) << 3)
1769
22.8k
            | (insn->opcode & 7)));
1770
22.8k
      break;
1771
136k
  }
1772
1773
136k
  return 0;
1774
136k
}
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
303k
{
1787
303k
  uint8_t imm8;
1788
303k
  uint16_t imm16;
1789
303k
  uint32_t imm32;
1790
303k
  uint64_t imm64;
1791
1792
303k
  if (insn->numImmediatesConsumed == 2) {
1793
    // debug("Already consumed two immediates");
1794
0
    return -1;
1795
0
  }
1796
1797
303k
  if (size == 0)
1798
0
    size = insn->immediateSize;
1799
303k
  else
1800
303k
    insn->immediateSize = size;
1801
1802
303k
  insn->immediateOffset = insn->readerCursor - insn->startLocation;
1803
1804
303k
  switch (size) {
1805
222k
    case 1:
1806
222k
      if (consumeByte(insn, &imm8))
1807
878
        return -1;
1808
1809
221k
      insn->immediates[insn->numImmediatesConsumed] = imm8;
1810
221k
      break;
1811
45.8k
    case 2:
1812
45.8k
      if (consumeUInt16(insn, &imm16))
1813
296
        return -1;
1814
1815
45.5k
      insn->immediates[insn->numImmediatesConsumed] = imm16;
1816
45.5k
      break;
1817
30.8k
    case 4:
1818
30.8k
      if (consumeUInt32(insn, &imm32))
1819
572
        return -1;
1820
1821
30.2k
      insn->immediates[insn->numImmediatesConsumed] = imm32;
1822
30.2k
      break;
1823
4.39k
    case 8:
1824
4.39k
      if (consumeUInt64(insn, &imm64))
1825
107
        return -1;
1826
4.29k
      insn->immediates[insn->numImmediatesConsumed] = imm64;
1827
4.29k
      break;
1828
303k
  }
1829
1830
301k
  insn->numImmediatesConsumed++;
1831
1832
301k
  return 0;
1833
303k
}
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
1.21M
{
1844
1.21M
  int vvvv;
1845
1846
1.21M
  if (insn->vectorExtensionType == TYPE_EVEX)
1847
53.0k
    vvvv = (v2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 4 |
1848
53.0k
        vvvvFromEVEX3of4(insn->vectorExtensionPrefix[2]));
1849
1.15M
  else if (insn->vectorExtensionType == TYPE_VEX_3B)
1850
7.52k
    vvvv = vvvvFromVEX3of3(insn->vectorExtensionPrefix[2]);
1851
1.14M
  else if (insn->vectorExtensionType == TYPE_VEX_2B)
1852
11.6k
    vvvv = vvvvFromVEX2of2(insn->vectorExtensionPrefix[1]);
1853
1.13M
  else if (insn->vectorExtensionType == TYPE_XOP)
1854
7.11k
    vvvv = vvvvFromXOP3of3(insn->vectorExtensionPrefix[2]);
1855
1.13M
  else
1856
1.13M
    return -1;
1857
1858
79.3k
  if (insn->mode != MODE_64BIT)
1859
47.8k
    vvvv &= 0xf; // Can only clear bit 4. Bit 3 must be cleared later.
1860
1861
79.3k
  insn->vvvv = (Reg)vvvv;
1862
1863
79.3k
  return 0;
1864
1.21M
}
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
37.4k
{
1875
37.4k
  if (insn->vectorExtensionType != TYPE_EVEX)
1876
0
    return -1;
1877
1878
37.4k
  insn->writemask = (Reg)(aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]));
1879
1880
37.4k
  return 0;
1881
37.4k
}
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
1.21M
{
1892
1.21M
  int hasVVVV, needVVVV;
1893
1.21M
  int sawRegImm = 0;
1894
1.21M
  int i;
1895
1896
  /* If non-zero vvvv specified, need to make sure one of the operands
1897
     uses it. */
1898
1.21M
  hasVVVV = !readVVVV(insn);
1899
1.21M
  needVVVV = hasVVVV && (insn->vvvv != 0);
1900
1901
8.46M
  for (i = 0; i < X86_MAX_OPERANDS; ++i) {
1902
7.25M
    const OperandSpecifier *op = &x86OperandSets[insn->spec->operands][i];
1903
7.25M
    switch (op->encoding) {
1904
5.21M
      case ENCODING_NONE:
1905
5.28M
      case ENCODING_SI:
1906
5.37M
      case ENCODING_DI:
1907
5.37M
        break;
1908
1909
36.7k
      CASE_ENCODING_VSIB:
1910
        // VSIB can use the V2 bit so check only the other bits.
1911
36.7k
        if (needVVVV)
1912
3.98k
          needVVVV = hasVVVV & ((insn->vvvv & 0xf) != 0);
1913
1914
36.7k
        if (readModRM(insn))
1915
0
          return -1;
1916
1917
        // Reject if SIB wasn't used.
1918
6.89k
        if (insn->eaBase != EA_BASE_sib && insn->eaBase != EA_BASE_sib64)
1919
15
          return -1;
1920
1921
        // If sibIndex was set to SIB_INDEX_NONE, index offset is 4.
1922
6.88k
        if (insn->sibIndex == SIB_INDEX_NONE)
1923
621
          insn->sibIndex = (SIBIndex)(insn->sibIndexBase + 4);
1924
1925
        // If EVEX.v2 is set this is one of the 16-31 registers.
1926
6.88k
        if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT &&
1927
6.88k
            v2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
1928
2.38k
          insn->sibIndex = (SIBIndex)(insn->sibIndex + 16);
1929
1930
        // Adjust the index register to the correct size.
1931
6.88k
        switch (op->type) {
1932
0
          default:
1933
            // debug("Unhandled VSIB index type");
1934
0
            return -1;
1935
2.95k
          case TYPE_MVSIBX:
1936
2.95k
            insn->sibIndex = (SIBIndex)(SIB_INDEX_XMM0 +
1937
2.95k
                (insn->sibIndex - insn->sibIndexBase));
1938
2.95k
            break;
1939
2.16k
          case TYPE_MVSIBY:
1940
2.16k
            insn->sibIndex = (SIBIndex)(SIB_INDEX_YMM0 +
1941
2.16k
                (insn->sibIndex - insn->sibIndexBase));
1942
2.16k
            break;
1943
1.76k
          case TYPE_MVSIBZ:
1944
1.76k
            insn->sibIndex = (SIBIndex)(SIB_INDEX_ZMM0 +
1945
1.76k
                (insn->sibIndex - insn->sibIndexBase));
1946
1.76k
            break;
1947
6.88k
        }
1948
1949
        // Apply the AVX512 compressed displacement scaling factor.
1950
6.88k
        if (op->encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1951
983
          insn->displacement *= 1 << (op->encoding - ENCODING_VSIB);
1952
6.88k
        break;
1953
1954
479k
      case ENCODING_REG:
1955
7.35M
      CASE_ENCODING_RM:
1956
7.35M
        if (readModRM(insn))
1957
0
          return -1;
1958
1959
1.07M
        if (fixupReg(insn, op))
1960
31
          return -1;
1961
1962
        // Apply the AVX512 compressed displacement scaling factor.
1963
1.07M
        if (op->encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1964
93.7k
          insn->displacement *= 1 << (op->encoding - ENCODING_RM);
1965
1.07M
        break;
1966
1967
223k
      case ENCODING_IB:
1968
223k
        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
796
          insn->immediates[insn->numImmediatesConsumed] =
1972
796
            insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1973
796
          ++insn->numImmediatesConsumed;
1974
796
          break;
1975
796
        }
1976
222k
        if (readImmediate(insn, 1))
1977
878
          return -1;
1978
221k
        if (op->type == TYPE_XMM || op->type == TYPE_YMM)
1979
1.62k
          sawRegImm = 1;
1980
221k
        break;
1981
1982
14.9k
      case ENCODING_IW:
1983
14.9k
        if (readImmediate(insn, 2))
1984
77
          return -1;
1985
14.8k
        break;
1986
1987
14.8k
      case ENCODING_ID:
1988
5.44k
        if (readImmediate(insn, 4))
1989
102
          return -1;
1990
5.34k
        break;
1991
1992
5.34k
      case ENCODING_IO:
1993
450
        if (readImmediate(insn, 8))
1994
16
          return -1;
1995
434
        break;
1996
1997
47.2k
      case ENCODING_Iv:
1998
47.2k
        if (readImmediate(insn, insn->immediateSize))
1999
607
          return -1;
2000
46.6k
        break;
2001
2002
46.6k
      case ENCODING_Ia:
2003
13.0k
        if (readImmediate(insn, insn->addressSize))
2004
173
          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
12.8k
        insn->displacementOffset = insn->immediateOffset;
2009
12.8k
        insn->consumedDisplacement = true;
2010
12.8k
        insn->displacementSize = insn->immediateSize;
2011
12.8k
        insn->displacement = insn->immediates[insn->numImmediatesConsumed - 1];
2012
12.8k
        insn->immediateOffset = 0;
2013
12.8k
        insn->immediateSize = 0;
2014
12.8k
        break;
2015
2016
2.21k
      case ENCODING_IRC:
2017
2.21k
        insn->RC = (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 1) |
2018
2.21k
          lFromEVEX4of4(insn->vectorExtensionPrefix[3]);
2019
2.21k
        break;
2020
2021
13.3k
      case ENCODING_RB:
2022
13.3k
        if (readOpcodeRegister(insn, 1))
2023
0
          return -1;
2024
13.3k
        break;
2025
2026
13.3k
      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
22.7k
      case ENCODING_RO:
2037
22.7k
        if (readOpcodeRegister(insn, 8))
2038
0
          return -1;
2039
22.7k
        break;
2040
2041
100k
      case ENCODING_Rv:
2042
100k
        if (readOpcodeRegister(insn, 0))
2043
0
          return -1;
2044
100k
        break;
2045
2046
100k
      case ENCODING_FP:
2047
8.91k
        break;
2048
2049
58.3k
      case ENCODING_VVVV:
2050
58.3k
        if (!hasVVVV)
2051
0
          return -1;
2052
2053
58.3k
        needVVVV = 0; /* Mark that we have found a VVVV operand. */
2054
2055
58.3k
        if (insn->mode != MODE_64BIT)
2056
36.1k
          insn->vvvv = (Reg)(insn->vvvv & 0x7);
2057
2058
58.3k
        if (fixupReg(insn, op))
2059
3
          return -1;
2060
58.3k
        break;
2061
2062
58.3k
      case ENCODING_WRITEMASK:
2063
37.4k
        if (readMaskRegister(insn))
2064
0
          return -1;
2065
37.4k
        break;
2066
2067
249k
      case ENCODING_DUP:
2068
249k
        break;
2069
2070
0
      default:
2071
        // dbgprintf(insn, "Encountered an operand with an unknown encoding.");
2072
0
        return -1;
2073
7.25M
    }
2074
7.25M
  }
2075
2076
  /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
2077
1.20M
  if (needVVVV)
2078
21
    return -1;
2079
2080
1.20M
  return 0;
2081
1.20M
}
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
1.21M
{
2087
  // LOCK prefix
2088
1.21M
  if (insn->hasLockPrefix) {
2089
37.7k
    switch(insn->instructionID) {
2090
187
      default:
2091
        // invalid LOCK
2092
187
        return true;
2093
2094
      // nop dword [rax]
2095
58
      case X86_NOOPL:
2096
2097
      // DEC
2098
782
      case X86_DEC16m:
2099
930
      case X86_DEC32m:
2100
1.12k
      case X86_DEC64m:
2101
1.39k
      case X86_DEC8m:
2102
2103
      // ADC
2104
1.51k
      case X86_ADC16mi:
2105
1.88k
      case X86_ADC16mi8:
2106
2.04k
      case X86_ADC16mr:
2107
2.33k
      case X86_ADC32mi:
2108
2.58k
      case X86_ADC32mi8:
2109
2.87k
      case X86_ADC32mr:
2110
3.10k
      case X86_ADC64mi32:
2111
3.23k
      case X86_ADC64mi8:
2112
3.50k
      case X86_ADC64mr:
2113
3.74k
      case X86_ADC8mi:
2114
4.23k
      case X86_ADC8mi8:
2115
4.55k
      case X86_ADC8mr:
2116
4.67k
      case X86_ADC8rm:
2117
4.94k
      case X86_ADC16rm:
2118
5.59k
      case X86_ADC32rm:
2119
5.92k
      case X86_ADC64rm:
2120
2121
      // ADD
2122
6.18k
      case X86_ADD16mi:
2123
6.52k
      case X86_ADD16mi8:
2124
6.96k
      case X86_ADD16mr:
2125
7.25k
      case X86_ADD32mi:
2126
7.61k
      case X86_ADD32mi8:
2127
8.00k
      case X86_ADD32mr:
2128
8.22k
      case X86_ADD64mi32:
2129
8.62k
      case X86_ADD64mi8:
2130
9.08k
      case X86_ADD64mr:
2131
9.27k
      case X86_ADD8mi:
2132
9.39k
      case X86_ADD8mi8:
2133
10.6k
      case X86_ADD8mr:
2134
11.0k
      case X86_ADD8rm:
2135
11.2k
      case X86_ADD16rm:
2136
11.6k
      case X86_ADD32rm:
2137
11.7k
      case X86_ADD64rm:
2138
2139
      // AND
2140
12.0k
      case X86_AND16mi:
2141
12.4k
      case X86_AND16mi8:
2142
12.9k
      case X86_AND16mr:
2143
13.0k
      case X86_AND32mi:
2144
13.4k
      case X86_AND32mi8:
2145
13.7k
      case X86_AND32mr:
2146
14.0k
      case X86_AND64mi32:
2147
14.0k
      case X86_AND64mi8:
2148
14.4k
      case X86_AND64mr:
2149
14.6k
      case X86_AND8mi:
2150
14.7k
      case X86_AND8mi8:
2151
14.9k
      case X86_AND8mr:
2152
15.0k
      case X86_AND8rm:
2153
15.3k
      case X86_AND16rm:
2154
15.6k
      case X86_AND32rm:
2155
15.7k
      case X86_AND64rm:
2156
2157
      // BTC
2158
15.8k
      case X86_BTC16mi8:
2159
15.9k
      case X86_BTC16mr:
2160
16.1k
      case X86_BTC32mi8:
2161
16.4k
      case X86_BTC32mr:
2162
16.6k
      case X86_BTC64mi8:
2163
16.8k
      case X86_BTC64mr:
2164
2165
      // BTR
2166
17.0k
      case X86_BTR16mi8:
2167
17.3k
      case X86_BTR16mr:
2168
17.4k
      case X86_BTR32mi8:
2169
17.4k
      case X86_BTR32mr:
2170
17.5k
      case X86_BTR64mi8:
2171
17.6k
      case X86_BTR64mr:
2172
2173
      // BTS
2174
17.7k
      case X86_BTS16mi8:
2175
17.7k
      case X86_BTS16mr:
2176
17.9k
      case X86_BTS32mi8:
2177
18.2k
      case X86_BTS32mr:
2178
18.5k
      case X86_BTS64mi8:
2179
18.7k
      case X86_BTS64mr:
2180
2181
      // CMPXCHG
2182
18.8k
      case X86_CMPXCHG16B:
2183
19.0k
      case X86_CMPXCHG16rm:
2184
19.1k
      case X86_CMPXCHG32rm:
2185
19.1k
      case X86_CMPXCHG64rm:
2186
19.3k
      case X86_CMPXCHG8rm:
2187
19.4k
      case X86_CMPXCHG8B:
2188
2189
      // INC
2190
19.6k
      case X86_INC16m:
2191
19.7k
      case X86_INC32m:
2192
19.9k
      case X86_INC64m:
2193
20.0k
      case X86_INC8m:
2194
2195
      // NEG
2196
20.0k
      case X86_NEG16m:
2197
20.4k
      case X86_NEG32m:
2198
20.4k
      case X86_NEG64m:
2199
20.6k
      case X86_NEG8m:
2200
2201
      // NOT
2202
20.7k
      case X86_NOT16m:
2203
20.8k
      case X86_NOT32m:
2204
20.9k
      case X86_NOT64m:
2205
21.1k
      case X86_NOT8m:
2206
2207
      // OR
2208
21.4k
      case X86_OR16mi:
2209
21.6k
      case X86_OR16mi8:
2210
21.9k
      case X86_OR16mr:
2211
22.0k
      case X86_OR32mi:
2212
22.2k
      case X86_OR32mi8:
2213
22.7k
      case X86_OR32mr:
2214
22.9k
      case X86_OR64mi32:
2215
23.0k
      case X86_OR64mi8:
2216
23.3k
      case X86_OR64mr:
2217
23.8k
      case X86_OR8mi8:
2218
24.0k
      case X86_OR8mi:
2219
24.6k
      case X86_OR8mr:
2220
24.7k
      case X86_OR8rm:
2221
25.1k
      case X86_OR16rm:
2222
25.2k
      case X86_OR32rm:
2223
25.4k
      case X86_OR64rm:
2224
2225
      // SBB
2226
25.5k
      case X86_SBB16mi:
2227
25.8k
      case X86_SBB16mi8:
2228
26.2k
      case X86_SBB16mr:
2229
26.4k
      case X86_SBB32mi:
2230
26.7k
      case X86_SBB32mi8:
2231
27.0k
      case X86_SBB32mr:
2232
27.2k
      case X86_SBB64mi32:
2233
27.5k
      case X86_SBB64mi8:
2234
27.6k
      case X86_SBB64mr:
2235
27.8k
      case X86_SBB8mi:
2236
28.0k
      case X86_SBB8mi8:
2237
28.2k
      case X86_SBB8mr:
2238
2239
      // SUB
2240
28.6k
      case X86_SUB16mi:
2241
28.9k
      case X86_SUB16mi8:
2242
29.2k
      case X86_SUB16mr:
2243
29.4k
      case X86_SUB32mi:
2244
29.7k
      case X86_SUB32mi8:
2245
29.8k
      case X86_SUB32mr:
2246
29.9k
      case X86_SUB64mi32:
2247
30.0k
      case X86_SUB64mi8:
2248
30.1k
      case X86_SUB64mr:
2249
30.3k
      case X86_SUB8mi8:
2250
30.4k
      case X86_SUB8mi:
2251
30.6k
      case X86_SUB8mr:
2252
30.9k
      case X86_SUB8rm:
2253
31.2k
      case X86_SUB16rm:
2254
31.7k
      case X86_SUB32rm:
2255
31.9k
      case X86_SUB64rm:
2256
2257
      // XADD
2258
32.0k
      case X86_XADD16rm:
2259
32.1k
      case X86_XADD32rm:
2260
32.4k
      case X86_XADD64rm:
2261
32.4k
      case X86_XADD8rm:
2262
2263
      // XCHG
2264
32.6k
      case X86_XCHG16rm:
2265
33.0k
      case X86_XCHG32rm:
2266
33.2k
      case X86_XCHG64rm:
2267
33.5k
      case X86_XCHG8rm:
2268
2269
      // XOR
2270
33.6k
      case X86_XOR16mi:
2271
33.9k
      case X86_XOR16mi8:
2272
34.2k
      case X86_XOR16mr:
2273
34.5k
      case X86_XOR32mi:
2274
34.9k
      case X86_XOR32mi8:
2275
35.2k
      case X86_XOR32mr:
2276
35.3k
      case X86_XOR64mi32:
2277
35.3k
      case X86_XOR64mi8:
2278
35.5k
      case X86_XOR64mr:
2279
35.7k
      case X86_XOR8mi8:
2280
36.0k
      case X86_XOR8mi:
2281
36.3k
      case X86_XOR8mr:
2282
36.6k
      case X86_XOR8rm:
2283
36.8k
      case X86_XOR16rm:
2284
37.0k
      case X86_XOR32rm:
2285
37.5k
      case X86_XOR64rm:
2286
2287
        // this instruction can be used with LOCK prefix
2288
37.5k
        return false;
2289
37.7k
    }
2290
37.7k
  }
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
1.17M
  return false;
2305
1.21M
}
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
1.21M
{
2328
1.21M
  insn->reader = reader;
2329
1.21M
  insn->readerArg = readerArg;
2330
1.21M
  insn->startLocation = startLoc;
2331
1.21M
  insn->readerCursor = startLoc;
2332
1.21M
  insn->mode = mode;
2333
1.21M
  insn->numImmediatesConsumed = 0;
2334
2335
1.21M
  if (readPrefixes(insn) ||
2336
1.21M
      readOpcode(insn) ||
2337
1.21M
      getID(insn) ||
2338
1.21M
      insn->instructionID == 0 ||
2339
1.21M
      checkPrefix(insn) ||
2340
1.21M
      readOperands(insn))
2341
7.59k
    return -1;
2342
2343
1.20M
  insn->length = (size_t)(insn->readerCursor - insn->startLocation);
2344
2345
  // instruction length must be <= 15 to be valid
2346
1.20M
  if (insn->length > 15)
2347
56
    return -1;
2348
2349
1.20M
  if (insn->operandSize == 0)
2350
1.20M
    insn->operandSize = insn->registerSize;
2351
2352
1.20M
  insn->operands = &x86OperandSets[insn->spec->operands][0];
2353
2354
1.20M
  return 0;
2355
1.20M
}
2356
2357
#endif
2358