VirtualBox

source: vbox/trunk/src/VBox/VMM/testcase/Instructions/InstructionTestGen.py@ 46554

Last change on this file since 46554 was 46554, checked in by vboxsync, 11 years ago

Test size control, better inputs.

  • Property svn:eol-style set to LF
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 31.0 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# $Id: InstructionTestGen.py 46554 2013-06-14 12:29:38Z vboxsync $
4
5"""
6Instruction Test Generator.
7"""
8
9from __future__ import print_function;
10
11__copyright__ = \
12"""
13Copyright (C) 2012-2013 Oracle Corporation
14
15Oracle Corporation confidential
16All rights reserved
17"""
18__version__ = "$Revision: 46554 $";
19
20
21# Standard python imports.
22import io;
23import os;
24from optparse import OptionParser
25import random;
26import sys;
27
28
29## @name Exit codes
30## @{
31RTEXITCODE_SUCCESS = 0;
32RTEXITCODE_SYNTAX = 2;
33## @}
34
35## @name Various C macros we're used to.
36## @{
37UINT8_MAX = 0xff
38UINT16_MAX = 0xffff
39UINT32_MAX = 0xffffffff
40UINT64_MAX = 0xffffffffffffffff
41def RT_BIT_32(iBit): # pylint: disable=C0103
42 """ 32-bit one bit mask. """
43 return 1 << iBit;
44def RT_BIT_64(iBit): # pylint: disable=C0103
45 """ 64-bit one bit mask. """
46 return 1 << iBit;
47## @}
48
49
50## @name ModR/M
51## @{
52X86_MODRM_RM_MASK = 0x07;
53X86_MODRM_REG_MASK = 0x38;
54X86_MODRM_REG_SMASK = 0x07;
55X86_MODRM_REG_SHIFT = 3;
56X86_MODRM_MOD_MASK = 0xc0;
57X86_MODRM_MOD_SMASK = 0x03;
58X86_MODRM_MOD_SHIFT = 6;
59## @}
60
61## @name SIB
62## @{
63X86_SIB_BASE_MASK = 0x07;
64X86_SIB_INDEX_MASK = 0x38;
65X86_SIB_INDEX_SMASK = 0x07;
66X86_SIB_INDEX_SHIFT = 3;
67X86_SIB_SCALE_MASK = 0xc0;
68X86_SIB_SCALE_SMASK = 0x03;
69X86_SIB_SCALE_SHIFT = 6;
70## @}
71
72## @name PRefixes
73## @
74X86_OP_PRF_CS = 0x2e;
75X86_OP_PRF_SS = 0x36;
76X86_OP_PRF_DS = 0x3e;
77X86_OP_PRF_ES = 0x26;
78X86_OP_PRF_FS = 0x64;
79X86_OP_PRF_GS = 0x65;
80X86_OP_PRF_SIZE_OP = 0x66;
81X86_OP_PRF_SIZE_ADDR = 0x67;
82X86_OP_PRF_LOCK = 0xf0;
83X86_OP_PRF_REPZ = 0xf2;
84X86_OP_PRF_REPNZ = 0xf3;
85X86_OP_REX_B = 0x41;
86X86_OP_REX_X = 0x42;
87X86_OP_REX_R = 0x44;
88X86_OP_REX_W = 0x48;
89## @}
90
91
92## @name Register names.
93## @{
94g_asGRegs64NoSp = ('rax', 'rcx', 'rdx', 'rbx', None, 'rbp', 'rsi', 'rdi', 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15');
95g_asGRegs64 = ('rax', 'rcx', 'rdx', 'rbx', 'rsp', 'rbp', 'rsi', 'rdi', 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15');
96g_asGRegs32NoSp = ('eax', 'ecx', 'edx', 'ebx', None, 'ebp', 'esi', 'edi',
97 'r8d', 'r9d', 'r10d', 'r11d', 'r12d', 'r13d', 'r14d', 'r15d');
98g_asGRegs32 = ('eax', 'ecx', 'edx', 'ebx', 'esp', 'ebp', 'esi', 'edi',
99 'r8d', 'r9d', 'r10d', 'r11d', 'r12d', 'r13d', 'r14d', 'r15d');
100g_asGRegs16NoSp = ('ax', 'cx', 'dx', 'bx', None, 'bp', 'si', 'di',
101 'r8w', 'r9w', 'r10w', 'r11w', 'r12w', 'r13w', 'r14w', 'r15w');
102g_asGRegs16 = ('ax', 'cx', 'dx', 'bx', 'sp', 'bp', 'si', 'di',
103 'r8w', 'r9w', 'r10w', 'r11w', 'r12w', 'r13w', 'r14w', 'r15w');
104g_asGRegs8 = ('al', 'cl', 'dl', 'bl', 'ah', 'ah', 'dh', 'bh');
105g_asGRegs8_64 = ('al', 'cl', 'dl', 'bl', 'spl', 'bpl', 'sil', 'dil', # pylint: disable=C0103
106 'r8b', 'r9b', 'r10b', 'r11b', 'r12b', 'r13b', 'r14b', 'r15b');
107## @}
108
109
110## @name Random
111## @{
112g_oMyRand = random.SystemRandom()
113def randU16():
114 """ Unsigned 16-bit random number. """
115 return g_oMyRand.getrandbits(16);
116
117def randU32():
118 """ Unsigned 32-bit random number. """
119 return g_oMyRand.getrandbits(32);
120
121def randU64():
122 """ Unsigned 64-bit random number. """
123 return g_oMyRand.getrandbits(64);
124
125def randUxx(cBits):
126 """ Unsigned 8-, 16-, 32-, or 64-bit random number. """
127 return g_oMyRand.getrandbits(cBits);
128
129def randUxxList(cBits, cElements):
130 """ List of nsigned 8-, 16-, 32-, or 64-bit random numbers. """
131 return [randUxx(cBits) for _ in range(cElements)];
132## @}
133
134
135
136## @name Instruction Emitter Helpers
137## @{
138
139def calcRexPrefixForTwoModRmRegs(iReg, iRm, bOtherRexPrefixes = 0):
140 """
141 Calculates a rex prefix if neccessary given the two registers
142 and optional rex size prefixes.
143 Returns an empty array if not necessary.
144 """
145 bRex = bOtherRexPrefixes;
146 if iReg >= 8:
147 bRex = bRex | X86_OP_REX_R;
148 if iRm >= 8:
149 bRex = bRex | X86_OP_REX_B;
150 if bRex == 0:
151 return [];
152 return [bRex,];
153
154def calcModRmForTwoRegs(iReg, iRm):
155 """
156 Calculate the RM byte for two registers.
157 Returns an array with one byte in it.
158 """
159 bRm = (0x3 << X86_MODRM_MOD_SHIFT) \
160 | ((iReg << X86_MODRM_REG_SHIFT) & X86_MODRM_REG_MASK) \
161 | (iRm & X86_MODRM_RM_MASK);
162 return [bRm,];
163
164## @}
165
166
167class TargetEnv(object):
168 """
169 Target Runtime Environment.
170 """
171
172 ## @name CPU Modes
173 ## @{
174 ksCpuMode_Real = 'real';
175 ksCpuMode_Protect = 'prot';
176 ksCpuMode_Paged = 'paged';
177 ksCpuMode_Long = 'long';
178 ksCpuMode_V86 = 'v86';
179 ## @}
180
181 ## @name Instruction set.
182 ## @{
183 ksInstrSet_16 = '16';
184 ksInstrSet_32 = '32';
185 ksInstrSet_64 = '64';
186 ## @}
187
188 def __init__(self, sName,
189 sInstrSet = ksInstrSet_32,
190 sCpuMode = ksCpuMode_Paged,
191 iRing = 3,
192 ):
193 self.sName = sName;
194 self.sInstrSet = sInstrSet;
195 self.sCpuMode = sCpuMode;
196 self.iRing = iRing;
197 self.asGRegs = g_asGRegs64 if self.is64Bit() else g_asGRegs32;
198 self.asGRegsNoSp = g_asGRegs64NoSp if self.is64Bit() else g_asGRegs32NoSp;
199
200 def isUsingIprt(self):
201 """ Whether it's an IPRT environment or not. """
202 return self.sName.startswith('iprt');
203
204 def is64Bit(self):
205 """ Whether it's a 64-bit environment or not. """
206 return self.sInstrSet == self.ksInstrSet_64;
207
208 def getDefOpBits(self):
209 """ Get the default operand size as a bit count. """
210 if self.sInstrSet == self.ksInstrSet_16:
211 return 16;
212 return 32;
213
214 def getDefOpBytes(self):
215 """ Get the default operand size as a byte count. """
216 return self.getDefOpBits() / 8;
217
218 def getMaxOpBits(self):
219 """ Get the max operand size as a bit count. """
220 if self.sInstrSet == self.ksInstrSet_64:
221 return 64;
222 return 32;
223
224 def getMaxOpBytes(self):
225 """ Get the max operand size as a byte count. """
226 return self.getMaxOpBits() / 8;
227
228 def getGRegCount(self):
229 """ Get the number of general registers. """
230 if self.sInstrSet == self.ksInstrSet_64:
231 return 16;
232 return 8;
233
234 def randGRegNoSp(self):
235 """ Returns a random general register number, excluding the SP register. """
236 iReg = randU16();
237 return iReg % (16 if self.is64Bit() else 8);
238
239
240
241## Target environments.
242g_dTargetEnvs = {
243 'iprt-r3-32': TargetEnv('iprt-r3-32', TargetEnv.ksInstrSet_32, TargetEnv.ksCpuMode_Protect, 3),
244 'iprt-r3-64': TargetEnv('iprt-r3-64', TargetEnv.ksInstrSet_64, TargetEnv.ksCpuMode_Long, 3),
245};
246
247
248class InstrTestBase(object): # pylint: disable=R0903
249 """
250 Base class for testing one instruction.
251 """
252
253 def __init__(self, sName, sInstr = None):
254 self.sName = sName;
255 self.sInstr = sInstr if sInstr else sName.split()[0];
256
257 def isApplicable(self, oGen):
258 """
259 Tests if the instruction test is applicable to the selected environment.
260 """
261 _ = oGen;
262 return True;
263
264 def generateTest(self, oGen, sTestFnName):
265 """
266 Emits the test assembly code.
267 """
268 oGen.write(';; @todo not implemented. This is for the linter: %s, %s\n' % (oGen, sTestFnName));
269 return True;
270
271
272class InstrTest_MemOrGreg_2_Greg(InstrTestBase):
273 """
274 Instruction reading memory or general register and writing the result to a
275 general register.
276 """
277
278 def __init__(self, sName, fnCalcResult, sInstr = None, acbOpVars = None):
279 InstrTestBase.__init__(self, sName, sInstr);
280 self.fnCalcResult = fnCalcResult;
281 self.acbOpVars = [ 1, 2, 4, 8 ] if not acbOpVars else list(acbOpVars);
282
283 def generateInputs(self, cbEffOp, cbMaxOp, oGen, fLong = False):
284 """ Generate a list of inputs. """
285 if fLong:
286 #
287 # Try do extremes as well as different ranges of random numbers.
288 #
289 auRet = [0, 1, ];
290 if cbMaxOp >= 1:
291 auRet += [ UINT8_MAX / 2, UINT8_MAX / 2 + 1, UINT8_MAX ];
292 if cbMaxOp >= 2:
293 auRet += [ UINT16_MAX / 2, UINT16_MAX / 2 + 1, UINT16_MAX ];
294 if cbMaxOp >= 4:
295 auRet += [ UINT32_MAX / 2, UINT32_MAX / 2 + 1, UINT32_MAX ];
296 if cbMaxOp >= 8:
297 auRet += [ UINT64_MAX / 2, UINT64_MAX / 2 + 1, UINT64_MAX ];
298
299 if oGen.oOptions.sTestSize == InstructionTestGen.ksTestSize_Tiny:
300 for cBits, cValues in ( (8, 4), (16, 4), (32, 8), (64, 8) ):
301 if cBits < cbMaxOp * 8:
302 auRet += randUxxList(cBits, cValues);
303 cWanted = 16;
304 elif oGen.oOptions.sTestSize == InstructionTestGen.ksTestSize_Medium:
305 for cBits, cValues in ( (8, 8), (16, 8), (24, 2), (32, 16), (40, 1), (48, 1), (56, 1), (64, 16) ):
306 if cBits < cbMaxOp * 8:
307 auRet += randUxxList(cBits, cValues);
308 cWanted = 64;
309 else:
310 for cBits, cValues in ( (8, 16), (16, 16), (24, 4), (32, 64), (40, 4), (48, 4), (56, 4), (64, 64) ):
311 if cBits < cbMaxOp * 8:
312 auRet += randUxxList(cBits, cValues);
313 cWanted = 168;
314 if len(auRet) < cWanted:
315 auRet += randUxxList(cbEffOp * 8, cWanted - len(auRet));
316 else:
317 #
318 # Short list, just do some random numbers.
319 #
320 auRet = [];
321 if oGen.oOptions.sTestSize == InstructionTestGen.ksTestSize_Tiny:
322 auRet += randUxxList(cbMaxOp, 1);
323 elif oGen.oOptions.sTestSize == InstructionTestGen.ksTestSize_Medium:
324 auRet += randUxxList(cbMaxOp, 2);
325 else:
326 auRet = [];
327 for cBits in (8, 16, 32, 64):
328 if cBits < cbMaxOp * 8:
329 auRet += randUxxList(cBits, 1);
330 return auRet;
331
332 def writeInstrGregGreg(self, cbEffOp, iOp1, iOp2, oGen):
333 """ Writes the instruction with two general registers as operands. """
334 if cbEffOp == 8:
335 iOp2 = iOp2 % len(g_asGRegs32);
336 oGen.write(' %s %s, %s\n' % (self.sInstr, g_asGRegs64[iOp1], g_asGRegs32[iOp2]));
337 elif cbEffOp == 4:
338 oGen.write(' %s %s, %s\n' % (self.sInstr, g_asGRegs32[iOp1], g_asGRegs16[iOp2]));
339 elif cbEffOp == 2:
340 oGen.write(' %s %s, %s\n' % (self.sInstr, g_asGRegs16[iOp1], g_asGRegs8[iOp2]));
341 else:
342 assert False;
343 return True;
344
345 def generateOneStdTest(self, oGen, cbEffOp, cbMaxOp, iOp1, iOp2, uInput, uResult):
346 """ Generate one standard test. """
347 oGen.write(' call VBINSTST_NAME(Common_LoadKnownValues)\n');
348 oGen.write(' mov %s, 0x%x\n' % (oGen.oTarget.asGRegs[iOp2], uInput,));
349 oGen.write(' push %s\n' % (oGen.oTarget.asGRegs[iOp2],));
350 self.writeInstrGregGreg(cbEffOp, iOp1, iOp2, oGen);
351 oGen.pushConst(uResult, cbMaxOp);
352 oGen.write(' call VBINSTST_NAME(%s)\n' % (oGen.needGRegChecker(iOp1, iOp2),));
353 return True;
354
355 def generateStandardTests(self, oGen):
356 """ Generate standard tests. """
357
358 # Parameters.
359 cbDefOp = oGen.oTarget.getDefOpBytes();
360 cbMaxOp = oGen.oTarget.getMaxOpBytes();
361 auShortInputs = self.generateInputs(cbDefOp, cbMaxOp, oGen);
362 auLongInputs = self.generateInputs(cbDefOp, cbMaxOp, oGen, fLong = True);
363 iLongOp1 = oGen.oTarget.randGRegNoSp();
364 iLongOp2 = oGen.oTarget.randGRegNoSp();
365 oOp2Range = range(oGen.oTarget.getGRegCount());
366 if oGen.oOptions.sTestSize == InstructionTestGen.ksTestSize_Tiny:
367 oOp2Range = [iLongOp2,];
368
369 # Register tests.
370 for cbEffOp in self.acbOpVars:
371 if cbEffOp > cbMaxOp:
372 continue;
373 for iOp1 in range(oGen.oTarget.getGRegCount()):
374 if oGen.oTarget.asGRegsNoSp[iOp1] is None:
375 continue;
376 for iOp2 in oOp2Range:
377 if oGen.oTarget.asGRegsNoSp[iOp2] is None:
378 continue;
379 for uInput in (auLongInputs if iOp1 == iLongOp1 and iOp2 == iLongOp2 else auShortInputs):
380 uResult = self.fnCalcResult(cbEffOp, uInput, oGen.auRegValues[iOp1] if iOp1 != iOp2 else uInput, oGen);
381 oGen.newSubTest();
382 self.generateOneStdTest(oGen, cbEffOp, cbMaxOp, iOp1, iOp2, uInput, uResult);
383
384 return True;
385
386 def generateTest(self, oGen, sTestFnName):
387 oGen.write('VBINSTST_BEGINPROC %s\n' % (sTestFnName,));
388 #oGen.write(' int3\n');
389
390 self.generateStandardTests(oGen);
391
392 #oGen.write(' int3\n');
393 oGen.write(' ret\n');
394 oGen.write('VBINSTST_ENDPROC %s\n' % (sTestFnName,));
395 return True;
396
397
398class InstrTest_MovSxD_Gv_Ev(InstrTest_MemOrGreg_2_Greg):
399 """
400 Tests MOVSXD Gv,Ev.
401 """
402 def __init__(self):
403 InstrTest_MemOrGreg_2_Greg.__init__(self, 'movsxd Gv,Ev', self.calc_movsxd, acbOpVars = [ 8, 4, 2, ]);
404
405 def writeInstrGregGreg(self, cbEffOp, iOp1, iOp2, oGen):
406 if cbEffOp == 8:
407 oGen.write(' %s %s, %s\n' % (self.sInstr, g_asGRegs64[iOp1], g_asGRegs32[iOp2]));
408 elif cbEffOp == 4 or cbEffOp == 2:
409 abInstr = [];
410 if cbEffOp != oGen.oTarget.getDefOpBytes():
411 abInstr.append(X86_OP_PRF_SIZE_OP);
412 abInstr += calcRexPrefixForTwoModRmRegs(iOp1, iOp2);
413 abInstr.append(0x63);
414 abInstr += calcModRmForTwoRegs(iOp1, iOp2);
415 oGen.writeInstrBytes(abInstr);
416 else:
417 assert False;
418 assert False;
419 return True;
420
421 def isApplicable(self, oGen):
422 return oGen.oTarget.is64Bit();
423
424 @staticmethod
425 def calc_movsxd(cbEffOp, uInput, uCur, oGen):
426 """
427 Calculates the result of a movxsd instruction.
428 Returns the result value (cbMaxOp sized).
429 """
430 _ = oGen;
431 if cbEffOp == 8 and (uInput & RT_BIT_32(31)):
432 return (UINT32_MAX << 32) | (uInput & UINT32_MAX);
433 if cbEffOp == 2:
434 return (uCur & 0xffffffffffff0000) | (uInput & 0xffff);
435 return uInput & UINT32_MAX;
436
437
438## Instruction Tests.
439g_aoInstructionTests = [
440 InstrTest_MovSxD_Gv_Ev(),
441];
442
443
444class InstructionTestGen(object):
445 """
446 Instruction Test Generator.
447 """
448
449 ## @name Test size
450 ## @{
451 ksTestSize_Large = 'large';
452 ksTestSize_Medium = 'medium';
453 ksTestSize_Tiny = 'tiny';
454 ## @}
455 kasTestSizes = ( ksTestSize_Large, ksTestSize_Medium, ksTestSize_Tiny );
456
457
458
459 def __init__(self, oOptions):
460 self.oOptions = oOptions;
461 self.oTarget = g_dTargetEnvs[oOptions.sTargetEnv];
462
463 # Calculate the number of output files.
464 self.cFiles = 1;
465 if len(g_aoInstructionTests) > self.oOptions.cInstrPerFile:
466 self.cFiles = len(g_aoInstructionTests) / self.oOptions.cInstrPerFile;
467 if self.cFiles * self.oOptions.cInstrPerFile < len(g_aoInstructionTests):
468 self.cFiles += 1;
469
470 # Fix the known register values.
471 self.au64Regs = randUxxList(64, 16);
472 self.au32Regs = [(self.au64Regs[i] & UINT32_MAX) for i in range(8)];
473 self.au16Regs = [(self.au64Regs[i] & UINT16_MAX) for i in range(8)];
474 self.auRegValues = self.au64Regs if self.oTarget.is64Bit() else self.au32Regs;
475
476 # Declare state variables used while generating.
477 self.oFile = sys.stderr;
478 self.iFile = -1;
479 self.sFile = '';
480 self.dCheckFns = dict();
481 self.d64BitConsts = dict();
482
483
484 #
485 # Methods used by instruction tests.
486 #
487
488 def write(self, sText):
489 """ Writes to the current output file. """
490 return self.oFile.write(unicode(sText));
491
492 def writeln(self, sText):
493 """ Writes a line to the current output file. """
494 self.write(sText);
495 return self.write('\n');
496
497 def writeInstrBytes(self, abInstr):
498 """
499 Emits an instruction given as a sequence of bytes values.
500 """
501 self.write(' db %#04x' % (abInstr[0],));
502 for i in range(1, len(abInstr)):
503 self.write(', %#04x' % (abInstr[i],));
504 return self.write('\n');
505
506 def newSubTest(self):
507 """
508 Indicates that a new subtest has started.
509 """
510 self.write(' mov dword [VBINSTST_NAME(g_uVBInsTstSubTestIndicator) xWrtRIP], __LINE__\n');
511 return True;
512
513 def needGRegChecker(self, iReg1, iReg2):
514 """
515 Records the need for a given register checker function, returning its label.
516 """
517 assert iReg1 < 32; assert iReg2 < 32;
518 iRegs = iReg1 + iReg2 * 32;
519 if iRegs in self.dCheckFns:
520 self.dCheckFns[iRegs] += 1;
521 else:
522 self.dCheckFns[iRegs] = 1;
523 return 'Common_Check_%s_%s' % (self.oTarget.asGRegs[iReg1], self.oTarget.asGRegs[iReg2]);
524
525 def need64BitConstant(self, uVal):
526 """
527 Records the need for a 64-bit constant, returning its label.
528 These constants are pooled to attempt reduce the size of the whole thing.
529 """
530 assert uVal >= 0 and uVal <= UINT64_MAX;
531 if uVal in self.d64BitConsts:
532 self.d64BitConsts[uVal] += 1;
533 else:
534 self.d64BitConsts[uVal] = 1;
535 return 'g_u64Const_0x%016x' % (uVal, );
536
537 def pushConst(self, uResult, cbMaxOp):
538 """
539 Emits a push constant value, taking care of high values on 64-bit hosts.
540 """
541 if cbMaxOp == 8 and uResult >= 0x80000000:
542 self.write(' push qword [%s wrt rip]\n' % (self.need64BitConstant(uResult),));
543 else:
544 self.write(' push dword 0x%x\n' % (uResult,));
545 return True;
546
547
548 #
549 # Internal machinery.
550 #
551
552 def _calcTestFunctionName(self, oInstrTest, iInstrTest):
553 """
554 Calc a test function name for the given instruction test.
555 """
556 sName = 'TestInstr%03u_%s' % (iInstrTest, oInstrTest.sName);
557 return sName.replace(',', '_').replace(' ', '_').replace('%', '_');
558
559 def _generateFileHeader(self, ):
560 """
561 Writes the file header.
562 Raises exception on trouble.
563 """
564 self.write('; $Id: InstructionTestGen.py 46554 2013-06-14 12:29:38Z vboxsync $\n'
565 ';; @file %s\n'
566 '; Autogenerate by %s %s. DO NOT EDIT\n'
567 ';\n'
568 '\n'
569 ';\n'
570 '; Headers\n'
571 ';\n'
572 '%%include "env-%s.mac"\n'
573 % ( os.path.basename(self.sFile),
574 os.path.basename(__file__), __version__[11:-1],
575 self.oTarget.sName,
576 ) );
577 # Target environment specific init stuff.
578
579 #
580 # Global variables.
581 #
582 self.write('\n\n'
583 ';\n'
584 '; Globals\n'
585 ';\n');
586 self.write('VBINSTST_BEGINDATA\n'
587 'VBINSTST_GLOBALNAME_EX g_uVBInsTstSubTestIndicator, data hidden\n'
588 ' dd 0\n'
589 'VBINSTST_BEGINCODE\n'
590 );
591 self.write('%ifdef RT_ARCH_AMD64\n');
592 for i in range(len(g_asGRegs64)):
593 self.write('g_u64KnownValue_%s: dq 0x%x\n' % (g_asGRegs64[i], self.au64Regs[i]));
594 self.write('%endif\n\n')
595
596 #
597 # Common functions.
598 #
599
600 # Loading common values.
601 self.write('\n\n'
602 'VBINSTST_BEGINPROC Common_LoadKnownValues\n'
603 '%ifdef RT_ARCH_AMD64\n');
604 for i in range(len(g_asGRegs64NoSp)):
605 if g_asGRegs64NoSp[i]:
606 self.write(' mov %s, 0x%x\n' % (g_asGRegs64NoSp[i], self.au64Regs[i],));
607 self.write('%else\n');
608 for i in range(8):
609 if g_asGRegs32NoSp[i]:
610 self.write(' mov %s, 0x%x\n' % (g_asGRegs32NoSp[i], self.au32Regs[i],));
611 self.write('%endif\n'
612 ' ret\n'
613 'VBINSTST_ENDPROC Common_LoadKnownValues\n'
614 '\n');
615
616 self.write('VBINSTST_BEGINPROC Common_CheckKnownValues\n'
617 '%ifdef RT_ARCH_AMD64\n');
618 for i in range(len(g_asGRegs64NoSp)):
619 if g_asGRegs64NoSp[i]:
620 self.write(' cmp %s, [g_u64KnownValue_%s wrt rip]\n'
621 ' je .ok_%u\n'
622 ' push %u ; register number\n'
623 ' push %s ; actual\n'
624 ' push qword [g_u64KnownValue_%s wrt rip] ; expected\n'
625 ' call VBINSTST_NAME(Common_BadValue)\n'
626 '.ok_%u:\n'
627 % ( g_asGRegs64NoSp[i], g_asGRegs64NoSp[i], i, i, g_asGRegs64NoSp[i], g_asGRegs64NoSp[i], i,));
628 self.write('%else\n');
629 for i in range(8):
630 if g_asGRegs32NoSp[i]:
631 self.write(' cmp %s, 0x%x\n'
632 ' je .ok_%u\n'
633 ' push %u ; register number\n'
634 ' push %s ; actual\n'
635 ' push dword 0x%x ; expected\n'
636 ' call VBINSTST_NAME(Common_BadValue)\n'
637 '.ok_%u:\n'
638 % ( g_asGRegs32NoSp[i], self.au32Regs[i], i, i, g_asGRegs32NoSp[i], self.au32Regs[i], i,));
639 self.write('%endif\n'
640 ' ret\n'
641 'VBINSTST_ENDPROC Common_CheckKnownValues\n'
642 '\n');
643
644 return True;
645
646 def _generateFileFooter(self):
647 """
648 Generates file footer.
649 """
650
651 # Register checking functions.
652 for iRegs in self.dCheckFns:
653 iReg1 = iRegs & 0x1f;
654 sReg1 = self.oTarget.asGRegs[iReg1];
655 iReg2 = (iRegs >> 5) & 0x1f;
656 sReg2 = self.oTarget.asGRegs[iReg2];
657 sPushSize = 'dword';
658
659 self.write('\n\n'
660 '; Checks two register values, expected values pushed on the stack.\n'
661 '; To save space, the callee cleans up the stack.'
662 '; Ref count: %u\n'
663 'VBINSTST_BEGINPROC Common_Check_%s_%s\n'
664 ' MY_PUSH_FLAGS\n'
665 % ( self.dCheckFns[iRegs], sReg1, sReg2, ) );
666
667 self.write(' cmp %s, [xSP + MY_PUSH_FLAGS_SIZE + xCB]\n'
668 ' je .equal1\n'
669 ' push %s %u ; register number\n'
670 ' push %s ; actual\n'
671 ' mov %s, [xSP + sCB*2 + MY_PUSH_FLAGS_SIZE + xCB]\n'
672 ' push %s ; expected\n'
673 ' call VBINSTST_NAME(Common_BadValue)\n'
674 ' pop %s\n'
675 ' pop %s\n'
676 ' pop %s\n'
677 '.equal1:\n'
678 % ( sReg1, sPushSize, iReg1, sReg1, sReg1, sReg1, sReg1, sReg1, sReg1, ) );
679 if iReg1 != iReg2: # If input and result regs are the same, only check the result.
680 self.write(' cmp %s, [xSP + sCB + MY_PUSH_FLAGS_SIZE + xCB]\n'
681 ' je .equal2\n'
682 ' push %s %u ; register number\n'
683 ' push %s ; actual\n'
684 ' mov %s, [xSP + sCB*3 + MY_PUSH_FLAGS_SIZE + xCB]\n'
685 ' push %s ; expected\n'
686 ' call VBINSTST_NAME(Common_BadValue)\n'
687 ' pop %s\n'
688 ' pop %s\n'
689 ' pop %s\n'
690 '.equal2:\n'
691 % ( sReg2, sPushSize, iReg2, sReg2, sReg2, sReg2, sReg2, sReg2, sReg2, ) );
692
693 if self.oTarget.is64Bit():
694 self.write(' mov %s, [g_u64KnownValue_%s wrt rip]\n' % (sReg1, sReg1,));
695 if iReg1 != iReg2:
696 self.write(' mov %s, [g_u64KnownValue_%s wrt rip]\n' % (sReg2, sReg2,));
697 else:
698 self.write(' mov %s, 0x%x\n' % (sReg1, self.au32Regs[iReg1],));
699 if iReg1 != iReg2:
700 self.write(' mov %s, 0x%x\n' % (sReg2, self.au32Regs[iReg2],));
701 self.write(' MY_POP_FLAGS\n'
702 ' call VBINSTST_NAME(Common_CheckKnownValues)\n'
703 ' ret sCB*2\n'
704 'VBINSTST_ENDPROC Common_Check_%s_%s\n'
705 % (sReg1, sReg2,));
706
707
708 # 64-bit constants.
709 if len(self.d64BitConsts) > 0:
710 self.write('\n\n'
711 ';\n'
712 '; 64-bit constants\n'
713 ';\n');
714 for uVal in self.d64BitConsts:
715 self.write('g_u64Const_0x%016x: dq 0x%016x ; Ref count: %d\n' % (uVal, uVal, self.d64BitConsts[uVal], ) );
716
717 return True;
718
719 def _generateTests(self):
720 """
721 Generate the test cases.
722 """
723 for self.iFile in range(self.cFiles):
724 if self.cFiles == 1:
725 self.sFile = '%s.asm' % (self.oOptions.sOutputBase,)
726 else:
727 self.sFile = '%s-%u.asm' % (self.oOptions.sOutputBase, self.iFile)
728 self.oFile = sys.stdout;
729 if self.oOptions.sOutputBase != '-':
730 self.oFile = io.open(self.sFile, 'w', encoding = 'utf-8');
731
732 self._generateFileHeader();
733
734 # Calc the range.
735 iInstrTestStart = self.iFile * self.oOptions.cInstrPerFile;
736 iInstrTestEnd = iInstrTestStart + self.oOptions.cInstrPerFile;
737 if iInstrTestEnd > len(g_aoInstructionTests):
738 iInstrTestEnd = len(g_aoInstructionTests);
739
740 # Generate the instruction tests.
741 for iInstrTest in range(iInstrTestStart, iInstrTestEnd):
742 oInstrTest = g_aoInstructionTests[iInstrTest];
743 self.write('\n'
744 '\n'
745 ';\n'
746 '; %s\n'
747 ';\n'
748 % (oInstrTest.sName,));
749 oInstrTest.generateTest(self, self._calcTestFunctionName(oInstrTest, iInstrTest));
750
751 # Generate the main function.
752 self.write('\n\n'
753 'VBINSTST_BEGINPROC TestInstrMain\n'
754 ' MY_PUSH_ALL\n'
755 ' sub xSP, 40h\n'
756 '\n');
757
758 for iInstrTest in range(iInstrTestStart, iInstrTestEnd):
759 oInstrTest = g_aoInstructionTests[iInstrTest];
760 if oInstrTest.isApplicable(self):
761 self.write('%%ifdef ASM_CALL64_GCC\n'
762 ' lea rdi, [.szInstr%03u wrt rip]\n'
763 '%%elifdef ASM_CALL64_MSC\n'
764 ' lea rcx, [.szInstr%03u wrt rip]\n'
765 '%%else\n'
766 ' mov xAX, .szInstr%03u\n'
767 ' mov [xSP], xAX\n'
768 '%%endif\n'
769 ' VBINSTST_CALL_FN_SUB_TEST\n'
770 ' call VBINSTST_NAME(%s)\n'
771 % ( iInstrTest, iInstrTest, iInstrTest, self._calcTestFunctionName(oInstrTest, iInstrTest)));
772
773 self.write('\n'
774 ' add xSP, 40h\n'
775 ' MY_POP_ALL\n'
776 ' ret\n\n');
777 for iInstrTest in range(iInstrTestStart, iInstrTestEnd):
778 self.write('.szInstr%03u: db \'%s\', 0\n' % (iInstrTest, g_aoInstructionTests[iInstrTest].sName,));
779 self.write('VBINSTST_ENDPROC TestInstrMain\n\n');
780
781 self._generateFileFooter();
782 if self.oOptions.sOutputBase != '-':
783 self.oFile.close();
784 self.oFile = None;
785 self.sFile = '';
786
787 return RTEXITCODE_SUCCESS;
788
789 def _runMakefileMode(self):
790 """
791 Generate a list of output files on standard output.
792 """
793 if self.cFiles == 1:
794 print('%s.asm' % (self.oOptions.sOutputBase,));
795 else:
796 print(' '.join('%s-%s.asm' % (self.oOptions.sOutputBase, i) for i in range(self.cFiles)));
797 return RTEXITCODE_SUCCESS;
798
799 def run(self):
800 """
801 Generates the tests or whatever is required.
802 """
803 if self.oOptions.fMakefileMode:
804 return self._runMakefileMode();
805 return self._generateTests();
806
807 @staticmethod
808 def main():
809 """
810 Main function a la C/C++. Returns exit code.
811 """
812
813 #
814 # Parse the command line.
815 #
816 oParser = OptionParser(version = __version__[11:-1].strip());
817 oParser.add_option('--makefile-mode', dest = 'fMakefileMode', action = 'store_true', default = False,
818 help = 'Special mode for use to output a list of output files for the benefit of '
819 'the make program (kmk).');
820 oParser.add_option('--split', dest = 'cInstrPerFile', metavar = '<instr-per-file>', type = 'int', default = 9999999,
821 help = 'Number of instruction to test per output file.');
822 oParser.add_option('--output-base', dest = 'sOutputBase', metavar = '<file>', default = None,
823 help = 'The output file base name, no suffix please. Required.');
824 oParser.add_option('--target', dest = 'sTargetEnv', metavar = '<target>',
825 default = 'iprt-r3-32',
826 choices = g_dTargetEnvs.keys(),
827 help = 'The target environment. Choices: %s'
828 % (', '.join(sorted(g_dTargetEnvs.keys())),));
829 oParser.add_option('--test-size', dest = 'sTestSize', default = InstructionTestGen.ksTestSize_Medium,
830 choices = InstructionTestGen.kasTestSizes,
831 help = 'Selects the test size.');
832
833 (oOptions, asArgs) = oParser.parse_args();
834 if len(asArgs) > 0:
835 oParser.print_help();
836 return RTEXITCODE_SYNTAX
837 if oOptions.sOutputBase is None:
838 print('syntax error: Missing required option --output-base.', file = sys.stderr);
839 return RTEXITCODE_SYNTAX
840
841 #
842 # Instantiate the program class and run it.
843 #
844 oProgram = InstructionTestGen(oOptions);
845 return oProgram.run();
846
847
848if __name__ == '__main__':
849 sys.exit(InstructionTestGen.main());
850
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette