Coverage Report

Created: 2026-02-26 07:11

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
1.88M
{
79
1.88M
  return CONTEXTS_SYM[attrMask];
80
1.88M
}
81
82
/*
83
 * modRMRequired - Reads the appropriate instruction table to determine whether
84
 *   the ModR/M byte is required to decode a particular instruction.
85
 *
86
 * @param type        - The opcode type (i.e., how many bytes it has).
87
 * @param insnContext - The context for the instruction, as returned by
88
 *                      contextForAttrs.
89
 * @param opcode      - The last byte of the instruction's opcode, not counting
90
 *                      ModR/M extensions and escapes.
91
 * @return            - true if the ModR/M byte is required, false otherwise.
92
 */
93
static int modRMRequired(OpcodeType type,
94
    InstructionContext insnContext,
95
    uint16_t opcode)
96
1.88M
{
97
1.88M
  const struct OpcodeDecision *decision = NULL;
98
1.88M
  const uint8_t *indextable = NULL;
99
1.88M
  unsigned int index;
100
101
1.88M
  switch (type) {
102
0
    default: break;
103
1.56M
    case ONEBYTE:
104
1.56M
      decision = ONEBYTE_SYM;
105
1.56M
      indextable = index_x86DisassemblerOneByteOpcodes;
106
1.56M
      break;
107
159k
    case TWOBYTE:
108
159k
      decision = TWOBYTE_SYM;
109
159k
      indextable = index_x86DisassemblerTwoByteOpcodes;
110
159k
      break;
111
55.6k
    case THREEBYTE_38:
112
55.6k
      decision = THREEBYTE38_SYM;
113
55.6k
      indextable = index_x86DisassemblerThreeByte38Opcodes;
114
55.6k
      break;
115
77.2k
    case THREEBYTE_3A:
116
77.2k
      decision = THREEBYTE3A_SYM;
117
77.2k
      indextable = index_x86DisassemblerThreeByte3AOpcodes;
118
77.2k
      break;
119
0
#ifndef CAPSTONE_X86_REDUCE
120
19.1k
    case XOP8_MAP:
121
19.1k
      decision = XOP8_MAP_SYM;
122
19.1k
      indextable = index_x86DisassemblerXOP8Opcodes;
123
19.1k
      break;
124
1.51k
    case XOP9_MAP:
125
1.51k
      decision = XOP9_MAP_SYM;
126
1.51k
      indextable = index_x86DisassemblerXOP9Opcodes;
127
1.51k
      break;
128
2.25k
    case XOPA_MAP:
129
2.25k
      decision = XOPA_MAP_SYM;
130
2.25k
      indextable = index_x86DisassemblerXOPAOpcodes;
131
2.25k
      break;
132
1.80k
    case THREEDNOW_MAP:
133
      // 3DNow instructions always have ModRM byte
134
1.80k
      return true;
135
1.88M
#endif
136
1.88M
  }
137
138
  // return decision->opcodeDecisions[insnContext].modRMDecisions[opcode].modrm_type != MODRM_ONEENTRY;
139
1.88M
  index = indextable[insnContext];
140
1.88M
  if (index)
141
1.87M
    return decision[index - 1].modRMDecisions[opcode].modrm_type != MODRM_ONEENTRY;
142
8.81k
  else
143
8.81k
    return false;
144
1.88M
}
145
146
/*
147
 * decode - Reads the appropriate instruction table to obtain the unique ID of
148
 *   an instruction.
149
 *
150
 * @param type        - See modRMRequired().
151
 * @param insnContext - See modRMRequired().
152
 * @param opcode      - See modRMRequired().
153
 * @param modRM       - The ModR/M byte if required, or any value if not.
154
 * @return            - The UID of the instruction, or 0 on failure.
155
 */
156
static InstrUID decode(OpcodeType type,
157
                       InstructionContext insnContext,
158
                       uint8_t opcode,
159
                       uint8_t modRM)
160
1.88M
{
161
1.88M
  const struct ModRMDecision *dec = NULL;
162
1.88M
  unsigned int index;
163
1.88M
  static const struct OpcodeDecision emptyDecision = { 0 };
164
165
1.88M
  switch (type) {
166
0
    default: break; // never reach
167
1.56M
    case ONEBYTE:
168
      // dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
169
1.56M
      index = index_x86DisassemblerOneByteOpcodes[insnContext];
170
1.56M
      if (index)
171
1.56M
        dec = &ONEBYTE_SYM[index - 1].modRMDecisions[opcode];
172
529
      else
173
529
        dec = &emptyDecision.modRMDecisions[opcode];
174
1.56M
      break;
175
159k
    case TWOBYTE:
176
      //dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
177
159k
      index = index_x86DisassemblerTwoByteOpcodes[insnContext];
178
159k
      if (index)
179
156k
        dec = &TWOBYTE_SYM[index - 1].modRMDecisions[opcode];
180
2.73k
      else
181
2.73k
        dec = &emptyDecision.modRMDecisions[opcode];
182
159k
      break;
183
55.6k
    case THREEBYTE_38:
184
      // dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
185
55.6k
      index = index_x86DisassemblerThreeByte38Opcodes[insnContext];
186
55.6k
      if (index)
187
54.8k
        dec = &THREEBYTE38_SYM[index - 1].modRMDecisions[opcode];
188
778
      else
189
778
        dec = &emptyDecision.modRMDecisions[opcode];
190
55.6k
      break;
191
77.1k
    case THREEBYTE_3A:
192
      //dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
193
77.1k
      index = index_x86DisassemblerThreeByte3AOpcodes[insnContext];
194
77.1k
      if (index)
195
76.7k
        dec = &THREEBYTE3A_SYM[index - 1].modRMDecisions[opcode];
196
417
      else
197
417
        dec = &emptyDecision.modRMDecisions[opcode];
198
77.1k
      break;
199
0
#ifndef CAPSTONE_X86_REDUCE
200
19.1k
    case XOP8_MAP:
201
      // dec = &XOP8_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
202
19.1k
      index = index_x86DisassemblerXOP8Opcodes[insnContext];
203
19.1k
      if (index)
204
15.7k
        dec = &XOP8_MAP_SYM[index - 1].modRMDecisions[opcode];
205
3.37k
      else
206
3.37k
        dec = &emptyDecision.modRMDecisions[opcode];
207
19.1k
      break;
208
1.51k
    case XOP9_MAP:
209
      // dec = &XOP9_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
210
1.51k
      index = index_x86DisassemblerXOP9Opcodes[insnContext];
211
1.51k
      if (index)
212
1.05k
        dec = &XOP9_MAP_SYM[index - 1].modRMDecisions[opcode];
213
460
      else
214
460
        dec = &emptyDecision.modRMDecisions[opcode];
215
1.51k
      break;
216
2.25k
    case XOPA_MAP:
217
      // dec = &XOPA_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
218
2.25k
      index = index_x86DisassemblerXOPAOpcodes[insnContext];
219
2.25k
      if (index)
220
1.73k
        dec = &XOPA_MAP_SYM[index - 1].modRMDecisions[opcode];
221
520
      else
222
520
        dec = &emptyDecision.modRMDecisions[opcode];
223
2.25k
      break;
224
1.80k
    case THREEDNOW_MAP:
225
      // dec = &THREEDNOW_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
226
1.80k
      index = index_x86Disassembler3DNowOpcodes[insnContext];
227
1.80k
      if (index)
228
1.05k
        dec = &THREEDNOW_MAP_SYM[index - 1].modRMDecisions[opcode];
229
745
      else
230
745
        dec = &emptyDecision.modRMDecisions[opcode];
231
1.80k
      break;
232
1.88M
#endif
233
1.88M
  }
234
235
1.88M
  switch (dec->modrm_type) {
236
0
    default:
237
      // debug("Corrupt table!  Unknown modrm_type");
238
0
      return 0;
239
870k
    case MODRM_ONEENTRY:
240
870k
      return modRMTable[dec->instructionIDs];
241
775k
    case MODRM_SPLITRM:
242
775k
      if (modFromModRM(modRM) == 0x3)
243
163k
        return modRMTable[dec->instructionIDs + 1];
244
611k
      return modRMTable[dec->instructionIDs];
245
199k
    case MODRM_SPLITREG:
246
199k
      if (modFromModRM(modRM) == 0x3)
247
67.5k
        return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3) + 8];
248
132k
      return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
249
35.4k
    case MODRM_SPLITMISC:
250
35.4k
      if (modFromModRM(modRM) == 0x3)
251
8.64k
        return modRMTable[dec->instructionIDs+(modRM & 0x3f) + 8];
252
26.7k
      return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
253
0
    case MODRM_FULL:
254
0
      return modRMTable[dec->instructionIDs+modRM];
255
1.88M
  }
256
1.88M
}
257
258
/*
259
 * specifierForUID - Given a UID, returns the name and operand specification for
260
 *   that instruction.
261
 *
262
 * @param uid - The unique ID for the instruction.  This should be returned by
263
 *              decode(); specifierForUID will not check bounds.
264
 * @return    - A pointer to the specification for that instruction.
265
 */
266
static const struct InstructionSpecifier *specifierForUID(InstrUID uid)
267
1.56M
{
268
1.56M
  return &INSTRUCTIONS_SYM[uid];
269
1.56M
}
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
5.10M
{
283
5.10M
  int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
284
285
5.10M
  if (!ret)
286
5.09M
    ++(insn->readerCursor);
287
288
5.10M
  return ret;
289
5.10M
}
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
484k
{
300
484k
  return insn->reader(insn->readerArg, byte, insn->readerCursor);
301
484k
}
302
303
static void unconsumeByte(struct InternalInstruction* insn)
304
1.75M
{
305
1.75M
  insn->readerCursor--;
306
1.75M
}
307
308
#define CONSUME_FUNC(name, type)                                  \
309
267k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
267k
    type combined = 0;                                            \
311
267k
    unsigned offset;                                              \
312
865k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
600k
      uint8_t byte;                                               \
314
600k
      int ret = insn->reader(insn->readerArg,                     \
315
600k
                             &byte,                               \
316
600k
                             insn->readerCursor + offset);        \
317
600k
      if (ret)                                                    \
318
600k
        return ret;                                               \
319
600k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
598k
    }                                                             \
321
267k
    *ptr = combined;                                              \
322
265k
    insn->readerCursor += sizeof(type);                           \
323
265k
    return 0;                                                     \
324
267k
  }
X86DisassemblerDecoder.c:consumeInt8
Line
Count
Source
309
107k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
107k
    type combined = 0;                                            \
311
107k
    unsigned offset;                                              \
312
215k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
107k
      uint8_t byte;                                               \
314
107k
      int ret = insn->reader(insn->readerArg,                     \
315
107k
                             &byte,                               \
316
107k
                             insn->readerCursor + offset);        \
317
107k
      if (ret)                                                    \
318
107k
        return ret;                                               \
319
107k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
107k
    }                                                             \
321
107k
    *ptr = combined;                                              \
322
107k
    insn->readerCursor += sizeof(type);                           \
323
107k
    return 0;                                                     \
324
107k
  }
X86DisassemblerDecoder.c:consumeInt16
Line
Count
Source
309
28.2k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
28.2k
    type combined = 0;                                            \
311
28.2k
    unsigned offset;                                              \
312
84.6k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
56.5k
      uint8_t byte;                                               \
314
56.5k
      int ret = insn->reader(insn->readerArg,                     \
315
56.5k
                             &byte,                               \
316
56.5k
                             insn->readerCursor + offset);        \
317
56.5k
      if (ret)                                                    \
318
56.5k
        return ret;                                               \
319
56.5k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
56.3k
    }                                                             \
321
28.2k
    *ptr = combined;                                              \
322
28.1k
    insn->readerCursor += sizeof(type);                           \
323
28.1k
    return 0;                                                     \
324
28.2k
  }
X86DisassemblerDecoder.c:consumeInt32
Line
Count
Source
309
34.8k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
34.8k
    type combined = 0;                                            \
311
34.8k
    unsigned offset;                                              \
312
173k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
138k
      uint8_t byte;                                               \
314
138k
      int ret = insn->reader(insn->readerArg,                     \
315
138k
                             &byte,                               \
316
138k
                             insn->readerCursor + offset);        \
317
138k
      if (ret)                                                    \
318
138k
        return ret;                                               \
319
138k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
138k
    }                                                             \
321
34.8k
    *ptr = combined;                                              \
322
34.4k
    insn->readerCursor += sizeof(type);                           \
323
34.4k
    return 0;                                                     \
324
34.8k
  }
X86DisassemblerDecoder.c:consumeUInt16
Line
Count
Source
309
53.7k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
53.7k
    type combined = 0;                                            \
311
53.7k
    unsigned offset;                                              \
312
160k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
107k
      uint8_t byte;                                               \
314
107k
      int ret = insn->reader(insn->readerArg,                     \
315
107k
                             &byte,                               \
316
107k
                             insn->readerCursor + offset);        \
