X86Disassembler.c 21.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
//===-- X86Disassembler.cpp - Disassembler for x86 and x86_64 -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is part of the X86 Disassembler.
// It contains code to translate the data produced by the decoder into
//  MCInsts.
// Documentation for the disassembler can be found in X86Disassembler.h.
//
//===----------------------------------------------------------------------===//

/* Capstone Disassembler Engine */
/* By Nguyen Anh Quynh <aquynh@gmail.com>, 2013> */

#include <inttypes.h>	// debug
#include <string.h>

#include "../../cs_priv.h"

#include "X86Disassembler.h"
#include "X86DisassemblerDecoderCommon.h"
#include "X86DisassemblerDecoder.h"
#include "../../MCInst.h"
29
#include "X86Mapping.h"
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

#define GET_REGINFO_ENUM
#include "X86GenRegisterInfo.inc"

#define GET_INSTRINFO_ENUM
#include "X86GenInstrInfo.inc"

struct reader_info {
	const uint8_t *code;
	uint64_t size;
	uint64_t offset;
};

// Fill-ins to make the compiler happy.  These constants are never actually
//   assigned; they are just filler to make an automatically-generated switch
//   statement work.
enum {
	X86_BX_SI = 500,
	X86_BX_DI = 501,
	X86_BP_SI = 502,
	X86_BP_DI = 503,
	X86_sib   = 504,
	X86_sib64 = 505
};

//
// Private code that translates from struct InternalInstructions to MCInsts.
//

/// translateRegister - Translates an internal register to the appropriate LLVM
///   register, and appends it as an operand to an MCInst.
///
/// @param mcInst     - The MCInst to append to.
/// @param reg        - The Reg to append.
static void translateRegister(MCInst *mcInst, Reg reg)
{
66
//#define ENTRY(x) X86_x,
67 68 69
#define ENTRY(x) X86_##x,
	uint8_t llvmRegnums[] = {
		ALL_REGS
70
			0
71 72 73 74 75 76 77
	};
#undef ENTRY

	uint8_t llvmRegnum = llvmRegnums[reg];
	MCInst_addOperand(mcInst, MCOperand_CreateReg(llvmRegnum));
}

78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = {
	0,        // SEG_OVERRIDE_NONE
	X86_CS,
	X86_SS,
	X86_DS,
	X86_ES,
	X86_FS,
	X86_GS
};

/// translateSrcIndex   - Appends a source index operand to an MCInst.
///
/// @param mcInst       - The MCInst to append to.
/// @param insn         - The internal instruction.
static bool translateSrcIndex(MCInst *mcInst, InternalInstruction *insn)
{
	unsigned baseRegNo;
	MCOperand *segmentReg;
	MCOperand *baseReg;

	if (insn->mode == MODE_64BIT)
		baseRegNo = insn->prefixPresent[0x67] ? X86_ESI : X86_RSI;
	else if (insn->mode == MODE_32BIT)
		baseRegNo = insn->prefixPresent[0x67] ? X86_SI : X86_ESI;
	else {
		// assert(insn->mode == MODE_16BIT);
		baseRegNo = insn->prefixPresent[0x67] ? X86_ESI : X86_SI;
	}

	baseReg = MCOperand_CreateReg(baseRegNo);
	MCInst_addOperand(mcInst, baseReg);

	segmentReg = MCOperand_CreateReg(segmentRegnums[insn->segmentOverride]);
	MCInst_addOperand(mcInst, segmentReg);

	return false;
}

