Coverage Report

Created: 2025-10-10 06:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/capstonev5/arch/X86/X86DisassemblerDecoder.c
Line
Count
Source
1
/*===-- X86DisassemblerDecoder.c - Disassembler decoder ------------*- C -*-===*
2
 *
3
 *                     The LLVM Compiler Infrastructure
4
 *
5
 * This file is distributed under the University of Illinois Open Source
6
 * License. See LICENSE.TXT for details.
7
 *
8
 *===----------------------------------------------------------------------===*
9
 *
10
 * This file is part of the X86 Disassembler.
11
 * It contains the implementation of the instruction decoder.
12
 * Documentation for the disassembler can be found in X86Disassembler.h.
13
 *
14
 *===----------------------------------------------------------------------===*/
15
16
/* Capstone Disassembly Engine */
17
/* By Nguyen Anh Quynh <aquynh@gmail.com>, 2013-2019 */
18
19
#ifdef CAPSTONE_HAS_X86
20
21
#include <stdarg.h>   /* for va_*()       */
22
#if defined(CAPSTONE_HAS_OSXKERNEL)
23
#include <libkern/libkern.h>
24
#else
25
#include <stdlib.h>   /* for exit()       */
26
#endif
27
28
#include <string.h>
29
30
#include "../../cs_priv.h"
31
#include "../../utils.h"
32
33
#include "X86DisassemblerDecoder.h"
34
#include "X86Mapping.h"
35
36
/// Specifies whether a ModR/M byte is needed and (if so) which
37
/// instruction each possible value of the ModR/M byte corresponds to.  Once
38
/// this information is known, we have narrowed down to a single instruction.
39
struct ModRMDecision {
40
  uint8_t modrm_type;
41
  uint16_t instructionIDs;
42
};
43
44
/// Specifies which set of ModR/M->instruction tables to look at
45
/// given a particular opcode.
46
struct OpcodeDecision {
47
  struct ModRMDecision modRMDecisions[256];
48
};
49
50
/// Specifies which opcode->instruction tables to look at given
51
/// a particular context (set of attributes).  Since there are many possible
52
/// contexts, the decoder first uses CONTEXTS_SYM to determine which context
53
/// applies given a specific set of attributes.  Hence there are only IC_max
54
/// entries in this table, rather than 2^(ATTR_max).
55
struct ContextDecision {
56
  struct OpcodeDecision opcodeDecisions[IC_max];
57
};
58
59
#ifdef CAPSTONE_X86_REDUCE
60
#include "X86GenDisassemblerTables_reduce.inc"
61
#include "X86GenDisassemblerTables_reduce2.inc"
62
#include "X86Lookup16_reduce.inc"
63
#else
64
#include "X86GenDisassemblerTables.inc"
65
#include "X86GenDisassemblerTables2.inc"
66
#include "X86Lookup16.inc"
67
#endif
68
69
/*
70
 * contextForAttrs - Client for the instruction context table.  Takes a set of
71
 *   attributes and returns the appropriate decode context.
72
 *
73
 * @param attrMask  - Attributes, from the enumeration attributeBits.
74
 * @return          - The InstructionContext to use when looking up an
75
 *                    an instruction with these attributes.
76
 */
77
static InstructionContext contextForAttrs(uint16_t attrMask)
78
331k
{
79
331k
  return CONTEXTS_SYM[attrMask];
80
331k
}
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
331k
{
97
331k
  const struct OpcodeDecision *decision = NULL;
98
331k
  const uint8_t *indextable = NULL;
99
331k
  unsigned int index;
100
101
331k
  switch (type) {
102
0
    default: break;
103
249k
    case ONEBYTE:
104
249k
      decision = ONEBYTE_SYM;
105
249k
      indextable = index_x86DisassemblerOneByteOpcodes;
106
249k
      break;
107
34.9k
    case TWOBYTE:
108
34.9k
      decision = TWOBYTE_SYM;
109
34.9k
      indextable = index_x86DisassemblerTwoByteOpcodes;
110
34.9k
      break;
111
16.9k
    case THREEBYTE_38:
112
16.9k
      decision = THREEBYTE38_SYM;
113
16.9k
      indextable = index_x86DisassemblerThreeByte38Opcodes;
114
16.9k
      break;
115
24.1k
    case THREEBYTE_3A:
116
24.1k
      decision = THREEBYTE3A_SYM;
117
24.1k
      indextable = index_x86DisassemblerThreeByte3AOpcodes;
118
24.1k
      break;
119
0
#ifndef CAPSTONE_X86_REDUCE
120
4.82k
    case XOP8_MAP:
121
4.82k
      decision = XOP8_MAP_SYM;
122
4.82k
      indextable = index_x86DisassemblerXOP8Opcodes;
123
4.82k
      break;
124
52
    case XOP9_MAP:
125
52
      decision = XOP9_MAP_SYM;
126
52
      indextable = index_x86DisassemblerXOP9Opcodes;
127
52
      break;
128
336
    case XOPA_MAP:
129
336
      decision = XOPA_MAP_SYM;
130
336
      indextable = index_x86DisassemblerXOPAOpcodes;
131
336
      break;
132
681
    case THREEDNOW_MAP:
133
      // 3DNow instructions always have ModRM byte
134
681
      return true;
135
331k
#endif
136
331k
  }
137
138
  // return decision->opcodeDecisions[insnContext].modRMDecisions[opcode].modrm_type != MODRM_ONEENTRY;
139
330k
  index = indextable[insnContext];
140
330k
  if (index)
141
328k
    return decision[index - 1].modRMDecisions[opcode].modrm_type != MODRM_ONEENTRY;
142
2.48k
  else
143
2.48k
    return false;
144
330k
}
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
330k
{
161
330k
  const struct ModRMDecision *dec = NULL;
162
330k
  unsigned int index;
163
330k
  static const struct OpcodeDecision emptyDecision = { 0 };
164
165
330k
  switch (type) {
166
0
    default: break; // never reach
167
249k
    case ONEBYTE:
168
      // dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
169
249k
      index = index_x86DisassemblerOneByteOpcodes[insnContext];
170
249k
      if (index)
171
249k
        dec = &ONEBYTE_SYM[index - 1].modRMDecisions[opcode];
172
18
      else
173
18
        dec = &emptyDecision.modRMDecisions[opcode];
174
249k
      break;
175
34.9k
    case TWOBYTE:
176
      //dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
177
34.9k
      index = index_x86DisassemblerTwoByteOpcodes[insnContext];
178
34.9k
      if (index)
179
34.0k
        dec = &TWOBYTE_SYM[index - 1].modRMDecisions[opcode];
180
926
      else
181
926
        dec = &emptyDecision.modRMDecisions[opcode];
182
34.9k
      break;
183
16.9k
    case THREEBYTE_38:
184
      // dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
185
16.9k
      index = index_x86DisassemblerThreeByte38Opcodes[insnContext];
186
16.9k
      if (index)
187
16.9k
        dec = &THREEBYTE38_SYM[index - 1].modRMDecisions[opcode];
188
25
      else
189
25
        dec = &emptyDecision.modRMDecisions[opcode];
190
16.9k
      break;
191
24.1k
    case THREEBYTE_3A:
192
      //dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
193
24.1k
      index = index_x86DisassemblerThreeByte3AOpcodes[insnContext];
194
24.1k
      if (index)
195
23.9k
        dec = &THREEBYTE3A_SYM[index - 1].modRMDecisions[opcode];
196
158
      else
197
158
        dec = &emptyDecision.modRMDecisions[opcode];
198
24.1k
      break;
199
0
#ifndef CAPSTONE_X86_REDUCE
200
4.82k
    case XOP8_MAP:
201
      // dec = &XOP8_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
202
4.82k
      index = index_x86DisassemblerXOP8Opcodes[insnContext];
203
4.82k
      if (index)
204
3.56k
        dec = &XOP8_MAP_SYM[index - 1].modRMDecisions[opcode];
205
1.25k
      else
206
1.25k
        dec = &emptyDecision.modRMDecisions[opcode];
207
4.82k
      break;
208
52
    case XOP9_MAP:
209
      // dec = &XOP9_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
210
52
      index = index_x86DisassemblerXOP9Opcodes[insnContext];
211
52
      if (index)
212
42
        dec = &XOP9_MAP_SYM[index - 1].modRMDecisions[opcode];
213
10
      else
214
10
        dec = &emptyDecision.modRMDecisions[opcode];
215
52
      break;
216
336
    case XOPA_MAP:
217
      // dec = &XOPA_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
218
336
      index = index_x86DisassemblerXOPAOpcodes[insnContext];
219
336
      if (index)
220
248
        dec = &XOPA_MAP_SYM[index - 1].modRMDecisions[opcode];
221
88
      else
222
88
        dec = &emptyDecision.modRMDecisions[opcode];
223
336
      break;
224
681
    case THREEDNOW_MAP:
225
      // dec = &THREEDNOW_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
226
681
      index = index_x86Disassembler3DNowOpcodes[insnContext];
227
681
      if (index)
228
450
        dec = &THREEDNOW_MAP_SYM[index - 1].modRMDecisions[opcode];
229
231
      else
230
231
        dec = &emptyDecision.modRMDecisions[opcode];
231
681
      break;
232
330k
#endif
233
330k
  }
234
235
330k
  switch (dec->modrm_type) {
236
0
    default:
237
      // debug("Corrupt table!  Unknown modrm_type");
238
0
      return 0;
239
142k
    case MODRM_ONEENTRY:
240
142k
      return modRMTable[dec->instructionIDs];
241
151k
    case MODRM_SPLITRM:
242
151k
      if (modFromModRM(modRM) == 0x3)
243
36.0k
        return modRMTable[dec->instructionIDs + 1];
244
115k
      return modRMTable[dec->instructionIDs];
245
30.1k
    case MODRM_SPLITREG:
246
30.1k
      if (modFromModRM(modRM) == 0x3)
247
8.08k
        return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3) + 8];
248
22.1k
      return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
249
5.97k
    case MODRM_SPLITMISC:
250
5.97k
      if (modFromModRM(modRM) == 0x3)
251
977
        return modRMTable[dec->instructionIDs+(modRM & 0x3f) + 8];
252
4.99k
      return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
253
0
    case MODRM_FULL:
254
0
      return modRMTable[dec->instructionIDs+modRM];
255
330k
  }
256
330k
}
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
273k
{
268
273k
  return &INSTRUCTIONS_SYM[uid];
269
273k
}
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
996k
{
283
996k
  int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
284
285
996k
  if (!ret)
286
996k
    ++(insn->readerCursor);
287
288
996k
  return ret;
289
996k
}
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
116k
{
300
116k
  return insn->reader(insn->readerArg, byte, insn->readerCursor);
301
116k
}
302
303
static void unconsumeByte(struct InternalInstruction* insn)
304
310k
{
305
310k
  insn->readerCursor--;
306
310k
}
307
308
#define CONSUME_FUNC(name, type)                                  \
309
49.4k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
49.4k
    type combined = 0;                                            \
311
49.4k
    unsigned offset;                                              \
312
159k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
109k
      uint8_t byte;                                               \
314
109k
      int ret = insn->reader(insn->readerArg,                     \
315
109k
                             &byte,                               \
316
109k
                             insn->readerCursor + offset);        \
317
109k
      if (ret)                                                    \
318
109k
        return ret;                                               \
319
109k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
109k
    }                                                             \
321
49.4k
    *ptr = combined;                                              \
322
49.1k
    insn->readerCursor += sizeof(type);                           \
323
49.1k
    return 0;                                                     \
324
49.4k
  }
X86DisassemblerDecoder.c:consumeInt8
Line
Count
Source
309
22.3k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
22.3k
    type combined = 0;                                            \
311
22.3k
    unsigned offset;                                              \
312
44.6k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
22.3k
      uint8_t byte;                                               \
314
22.3k
      int ret = insn->reader(insn->readerArg,                     \
315
22.3k
                             &byte,                               \
316
22.3k
                             insn->readerCursor + offset);        \
317
22.3k
      if (ret)                                                    \
318
22.3k
        return ret;                                               \
319
22.3k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
22.2k
    }                                                             \
321
22.3k
    *ptr = combined;                                              \