317
107k
      if (ret)                                                    \
318
107k
        return ret;                                               \
319
107k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
106k
    }                                                             \
321
53.7k
    *ptr = combined;                                              \
322
53.4k
    insn->readerCursor += sizeof(type);                           \
323
53.4k
    return 0;                                                     \
324
53.7k
  }
X86DisassemblerDecoder.c:consumeUInt32
Line
Count
Source
309
37.1k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
37.1k
    type combined = 0;                                            \
311
37.1k
    unsigned offset;                                              \
312
184k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
147k
      uint8_t byte;                                               \
314
147k
      int ret = insn->reader(insn->readerArg,                     \
315
147k
                             &byte,                               \
316
147k
                             insn->readerCursor + offset);        \
317
147k
      if (ret)                                                    \
318
147k
        return ret;                                               \
319
147k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
147k
    }                                                             \
321
37.1k
    *ptr = combined;                                              \
322
36.6k
    insn->readerCursor += sizeof(type);                           \
323
36.6k
    return 0;                                                     \
324
37.1k
  }
X86DisassemblerDecoder.c:consumeUInt64
Line
Count
Source
309
5.40k
  static int name(struct InternalInstruction* insn, type* ptr) {  \
310
5.40k
    type combined = 0;                                            \
311
5.40k
    unsigned offset;                                              \
312
47.9k
    for (offset = 0; offset < sizeof(type); ++offset) {           \
313
42.6k
      uint8_t byte;                                               \
314
42.6k
      int ret = insn->reader(insn->readerArg,                     \
315
42.6k
                             &byte,                               \
316
42.6k
                             insn->readerCursor + offset);        \
317
42.6k
      if (ret)                                                    \
318
42.6k
        return ret;                                               \
319
42.6k
      combined = combined | ((uint64_t)byte << (offset * 8));     \
320
42.5k
    }                                                             \
321
5.40k
    *ptr = combined;                                              \
322
5.26k
    insn->readerCursor += sizeof(type);                           \
323
5.26k
    return 0;                                                     \
324
5.40k
  }
325
326
/*
327
 * consume* - Use the reader function provided by the user to consume data
328
 *   values of various sizes from the instruction's memory and advance the
329
 *   cursor appropriately.  These readers perform endian conversion.
330
 *
331
 * @param insn    - See consumeByte().
332
 * @param ptr     - A pointer to a pre-allocated memory of appropriate size to
333
 *                  be populated with the data read.
334
 * @return        - See consumeByte().
335
 */
336
CONSUME_FUNC(consumeInt8, int8_t)
337
CONSUME_FUNC(consumeInt16, int16_t)
338
CONSUME_FUNC(consumeInt32, int32_t)
339
CONSUME_FUNC(consumeUInt16, uint16_t)
340
CONSUME_FUNC(consumeUInt32, uint32_t)
341
CONSUME_FUNC(consumeUInt64, uint64_t)
342
343
static bool isREX(struct InternalInstruction *insn, uint8_t prefix)
344
1.34M
{
345
1.34M
  if (insn->mode == MODE_64BIT)
346
485k
    return prefix >= 0x40 && prefix <= 0x4f;
347
348
859k
  return false;
349
1.34M
}
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
105k
{
359
105k
  uint8_t nextByte;
360
361
105k
  switch (prefix) {
362
27.6k
    case 0xf0:  // LOCK
363
27.6k
      insn->hasLockPrefix = true;
364
27.6k
      insn->repeatPrefix = 0;
365
27.6k
      break;
366
367
24.0k
    case 0xf2:  // REPNE/REPNZ
368
44.1k
    case 0xf3:  // REP or REPE/REPZ
369
44.1k
      if (lookAtByte(insn, &nextByte))
370
13
        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
44.1k
      if (isREX(insn, nextByte) || nextByte == 0x0f || nextByte == 0x66)
378
        // The last of 0xf2 /0xf3 is mandatory prefix
379
11.8k
        insn->mandatoryPrefix = prefix;
380
381
44.1k
      insn->repeatPrefix = prefix;
382
44.1k
      insn->hasLockPrefix = false;
383
44.1k
      break;
384
385
12.5k
    case 0x66:
386
12.5k
      if (lookAtByte(insn, &nextByte))
387
23
        break;
388
      // 0x66 can't overwrite existing mandatory prefix and should be ignored
389
12.5k
      if (!insn->mandatoryPrefix && (nextByte == 0x0f || isREX(insn, nextByte)))
390
4.56k
        insn->mandatoryPrefix = prefix;
391
12.5k
      break;
392
105k
  }
393
105k
}
394
395
/*
396
 * readPrefixes - Consumes all of an instruction's prefix bytes, and marks the
397
 *   instruction as having them.  Also sets the instruction's default operand,
398
 *   address, and other relevant data sizes to report operands correctly.
399
 *
400
 * @param insn  - The instruction whose prefixes are to be read.
401
 * @return      - 0 if the instruction could be read until the end of the prefix
402
 *                bytes, and no prefixes conflicted; nonzero otherwise.
403
 */
404
static int readPrefixes(struct InternalInstruction* insn)
405
1.36M
{
406
1.36M
  bool isPrefix = true;
407
1.36M
  uint8_t byte = 0;
408
1.36M
  uint8_t nextByte;
409
410
2.98M
  while (isPrefix) {
411
1.62M
    if (insn->mode == MODE_64BIT) {
412
      // eliminate consecutive redundant REX bytes in front
413
600k
      if (consumeByte(insn, &byte))
414
192
        return -1;
415
416
600k
      if ((byte & 0xf0) == 0x40) {
417
104k
        while(true) {
418
104k
          if (lookAtByte(insn, &byte))  // out of input code
419
217
            return -1;
420
103k
          if ((byte & 0xf0) == 0x40) {
421
            // another REX prefix, but we only remember the last one
422
11.8k
            if (consumeByte(insn, &byte))
423
0
              return -1;
424
11.8k
          } else
425
92.1k
            break;
426
103k
        }
427
428
        // recover the last REX byte if next byte is not a legacy prefix
429
92.1k
        switch (byte) {
430
2.19k
          case 0xf2:  /* REPNE/REPNZ */
431
3.76k
          case 0xf3:  /* REP or REPE/REPZ */
432
6.58k
          case 0xf0:  /* LOCK */
433
7.32k
          case 0x2e:  /* CS segment override -OR- Branch not taken */
434
8.72k
          case 0x36:  /* SS segment override -OR- Branch taken */
435
9.17k
          case 0x3e:  /* DS segment override */
436
9.39k
          case 0x26:  /* ES segment override */
437
9.91k
          case 0x64:  /* FS segment override */
438
10.1k
          case 0x65:  /* GS segment override */
439
11.2k
          case 0x66:  /* Operand-size override */
440
12.4k
          case 0x67:  /* Address-size override */
441
12.4k
            break;
442
79.6k
          default:    /* Not a prefix byte */
443
79.6k
            unconsumeByte(insn);
444
79.6k
            break;
445
92.1k
        }
446
507k
      } else {
447
507k
        unconsumeByte(insn);
448
507k
      }
449
600k
    }
450
451
    /* If we fail reading prefixes, just stop here and let the opcode reader deal with it */
452
1.62M
    if (consumeByte(insn, &byte))
453
196
      return -1;
454
455
1.61M
    if (insn->readerCursor - 1 == insn->startLocation
456
1.35M
        && (byte == 0xf2 || byte == 0xf3)) {
457
      // prefix requires next byte
458
82.9k
      if (lookAtByte(insn, &nextByte))
459
169
        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
82.7k
      if (((nextByte == 0xf0) ||
469
79.9k
        ((nextByte & 0xfe) == 0x86 || (nextByte & 0xf8) == 0x90))) {
470
5.99k
        insn->xAcquireRelease = byte;
471
5.99k
      }
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
82.7k
      if (byte == 0xf3 && (nextByte == 0x88 || nextByte == 0x89 ||
480
37.5k
            nextByte == 0xc6 || nextByte == 0xc7)) {
481
1.03k
        insn->xAcquireRelease = byte;
482
1.03k
      }
483
484
82.7k
      if (isREX(insn, nextByte)) {
485
9.62k
        uint8_t nnextByte;
486
487
        // Go to REX prefix after the current one
488
9.62k
        if (consumeByte(insn, &nnextByte))
489
0
          return -1;
490
491
        // We should be able to read next byte after REX prefix
492
9.62k
        if (lookAtByte(insn, &nnextByte))
493
23
          return -1;
494
495
9.59k
        unconsumeByte(insn);
496
9.59k
      }
497
82.7k
    }
498
499
1.61M
    switch (byte) {
500
65.1k
      case 0xf0:  /* LOCK */
501
120k
      case 0xf2:  /* REPNE/REPNZ */
502
166k
      case 0xf3:  /* REP or REPE/REPZ */
503
        // only accept the last prefix
504
166k
        setPrefixPresent(insn, byte);
505
166k
        insn->prefix0 = byte;
506
166k
        break;
507
508
10.1k
      case 0x2e:  /* CS segment override -OR- Branch not taken */
509
16.5k
      case 0x36:  /* SS segment override -OR- Branch taken */
510
22.5k
      case 0x3e:  /* DS segment override */
511
30.0k
      case 0x26:  /* ES segment override */
512
37.4k
      case 0x64:  /* FS segment override */
513
46.4k
      case 0x65:  /* GS segment override */
514
46.4k
        switch (byte) {
515
10.1k
          case 0x2e:
516
10.1k
            insn->segmentOverride = SEG_OVERRIDE_CS;
517
10.1k
            insn->prefix1 = byte;
518
10.1k
            break;
519
6.37k
          case 0x36:
520
6.37k
            insn->segmentOverride = SEG_OVERRIDE_SS;
521
6.37k
            insn->prefix1 = byte;
522
6.37k
            break;
523
5.96k
          case 0x3e:
524
5.96k
            insn->segmentOverride = SEG_OVERRIDE_DS;
525
5.96k
            insn->prefix1 = byte;
526
5.96k
            break;
527
7.56k
          case 0x26:
528
7.56k
            insn->segmentOverride = SEG_OVERRIDE_ES;
529
7.56k
            insn->prefix1 = byte;
530
7.56k
            break;
531
7.35k
          case 0x64:
532
7.35k
            insn->segmentOverride = SEG_OVERRIDE_FS;
533
7.35k
            insn->prefix1 = byte;
534
7.35k
            break;
535
9.07k
          case 0x65:
536
9.07k
            insn->segmentOverride = SEG_OVERRIDE_GS;
537
9.07k
            insn->prefix1 = byte;
538
9.07k
            break;
539
0
          default:
540
            // debug("Unhandled override");
541
0
            return -1;
542
46.4k
        }
543
46.4k
        setPrefixPresent(insn, byte);
544
46.4k
        break;
545
546
28.6k
      case 0x66:  /* Operand-size override */
547
28.6k
        insn->hasOpSize = true;
548
28.6k
        setPrefixPresent(insn, byte);
549
28.6k
        insn->prefix2 = byte;
550
28.6k
        break;
551
552
16.1k
      case 0x67:  /* Address-size override */
553
16.1k
        insn->hasAdSize = true;
554
16.1k
        setPrefixPresent(insn, byte);
555
16.1k
        insn->prefix3 = byte;
556
16.1k
        break;
557
1.36M
      default:    /* Not a prefix byte */
558
1.36M
        isPrefix = false;
559
1.36M
        break;
560
1.61M
    }
561
1.61M
  }
562
563
1.36M
  insn->vectorExtensionType = TYPE_NO_VEX_XOP;
564
565
1.36M
  if (byte == 0x62) {
566
111k
    uint8_t byte1, byte2;
567
568
111k
    if (consumeByte(insn, &byte1)) {
569
      // dbgprintf(insn, "Couldn't read second byte of EVEX prefix");
570
125
      return -1;
571
125
    }
572
573
111k
    if (lookAtByte(insn, &byte2)) {
574
      // dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
575
129
      unconsumeByte(insn); /* unconsume byte1 */
576
129
      unconsumeByte(insn); /* unconsume byte  */
577
111k
    } else {
578
111k
      if ((insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) &&
579
99.9k
          ((~byte1 & 0xc) == 0xc) && ((byte2 & 0x4) == 0x4)) {
580
99.6k
        insn->vectorExtensionType = TYPE_EVEX;
581
99.6k
      } else {
582
11.7k
        unconsumeByte(insn); /* unconsume byte1 */
583
11.7k
        unconsumeByte(insn); /* unconsume byte  */
584
11.7k
      }
585
111k
    }
586
587
111k
    if (insn->vectorExtensionType == TYPE_EVEX) {
588
99.6k
      insn->vectorExtensionPrefix[0] = byte;
589
99.6k
      insn->vectorExtensionPrefix[1] = byte1;
590
99.6k
      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
99.6k
      if (consumeByte(insn, &insn->vectorExtensionPrefix[3])) {
596
        // dbgprintf(insn, "Couldn't read fourth byte of EVEX prefix");
597
84
        return -1;
598
84
      }
599
600
      /* We simulate the REX prefix for simplicity's sake */
601
99.5k
      if (insn->mode == MODE_64BIT) {
602
41.2k
        insn->rexPrefix = 0x40
603
41.2k
          | (wFromEVEX3of4(insn->vectorExtensionPrefix[2]) << 3)
604
41.2k
          | (rFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 2)
605
41.2k
          | (xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 1)
606
41.2k
          | (bFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 0);
607
41.2k
      }
608
609
      // dbgprintf(insn, "Found EVEX prefix 0x%hhx 0x%hhx 0x%hhx 0x%hhx",
610
      //    insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
611
      //    insn->vectorExtensionPrefix[2], insn->vectorExtensionPrefix[3]);
612
99.5k
    }
613
1.24M
  } else if (byte == 0xc4) {
614
12.2k
    uint8_t byte1;
615
616
12.2k
    if (lookAtByte(insn, &byte1)) {
617
      // dbgprintf(insn, "Couldn't read second byte of VEX");
618
17
      return -1;
619
17
    }
620
621
12.2k
    if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)
622
10.5k
      insn->vectorExtensionType = TYPE_VEX_3B;
623
1.63k
    else
624
1.63k
      unconsumeByte(insn);
625
626
12.2k
    if (insn->vectorExtensionType == TYPE_VEX_3B) {
627
10.5k
      insn->vectorExtensionPrefix[0] = byte;
628
10.5k
      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
629
10.5k
      consumeByte(insn, &insn->vectorExtensionPrefix[2]);
630
631
      /* We simulate the REX prefix for simplicity's sake */
632
10.5k
      if (insn->mode == MODE_64BIT)
633
5.62k
        insn->rexPrefix = 0x40
634
5.62k
          | (wFromVEX3of3(insn->vectorExtensionPrefix[2]) << 3)
635
5.62k
          | (rFromVEX2of3(insn->vectorExtensionPrefix[1]) << 2)
636
5.62k
          | (xFromVEX2of3(insn->vectorExtensionPrefix[1]) << 1)
637
5.62k
          | (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
10.5k
    }
643
1.23M
  } else if (byte == 0xc5) {
644
16.0k
    uint8_t byte1;
645
646
16.0k
    if (lookAtByte(insn, &byte1)) {
647
      // dbgprintf(insn, "Couldn't read second byte of VEX");
648
15
      return -1;
649
15
    }
650
651
16.0k
    if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)
652
13.9k
      insn->vectorExtensionType = TYPE_VEX_2B;
653
2.09k
    else
654
2.09k
      unconsumeByte(insn);
655
656
16.0k
    if (insn->vectorExtensionType == TYPE_VEX_2B) {
657
13.9k
      insn->vectorExtensionPrefix[0] = byte;
658
13.9k
      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
659
660
13.9k
      if (insn->mode == MODE_64BIT)
661
4.44k
        insn->rexPrefix = 0x40
662
4.44k
          | (rFromVEX2of2(insn->vectorExtensionPrefix[1]) << 2);
663
664
13.9k
      switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
665
6.66k
        default:
666
6.66k
          break;
667
7.30k
        case VEX_PREFIX_66:
668
7.30k
          insn->hasOpSize = true;
669
7.30k
          break;
670
13.9k
      }
671
672
      // dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx",
673
      //    insn->vectorExtensionPrefix[0],
674
      //    insn->vectorExtensionPrefix[1]);
675
13.9k
    }