/// translateDstIndex   - Appends a destination index operand to an MCInst.
///
/// @param mcInst       - The MCInst to append to.
/// @param insn         - The internal instruction.
static bool translateDstIndex(MCInst *mcInst, InternalInstruction *insn)
{
	unsigned baseRegNo;
	MCOperand *baseReg;

	if (insn->mode == MODE_64BIT)
		baseRegNo = insn->prefixPresent[0x67] ? X86_EDI : X86_RDI;
	else if (insn->mode == MODE_32BIT)
		baseRegNo = insn->prefixPresent[0x67] ? X86_DI : X86_EDI;
	else {
		// assert(insn->mode == MODE_16BIT);
		baseRegNo = insn->prefixPresent[0x67] ? X86_EDI : X86_DI;
	}

	baseReg = MCOperand_CreateReg(baseRegNo);
	MCInst_addOperand(mcInst, baseReg);

	return false;
}

140 141 142 143 144 145 146 147 148
/// translateImmediate  - Appends an immediate operand to an MCInst.
///
/// @param mcInst       - The MCInst to append to.
/// @param immediate    - The immediate value to append.
/// @param operand      - The operand, as stored in the descriptor table.
/// @param insn         - The internal instruction.
static void translateImmediate(MCInst *mcInst, uint64_t immediate,
		const OperandSpecifier *operand, InternalInstruction *insn)
{
149 150
	OperandType type;
	MCOperand *segmentReg;
151

152
	type = (OperandType)operand->type;
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
	if (type == TYPE_RELv) {
		//isBranch = true;
		//pcrel = insn->startLocation + insn->immediateOffset + insn->immediateSize;
		switch (insn->displacementSize) {
			case 1:
				if (immediate & 0x80)
					immediate |= ~(0xffull);
				break;
			case 2:
				if (immediate & 0x8000)
					immediate |= ~(0xffffull);
				break;
			case 4:
				if (immediate & 0x80000000)
					immediate |= ~(0xffffffffull);
				break;
			case 8:
				break;
			default:
				break;
		}
	} // By default sign-extend all X86 immediates based on their encoding.
	else if (type == TYPE_IMM8 || type == TYPE_IMM16 || type == TYPE_IMM32 ||
			type == TYPE_IMM64) {
		uint32_t Opcode = MCInst_getOpcode(mcInst);
		switch (operand->encoding) {
			default:
				break;
			case ENCODING_IB:
				// Special case those X86 instructions that use the imm8 as a set of
				// bits, bit count, etc. and are not sign-extend.
				if (Opcode != X86_BLENDPSrri && Opcode != X86_BLENDPDrri &&
						Opcode != X86_PBLENDWrri && Opcode != X86_MPSADBWrri &&
						Opcode != X86_DPPSrri && Opcode != X86_DPPDrri &&
						Opcode != X86_INSERTPSrr && Opcode != X86_VBLENDPSYrri &&
						Opcode != X86_VBLENDPSYrmi && Opcode != X86_VBLENDPDYrri &&
						Opcode != X86_VBLENDPDYrmi && Opcode != X86_VPBLENDWrri &&
						Opcode != X86_VMPSADBWrri && Opcode != X86_VDPPSYrri &&
						Opcode != X86_VDPPSYrmi && Opcode != X86_VDPPDrri &&
						Opcode != X86_VINSERTPSrr && Opcode != X86_INT)
					if(immediate & 0x80)
						immediate |= ~(0xffull);
				break;
			case ENCODING_IW:
				if(immediate & 0x8000)
					immediate |= ~(0xffffull);
				break;
			case ENCODING_ID:
				if(immediate & 0x80000000)
					immediate |= ~(0xffffffffull);
				break;
			case ENCODING_IO:
				break;
		}
	}

	switch (type) {
		case TYPE_XMM32:
		case TYPE_XMM64:
		case TYPE_XMM128:
213
			MCInst_addOperand(mcInst, MCOperand_CreateReg(X86_XMM0 + ((uint32_t)immediate >> 4)));
214 215
			return;
		case TYPE_XMM256:
216
			MCInst_addOperand(mcInst, MCOperand_CreateReg(X86_YMM0 + ((uint32_t)immediate >> 4)));
217 218
			return;
		case TYPE_XMM512:
219
			MCInst_addOperand(mcInst, MCOperand_CreateReg(X86_ZMM0 + ((uint32_t)immediate >> 4)));
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
			return;
		case TYPE_REL8:
			if(immediate & 0x80)
				immediate |= ~(0xffull);
			break;
		case TYPE_REL32:
		case TYPE_REL64:
			if(immediate & 0x80000000)
				immediate |= ~(0xffffffffull);
			break;
		default:
			// operand is 64 bits wide.  Do nothing.
			break;
	}

	MCInst_addOperand(mcInst, MCOperand_CreateImm(immediate));
236 237 238 239 240 241

	if (type == TYPE_MOFFS8 || type == TYPE_MOFFS16 ||
			type == TYPE_MOFFS32 || type == TYPE_MOFFS64) {
		segmentReg = MCOperand_CreateReg(segmentRegnums[insn->segmentOverride]);
		MCInst_addOperand(mcInst, segmentReg);
	}
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
}

