Coverage Report

Created: 2024-09-08 06:22

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