676
1.22M
  } else if (byte == 0x8f) {
677
11.7k
    uint8_t byte1;
678
679
11.7k
    if (lookAtByte(insn, &byte1)) {
680
      // dbgprintf(insn, "Couldn't read second byte of XOP");
681
15
      return -1;
682
15
    }
683
684
11.7k
    if ((byte1 & 0x38) != 0x0) /* 0 in these 3 bits is a POP instruction. */
685
10.5k
      insn->vectorExtensionType = TYPE_XOP;
686
1.16k
    else
687
1.16k
      unconsumeByte(insn);
688
689
11.7k
    if (insn->vectorExtensionType == TYPE_XOP) {
690
10.5k
      insn->vectorExtensionPrefix[0] = byte;
691
10.5k
      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
692
10.5k
      consumeByte(insn, &insn->vectorExtensionPrefix[2]);
693
694
      /* We simulate the REX prefix for simplicity's sake */
695
10.5k
      if (insn->mode == MODE_64BIT)
696
2.82k
        insn->rexPrefix = 0x40
697
2.82k
          | (wFromXOP3of3(insn->vectorExtensionPrefix[2]) << 3)
698
2.82k
          | (rFromXOP2of3(insn->vectorExtensionPrefix[1]) << 2)
699
2.82k
          | (xFromXOP2of3(insn->vectorExtensionPrefix[1]) << 1)
700
2.82k
          | (bFromXOP2of3(insn->vectorExtensionPrefix[1]) << 0);
701
702
10.5k
      switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
703
10.5k
        default:
704
10.5k
          break;
705
10.5k
        case VEX_PREFIX_66:
706
26
          insn->hasOpSize = true;
707
26
          break;
708
10.5k
      }
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
10.5k
    }
714
1.20M
  } else if (isREX(insn, byte)) {
715
79.6k
    if (lookAtByte(insn, &nextByte))
716
0
      return -1;
717
718
79.6k
    insn->rexPrefix = byte;
719
    // dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
720
79.6k
  } else
721
1.13M
    unconsumeByte(insn);
722
723
1.36M
  if (insn->mode == MODE_16BIT) {
724
477k
    insn->registerSize = (insn->hasOpSize ? 4 : 2);
725
477k
    insn->addressSize = (insn->hasAdSize ? 4 : 2);
726
477k
    insn->displacementSize = (insn->hasAdSize ? 4 : 2);
727
477k
    insn->immediateSize = (insn->hasOpSize ? 4 : 2);
728
477k
    insn->immSize = (insn->hasOpSize ? 4 : 2);
729
883k
  } else if (insn->mode == MODE_32BIT) {
730
398k
    insn->registerSize = (insn->hasOpSize ? 2 : 4);
731
398k
    insn->addressSize = (insn->hasAdSize ? 2 : 4);
732
398k
    insn->displacementSize = (insn->hasAdSize ? 2 : 4);
733
398k
    insn->immediateSize = (insn->hasOpSize ? 2 : 4);
734
398k
    insn->immSize = (insn->hasOpSize ? 2 : 4);
735
485k
  } else if (insn->mode == MODE_64BIT) {
736
485k
    if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
737
81.1k
      insn->registerSize       = 8;
738
81.1k
      insn->addressSize = (insn->hasAdSize ? 4 : 8);
739
81.1k
      insn->displacementSize   = 4;
740
81.1k
      insn->immediateSize      = 4;
741
81.1k
      insn->immSize      = 4;
742
404k
    } else {
743
404k
      insn->registerSize = (insn->hasOpSize ? 2 : 4);
744
404k
      insn->addressSize = (insn->hasAdSize ? 4 : 8);
745
404k
      insn->displacementSize = (insn->hasOpSize ? 2 : 4);
746
404k
      insn->immediateSize = (insn->hasOpSize ? 2 : 4);
747
404k
      insn->immSize      = (insn->hasOpSize ? 4 : 8);
748
404k
    }
749
485k
  }
750
751
1.36M
  return 0;
752
1.36M
}
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
562k
{
765
562k
  uint8_t current;
766
767
  // dbgprintf(insn, "readOpcode()");
768
769
562k
  insn->opcodeType = ONEBYTE;
770
771
562k
  if (insn->vectorExtensionType == TYPE_EVEX) {
772
52.9k
    switch (mmFromEVEX2of4(insn->vectorExtensionPrefix[1])) {
773
3
      default:
774
        // dbgprintf(insn, "Unhandled mm field for instruction (0x%hhx)",
775
        //    mmFromEVEX2of4(insn->vectorExtensionPrefix[1]));
776
3
        return -1;
777
12.8k
      case VEX_LOB_0F:
778
12.8k
        insn->opcodeType = TWOBYTE;
779
12.8k
        return consumeByte(insn, &insn->opcode);
780
17.9k
      case VEX_LOB_0F38:
781
17.9k
        insn->opcodeType = THREEBYTE_38;
782
17.9k
        return consumeByte(insn, &insn->opcode);
783
22.1k
      case VEX_LOB_0F3A:
784
22.1k
        insn->opcodeType = THREEBYTE_3A;
785
22.1k
        return consumeByte(insn, &insn->opcode);
786
52.9k
    }
787
509k
  } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
788
5.01k
    switch (mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])) {
789
17
      default:
790
        // dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
791
        //    mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
792
17
        return -1;
793
452
      case VEX_LOB_0F:
794
        //insn->twoByteEscape = 0x0f;
795
452
        insn->opcodeType = TWOBYTE;
796
452
        return consumeByte(insn, &insn->opcode);
797
3.03k
      case VEX_LOB_0F38:
798
        //insn->twoByteEscape = 0x0f;
799
3.03k
        insn->opcodeType = THREEBYTE_38;
800
3.03k
        return consumeByte(insn, &insn->opcode);
801
1.51k
      case VEX_LOB_0F3A:
802
        //insn->twoByteEscape = 0x0f;
803
1.51k
        insn->opcodeType = THREEBYTE_3A;
804
1.51k
        return consumeByte(insn, &insn->opcode);
805
5.01k
    }
806
504k
  } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
807
    //insn->twoByteEscape = 0x0f;
808
5.78k
    insn->opcodeType = TWOBYTE;
809
5.78k
    return consumeByte(insn, &insn->opcode);
810
498k
  } else if (insn->vectorExtensionType == TYPE_XOP) {
811
4.50k
    switch (mmmmmFromXOP2of3(insn->vectorExtensionPrefix[1])) {
812
25
      default:
813
        // dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
814
        //    mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
815
25
        return -1;
816
3.98k
      case XOP_MAP_SELECT_8:
817
3.98k
        insn->opcodeType = XOP8_MAP;
818
3.98k
        return consumeByte(insn, &insn->opcode);
819
229
      case XOP_MAP_SELECT_9:
820
229
        insn->opcodeType = XOP9_MAP;
821
229
        return consumeByte(insn, &insn->opcode);
822
262
      case XOP_MAP_SELECT_A:
823
262
        insn->opcodeType = XOPA_MAP;
824
262
        return consumeByte(insn, &insn->opcode);
825
4.50k
    }
826
4.50k
  }
827
828
494k
  if (consumeByte(insn, &current))
829
0
    return -1;
830
831
    // save this first byte for MOVcr, MOVdr, MOVrc, MOVrd
832
494k
    insn->firstByte = current;
833
834
494k
  if (current == 0x0f) {
835
    // dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
836
30.9k
    insn->twoByteEscape = current;
837
838
30.9k
    if (consumeByte(insn, &current))
839
60
      return -1;
840
841
30.9k
    if (current == 0x38) {
842
      // dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
843
1.00k
      if (consumeByte(insn, &current))
844
1
        return -1;
845
846
1.00k
      insn->opcodeType = THREEBYTE_38;
847
29.9k
    } else if (current == 0x3a) {
848
      // dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
849
300
      if (consumeByte(insn, &current))
850
1
        return -1;
851
852
299
      insn->opcodeType = THREEBYTE_3A;
853
29.6k
    } 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
259
      if (readModRM(insn))
857
1
        return -1;
858
859
258
      if (consumeByte(insn, &current))
860
3
        return -1;
861
862
255
      insn->opcodeType = THREEDNOW_MAP;
863
29.3k
    } else {
864
      // dbgprintf(insn, "Didn't find a three-byte escape prefix");
865
29.3k
      insn->opcodeType = TWOBYTE;
866
29.3k
    }
867
463k
  } else if (insn->mandatoryPrefix)
868
    // The opcode with mandatory prefix must start with opcode escape.
869
    // If not it's legacy repeat prefix
870
6.94k
    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
494k
  insn->opcode = current;
878
879
494k
  return 0;
880
494k
}
881
882
// Hacky for FEMMS
883
#define GET_INSTRINFO_ENUM
884
#ifndef CAPSTONE_X86_REDUCE
885
#include "X86GenInstrInfo.inc"
886
#else
887
#include "X86GenInstrInfo_reduce.inc"
888
#endif
889
890
/*
891
 * getIDWithAttrMask - Determines the ID of an instruction, consuming
892
 *   the ModR/M byte as appropriate for extended and escape opcodes,
893
 *   and using a supplied attribute mask.
894
 *
895
 * @param instructionID - A pointer whose target is filled in with the ID of the
896
 *                        instruction.
897
 * @param insn          - The instruction whose ID is to be determined.
898
 * @param attrMask      - The attribute mask to search.
899
 * @return              - 0 if the ModR/M could be read when needed or was not
900
 *                        needed; nonzero otherwise.
901
 */
