Coverage Report

Created: 2026-06-30 07:05

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