Coverage Report

Created: 2026-05-30 06:22

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