Coverage Report

Created: 2026-08-31 06:58

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