/// translateRMRegister - Translates a register stored in the R/M field of the
///   ModR/M byte to its LLVM equivalent and appends it to an MCInst.
/// @param mcInst       - The MCInst to append to.
/// @param insn         - The internal instruction to extract the R/M field
///                       from.
/// @return             - 0 on success; -1 otherwise
static bool translateRMRegister(MCInst *mcInst, InternalInstruction *insn)
{
	if (insn->eaBase == EA_BASE_sib || insn->eaBase == EA_BASE_sib64) {
		//debug("A R/M register operand may not have a SIB byte");
		return true;
	}

	switch (insn->eaBase) {
		case EA_BASE_NONE:
			//debug("EA_BASE_NONE for ModR/M base");
			return true;
#define ENTRY(x) case EA_BASE_##x:
			ALL_EA_BASES
#undef ENTRY
				//debug("A R/M register operand may not have a base; "
				//      "the operand must be a register.");
				return true;
#define ENTRY(x)                                                      \
		case EA_REG_##x:                                                    \
269
																			MCInst_addOperand(mcInst, MCOperand_CreateReg(X86_##x)); break;
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
			ALL_REGS
#undef ENTRY
		default:
				//debug("Unexpected EA base register");
				return true;
	}

	return false;
}

/// translateRMMemory - Translates a memory operand stored in the Mod and R/M
///   fields of an internal instruction (and possibly its SIB byte) to a memory
///   operand in LLVM's format, and appends it to an MCInst.
///
/// @param mcInst       - The MCInst to append to.
/// @param insn         - The instruction to extract Mod, R/M, and SIB fields
///                       from.
/// @return             - 0 on success; nonzero otherwise
static bool translateRMMemory(MCInst *mcInst, InternalInstruction *insn)
{
	// Addresses in an MCInst are represented as five operands:
	//   1. basereg       (register)  The R/M base, or (if there is a SIB) the 
	//                                SIB base
	//   2. scaleamount   (immediate) 1, or (if there is a SIB) the specified 
	//                                scale amount
	//   3. indexreg      (register)  x86_registerNONE, or (if there is a SIB)
	//                                the index (which is multiplied by the 
	//                                scale amount)
	//   4. displacement  (immediate) 0, or the displacement if there is one
	//   5. segmentreg    (register)  x86_registerNONE for now, but could be set
	//                                if we have segment overrides

	MCOperand *baseReg;
	MCOperand *scaleAmount;
	MCOperand *indexReg;
	MCOperand *displacement;
	MCOperand *segmentReg;
307
	bool IndexIs512;
308 309 310 311 312 313

	if (insn->eaBase == EA_BASE_sib || insn->eaBase == EA_BASE_sib64) {
		if (insn->sibBase != SIB_BASE_NONE) {
			switch (insn->sibBase) {
#define ENTRY(x)                                          \
				case SIB_BASE_##x:                                  \
314
																	baseReg = MCOperand_CreateReg(X86_##x); break;
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
				ALL_SIB_BASES
#undef ENTRY
				default:
					//debug("Unexpected sibBase");
					return true;
			}
		} else {
			baseReg = MCOperand_CreateReg(0);
		}

		// Check whether we are handling VSIB addressing mode for GATHER.
		// If sibIndex was set to SIB_INDEX_NONE, index offset is 4 and
		// we should use SIB_INDEX_XMM4|YMM4 for VSIB.
		// I don't see a way to get the correct IndexReg in readSIB:
		//   We can tell whether it is VSIB or SIB after instruction ID is decoded,
		//   but instruction ID may not be decoded yet when calling readSIB.
		uint32_t Opcode = MCInst_getOpcode(mcInst);
		bool IndexIs128 = (Opcode == X86_VGATHERDPDrm ||
				Opcode == X86_VGATHERDPDYrm ||
				Opcode == X86_VGATHERQPDrm ||
				Opcode == X86_VGATHERDPSrm ||
				Opcode == X86_VGATHERQPSrm ||
				Opcode == X86_VPGATHERDQrm ||
				Opcode == X86_VPGATHERDQYrm ||
				Opcode == X86_VPGATHERQQrm ||
				Opcode == X86_VPGATHERDDrm ||
				Opcode == X86_VPGATHERQDrm);
		bool IndexIs256 = (Opcode == X86_VGATHERQPDYrm ||
				Opcode == X86_VGATHERDPSYrm ||
				Opcode == X86_VGATHERQPSYrm ||
345 346
				Opcode == X86_VGATHERDPDZrm ||
				Opcode == X86_VPGATHERDQZrm ||
347 348 349
				Opcode == X86_VPGATHERQQYrm ||
				Opcode == X86_VPGATHERDDYrm ||
				Opcode == X86_VPGATHERQDYrm);
350 351 352 353 354 355 356 357
		IndexIs512 = (Opcode == X86_VGATHERQPDZrm ||
				Opcode == X86_VGATHERDPSZrm ||
				Opcode == X86_VGATHERQPSZrm ||
				Opcode == X86_VPGATHERQQZrm ||
				Opcode == X86_VPGATHERDDZrm ||
				Opcode == X86_VPGATHERQDZrm);

		if (IndexIs128 || IndexIs256 || IndexIs512) {
358 359
			unsigned IndexOffset = insn->sibIndex -
				(insn->addressSize == 8 ? SIB_INDEX_RAX:SIB_INDEX_EAX);
360 361 362
			SIBIndex IndexBase = IndexIs512 ? SIB_INDEX_ZMM0 :
				IndexIs256 ? SIB_INDEX_YMM0 : SIB_INDEX_XMM0;

363 364 365 366 367 368 369 370 371 372
			insn->sibIndex = (SIBIndex)(IndexBase + (insn->sibIndex == SIB_INDEX_NONE ? 4 : IndexOffset));
		}

		if (insn->sibIndex != SIB_INDEX_NONE) {
			switch (insn->sibIndex) {
				default:
					//debug("Unexpected sibIndex");
					return true;
#define ENTRY(x)                                          \
				case SIB_INDEX_##x:                                 \
373
																	indexReg = MCOperand_CreateReg(X86_##x); break;
374
					EA_BASES_32BIT
375 376 377 378
						EA_BASES_64BIT
						REGS_XMM
						REGS_YMM
						REGS_ZMM
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
#undef ENTRY
			}
		} else {
			indexReg = MCOperand_CreateReg(0);
		}

		scaleAmount = MCOperand_CreateImm(insn->sibScale);
	} else {
		switch (insn->eaBase) {
			case EA_BASE_NONE:
				if (insn->eaDisplacement == EA_DISP_NONE) {
					//debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
					return true;
				}
				if (insn->mode == MODE_64BIT) {
					baseReg = MCOperand_CreateReg(X86_RIP); // Section 2.2.1.6
				} else
					baseReg = MCOperand_CreateReg(0);

				indexReg = MCOperand_CreateReg(0);
				break;
			case EA_BASE_BX_SI:
				baseReg = MCOperand_CreateReg(X86_BX);
				indexReg = MCOperand_CreateReg(X86_SI);
				break;
			case EA_BASE_BX_DI:
				baseReg = MCOperand_CreateReg(X86_BX);
				indexReg = MCOperand_CreateReg(X86_DI);
				break;
			case EA_BASE_BP_SI:
				baseReg = MCOperand_CreateReg(X86_BP);
				indexReg = MCOperand_CreateReg(X86_SI);
				break;
			case EA_BASE_BP_DI:
				baseReg = MCOperand_CreateReg(X86_BP);
				indexReg = MCOperand_CreateReg(X86_DI);
				break;
			default:
				indexReg = MCOperand_CreateReg(0);
				switch (insn->eaBase) {
					default:
						//debug("Unexpected eaBase");
						return true;
						// Here, we will use the fill-ins defined above.  However,
						//   BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and
						//   sib and sib64 were handled in the top-level if, so they're only
						//   placeholders to keep the compiler happy.
#define ENTRY(x)                                        \
					case EA_BASE_##x:                                 \
428
																	  baseReg = MCOperand_CreateReg(X86_##x); break; 
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
						ALL_EA_BASES
#undef ENTRY
#define ENTRY(x) case EA_REG_##x:
							ALL_REGS
#undef ENTRY
							//debug("A R/M memory operand may not be a register; "
							//      "the base field must be a base.");
							return true;
				}
		}

		scaleAmount = MCOperand_CreateImm(1);
	}

	displacement = MCOperand_CreateImm(insn->displacement);

	segmentReg = MCOperand_CreateReg(segmentRegnums[insn->segmentOverride]);

	MCInst_addOperand(mcInst, baseReg);
	MCInst_addOperand(mcInst, scaleAmount);
	MCInst_addOperand(mcInst, indexReg);

	MCInst_addOperand(mcInst, displacement);
	MCInst_addOperand(mcInst, segmentReg);

	return false;
}

/// translateRM - Translates an operand stored in the R/M (and possibly SIB)
///   byte of an instruction to LLVM form, and appends it to an MCInst.
///
/// @param mcInst       - The MCInst to append to.
/// @param operand      - The operand, as stored in the descriptor table.
/// @param insn         - The instruction to extract Mod, R/M, and SIB fields
///                       from.
/// @return             - 0 on success; nonzero otherwise
static bool translateRM(MCInst *mcInst, const OperandSpecifier *operand,
		InternalInstruction *insn)
{  
	switch (operand->type) {
		case TYPE_R8:
		case TYPE_R16:
		case TYPE_R32:
		case TYPE_R64:
		case TYPE_Rv:
		case TYPE_MM:
		case TYPE_MM32:
		case TYPE_MM64:
		case TYPE_XMM:
		case TYPE_XMM32:
		case TYPE_XMM64:
		case TYPE_XMM128:
		case TYPE_XMM256:
		case TYPE_XMM512:
483 484 485
		case TYPE_VK1:
		case TYPE_VK8:
		case TYPE_VK16:
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
		case TYPE_DEBUGREG:
		case TYPE_CONTROLREG:
			return translateRMRegister(mcInst, insn);
		case TYPE_M:
		case TYPE_M8:
		case TYPE_M16:
		case TYPE_M32:
		case TYPE_M64:
		case TYPE_M128:
		case TYPE_M256:
		case TYPE_M512:
		case TYPE_Mv:
		case TYPE_M32FP:
		case TYPE_M64FP:
		case TYPE_M80FP:
		case TYPE_M16INT:
		case TYPE_M32INT:
		case TYPE_M64INT:
		case TYPE_M1616:
		case TYPE_M1632:
		case TYPE_M1664:
		case TYPE_LEA:
			return translateRMMemory(mcInst, insn);
		default:
			//debug("Unexpected type for a R/M operand");
			return true;
	}
}

/// translateFPRegister - Translates a stack position on the FPU stack to its
///   LLVM form, and appends it to an MCInst.
///
/// @param mcInst       - The MCInst to append to.
/// @param stackPos     - The stack position to translate.
520
static void translateFPRegister(MCInst *mcInst, uint8_t stackPos)
521
{
522 523 524 525 526 527 528 529 530 531 532 533 534
	MCInst_addOperand(mcInst, MCOperand_CreateReg(X86_ST0 + stackPos));
}

/// translateMaskRegister - Translates a 3-bit mask register number to
///   LLVM form, and appends it to an MCInst.
///
/// @param mcInst       - The MCInst to append to.
/// @param maskRegNum   - Number of mask register from 0 to 7.
/// @return             - false on success; true otherwise.
static bool translateMaskRegister(MCInst *mcInst, uint8_t maskRegNum)
{
	if (maskRegNum >= 8) {
		// debug("Invalid mask register number");
535 536 537
		return true;
	}

538
	MCInst_addOperand(mcInst, MCOperand_CreateReg(X86_K0 + maskRegNum));
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555

	return false;
}

/// translateOperand - Translates an operand stored in an internal instruction 
///   to LLVM's format and appends it to an MCInst.
///
/// @param mcInst       - The MCInst to append to.
/// @param operand      - The operand, as stored in the descriptor table.
/// @param insn         - The internal instruction.
/// @return             - false on success; true otherwise.
static bool translateOperand(MCInst *mcInst, const OperandSpecifier *operand, InternalInstruction *insn)
{
	switch (operand->encoding) {
		case ENCODING_REG:
			translateRegister(mcInst, insn->reg);
			return false;
556 557
		case ENCODING_WRITEMASK:
			return translateMaskRegister(mcInst, insn->writemask);
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
		case ENCODING_RM:
			return translateRM(mcInst, operand, insn);
		case ENCODING_CB:
		case ENCODING_CW:
		case ENCODING_CD:
		case ENCODING_CP:
		case ENCODING_CO:
		case ENCODING_CT:
			//debug("Translation of code offsets isn't supported.");
			return true;
		case ENCODING_IB:
		case ENCODING_IW:
		case ENCODING_ID:
		case ENCODING_IO:
		case ENCODING_Iv:
		case ENCODING_Ia:
			translateImmediate(mcInst, insn->immediates[insn->numImmediatesTranslated++], operand, insn);
			return false;
576 577 578 579
		case ENCODING_SI:
			return translateSrcIndex(mcInst, insn);
		case ENCODING_DI:
			return translateDstIndex(mcInst, insn);
580 581 582 583 584 585 586
		case ENCODING_RB:
		case ENCODING_RW:
		case ENCODING_RD:
		case ENCODING_RO:
		case ENCODING_Rv:
			translateRegister(mcInst, insn->opcodeRegister);
			return false;
587 588 589
		case ENCODING_FP:
			translateFPRegister(mcInst, insn->modRM & 7);
			return false;
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
		case ENCODING_VVVV:
			translateRegister(mcInst, insn->vvvv);
			return false;
		case ENCODING_DUP:
			return translateOperand(mcInst, &insn->operands[operand->type - TYPE_DUP0], insn);
		default:
			//debug("Unhandled operand encoding during translation");
			return true;
	}
}

static bool translateInstruction(MCInst *mcInst, InternalInstruction *insn)
{
	int index;

	if (!insn->spec) {
		//debug("Instruction has no specification");
		return true;
	}

	MCInst_setOpcode(mcInst, insn->instructionID);

	// If when reading the prefix bytes we determined the overlapping 0xf2 or 0xf3
	// prefix bytes should be disassembled as xrelease and xacquire then set the
	// opcode to those instead of the rep and repne opcodes.
	if (insn->xAcquireRelease) {
		if (MCInst_getOpcode(mcInst) == X86_REP_PREFIX)
			MCInst_setOpcode(mcInst, X86_XRELEASE_PREFIX);
		else if (MCInst_getOpcode(mcInst) == X86_REPNE_PREFIX)
			MCInst_setOpcode(mcInst, X86_XACQUIRE_PREFIX);
	}

	insn->numImmediatesTranslated = 0;

	for (index = 0; index < X86_MAX_OPERANDS; ++index) {
		if (insn->operands[index].encoding != ENCODING_NONE) {
			if (translateOperand(mcInst, &insn->operands[index], insn)) {
				return true;
			}
		}
	}

	return false;
}

static int reader(const void* arg, uint8_t* byte, uint64_t address)
{
	struct reader_info *info = (void *)arg;

	if (address - info->offset >= info->size)
		// out of buffer range
		return -1;

	*byte = info->code[address - info->offset];

	return 0;
}

// copy x86 detail information from internal structure to public structure
649
static void update_pub_insn(cs_insn_flat *pub, InternalInstruction *inter)
650 651 652 653 654 655 656 657 658 659 660 661 662
{
	int i, c;

	c = 0;
	for(i = 0; i < 0x100; i++) {
		if (inter->prefixPresent[i] > 0) {
			pub->x86.prefix[c] = inter->prefixPresent[i];
			c++;
		}
	}

	pub->x86.segment = x86_map_segment(inter->segmentOverride);

663 664
	if (inter->vectorExtensionType > 0)
		memcpy(pub->x86.opcode, inter->vectorExtensionPrefix, sizeof(pub->x86.opcode));
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
	else {
		pub->x86.opcode[0] = inter->opcode;
		pub->x86.opcode[1] = inter->twoByteEscape;
		pub->x86.opcode[2] = inter->threeByteEscape;
	}

	pub->x86.op_size = inter->operandSize;
	pub->x86.addr_size = inter->addressSize;
	pub->x86.disp_size = inter->displacementSize;
	pub->x86.imm_size = inter->immediateSize;

	pub->x86.modrm = inter->modRM;
	pub->x86.sib = inter->sib;
	pub->x86.disp = inter->displacement;

	pub->x86.sib_index = x86_map_sib_index(inter->sibIndex);
	pub->x86.sib_scale = inter->sibScale;
	pub->x86.sib_base = x86_map_sib_base(inter->sibBase);
}

// Public interface for the disassembler
bool X86_getInstruction(csh ud, const uint8_t *code, size_t code_len, MCInst *instr, uint16_t *size, uint64_t address, void *_info)
{
	cs_struct *handle = (cs_struct *)(uintptr_t)ud;
	InternalInstruction insn;
	struct reader_info info;
	int ret;
	bool result;

	info.code = code;
	info.size = code_len;
	info.offset = address;

	memset(&insn, 0, sizeof(insn));

	if (handle->mode & CS_MODE_16)
		ret = decodeInstruction(&insn,
				reader, &info,
				address,
				MODE_16BIT);
	else if (handle->mode & CS_MODE_32)
		ret = decodeInstruction(&insn,
				reader, &info,
				address,
				MODE_32BIT);
	else
		ret = decodeInstruction(&insn,
				reader, &info,
				address,
				MODE_64BIT);

	if (ret) {
717
		*size = (uint16_t)(insn.readerCursor - address);
718 719
		return false;
	} else {
720
		*size = (uint16_t)insn.length;
721
		result = (!translateInstruction(instr, &insn)) ?  true : false;
722 723 724 725 726 727 728 729
		if (result) {
			if (handle->detail)
				update_pub_insn(&instr->flat_insn, &insn);

			// save immediate size to print immediate properly
			instr->x86_imm_size = insn.immediateSize;
		}

730 731 732
		return result;
	}
}