InstructionTestGen.py revision 51ef69064b4ea4d571ed129ab883b0c08967c901
# -*- 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 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 getGRegCount(self):
""" Get the number of general registers. """
return 16;
return 8;
## Target environments.
g_dTargetEnvs = {
};
"""
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;
"""
Instruction reading memory or general register and writing the result to a
general register.
"""
""" Generate a list of inputs. """
# Fixed ranges.
if cbEffOp == 1:
elif cbEffOp == 2:
elif cbEffOp == 4:
elif cbEffOp == 8:
else:
assert False;
# Append some random values as well.
return auRet;
""" Writes the instruction with two general registers as operands. """
if cbEffOp == 8:
elif cbEffOp == 4:
elif cbEffOp == 2:
else:
assert False;
return True;
""" Generate one standard test. """
return True;
""" Generate standard tests. """
continue;
continue;
continue;
uResult = self.fnCalcResult(cbEffOp, uInput, oGen.auRegValues[iOp1] if iOp1 != iOp2 else uInput, oGen);
oGen.newSubTest();
return True;
#oGen.write(' int3\n');
#oGen.write(' int3\n');
return True;
"""
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.
];
class InstructionTestGen(object):
"""
Instruction Test Generator.
"""
# 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 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_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;
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'
# 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'
return RTEXITCODE_SYNTAX
if oOptions.sOutputBase is None:
return RTEXITCODE_SYNTAX
#
# Instantiate the program class and run it.
#
if __name__ == '__main__':