Coverage Report

Created: 2025-11-16 06:38

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