verify.py revision 13178:1e2d0a8ffdb0
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 error_filt(num): 199 return tagged_filt('Error', num) 200 201def warning_filt(num): 202 return tagged_filt('Warning', num) 203 204def info_filt(num): 205 return tagged_filt('Info', num) 206 207class LogChecker(Checker): 208 def merge_filts(*filts): 209 filts = map(lambda f: '(' + f + ')', filts) 210 filts = '|'.join(filts) 211 return re.compile(filts, flags=re.MULTILINE) 212 213 # The reporting mechanism will print the actual filename when running in 214 # gem5, and the "golden" output will say "<removed by verify.py>". We want 215 # to strip out both versions to make comparing the output sensible. 216 in_file_filt = r'^In file: ((<removed by verify\.pl>)|([a-zA-Z0-9.:_/]*))$' 217 218 ref_filt = merge_filts( 219 r'^\nInfo: /OSCI/SystemC: Simulation stopped by user.\n', 220 r'^SystemC Simulation\n', 221 r'^\nInfo: \(I804\) /IEEE_Std_1666/deprecated: ' + 222 r'You can turn off(.*\n){7}', 223 r'^\nInfo: \(I804\) /IEEE_Std_1666/deprecated: \n' + 224 r' sc_clock\(const char(.*\n){3}', 225 warning_filt(540), 226 warning_filt(569), 227 warning_filt(571), 228 error_filt(514), 229 error_filt(515), 230 error_filt(525), 231 error_filt(541), 232 error_filt(542), 233 error_filt(543), 234 info_filt(804), 235 in_file_filt, 236 ) 237 test_filt = merge_filts( 238 r'^Global frequency set at \d* ticks per second\n', 239 info_filt(804), 240 in_file_filt, 241 ) 242 243 def __init__(self, ref, test, tag, out_dir): 244 super(LogChecker, self).__init__(ref, test, tag) 245 self.out_dir = out_dir 246 247 def apply_filters(self, data, filts): 248 re.sub(filt, '', data) 249 250 def check(self): 251 test_file = os.path.basename(self.test) 252 ref_file = os.path.basename(self.ref) 253 with open(self.test) as test_f, open(self.ref) as ref_f: 254 test = re.sub(self.test_filt, '', test_f.read()) 255 ref = re.sub(self.ref_filt, '', ref_f.read()) 256 diff_file = '.'.join([ref_file, 'diff']) 257 diff_path = os.path.join(self.out_dir, diff_file) 258 if test != ref: 259 with open(diff_path, 'w') as diff_f: 260 for line in difflib.unified_diff( 261 ref.splitlines(True), test.splitlines(True), 262 fromfile=ref_file, 263 tofile=test_file): 264 diff_f.write(line) 265 return False 266 else: 267 if os.path.exists(diff_path): 268 os.unlink(diff_path) 269 return True 270 271class GoldenDir(object): 272 def __init__(self, path, platform): 273 self.path = path 274 self.platform = platform 275 276 contents = os.listdir(path) 277 suffix = '.' + platform 278 suffixed = filter(lambda c: c.endswith(suffix), contents) 279 bases = map(lambda t: t[:-len(platform)], suffixed) 280 common = filter(lambda t: not t.startswith(tuple(bases)), contents) 281 282 self.entries = {} 283 class Entry(object): 284 def __init__(self, e_path): 285 self.used = False 286 self.path = os.path.join(path, e_path) 287 288 def use(self): 289 self.used = True 290 291 for entry in contents: 292 self.entries[entry] = Entry(entry) 293 294 def entry(self, name): 295 def match(n): 296 return (n == name) or n.startswith(name + '.') 297 matches = { n: e for n, e in self.entries.items() if match(n) } 298 299 for match in matches.values(): 300 match.use() 301 302 platform_name = '.'.join([ name, self.platform ]) 303 if platform_name in matches: 304 return matches[platform_name].path 305 if name in matches: 306 return matches[name].path 307 else: 308 return None 309 310 def unused(self): 311 items = self.entries.items() 312 items = filter(lambda i: not i[1].used, items) 313 314 items.sort() 315 sources = [] 316 i = 0 317 while i < len(items): 318 root = items[i][0] 319 sources.append(root) 320 i += 1 321 while i < len(items) and items[i][0].startswith(root): 322 i += 1 323 return sources 324 325class VerifyPhase(TestPhaseBase): 326 name = 'verify' 327 number = 3 328 329 def reset_status(self): 330 self._passed = [] 331 self._failed = {} 332 333 def passed(self, test): 334 self._passed.append(test) 335 336 def failed(self, test, cause, note=''): 337 test.set_prop('note', note) 338 self._failed.setdefault(cause, []).append(test) 339 340 def print_status(self): 341 total_passed = len(self._passed) 342 total_failed = sum(map(len, self._failed.values())) 343 print() 344 print('Passed: {passed:4} - Failed: {failed:4}'.format( 345 passed=total_passed, failed=total_failed)) 346 347 def write_result_file(self, path): 348 results = { 349 'passed': map(lambda t: t.props, self._passed), 350 'failed': { 351 cause: map(lambda t: t.props, tests) for 352 cause, tests in self._failed.iteritems() 353 } 354 } 355 with open(path, 'w') as rf: 356 json.dump(results, rf) 357 358 def print_results(self): 359 print() 360 print('Passed:') 361 for path in sorted(list([ t.path for t in self._passed ])): 362 print(' ', path) 363 364 print() 365 print('Failed:') 366 367 causes = [] 368 for cause, tests in sorted(self._failed.items()): 369 block = ' ' + cause.capitalize() + ':\n' 370 for test in sorted(tests, key=lambda t: t.path): 371 block += ' ' + test.path 372 if test.note: 373 block += ' - ' + test.note 374 block += '\n' 375 causes.append(block) 376 377 print('\n'.join(causes)) 378 379 def run(self, tests): 380 parser = argparse.ArgumentParser() 381 result_opts = parser.add_mutually_exclusive_group() 382 result_opts.add_argument('--result-file', action='store_true', 383 help='Create a results.json file in the current directory.') 384 result_opts.add_argument('--result-file-at', metavar='PATH', 385 help='Create a results json file at the given path.') 386 parser.add_argument('--print-results', action='store_true', 387 help='Print a list of tests that passed or failed') 388 args = parser.parse_args(self.args) 389 390 self.reset_status() 391 392 runnable = filter(lambda t: not t.compile_only, tests) 393 compile_only = filter(lambda t: t.compile_only, tests) 394 395 for test in compile_only: 396 if os.path.exists(test.full_path()): 397 self.passed(test) 398 else: 399 self.failed(test, 'compile failed') 400 401 for test in runnable: 402 with open(test.returncode_file()) as rc: 403 returncode = int(rc.read()) 404 405 expected_returncode = 0 406 if os.path.exists(test.expected_returncode_file()): 407 with open(test.expected_returncode_file()) as erc: 408 expected_returncode = int(erc.read()) 409 410 if returncode == 124: 411 self.failed(test, 'time out') 412 continue 413 elif returncode != expected_returncode: 414 if expected_returncode == 0: 415 self.failed(test, 'abort') 416 else: 417 self.failed(test, 'missed abort') 418 continue 419 420 out_dir = test.m5out_dir() 421 422 Diff = collections.namedtuple( 423 'Diff', 'ref, test, tag, ref_filter') 424 425 diffs = [] 426 427 gd = GoldenDir(test.golden_dir(), 'linux64') 428 429 missing = [] 430 log_file = '.'.join([test.name, 'log']) 431 log_path = gd.entry(log_file) 432 simout_path = os.path.join(out_dir, 'simout') 433 if not os.path.exists(simout_path): 434 missing.append('log output') 435 elif log_path: 436 diffs.append(LogChecker(log_path, simout_path, 437 log_file, out_dir)) 438 439 for name in gd.unused(): 440 test_path = os.path.join(out_dir, name) 441 ref_path = gd.entry(name) 442 if not os.path.exists(test_path): 443 missing.append(name) 444 else: 445 diffs.append(Checker(ref_path, test_path, name)) 446 447 if missing: 448 self.failed(test, 'missing output', ' '.join(missing)) 449 continue 450 451 failed_diffs = filter(lambda d: not d.check(), diffs) 452 if failed_diffs: 453 tags = map(lambda d: d.tag, failed_diffs) 454 self.failed(test, 'failed diffs', ' '.join(tags)) 455 continue 456 457 self.passed(test) 458 459 if args.print_results: 460 self.print_results() 461 462 self.print_status() 463 464 result_path = None 465 if args.result_file: 466 result_path = os.path.join(os.getcwd(), 'results.json') 467 elif args.result_file_at: 468 result_path = args.result_file_at 469 470 if result_path: 471 self.write_result_file(result_path) 472 473 474parser = argparse.ArgumentParser(description='SystemC test utility') 475 476parser.add_argument('build_dir', metavar='BUILD_DIR', 477 help='The build directory (ie. build/ARM).') 478 479parser.add_argument('--update-json', action='store_true', 480 help='Update the json manifest of tests.') 481 482parser.add_argument('--flavor', choices=['debug', 'opt', 'fast'], 483 default='opt', 484 help='Flavor of binary to test.') 485 486parser.add_argument('--list', action='store_true', 487 help='List the available tests') 488 489filter_opts = parser.add_mutually_exclusive_group() 490filter_opts.add_argument('--filter', default='True', 491 help='Python expression which filters tests based ' 492 'on their properties') 493filter_opts.add_argument('--filter-file', default=None, 494 type=argparse.FileType('r'), 495 help='Same as --filter, but read from a file') 496 497def collect_phases(args): 498 phase_groups = [list(g) for k, g in 499 itertools.groupby(args, lambda x: x != '--phase') if k] 500 main_args = parser.parse_args(phase_groups[0][1:]) 501 phases = [] 502 names = [] 503 for group in phase_groups[1:]: 504 name = group[0] 505 if name in names: 506 raise RuntimeException('Phase %s specified more than once' % name) 507 phase = test_phase_classes[name] 508 phases.append(phase(main_args, *group[1:])) 509 phases.sort() 510 return main_args, phases 511 512main_args, phases = collect_phases(sys.argv) 513 514if len(phases) == 0: 515 phases = [ 516 CompilePhase(main_args), 517 RunPhase(main_args), 518 VerifyPhase(main_args) 519 ] 520 521 522 523json_path = os.path.join(main_args.build_dir, json_rel_path) 524 525if main_args.update_json: 526 scons(os.path.join(json_path)) 527 528with open(json_path) as f: 529 test_data = json.load(f) 530 531 if main_args.filter_file: 532 f = main_args.filter_file 533 filt = compile(f.read(), f.name, 'eval') 534 else: 535 filt = compile(main_args.filter, '<string>', 'eval') 536 537 filtered_tests = { 538 target: props for (target, props) in 539 test_data.iteritems() if eval(filt, dict(props)) 540 } 541 542 if len(filtered_tests) == 0: 543 print('All tests were filtered out.') 544 exit() 545 546 if main_args.list: 547 for target, props in sorted(filtered_tests.iteritems()): 548 print('%s.%s' % (target, main_args.flavor)) 549 for key, val in props.iteritems(): 550 print(' %s: %s' % (key, val)) 551 print('Total tests: %d' % len(filtered_tests)) 552 else: 553 tests_to_run = list([ 554 Test(target, main_args.flavor, main_args.build_dir, props) for 555 target, props in sorted(filtered_tests.iteritems()) 556 ]) 557 558 for phase in phases: 559 phase.run(tests_to_run) 560