322
22.2k
    insn->readerCursor += sizeof(type);                           \
323
22.2k
    return 0;                                                     \
324
22.3k
  }
X86DisassemblerDecoder.c:consumeInt16
Line
Count
Source
309
3.43k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
3.43k
    type combined = 0;                                            \
311
3.43k
    unsigned offset;                                              \
312
10.2k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
6.86k
      uint8_t byte;                                               \
314
6.86k
      int ret = insn->reader(insn->readerArg,                     \
315
6.86k
                             &byte,                               \
316
6.86k
                             insn->readerCursor + offset);        \
317
6.86k
      if (ret)                                                    \
318
6.86k
        return ret;                                               \
319
6.86k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
6.85k
    }                                                             \
321
3.43k
    *ptr = combined;                                              \
322
3.42k
    insn->readerCursor += sizeof(type);                           \
323
3.42k
    return 0;                                                     \
324
3.43k
  }
X86DisassemblerDecoder.c:consumeInt32
Line
Count
Source
309
6.14k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
6.14k
    type combined = 0;                                            \
311
6.14k
    unsigned offset;                                              \
312
30.5k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
24.4k
      uint8_t byte;                                               \
314
24.4k
      int ret = insn->reader(insn->readerArg,                     \
315
24.4k
                             &byte,                               \
316
24.4k
                             insn->readerCursor + offset);        \
317
24.4k
      if (ret)                                                    \
318
24.4k
        return ret;                                               \
319
24.4k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
24.3k
    }                                                             \
321
6.14k
    *ptr = combined;                                              \
322
6.07k
    insn->readerCursor += sizeof(type);                           \
323
6.07k
    return 0;                                                     \
324
6.14k
  }
X86DisassemblerDecoder.c:consumeUInt16
Line
Count
Source
309
8.88k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
8.88k
    type combined = 0;                                            \
311
8.88k
    unsigned offset;                                              \
312
26.5k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
17.7k
      uint8_t byte;                                               \
314
17.7k
      int ret = insn->reader(insn->readerArg,                     \
315
17.7k
                             &byte,                               \
316
17.7k
                             insn->readerCursor + offset);        \
317
17.7k
      if (ret)                                                    \
318
17.7k
        return ret;                                               \
319
17.7k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
17.6k
    }                                                             \
321
8.88k
    *ptr = combined;                                              \
322
8.82k
    insn->readerCursor += sizeof(type);                           \
323
8.82k
    return 0;                                                     \
324
8.88k
  }
X86DisassemblerDecoder.c:consumeUInt32
Line
Count
Source
309
7.53k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
7.53k
    type combined = 0;                                            \
311
7.53k
    unsigned offset;                                              \
312
37.3k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
29.9k
      uint8_t byte;                                               \
314
29.9k
      int ret = insn->reader(insn->readerArg,                     \
315
29.9k
                             &byte,                               \
316
29.9k
                             insn->readerCursor + offset);        \
317
29.9k
      if (ret)                                                    \
318
29.9k
        return ret;                                               \
319
29.9k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
29.8k
    }                                                             \
321
7.53k
    *ptr = combined;                                              \
322
7.43k
    insn->readerCursor += sizeof(type);                           \
323
7.43k
    return 0;                                                     \
324
7.53k
  }
X86DisassemblerDecoder.c:consumeUInt64
Line
Count
Source
309
1.09k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
1.09k
    type combined = 0;                                            \
311
1.09k
    unsigned offset;                                              \
312
9.74k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
8.67k
      uint8_t byte;                                               \
314
8.67k
      int ret = insn->reader(insn->readerArg,                     \
315
8.67k
                             &byte,                               \
316
8.67k
                             insn->readerCursor + offset);        \
317
8.67k
      if (ret)                                                    \
318
8.67k
        return ret;                                               \
319
8.67k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
8.65k
    }                                                             \
321
1.09k
    *ptr = combined;                                              \
322
1.07k
    insn->readerCursor += sizeof(type);                           \
323
1.07k
    return 0;                                                     \
324
1.09k
  }
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
241k
{
345
241k
  if (insn->mode == MODE_64BIT)
346
93.7k
    return prefix >= 0x40 && prefix <= 0x4f;
347
348
147k
  return false;
349
241k
}
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
50.4k
{
359
50.4k
  uint8_t nextByte;
360
361
50.4k
  switch (prefix) {
362
11.7k
    case 0xf0:  // LOCK
363
11.7k
      insn->hasLockPrefix = true;
364
11.7k
      insn->repeatPrefix = 0;
365
11.7k
      break;
366
367
10.9k
    case 0xf2:  // REPNE/REPNZ
368
20.0k
    case 0xf3:  // REP or REPE/REPZ
369
20.0k
      if (lookAtByte(insn, &nextByte))
370
14
        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
20.0k
      if (isREX(insn, nextByte) || nextByte == 0x0f || nextByte == 0x66)
378
        // The last of 0xf2 /0xf3 is mandatory prefix
379
6.01k
        insn->mandatoryPrefix = prefix;
380
381
20.0k
      insn->repeatPrefix = prefix;
382
20.0k
      insn->hasLockPrefix = false;
383
20.0k
      break;
384
385
6.62k
    case 0x66:
386
6.62k
      if (lookAtByte(insn, &nextByte))
387
16
        break;
388
      // 0x66 can't overwrite existing mandatory prefix and should be ignored
389
6.60k
      if (!insn->mandatoryPrefix && (nextByte == 0x0f || isREX(insn, nextByte)))
390
1.99k
        insn->mandatoryPrefix = prefix;
391
6.60k
      break;
392
50.4k
  }
393
50.4k
}
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
244k
{
406
244k
  bool isPrefix = true;
407
244k
  uint8_t byte = 0;
408
244k
  uint8_t nextByte;
409
410
539k
  while (isPrefix) {
411
295k
    if (insn->mode == MODE_64BIT) {
412
      // eliminate consecutive redundant REX bytes in front
413
115k
      if (consumeByte(insn, &byte))
414
45
        return -1;
415
416
115k
      if ((byte & 0xf0) == 0x40) {
417
16.5k
        while(true) {
418
16.5k
          if (lookAtByte(insn, &byte))  // out of input code
419
41
            return -1;
420
16.4k
          if ((byte & 0xf0) == 0x40) {
421
            // another REX prefix, but we only remember the last one
422
1.60k
            if (consumeByte(insn, &byte))
423
0
              return -1;
424
1.60k
          } else
425
14.8k
            break;
426
16.4k
        }
427
428
        // recover the last REX byte if next byte is not a legacy prefix
429
14.8k
        switch (byte) {
430
488
          case 0xf2:  /* REPNE/REPNZ */
431
762
          case 0xf3:  /* REP or REPE/REPZ */
432
1.06k
          case 0xf0:  /* LOCK */
433
1.20k
          case 0x2e:  /* CS segment override -OR- Branch not taken */
434
1.25k
          case 0x36:  /* SS segment override -OR- Branch taken */
435
1.36k
          case 0x3e:  /* DS segment override */
436
1.37k
          case 0x26:  /* ES segment override */
437
1.39k
          case 0x64:  /* FS segment override */
438
1.42k
          case 0x65:  /* GS segment override */
439
1.63k
          case 0x66:  /* Operand-size override */
440
1.83k
          case 0x67:  /* Address-size override */
441
1.83k
            break;
442
13.0k
          default:    /* Not a prefix byte */
443
13.0k
            unconsumeByte(insn);
444
13.0k
            break;
445
14.8k
        }
446
100k
      } else {
447
100k
        unconsumeByte(insn);
448
100k
      }
449
115k
    }
450
451
    /* If we fail reading prefixes, just stop here and let the opcode reader deal with it */
452
295k
    if (consumeByte(insn, &byte))
453
74
      return -1;
454
455
294k
    if (insn->readerCursor - 1 == insn->startLocation
456
243k
        && (byte == 0xf2 || byte == 0xf3)) {
457
      // prefix requires next byte
458
15.9k
      if (lookAtByte(insn, &nextByte))
459
35
        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
15.9k
      if (((nextByte == 0xf0) ||
469
15.3k
        ((nextByte & 0xfe) == 0x86 || (nextByte & 0xf8) == 0x90))) {
470
1.27k
        insn->xAcquireRelease = byte;
471
1.27k
      }
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
15.9k
      if (byte == 0xf3 && (nextByte == 0x88 || nextByte == 0x89 ||
480
7.05k
            nextByte == 0xc6 || nextByte == 0xc7)) {
481
381
        insn->xAcquireRelease = byte;
482
381
      }
483
484
15.9k
      if (isREX(insn, nextByte)) {
485
1.55k
        uint8_t nnextByte;
486
487
        // Go to REX prefix after the current one
488
1.55k
        if (consumeByte(insn, &nnextByte))
489
0
          return -1;
490
491
        // We should be able to read next byte after REX prefix
492
1.55k
        if (lookAtByte(insn, &nnextByte))
493
1
          return -1;
494
495
1.54k
        unconsumeByte(insn);
496
1.54k
      }
497
15.9k
    }
498
499
294k
    switch (byte) {
500
11.7k
      case 0xf0:  /* LOCK */
501
22.6k
      case 0xf2:  /* REPNE/REPNZ */
502
31.8k
      case 0xf3:  /* REP or REPE/REPZ */
503
        // only accept the last prefix
504
31.8k
        setPrefixPresent(insn, byte);
505
31.8k
        insn->prefix0 = byte;
506
31.8k
        break;
507
508
1.94k
      case 0x2e:  /* CS segment override -OR- Branch not taken */
509
2.59k
      case 0x36:  /* SS segment override -OR- Branch taken */
510
4.35k
      case 0x3e:  /* DS segment override */
511
5.45k
      case 0x26:  /* ES segment override */
512
7.02k
      case 0x64:  /* FS segment override */
513
7.91k
      case 0x65:  /* GS segment override */
514
7.91k
        switch (byte) {
515
1.94k
          case 0x2e:
516
1.94k
            insn->segmentOverride = SEG_OVERRIDE_CS;
517
1.94k
            insn->prefix1 = byte;
518
1.94k
            break;
519
649
          case 0x36:
520
649
            insn->segmentOverride = SEG_OVERRIDE_SS;
521
649
            insn->prefix1 = byte;
522
649
            break;
523
1.75k
          case 0x3e:
524
1.75k
            insn->segmentOverride = SEG_OVERRIDE_DS;
525
1.75k
            insn->prefix1 = byte;
526
1.75k
            break;
527
1.10k
          case 0x26:
528
1.10k
            insn->segmentOverride = SEG_OVERRIDE_ES;
529
1.10k
            insn->prefix1 = byte;
530
1.10k
            break;
531
1.57k
          case 0x64:
532
1.57k
            insn->segmentOverride = SEG_OVERRIDE_FS;
533
1.57k
            insn->prefix1 = byte;
534
1.57k
            break;
535
883
          case 0x65:
536
883
            insn->segmentOverride = SEG_OVERRIDE_GS;
537
883
            insn->prefix1 = byte;
538
883
            break;
539
0
          default:
540
            // debug("Unhandled override");
541
0
            return -1;
542
7.91k
        }
543
7.91k
        setPrefixPresent(insn, byte);
544
7.91k
        break;
545
546
6.62k
      case 0x66:  /* Operand-size override */
547
6.62k
        insn->hasOpSize = true;
548
6.62k
        setPrefixPresent(insn, byte);
549
6.62k
        insn->prefix2 = byte;
550
6.62k
        break;
551
552
4.06k
      case 0x67:  /* Address-size override */
553
4.06k
        insn->hasAdSize = true;
554
4.06k
        setPrefixPresent(insn, byte);
555
4.06k
        insn->prefix3 = byte;
556
4.06k
        break;
557
244k
      default:    /* Not a prefix byte */
558
244k
        isPrefix = false;
559
244k
        break;
560
294k
    }
561
294k
  }
562
563
244k
  insn->vectorExtensionType = TYPE_NO_VEX_XOP;
564
565
244k
  if (byte == 0x62) {
566
32.5k
    uint8_t byte1, byte2;
567
568
32.5k
    if (consumeByte(insn, &byte1)) {
569
      // dbgprintf(insn, "Couldn't read second byte of EVEX prefix");
570
22
      return -1;
571
22
    }
572
573
32.5k
    if (lookAtByte(insn, &byte2)) {
574
      // dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
575
21
      unconsumeByte(insn); /* unconsume byte1 */
576
21
      unconsumeByte(insn); /* unconsume byte  */
577
32.5k
    } else {
578
32.5k
      if ((insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) &&
579
29.6k
          ((~byte1 & 0xc) == 0xc) && ((byte2 & 0x4) == 0x4)) {
580
29.5k
        insn->vectorExtensionType = TYPE_EVEX;
581
29.5k
      } else {
582
2.98k
        unconsumeByte(insn); /* unconsume byte1 */
583
2.98k
        unconsumeByte(insn); /* unconsume byte  */
584
2.98k
      }
585
32.5k
    }
586
587
32.5k
    if (insn->vectorExtensionType == TYPE_EVEX) {
588
29.5k
      insn->vectorExtensionPrefix[0] = byte;
589
29.5k
      insn->vectorExtensionPrefix[1] = byte1;
590
29.5k
      if (consumeByte(insn, &insn->vectorExtensionPrefix[2])) {
591
        // dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
592
0
        return -1;
593
0
      }
594
595
29.5k
      if (consumeByte(insn, &insn->vectorExtensionPrefix[3])) {
596
        // dbgprintf(insn, "Couldn't read fourth byte of EVEX prefix");
597
14
        return -1;
598
14
      }
599
600
      /* We simulate the REX prefix for simplicity's sake */
601
29.5k
      if (insn->mode == MODE_64BIT) {
602
14.1k
        insn->rexPrefix = 0x40
603
14.1k
          | (wFromEVEX3of4(insn->vectorExtensionPrefix[2]) << 3)
604
14.1k
          | (rFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 2)
605
14.1k
          | (xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 1)
606
14.1k
          | (bFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 0);
607
14.1k
      }
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
29.5k
    }
613
211k
  } else if (byte == 0xc4) {
614
3.91k
    uint8_t byte1;
615
616
3.91k
    if (lookAtByte(insn, &byte1)) {
617
      // dbgprintf(insn, "Couldn't read second byte of VEX");
618
2
      return -1;
619
2
    }
620
621
3.90k
    if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)
622
3.73k
      insn->vectorExtensionType = TYPE_VEX_3B;
623
175
    else
624
175
      unconsumeByte(insn);
625
626
3.90k
    if (insn->vectorExtensionType == TYPE_VEX_3B) {
627
3.73k
      insn->vectorExtensionPrefix[0] = byte;
628
3.73k
      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
629
3.73k
      consumeByte(insn, &insn->vectorExtensionPrefix[2]);
630
631
      /* We simulate the REX prefix for simplicity's sake */
632
3.73k
      if (insn->mode == MODE_64BIT)
633
2.95k
        insn->rexPrefix = 0x40
634
2.95k
          | (wFromVEX3of3(insn->vectorExtensionPrefix[2]) << 3)
635
2.95k
          | (rFromVEX2of3(insn->vectorExtensionPrefix[1]) << 2)
636
2.95k
          | (xFromVEX2of3(insn->vectorExtensionPrefix[1]) << 1)
637
2.95k
          | (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
3.73k
    }
643
208k
  } else if (byte == 0xc5) {
644
3.98k
    uint8_t byte1;
645
646
3.98k
    if (lookAtByte(insn, &byte1)) {
647
      // dbgprintf(insn, "Couldn't read second byte of VEX");
648
4
      return -1;
649
4
    }
650
651
3.97k
    if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)
652
3.65k
      insn->vectorExtensionType = TYPE_VEX_2B;
653
326
    else
654
326
      unconsumeByte(insn);
655
656
3.97k
    if (insn->vectorExtensionType == TYPE_VEX_2B) {
657
3.65k
      insn->vectorExtensionPrefix[0] = byte;
658
3.65k
      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
659
660
3.65k
      if (insn->mode == MODE_64BIT)
661
1.05k
        insn->rexPrefix = 0x40
662
1.05k
          | (rFromVEX2of2(insn->vectorExtensionPrefix[1]) << 2);
663
664
3.65k
      switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
665
1.40k
        default:
666
1.40k
          break;
667
2.25k
        case VEX_PREFIX_66:
668
2.25k
          insn->hasOpSize = true;
669
2.25k
          break;
670
3.65k
      }
671
672
      // dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx",
673
      //    insn->vectorExtensionPrefix[0],
674
      //    insn->vectorExtensionPrefix[1]);
675
3.65k
    }
676
204k
  } else if (byte == 0x8f) {
677
2.34k
    uint8_t byte1;
678
679
2.34k
    if (lookAtByte(insn, &byte1)) {
680
      // dbgprintf(insn, "Couldn't read second byte of XOP");
681
4
      return -1;
682
4
    }
683
684
2.34k
    if ((byte1 & 0x38) != 0x0) /* 0 in these 3 bits is a POP instruction. */
685
2.19k
      insn->vectorExtensionType = TYPE_XOP;
686
147
    else
687
147
      unconsumeByte(insn);
688
689
2.34k
    if (insn->vectorExtensionType == TYPE_XOP) {
690
2.19k
      insn->vectorExtensionPrefix[0] = byte;
691
2.19k
      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
692
2.19k
      consumeByte(insn, &insn->vectorExtensionPrefix[2]);
693
694
      /* We simulate the REX prefix for simplicity's sake */
695
2.19k
      if (insn->mode == MODE_64BIT)
696
579
        insn->rexPrefix = 0x40
697
579
          | (wFromXOP3of3(insn->vectorExtensionPrefix[2]) << 3)
698
579
          | (rFromXOP2of3(insn->vectorExtensionPrefix[1]) << 2)
699
579
          | (xFromXOP2of3(insn->vectorExtensionPrefix[1]) << 1)
700
579
          | (bFromXOP2of3(insn->vectorExtensionPrefix[1]) << 0);
701
702
2.19k
      switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
703
2.19k
        default:
704
2.19k
          break;
705
2.19k
        case VEX_PREFIX_66:
706
3
          insn->hasOpSize = true;
707
3
          break;
708
2.19k
      }
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
2.19k
    }
714
201k
  } else if (isREX(insn, byte)) {
715
13.0k
    if (lookAtByte(insn, &nextByte))
716
0
      return -1;
717
718
13.0k
    insn->rexPrefix = byte;
719
    // dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
720
13.0k
  } else
721
188k
    unconsumeByte(insn);
722
723
244k
  if (insn->mode == MODE_16BIT) {
724
74.9k
    insn->registerSize = (insn->hasOpSize ? 4 : 2);
725
74.9k
    insn->addressSize = (insn->hasAdSize ? 4 : 2);
726
74.9k
    insn->displacementSize = (insn->hasAdSize ? 4 : 2);
727
74.9k
    insn->immediateSize = (insn->hasOpSize ? 4 : 2);
728
74.9k
    insn->immSize = (insn->hasOpSize ? 4 : 2);
729
169k
  } else if (insn->mode == MODE_32BIT) {
730
75.8k
    insn->registerSize = (insn->hasOpSize ? 2 : 4);
731
75.8k
    insn->addressSize = (insn->hasAdSize ? 2 : 4);
732
75.8k
    insn->displacementSize = (insn->hasAdSize ? 2 : 4);
733
75.8k
    insn->immediateSize = (insn->hasOpSize ? 2 : 4);
734
75.8k
    insn->immSize = (insn->hasOpSize ? 2 : 4);
735
93.6k
  } else if (insn->mode == MODE_64BIT) {
736
93.6k
    if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
737
17.9k
      insn->registerSize       = 8;
738
17.9k
      insn->addressSize = (insn->hasAdSize ? 4 : 8);
739
17.9k
      insn->displacementSize   = 4;
740
17.9k
      insn->immediateSize      = 4;
741
17.9k
      insn->immSize      = 4;
742
75.7k
    } else {
743
75.7k
      insn->registerSize = (insn->hasOpSize ? 2 : 4);
744
75.7k
      insn->addressSize = (insn->hasAdSize ? 4 : 8);
745
75.7k
      insn->displacementSize = (insn->hasOpSize ? 2 : 4);
746
75.7k
      insn->immediateSize = (insn->hasOpSize ? 2 : 4);
747
75.7k
      insn->immSize      = (insn->hasOpSize ? 4 : 8);
748
75.7k
    }
749
93.6k
  }
750
751
244k
  return 0;
752
244k
}
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
244k
{
765
244k
  uint8_t current;
766
767
  // dbgprintf(insn, "readOpcode()");
768
769
244k
  insn->opcodeType = ONEBYTE;
770
771
244k
  if (insn->vectorExtensionType == TYPE_EVEX) {
772
29.5k
    switch (mmFromEVEX2of4(insn->vectorExtensionPrefix[1])) {
773
2
      default:
774
        // dbgprintf(insn, "Unhandled mm field for instruction (0x%hhx)",
775
        //    mmFromEVEX2of4(insn->vectorExtensionPrefix[1]));
776
2
        return -1;
777
6.08k
      case VEX_LOB_0F:
778
6.08k
        insn->opcodeType = TWOBYTE;
779
6.08k
        return consumeByte(insn, &insn->opcode);
780
9.84k
      case VEX_LOB_0F38:
781
9.84k
        insn->opcodeType = THREEBYTE_38;
782
9.84k
        return consumeByte(insn, &insn->opcode);
783
13.5k
      case VEX_LOB_0F3A:
784
13.5k
        insn->opcodeType = THREEBYTE_3A;
785
13.5k
        return consumeByte(insn, &insn->opcode);
786
29.5k
    }
787
214k
  } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
788
3.73k
    switch (mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])) {
789
15
      default:
790
        // dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
791
        //    mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
792
15
        return -1;
793
398
      case VEX_LOB_0F:
794
        //insn->twoByteEscape = 0x0f;
795
398
        insn->opcodeType = TWOBYTE;
796
398
        return consumeByte(insn, &insn->opcode);
797
2.71k
      case VEX_LOB_0F38:
798
        //insn->twoByteEscape = 0x0f;
799
2.71k
        insn->opcodeType = THREEBYTE_38;
800
2.71k
        return consumeByte(insn, &insn->opcode);
801
611
      case VEX_LOB_0F3A:
802
        //insn->twoByteEscape = 0x0f;
803
611
        insn->opcodeType = THREEBYTE_3A;
804
611
        return consumeByte(insn, &insn->opcode);
805
3.73k
    }
806
211k
  } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
807
    //insn->twoByteEscape = 0x0f;
808
3.65k
    insn->opcodeType = TWOBYTE;
809
3.65k
    return consumeByte(insn, &insn->opcode);
810
207k
  } else if (insn->vectorExtensionType == TYPE_XOP) {
811
2.19k
    switch (mmmmmFromXOP2of3(insn->vectorExtensionPrefix[1])) {
812
7
      default:
813
        // dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
814
        //    mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
815
7
        return -1;
816
2.07k
      case XOP_MAP_SELECT_8:
817
2.07k
        insn->opcodeType = XOP8_MAP;
818
2.07k
        return consumeByte(insn, &insn->opcode);
819
25
      case XOP_MAP_SELECT_9:
820
25
        insn->opcodeType = XOP9_MAP;
821
25
        return consumeByte(insn, &insn->opcode);
822
88
      case XOP_MAP_SELECT_A:
823
88
        insn->opcodeType = XOPA_MAP;
824
88
        return consumeByte(insn, &insn->opcode);
825
2.19k
    }
826
2.19k
  }
827
828
205k
  if (consumeByte(insn, &current))
829
0
    return -1;
830
831
    // save this first byte for MOVcr, MOVdr, MOVrc, MOVrd
832
205k
    insn->firstByte = current;
833
834
205k
  if (current == 0x0f) {
835
    // dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
836
14.9k
    insn->twoByteEscape = current;
837
838
14.9k
    if (consumeByte(insn, &current))
839
20
      return -1;
840
841
14.9k
    if (current == 0x38) {
842
      // dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
843
204
      if (consumeByte(insn, &current))
844
0
        return -1;
845
846
204
      insn->opcodeType = THREEBYTE_38;
847
14.7k
    } else if (current == 0x3a) {
848
      // dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
849
285
      if (consumeByte(insn, &current))
850
1
        return -1;
851
852
284
      insn->opcodeType = THREEBYTE_3A;
853
14.4k
    } 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
348
      if (readModRM(insn))
857
3
        return -1;
858
859
345
      if (consumeByte(insn, &current))
860
1
        return -1;
861
862
344
      insn->opcodeType = THREEDNOW_MAP;
863
14.1k
    } else {
864
      // dbgprintf(insn, "Didn't find a three-byte escape prefix");
865
14.1k
      insn->opcodeType = TWOBYTE;
866
14.1k
    }
867
190k
  } else if (insn->mandatoryPrefix)
868
    // The opcode with mandatory prefix must start with opcode escape.
869
    // If not it's legacy repeat prefix
870
2.28k
    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
205k
  insn->opcode = current;
878
879
205k
  return 0;
880
205k
}
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
331k
{
906
331k
  bool hasModRMExtension;
907
908
331k
  InstructionContext instructionClass = contextForAttrs(attrMask);
909
910
331k
  hasModRMExtension = modRMRequired(insn->opcodeType,
911
331k
      instructionClass,
912
331k
      insn->opcode);
913
914
331k
  if (hasModRMExtension) {
915
188k
    if (readModRM(insn))
916
530
      return -1;
917
918
188k
    *instructionID = decode(insn->opcodeType,
919
188k
        instructionClass,
920
188k
        insn->opcode,
921
188k
        insn->modRM);
922
188k
  } else {
923
142k
    *instructionID = decode(insn->opcodeType,
924
142k
        instructionClass,
925
142k
        insn->opcode,
926
142k
        0);
927
142k
  }
928
929
330k
  return 0;
930
331k
}
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
66.3k
{
941
66.3k
  size_t i;
942
66.3k
  uint16_t idx;
943
944
66.3k
  if ((idx = x86_16_bit_eq_lookup[orig]) != 0) {
945
32.4k
    for (i = idx - 1; i < ARR_SIZE(x86_16_bit_eq_tbl) && x86_16_bit_eq_tbl[i].first == orig; i++) {
946
31.0k
      if (x86_16_bit_eq_tbl[i].second == equiv)
947
29.6k
        return true;
948
31.0k
    }
949
31.0k
  }
950
951
36.6k
  return false;
952
66.3k
}
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
8.17k
{
961
8.17k
  unsigned int i = find_insn(id);
962
8.17k
  if (i != -1) {
963
8.13k
    return insns[i].is64bit;
964
8.13k
  }
965
966
  // not found??
967
40
  return false;
968
8.17k
}
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
244k
{
981
244k
  uint16_t attrMask;
982
244k
  uint16_t instructionID;
983
984
244k
  attrMask = ATTR_NONE;
985
986
244k
  if (insn->mode == MODE_64BIT)
987
93.6k
    attrMask |= ATTR_64BIT;
988
989
244k
  if (insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
990
39.0k
    attrMask |= (insn->vectorExtensionType == TYPE_EVEX) ? ATTR_EVEX : ATTR_VEX;
991
992
39.0k
    if (insn->vectorExtensionType == TYPE_EVEX) {
993
29.5k
      switch (ppFromEVEX3of4(insn->vectorExtensionPrefix[2])) {
994
26.8k
        case VEX_PREFIX_66:
995
26.8k
          attrMask |= ATTR_OPSIZE;
996
26.8k
          break;
997
682
        case VEX_PREFIX_F3:
998
682
          attrMask |= ATTR_XS;
999
682
          break;
1000
425
        case VEX_PREFIX_F2:
1001
425
          attrMask |= ATTR_XD;
1002
425
          break;
1003
29.5k
      }
1004
1005
29.5k
      if (zFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1006
1.86k
        attrMask |= ATTR_EVEXKZ;
1007
29.5k
      if (bFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1008
6.75k
        attrMask |= ATTR_EVEXB;
1009
29.5k
      if (aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1010
20.8k
        attrMask |= ATTR_EVEXK;
1011
29.5k
      if (lFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1012
13.5k
        attrMask |= ATTR_EVEXL;
1013
29.5k
      if (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
1014
12.8k
        attrMask |= ATTR_EVEXL2;
1015
29.5k
    } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
1016
3.71k
      switch (ppFromVEX3of3(insn->vectorExtensionPrefix[2])) {
1017
3.43k
        case VEX_PREFIX_66:
1018
3.43k
          attrMask |= ATTR_OPSIZE;
1019
3.43k
          break;
1020
71
        case VEX_PREFIX_F3:
1021
71
          attrMask |= ATTR_XS;
1022
71
          break;
1023
182
        case VEX_PREFIX_F2:
1024
182
          attrMask |= ATTR_XD;
1025
182
          break;
1026
3.71k
      }
1027
1028
3.71k
      if (lFromVEX3of3(insn->vectorExtensionPrefix[2]))
1029
1.96k
        attrMask |= ATTR_VEXL;
1030
5.83k
    } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
1031
3.64k
      switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
1032
2.25k
        case VEX_PREFIX_66:
1033
2.25k
          attrMask |= ATTR_OPSIZE;
1034
2.25k
          break;
1035
776
        case VEX_PREFIX_F3:
1036
776
          attrMask |= ATTR_XS;
1037
776
          break;
1038
31
        case VEX_PREFIX_F2:
1039
31
          attrMask |= ATTR_XD;
1040
31
          break;
1041
3.64k
      }
1042
1043
3.64k
      if (lFromVEX2of2(insn->vectorExtensionPrefix[1]))
1044
3.18k
        attrMask |= ATTR_VEXL;
1045
3.64k
    } else if (insn->vectorExtensionType == TYPE_XOP) {
1046
2.18k
      switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
1047
1
        case VEX_PREFIX_66:
1048
1
          attrMask |= ATTR_OPSIZE;
1049
1
          break;
1050
4
        case VEX_PREFIX_F3:
1051
4
          attrMask |= ATTR_XS;
1052
4
          break;
1053
4
        case VEX_PREFIX_F2:
1054
4
          attrMask |= ATTR_XD;
1055
4
          break;
1056
2.18k
      }
1057
1058
2.18k
      if (lFromXOP3of3(insn->vectorExtensionPrefix[2]))
1059
205
        attrMask |= ATTR_VEXL;
1060
2.18k
    } else {
1061
0
      return -1;
1062
0
    }
1063
205k
  } else if (!insn->mandatoryPrefix) {
1064
    // If we don't have mandatory prefix we should use legacy prefixes here
1065
200k
    if (insn->hasOpSize && (insn->mode != MODE_16BIT))
1066
2.96k
      attrMask |= ATTR_OPSIZE;
1067
200k
    if (insn->hasAdSize)
1068
3.30k
      attrMask |= ATTR_ADSIZE;
1069
200k
    if (insn->opcodeType == ONEBYTE) {
1070
190k
      if (insn->repeatPrefix == 0xf3 && (insn->opcode == 0x90))
1071
        // Special support for PAUSE
1072
18
        attrMask |= ATTR_XS;
1073
190k
    } else {
1074
9.62k
      if (insn->repeatPrefix == 0xf2)
1075
309
        attrMask |= ATTR_XD;
1076
9.31k
      else if (insn->repeatPrefix == 0xf3)
1077
161
        attrMask |= ATTR_XS;
1078
9.62k
    }
1079
200k
  } else {
1080
5.33k
    switch (insn->mandatoryPrefix) {
1081
2.32k
      case 0xf2:
1082
2.32k
        attrMask |= ATTR_XD;
1083
2.32k
        break;
1084
1.31k
      case 0xf3:
1085
1.31k
        attrMask |= ATTR_XS;
1086
1.31k
        break;
1087
1.69k
      case 0x66:
1088
1.69k
        if (insn->mode != MODE_16BIT)
1089
1.58k
          attrMask |= ATTR_OPSIZE;
1090
1.69k
        break;
1091
0
      case 0x67:
1092
0
        attrMask |= ATTR_ADSIZE;
1093
0
        break;
1094
5.33k
    }
1095
1096
5.33k
  }
1097
1098
244k
  if (insn->rexPrefix & 0x08) {
1099
17.9k
    attrMask |= ATTR_REXW;
1100
17.9k
    attrMask &= ~ATTR_ADSIZE;
1101
17.9k
  }
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
244k
  if (insn->mode == MODE_16BIT && insn->opcodeType == ONEBYTE &&
1108
59.7k
      insn->opcode == 0xE3)
1109
358
    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
244k
  if ((insn->mode == MODE_64BIT) && insn->hasOpSize) {
1116
2.71k
    switch (insn->opcode) {
1117
86
      case 0xE8:
1118
94
      case 0xE9:
1119
        // Take care of psubsb and other mmx instructions.
1120
94
        if (insn->opcodeType == ONEBYTE) {
1121
29
          attrMask ^= ATTR_OPSIZE;
1122
29
          insn->immediateSize = 4;
1123
29
          insn->displacementSize = 4;
1124
29
        }
1125
94
        break;
1126
123
      case 0x82:
1127
141
      case 0x83:
1128
145
      case 0x84:
1129
172
      case 0x85:
1130
400
      case 0x86:
1131
507
      case 0x87:
1132
536
      case 0x88:
1133
580
      case 0x89:
1134
597
      case 0x8A:
1135
620
      case 0x8B:
1136
671
      case 0x8C:
1137
678
      case 0x8D:
1138
734
      case 0x8E:
1139
736
      case 0x8F:
1140
        // Take care of lea and three byte ops.
1141
736
        if (insn->opcodeType == TWOBYTE) {
1142
131
          attrMask ^= ATTR_OPSIZE;
1143
131
          insn->immediateSize = 4;
1144
131
          insn->displacementSize = 4;
1145
131
        }
1146
736
        break;
1147
2.71k
    }
1148
2.71k
  }
1149
1150
  /* The following clauses compensate for limitations of the tables. */
1151
244k
  if (insn->mode != MODE_64BIT &&
1152
150k
      insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
1153
20.3k
    if (getIDWithAttrMask(&instructionID, insn, attrMask)) {
1154
23
      return -1;
1155
23
    }
1156
1157
    /*
1158
     * The tables can't distinquish between cases where the W-bit is used to
1159
     * select register size and cases where its a required part of the opcode.
1160
     */
1161
20.2k
    if ((insn->vectorExtensionType == TYPE_EVEX &&
1162
15.3k
          wFromEVEX3of4(insn->vectorExtensionPrefix[2])) ||
1163
12.5k
        (insn->vectorExtensionType == TYPE_VEX_3B &&
1164
769
         wFromVEX3of3(insn->vectorExtensionPrefix[2])) ||
1165
12.2k
        (insn->vectorExtensionType == TYPE_XOP &&
1166
8.17k
         wFromXOP3of3(insn->vectorExtensionPrefix[2]))) {
1167
8.17k
      uint16_t instructionIDWithREXW;
1168
1169
8.17k
      if (getIDWithAttrMask(&instructionIDWithREXW,
1170
8.17k
            insn, attrMask | ATTR_REXW)) {
1171
0
        insn->instructionID = instructionID;
1172
0
        insn->spec = specifierForUID(instructionID);
1173
0
        return 0;
1174
0
      }
1175
1176
      // If not a 64-bit instruction. Switch the opcode.
1177
8.17k
      if (!is64Bit(instructionIDWithREXW)) {
1178
7.87k
        insn->instructionID = instructionIDWithREXW;
1179
7.87k
        insn->spec = specifierForUID(instructionIDWithREXW);
1180
1181
7.87k
        return 0;
1182
7.87k
      }
1183
8.17k
    }
1184
20.2k
  }
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
236k
  if ((insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0)) ||
1194
233k
      (insn->opcodeType == TWOBYTE && (insn->opcode == 0xAE)) ||
1195
233k
      (insn->opcodeType == THREEBYTE_38 && insn->opcode == 0xF8)) {
1196
    /* Make sure we observed the prefixes in any position. */
1197
3.19k
    if (insn->hasAdSize)
1198
113
      attrMask |= ATTR_ADSIZE;
1199
1200
3.19k
    if (insn->hasOpSize)
1201
61
      attrMask |= ATTR_OPSIZE;
1202
1203
    /* In 16-bit, invert the attributes. */
1204
3.19k
    if (insn->mode == MODE_16BIT) {
1205
904
      attrMask ^= ATTR_ADSIZE;
1206
1207
      /* The OpSize attribute is only valid with the absolute moves. */
1208
904
      if (insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0))
1209
730
        attrMask ^= ATTR_OPSIZE;
1210
904
    }
1211
1212
3.19k
    if (getIDWithAttrMask(&instructionID, insn, attrMask)) {
1213
2
      return -1;
1214
2
    }
1215
1216
3.18k
    insn->instructionID = instructionID;
1217
3.18k
    insn->spec = specifierForUID(instructionID);
1218
1219
3.18k
    return 0;
1220
3.19k
  }
1221
233k
  if (getIDWithAttrMask(&instructionID, insn, attrMask)) {
1222
503
    return -1;
1223
503
  }
1224
1225
232k
  if ((insn->mode == MODE_16BIT || insn->hasOpSize) &&
1226
76.3k
      !(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
66.3k
    const struct InstructionSpecifier *spec;
1235
66.3k
    uint16_t instructionIDWithOpsize;
1236
1237
66.3k
    spec = specifierForUID(instructionID);
1238
1239
66.3k
    if (getIDWithAttrMask(&instructionIDWithOpsize,
1240
66.3k
          insn,
1241
66.3k
          attrMask | ATTR_OPSIZE)) {
1242
      /*
1243
       * ModRM required with OpSize but not present; give up and return version
1244
       * without OpSize set
1245
       */
1246
2
      insn->instructionID = instructionID;
1247
2
      insn->spec = spec;
1248
1249
2
      return 0;
1250
2
    }
1251
1252
66.3k
    if (is16BitEquivalent(instructionID, instructionIDWithOpsize) &&
1253
29.6k
        (insn->mode == MODE_16BIT) ^ insn->hasOpSize) {
1254
29.0k
      insn->instructionID = instructionIDWithOpsize;
1255
29.0k
      insn->spec = specifierForUID(instructionIDWithOpsize);
1256
37.2k
    } else {
1257
37.2k
      insn->instructionID = instructionID;
1258
37.2k
      insn->spec = spec;
1259
37.2k
    }
1260
1261
66.3k
    return 0;
1262
66.3k
  }
1263
1264
166k
  if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
1265
223
      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
158
    const struct InstructionSpecifier *spec;
1271
158
    uint16_t instructionIDWithNewOpcode;
1272
158
    const struct InstructionSpecifier *specWithNewOpcode;
1273
1274
158
    spec = specifierForUID(instructionID);
1275
1276
    /* Borrow opcode from one of the other XCHGar opcodes */
1277
158
    insn->opcode = 0x91;
1278
1279
158
    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
158
    specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
1289
1290
    /* Change back */
1291
158
    insn->opcode = 0x90;
1292
1293
158
    insn->instructionID = instructionIDWithNewOpcode;
1294
158
    insn->spec = specWithNewOpcode;
1295
1296
158
    return 0;
1297
158
  }
1298
1299
166k
  insn->instructionID = instructionID;
1300
166k
  insn->spec = specifierForUID(insn->instructionID);
1301
1302
166k
  return 0;
1303
166k
}
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
14.8k
{
1314
14.8k
  SIBBase sibBaseBase = SIB_BASE_NONE;
1315
14.8k
  uint8_t index, base;
1316
1317
  // dbgprintf(insn, "readSIB()");
1318
1319
14.8k
  if (insn->consumedSIB)
1320
0
    return 0;
1321
1322
14.8k
  insn->consumedSIB = true;
1323
1324
14.8k
  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
5.41k
    case 4:
1329
5.41k
      insn->sibIndexBase = SIB_INDEX_EAX;
1330
5.41k
      sibBaseBase = SIB_BASE_EAX;
1331
5.41k
      break;
1332
9.47k
    case 8:
1333
9.47k
      insn->sibIndexBase = SIB_INDEX_RAX;
1334
9.47k
      sibBaseBase = SIB_BASE_RAX;
1335
9.47k
      break;
1336
14.8k
  }
1337
1338
14.8k
  if (consumeByte(insn, &insn->sib))
1339
20
    return -1;
1340
1341
14.8k
  index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
1342
1343
14.8k
  if (index == 0x4) {
1344
1.36k
    insn->sibIndex = SIB_INDEX_NONE;
1345
13.5k
  } else {
1346
13.5k
    insn->sibIndex = (SIBIndex)(insn->sibIndexBase + index);
1347
13.5k
  }
1348
1349
14.8k
  insn->sibScale = 1 << scaleFromSIB(insn->sib);
1350
1351
14.8k
  base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
1352
1353
14.8k
  switch (base) {
1354
993
    case 0x5:
1355
1.34k
    case 0xd:
1356
1.34k
      switch (modFromModRM(insn->modRM)) {
1357
373
        case 0x0:
1358
373
          insn->eaDisplacement = EA_DISP_32;
1359
373
          insn->sibBase = SIB_BASE_NONE;
1360
373
          break;
1361
764
        case 0x1:
1362
764
          insn->eaDisplacement = EA_DISP_8;
1363
764
          insn->sibBase = (SIBBase)(sibBaseBase + base);
1364
764
          break;
1365
210
        case 0x2:
1366
210
          insn->eaDisplacement = EA_DISP_32;
1367
210
          insn->sibBase = (SIBBase)(sibBaseBase + base);
1368
210
          break;
1369
0
        case 0x3:
1370
          // debug("Cannot have Mod = 0b11 and a SIB byte");
1371
0
          return -1;
1372
1.34k
      }
1373
1.34k
      break;
1374
13.5k
    default:
1375
13.5k
      insn->sibBase = (SIBBase)(sibBaseBase + base);
1376
13.5k
      break;
1377
14.8k
  }
1378
1379
14.8k
  return 0;
1380
14.8k
}
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
52.2k
{
1391
52.2k
  int8_t d8;
1392
52.2k
  int16_t d16;
1393
52.2k
  int32_t d32;
1394
1395
  // dbgprintf(insn, "readDisplacement()");
1396
1397
52.2k
  if (insn->consumedDisplacement)
1398
0
    return 0;
1399
1400
52.2k
  insn->consumedDisplacement = true;
1401
52.2k
  insn->displacementOffset = insn->readerCursor - insn->startLocation;
1402
1403
52.2k
  switch (insn->eaDisplacement) {
1404
20.3k
    case EA_DISP_NONE:
1405
20.3k
      insn->consumedDisplacement = false;
1406
20.3k
      break;
1407
22.3k
    case EA_DISP_8:
1408
22.3k
      if (consumeInt8(insn, &d8))
1409
43
        return -1;
1410
22.2k
      insn->displacement = d8;
1411
22.2k
      break;
1412
3.43k
    case EA_DISP_16:
1413
3.43k
      if (consumeInt16(insn, &d16))
1414
17
        return -1;
1415
3.42k
      insn->displacement = d16;
1416
3.42k
      break;
1417
6.14k
    case EA_DISP_32:
1418
6.14k
      if (consumeInt32(insn, &d32))
1419
64
        return -1;
1420
6.07k
      insn->displacement = d32;
1421
6.07k
      break;
1422
52.2k
  }
1423
1424
1425
52.1k
  return 0;
1426
52.2k
}
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
438k
{
1437
438k
  uint8_t mod, rm, reg, evexrm;
1438
1439
  // dbgprintf(insn, "readModRM()");
1440
1441
438k
  if (insn->consumedModRM)
1442
298k
    return 0;
1443
1444
139k
  insn->modRMOffset = (uint8_t)(insn->readerCursor - insn->startLocation);
1445
1446
139k
  if (consumeByte(insn, &insn->modRM))
1447
389
    return -1;
1448
1449
139k
  insn->consumedModRM = true;
1450
1451
  // save original ModRM for later reference
1452
139k
  insn->orgModRM = insn->modRM;
1453
1454
  // handle MOVcr, MOVdr, MOVrc, MOVrd by pretending they have MRM.mod = 3
1455
139k
  if ((insn->firstByte == 0x0f && insn->opcodeType == TWOBYTE) &&
1456
13.7k
      (insn->opcode >= 0x20 && insn->opcode <= 0x23 ))
1457
355
    insn->modRM |= 0xC0;
1458
1459
139k
  mod = modFromModRM(insn->modRM);
1460
139k
  rm  = rmFromModRM(insn->modRM);
1461
139k
  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
139k
  switch (insn->registerSize) {
1469
45.4k
    case 2:
1470
45.4k
      insn->regBase = MODRM_REG_AX;
1471
45.4k
      insn->eaRegBase = EA_REG_AX;
1472
45.4k
      break;
1473
78.9k
    case 4:
1474
78.9k
      insn->regBase = MODRM_REG_EAX;
1475
78.9k
      insn->eaRegBase = EA_REG_EAX;
1476
78.9k
      break;
1477
15.1k
    case 8:
1478
15.1k
      insn->regBase = MODRM_REG_RAX;
1479
15.1k
      insn->eaRegBase = EA_REG_RAX;
1480
15.1k
      break;
1481
139k
  }
1482
1483
139k
  reg |= rFromREX(insn->rexPrefix) << 3;
1484
139k
  rm  |= bFromREX(insn->rexPrefix) << 3;
1485
1486
139k
  evexrm = 0;
1487
139k
  if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT) {
1488
14.1k
    reg |= r2FromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1489
14.1k
    evexrm = xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1490
14.1k
  }
1491
1492
139k
  insn->reg = (Reg)(insn->regBase + reg);
1493
1494
139k
  switch (insn->addressSize) {
1495
41.8k
    case 2: {
1496
41.8k
      EABase eaBaseBase = EA_BASE_BX_SI;
1497
1498
41.8k
      switch (mod) {
1499
23.7k
        case 0x0:
1500
23.7k
          if (rm == 0x6) {
1501
1.07k
            insn->eaBase = EA_BASE_NONE;
1502
1.07k
            insn->eaDisplacement = EA_DISP_16;
1503
1.07k
            if (readDisplacement(insn))
1504
4
              return -1;
1505
22.6k
          } else {
1506
22.6k
            insn->eaBase = (EABase)(eaBaseBase + rm);
1507
22.6k
            insn->eaDisplacement = EA_DISP_NONE;
1508
22.6k
          }
1509
23.7k
          break;
1510
23.7k
        case 0x1:
1511
6.48k
          insn->eaBase = (EABase)(eaBaseBase + rm);
1512
6.48k
          insn->eaDisplacement = EA_DISP_8;
1513
6.48k
          insn->displacementSize = 1;
1514
6.48k
          if (readDisplacement(insn))
1515
12
            return -1;
1516
6.47k
          break;
1517
6.47k
        case 0x2:
1518
2.36k
          insn->eaBase = (EABase)(eaBaseBase + rm);
1519
2.36k
          insn->eaDisplacement = EA_DISP_16;
1520
2.36k
          if (readDisplacement(insn))
1521
13
            return -1;
1522
2.35k
          break;
1523
9.30k
        case 0x3:
1524
9.30k
          insn->eaBase = (EABase)(insn->eaRegBase + rm);
1525
9.30k
          if (readDisplacement(insn))
1526
0
            return -1;
1527
9.30k
          break;
1528
41.8k
      }
1529
41.8k
      break;
1530
41.8k
    }
1531
1532
44.8k
    case 4:
1533
97.6k
    case 8: {
1534
97.6k
      EABase eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1535
1536
97.6k
      switch (mod) {
1537
0
        default: break;
1538
51.5k
        case 0x0:
1539
51.5k
          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
51.5k
          switch (rm & 7) {
1544
11.4k
            case 0x4: // SIB byte is present
1545
11.4k
              insn->eaBase = (insn->addressSize == 4 ?
1546
7.90k
                  EA_BASE_sib : EA_BASE_sib64);
1547
11.4k
              if (readSIB(insn) || readDisplacement(insn))
1548
9
                return -1;
1549
11.4k
              break;
1550
11.4k
            case 0x5: // RIP-relative
1551
903
              insn->eaBase = EA_BASE_NONE;
1552
903
              insn->eaDisplacement = EA_DISP_32;
1553
903
              if (readDisplacement(insn))
1554
14
                return -1;
1555
889
              break;
1556
39.2k
            default:
1557
39.2k
              insn->eaBase = (EABase)(eaBaseBase + rm);
1558
39.2k
              break;
1559
51.5k
          }
1560
51.5k
          break;
1561
51.5k
        case 0x1:
1562
15.8k
          insn->displacementSize = 1;
1563
          /* FALLTHROUGH */
1564
20.7k
        case 0x2:
1565
20.7k
          insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1566
20.7k
          switch (rm & 7) {
1567
3.47k
            case 0x4: // SIB byte is present
1568
3.47k
              insn->eaBase = EA_BASE_sib;
1569
3.47k
              if (readSIB(insn) || readDisplacement(insn))
1570
16
                return -1;
1571
3.46k
              break;
1572
17.2k
            default:
1573
17.2k
              insn->eaBase = (EABase)(eaBaseBase + rm);
1574
17.2k
              if (readDisplacement(insn))
1575
76
                return -1;
1576
17.1k
              break;
1577
20.7k
          }
1578
20.6k
          break;
1579
25.3k
        case 0x3:
1580
25.3k
          insn->eaDisplacement = EA_DISP_NONE;
1581
25.3k
          insn->eaBase = (EABase)(insn->eaRegBase + rm + evexrm);
1582
25.3k
          break;
1583
97.6k
      }
1584
1585
97.5k
      break;
1586
97.6k
    }
1587
139k
  } /* switch (insn->addressSize) */
1588
1589
139k
  return 0;
1590
139k
}
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
173k
                       uint8_t *valid) {                  \
1597
173k
    *valid = 1;                                           \
1598
173k
    switch (type) {                                       \
1599
0
    default:                                              \
1600
0
      *valid = 0;                                         \
1601
0
      return 0;                                           \
1602
29.3k
    case TYPE_Rv:                                         \
1603
29.3k
      return base + index;                                \
1604
44.2k
    case TYPE_R8:                                         \
1605
44.2k
      index &= mask;                                      \
1606
44.2k
      if (index > 0xf)                                    \
1607
44.2k
        *valid = 0;                                       \
1608
44.2k
      if (insn->rexPrefix &&                              \
1609
44.2k
         index >= 4 && index <= 7) {                      \
1610
1.14k
        return prefix##_SPL + (index - 4);                \
1611
43.1k
      } else {                                            \
1612
43.1k
        return prefix##_AL + index;                       \
1613
43.1k
      }                                                   \
1614
44.2k
    case TYPE_R16:                                        \
1615
1.86k
      index &= mask;                                      \
1616
1.86k
      if (index > 0xf)                                    \
1617
1.86k
        *valid = 0;                                       \
1618
1.86k
      return prefix##_AX + index;                         \
1619
44.2k
    case TYPE_R32:                                        \
1620
531
      index &= mask;                                      \
1621
531
      if (index > 0xf)                                    \
1622
531
        *valid = 0;                                       \
1623
531
      return prefix##_EAX + index;                        \
1624
44.2k
    case TYPE_R64:                                        \
1625
3.96k
      index &= mask;                                      \
1626
3.96k
      if (index > 0xf)                                    \
1627
3.96k
        *valid = 0;                                       \
1628
3.96k
      return prefix##_RAX + index;                        \
1629
44.2k
    case TYPE_ZMM:                                        \
1630
17.0k
      return prefix##_ZMM0 + index;                       \
1631
44.2k
    case TYPE_YMM:                                        \
1632
18.6k
      return prefix##_YMM0 + index;                       \
1633
44.2k
    case TYPE_XMM:                                        \
1634
35.3k
      return prefix##_XMM0 + index;                       \
1635
44.2k
    case TYPE_VK:                                         \
1636
16.5k
      index &= 0xf;                                       \
1637
16.5k
      if (index > 7)                                      \
1638
16.5k
        *valid = 0;                                       \
1639
16.5k
      return prefix##_K0 + index;                         \
1640
44.2k
    case TYPE_MM64:                                       \
1641
2.35k
      return prefix##_MM0 + (index & 0x7);                \
1642
44.2k
    case TYPE_SEGMENTREG:                                 \
1643
470
      if ((index & 7) > 5)                                \
1644
470
        *valid = 0;                                       \
1645
470
      return prefix##_ES + (index & 7);                   \
1646
44.2k
    case TYPE_DEBUGREG:                                   \
1647
19
      return prefix##_DR0 + index;                        \
1648
44.2k
    case TYPE_CONTROLREG:                                 \
1649
336
      return prefix##_CR0 + index;                        \
1650
44.2k
    case TYPE_BNDR:                                       \
1651
2.38k
      if (index > 3)                                      \
1652
2.38k
        *valid = 0;                                       \
1653
2.38k
      return prefix##_BND0 + index;                       \
1654
44.2k
    case TYPE_MVSIBX:                                     \
1655
0
      return prefix##_XMM0 + index;                       \
1656
44.2k
    case TYPE_MVSIBY:                                     \
1657
0
      return prefix##_YMM0 + index;                       \
1658
44.2k
    case TYPE_MVSIBZ:                                     \
1659
0
      return prefix##_ZMM0 + index;                       \
1660
173k
    }                                                     \
1661
173k
  }
X86DisassemblerDecoder.c:fixupRegValue
Line
Count
Source
1596
139k
                       uint8_t *valid) {                  \
1597
139k
    *valid = 1;                                           \
1598
139k
    switch (type) {                                       \
1599
0
    default:                                              \
1600
0
      *valid = 0;                                         \
1601
0
      return 0;                                           \
1602
22.6k
    case TYPE_Rv:                                         \
1603
22.6k
      return base + index;                                \
1604
35.0k
    case TYPE_R8:                                         \
1605
35.0k
      index &= mask;                                      \
1606
35.0k
      if (index > 0xf)                                    \
1607
35.0k
        *valid = 0;                                       \
1608
35.0k
      if (insn->rexPrefix &&                              \
1609
35.0k
         index >= 4 && index <= 7) {                      \
1610
591
        return prefix##_SPL + (index - 4);                \
1611
34.4k
      } else {                                            \
1612
34.4k
        return prefix##_AL + index;                       \
1613
34.4k
      }                                                   \
1614
35.0k
    case TYPE_R16:                                        \
1615
1.64k
      index &= mask;                                      \
1616
1.64k
      if (index > 0xf)                                    \
1617
1.64k
        *valid = 0;                                       \
1618
1.64k
      return prefix##_AX + index;                         \
1619
35.0k
    case TYPE_R32:                                        \
1620
232
      index &= mask;                                      \
1621
232
      if (index > 0xf)                                    \
1622
232
        *valid = 0;                                       \
1623
232
      return prefix##_EAX + index;                        \
1624
35.0k
    case TYPE_R64:                                        \
1625
2.93k
      index &= mask;                                      \
1626
2.93k
      if (index > 0xf)                                    \
1627
2.93k
        *valid = 0;                                       \
1628
2.93k
      return prefix##_RAX + index;                        \
1629
35.0k
    case TYPE_ZMM:                                        \
1630
13.8k
      return prefix##_ZMM0 + index;                       \
1631
35.0k
    case TYPE_YMM:                                        \
1632
14.9k
      return prefix##_YMM0 + index;                       \
1633
35.0k
    case TYPE_XMM:                                        \
1634
28.1k
      return prefix##_XMM0 + index;                       \
1635
35.0k
    case TYPE_VK:                                         \
1636
15.8k
      index &= 0xf;                                       \
1637
15.8k
      if (index > 7)                                      \
1638
15.8k
        *valid = 0;                                       \
1639
15.8k
      return prefix##_K0 + index;                         \
1640
35.0k
    case TYPE_MM64:                                       \
1641
1.27k
      return prefix##_MM0 + (index & 0x7);                \
1642
35.0k
    case TYPE_SEGMENTREG:                                 \
1643
470
      if ((index & 7) > 5)                                \
1644
470
        *valid = 0;                                       \
1645
470
      return prefix##_ES + (index & 7);                   \
1646
35.0k
    case TYPE_DEBUGREG:                                   \
1647
19
      return prefix##_DR0 + index;                        \
1648
35.0k
    case TYPE_CONTROLREG:                                 \
1649
336
      return prefix##_CR0 + index;                        \
1650
35.0k
    case TYPE_BNDR:                                       \
1651
2.18k
      if (index > 3)                                      \
1652
2.18k
        *valid = 0;                                       \
1653
2.18k
      return prefix##_BND0 + index;                       \
1654
35.0k
    case TYPE_MVSIBX:                                     \
1655
0
      return prefix##_XMM0 + index;                       \
1656
35.0k
    case TYPE_MVSIBY:                                     \
1657
0
      return prefix##_YMM0 + index;                       \
1658
35.0k
    case TYPE_MVSIBZ:                                     \
1659
0
      return prefix##_ZMM0 + index;                       \
1660
139k
    }                                                     \
1661
139k
  }
X86DisassemblerDecoder.c:fixupRMValue
Line
Count
Source
1596
33.7k
                       uint8_t *valid) {                  \
1597
33.7k
    *valid = 1;                                           \
1598
33.7k
    switch (type) {                                       \
1599
0
    default:                                              \
1600
0
      *valid = 0;                                         \
1601
0
      return 0;                                           \
1602
6.75k
    case TYPE_Rv:                                         \
1603
6.75k
      return base + index;                                \
1604
9.24k
    case TYPE_R8:                                         \
1605
9.24k
      index &= mask;                                      \
1606
9.24k
      if (index > 0xf)                                    \
1607
9.24k
        *valid = 0;                                       \
1608
9.24k
      if (insn->rexPrefix &&                              \
1609
9.24k
         index >= 4 && index <= 7) {                      \
1610
554
        return prefix##_SPL + (index - 4);                \
1611
8.68k
      } else {                                            \
1612
8.68k
        return prefix##_AL + index;                       \
1613
8.68k
      }                                                   \
1614
9.24k
    case TYPE_R16:                                        \
1615
222
      index &= mask;                                      \
1616
222
      if (index > 0xf)                                    \
1617
222
        *valid = 0;                                       \
1618
222
      return prefix##_AX + index;                         \
1619
9.24k
    case TYPE_R32:                                        \
1620
299
      index &= mask;                                      \
1621
299
      if (index > 0xf)                                    \
1622
299
        *valid = 0;                                       \
1623
299
      return prefix##_EAX + index;                        \
1624
9.24k
    case TYPE_R64:                                        \
1625
1.03k
      index &= mask;                                      \
1626
1.03k
      if (index > 0xf)                                    \
1627
1.03k
        *valid = 0;                                       \
1628
1.03k
      return prefix##_RAX + index;                        \
1629
9.24k
    case TYPE_ZMM:                                        \
1630
3.23k
      return prefix##_ZMM0 + index;                       \
1631
9.24k
    case TYPE_YMM:                                        \
1632
3.67k
      return prefix##_YMM0 + index;                       \
1633
9.24k
    case TYPE_XMM:                                        \
1634
7.23k
      return prefix##_XMM0 + index;                       \
1635
9.24k
    case TYPE_VK:                                         \
1636
762
      index &= 0xf;                                       \
1637
762
      if (index > 7)                                      \
1638
762
        *valid = 0;                                       \
1639
762
      return prefix##_K0 + index;                         \
1640
9.24k
    case TYPE_MM64:                                       \
1641
1.07k
      return prefix##_MM0 + (index & 0x7);                \
1642
9.24k
    case TYPE_SEGMENTREG:                                 \
1643
0
      if ((index & 7) > 5)                                \
1644
0
        *valid = 0;                                       \
1645
0
      return prefix##_ES + (index & 7);                   \
1646
9.24k
    case TYPE_DEBUGREG:                                   \
1647
0
      return prefix##_DR0 + index;                        \
1648
9.24k
    case TYPE_CONTROLREG:                                 \
1649
0
      return prefix##_CR0 + index;                        \
1650
9.24k
    case TYPE_BNDR:                                       \
1651
203
      if (index > 3)                                      \
1652
203
        *valid = 0;                                       \
1653
203
      return prefix##_BND0 + index;                       \
1654
9.24k
    case TYPE_MVSIBX:                                     \
1655
0
      return prefix##_XMM0 + index;                       \
1656
9.24k
    case TYPE_MVSIBY:                                     \
1657
0
      return prefix##_YMM0 + index;                       \
1658
9.24k
    case TYPE_MVSIBZ:                                     \
1659
0
      return prefix##_ZMM0 + index;                       \
1660
33.7k
    }                                                     \
1661
33.7k
  }
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
270k
{
1691
270k
  uint8_t valid;
1692
1693
270k
  switch ((OperandEncoding)op->encoding) {
1694
0
    default:
1695
      // debug("Expected a REG or R/M encoding in fixupReg");
1696
0
      return -1;
1697
28.2k
    case ENCODING_VVVV:
1698
28.2k
      insn->vvvv = (Reg)fixupRegValue(insn,
1699
28.2k
          (OperandType)op->type,
1700
28.2k
          insn->vvvv,
1701
28.2k
          &valid);
1702
28.2k
      if (!valid)
1703
1
        return -1;
1704
28.2k
      break;
1705
111k
    case ENCODING_REG:
1706
111k
      insn->reg = (Reg)fixupRegValue(insn,
1707
111k
          (OperandType)op->type,
1708
111k
          insn->reg - insn->regBase,
1709
111k
          &valid);
1710
111k
      if (!valid)
1711
12
        return -1;
1712
111k
      break;
1713
820k
    CASE_ENCODING_RM:
1714
820k
      if (insn->eaBase >= insn->eaRegBase) {
1715
33.7k
        insn->eaBase = (EABase)fixupRMValue(insn,
1716
33.7k
            (OperandType)op->type,
1717
33.7k
            insn->eaBase - insn->eaRegBase,
1718
33.7k
            &valid);
1719
33.7k
        if (!valid)
1720
1
          return -1;
1721
33.7k
      }
1722
130k
      break;
1723
270k
  }
1724
1725
270k
  return 0;
1726
270k
}
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
20.5k
{
1741
20.5k
  if (size == 0)
1742
15.1k
    size = insn->registerSize;
1743
1744
20.5k
  switch (size) {
1745
1.74k
    case 1:
1746
1.74k
      insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
1747
1.74k
            | (insn->opcode & 7)));
1748
1.74k
      if (insn->rexPrefix &&
1749
116
          insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1750
62
          insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1751
11
        insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1752
11
            + (insn->opcodeRegister - MODRM_REG_AL - 4));
1753
11
      }
1754
1755
1.74k
      break;
1756
6.46k
    case 2:
1757
6.46k
      insn->opcodeRegister = (Reg)(MODRM_REG_AX
1758
6.46k
          + ((bFromREX(insn->rexPrefix) << 3)
1759
6.46k
            | (insn->opcode & 7)));
1760
6.46k
      break;
1761
8.67k
    case 4:
1762
8.67k
      insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1763
8.67k
          + ((bFromREX(insn->rexPrefix) << 3)
1764
8.67k
            | (insn->opcode & 7)));
1765
8.67k
      break;
1766
3.70k
    case 8:
1767
3.70k
      insn->opcodeRegister = (Reg)(MODRM_REG_RAX
1768
3.70k
          + ((bFromREX(insn->rexPrefix) << 3)
1769
3.70k
            | (insn->opcode & 7)));
1770
3.70k
      break;
1771
20.5k
  }
1772
1773
20.5k
  return 0;
1774
20.5k
}
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
78.4k
{
1787
78.4k
  uint8_t imm8;
1788
78.4k
  uint16_t imm16;
1789
78.4k
  uint32_t imm32;
1790
78.4k
  uint64_t imm64;
1791
1792
78.4k
  if (insn->numImmediatesConsumed == 2) {
1793
    // debug("Already consumed two immediates");
1794
0
    return -1;
1795
0
  }
1796
1797
78.4k
  if (size == 0)
1798
0
    size = insn->immediateSize;
1799
78.4k
  else
1800
78.4k
    insn->immediateSize = size;
1801
1802
78.4k
  insn->immediateOffset = insn->readerCursor - insn->startLocation;
1803
1804
78.4k
  switch (size) {
1805
60.9k
    case 1:
1806
60.9k
      if (consumeByte(insn, &imm8))
1807
188
        return -1;
1808
1809
60.7k
      insn->immediates[insn->numImmediatesConsumed] = imm8;
1810
60.7k
      break;
1811
8.88k
    case 2:
1812
8.88k
      if (consumeUInt16(insn, &imm16))
1813
67
        return -1;
1814
1815
8.82k
      insn->immediates[insn->numImmediatesConsumed] = imm16;
1816
8.82k
      break;
1817
7.53k
    case 4:
1818
7.53k
      if (consumeUInt32(insn, &imm32))
1819
95
        return -1;
1820
1821
7.43k
      insn->immediates[insn->numImmediatesConsumed] = imm32;
1822
7.43k
      break;
1823
1.09k
    case 8:
1824
1.09k
      if (consumeUInt64(insn, &imm64))
1825
21
        return -1;
1826
1.07k
      insn->immediates[insn->numImmediatesConsumed] = imm64;
1827
1.07k
      break;
1828
78.4k
  }
1829
1830
78.1k
  insn->numImmediatesConsumed++;
1831
1832
78.1k
  return 0;
1833
78.4k
}
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
243k
{
1844
243k
  int vvvv;
1845
1846
243k
  if (insn->vectorExtensionType == TYPE_EVEX)
1847
29.3k
    vvvv = (v2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 4 |
1848
29.3k
        vvvvFromEVEX3of4(insn->vectorExtensionPrefix[2]));
1849
214k
  else if (insn->vectorExtensionType == TYPE_VEX_3B)
1850
3.69k
    vvvv = vvvvFromVEX3of3(insn->vectorExtensionPrefix[2]);
1851
210k
  else if (insn->vectorExtensionType == TYPE_VEX_2B)
1852
3.63k
    vvvv = vvvvFromVEX2of2(insn->vectorExtensionPrefix[1]);
1853
206k
  else if (insn->vectorExtensionType == TYPE_XOP)
1854
2.15k
    vvvv = vvvvFromXOP3of3(insn->vectorExtensionPrefix[2]);
1855
204k
  else
1856
204k
    return -1;
1857
1858
38.8k
  if (insn->mode != MODE_64BIT)
1859
20.2k
    vvvv &= 0xf; // Can only clear bit 4. Bit 3 must be cleared later.
1860
1861
38.8k
  insn->vvvv = (Reg)vvvv;
1862
1863
38.8k
  return 0;
1864
243k
}
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
21.3k
{
1875
21.3k
  if (insn->vectorExtensionType != TYPE_EVEX)
1876
0
    return -1;
1877
1878
21.3k
  insn->writemask = (Reg)(aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]));
1879
1880
21.3k
  return 0;
1881
21.3k
}
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
243k
{
1892
243k
  int hasVVVV, needVVVV;
1893
243k
  int sawRegImm = 0;
1894
243k
  int i;
1895
1896
  /* If non-zero vvvv specified, need to make sure one of the operands
1897
     uses it. */
1898
243k
  hasVVVV = !readVVVV(insn);
1899
243k
  needVVVV = hasVVVV && (insn->vvvv != 0);
1900
1901
1.70M
  for (i = 0; i < X86_MAX_OPERANDS; ++i) {
1902
1.45M
    const OperandSpecifier *op = &x86OperandSets[insn->spec->operands][i];
1903
1.45M
    switch (op->encoding) {
1904
973k
      case ENCODING_NONE:
1905
983k
      case ENCODING_SI:
1906
996k
      case ENCODING_DI:
1907
996k
        break;
1908
1909
39.7k
      CASE_ENCODING_VSIB:
1910
        // VSIB can use the V2 bit so check only the other bits.
1911
39.7k
        if (needVVVV)
1912
5.03k
          needVVVV = hasVVVV & ((insn->vvvv & 0xf) != 0);
1913
1914
39.7k
        if (readModRM(insn))
1915
0
          return -1;
1916
1917
        // Reject if SIB wasn't used.
1918
7.42k
        if (insn->eaBase != EA_BASE_sib && insn->eaBase != EA_BASE_sib64)
1919
16
          return -1;
1920
1921
        // If sibIndex was set to SIB_INDEX_NONE, index offset is 4.
1922
7.40k
        if (insn->sibIndex == SIB_INDEX_NONE)
1923
344
          insn->sibIndex = (SIBIndex)(insn->sibIndexBase + 4);
1924
1925
        // If EVEX.v2 is set this is one of the 16-31 registers.
1926
7.40k
        if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT &&
1927
4.23k
            v2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
1928
3.37k
          insn->sibIndex = (SIBIndex)(insn->sibIndex + 16);
1929
1930
        // Adjust the index register to the correct size.
1931
7.40k
        switch (op->type) {
1932
0
          default:
1933
            // debug("Unhandled VSIB index type");
1934
0
            return -1;
1935
1.94k
          case TYPE_MVSIBX:
1936
1.94k
            insn->sibIndex = (SIBIndex)(SIB_INDEX_XMM0 +
1937
1.94k
                (insn->sibIndex - insn->sibIndexBase));
1938
1.94k
            break;
1939
3.82k
          case TYPE_MVSIBY:
1940
3.82k
            insn->sibIndex = (SIBIndex)(SIB_INDEX_YMM0 +
1941
3.82k
                (insn->sibIndex - insn->sibIndexBase));
1942
3.82k
            break;
1943
1.63k
          case TYPE_MVSIBZ:
1944
1.63k
            insn->sibIndex = (SIBIndex)(SIB_INDEX_ZMM0 +
1945
1.63k
                (insn->sibIndex - insn->sibIndexBase));
1946
1.63k
            break;
1947
7.40k
        }
1948
1949
        // Apply the AVX512 compressed displacement scaling factor.
1950
7.40k
        if (op->encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1951
494
          insn->displacement *= 1 << (op->encoding - ENCODING_VSIB);
1952
7.40k
        break;
1953
1954
111k
      case ENCODING_REG:
1955
1.59M
      CASE_ENCODING_RM:
1956
1.59M
        if (readModRM(insn))
1957
0
          return -1;
1958
1959
242k
        if (fixupReg(insn, op))
1960
13
          return -1;
1961
1962
        // Apply the AVX512 compressed displacement scaling factor.
1963
242k
        if (op->encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1964
21.7k
          insn->displacement *= 1 << (op->encoding - ENCODING_RM);
1965
242k
        break;
1966
1967
61.3k
      case ENCODING_IB:
1968
61.3k
        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
325
          insn->immediates[insn->numImmediatesConsumed] =
1972
325
            insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1973
325
          ++insn->numImmediatesConsumed;
1974
325
          break;
1975
325
        }
1976
60.9k
        if (readImmediate(insn, 1))
1977
188
          return -1;
1978
60.7k
        if (op->type == TYPE_XMM || op->type == TYPE_YMM)
1979
805
          sawRegImm = 1;
1980
60.7k
        break;
1981
1982
2.84k
      case ENCODING_IW:
1983
2.84k
        if (readImmediate(insn, 2))
1984
17
          return -1;
1985
2.83k
        break;
1986
1987
2.83k
      case ENCODING_ID:
1988
810
        if (readImmediate(insn, 4))
1989
18
          return -1;
1990
792
        break;
1991
1992
792
      case ENCODING_IO:
1993
86
        if (readImmediate(insn, 8))
1994
4
          return -1;
1995
82
        break;
1996
1997
10.8k
      case ENCODING_Iv:
1998
10.8k
        if (readImmediate(insn, insn->immediateSize))
1999
116
          return -1;
2000
10.7k
        break;
2001
2002
10.7k
      case ENCODING_Ia:
2003
2.94k
        if (readImmediate(insn, insn->addressSize))
2004
28
          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
2.91k
        insn->displacementOffset = insn->immediateOffset;
2009
2.91k
        insn->consumedDisplacement = true;
2010
2.91k
        insn->displacementSize = insn->immediateSize;
2011
2.91k
        insn->displacement = insn->immediates[insn->numImmediatesConsumed - 1];
2012
2.91k
        insn->immediateOffset = 0;
2013
2.91k
        insn->immediateSize = 0;
2014
2.91k
        break;
2015
2016
527
      case ENCODING_IRC:
2017
527
        insn->RC = (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 1) |
2018
527
          lFromEVEX4of4(insn->vectorExtensionPrefix[3]);
2019
527
        break;
2020
2021
1.74k
      case ENCODING_RB:
2022
1.74k
        if (readOpcodeRegister(insn, 1))
2023
0
          return -1;
2024
1.74k
        break;
2025
2026
1.74k
      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
3.65k
      case ENCODING_RO:
2037
3.65k
        if (readOpcodeRegister(insn, 8))
2038
0
          return -1;
2039
3.65k
        break;
2040
2041
15.1k
      case ENCODING_Rv:
2042
15.1k
        if (readOpcodeRegister(insn, 0))
2043
0
          return -1;
2044
15.1k
        break;
2045
2046
15.1k
      case ENCODING_FP:
2047
604
        break;
2048
2049
28.2k
      case ENCODING_VVVV:
2050
28.2k
        if (!hasVVVV)
2051
0
          return -1;
2052
2053
28.2k
        needVVVV = 0; /* Mark that we have found a VVVV operand. */
2054
2055
28.2k
        if (insn->mode != MODE_64BIT)
2056
15.5k
          insn->vvvv = (Reg)(insn->vvvv & 0x7);
2057
2058
28.2k
        if (fixupReg(insn, op))
2059
1
          return -1;
2060
28.2k
        break;
2061
2062
28.2k
      case ENCODING_WRITEMASK:
2063
21.3k
        if (readMaskRegister(insn))
2064
0
          return -1;
2065
21.3k
        break;
2066
2067
62.6k
      case ENCODING_DUP:
2068
62.6k
        break;
2069
2070
0
      default:
2071
        // dbgprintf(insn, "Encountered an operand with an unknown encoding.");
2072
0
        return -1;
2073
1.45M
    }
2074
1.45M
  }
2075
2076
  /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
2077
242k
  if (needVVVV)
2078
3
    return -1;
2079
2080
242k
  return 0;
2081
242k
}
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
243k
{
2087
  // LOCK prefix
2088
243k
  if (insn->hasLockPrefix) {
2089
10.1k
    switch(insn->instructionID) {
2090
58
      default:
2091
        // invalid LOCK
2092
58
        return true;
2093
2094
      // nop dword [rax]
2095
36
      case X86_NOOPL:
2096
2097
      // DEC
2098
77
      case X86_DEC16m:
2099
125
      case X86_DEC32m:
2100
270
      case X86_DEC64m:
2101
335
      case X86_DEC8m:
2102
2103
      // ADC
2104
335
      case X86_ADC16mi:
2105
626
      case X86_ADC16mi8:
2106
673
      case X86_ADC16mr:
2107
811
      case X86_ADC32mi:
2108
1.08k
      case X86_ADC32mi8:
2109
1.11k
      case X86_ADC32mr:
2110
1.13k
      case X86_ADC64mi32:
2111
1.13k
      case X86_ADC64mi8:
2112
1.14k
      case X86_ADC64mr:
2113
1.33k
      case X86_ADC8mi:
2114
1.36k
      case X86_ADC8mi8:
2115
1.46k
      case X86_ADC8mr:
2116
1.47k
      case X86_ADC8rm:
2117
1.59k
      case X86_ADC16rm:
2118
1.60k
      case X86_ADC32rm:
2119
1.62k
      case X86_ADC64rm:
2120
2121
      // ADD
2122
1.63k
      case X86_ADD16mi:
2123
1.68k
      case X86_ADD16mi8:
2124
1.86k
      case X86_ADD16mr:
2125
2.04k
      case X86_ADD32mi:
2126
2.08k
      case X86_ADD32mi8:
2127
2.12k
      case X86_ADD32mr:
2128
2.15k
      case X86_ADD64mi32:
2129
2.17k
      case X86_ADD64mi8:
2130
2.19k
      case X86_ADD64mr:
2131
2.26k
      case X86_ADD8mi:
2132
2.41k
      case X86_ADD8mi8:
2133
2.76k
      case X86_ADD8mr:
2134
2.94k
      case X86_ADD8rm:
2135
3.08k
      case X86_ADD16rm:
2136
3.11k
      case X86_ADD32rm:
2137
3.12k
      case X86_ADD64rm:
2138
2139
      // AND
2140
3.26k
      case X86_AND16mi:
2141
3.40k
      case X86_AND16mi8:
2142
3.55k
      case X86_AND16mr:
2143
3.59k
      case X86_AND32mi:
2144
3.73k
      case X86_AND32mi8:
2145
3.77k
      case X86_AND32mr:
2146
3.77k
      case X86_AND64mi32:
2147
3.80k
      case X86_AND64mi8:
2148
3.80k
      case X86_AND64mr:
2149
3.82k
      case X86_AND8mi:
2150
3.84k
      case X86_AND8mi8:
2151
3.99k
      case X86_AND8mr:
2152
4.02k
      case X86_AND8rm:
2153
4.07k
      case X86_AND16rm:
2154
4.20k
      case X86_AND32rm:
2155
4.20k
      case X86_AND64rm:
2156
2157
      // BTC
2158
4.21k
      case X86_BTC16mi8:
2159
4.22k
      case X86_BTC16mr:
2160
4.24k
      case X86_BTC32mi8:
2161
4.31k
      case X86_BTC32mr:
2162
4.31k
      case X86_BTC64mi8:
2163
4.35k
      case X86_BTC64mr:
2164
2165
      // BTR
2166
4.42k
      case X86_BTR16mi8:
2167
4.42k
      case X86_BTR16mr:
2168
4.44k
      case X86_BTR32mi8:
2169
4.45k
      case X86_BTR32mr:
2170
4.47k
      case X86_BTR64mi8:
2171
4.48k
      case X86_BTR64mr:
2172
2173
      // BTS
2174
4.54k
      case X86_BTS16mi8:
2175
4.55k
      case X86_BTS16mr:
2176
4.56k
      case X86_BTS32mi8:
2177
4.61k
      case X86_BTS32mr:
2178
4.62k
      case X86_BTS64mi8:
2179
4.64k
      case X86_BTS64mr:
2180
2181
      // CMPXCHG
2182
4.66k
      case X86_CMPXCHG16B:
2183
4.70k
      case X86_CMPXCHG16rm:
2184
4.85k
      case X86_CMPXCHG32rm:
2185
4.87k
      case X86_CMPXCHG64rm:
2186
4.89k
      case X86_CMPXCHG8rm:
2187
4.89k
      case X86_CMPXCHG8B:
2188
2189
      // INC
2190
5.00k
      case X86_INC16m:
2191
5.19k
      case X86_INC32m:
2192
5.20k
      case X86_INC64m:
2193
5.20k
      case X86_INC8m:
2194
2195
      // NEG
2196
5.23k
      case X86_NEG16m:
2197
5.24k
      case X86_NEG32m:
2198
5.43k
      case X86_NEG64m:
2199
5.44k
      case X86_NEG8m:
2200
2201
      // NOT
2202
5.46k
      case X86_NOT16m:
2203
5.48k
      case X86_NOT32m:
2204
5.62k
      case X86_NOT64m:
2205
5.65k
      case X86_NOT8m:
2206
2207
      // OR
2208
5.71k
      case X86_OR16mi:
2209
5.72k
      case X86_OR16mi8:
2210
5.87k
      case X86_OR16mr:
2211
5.87k
      case X86_OR32mi:
2212
5.94k
      case X86_OR32mi8:
2213
6.00k
      case X86_OR32mr:
2214
6.02k
      case X86_OR64mi32:
2215
6.08k
      case X86_OR64mi8:
2216
6.09k
      case X86_OR64mr:
2217
6.14k
      case X86_OR8mi8:
2218
6.21k
      case X86_OR8mi:
2219
6.24k
      case X86_OR8mr:
2220
6.26k
      case X86_OR8rm:
2221
6.30k
      case X86_OR16rm:
2222
6.45k
      case X86_OR32rm:
2223
6.50k
      case X86_OR64rm:
2224
2225
      // SBB
2226
6.53k
      case X86_SBB16mi:
2227
6.54k
      case X86_SBB16mi8:
2228
6.54k
      case X86_SBB16mr:
2229
6.62k
      case X86_SBB32mi:
2230
6.78k
      case X86_SBB32mi8:
2231
6.94k
      case X86_SBB32mr:
2232
6.95k
      case X86_SBB64mi32:
2233
6.96k
      case X86_SBB64mi8:
2234
7.10k
      case X86_SBB64mr:
2235
7.28k
      case X86_SBB8mi:
2236
7.30k
      case X86_SBB8mi8:
2237
7.31k
      case X86_SBB8mr:
2238
2239
      // SUB
2240
7.31k
      case X86_SUB16mi:
2241
7.32k
      case X86_SUB16mi8:
2242
7.33k
      case X86_SUB16mr:
2243
7.55k
      case X86_SUB32mi:
2244
7.57k
      case X86_SUB32mi8:
2245
7.71k
      case X86_SUB32mr:
2246
7.74k
      case X86_SUB64mi32:
2247
7.89k
      case X86_SUB64mi8:
2248
7.89k
      case X86_SUB64mr:
2249
7.97k
      case X86_SUB8mi8:
2250
8.14k
      case X86_SUB8mi:
2251
8.15k
      case X86_SUB8mr:
2252
8.17k
      case X86_SUB8rm:
2253
8.21k
      case X86_SUB16rm:
2254
8.34k
      case X86_SUB32rm:
2255
8.36k
      case X86_SUB64rm:
2256
2257
      // XADD
2258
8.53k
      case X86_XADD16rm:
2259
8.56k
      case X86_XADD32rm:
2260
8.57k
      case X86_XADD64rm:
2261
8.60k
      case X86_XADD8rm:
2262
2263
      // XCHG
2264
8.61k
      case X86_XCHG16rm:
2265
8.68k
      case X86_XCHG32rm:
2266
8.72k
      case X86_XCHG64rm:
2267
8.74k
      case X86_XCHG8rm:
2268
2269
      // XOR
2270
8.90k
      case X86_XOR16mi:
2271
8.93k
      case X86_XOR16mi8:
2272
9.07k
      case X86_XOR16mr:
2273
9.14k
      case X86_XOR32mi:
2274
9.28k
      case X86_XOR32mi8:
2275
9.33k
      case X86_XOR32mr:
2276
9.35k
      case X86_XOR64mi32:
2277
9.35k
      case X86_XOR64mi8:
2278
9.52k
      case X86_XOR64mr:
2279
9.57k
      case X86_XOR8mi8:
2280
9.61k
      case X86_XOR8mi:
2281
9.80k
      case X86_XOR8mr:
2282
9.84k
      case X86_XOR8rm:
2283
9.85k
      case X86_XOR16rm:
2284
10.0k
      case X86_XOR32rm:
2285
10.0k
      case X86_XOR64rm:
2286
2287
        // this instruction can be used with LOCK prefix
2288
10.0k
        return false;
2289
10.1k
    }
2290
10.1k
  }
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
233k
  return false;
2305
243k
}
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
244k
{
2328
244k
  insn->reader = reader;
2329
244k
  insn->readerArg = readerArg;
2330
244k
  insn->startLocation = startLoc;
2331
244k
  insn->readerCursor = startLoc;
2332
244k
  insn->mode = mode;
2333
244k
  insn->numImmediatesConsumed = 0;
2334
2335
244k
  if (readPrefixes(insn) ||
2336
244k
      readOpcode(insn) ||
2337
244k
      getID(insn) ||
2338
243k
      insn->instructionID == 0 ||
2339
243k
      checkPrefix(insn) ||
2340
243k
      readOperands(insn))
2341
1.71k
    return -1;
2342
2343
242k
  insn->length = (size_t)(insn->readerCursor - insn->startLocation);
2344
2345
  // instruction length must be <= 15 to be valid
2346
242k
  if (insn->length > 15)
2347
7
    return -1;
2348
2349
242k
  if (insn->operandSize == 0)
2350
242k
    insn->operandSize = insn->registerSize;
2351
2352
242k
  insn->operands = &x86OperandSets[insn->spec->operands][0];
2353
2354
242k
  return 0;
2355
242k
}
2356
2357
#endif
2358