verify.py revision 13134:23ee016d1f54
1#!/usr/bin/env python2 2# 3# Copyright 2018 Google, Inc. 4# 5# Redistribution and use in source and binary forms, with or without 6# modification, are permitted provided that the following conditions are 7# met: redistributions of source code must retain the above copyright 8# notice, this list of conditions and the following disclaimer; 9# redistributions in binary form must reproduce the above copyright 10# notice, this list of conditions and the following disclaimer in the 11# documentation and/or other materials provided with the distribution; 12# neither the name of the copyright holders nor the names of its 13# contributors may be used to endorse or promote products derived from 14# this software without specific prior written permission. 15# 16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 18# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 19# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 20# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 21# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 22# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 26# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27# 28# Authors: Gabe Black 29 30from __future__ import print_function 31 32import argparse 33import collections 34import difflib 35import functools 36import inspect 37import itertools 38import json 39import multiprocessing.pool 40import os 41import re 42import subprocess 43import sys 44 45script_path = os.path.abspath(inspect.getfile(inspect.currentframe())) 46script_dir = os.path.dirname(script_path) 47config_path = os.path.join(script_dir, 'config.py') 48 49systemc_rel_path = 'systemc' 50tests_rel_path = os.path.join(systemc_rel_path, 'tests') 51json_rel_path = os.path.join(tests_rel_path, 'tests.json') 52 53 54 55def scons(*args): 56 args = ['scons'] + list(args) 57 subprocess.check_call(args) 58 59 60 61class Test(object): 62 def __init__(self, target, suffix, build_dir, props): 63 self.target = target 64 self.suffix = suffix 65 self.build_dir = build_dir 66 self.props = {} 67 68 for key, val in props.iteritems(): 69 self.set_prop(key, val) 70 71 def set_prop(self, key, val): 72 setattr(self, key, val) 73 self.props[key] = val 74 75 def dir(self): 76 return os.path.join(self.build_dir, tests_rel_path, self.path) 77 78 def src_dir(self): 79 return os.path.join(script_dir, self.path) 80 81 def expected_returncode_file(self): 82 return os.path.join(self.src_dir(), 'expected_returncode') 83 84 def golden_dir(self): 85 return os.path.join(self.src_dir(), 'golden') 86 87 def bin(self): 88 return '.'.join([self.name, self.suffix]) 89 90 def full_path(self): 91 return os.path.join(self.dir(), self.bin()) 92 93 def m5out_dir(self): 94 return os.path.join(self.dir(), 'm5out.' + self.suffix) 95 96 def returncode_file(self): 97 return os.path.join(self.m5out_dir(), 'returncode') 98 99 100 101test_phase_classes = {} 102 103class TestPhaseMeta(type): 104 def __init__(cls, name, bases, d): 105 if not d.pop('abstract', False): 106 test_phase_classes[d['name']] = cls 107 108 super(TestPhaseMeta, cls).__init__(name, bases, d) 109 110class TestPhaseBase(object): 111 __metaclass__ = TestPhaseMeta 112 abstract = True 113 114 def __init__(self, main_args, *args): 115 self.main_args = main_args 116 self.args = args 117 118 def __lt__(self, other): 119 return self.number < other.number 120 121class CompilePhase(TestPhaseBase): 122 name = 'compile' 123 number = 1 124 125 def run(self, tests): 126 targets = list([test.full_path() for test in tests]) 127 scons_args = [ 'USE_SYSTEMC=1' ] + list(self.args) + targets 128 scons(*scons_args) 129 130class RunPhase(TestPhaseBase): 131 name = 'execute' 132 number = 2 133 134 def run(self, tests): 135 parser = argparse.ArgumentParser() 136 parser.add_argument('--timeout', type=int, metavar='SECONDS', 137 help='Time limit for each run in seconds.', 138 default=0) 139 parser.add_argument('-j', type=int, default=1, 140 help='How many tests to run in parallel.') 141 args = parser.parse_args(self.args) 142 143 timeout_cmd = [ 144 'timeout', 145 '--kill-after', str(args.timeout * 2), 146 str(args.timeout) 147 ] 148 curdir = os.getcwd() 149 def run_test(test): 150 cmd = [] 151 if args.timeout: 152 cmd.extend(timeout_cmd) 153 cmd.extend([ 154 test.full_path(), 155 '-red', os.path.abspath(test.m5out_dir()), 156 '--listener-mode=off', 157 '--quiet', 158 config_path, 159 '--working-dir', 160 os.path.dirname(test.src_dir()) 161 ]) 162 # Ensure the output directory exists. 163 if not os.path.exists(test.m5out_dir()): 164 os.makedirs(test.m5out_dir()) 165 try: 166 subprocess.check_call(cmd) 167 except subprocess.CalledProcessError, error: 168 returncode = error.returncode 169 else: 170 returncode = 0 171 os.chdir(curdir) 172 with open(test.returncode_file(), 'w') as rc: 173 rc.write('%d\n' % returncode) 174 175 runnable = filter(lambda t: not t.compile_only, tests) 176 if args.j == 1: 177 map(run_test, runnable) 178 else: 179 tp = multiprocessing.pool.ThreadPool(args.j) 180 map(lambda t: tp.apply_async(run_test, (t,)), runnable) 181 tp.close() 182 tp.join() 183 184class Checker(object): 185 def __init__(self, ref, test, tag): 186 self.ref = ref 187 self.test = test 188 self.tag = tag 189 190 def check(self): 191 with open(self.text) as test_f, open(self.ref) as ref_f: 192 return test_f.read() == ref_f.read() 193 194def tagged_filt(tag, num): 195 return (r'^\n{}: \({}{}\) .*\n(In file: .*\n)?' 196 r'(In process: [\w.]* @ .*\n)?').format(tag, tag[0], num) 197 198def warning_filt(num): 199 return tagged_filt('Warning', num) 200 201def info_filt(num): 202 return tagged_filt('Info', num) 203 204class LogChecker(Checker): 205 def merge_filts(*filts): 206 filts = map(lambda f: '(' + f + ')', filts) 207 filts = '|'.join(filts) 208 return re.compile(filts, flags=re.MULTILINE) 209 210 ref_filt = merge_filts( 211 r'^\nInfo: /OSCI/SystemC: Simulation stopped by user.\n', 212 r'^SystemC Simulation\n', 213 r'^\nInfo: \(I804\) /IEEE_Std_1666/deprecated: ' + 214 r'You can turn off(.*\n){7}', 215 r'^\nInfo: \(I804\) /IEEE_Std_1666/deprecated: \n' + 216 r' sc_clock\(const char(.*\n){3}', 217 warning_filt(540), 218 warning_filt(569), 219 warning_filt(571), 220 info_filt(804), 221 ) 222 test_filt = merge_filts( 223 r'^Global frequency set at \d* ticks per second\n', 224 info_filt(804), 225 ) 226 227 def __init__(self, ref, test, tag, out_dir): 228 super(LogChecker, self).__init__(ref, test, tag) 229 self.out_dir = out_dir 230 231 def apply_filters(self, data, filts): 232 re.sub(filt, '', data) 233 234 def check(self): 235 test_file = os.path.basename(self.test) 236 ref_file = os.path.basename(self.ref) 237 with open(self.test) as test_f, open(self.ref) as ref_f: 238 test = re.sub(self.test_filt, '', test_f.read()) 239 ref = re.sub(self.ref_filt, '', ref_f.read()) 240 diff_file = '.'.join([ref_file, 'diff']) 241 diff_path = os.path.join(self.out_dir, diff_file) 242 if test != ref: 243 with open(diff_path, 'w') as diff_f: 244 for line in difflib.unified_diff( 245 ref.splitlines(True), test.splitlines(True), 246 fromfile=ref_file, 247 tofile=test_file): 248 diff_f.write(line) 249 return False 250 else: 251 if os.path.exists(diff_path): 252 os.unlink(diff_path) 253 return True 254 255class GoldenDir(object): 256 def __init__(self, path, platform): 257 self.path = path 258 self.platform = platform 259 260 contents = os.listdir(path) 261 suffix = '.' + platform 262 suffixed = filter(lambda c: c.endswith(suffix), contents) 263 bases = map(lambda t: t[:-len(platform)], suffixed) 264 common = filter(lambda t: not t.startswith(tuple(bases)), contents) 265 266 self.entries = {} 267 class Entry(object): 268 def __init__(self, e_path): 269 self.used = False 270 self.path = os.path.join(path, e_path) 271 272 def use(self): 273 self.used = True 274 275 for entry in contents: 276 self.entries[entry] = Entry(entry) 277 278 def entry(self, name): 279 def match(n): 280 return (n == name) or n.startswith(name + '.') 281 matches = { n: e for n, e in self.entries.items() if match(n) } 282 283 for match in matches.values(): 284 match.use() 285 286 platform_name = '.'.join([ name, self.platform ]) 287 if platform_name in matches: 288 return matches[platform_name].path 289 if name in matches: 290 return matches[name].path 291 else: 292 return None 293 294 def unused(self): 295 items = self.entries.items() 296 items = filter(lambda i: not i[1].used, items) 297 298 items.sort() 299 sources = [] 300 i = 0 301 while i < len(items): 302 root = items[i][0] 303 sources.append(root) 304 i += 1 305 while i < len(items) and items[i][0].startswith(root): 306 i += 1 307 return sources 308 309class VerifyPhase(TestPhaseBase): 310 name = 'verify' 311 number = 3 312 313 def reset_status(self): 314 self._passed = [] 315 self._failed = {} 316 317 def passed(self, test): 318 self._passed.append(test) 319 320 def failed(self, test, cause, note=''): 321 test.set_prop('note', note) 322 self._failed.setdefault(cause, []).append(test) 323 324 def print_status(self): 325 total_passed = len(self._passed) 326 total_failed = sum(map(len, self._failed.values())) 327 print() 328 print('Passed: {passed:4} - Failed: {failed:4}'.format( 329 passed=total_passed, failed=total_failed)) 330 331 def write_result_file(self, path): 332 results = { 333 'passed': map(lambda t: t.props, self._passed), 334 'failed': { 335 cause: map(lambda t: t.props, tests) for 336 cause, tests in self._failed.iteritems() 337 } 338 } 339 with open(path, 'w') as rf: 340 json.dump(results, rf) 341 342 def print_results(self): 343 print() 344 print('Passed:') 345 for path in sorted(list([ t.path for t in self._passed ])): 346 print(' ', path) 347 348 print() 349 print('Failed:') 350 351 causes = [] 352 for cause, tests in sorted(self._failed.items()): 353 block = ' ' + cause.capitalize() + ':\n' 354 for test in sorted(tests, key=lambda t: t.path): 355 block += ' ' + test.path 356 if test.note: 357 block += ' - ' + test.note 358 block += '\n' 359 causes.append(block) 360 361 print('\n'.join(causes)) 362 363 def run(self, tests): 364 parser = argparse.ArgumentParser() 365 result_opts = parser.add_mutually_exclusive_group() 366 result_opts.add_argument('--result-file', action='store_true', 367 help='Create a results.json file in the current directory.') 368 result_opts.add_argument('--result-file-at', metavar='PATH', 369 help='Create a results json file at the given path.') 370 parser.add_argument('--print-results', action='store_true', 371 help='Print a list of tests that passed or failed') 372 args = parser.parse_args(self.args) 373 374 self.reset_status() 375 376 runnable = filter(lambda t: not t.compile_only, tests) 377 compile_only = filter(lambda t: t.compile_only, tests) 378 379 for test in compile_only: 380 if os.path.exists(test.full_path()): 381 self.passed(test) 382 else: 383 self.failed(test, 'compile failed') 384 385 for test in runnable: 386 with open(test.returncode_file()) as rc: 387 returncode = int(rc.read()) 388 389 expected_returncode = 0 390 if os.path.exists(test.expected_returncode_file()): 391 with open(test.expected_returncode_file()) as erc: 392 expected_returncode = int(erc.read()) 393 394 if returncode == 124: 395 self.failed(test, 'time out') 396 continue 397 elif returncode != expected_returncode: 398 if expected_returncode == 0: 399 self.failed(test, 'abort') 400 else: 401 self.failed(test, 'missed abort') 402 continue 403 404 out_dir = test.m5out_dir() 405 406 Diff = collections.namedtuple( 407 'Diff', 'ref, test, tag, ref_filter') 408 409 diffs = [] 410 411 gd = GoldenDir(test.golden_dir(), 'linux64') 412 413 missing = [] 414 log_file = '.'.join([test.name, 'log']) 415 log_path = gd.entry(log_file) 416 simout_path = os.path.join(out_dir, 'simout') 417 if not os.path.exists(simout_path): 418 missing.append('log output') 419 elif log_path: 420 diffs.append(LogChecker(log_path, simout_path, 421 log_file, out_dir)) 422 423 for name in gd.unused(): 424 test_path = os.path.join(out_dir, name) 425 ref_path = gd.entry(name) 426 if not os.path.exists(test_path): 427 missing.append(name) 428 else: 429 diffs.append(Checker(ref_path, test_path, name)) 430 431 if missing: 432 self.failed(test, 'missing output', ' '.join(missing)) 433 continue 434 435 failed_diffs = filter(lambda d: not d.check(), diffs) 436 if failed_diffs: 437 tags = map(lambda d: d.tag, failed_diffs) 438 self.failed(test, 'failed diffs', ' '.join(tags)) 439 continue 440 441 self.passed(test) 442 443 if args.print_results: 444 self.print_results() 445 446 self.print_status() 447 448 result_path = None 449 if args.result_file: 450 result_path = os.path.join(os.getcwd(), 'results.json') 451 elif args.result_file_at: 452 result_path = args.result_file_at 453 454 if result_path: 455 self.write_result_file(result_path) 456 457 458parser = argparse.ArgumentParser(description='SystemC test utility') 459 460parser.add_argument('build_dir', metavar='BUILD_DIR', 461 help='The build directory (ie. build/ARM).') 462 463parser.add_argument('--update-json', action='store_true', 464 help='Update the json manifest of tests.') 465 466parser.add_argument('--flavor', choices=['debug', 'opt', 'fast'], 467 default='opt', 468 help='Flavor of binary to test.') 469 470parser.add_argument('--list', action='store_true', 471 help='List the available tests') 472 473filter_opts = parser.add_mutually_exclusive_group() 474filter_opts.add_argument('--filter', default='True', 475 help='Python expression which filters tests based ' 476 'on their properties') 477filter_opts.add_argument('--filter-file', default=None, 478 type=argparse.FileType('r'), 479 help='Same as --filter, but read from a file') 480 481def collect_phases(args): 482 phase_groups = [list(g) for k, g in 483 itertools.groupby(args, lambda x: x != '--phase') if k] 484 main_args = parser.parse_args(phase_groups[0][1:]) 485 phases = [] 486 names = [] 487 for group in phase_groups[1:]: 488 name = group[0] 489 if name in names: 490 raise RuntimeException('Phase %s specified more than once' % name) 491 phase = test_phase_classes[name] 492 phases.append(phase(main_args, *group[1:])) 493 phases.sort() 494 return main_args, phases 495 496main_args, phases = collect_phases(sys.argv) 497 498if len(phases) == 0: 499 phases = [ 500 CompilePhase(main_args), 501 RunPhase(main_args), 502 VerifyPhase(main_args) 503 ] 504 505 506 507json_path = os.path.join(main_args.build_dir, json_rel_path) 508 509if main_args.update_json: 510 scons(os.path.join(json_path)) 511 512with open(json_path) as f: 513 test_data = json.load(f) 514 515 if main_args.filter_file: 516 f = main_args.filter_file 517 filt = compile(f.read(), f.name, 'eval') 518 else: 519 filt = compile(main_args.filter, '<string>', 'eval') 520 521 filtered_tests = { 522 target: props for (target, props) in 523 test_data.iteritems() if eval(filt, dict(props)) 524 } 525 526 if len(filtered_tests) == 0: 527 print('All tests were filtered out.') 528 exit() 529 530 if main_args.list: 531 for target, props in sorted(filtered_tests.iteritems()): 532 print('%s.%s' % (target, main_args.flavor)) 533 for key, val in props.iteritems(): 534 print(' %s: %s' % (key, val)) 535 print('Total tests: %d' % len(filtered_tests)) 536 else: 537 tests_to_run = list([ 538 Test(target, main_args.flavor, main_args.build_dir, props) for 539 target, props in sorted(filtered_tests.iteritems()) 540 ]) 541 542 for phase in phases: 543 phase.run(tests_to_run) 544