902
static int getIDWithAttrMask(uint16_t *instructionID,
903
                             struct InternalInstruction* insn,
904
                             uint16_t attrMask)
905
1.88M
{
906
1.88M
  bool hasModRMExtension;
907
908
1.88M
  InstructionContext instructionClass = contextForAttrs(attrMask);
909
910
1.88M
  hasModRMExtension = modRMRequired(insn->opcodeType,
911
1.88M
      instructionClass,
912
1.88M
      insn->opcode);
913
914
1.88M
  if (hasModRMExtension) {
915
1.01M
    if (readModRM(insn))
916
2.54k
      return -1;
917
918
1.01M
    *instructionID = decode(insn->opcodeType,
919
1.01M
        instructionClass,
920
1.01M
        insn->opcode,
921
1.01M
        insn->modRM);
922
1.01M
  } else {
923
869k
    *instructionID = decode(insn->opcodeType,
924
869k
        instructionClass,
925
869k
        insn->opcode,
926
869k
        0);
927
869k
  }
928
929
1.88M
  return 0;
930
1.88M
}
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
439k
{
941
439k
  size_t i;
942
439k
  uint16_t idx;
943
944
439k
  if ((idx = x86_16_bit_eq_lookup[orig]) != 0) {
945
215k
    for (i = idx - 1; i < ARR_SIZE(x86_16_bit_eq_tbl) && x86_16_bit_eq_tbl[i].first == orig; i++) {
946
210k
      if (x86_16_bit_eq_tbl[i].second == equiv)
947
206k
        return true;
948
210k
    }
949
210k
  }
950
951
233k
  return false;
952
439k
}
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
33.9k
{
961
33.9k
  unsigned int i = find_insn(id);
962
33.9k
  if (i != -1) {
963
33.7k
    return insns[i].is64bit;
964
33.7k
  }
965
966
  // not found??
967
155
  return false;
968
33.9k
}
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
562k
{
981
562k
  uint16_t attrMask;
982
562k
  uint16_t instructionID;
983
984
562k
  attrMask = ATTR_NONE;
985
986
562k
  if (insn->mode == MODE_64BIT)
987
193k
    attrMask |= ATTR_64BIT;
988
989
562k
  if (insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
990
68.1k
    attrMask |= (insn->vectorExtensionType == TYPE_EVEX) ? ATTR_EVEX : ATTR_VEX;
991
992
68.1k
    if (insn->vectorExtensionType == TYPE_EVEX) {
993
52.9k
      switch (ppFromEVEX3of4(insn->vectorExtensionPrefix[2])) {
994
46.9k
        case VEX_PREFIX_66:
995
46.9k
          attrMask |= ATTR_OPSIZE;
996
46.9k
          break;
997
2.00k
        case VEX_PREFIX_F3:
998
2.00k
          attrMask |= ATTR_XS;
999
2.00k
          break;
1000
498
        case VEX_PREFIX_F2:
1001
498
          attrMask |= ATTR_XD;
1002
498
          break;
1003
52.9k
      }
1004
1005
52.9k
      if (zFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1006
3.82k
        attrMask |= ATTR_EVEXKZ;
1007
52.9k
      if (bFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1008
16.3k
        attrMask |= ATTR_EVEXB;
1009
52.9k
      if (aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1010
36.7k
        attrMask |= ATTR_EVEXK;
1011
52.9k
      if (lFromEVEX4of4(insn->vectorExtensionPrefix[3]))
1012
27.9k
        attrMask |= ATTR_EVEXL;
1013
52.9k
      if (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
1014
23.8k
        attrMask |= ATTR_EVEXL2;
1015
52.9k
    } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
1016
4.98k
      switch (ppFromVEX3of3(insn->vectorExtensionPrefix[2])) {
1017
4.50k
        case VEX_PREFIX_66:
1018
4.50k
          attrMask |= ATTR_OPSIZE;
1019
4.50k
          break;
1020
213
        case VEX_PREFIX_F3:
1021
213
          attrMask |= ATTR_XS;
1022
213
          break;
1023
77
        case VEX_PREFIX_F2:
1024
77
          attrMask |= ATTR_XD;
1025
77
          break;
1026
4.98k
      }
1027
1028
4.98k
      if (lFromVEX3of3(insn->vectorExtensionPrefix[2]))
1029
2.14k
        attrMask |= ATTR_VEXL;
1030
10.2k
    } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
1031
5.77k
      switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
1032
3.58k
        case VEX_PREFIX_66:
1033
3.58k
          attrMask |= ATTR_OPSIZE;
1034
3.58k
          break;
1035
575
        case VEX_PREFIX_F3:
1036
575
          attrMask |= ATTR_XS;
1037
575
          break;
1038
433
        case VEX_PREFIX_F2:
1039
433
          attrMask |= ATTR_XD;
1040
433
          break;
1041
5.77k
      }
1042
1043
5.77k
      if (lFromVEX2of2(insn->vectorExtensionPrefix[1]))
1044
3.89k
        attrMask |= ATTR_VEXL;
1045
5.77k
    } else if (insn->vectorExtensionType == TYPE_XOP) {
1046
4.46k
      switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
1047
6
        case VEX_PREFIX_66:
1048
6
          attrMask |= ATTR_OPSIZE;
1049
6
          break;
1050
6
        case VEX_PREFIX_F3:
1051
6
          attrMask |= ATTR_XS;
1052
6
          break;
1053
4
        case VEX_PREFIX_F2:
1054
4
          attrMask |= ATTR_XD;
1055
4
          break;
1056
4.46k
      }
1057
1058
4.46k
      if (lFromXOP3of3(insn->vectorExtensionPrefix[2]))
1059
217
        attrMask |= ATTR_VEXL;
1060
4.46k
    } else {
1061
0
      return -1;
1062
0
    }
1063
494k
  } else if (!insn->mandatoryPrefix) {
1064
    // If we don't have mandatory prefix we should use legacy prefixes here
1065
484k
    if (insn->hasOpSize && (insn->mode != MODE_16BIT))
1066
6.90k
      attrMask |= ATTR_OPSIZE;
1067
484k
    if (insn->hasAdSize)
1068
4.01k
      attrMask |= ATTR_ADSIZE;
1069
484k
    if (insn->opcodeType == ONEBYTE) {
1070
463k
      if (insn->repeatPrefix == 0xf3 && (insn->opcode == 0x90))
1071
        // Special support for PAUSE
1072
272
        attrMask |= ATTR_XS;
1073
463k
    } else {
1074
21.8k
      if (insn->repeatPrefix == 0xf2)
1075
597
        attrMask |= ATTR_XD;
1076
21.2k
      else if (insn->repeatPrefix == 0xf3)
1077
85
        attrMask |= ATTR_XS;
1078
21.8k
    }
1079
484k
  } else {
1080
9.06k
    switch (insn->mandatoryPrefix) {
1081
3.39k
      case 0xf2:
1082
3.39k
        attrMask |= ATTR_XD;
1083
3.39k
        break;
1084
3.23k
      case 0xf3:
1085
3.23k
        attrMask |= ATTR_XS;
1086
3.23k
        break;
1087
2.44k
      case 0x66:
1088
2.44k
        if (insn->mode != MODE_16BIT)
1089
2.08k
          attrMask |= ATTR_OPSIZE;
1090
2.44k
        break;
1091
0
      case 0x67:
1092
0
        attrMask |= ATTR_ADSIZE;
1093
0
        break;
1094
9.06k
    }
1095
1096
9.06k
  }
1097
1098
562k
  if (insn->rexPrefix & 0x08) {
1099
36.4k
    attrMask |= ATTR_REXW;
1100
36.4k
    attrMask &= ~ATTR_ADSIZE;
1101
36.4k
  }
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
562k
  if (insn->mode == MODE_16BIT && insn->opcodeType == ONEBYTE &&
1108
185k
      insn->opcode == 0xE3)
1109
1.39k
    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
562k
  if ((insn->mode == MODE_64BIT) && insn->hasOpSize) {
1116
7.74k
    switch (insn->opcode) {
1117
305
      case 0xE8:
1118
547
      case 0xE9:
1119
        // Take care of psubsb and other mmx instructions.
1120
547
        if (insn->opcodeType == ONEBYTE) {
1121
73
          attrMask ^= ATTR_OPSIZE;
1122
73
          insn->immediateSize = 4;
1123
73
          insn->displacementSize = 4;
1124
73
        }
1125
547
        break;
1126
164
      case 0x82:
1127
599
      case 0x83:
1128
622
      case 0x84:
1129
720
      case 0x85:
1130
1.24k
      case 0x86:
1131
1.52k
      case 0x87:
1132
1.60k
      case 0x88:
1133
1.69k
      case 0x89:
1134
1.77k
      case 0x8A:
1135
1.97k
      case 0x8B:
1136
2.39k
      case 0x8C:
1137
2.53k
      case 0x8D:
1138
2.57k
      case 0x8E:
1139
2.70k
      case 0x8F:
1140
        // Take care of lea and three byte ops.
1141
2.70k
        if (insn->opcodeType == TWOBYTE) {
1142
163
          attrMask ^= ATTR_OPSIZE;
1143
163
          insn->immediateSize = 4;
1144
163
          insn->displacementSize = 4;
1145
163
        }
1146
2.70k
        break;
1147
7.74k
    }
1148
7.74k
  }
1149
1150
  /* The following clauses compensate for limitations of the tables. */
1151
562k
  if (insn->mode != MODE_64BIT &&
1152
368k
      insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
1153
37.2k
    if (getIDWithAttrMask(&instructionID, insn, attrMask)) {
1154
22
      return -1;
1155
22
    }
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
37.2k
    if ((insn->vectorExtensionType == TYPE_EVEX &&
1162
27.9k
          wFromEVEX3of4(insn->vectorExtensionPrefix[2])) ||
1163
24.3k
        (insn->vectorExtensionType == TYPE_VEX_3B &&
1164
1.69k
         wFromVEX3of3(insn->vectorExtensionPrefix[2])) ||
1165
23.2k
        (insn->vectorExtensionType == TYPE_XOP &&
1166
14.2k
         wFromXOP3of3(insn->vectorExtensionPrefix[2]))) {
1167
14.2k
      uint16_t instructionIDWithREXW;
1168
1169
14.2k
      if (getIDWithAttrMask(&instructionIDWithREXW,
1170
14.2k
            insn, attrMask | ATTR_REXW)) {
1171
1
        insn->instructionID = instructionID;
1172
1
        insn->spec = specifierForUID(instructionID);
1173
1
        return 0;
1174
1
      }
1175
1176
      // If not a 64-bit instruction. Switch the opcode.
1177
14.2k
      if (!is64Bit(instructionIDWithREXW)) {
1178
13.6k
        insn->instructionID = instructionIDWithREXW;
1179
13.6k
        insn->spec = specifierForUID(instructionIDWithREXW);
1180
1181
13.6k
        return 0;
1182
13.6k
      }
1183
14.2k
    }
1184
37.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
548k
  if ((insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0)) ||
1194
541k
      (insn->opcodeType == TWOBYTE && (insn->opcode == 0xAE)) ||
1195
541k
      (insn->opcodeType == THREEBYTE_38 && insn->opcode == 0xF8)) {
1196
    /* Make sure we observed the prefixes in any position. */
1197
7.46k
    if (insn->hasAdSize)
1198
89
      attrMask |= ATTR_ADSIZE;
1199
1200
7.46k
    if (insn->hasOpSize)
1201
106
      attrMask |= ATTR_OPSIZE;
1202
1203
    /* In 16-bit, invert the attributes. */
1204
7.46k
    if (insn->mode == MODE_16BIT) {
1205
2.92k
      attrMask ^= ATTR_ADSIZE;
1206
1207
      /* The OpSize attribute is only valid with the absolute moves. */
1208
2.92k
      if (insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0))
1209
2.69k
        attrMask ^= ATTR_OPSIZE;
1210
2.92k
    }
1211
1212
7.46k
    if (getIDWithAttrMask(&instructionID, insn, attrMask)) {
1213
4
      return -1;
1214
4
    }
1215
1216
7.46k
    insn->instructionID = instructionID;
1217
7.46k
    insn->spec = specifierForUID(instructionID);
1218
1219
7.46k
    return 0;
1220
7.46k
  }
1221
541k
  if (getIDWithAttrMask(&instructionID, insn, attrMask)) {
1222
968
    return -1;
1223
968
  }
1224
1225
540k
  if ((insn->mode == MODE_16BIT || insn->hasOpSize) &&
1226
218k
      !(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
199k
    const struct InstructionSpecifier *spec;
1235
199k
    uint16_t instructionIDWithOpsize;
1236
1237
199k
    spec = specifierForUID(instructionID);
1238
1239
199k
    if (getIDWithAttrMask(&instructionIDWithOpsize,
1240
199k
          insn,
1241
199k
          attrMask | ATTR_OPSIZE)) {
1242
      /*
1243
       * ModRM required with OpSize but not present; give up and return version
1244
       * without OpSize set
1245
       */
1246
0
      insn->instructionID = instructionID;
1247
0
      insn->spec = spec;
1248
1249
0
      return 0;
1250
0
    }
1251
1252
199k
    if (is16BitEquivalent(instructionID, instructionIDWithOpsize) &&
1253
90.3k
        (insn->mode == MODE_16BIT) ^ insn->hasOpSize) {
1254
89.7k
      insn->instructionID = instructionIDWithOpsize;
1255
89.7k
      insn->spec = specifierForUID(instructionIDWithOpsize);
1256
109k
    } else {
1257
109k
      insn->instructionID = instructionID;
1258
109k
      insn->spec = spec;
1259
109k
    }
1260
1261
199k
    return 0;
1262
199k
  }
1263
1264
340k
  if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
1265
1.03k
      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
451
    const struct InstructionSpecifier *spec;
1271
451
    uint16_t instructionIDWithNewOpcode;
1272
451
    const struct InstructionSpecifier *specWithNewOpcode;
1273
1274
451
    spec = specifierForUID(instructionID);
1275
1276
    /* Borrow opcode from one of the other XCHGar opcodes */
1277
451
    insn->opcode = 0x91;
1278
1279
451
    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
451
    specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
1289
1290
    /* Change back */
1291
451
    insn->opcode = 0x90;
1292
1293
451
    insn->instructionID = instructionIDWithNewOpcode;
1294
451
    insn->spec = specWithNewOpcode;
1295
1296
451
    return 0;
1297
451
  }
1298
1299
340k
  insn->instructionID = instructionID;
1300
340k
  insn->spec = specifierForUID(insn->instructionID);
1301
1302
340k
  return 0;
1303
340k
}
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
39.8k
{
1314
39.8k
  SIBBase sibBaseBase = SIB_BASE_NONE;
1315
39.8k
  uint8_t index, base;
1316
1317
  // dbgprintf(insn, "readSIB()");
1318
1319
39.8k
  if (insn->consumedSIB)
1320
0
    return 0;
1321
1322
39.8k
  insn->consumedSIB = true;
1323
1324
39.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
16.9k
    case 4:
1329
16.9k
      insn->sibIndexBase = SIB_INDEX_EAX;
1330
16.9k
      sibBaseBase = SIB_BASE_EAX;
1331
16.9k
      break;
1332
22.8k
    case 8:
1333
22.8k
      insn->sibIndexBase = SIB_INDEX_RAX;
1334
22.8k
      sibBaseBase = SIB_BASE_RAX;
1335
22.8k
      break;
1336
39.8k
  }
1337
1338
39.8k
  if (consumeByte(insn, &insn->sib))
1339
62
    return -1;
1340
1341
39.8k
  index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
1342
1343
39.8k
  if (index == 0x4) {
1344
7.70k
    insn->sibIndex = SIB_INDEX_NONE;
1345
32.0k
  } else {
1346
32.0k
    insn->sibIndex = (SIBIndex)(insn->sibIndexBase + index);
1347
32.0k
  }
1348
1349
39.8k
  insn->sibScale = 1 << scaleFromSIB(insn->sib);
1350
1351
39.8k
  base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
1352
1353
39.8k
  switch (base) {
1354
3.84k
    case 0x5:
1355
5.30k
    case 0xd:
1356
5.30k
      switch (modFromModRM(insn->modRM)) {
1357
2.27k
        case 0x0:
1358
2.27k
          insn->eaDisplacement = EA_DISP_32;
1359
2.27k
          insn->sibBase = SIB_BASE_NONE;
1360
2.27k
          break;
1361
2.76k
        case 0x1:
1362
2.76k
          insn->eaDisplacement = EA_DISP_8;
1363
2.76k
          insn->sibBase = (SIBBase)(sibBaseBase + base);
1364
2.76k
          break;
1365
262
        case 0x2:
1366
262
          insn->eaDisplacement = EA_DISP_32;
1367
262
          insn->sibBase = (SIBBase)(sibBaseBase + base);
1368
262
          break;
1369
0
        case 0x3:
1370
          // debug("Cannot have Mod = 0b11 and a SIB byte");
1371
0
          return -1;
1372
5.30k
      }
1373
5.30k
      break;
1374
34.4k
    default:
1375
34.4k
      insn->sibBase = (SIBBase)(sibBaseBase + base);
1376
34.4k
      break;
1377
39.8k
  }
1378
1379
39.8k
  return 0;
1380
39.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
245k
{
1391
245k
  int8_t d8;
1392
245k
  int16_t d16;
1393
245k
  int32_t d32;
1394
1395
  // dbgprintf(insn, "readDisplacement()");
1396
1397
245k
  if (insn->consumedDisplacement)
1398
0
    return 0;
1399
1400
245k
  insn->consumedDisplacement = true;
1401
245k
  insn->displacementOffset = insn->readerCursor - insn->startLocation;
1402
1403
245k
  switch (insn->eaDisplacement) {
1404
74.2k
    case EA_DISP_NONE:
1405
74.2k
      insn->consumedDisplacement = false;
1406
74.2k
      break;
1407
107k
    case EA_DISP_8:
1408
107k
      if (consumeInt8(insn, &d8))
1409
224
        return -1;
1410
107k
      insn->displacement = d8;
1411
107k
      break;
1412
28.2k
    case EA_DISP_16:
1413
28.2k
      if (consumeInt16(insn, &d16))
1414
115
        return -1;
1415
28.1k
      insn->displacement = d16;
1416
28.1k
      break;
1417
34.8k
    case EA_DISP_32:
1418
34.8k
      if (consumeInt32(insn, &d32))
1419
429
        return -1;
1420
34.4k
      insn->displacement = d32;
1421
34.4k
      break;
1422
245k
  }
1423
1424
1425
244k
  return 0;
1426
245k
}
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
2.29M
{
1437
2.29M
  uint8_t mod, rm, reg, evexrm;
1438
1439
  // dbgprintf(insn, "readModRM()");
1440
1441
2.29M
  if (insn->consumedModRM)
1442
1.56M
    return 0;
1443
1444
738k
  insn->modRMOffset = (uint8_t)(insn->readerCursor - insn->startLocation);
1445
1446
738k
  if (consumeByte(insn, &insn->modRM))
1447
1.72k
    return -1;
1448
1449
736k
  insn->consumedModRM = true;
1450
1451
  // save original ModRM for later reference
1452
736k
  insn->orgModRM = insn->modRM;
1453
1454
  // handle MOVcr, MOVdr, MOVrc, MOVrd by pretending they have MRM.mod = 3
1455
736k
  if ((insn->firstByte == 0x0f && insn->opcodeType == TWOBYTE) &&
1456
60.6k
      (insn->opcode >= 0x20 && insn->opcode <= 0x23 ))
1457
1.07k
    insn->modRM |= 0xC0;
1458
1459
736k
  mod = modFromModRM(insn->modRM);
1460
736k
  rm  = rmFromModRM(insn->modRM);
1461
736k
  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
736k
  switch (insn->registerSize) {
1469
267k
    case 2:
1470
267k
      insn->regBase = MODRM_REG_AX;
1471
267k
      insn->eaRegBase = EA_REG_AX;
1472
267k
      break;
1473
406k
    case 4:
1474
406k
      insn->regBase = MODRM_REG_EAX;
1475
406k
      insn->eaRegBase = EA_REG_EAX;
1476
406k
      break;
1477
63.6k
    case 8:
1478
63.6k
      insn->regBase = MODRM_REG_RAX;
1479
63.6k
      insn->eaRegBase = EA_REG_RAX;
1480
63.6k
      break;
1481
736k
  }
1482
1483
736k
  reg |= rFromREX(insn->rexPrefix) << 3;
1484
736k
  rm  |= bFromREX(insn->rexPrefix) << 3;
1485
1486
736k
  evexrm = 0;
1487
736k
  if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT) {
1488
40.9k
    reg |= r2FromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1489
40.9k
    evexrm = xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1490
40.9k
  }
1491
1492
736k
  insn->reg = (Reg)(insn->regBase + reg);
1493
1494
736k
  switch (insn->addressSize) {
1495
250k
    case 2: {
1496
250k
      EABase eaBaseBase = EA_BASE_BX_SI;
1497
1498
250k
      switch (mod) {
1499
142k
        case 0x0:
1500
142k
          if (rm == 0x6) {
1501
7.79k
            insn->eaBase = EA_BASE_NONE;
1502
7.79k
            insn->eaDisplacement = EA_DISP_16;
1503
7.79k
            if (readDisplacement(insn))
1504
21
              return -1;
1505
135k
          } else {
1506
135k
            insn->eaBase = (EABase)(eaBaseBase + rm);
1507
135k
            insn->eaDisplacement = EA_DISP_NONE;
1508
135k
          }
1509
142k
          break;
1510
142k
        case 0x1:
1511
36.0k
          insn->eaBase = (EABase)(eaBaseBase + rm);
1512
36.0k
          insn->eaDisplacement = EA_DISP_8;
1513
36.0k
          insn->displacementSize = 1;
1514
36.0k
          if (readDisplacement(insn))
1515
59
            return -1;
1516
35.9k
          break;
1517
35.9k
        case 0x2:
1518
20.4k
          insn->eaBase = (EABase)(eaBaseBase + rm);
1519
20.4k
          insn->eaDisplacement = EA_DISP_16;
1520
20.4k
          if (readDisplacement(insn))
1521
94
            return -1;
1522
20.3k
          break;
1523
50.8k
        case 0x3:
1524
50.8k
          insn->eaBase = (EABase)(insn->eaRegBase + rm);
1525
50.8k
          if (readDisplacement(insn))
1526
0
            return -1;
1527
50.8k
          break;
1528
250k
      }
1529
250k
      break;
1530
250k
    }
1531
1532
250k
    case 4:
1533
486k
    case 8: {
1534
486k
      EABase eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1535
1536
486k
      switch (mod) {
1537
0
        default: break;
1538
256k
        case 0x0:
1539
256k
          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
256k
          switch (rm & 7) {
1544
25.6k
            case 0x4: // SIB byte is present
1545
25.6k
              insn->eaBase = (insn->addressSize == 4 ?
1546
15.0k
                  EA_BASE_sib : EA_BASE_sib64);
1547
25.6k
              if (readSIB(insn) || readDisplacement(insn))
1548
60
                return -1;
1549
25.5k
              break;
1550
25.5k
            case 0x5: // RIP-relative
1551
6.38k
              insn->eaBase = EA_BASE_NONE;
1552
6.38k
              insn->eaDisplacement = EA_DISP_32;
1553
6.38k
              if (readDisplacement(insn))
1554
81
                return -1;
1555
6.30k
              break;
1556
224k
            default:
1557
224k
              insn->eaBase = (EABase)(eaBaseBase + rm);
1558
224k
              break;
1559
256k
          }
1560
256k
          break;
1561
256k
        case 0x1:
1562
71.6k
          insn->displacementSize = 1;
1563
          /* FALLTHROUGH */
1564
97.8k
        case 0x2:
1565
97.8k
          insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1566
97.8k
          switch (rm & 7) {
1567
14.2k
            case 0x4: // SIB byte is present
1568
14.2k
              insn->eaBase = EA_BASE_sib;
1569
14.2k
              if (readSIB(insn) || readDisplacement(insn))
1570
75
                return -1;
1571
14.1k
              break;
1572
83.6k
            default:
1573
83.6k
              insn->eaBase = (EABase)(eaBaseBase + rm);
1574
83.6k
              if (readDisplacement(insn))
1575
440
                return -1;
1576
83.2k
              break;
1577
97.8k
          }
1578
97.3k
          break;
1579
131k
        case 0x3:
1580
131k
          insn->eaDisplacement = EA_DISP_NONE;
1581
131k
          insn->eaBase = (EABase)(insn->eaRegBase + rm + evexrm);
1582
131k
          break;
1583
486k
      }
1584
1585
485k
      break;
1586
486k
    }
1587
736k
  } /* switch (insn->addressSize) */
1588
1589
736k
  return 0;
