InstructionTestGen.py revision bec4d1c0274e4712fe01426313aab120b5ad1c17
# -*- 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 Misc
## @{
def convU32ToSigned(u32):
""" Converts a 32-bit unsigned value to 32-bit signed. """
if u32 < 0x80000000:
return u32;
## @}
## @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 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');
## @}
## @name Random
## @{
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 nsigned 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:
if iRm >= 8:
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,];
## @}
"""
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. """
def getGRegCount(self):
""" Get the number of general registers. """
return 16;
return 8;
def randGRegNoSp(self):
""" Returns a random general register number, excluding the SP register. """
def getAddrModes(self):
return [16, 32];
return [32, 16];
return [64, 64];
## 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.
"""
""" Writes the instruction with two general registers as operands. """
if cbEffOp == 8:
elif cbEffOp == 4:
elif cbEffOp == 2:
elif cbEffOp == 1:
else:
assert False;
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;
""" Generate one standard test. """
_ = cbMaxOp;
return True;
""" Sets up memory for a pure R/M addressed read, iOp2 being the R/M value. """
else:
## @todo generate REX.B=1 variant.
return True;
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;
""" Generate standard tests. """
# Parameters.
oOp1MemRange = [iLongOp1,];
# Register tests
if False:
continue;
continue;
continue;
oGen.newSubTest();
# Memory test.
continue;
for iOp1 in oOp1MemRange:
continue;
if iOp2 != 4:
oGen.newSubTest();
continue; # Don't know the high bit of the address ending up the result - skip it.
else:
pass; # SIB
break; ## remove me!
#break; ## remove me!
#break; ## remove me!
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;
## Instruction Tests.
#InstrTest_MovSxD_Gv_Ev(),
];
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.
#
# 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.
"""
else:
"""
Records the need for a given register checker function, returning its label.
"""
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;
#
# Internal machinery.
#
"""
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 = 3;
u32Disp = None;
i += 1;
sIndexReg = None;
iIndexReg = None;
i += 1;
iScale = 1;
i += 1;
assert i == len(asParams), 'i=%d len=%d len[i]=%d (%s)' % (i, len(asParams), len(asParams[i]), asParams[i],);
# Prologue.
'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:
assert cEffOpBits == 8;
sDataVar = 'VBINSTST_NAME(g_u8Data)';
# Load the value and mem address, sorting the value there.
if cAddrBits >= cDefAddrBits:
else:
if cAddrBits == 16:
else:
# Adjust for disposition and scaling.
if u32Disp is not None:
if iIndexReg is not None:
if cAddrBits == 64:
elif cAddrBits == 16:
else:
assert cAddrBits == 16;
# Set upper bits that's supposed to be unused.
if cDefAddrBits == 64:
assert cAddrBits == 32;
' or %s, %s\n'
if iIndexReg is not None:
' or %s, %s\n'
else:
if iIndexReg 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';
'; Checks two 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_%s\n'
' MY_PUSH_FLAGS\n'
' je .equal1\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'
' pop %s\n'
' pop %s\n'
' pop %s\n'
'.equal1:\n'
' je .equal2\n'
' push %s %u ; register number\n'
' push %s ; actual\n'
' mov %s, [xSP + sCB*3 + MY_PUSH_FLAGS_SIZE + xCB]\n'
' push %s ; expected\n'
' call VBINSTST_NAME(Common_BadValue)\n'
' pop %s\n'
' pop %s\n'
' pop %s\n'
'.equal2:\n'
else:
' call VBINSTST_NAME(Common_CheckKnownValues)\n'
' ret sCB*2\n'
'VBINSTST_ENDPROC Common_Check_%s_%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__':