InstructionTestGen.py revision 0cd5b157d7c4708b8ad79e3acd474ac781dfbcf1
# -*- coding: utf-8 -*-
# $Id$
"""
Instruction Test Generator.
"""
from __future__ import print_function;
__copyright__ = \
"""
Copyright (C) 2012-2013 Oracle Corporation
Oracle Corporation confidential
All rights reserved
"""
__version__ = "$Revision$";
# Standard python imports.
import io;
import os;
from optparse import OptionParser
import random;
import sys;
## @name Exit codes
## @{
RTEXITCODE_SUCCESS = 0;
RTEXITCODE_SYNTAX = 2;
## @}
## @name Various C macros we're used to.
## @{
UINT8_MAX = 0xff
UINT16_MAX = 0xffff
UINT32_MAX = 0xffffffff
UINT64_MAX = 0xffffffffffffffff
""" 32-bit one bit mask. """
return 1 << iBit;
""" 64-bit one bit mask. """
return 1 << iBit;
## @}
## @name ModR/M
## @{
X86_MODRM_RM_MASK = 0x07;
X86_MODRM_REG_MASK = 0x38;
X86_MODRM_REG_SMASK = 0x07;
X86_MODRM_REG_SHIFT = 3;
X86_MODRM_MOD_MASK = 0xc0;
X86_MODRM_MOD_SMASK = 0x03;
X86_MODRM_MOD_SHIFT = 6;
## @}
## @name SIB
## @{
X86_SIB_BASE_MASK = 0x07;
X86_SIB_INDEX_MASK = 0x38;
X86_SIB_INDEX_SMASK = 0x07;
X86_SIB_INDEX_SHIFT = 3;
X86_SIB_SCALE_MASK = 0xc0;
X86_SIB_SCALE_SMASK = 0x03;
X86_SIB_SCALE_SHIFT = 6;
## @}
## @name Prefixes
## @
X86_OP_PRF_CS = 0x2e;
X86_OP_PRF_SS = 0x36;
X86_OP_PRF_DS = 0x3e;
X86_OP_PRF_ES = 0x26;
X86_OP_PRF_FS = 0x64;
X86_OP_PRF_GS = 0x65;
X86_OP_PRF_SIZE_OP = 0x66;
X86_OP_PRF_SIZE_ADDR = 0x67;
X86_OP_PRF_LOCK = 0xf0;
X86_OP_PRF_REPZ = 0xf2;
X86_OP_PRF_REPNZ = 0xf3;
X86_OP_REX_B = 0x41;
X86_OP_REX_X = 0x42;
X86_OP_REX_R = 0x44;
X86_OP_REX_W = 0x48;
## @}
## @name General registers
## @
X86_GREG_xAX = 0
X86_GREG_xCX = 1
X86_GREG_xDX = 2
X86_GREG_xBX = 3
X86_GREG_xSP = 4
X86_GREG_xBP = 5
X86_GREG_xSI = 6
X86_GREG_xDI = 7
X86_GREG_x8 = 8
X86_GREG_x9 = 9
X86_GREG_x10 = 10
X86_GREG_x11 = 11
X86_GREG_x12 = 12
X86_GREG_x13 = 13
X86_GREG_x14 = 14
X86_GREG_x15 = 15
## @}
## @name Register names.
## @{
g_asGRegs64NoSp = ('rax', 'rcx', 'rdx', 'rbx', None, 'rbp', 'rsi', 'rdi', 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15');
g_asGRegs64 = ('rax', 'rcx', 'rdx', 'rbx', 'rsp', 'rbp', 'rsi', 'rdi', 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15');
'r8d', 'r9d', 'r10d', 'r11d', 'r12d', 'r13d', 'r14d', 'r15d');
'r8d', 'r9d', 'r10d', 'r11d', 'r12d', 'r13d', 'r14d', 'r15d');
'r8w', 'r9w', 'r10w', 'r11w', 'r12w', 'r13w', 'r14w', 'r15w');
'r8w', 'r9w', 'r10w', 'r11w', 'r12w', 'r13w', 'r14w', 'r15w');
'r8b', 'r9b', 'r10b', 'r11b', 'r12b', 'r13b', 'r14b', 'r15b',
'ah', 'ch', 'dh', 'bh');
## @}
## @name Random
## @{
#g_iMyRandSeed = 286523426;
#g_iMyRandSeed = 1994382324;
#g_oMyRand = random.SystemRandom();
def randU8():
""" Unsigned 8-bit random number. """
def randU16():
""" Unsigned 16-bit random number. """
def randU32():
""" Unsigned 32-bit random number. """
def randU64():
""" Unsigned 64-bit random number. """
""" Unsigned 8-, 16-, 32-, or 64-bit random number. """
""" List of unsigned 8-, 16-, 32-, or 64-bit random numbers. """
## @}
## @name Instruction Emitter Helpers
## @{
"""
Calculates a rex prefix if neccessary given the two registers
and optional rex size prefixes.
Returns an empty array if not necessary.
"""
if iReg >= 8:
bRex |= X86_OP_REX_R;
if iRm >= 8:
bRex |= X86_OP_REX_B;
if bRex == 0:
return [];
return [bRex,];
"""
Calculate the RM byte for two registers.
Returns an array with one byte in it.
"""
| (iRm & X86_MODRM_RM_MASK);
return [bRm,];
## @}
## @name Misc
## @{
def convU32ToSigned(u32):
""" Converts a 32-bit unsigned value to 32-bit signed. """
if u32 < 0x80000000:
return u32;
""" Rotate a xx-bit wide unsigned number to the left. """
if cBits == 16:
uMask = UINT16_MAX;
elif cBits == 32:
uMask = UINT32_MAX;
elif cBits == 64:
uMask = UINT64_MAX;
else:
assert cBits == 8;
return uRet;
""" Rotate a xx-bit wide unsigned number to the right. """
if cBits == 16:
uMask = UINT16_MAX;
elif cBits == 32:
uMask = UINT32_MAX;
elif cBits == 64:
uMask = UINT64_MAX;
else:
assert cBits == 8;
return uRet;
""" Gets the name of a general register by index and width. """
if cBits == 64:
return g_asGRegs64[iReg];
if cBits == 32:
return g_asGRegs32[iReg];
if cBits == 16:
return g_asGRegs16[iReg];
assert cBits == 8;
if fRexByteRegs:
return g_asGRegs8Rex[iReg];
return g_asGRegs8[iReg];
## @}
"""
Target Runtime Environment.
"""
## @name CPU Modes
## @{
ksCpuMode_Real = 'real';
ksCpuMode_Protect = 'prot';
ksCpuMode_Paged = 'paged';
ksCpuMode_Long = 'long';
ksCpuMode_V86 = 'v86';
## @}
## @name Instruction set.
## @{
ksInstrSet_16 = '16';
ksInstrSet_32 = '32';
ksInstrSet_64 = '64';
## @}
iRing = 3,
):
def isUsingIprt(self):
""" Whether it's an IPRT environment or not. """
""" Whether it's a 64-bit environment or not. """
def getDefOpBits(self):
""" Get the default operand size as a bit count. """
return 16;
return 32;
def getDefOpBytes(self):
""" Get the default operand size as a byte count. """
def getMaxOpBits(self):
""" Get the max operand size as a bit count. """
return 64;
return 32;
def getMaxOpBytes(self):
""" Get the max operand size as a byte count. """
def getDefAddrBits(self):
""" Get the default address size as a bit count. """
return 16;
return 32;
return 64;
def getDefAddrBytes(self):
""" Get the default address size as a byte count. """
""" Get the number of general registers. """
if cbEffBytes == 1:
return 16 + 4;
return 16;
return 8;
""" Returns a random general register number, excluding the SP register. """
while iReg == X86_GREG_xSP:
return iReg;
""" List of randGRegNoSp values. """
aiRegs = [];
return aiRegs;
def getAddrModes(self):
return [16, 32];
return [32, 16];
return [64, 32];
""" Checks if the given register is a high 8-bit general register (AH, CH, DH or BH). """
if cbEffOp == 1:
if iGReg >= 16:
return True;
return True;
return False;
## Target environments.
g_dTargetEnvs = {
};
class InstrTestBase(object):
"""
Base class for testing one instruction.
"""
"""
Tests if the instruction test is applicable to the selected environment.
"""
_ = oGen;
return True;
"""
Emits the test assembly code.
"""
return True;
""" Generate a list of inputs. """
if fLong:
#
# Try do extremes as well as different ranges of random numbers.
#
if cbMaxOp >= 1:
if cbMaxOp >= 2:
if cbMaxOp >= 4:
if cbMaxOp >= 8:
cWanted = 16;
cWanted = 64;
else:
for cBits, cValues in ( (8, 16), (16, 16), (24, 4), (32, 64), (40, 4), (48, 4), (56, 4), (64, 64) ):
cWanted = 168;
else:
#
# Short list, just do some random numbers.
#
auRet = [];
else:
auRet = [];
return auRet;
"""
Instruction reading memory or general register and writing the result to a
general register.
"""
## @name Test Instruction Writers
## @{
""" Writes the instruction with two general registers as operands. """
% (self.sInstr, gregName(iOp1, cbEffOp * 8, fRexByteRegs), gregName(iOp2, cbEffOp * 8, fRexByteRegs),));
return True;
""" Writes the instruction with two general registers as operands. """
if cbEffOp == 8:
elif cbEffOp == 4:
elif cbEffOp == 2:
elif cbEffOp == 1:
else:
assert False;
else:
if iMod == 1:
elif iMod == 2:
else:
assert iMod == 0;
if cAddrBits == 64:
elif cAddrBits == 32:
elif cAddrBits == 16:
assert False; ## @todo implement 16-bit addressing.
else:
return True;
def writeInstrGregSibLabel(self, cbEffOp, iOp1, cAddrBits, iBaseReg, iIndexReg, iScale, offDisp, oGen):
""" Writes the instruction taking a register and a label (base only w/o reg), SIB form. """
if cAddrBits == 64:
# Note! Cannot test this in 64-bit mode in any sensible way because the disp is 32-bit
# and we cannot (yet) make assumtions about where we're loaded.
## @todo Enable testing this in environments where we can make assumptions (boot sector).
else:
return True;
def writeInstrGregSibScaledReg(self, cbEffOp, iOp1, cAddrBits, iBaseReg, iIndexReg, iScale, offDisp, oGen):
""" Writes the instruction taking a register and disp+scaled register (no base reg), SIB form. """
# Note! Using altsibxN to force scaled encoding. This is only really a
# necessity for iScale=1, but doesn't hurt for the rest.
if offDisp is not None:
_ = iBaseReg;
return True;
def writeInstrGregSibBase(self, cbEffOp, iOp1, cAddrBits, iBaseReg, iIndexReg, iScale, offDisp, oGen):
""" Writes the instruction taking a register and base only (with reg), SIB form. """
if offDisp is not None:
_ = iIndexReg;
return True;
def writeInstrGregSibBaseAndScaledReg(self, cbEffOp, iOp1, cAddrBits, iBaseReg, iIndexReg, iScale, offDisp, oGen):
""" Writes tinstruction taking a register and full featured SIB form address. """
# Note! From the looks of things, yasm will encode the following instructions the same way:
# mov eax, [rsi*1 + rbx]
# mov eax, [rbx + rsi*1]
# So, when there are two registers involved, the '*1' selects
# which is index and which is base.
if offDisp is not None:
return True;
## @}
## @name Memory setups
## @{
""" Sets up memory for a memory read. """
return True;
""" Sets up memory for a memory read indirectly addressed thru one register and optional displacement. """
return True;
def generateMemSetupReadByScaledReg(self, oGen, cAddrBits, cbEffOp, iIndexReg, iScale, uInput, offDisp = None):
""" Sets up memory for a memory read indirectly addressed thru one register and optional displacement. """
% (oGen.needGRegMemSetup(cAddrBits, cbEffOp, offDisp = offDisp, iIndexReg = iIndexReg, iScale = iScale),));
return True;
def generateMemSetupReadByBaseAndScaledReg(self, oGen, cAddrBits, cbEffOp, iBaseReg, iIndexReg, iScale, uInput, offDisp):
""" Sets up memory for a memory read indirectly addressed thru two registers with optional displacement. """
return True;
""" Sets up memory for a pure R/M addressed read, iOp2 being the R/M value. """
else:
return True;
## @}
def generateOneStdTestGregGreg(self, oGen, cbEffOp, cbMaxOp, iOp1, iOp1X, iOp2, iOp2X, uInput, uResult):
""" Generate one standard instr greg,greg test. """
oGen.write(' call VBINSTST_NAME(%s)\n' % (oGen.needGRegChecker(iOp1X, iOp2X if iOp1X != iOp2X else None),));
_ = cbMaxOp;
return True;
""" High 8-bit registers are a real pain! """
# Figure out the register indexes of the max op sized regs involved.
# Calculate unshifted result.
else:
else:
# Hand it over to an overridable worker method.
return self.generateOneStdTestGregGreg(oGen, cbEffOp, cbMaxOp, iOp1, iOp1X, iOp2, iOp2X, uInput, uResult);
def generateOneStdTestGregMemNoSib(self, oGen, cAddrBits, cbEffOp, cbMaxOp, iOp1, iOp2, uInput, uResult):
""" Generate mode 0, 1 and 2 test for the R/M=iOp2. """
if cAddrBits == 16:
_ = cbMaxOp;
else:
iMod = 1;
iMod = 2;
return True;
def generateOneStdTestGregMemSib(self, oGen, cAddrBits, cbEffOp, cbMaxOp, iOp1, iMod, # pylint: disable=R0913
""" Generate one SIB variations. """
if iIndexReg == 4:
if cAddrBits == 64:
continue; # skipping.
else:
self.writeInstrGregSibScaledReg(cbEffOp, iOp1, cAddrBits, iBaseReg, iIndexReg, iScale, offDisp, oGen);
else:
if iIndexReg == 4:
else:
else: offDisp -= 1;
self.writeInstrGregSibBaseAndScaledReg(cbEffOp, iOp1, cAddrBits, iBaseReg, iIndexReg, iScale, offDisp, oGen);
_ = cbMaxOp;
return True;
""" Generate all SIB variations for the given iOp1 (reg) value. """
i = oGen.cSibBasePerRun;
while i > 0:
continue;
j = oGen.getSibIndexPerRun();
while j > 0:
continue; # Don't know the high bit of the address ending up the result - skip it for now.
continue; # Don't know the high bit of the address ending up the result - skip it for now.
for _ in oGen.oSibScaleRange:
oGen.newSubTest();
j -= 1;
i -= 1;
return True;
""" Generate standard tests. """
# Parameters.
# Register tests
if True:
continue;
if iOp1 == X86_GREG_xSP:
continue; # Cannot test xSP atm.
continue; # Any REX encoding turns AH,CH,DH,BH regs into SPL,BPL,SIL,DIL.
if iOp2 == X86_GREG_xSP:
continue; # Cannot test xSP atm.
oGen.newSubTest();
if not oGen.oTarget.is8BitHighGReg(cbEffOp, iOp1) and not oGen.oTarget.is8BitHighGReg(cbEffOp, iOp2):
else:
# Memory test.
if True:
continue;
continue; # Cannot test xSP atm.
continue; ## TODO AH,CH,DH,BH
for _ in oGen.oModRmRange:
oGen.newSubTest();
continue; # Don't know the high bit of the address ending up the result - skip it for now.
else:
# SIB - currently only short list of inputs or things may get seriously out of hand.
#break;
#break;
return True;
#oGen.write(' int3\n');
#oGen.write(' int3\n');
return True;
"""
Tests MOV Gv,Ev.
"""
""" Calculates the result of a mov instruction."""
if cbEffOp == 8:
return uInput & UINT64_MAX;
if cbEffOp == 4:
return uInput & UINT32_MAX;
if cbEffOp == 2:
"""
Tests MOVSXD Gv,Ev.
"""
InstrTest_MemOrGreg_2_Greg.__init__(self, 'movsxd Gv,Ev', self.calc_movsxd, acbOpVars = [ 8, 4, 2, ]);
if cbEffOp == 8:
abInstr = [];
else:
assert False;
assert False;
return True;
"""
Calculates the result of a movxsd instruction.
Returns the result value (cbMaxOp sized).
"""
_ = oGen;
if cbEffOp == 2:
return uInput & UINT32_MAX;
class InstrTest_DivIDiv(InstrTestBase):
"""
Tests IDIV and DIV instructions.
"""
if not fIsIDiv:
else
InstrTest_MemOrGreg_2_Greg.__init__(self, 'idiv Gv,Ev', self.calc_idiv, acbOpVars = [ 8, 4, 2, 1 ]);
""" Generates test that causes no exceptions. """
# Parameters.
#auShortInputs = self.generateInputs(cbDefOp, cbMaxOp, oGen);
#auLongInputs = self.generateInputs(cbDefOp, cbMaxOp, oGen, fLong = True);
# Register tests
if True:
continue;
if iOp2 == X86_GREG_xSP:
continue; # Cannot test xSP atm.
#for uInput in (auLongInputs if iOp2 == iLongOp2 else auShortInputs):
# oGen.newSubTest();
# if not oGen.oTarget.is8BitHighGReg(cbEffOp, iOp2):
# uResult = self.fnCalcResult(cbEffOp, uInput, uCur, oGen);
# self.generateOneStdTestGregGreg(oGen, cbEffOp, cbMaxOp, iOp2, iOp2 & 15,
# uInput, uResult);
# else:
# self.generateOneStdTestGregGreg8BitHighPain(oGen, cbEffOp, cbMaxOp, iOp2, uInput);
## Memory test.
#if False:
# for cAddrBits in oGen.oTarget.getAddrModes():
# for cbEffOp in self.acbOpVars:
# if cbEffOp > cbMaxOp:
# continue;
#
# auInputs = auLongInputs if oGen.iModReg == iLongOp1 else auShortInputs;
# for _ in oGen.oModRmRange:
# oGen.iModRm = (oGen.iModRm + 1) % oGen.oTarget.getGRegCount(cAddrBits * 8);
# if oGen.iModRm != 4 or cAddrBits == 16:
# for uInput in auInputs:
# oGen.newSubTest();
# if oGen.iModReg == oGen.iModRm and oGen.iModRm != 5 and oGen.iModRm != 13 and cbEffOp != cbMaxOp:
# continue; # Don't know the high bit of the address ending up the result - skip it for now.
# uResult = self.fnCalcResult(cbEffOp, uInput, oGen.auRegValues[oGen.iModReg & 15], oGen);
# self.generateOneStdTestGregMemNoSib(oGen, cAddrBits, cbEffOp, cbMaxOp,
# oGen.iModReg, oGen.iModRm, uInput, uResult);
# else:
# # SIB - currently only short list of inputs or things may get seriously out of hand.
# self.generateStdTestGregMemSib(oGen, cAddrBits, cbEffOp, cbMaxOp, oGen.iModReg, auShortInputs);
#
return True;
#oGen.write(' int3\n');
#oGen.write(' int3\n');
return True;
""" Returns a register pair. """
return 0;
""" Returns a register pair. """
return 0;
## Instruction Tests.
#InstrTest_Mov_Gv_Ev(),
#InstrTest_MovSxD_Gv_Ev(),
#InstrTest_DivIDiv(fIsIDiv = False),
];
class InstructionTestGen(object):
"""
Instruction Test Generator.
"""
## @name Test size
## @{
ksTestSize_Large = 'large';
ksTestSize_Medium = 'medium';
ksTestSize_Tiny = 'tiny';
## @}
# Calculate the number of output files.
# Fix the known register values.
# Declare state variables used while generating.
# State variables used while generating test convenientely placed here (lazy bird)...
else:
#
# Methods used by instruction tests.
#
""" Writes to the current output file. """
""" Writes a line to the current output file. """
"""
Emits an instruction given as a sequence of bytes values.
"""
def newSubTest(self):
"""
Indicates that a new subtest has started.
"""
return True;
"""
Records the need for a given register checker function, returning its label.
"""
if iReg2 is not None:
if iReg3 is not None:
sName = '%s_%s_%s' % (self.oTarget.asGRegs[iReg1], self.oTarget.asGRegs[iReg2], self.oTarget.asGRegs[iReg3],);
else:
else:
assert iReg3 is None;
else:
return 'Common_Check_' + sName;
def needGRegMemSetup(self, cAddrBits, cbEffOp, iBaseReg = None, offDisp = None, iIndexReg = None, iScale = 1):
"""
Records the need for a given register checker function, returning its label.
"""
if iBaseReg is not None:
if iIndexReg is not None:
if offDisp is not None:
else:
return 'Common_MemSetup_' + sName;
"""
Records the need for a 64-bit constant, returning its label.
These constants are pooled to attempt reduce the size of the whole thing.
"""
else:
return 'g_u64Const_0x%016x' % (uVal, );
"""
Emits a push constant value, taking care of high values on 64-bit hosts.
"""
else:
return True;
"""
Get a set of address dispositions for a given addressing mode.
The alignment restriction is for SIB scaling.
"""
if iMod == 0:
aoffDisp = [ None, ];
elif iMod == 1:
elif iMod == 2:
else: assert False;
return aoffDisp;
"""
The Mod R/M register range varies with the effective operand size, for
8-bit registers we have 4 more.
"""
if cbEffOp == 1:
return self._oModRegRange8;
return self._oModRegRange;
def getSibIndexPerRun(self):
"""
We vary the SIB index test range a little to try cover more operand
combinations and avoid repeating the same ones.
"""
return self._cSibIndexPerRun;
#
# Internal machinery.
#
def _randInitIndexes(self):
"""
Initializes the Mod R/M and SIB state index with random numbers prior
to generating a test.
Note! As with all other randomness and variations we do, we cannot
test all combinations for each and every instruction so we try
get coverage over time.
"""
return True;
"""
Calc a test function name for the given instruction test.
"""
def _generateFileHeader(self, ):
"""
Writes the file header.
Raises exception on trouble.
"""
';; @file %s\n'
'; Autogenerate by %s %s. DO NOT EDIT\n'
';\n'
'\n'
';\n'
'; Headers\n'
';\n'
'%%include "env-%s.mac"\n'
) );
# Target environment specific init stuff.
#
# Global variables.
#
';\n'
'; Globals\n'
';\n');
'VBINSTST_GLOBALNAME_EX g_pvLow16Mem4K, data hidden\n'
' dq 0\n'
'VBINSTST_GLOBALNAME_EX g_pvLow32Mem4K, data hidden\n'
' dq 0\n'
'VBINSTST_GLOBALNAME_EX g_pvMem4K, data hidden\n'
' dq 0\n'
'VBINSTST_GLOBALNAME_EX g_uVBInsTstSubTestIndicator, data hidden\n'
' dd 0\n'
'VBINSTST_BEGINCODE\n'
);
#
# Common functions.
#
# Loading common values.
'VBINSTST_BEGINPROC Common_LoadKnownValues\n'
'%ifdef RT_ARCH_AMD64\n');
if g_asGRegs64NoSp[i]:
for i in range(8):
if g_asGRegs32NoSp[i]:
' ret\n'
'VBINSTST_ENDPROC Common_LoadKnownValues\n'
'\n');
'%ifdef RT_ARCH_AMD64\n');
if g_asGRegs64NoSp[i]:
' je .ok_%u\n'
' push %u ; register number\n'
' push %s ; actual\n'
' push qword [g_u64KnownValue_%s wrt rip] ; expected\n'
' call VBINSTST_NAME(Common_BadValue)\n'
'.ok_%u:\n'
for i in range(8):
if g_asGRegs32NoSp[i]:
' je .ok_%u\n'
' push %u ; register number\n'
' push %s ; actual\n'
' push dword 0x%x ; expected\n'
' call VBINSTST_NAME(Common_BadValue)\n'
'.ok_%u:\n'
' ret\n'
'VBINSTST_ENDPROC Common_CheckKnownValues\n'
'\n');
return True;
"""
Generates the memory setup functions.
"""
# Unpack it.
else: asAddrGRegs = g_asGRegs16;
i = 2;
iBaseReg = None;
sBaseReg = None;
i += 1
i += 1;
sIndexReg = None;
iIndexReg = None;
i += 1;
u32Disp = None;
i += 1;
assert i == len(asParams), 'i=%d len=%d len[i]=%d (%s)' % (i, len(asParams), len(asParams[i]), asParams[i],);
# Find a temporary register.
iTmpReg1 += 1;
# Prologue.
'; cAddrBits=%s cEffOpBits=%s iBaseReg=%s u32Disp=%s iIndexReg=%s iScale=%s\n'
'VBINSTST_BEGINPROC Common_MemSetup_%s\n'
' MY_PUSH_FLAGS\n'
' push %s\n'
# Figure out what to use.
if cEffOpBits == 64:
sDataVar = 'VBINSTST_NAME(g_u64Data)';
elif cEffOpBits == 32:
sDataVar = 'VBINSTST_NAME(g_u32Data)';
elif cEffOpBits == 16:
sDataVar = 'VBINSTST_NAME(g_u16Data)';
else:
sDataVar = 'VBINSTST_NAME(g_u8Data)';
# Special case: reg + reg * [2,4,8]
iTmpReg2 += 1;
' push %s\n'
' push sDX\n'
if cAddrBits == 16:
else:
if u32Disp is not None:
'%if xCB == 2\n'
' push 0\n'
'%endif\n');
' pop sDX\n'); # sTmpReg2 is eff address; sAX is sIndexReg value.
# Note! sTmpReg1 can be xDX and that's no problem now.
if iBaseReg == X86_GREG_xAX:
else:
else:
# Load the value and mem address, storing the value there.
# Note! ASSUMES that the scale and disposition works fine together.
if cAddrBits >= cDefAddrBits:
else:
if cAddrBits == 16:
else:
# Adjust for disposition and scaling.
if u32Disp is not None:
if iIndexReg is not None:
assert iScale == 1;
elif sBaseReg is not None:
if cAddrBits == 64:
' sub %s, %s\n'
' mov %s, %u\n'
sIndexReg, uIdxRegVal, ));
else:
assert cAddrBits == 32;
' sub %s, %#06x\n'
elif iScale == 2:
elif iScale == 4:
elif iScale == 8:
else:
assert iScale == 1;
# Set upper bits that's supposed to be unused.
if cDefAddrBits == 64:
assert cAddrBits == 32;
if iBaseReg is not None:
' or %s, %s\n'
' or %s, %s\n'
else:
if iBaseReg is not None:
# Epilogue.
' MY_POP_FLAGS\n'
' ret sCB\n'
'VBINSTST_ENDPROC Common_MemSetup_%s\n'
def _generateFileFooter(self):
"""
Generates file footer.
"""
# Register checking functions.
sPushSize = 'dword';
# Prologue
'; Checks 1 or more register values, expected values pushed on the stack.\n'
'; To save space, the callee cleans up the stack.'
'; Ref count: %u\n'
'VBINSTST_BEGINPROC Common_Check_%s\n'
' MY_PUSH_FLAGS\n'
# Register checks.
' je .equal%u\n'
' push %s %u ; register number\n'
' push %s ; actual\n'
' mov %s, [xSP + sCB*2 + MY_PUSH_FLAGS_SIZE + xCB]\n'
' push %s ; expected\n'
' call VBINSTST_NAME(Common_BadValue)\n'
'.equal%u:\n'
# Restore known register values and check the other registers.
else:
' call VBINSTST_NAME(Common_CheckKnownValues)\n'
' ret sCB*%u\n'
'VBINSTST_ENDPROC Common_Check_%s\n'
# memory setup functions
# 64-bit constants.
';\n'
'; 64-bit constants\n'
';\n');
self.write('g_u64Const_0x%016x: dq 0x%016x ; Ref count: %d\n' % (uVal, uVal, self._d64BitConsts[uVal], ) );
return True;
def _generateTests(self):
"""
Generate the test cases.
"""
else:
# Calc the range.
# Generate the instruction tests.
'\n'
';\n'
'; %s\n'
';\n'
% (oInstrTest.sName,));
# Generate the main function.
'VBINSTST_BEGINPROC TestInstrMain\n'
' MY_PUSH_ALL\n'
' sub xSP, 40h\n'
'\n');
' lea rdi, [.szInstr%03u wrt rip]\n'
'%%elifdef ASM_CALL64_MSC\n'
' lea rcx, [.szInstr%03u wrt rip]\n'
'%%else\n'
' mov xAX, .szInstr%03u\n'
' mov [xSP], xAX\n'
'%%endif\n'
' VBINSTST_CALL_FN_SUB_TEST\n'
' call VBINSTST_NAME(%s)\n'
' add xSP, 40h\n'
' MY_POP_ALL\n'
' ret\n\n');
return RTEXITCODE_SUCCESS;
def _runMakefileMode(self):
"""
Generate a list of output files on standard output.
"""
else:
return RTEXITCODE_SUCCESS;
"""
Generates the tests or whatever is required.
"""
return self._runMakefileMode();
return self._generateTests();
def main():
"""
Main function a la C/C++. Returns exit code.
"""
#
# Parse the command line.
#
oParser.add_option('--makefile-mode', dest = 'fMakefileMode', action = 'store_true', default = False,
help = 'Special mode for use to output a list of output files for the benefit of '
'the make program (kmk).');
oParser.add_option('--split', dest = 'cInstrPerFile', metavar = '<instr-per-file>', type = 'int', default = 9999999,
help = 'Number of instruction to test per output file.');
help = 'The output file base name, no suffix please. Required.');
default = 'iprt-r3-32',
help = 'The target environment. Choices: %s'
oParser.add_option('--test-size', dest = 'sTestSize', default = InstructionTestGen.ksTestSize_Medium,
help = 'Selects the test size.');
return RTEXITCODE_SYNTAX
if oOptions.sOutputBase is None:
return RTEXITCODE_SYNTAX
#
# Instantiate the program class and run it.
#
if __name__ == '__main__':