1590
736k
}
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
827k
                       uint8_t *valid) {                  \
1597
827k
    *valid = 1;                                           \
1598
827k
    switch (type) {                                       \
1599
0
    default:                                              \
1600
0
      *valid = 0;                                         \
1601
0
      return 0;                                           \
1602
190k
    case TYPE_Rv:                                         \
1603
190k
      return base + index;                                \
1604
280k
    case TYPE_R8:                                         \
1605
280k
      index &= mask;                                      \
1606
280k
      if (index > 0xf)                                    \
1607
280k
        *valid = 0;                                       \
1608
280k
      if (insn->rexPrefix &&                              \
1609
280k
         index >= 4 && index <= 7) {                      \
1610
3.70k
        return prefix##_SPL + (index - 4);                \
1611
277k
      } else {                                            \
1612
277k
        return prefix##_AL + index;                       \
1613
277k
      }                                                   \
1614
280k
    case TYPE_R16:                                        \
1615
6.81k
      index &= mask;                                      \
1616
6.81k
      if (index > 0xf)                                    \
1617
6.81k
        *valid = 0;                                       \
1618
6.81k
      return prefix##_AX + index;                         \
1619
280k
    case TYPE_R32:                                        \
1620
2.74k
      index &= mask;                                      \
1621
2.74k
      if (index > 0xf)                                    \
1622
2.74k
        *valid = 0;                                       \
1623
2.74k
      return prefix##_EAX + index;                        \
1624
280k
    case TYPE_R64:                                        \
1625
22.9k
      index &= mask;                                      \
1626
22.9k
      if (index > 0xf)                                    \
1627
22.9k
        *valid = 0;                                       \
1628
22.9k
      return prefix##_RAX + index;                        \
1629
280k
    case TYPE_ZMM:                                        \
1630
68.6k
      return prefix##_ZMM0 + index;                       \
1631
280k
    case TYPE_YMM:                                        \
1632
60.9k
      return prefix##_YMM0 + index;                       \
1633
280k
    case TYPE_XMM:                                        \
1634
120k
      return prefix##_XMM0 + index;                       \
1635
280k
    case TYPE_VK:                                         \
1636
50.8k
      index &= 0xf;                                       \
1637
50.8k
      if (index > 7)                                      \
1638
50.8k
        *valid = 0;                                       \
1639
50.8k
      return prefix##_K0 + index;                         \
1640
280k
    case TYPE_MM64:                                       \
1641
8.25k
      return prefix##_MM0 + (index & 0x7);                \
1642
280k
    case TYPE_SEGMENTREG:                                 \
1643
2.90k
      if ((index & 7) > 5)                                \
1644
2.90k
        *valid = 0;                                       \
1645
2.90k
      return prefix##_ES + (index & 7);                   \
1646
280k
    case TYPE_DEBUGREG:                                   \
1647
774
      return prefix##_DR0 + index;                        \
1648
280k
    case TYPE_CONTROLREG:                                 \
1649
301
      return prefix##_CR0 + index;                        \
1650
280k
    case TYPE_BNDR:                                       \
1651
9.91k
      if (index > 3)                                      \
1652
9.91k
        *valid = 0;                                       \
1653
9.91k
      return prefix##_BND0 + index;                       \
1654
280k
    case TYPE_MVSIBX:                                     \
1655
0
      return prefix##_XMM0 + index;                       \
1656
280k
    case TYPE_MVSIBY:                                     \
1657
0
      return prefix##_YMM0 + index;                       \
1658
280k
    case TYPE_MVSIBZ:                                     \
1659
0
      return prefix##_ZMM0 + index;                       \
1660
827k
    }                                                     \
1661
827k
  }
X86DisassemblerDecoder.c:fixupRegValue
Line
Count
Source
1596
653k
                       uint8_t *valid) {                  \
1597
653k
    *valid = 1;                                           \
1598
653k
    switch (type) {                                       \
1599
0
    default:                                              \
1600
0
      *valid = 0;                                         \
1601
0
      return 0;                                           \
1602
140k
    case TYPE_Rv:                                         \
1603
140k
      return base + index;                                \
1604
227k
    case TYPE_R8:                                         \
1605
227k
      index &= mask;                                      \
1606
227k
      if (index > 0xf)                                    \
1607
227k
        *valid = 0;                                       \
1608
227k
      if (insn->rexPrefix &&                              \
1609
227k
         index >= 4 && index <= 7) {                      \
1610
2.18k
        return prefix##_SPL + (index - 4);                \
1611
225k
      } else {                                            \
1612
225k
        return prefix##_AL + index;                       \
1613
225k
      }                                                   \
1614
227k
    case TYPE_R16:                                        \
1615
5.02k
      index &= mask;                                      \
1616
5.02k
      if (index > 0xf)                                    \
1617
5.02k
        *valid = 0;                                       \
1618
5.02k
      return prefix##_AX + index;                         \
1619
227k
    case TYPE_R32:                                        \
1620
1.17k
      index &= mask;                                      \
1621
1.17k
      if (index > 0xf)                                    \
1622
1.17k
        *valid = 0;                                       \
1623
1.17k
      return prefix##_EAX + index;                        \
1624
227k
    case TYPE_R64:                                        \
1625
12.5k
      index &= mask;                                      \
1626
12.5k
      if (index > 0xf)                                    \
1627
12.5k
        *valid = 0;                                       \
1628
12.5k
      return prefix##_RAX + index;                        \
1629
227k
    case TYPE_ZMM:                                        \
1630
53.4k
      return prefix##_ZMM0 + index;                       \
1631
227k
    case TYPE_YMM:                                        \
1632
48.3k
      return prefix##_YMM0 + index;                       \
1633
227k
    case TYPE_XMM:                                        \
1634
99.0k
      return prefix##_XMM0 + index;                       \
1635
227k
    case TYPE_VK:                                         \
1636
48.1k
      index &= 0xf;                                       \
1637
48.1k
      if (index > 7)                                      \
1638
48.1k
        *valid = 0;                                       \
1639
48.1k
      return prefix##_K0 + index;                         \
1640
227k
    case TYPE_MM64:                                       \
1641
5.19k
      return prefix##_MM0 + (index & 0x7);                \
1642
227k
    case TYPE_SEGMENTREG:                                 \
1643
2.90k
      if ((index & 7) > 5)                                \
1644
2.90k
        *valid = 0;                                       \
1645
2.90k
      return prefix##_ES + (index & 7);                   \
1646
227k
    case TYPE_DEBUGREG:                                   \
1647
774
      return prefix##_DR0 + index;                        \
1648
227k
    case TYPE_CONTROLREG:                                 \
1649
301
      return prefix##_CR0 + index;                        \
1650
227k
    case TYPE_BNDR:                                       \
1651
8.87k
      if (index > 3)                                      \
1652
8.87k
        *valid = 0;                                       \
1653
8.87k
      return prefix##_BND0 + index;                       \
1654
227k
    case TYPE_MVSIBX:                                     \
1655
0
      return prefix##_XMM0 + index;                       \
1656
227k
    case TYPE_MVSIBY:                                     \
1657
0
      return prefix##_YMM0 + index;                       \
1658
227k
    case TYPE_MVSIBZ:                                     \
1659
0
      return prefix##_ZMM0 + index;                       \
1660
653k
    }                                                     \
1661
653k
  }
X86DisassemblerDecoder.c:fixupRMValue
Line
Count
Source
1596
174k
                       uint8_t *valid) {                  \
1597
174k
    *valid = 1;                                           \
1598
174k
    switch (type) {                                       \
1599
0
    default:                                              \
1600
0
      *valid = 0;                                         \
1601
0
      return 0;                                           \
1602
50.4k
    case TYPE_Rv:                                         \
1603
50.4k
      return base + index;                                \
1604
53.6k
    case TYPE_R8:                                         \
1605
53.6k
      index &= mask;                                      \
1606
53.6k
      if (index > 0xf)                                    \
1607
53.6k
        *valid = 0;                                       \
1608
53.6k
      if (insn->rexPrefix &&                              \
1609
53.6k
         index >= 4 && index <= 7) {                      \
1610
1.52k
        return prefix##_SPL + (index - 4);                \
1611
52.1k
      } else {                                            \
1612
52.1k
        return prefix##_AL + index;                       \
1613
52.1k
      }                                                   \
1614
53.6k
    case TYPE_R16:                                        \
1615
1.79k
      index &= mask;                                      \
1616
1.79k
      if (index > 0xf)                                    \
1617
1.79k
        *valid = 0;                                       \
1618
1.79k
      return prefix##_AX + index;                         \
1619
53.6k
    case TYPE_R32:                                        \
1620
1.56k
      index &= mask;                                      \
1621
1.56k
      if (index > 0xf)                                    \
1622
1.56k
        *valid = 0;                                       \
1623
1.56k
      return prefix##_EAX + index;                        \
1624
53.6k
    case TYPE_R64:                                        \
1625
10.4k
      index &= mask;                                      \
1626
10.4k
      if (index > 0xf)                                    \
1627
10.4k
        *valid = 0;                                       \
1628
10.4k
      return prefix##_RAX + index;                        \
1629
53.6k
    case TYPE_ZMM:                                        \
1630
15.1k
      return prefix##_ZMM0 + index;                       \
1631
53.6k
    case TYPE_YMM:                                        \
1632
12.5k
      return prefix##_YMM0 + index;                       \
1633
53.6k
    case TYPE_XMM:                                        \
1634
21.7k
      return prefix##_XMM0 + index;                       \
1635
53.6k
    case TYPE_VK:                                         \
1636
2.72k
      index &= 0xf;                                       \
1637
2.72k
      if (index > 7)                                      \
1638
2.72k
        *valid = 0;                                       \
1639
2.72k
      return prefix##_K0 + index;                         \
1640
53.6k
    case TYPE_MM64:                                       \
1641
3.06k
      return prefix##_MM0 + (index & 0x7);                \
1642
53.6k
    case TYPE_SEGMENTREG:                                 \
1643
0
      if ((index & 7) > 5)                                \
1644
0
        *valid = 0;                                       \
1645
0
      return prefix##_ES + (index & 7);                   \
1646
53.6k
    case TYPE_DEBUGREG:                                   \
1647
0
      return prefix##_DR0 + index;                        \
1648
53.6k
    case TYPE_CONTROLREG:                                 \
1649
0
      return prefix##_CR0 + index;                        \
1650
53.6k
    case TYPE_BNDR:                                       \
1651
1.03k
      if (index > 3)                                      \
1652
1.03k
        *valid = 0;                                       \
1653
1.03k
      return prefix##_BND0 + index;                       \
1654
53.6k
    case TYPE_MVSIBX:                                     \
1655
0
      return prefix##_XMM0 + index;                       \
1656
53.6k
    case TYPE_MVSIBY:                                     \
1657
0
      return prefix##_YMM0 + index;                       \
1658
53.6k
    case TYPE_MVSIBZ:                                     \
1659
0
      return prefix##_ZMM0 + index;                       \
1660
174k
    }                                                     \
1661
174k
  }
1662
1663
/*
1664
 * fixup*Value - Consults an operand type to determine the meaning of the
1665
 *   reg or R/M field.  If the operand is an XMM operand, for example, an
1666
 *   operand would be XMM0 instead of AX, which readModRM() would otherwise
1667
 *   misinterpret it as.
1668
 *
1669
 * @param insn  - The instruction containing the operand.
1670
 * @param type  - The operand type.
1671
 * @param index - The existing value of the field as reported by readModRM().
1672
 * @param valid - The address of a uint8_t.  The target is set to 1 if the
1673
 *                field is valid for the register class; 0 if not.
1674
 * @return      - The proper value.
1675
 */
1676
GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase, MODRM_REG, 0x1f)
1677
GENERIC_FIXUP_FUNC(fixupRMValue, insn->eaRegBase, EA_REG, 0xf)
1678
1679
/*
1680
 * fixupReg - Consults an operand specifier to determine which of the
1681
 *   fixup*Value functions to use in correcting readModRM()'ss interpretation.
1682
 *
1683
 * @param insn  - See fixup*Value().
1684
 * @param op    - The operand specifier.
1685
 * @return      - 0 if fixup was successful; -1 if the register returned was
1686
 *                invalid for its class.
1687
 */
1688
static int fixupReg(struct InternalInstruction *insn,
1689
                    const struct OperandSpecifier *op)
1690
1.36M
{
1691
1.36M
  uint8_t valid;
1692
1693
1.36M
  switch ((OperandEncoding)op->encoding) {
1694
0
    default:
1695
      // debug("Expected a REG or R/M encoding in fixupReg");
1696
0
      return -1;
1697
95.8k
    case ENCODING_VVVV:
1698
95.8k
      insn->vvvv = (Reg)fixupRegValue(insn,
1699
95.8k
          (OperandType)op->type,
1700
95.8k
          insn->vvvv,
1701
95.8k
          &valid);
1702
95.8k
      if (!valid)
1703
1
        return -1;
1704
95.8k
      break;
1705
557k
    case ENCODING_REG:
1706
557k
      insn->reg = (Reg)fixupRegValue(insn,
1707
557k
          (OperandType)op->type,
1708
557k
          insn->reg - insn->regBase,
1709
557k
          &valid);
1710
557k
      if (!valid)
1711
30
        return -1;
1712
557k
      break;
1713
4.66M
    CASE_ENCODING_RM:
1714
4.66M
      if (insn->eaBase >= insn->eaRegBase) {
1715
174k
        insn->eaBase = (EABase)fixupRMValue(insn,
1716
174k
            (OperandType)op->type,
1717
174k
            insn->eaBase - insn->eaRegBase,
1718
174k
            &valid);
1719
174k
        if (!valid)
1720
3
          return -1;
1721
174k
      }
1722
714k
      break;
1723
1.36M
  }
1724
1725
1.36M
  return 0;
1726
1.36M
}
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
144k
{
1741
144k
  if (size == 0)
1742
104k
    size = insn->registerSize;
1743
1744
144k
  switch (size) {
1745
17.3k
    case 1:
1746
17.3k
      insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
1747
17.3k
            | (insn->opcode & 7)));
