Coverage Report

Created: 2023-09-25 06:24

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