VirtualBox

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

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

elf, gcc and 32-bit.

  • Property svn:eol-style set to LF
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 28.3 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# $Id: InstructionTestGen.py 46550 2013-06-14 11:32:24Z 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: 46550 $";
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
235
236## Target environments.
237g_dTargetEnvs = {
238 'iprt-r3-32': TargetEnv('iprt-r3-32', TargetEnv.ksInstrSet_32, TargetEnv.ksCpuMode_Protect, 3),
239 'iprt-r3-64': TargetEnv('iprt-r3-64', TargetEnv.ksInstrSet_64, TargetEnv.ksCpuMode_Long, 3),
240};
241
242
243class InstrTestBase(object): # pylint: disable=R0903
244 """
245 Base class for testing one instruction.
246 """
247
248 def __init__(self, sName, sInstr = None):
249 self.sName = sName;
250 self.sInstr = sInstr if sInstr else sName.split()[0];
251
252 def isApplicable(self, oGen):
253 """
254 Tests if the instruction test is applicable to the selected environment.
255 """
256 _ = oGen;
257 return True;
258
259 def generateTest(self, oGen, sTestFnName):
260 """
261 Emits the test assembly code.
262 """
263 oGen.write(';; @todo not implemented. This is for the linter: %s, %s\n' % (oGen, sTestFnName));
264 return True;
265
266
267class InstrTest_MemOrGreg_2_Greg(InstrTestBase):
268 """
269 Instruction reading memory or general register and writing the result to a
270 general register.
271 """
272
273 def __init__(self, sName, fnCalcResult, sInstr = None, acbOpVars = None):
274 InstrTestBase.__init__(self, sName, sInstr);
275 self.fnCalcResult = fnCalcResult;
276 self.acbOpVars = [ 1, 2, 4, 8 ] if not acbOpVars else list(acbOpVars);
277
278 def generateInputs(self, cbEffOp, cbMaxOp):
279 """ Generate a list of inputs. """
280 # Fixed ranges.
281 auRet = [0, 1, ];
282 if cbEffOp == 1:
283 auRet += [ UINT8_MAX / 2, UINT8_MAX / 2 + 1, UINT8_MAX ];
284 elif cbEffOp == 2:
285 auRet += [ UINT16_MAX / 2, UINT16_MAX / 2 + 1, UINT16_MAX ];
286 elif cbEffOp == 4:
287 auRet += [ UINT32_MAX / 2, UINT32_MAX / 2 + 1, UINT32_MAX ];
288 elif cbEffOp == 8:
289 auRet += [ UINT64_MAX / 2, UINT64_MAX / 2 + 1, UINT64_MAX ];
290 else:
291 assert False;
292
293 # Append some random values as well.
294 auRet += randUxxList(cbEffOp * 8, 4);
295 auRet += randUxxList(cbMaxOp * 8, 4);
296
297 return auRet;
298
299 def writeInstrGregGreg(self, cbEffOp, iOp1, iOp2, oGen):
300 """ Writes the instruction with two general registers as operands. """
301 if cbEffOp == 8:
302 iOp2 = iOp2 % len(g_asGRegs32);
303 oGen.write(' %s %s, %s\n' % (self.sInstr, g_asGRegs64[iOp1], g_asGRegs32[iOp2]));
304 elif cbEffOp == 4:
305 oGen.write(' %s %s, %s\n' % (self.sInstr, g_asGRegs32[iOp1], g_asGRegs16[iOp2]));
306 elif cbEffOp == 2:
307 oGen.write(' %s %s, %s\n' % (self.sInstr, g_asGRegs16[iOp1], g_asGRegs8[iOp2]));
308 else:
309 assert False;
310 return True;
311
312 def generateOneStdTest(self, oGen, cbEffOp, cbMaxOp, iOp1, iOp2, uInput, uResult):
313 """ Generate one standard test. """
314 oGen.write(' call VBINSTST_NAME(Common_LoadKnownValues)\n');
315 oGen.write(' mov %s, 0x%x\n' % (oGen.oTarget.asGRegs[iOp2], uInput,));
316 oGen.write(' push %s\n' % (oGen.oTarget.asGRegs[iOp2],));
317 self.writeInstrGregGreg(cbEffOp, iOp1, iOp2, oGen);
318 oGen.pushConst(uResult, cbMaxOp);
319 oGen.write(' call VBINSTST_NAME(%s)\n' % (oGen.needGRegChecker(iOp1, iOp2),));
320 return True;
321
322 def generateStandardTests(self, oGen):
323 """ Generate standard tests. """
324
325 cbDefOp = oGen.oTarget.getDefOpBytes();
326 cbMaxOp = oGen.oTarget.getMaxOpBytes();
327 auInputs = self.generateInputs(cbDefOp, cbMaxOp);
328
329
330 for cbEffOp in self.acbOpVars:
331 if cbEffOp > cbMaxOp:
332 continue;
333 for iOp1 in range(oGen.oTarget.getGRegCount()):
334 if oGen.oTarget.asGRegsNoSp[iOp1] is None:
335 continue;
336 for iOp2 in range(oGen.oTarget.getGRegCount()):
337 if oGen.oTarget.asGRegsNoSp[iOp2] is None:
338 continue;
339 for uInput in auInputs:
340 uResult = self.fnCalcResult(cbEffOp, uInput, oGen.auRegValues[iOp1] if iOp1 != iOp2 else uInput, oGen);
341 oGen.newSubTest();
342 self.generateOneStdTest(oGen, cbEffOp, cbMaxOp, iOp1, iOp2, uInput, uResult);
343 return True;
344
345 def generateTest(self, oGen, sTestFnName):
346 oGen.write('VBINSTST_BEGINPROC %s\n' % (sTestFnName,));
347 #oGen.write(' int3\n');
348
349 self.generateStandardTests(oGen);
350
351 #oGen.write(' int3\n');
352 oGen.write(' ret\n');
353 oGen.write('VBINSTST_ENDPROC %s\n' % (sTestFnName,));
354 return True;
355
356
357class InstrTest_MovSxD_Gv_Ev(InstrTest_MemOrGreg_2_Greg):
358 """
359 Tests MOVSXD Gv,Ev.
360 """
361 def __init__(self):
362 InstrTest_MemOrGreg_2_Greg.__init__(self, 'movsxd Gv,Ev', self.calc_movsxd, acbOpVars = [ 8, 4, 2, ]);
363
364 def writeInstrGregGreg(self, cbEffOp, iOp1, iOp2, oGen):
365 if cbEffOp == 8:
366 oGen.write(' %s %s, %s\n' % (self.sInstr, g_asGRegs64[iOp1], g_asGRegs32[iOp2]));
367 elif cbEffOp == 4 or cbEffOp == 2:
368 abInstr = [];
369 if cbEffOp != oGen.oTarget.getDefOpBytes():
370 abInstr.append(X86_OP_PRF_SIZE_OP);
371 abInstr += calcRexPrefixForTwoModRmRegs(iOp1, iOp2);
372 abInstr.append(0x63);
373 abInstr += calcModRmForTwoRegs(iOp1, iOp2);
374 oGen.writeInstrBytes(abInstr);
375 else:
376 assert False;
377 assert False;
378 return True;
379
380 def isApplicable(self, oGen):
381 return oGen.oTarget.is64Bit();
382
383 @staticmethod
384 def calc_movsxd(cbEffOp, uInput, uCur, oGen):
385 """
386 Calculates the result of a movxsd instruction.
387 Returns the result value (cbMaxOp sized).
388 """
389 _ = oGen;
390 if cbEffOp == 8 and (uInput & RT_BIT_32(31)):
391 return (UINT32_MAX << 32) | (uInput & UINT32_MAX);
392 if cbEffOp == 2:
393 return (uCur & 0xffffffffffff0000) | (uInput & 0xffff);
394 return uInput & UINT32_MAX;
395
396
397## Instruction Tests.
398g_aoInstructionTests = [
399 InstrTest_MovSxD_Gv_Ev(),
400];
401
402
403class InstructionTestGen(object):
404 """
405 Instruction Test Generator.
406 """
407
408
409 def __init__(self, oOptions):
410 self.oOptions = oOptions;
411 self.oTarget = g_dTargetEnvs[oOptions.sTargetEnv];
412
413 # Calculate the number of output files.
414 self.cFiles = 1;
415 if len(g_aoInstructionTests) > self.oOptions.cInstrPerFile:
416 self.cFiles = len(g_aoInstructionTests) / self.oOptions.cInstrPerFile;
417 if self.cFiles * self.oOptions.cInstrPerFile < len(g_aoInstructionTests):
418 self.cFiles += 1;
419
420 # Fix the known register values.
421 self.au64Regs = randUxxList(64, 16);
422 self.au32Regs = [(self.au64Regs[i] & UINT32_MAX) for i in range(8)];
423 self.au16Regs = [(self.au64Regs[i] & UINT16_MAX) for i in range(8)];
424 self.auRegValues = self.au64Regs if self.oTarget.is64Bit() else self.au32Regs;
425
426 # Declare state variables used while generating.
427 self.oFile = sys.stderr;
428 self.iFile = -1;
429 self.sFile = '';
430 self.dCheckFns = dict();
431 self.d64BitConsts = dict();
432
433
434 #
435 # Methods used by instruction tests.
436 #
437
438 def write(self, sText):
439 """ Writes to the current output file. """
440 return self.oFile.write(unicode(sText));
441
442 def writeln(self, sText):
443 """ Writes a line to the current output file. """
444 self.write(sText);
445 return self.write('\n');
446
447 def writeInstrBytes(self, abInstr):
448 """
449 Emits an instruction given as a sequence of bytes values.
450 """
451 self.write(' db %#04x' % (abInstr[0],));
452 for i in range(1, len(abInstr)):
453 self.write(', %#04x' % (abInstr[i],));
454 return self.write('\n');
455
456 def newSubTest(self):
457 """
458 Indicates that a new subtest has started.
459 """
460 self.write(' mov dword [VBINSTST_NAME(g_uVBInsTstSubTestIndicator) xWrtRIP], __LINE__\n');
461 return True;
462
463 def needGRegChecker(self, iReg1, iReg2):
464 """
465 Records the need for a given register checker function, returning its label.
466 """
467 assert iReg1 < 32; assert iReg2 < 32;
468 iRegs = iReg1 + iReg2 * 32;
469 if iRegs in self.dCheckFns:
470 self.dCheckFns[iRegs] += 1;
471 else:
472 self.dCheckFns[iRegs] = 1;
473 return 'Common_Check_%s_%s' % (self.oTarget.asGRegs[iReg1], self.oTarget.asGRegs[iReg2]);
474
475 def need64BitConstant(self, uVal):
476 """
477 Records the need for a 64-bit constant, returning its label.
478 These constants are pooled to attempt reduce the size of the whole thing.
479 """
480 assert uVal >= 0 and uVal <= UINT64_MAX;
481 if uVal in self.d64BitConsts:
482 self.d64BitConsts[uVal] += 1;
483 else:
484 self.d64BitConsts[uVal] = 1;
485 return 'g_u64Const_0x%016x' % (uVal, );
486
487 def pushConst(self, uResult, cbMaxOp):
488 """
489 Emits a push constant value, taking care of high values on 64-bit hosts.
490 """
491 if cbMaxOp == 8 and uResult >= 0x80000000:
492 self.write(' push qword [%s wrt rip]\n' % (self.need64BitConstant(uResult),));
493 else:
494 self.write(' push dword 0x%x\n' % (uResult,));
495 return True;
496
497
498 #
499 # Internal machinery.
500 #
501
502 def _calcTestFunctionName(self, oInstrTest, iInstrTest):
503 """
504 Calc a test function name for the given instruction test.
505 """
506 sName = 'TestInstr%03u_%s' % (iInstrTest, oInstrTest.sName);
507 return sName.replace(',', '_').replace(' ', '_').replace('%', '_');
508
509 def _generateFileHeader(self, ):
510 """
511 Writes the file header.
512 Raises exception on trouble.
513 """
514 self.write('; $Id: InstructionTestGen.py 46550 2013-06-14 11:32:24Z vboxsync $\n'
515 ';; @file %s\n'
516 '; Autogenerate by %s %s. DO NOT EDIT\n'
517 ';\n'
518 '\n'
519 ';\n'
520 '; Headers\n'
521 ';\n'
522 '%%include "env-%s.mac"\n'
523 % ( os.path.basename(self.sFile),
524 os.path.basename(__file__), __version__[11:-1],
525 self.oTarget.sName,
526 ) );
527 # Target environment specific init stuff.
528
529 #
530 # Global variables.
531 #
532 self.write('\n\n'
533 ';\n'
534 '; Globals\n'
535 ';\n');
536 self.write('VBINSTST_BEGINDATA\n'
537 'VBINSTST_GLOBALNAME_EX g_uVBInsTstSubTestIndicator, data hidden\n'
538 ' dd 0\n'
539 'VBINSTST_BEGINCODE\n'
540 );
541 self.write('%ifdef RT_ARCH_AMD64\n');
542 for i in range(len(g_asGRegs64)):
543 self.write('g_u64KnownValue_%s: dq 0x%x\n' % (g_asGRegs64[i], self.au64Regs[i]));
544 self.write('%endif\n\n')
545
546 #
547 # Common functions.
548 #
549
550 # Loading common values.
551 self.write('\n\n'
552 'VBINSTST_BEGINPROC Common_LoadKnownValues\n'
553 '%ifdef RT_ARCH_AMD64\n');
554 for i in range(len(g_asGRegs64NoSp)):
555 if g_asGRegs64NoSp[i]:
556 self.write(' mov %s, 0x%x\n' % (g_asGRegs64NoSp[i], self.au64Regs[i],));
557 self.write('%else\n');
558 for i in range(8):
559 if g_asGRegs32NoSp[i]:
560 self.write(' mov %s, 0x%x\n' % (g_asGRegs32NoSp[i], self.au32Regs[i],));
561 self.write('%endif\n'
562 ' ret\n'
563 'VBINSTST_ENDPROC Common_LoadKnownValues\n'
564 '\n');
565
566 self.write('VBINSTST_BEGINPROC Common_CheckKnownValues\n'
567 '%ifdef RT_ARCH_AMD64\n');
568 for i in range(len(g_asGRegs64NoSp)):
569 if g_asGRegs64NoSp[i]:
570 self.write(' cmp %s, [g_u64KnownValue_%s wrt rip]\n'
571 ' je .ok_%u\n'
572 ' push %u ; register number\n'
573 ' push %s ; actual\n'
574 ' push qword [g_u64KnownValue_%s wrt rip] ; expected\n'
575 ' call VBINSTST_NAME(Common_BadValue)\n'
576 '.ok_%u:\n'
577 % ( g_asGRegs64NoSp[i], g_asGRegs64NoSp[i], i, i, g_asGRegs64NoSp[i], g_asGRegs64NoSp[i], i,));
578 self.write('%else\n');
579 for i in range(8):
580 if g_asGRegs32NoSp[i]:
581 self.write(' cmp %s, 0x%x\n'
582 ' je .ok_%u\n'
583 ' push %u ; register number\n'
584 ' push %s ; actual\n'
585 ' push dword 0x%x ; expected\n'
586 ' call VBINSTST_NAME(Common_BadValue)\n'
587 '.ok_%u:\n'
588 % ( g_asGRegs32NoSp[i], self.au32Regs[i], i, i, g_asGRegs32NoSp[i], self.au32Regs[i], i,));
589 self.write('%endif\n'
590 ' ret\n'
591 'VBINSTST_ENDPROC Common_CheckKnownValues\n'
592 '\n');
593
594 return True;
595
596 def _generateFileFooter(self):
597 """
598 Generates file footer.
599 """
600
601 # Register checking functions.
602 for iRegs in self.dCheckFns:
603 iReg1 = iRegs & 0x1f;
604 sReg1 = self.oTarget.asGRegs[iReg1];
605 iReg2 = (iRegs >> 5) & 0x1f;
606 sReg2 = self.oTarget.asGRegs[iReg2];
607 sPushSize = 'dword';
608
609 self.write('\n\n'
610 '; Checks two register values, expected values pushed on the stack.\n'
611 '; To save space, the callee cleans up the stack.'
612 '; Ref count: %u\n'
613 'VBINSTST_BEGINPROC Common_Check_%s_%s\n'
614 ' MY_PUSH_FLAGS\n'
615 % ( self.dCheckFns[iRegs], sReg1, sReg2, ) );
616
617 self.write(' cmp %s, [xSP + MY_PUSH_FLAGS_SIZE + xCB]\n'
618 ' je .equal1\n'
619 ' push %s %u ; register number\n'
620 ' push %s ; actual\n'
621 ' mov %s, [xSP + sCB*2 + MY_PUSH_FLAGS_SIZE + xCB]\n'
622 ' push %s ; expected\n'
623 ' call VBINSTST_NAME(Common_BadValue)\n'
624 ' pop %s\n'
625 ' pop %s\n'
626 ' pop %s\n'
627 '.equal1:\n'
628 % ( sReg1, sPushSize, iReg1, sReg1, sReg1, sReg1, sReg1, sReg1, sReg1, ) );
629 if iReg1 != iReg2: # If input and result regs are the same, only check the result.
630 self.write(' cmp %s, [xSP + sCB + MY_PUSH_FLAGS_SIZE + xCB]\n'
631 ' je .equal2\n'
632 ' push %s %u ; register number\n'
633 ' push %s ; actual\n'
634 ' mov %s, [xSP + sCB*3 + MY_PUSH_FLAGS_SIZE + xCB]\n'
635 ' push %s ; expected\n'
636 ' call VBINSTST_NAME(Common_BadValue)\n'
637 ' pop %s\n'
638 ' pop %s\n'
639 ' pop %s\n'
640 '.equal2:\n'
641 % ( sReg2, sPushSize, iReg2, sReg2, sReg2, sReg2, sReg2, sReg2, sReg2, ) );
642
643 if self.oTarget.is64Bit():
644 self.write(' mov %s, [g_u64KnownValue_%s wrt rip]\n' % (sReg1, sReg1,));
645 if iReg1 != iReg2:
646 self.write(' mov %s, [g_u64KnownValue_%s wrt rip]\n' % (sReg2, sReg2,));
647 else:
648 self.write(' mov %s, 0x%x\n' % (sReg1, self.au32Regs[iReg1],));
649 if iReg1 != iReg2:
650 self.write(' mov %s, 0x%x\n' % (sReg2, self.au32Regs[iReg2],));
651 self.write(' MY_POP_FLAGS\n'
652 ' call VBINSTST_NAME(Common_CheckKnownValues)\n'
653 ' ret sCB*2\n'
654 'VBINSTST_ENDPROC Common_Check_%s_%s\n'
655 % (sReg1, sReg2,));
656
657
658 # 64-bit constants.
659 if len(self.d64BitConsts) > 0:
660 self.write('\n\n'
661 ';\n'
662 '; 64-bit constants\n'
663 ';\n');
664 for uVal in self.d64BitConsts:
665 self.write('g_u64Const_0x%016x: dq 0x%016x ; Ref count: %d\n' % (uVal, uVal, self.d64BitConsts[uVal], ) );
666
667 return True;
668
669 def _generateTests(self):
670 """
671 Generate the test cases.
672 """
673 for self.iFile in range(self.cFiles):
674 if self.cFiles == 1:
675 self.sFile = '%s.asm' % (self.oOptions.sOutputBase,)
676 else:
677 self.sFile = '%s-%u.asm' % (self.oOptions.sOutputBase, self.iFile)
678 self.oFile = sys.stdout;
679 if self.oOptions.sOutputBase != '-':
680 self.oFile = io.open(self.sFile, 'w', encoding = 'utf-8');
681
682 self._generateFileHeader();
683
684 # Calc the range.
685 iInstrTestStart = self.iFile * self.oOptions.cInstrPerFile;
686 iInstrTestEnd = iInstrTestStart + self.oOptions.cInstrPerFile;
687 if iInstrTestEnd > len(g_aoInstructionTests):
688 iInstrTestEnd = len(g_aoInstructionTests);
689
690 # Generate the instruction tests.
691 for iInstrTest in range(iInstrTestStart, iInstrTestEnd):
692 oInstrTest = g_aoInstructionTests[iInstrTest];
693 self.write('\n'
694 '\n'
695 ';\n'
696 '; %s\n'
697 ';\n'
698 % (oInstrTest.sName,));
699 oInstrTest.generateTest(self, self._calcTestFunctionName(oInstrTest, iInstrTest));
700
701 # Generate the main function.
702 self.write('\n\n'
703 'VBINSTST_BEGINPROC TestInstrMain\n'
704 ' MY_PUSH_ALL\n'
705 ' sub xSP, 40h\n'
706 '\n');
707
708 for iInstrTest in range(iInstrTestStart, iInstrTestEnd):
709 oInstrTest = g_aoInstructionTests[iInstrTest];
710 if oInstrTest.isApplicable(self):
711 self.write('%%ifdef ASM_CALL64_GCC\n'
712 ' lea rdi, [.szInstr%03u wrt rip]\n'
713 '%%elifdef ASM_CALL64_MSC\n'
714 ' lea rcx, [.szInstr%03u wrt rip]\n'
715 '%%else\n'
716 ' mov xAX, .szInstr%03u\n'
717 ' mov [xSP], xAX\n'
718 '%%endif\n'
719 ' VBINSTST_CALL_FN_SUB_TEST\n'
720 ' call VBINSTST_NAME(%s)\n'
721 % ( iInstrTest, iInstrTest, iInstrTest, self._calcTestFunctionName(oInstrTest, iInstrTest)));
722
723 self.write('\n'
724 ' add xSP, 40h\n'
725 ' MY_POP_ALL\n'
726 ' ret\n\n');
727 for iInstrTest in range(iInstrTestStart, iInstrTestEnd):
728 self.write('.szInstr%03u: db \'%s\', 0\n' % (iInstrTest, g_aoInstructionTests[iInstrTest].sName,));
729 self.write('VBINSTST_ENDPROC TestInstrMain\n\n');
730
731 self._generateFileFooter();
732 if self.oOptions.sOutputBase != '-':
733 self.oFile.close();
734 self.oFile = None;
735 self.sFile = '';
736
737 return RTEXITCODE_SUCCESS;
738
739 def _runMakefileMode(self):
740 """
741 Generate a list of output files on standard output.
742 """
743 if self.cFiles == 1:
744 print('%s.asm' % (self.oOptions.sOutputBase,));
745 else:
746 print(' '.join('%s-%s.asm' % (self.oOptions.sOutputBase, i) for i in range(self.cFiles)));
747 return RTEXITCODE_SUCCESS;
748
749 def run(self):
750 """
751 Generates the tests or whatever is required.
752 """
753 if self.oOptions.fMakefileMode:
754 return self._runMakefileMode();
755 return self._generateTests();
756
757 @staticmethod
758 def main():
759 """
760 Main function a la C/C++. Returns exit code.
761 """
762
763 #
764 # Parse the command line.
765 #
766 oParser = OptionParser(version = __version__[11:-1].strip());
767 oParser.add_option('--makefile-mode', dest = 'fMakefileMode', action = 'store_true', default = False,
768 help = 'Special mode for use to output a list of output files for the benefit of '
769 'the make program (kmk).');
770 oParser.add_option('--split', dest = 'cInstrPerFile', metavar = '<instr-per-file>', type = 'int', default = 9999999,
771 help = 'Number of instruction to test per output file.');
772 oParser.add_option('--output-base', dest = 'sOutputBase', metavar = '<file>', default = None,
773 help = 'The output file base name, no suffix please. Required.');
774 oParser.add_option('--target', dest = 'sTargetEnv', metavar = '<target>',
775 default = 'iprt-r3-32',
776 choices = g_dTargetEnvs.keys(),
777 help = 'The target environment. Choices: %s'
778 % (', '.join(sorted(g_dTargetEnvs.keys())),));
779
780 (oOptions, asArgs) = oParser.parse_args();
781 if len(asArgs) > 0:
782 oParser.print_help();
783 return RTEXITCODE_SYNTAX
784 if oOptions.sOutputBase is None:
785 print('syntax error: Missing required option --output-base.', file = sys.stderr);
786 return RTEXITCODE_SYNTAX
787
788 #
789 # Instantiate the program class and run it.
790 #
791 oProgram = InstructionTestGen(oOptions);
792 return oProgram.run();
793
794
795if __name__ == '__main__':
796 sys.exit(InstructionTestGen.main());
797
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