1748
17.3k
      if (insn->rexPrefix &&
1749
1.66k
          insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1750
1.12k
          insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1751
584
        insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1752
584
            + (insn->opcodeRegister - MODRM_REG_AL - 4));
1753
584
      }
1754
1755
17.3k
      break;
1756
50.4k
    case 2:
1757
50.4k
      insn->opcodeRegister = (Reg)(MODRM_REG_AX
1758
50.4k
          + ((bFromREX(insn->rexPrefix) << 3)
1759
50.4k
            | (insn->opcode & 7)));
1760
50.4k
      break;
1761
53.9k
    case 4:
1762
53.9k
      insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1763
53.9k
          + ((bFromREX(insn->rexPrefix) << 3)
1764
53.9k
            | (insn->opcode & 7)));
1765
53.9k
      break;
1766
22.9k
    case 8:
1767
22.9k
      insn->opcodeRegister = (Reg)(MODRM_REG_RAX
1768
22.9k
          + ((bFromREX(insn->rexPrefix) << 3)
1769
22.9k
            | (insn->opcode & 7)));
1770
22.9k
      break;
1771
144k
  }
1772
1773
144k
  return 0;
1774
144k
}
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
375k
{
1787
375k
  uint8_t imm8;
1788
375k
  uint16_t imm16;
1789
375k
  uint32_t imm32;
1790
375k
  uint64_t imm64;
1791
1792
375k
  if (insn->numImmediatesConsumed == 2) {
1793
    // debug("Already consumed two immediates");
1794
0
    return -1;
1795
0
  }
1796
1797
375k
  if (size == 0)
1798
0
    size = insn->immediateSize;
1799
375k
  else
1800
375k
    insn->immediateSize = size;
1801
1802
375k
  insn->immediateOffset = insn->readerCursor - insn->startLocation;
1803
1804
375k
  switch (size) {
1805
279k
    case 1:
1806
279k
      if (consumeByte(insn, &imm8))
1807
705
        return -1;
1808
1809
278k
      insn->immediates[insn->numImmediatesConsumed] = imm8;
1810
278k
      break;
1811
53.7k
    case 2:
1812
53.7k
      if (consumeUInt16(insn, &imm16))
1813
293
        return -1;
1814
1815
53.4k
      insn->immediates[insn->numImmediatesConsumed] = imm16;
1816
53.4k
      break;
1817
37.1k
    case 4:
1818
37.1k
      if (consumeUInt32(insn, &imm32))
1819
468
        return -1;
1820
1821
36.6k
      insn->immediates[insn->numImmediatesConsumed] = imm32;
1822
36.6k
      break;
1823
5.40k
    case 8:
1824
5.40k
      if (consumeUInt64(insn, &imm64))
1825
137
        return -1;
1826
5.26k
      insn->immediates[insn->numImmediatesConsumed] = imm64;
1827
5.26k
      break;
1828
375k
  }
1829
1830
374k
  insn->numImmediatesConsumed++;
1831
1832
374k
  return 0;
1833
375k
}
1834
1835
/*
1836
 * readVVVV - Consumes vvvv from an instruction if it has a VEX prefix.
1837
 *
1838
 * @param insn  - The instruction whose operand is to be read.
1839
 * @return      - 0 if the vvvv was successfully consumed; nonzero
1840
 *                otherwise.
1841
 */
1842
static int readVVVV(struct InternalInstruction* insn)
1843
1.35M
{
1844
1.35M
  int vvvv;
1845
1846
1.35M
  if (insn->vectorExtensionType == TYPE_EVEX)
1847
98.9k
    vvvv = (v2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 4 |
1848
98.9k
        vvvvFromEVEX3of4(insn->vectorExtensionPrefix[2]));
1849
1.25M
  else if (insn->vectorExtensionType == TYPE_VEX_3B)
1850
10.4k
    vvvv = vvvvFromVEX3of3(insn->vectorExtensionPrefix[2]);
1851
1.24M
  else if (insn->vectorExtensionType == TYPE_VEX_2B)
1852
13.8k
    vvvv = vvvvFromVEX2of2(insn->vectorExtensionPrefix[1]);
1853
1.23M
  else if (insn->vectorExtensionType == TYPE_XOP)
1854
10.3k
    vvvv = vvvvFromXOP3of3(insn->vectorExtensionPrefix[2]);
1855
1.22M
  else
1856
1.22M
    return -1;
1857
1858
133k
  if (insn->mode != MODE_64BIT)
1859
79.9k
    vvvv &= 0xf; // Can only clear bit 4. Bit 3 must be cleared later.
1860
1861
133k
  insn->vvvv = (Reg)vvvv;
1862
1863
133k
  return 0;
1864
1.35M
}
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
67.7k
{
1875
67.7k
  if (insn->vectorExtensionType != TYPE_EVEX)
1876
0
    return -1;
1877
1878
67.7k
  insn->writemask = (Reg)(aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]));
1879
1880
67.7k
  return 0;
1881
67.7k
}
1882
1883
/*
1884
 * readOperands - Consults the specifier for an instruction and consumes all
1885
 *   operands for that instruction, interpreting them as it goes.
1886
 *
1887
 * @param insn  - The instruction whose operands are to be read and interpreted.
1888
 * @return      - 0 if all operands could be read; nonzero otherwise.
1889
 */
1890
static int readOperands(struct InternalInstruction* insn)
1891
1.35M
{
1892
1.35M
  int hasVVVV, needVVVV;
1893
1.35M
  int sawRegImm = 0;
1894
1.35M
  int i;
1895
1896
  /* If non-zero vvvv specified, need to make sure one of the operands
1897
     uses it. */
1898
1.35M
  hasVVVV = !readVVVV(insn);
1899
1.35M
  needVVVV = hasVVVV && (insn->vvvv != 0);
1900
1901
9.48M
  for (i = 0; i < X86_MAX_OPERANDS; ++i) {
1902
8.12M
    const OperandSpecifier *op = &x86OperandSets[insn->spec->operands][i];
1903
8.12M
    switch (op->encoding) {
1904
5.71M
      case ENCODING_NONE:
1905
5.77M
      case ENCODING_SI:
1906
5.84M
      case ENCODING_DI:
1907
5.84M
        break;
1908
1909
65.4k
      CASE_ENCODING_VSIB:
1910
        // VSIB can use the V2 bit so check only the other bits.
1911
65.4k
        if (needVVVV)
1912
7.65k
          needVVVV = hasVVVV & ((insn->vvvv & 0xf) != 0);
1913
1914
65.4k
        if (readModRM(insn))
1915
0
          return -1;
1916
1917
        // Reject if SIB wasn't used.
1918
12.4k
        if (insn->eaBase != EA_BASE_sib && insn->eaBase != EA_BASE_sib64)
1919
28
          return -1;
1920
1921
        // If sibIndex was set to SIB_INDEX_NONE, index offset is 4.
1922
12.4k
        if (insn->sibIndex == SIB_INDEX_NONE)
1923
1.18k
          insn->sibIndex = (SIBIndex)(insn->sibIndexBase + 4);
1924
1925
        // If EVEX.v2 is set this is one of the 16-31 registers.
1926
12.4k
        if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT &&
1927
6.77k
            v2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
1928
5.31k
          insn->sibIndex = (SIBIndex)(insn->sibIndex + 16);
1929
1930
        // Adjust the index register to the correct size.
1931
12.4k
        switch (op->type) {
1932
0
          default:
1933
            // debug("Unhandled VSIB index type");
1934
0
            return -1;
1935
5.05k
          case TYPE_MVSIBX:
1936
5.05k
            insn->sibIndex = (SIBIndex)(SIB_INDEX_XMM0 +
1937
5.05k
                (insn->sibIndex - insn->sibIndexBase));
1938
5.05k
            break;
1939
4.56k
          case TYPE_MVSIBY:
1940
4.56k
            insn->sibIndex = (SIBIndex)(SIB_INDEX_YMM0 +
1941
4.56k
                (insn->sibIndex - insn->sibIndexBase));
1942
4.56k
            break;
1943
2.83k
          case TYPE_MVSIBZ:
1944
2.83k
            insn->sibIndex = (SIBIndex)(SIB_INDEX_ZMM0 +
1945
2.83k
                (insn->sibIndex - insn->sibIndexBase));
1946
2.83k
            break;
1947
12.4k
        }
1948
1949
        // Apply the AVX512 compressed displacement scaling factor.
1950
12.4k
        if (op->encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1951
1.07k
          insn->displacement *= 1 << (op->encoding - ENCODING_VSIB);
1952
12.4k
        break;
1953
1954
557k
      case ENCODING_REG:
1955
8.56M
      CASE_ENCODING_RM:
1956
8.56M
        if (readModRM(insn))
1957
0
          return -1;
1958
1959
1.27M
        if (fixupReg(insn, op))
1960
33
          return -1;
1961
1962
        // Apply the AVX512 compressed displacement scaling factor.
1963
1.27M
        if (op->encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1964
106k
          insn->displacement *= 1 << (op->encoding - ENCODING_RM);
1965
1.27M
        break;
1966
1967
281k
      case ENCODING_IB:
1968
281k
        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
1.61k
          insn->immediates[insn->numImmediatesConsumed] =
1972
1.61k
            insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1973
1.61k
          ++insn->numImmediatesConsumed;
1974
1.61k
          break;
1975
1.61k
        }
1976
279k
        if (readImmediate(insn, 1))
1977
705
          return -1;
1978
278k
        if (op->type == TYPE_XMM || op->type == TYPE_YMM)
1979
2.76k
          sawRegImm = 1;
1980
278k
        break;
1981
1982
18.5k
      case ENCODING_IW:
1983
18.5k
        if (readImmediate(insn, 2))
1984
81
          return -1;
1985
18.4k
        break;
1986
1987
18.4k
      case ENCODING_ID:
1988
6.67k
        if (readImmediate(insn, 4))
1989
81
          return -1;
1990
6.59k
        break;
1991
1992
6.59k
      case ENCODING_IO:
1993
1.10k
        if (readImmediate(insn, 8))
1994
29
          return -1;
1995
1.07k
        break;
1996
1997
54.3k
      case ENCODING_Iv:
1998
54.3k
        if (readImmediate(insn, insn->immediateSize))
1999
530
          return -1;
2000
53.7k
        break;
2001
2002
53.7k
      case ENCODING_Ia:
2003
15.5k
        if (readImmediate(insn, insn->addressSize))
2004
177
          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
15.3k
        insn->displacementOffset = insn->immediateOffset;
2009
15.3k
        insn->consumedDisplacement = true;
2010
15.3k
        insn->displacementSize = insn->immediateSize;
2011
15.3k
        insn->displacement = insn->immediates[insn->numImmediatesConsumed - 1];
2012
15.3k
        insn->immediateOffset = 0;
2013
15.3k
        insn->immediateSize = 0;
2014
15.3k
        break;
2015
2016
4.78k
      case ENCODING_IRC:
2017
4.78k
        insn->RC = (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 1) |
2018
4.78k
          lFromEVEX4of4(insn->vectorExtensionPrefix[3]);
2019
4.78k
        break;
2020
2021
17.3k
      case ENCODING_RB:
2022
17.3k
        if (readOpcodeRegister(insn, 1))
2023
0
          return -1;
2024
17.3k
        break;
2025
2026
17.3k
      case ENCODING_RW:
2027
0
        if (readOpcodeRegister(insn, 2))
2028
0
          return -1;
2029
0
        break;
2030
2031
0
      case ENCODING_RD:
2032
0
        if (readOpcodeRegister(insn, 4))
2033
0
          return -1;
2034
0
        break;
2035
2036
22.3k
      case ENCODING_RO:
2037
22.3k
        if (readOpcodeRegister(insn, 8))
2038
0
          return -1;
2039
22.3k
        break;
2040
2041
104k
      case ENCODING_Rv:
2042
104k
        if (readOpcodeRegister(insn, 0))
2043
0
          return -1;
2044
104k
        break;
2045
2046
104k
      case ENCODING_FP:
2047
6.19k
        break;
2048
2049
95.8k
      case ENCODING_VVVV:
2050
95.8k
        if (!hasVVVV)
2051
0
          return -1;
2052
2053
95.8k
        needVVVV = 0; /* Mark that we have found a VVVV operand. */
2054
2055
95.8k
        if (insn->mode != MODE_64BIT)
2056
58.8k
          insn->vvvv = (Reg)(insn->vvvv & 0x7);
2057
2058
95.8k
        if (fixupReg(insn, op))
2059
1
          return -1;
2060
95.8k
        break;
2061
2062
95.8k
      case ENCODING_WRITEMASK:
2063
67.7k
        if (readMaskRegister(insn))
2064
0
          return -1;
2065
67.7k
        break;
2066
2067
298k
      case ENCODING_DUP:
2068
298k
        break;
2069
2070
0
      default:
2071
        // dbgprintf(insn, "Encountered an operand with an unknown encoding.");
2072
0
        return -1;
2073
8.12M
    }
2074
8.12M
  }
2075
2076
  /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
2077
1.35M
  if (needVVVV)
2078
30
    return -1;
2079
2080
1.35M
  return 0;
2081
1.35M
}
2082
2083
// return True if instruction is illegal to use with prefixes
2084
// This also check & fix the isPrefixNN when a prefix is irrelevant.
2085
static bool checkPrefix(struct InternalInstruction *insn)
2086
1.35M
{
2087
  // LOCK prefix
2088
1.35M
  if (insn->hasLockPrefix) {
2089
56.0k
    switch(insn->instructionID) {
2090
363
      default:
2091
        // invalid LOCK
2092
363
        return true;
2093
2094
      // nop dword [rax]
2095
50
      case X86_NOOPL:
2096
2097
      // DEC
2098
176
      case X86_DEC16m:
2099
422
      case X86_DEC32m:
2100
663
      case X86_DEC64m:
2101
981
      case X86_DEC8m:
2102
2103
      // ADC
2104
1.10k
      case X86_ADC16mi:
2105
1.61k
      case X86_ADC16mi8:
2106
1.83k
      case X86_ADC16mr:
2107
1.97k
      case X86_ADC32mi:
2108
2.84k
      case X86_ADC32mi8:
2109
3.02k
      case X86_ADC32mr:
2110
3.54k
      case X86_ADC64mi32:
2111
3.74k
      case X86_ADC64mi8:
2112
3.94k
      case X86_ADC64mr:
2113
4.26k
      case X86_ADC8mi:
2114
4.58k
      case X86_ADC8mi8:
2115
5.31k
      case X86_ADC8mr:
2116
5.62k
      case X86_ADC8rm:
2117
5.96k
      case X86_ADC16rm:
2118
6.12k
      case X86_ADC32rm:
2119
6.52k
      case X86_ADC64rm:
2120
2121
      // ADD
2122
6.77k
      case X86_ADD16mi:
2123
7.32k
      case X86_ADD16mi8:
2124
7.75k
      case X86_ADD16mr:
2125
8.17k
      case X86_ADD32mi:
2126
8.54k
      case X86_ADD32mi8:
2127
9.12k
      case X86_ADD32mr:
2128
9.25k
      case X86_ADD64mi32:
2129
9.70k
      case X86_ADD64mi8:
2130
10.3k
      case X86_ADD64mr:
2131
10.6k
      case X86_ADD8mi:
2132
10.9k
      case X86_ADD8mi8:
2133
11.7k
      case X86_ADD8mr:
2134
12.3k
      case X86_ADD8rm:
2135
13.2k
      case X86_ADD16rm:
2136
13.5k
      case X86_ADD32rm:
2137
13.9k
      case X86_ADD64rm:
2138
2139
      // AND
2140
14.4k
      case X86_AND16mi:
2141
14.6k
      case X86_AND16mi8:
2142
15.0k
      case X86_AND16mr:
2143
15.6k
      case X86_AND32mi:
2144
16.2k
      case X86_AND32mi8:
2145
16.4k
      case X86_AND32mr:
2146
16.6k
      case X86_AND64mi32:
2147
16.9k
      case X86_AND64mi8:
2148
17.1k
      case X86_AND64mr:
2149
17.5k
      case X86_AND8mi:
2150
17.7k
      case X86_AND8mi8:
2151
18.2k
      case X86_AND8mr:
2152
18.5k
      case X86_AND8rm:
2153
19.0k
      case X86_AND16rm:
2154
19.2k
      case X86_AND32rm:
2155
19.5k
      case X86_AND64rm:
2156
2157
      // BTC
2158
19.8k
      case X86_BTC16mi8:
2159
20.0k
      case X86_BTC16mr:
2160
20.1k
      case X86_BTC32mi8:
2161
20.3k
      case X86_BTC32mr:
2162
20.5k
      case X86_BTC64mi8:
2163
20.7k
      case X86_BTC64mr:
2164
2165
      // BTR
2166
21.1k
      case X86_BTR16mi8:
2167
22.0k
      case X86_BTR16mr:
2168
22.3k
      case X86_BTR32mi8:
2169
22.8k
      case X86_BTR32mr:
2170
23.0k
      case X86_BTR64mi8:
2171
23.3k
      case X86_BTR64mr:
2172
2173
      // BTS
2174
23.6k
      case X86_BTS16mi8:
2175
23.8k
      case X86_BTS16mr:
2176
24.3k
      case X86_BTS32mi8:
2177
24.5k
      case X86_BTS32mr:
2178
24.8k
      case X86_BTS64mi8:
2179
24.9k
      case X86_BTS64mr:
2180
2181
      // CMPXCHG
2182
25.3k
      case X86_CMPXCHG16B:
2183
25.6k
      case X86_CMPXCHG16rm:
2184
25.8k
      case X86_CMPXCHG32rm:
2185
26.3k
      case X86_CMPXCHG64rm:
2186
27.2k
      case X86_CMPXCHG8rm:
2187
27.3k
      case X86_CMPXCHG8B:
2188
2189
      // INC
2190
27.6k
      case X86_INC16m:
2191
27.9k
      case X86_INC32m:
2192
28.0k
      case X86_INC64m:
2193
28.4k
      case X86_INC8m:
2194
2195
      // NEG
2196
28.7k
      case X86_NEG16m:
2197
28.9k
      case X86_NEG32m:
2198
29.0k
      case X86_NEG64m:
2199
29.1k
      case X86_NEG8m:
2200
2201
      // NOT
2202
29.4k
      case X86_NOT16m:
2203
29.6k
      case X86_NOT32m:
2204
29.9k
      case X86_NOT64m:
2205
30.2k
      case X86_NOT8m:
2206
2207
      // OR
2208
30.5k
      case X86_OR16mi:
2209
31.6k
      case X86_OR16mi8:
2210
32.0k
      case X86_OR16mr:
2211
32.4k
      case X86_OR32mi:
2212
32.8k
      case X86_OR32mi8:
2213
33.3k
      case X86_OR32mr:
2214
33.5k
      case X86_OR64mi32:
2215
33.9k
      case X86_OR64mi8:
2216
34.0k
      case X86_OR64mr:
2217
34.2k
      case X86_OR8mi8:
2218
34.9k
      case X86_OR8mi:
2219
35.1k
      case X86_OR8mr:
2220
35.5k
      case X86_OR8rm:
2221
35.9k
      case X86_OR16rm:
2222
36.4k
      case X86_OR32rm:
2223
36.7k
      case X86_OR64rm:
2224
2225
      // SBB
2226
36.9k
      case X86_SBB16mi:
2227
37.2k
      case X86_SBB16mi8:
2228
37.4k
      case X86_SBB16mr:
2229
37.6k
      case X86_SBB32mi:
2230
37.8k
      case X86_SBB32mi8:
2231
38.1k
      case X86_SBB32mr:
2232
38.3k
      case X86_SBB64mi32:
2233
38.9k
      case X86_SBB64mi8:
2234
39.1k
      case X86_SBB64mr:
2235
39.4k
      case X86_SBB8mi:
2236
40.0k
      case X86_SBB8mi8:
2237
40.2k
      case X86_SBB8mr:
2238
2239
      // SUB
2240
40.7k
      case X86_SUB16mi:
2241
40.9k
      case X86_SUB16mi8:
2242
41.4k
      case X86_SUB16mr:
2243
41.7k
      case X86_SUB32mi:
2244
42.0k
      case X86_SUB32mi8:
2245
42.3k
      case X86_SUB32mr:
2246
42.8k
      case X86_SUB64mi32:
2247
43.3k
      case X86_SUB64mi8:
2248
44.0k
      case X86_SUB64mr:
2249
44.1k
      case X86_SUB8mi8:
2250
44.5k
      case X86_SUB8mi:
2251
44.8k
      case X86_SUB8mr:
2252
45.3k
      case X86_SUB8rm:
2253
45.7k
      case X86_SUB16rm:
2254
46.2k
      case X86_SUB32rm:
2255
46.6k
      case X86_SUB64rm:
2256
2257
      // XADD
2258
46.8k
      case X86_XADD16rm:
2259
46.9k
      case X86_XADD32rm:
2260
47.2k
      case X86_XADD64rm:
2261
47.6k
      case X86_XADD8rm:
2262
2263
      // XCHG
2264
48.2k
      case X86_XCHG16rm:
2265
48.7k
      case X86_XCHG32rm:
2266
48.8k
      case X86_XCHG64rm:
2267
49.1k
      case X86_XCHG8rm:
2268
2269
      // XOR
2270
49.5k
      case X86_XOR16mi:
2271
50.1k
      case X86_XOR16mi8:
2272
50.4k
      case X86_XOR16mr:
2273
50.5k
      case X86_XOR32mi:
2274
50.8k
      case X86_XOR32mi8:
2275
51.0k
      case X86_XOR32mr:
2276
51.3k
      case X86_XOR64mi32:
2277
52.3k
      case X86_XOR64mi8:
2278
52.7k
      case X86_XOR64mr:
2279
53.0k
      case X86_XOR8mi8:
2280
53.8k
      case X86_XOR8mi:
2281
54.2k
      case X86_XOR8mr:
2282
54.8k
      case X86_XOR8rm:
2283
55.3k
      case X86_XOR16rm:
2284
55.5k
      case X86_XOR32rm:
2285
55.6k
      case X86_XOR64rm:
2286
2287
        // this instruction can be used with LOCK prefix
2288
55.6k
        return false;
2289
56.0k
    }
2290
56.0k
  }
2291
2292
#if 0
2293
  // REPNE prefix
2294
  if (insn->repeatPrefix) {
2295
    // 0xf2 can be a part of instruction encoding, but not really a prefix.
2296
    // In such a case, clear it.
2297
    if (insn->twoByteEscape == 0x0f) {
2298
      insn->prefix0 = 0;
2299
    }
2300
  }
2301
#endif
2302
2303
  // no invalid prefixes
2304
1.30M
  return false;
2305
1.35M
}
2306
2307
/*
2308
 * decodeInstruction - Reads and interprets a full instruction provided by the
2309
 *   user.
2310
 *
2311
 * @param insn      - A pointer to the instruction to be populated.  Must be
2312
 *                    pre-allocated.
2313
 * @param reader    - The function to be used to read the instruction's bytes.
2314
 * @param readerArg - A generic argument to be passed to the reader to store
2315
 *                    any internal state.
2316
 * @param startLoc  - The address (in the reader's address space) of the first
2317
 *                    byte in the instruction.
2318
 * @param mode      - The mode (real mode, IA-32e, or IA-32e in 64-bit mode) to
2319
 *                    decode the instruction in.
2320
 * @return          - 0 if instruction is valid; nonzero if not.
2321
 */
2322
int decodeInstruction(struct InternalInstruction *insn,
2323
    byteReader_t reader,
2324
    const void *readerArg,
2325
    uint64_t startLoc,
2326
    DisassemblerMode mode)
2327
1.36M
{
2328
1.36M
  insn->reader = reader;
2329
1.36M
  insn->readerArg = readerArg;
2330
1.36M
  insn->startLocation = startLoc;
2331
1.36M
  insn->readerCursor = startLoc;
2332
1.36M
  insn->mode = mode;
2333
1.36M
  insn->numImmediatesConsumed = 0;
2334
2335
1.36M
  if (readPrefixes(insn) ||
2336
1.36M
      readOpcode(insn) ||
2337
1.36M
      getID(insn) ||
2338
1.35M
      insn->instructionID == 0 ||
2339
1.35M
      checkPrefix(insn) ||
2340
1.35M
      readOperands(insn))
2341
8.45k
    return -1;
2342
2343
1.35M
  insn->length = (size_t)(insn->readerCursor - insn->startLocation);
2344
2345
  // instruction length must be <= 15 to be valid
2346
1.35M
  if (insn->length > 15)
2347
62
    return -1;
2348
2349
1.35M
  if (insn->operandSize == 0)
2350
1.35M
    insn->operandSize = insn->registerSize;
2351
2352
1.35M
  insn->operands = &x86OperandSets[insn->spec->operands][0];
2353
2354
1.35M
  return 0;
2355
1.35M
}
2356
2357
#endif
2358