verify.py revision 13100:fc7df026c235
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 golden_dir(self): 82 return os.path.join(self.src_dir(), 'golden') 83 84 def bin(self): 85 return '.'.join([self.name, self.suffix]) 86 87 def full_path(self): 88 return os.path.join(self.dir(), self.bin()) 89 90 def m5out_dir(self): 91 return os.path.join(self.dir(), 'm5out.' + self.suffix) 92 93 def returncode_file(self): 94 return os.path.join(self.m5out_dir(), 'returncode') 95 96 97 98test_phase_classes = {} 99 100class TestPhaseMeta(type): 101 def __init__(cls, name, bases, d): 102 if not d.pop('abstract', False): 103 test_phase_classes[d['name']] = cls 104 105 super(TestPhaseMeta, cls).__init__(name, bases, d) 106 107class TestPhaseBase(object): 108 __metaclass__ = TestPhaseMeta 109 abstract = True 110 111 def __init__(self, main_args, *args): 112 self.main_args = main_args 113 self.args = args 114 115 def __lt__(self, other): 116 return self.number < other.number 117 118class CompilePhase(TestPhaseBase): 119 name = 'compile' 120 number = 1 121 122 def run(self, tests): 123 targets = list([test.full_path() for test in tests]) 124 scons_args = [ 'USE_SYSTEMC=1' ] + list(self.args) + targets 125 scons(*scons_args) 126 127class RunPhase(TestPhaseBase): 128 name = 'execute' 129 number = 2 130 131 def run(self, tests): 132 parser = argparse.ArgumentParser() 133 parser.add_argument('--timeout', type=int, metavar='SECONDS', 134 help='Time limit for each run in seconds.', 135 default=0) 136 parser.add_argument('-j', type=int, default=1, 137 help='How many tests to run in parallel.') 138 args = parser.parse_args(self.args) 139 140 timeout_cmd = [ 141 'timeout', 142 '--kill-after', str(args.timeout * 2), 143 str(args.timeout) 144 ] 145 curdir = os.getcwd() 146 def run_test(test): 147 cmd = [] 148 if args.timeout: 149 cmd.extend(timeout_cmd) 150 cmd.extend([ 151 test.full_path(), 152 '-red', os.path.abspath(test.m5out_dir()), 153 '--listener-mode=off', 154 '--quiet', 155 config_path, 156 '--working-dir', 157 os.path.dirname(test.src_dir()) 158 ]) 159 # Ensure the output directory exists. 160 if not os.path.exists(test.m5out_dir()): 161 os.makedirs(test.m5out_dir()) 162 try: 163 subprocess.check_call(cmd) 164 except subprocess.CalledProcessError, error: 165 returncode = error.returncode 166 else: 167 returncode = 0 168 os.chdir(curdir) 169 with open(test.returncode_file(), 'w') as rc: 170 rc.write('%d\n' % returncode) 171 172 runnable = filter(lambda t: not t.compile_only, tests) 173 if args.j == 1: 174 map(run_test, runnable) 175 else: 176 tp = multiprocessing.pool.ThreadPool(args.j) 177 map(lambda t: tp.apply_async(run_test, (t,)), runnable) 178 tp.close() 179 tp.join() 180 181class Checker(object): 182 def __init__(self, ref, test, tag): 183 self.ref = ref 184 self.test = test 185 self.tag = tag 186 187 def check(self): 188 with open(self.text) as test_f, open(self.ref) as ref_f: 189 return test_f.read() == ref_f.read() 190 191def tagged_filt(tag, num): 192 return (r'^\n{}: \({}{}\) .*\n(In file: .*\n)?' 193 r'(In process: [\w.]* @ .*\n)?').format(tag, tag[0], num) 194 195def warning_filt(num): 196 return tagged_filt('Warning', num) 197 198def info_filt(num): 199 return tagged_filt('Info', num) 200 201class LogChecker(Checker): 202 def merge_filts(*filts): 203 filts = map(lambda f: '(' + f + ')', filts) 204 filts = '|'.join(filts) 205 return re.compile(filts, flags=re.MULTILINE) 206 207 ref_filt = merge_filts( 208 r'^\nInfo: /OSCI/SystemC: Simulation stopped by user.\n', 209 r'^SystemC Simulation\n', 210 r'^\nInfo: \(I804\) /IEEE_Std_1666/deprecated: ' + 211 r'You can turn off(.*\n){7}', 212 r'^\nInfo: \(I804\) /IEEE_Std_1666/deprecated: \n' + 213 r' sc_clock\(const char(.*\n){3}', 214 warning_filt(540), 215 warning_filt(569), 216 warning_filt(571), 217 info_filt(804), 218 ) 219 test_filt = merge_filts( 220 r'^Global frequency set at \d* ticks per second\n', 221 info_filt(804), 222 ) 223 224 def __init__(self, ref, test, tag, out_dir): 225 super(LogChecker, self).__init__(ref, test, tag) 226 self.out_dir = out_dir 227 228 def apply_filters(self, data, filts): 229 re.sub(filt, '', data) 230 231 def check(self): 232 test_file = os.path.basename(self.test) 233 ref_file = os.path.basename(self.ref) 234 with open(self.test) as test_f, open(self.ref) as ref_f: 235 test = re.sub(self.test_filt, '', test_f.read()) 236 ref = re.sub(self.ref_filt, '', ref_f.read()) 237 diff_file = '.'.join([ref_file, 'diff']) 238 diff_path = os.path.join(self.out_dir, diff_file) 239 if test != ref: 240 with open(diff_path, 'w') as diff_f: 241 for line in difflib.unified_diff( 242 ref.splitlines(True), test.splitlines(True), 243 fromfile=ref_file, 244 tofile=test_file): 245 diff_f.write(line) 246 return False 247 else: 248 if os.path.exists(diff_path): 249 os.unlink(diff_path) 250 return True 251 252class GoldenDir(object): 253 def __init__(self, path, platform): 254 self.path = path 255 self.platform = platform 256 257 contents = os.listdir(path) 258 suffix = '.' + platform 259 suffixed = filter(lambda c: c.endswith(suffix), contents) 260 bases = map(lambda t: t[:-len(platform)], suffixed) 261 common = filter(lambda t: not t.startswith(tuple(bases)), contents) 262 263 self.entries = {} 264 class Entry(object): 265 def __init__(self, e_path): 266 self.used = False 267 self.path = os.path.join(path, e_path) 268 269 def use(self): 270 self.used = True 271 272 for entry in contents: 273 self.entries[entry] = Entry(entry) 274 275 def entry(self, name): 276 def match(n): 277 return (n == name) or n.startswith(name + '.') 278 matches = { n: e for n, e in self.entries.items() if match(n) } 279 280 for match in matches.values(): 281 match.use() 282 283 platform_name = '.'.join([ name, self.platform ]) 284 if platform_name in matches: 285 return matches[platform_name].path 286 if name in matches: 287 return matches[name].path 288 else: 289 return None 290 291 def unused(self): 292 items = self.entries.items() 293 items = filter(lambda i: not i[1].used, items) 294 295 items.sort() 296 sources = [] 297 i = 0 298 while i < len(items): 299 root = items[i][0] 300 sources.append(root) 301 i += 1 302 while i < len(items) and items[i][0].startswith(root): 303 i += 1 304 return sources 305 306class VerifyPhase(TestPhaseBase): 307 name = 'verify' 308 number = 3 309 310 def reset_status(self): 311 self._passed = [] 312 self._failed = {} 313 314 def passed(self, test): 315 self._passed.append(test) 316 317 def failed(self, test, cause, note=''): 318 test.set_prop('note', note) 319 self._failed.setdefault(cause, []).append(test) 320 321 def print_status(self): 322 total_passed = len(self._passed) 323 total_failed = sum(map(len, self._failed.values())) 324 print() 325 print('Passed: {passed:4} - Failed: {failed:4}'.format( 326 passed=total_passed, failed=total_failed)) 327 328 def write_result_file(self, path): 329 results = { 330 'passed': map(lambda t: t.props, self._passed), 331 'failed': { 332 cause: map(lambda t: t.props, tests) for 333 cause, tests in self._failed.iteritems() 334 } 335 } 336 with open(path, 'w') as rf: 337 json.dump(results, rf) 338 339 def print_results(self): 340 print() 341 print('Passed:') 342 for path in sorted(list([ t.path for t in self._passed ])): 343 print(' ', path) 344 345 print() 346 print('Failed:') 347 348 causes = [] 349 for cause, tests in sorted(self._failed.items()): 350 block = ' ' + cause.capitalize() + ':\n' 351 for test in sorted(tests, key=lambda t: t.path): 352 block += ' ' + test.path 353 if test.note: 354 block += ' - ' + test.note 355 block += '\n' 356 causes.append(block) 357 358 print('\n'.join(causes)) 359 360 def run(self, tests): 361 parser = argparse.ArgumentParser() 362 result_opts = parser.add_mutually_exclusive_group() 363 result_opts.add_argument('--result-file', action='store_true', 364 help='Create a results.json file in the current directory.') 365 result_opts.add_argument('--result-file-at', metavar='PATH', 366 help='Create a results json file at the given path.') 367 parser.add_argument('--print-results', action='store_true', 368 help='Print a list of tests that passed or failed') 369 args = parser.parse_args(self.args) 370 371 self.reset_status() 372 373 runnable = filter(lambda t: not t.compile_only, tests) 374 compile_only = filter(lambda t: t.compile_only, tests) 375 376 for test in compile_only: 377 if os.path.exists(test.full_path()): 378 self.passed(test) 379 else: 380 self.failed(test, 'compile failed') 381 382 for test in runnable: 383 with open(test.returncode_file()) as rc: 384 returncode = int(rc.read()) 385 386 if returncode == 124: 387 self.failed(test, 'time out') 388 continue 389 elif returncode != 0: 390 self.failed(test, 'abort') 391 continue 392 393 out_dir = test.m5out_dir() 394 395 Diff = collections.namedtuple( 396 'Diff', 'ref, test, tag, ref_filter') 397 398 diffs = [] 399 400 gd = GoldenDir(test.golden_dir(), 'linux64') 401 402 missing = [] 403 log_file = '.'.join([test.name, 'log']) 404 log_path = gd.entry(log_file) 405 simout_path = os.path.join(out_dir, 'simout') 406 if not os.path.exists(simout_path): 407 missing.append('log output') 408 elif log_path: 409 diffs.append(LogChecker(log_path, simout_path, 410 log_file, out_dir)) 411 412 for name in gd.unused(): 413 test_path = os.path.join(out_dir, name) 414 ref_path = gd.entry(name) 415 if not os.path.exists(test_path): 416 missing.append(name) 417 else: 418 diffs.append(Checker(ref_path, test_path, name)) 419 420 if missing: 421 self.failed(test, 'missing output', ' '.join(missing)) 422 continue 423 424 failed_diffs = filter(lambda d: not d.check(), diffs) 425 if failed_diffs: 426 tags = map(lambda d: d.tag, failed_diffs) 427 self.failed(test, 'failed diffs', ' '.join(tags)) 428 continue 429 430 self.passed(test) 431 432 if args.print_results: 433 self.print_results() 434 435 self.print_status() 436 437 result_path = None 438 if args.result_file: 439 result_path = os.path.join(os.getcwd(), 'results.json') 440 elif args.result_file_at: 441 result_path = args.result_file_at 442 443 if result_path: 444 self.write_result_file(result_path) 445 446 447parser = argparse.ArgumentParser(description='SystemC test utility') 448 449parser.add_argument('build_dir', metavar='BUILD_DIR', 450 help='The build directory (ie. build/ARM).') 451 452parser.add_argument('--update-json', action='store_true', 453 help='Update the json manifest of tests.') 454 455parser.add_argument('--flavor', choices=['debug', 'opt', 'fast'], 456 default='opt', 457 help='Flavor of binary to test.') 458 459parser.add_argument('--list', action='store_true', 460 help='List the available tests') 461 462filter_opts = parser.add_mutually_exclusive_group() 463filter_opts.add_argument('--filter', default='True', 464 help='Python expression which filters tests based ' 465 'on their properties') 466filter_opts.add_argument('--filter-file', default=None, 467 type=argparse.FileType('r'), 468 help='Same as --filter, but read from a file') 469 470def collect_phases(args): 471 phase_groups = [list(g) for k, g in 472 itertools.groupby(args, lambda x: x != '--phase') if k] 473 main_args = parser.parse_args(phase_groups[0][1:]) 474 phases = [] 475 names = [] 476 for group in phase_groups[1:]: 477 name = group[0] 478 if name in names: 479 raise RuntimeException('Phase %s specified more than once' % name) 480 phase = test_phase_classes[name] 481 phases.append(phase(main_args, *group[1:])) 482 phases.sort() 483 return main_args, phases 484 485main_args, phases = collect_phases(sys.argv) 486 487if len(phases) == 0: 488 phases = [ 489 CompilePhase(main_args), 490 RunPhase(main_args), 491 VerifyPhase(main_args) 492 ] 493 494 495 496json_path = os.path.join(main_args.build_dir, json_rel_path) 497 498if main_args.update_json: 499 scons(os.path.join(json_path)) 500 501with open(json_path) as f: 502 test_data = json.load(f) 503 504 if main_args.filter_file: 505 f = main_args.filter_file 506 filt = compile(f.read(), f.name, 'eval') 507 else: 508 filt = compile(main_args.filter, '<string>', 'eval') 509 510 filtered_tests = { 511 target: props for (target, props) in 512 test_data.iteritems() if eval(filt, dict(props)) 513 } 514 515 if main_args.list: 516 for target, props in sorted(filtered_tests.iteritems()): 517 print('%s.%s' % (target, main_args.flavor)) 518 for key, val in props.iteritems(): 519 print(' %s: %s' % (key, val)) 520 print('Total tests: %d' % len(filtered_tests)) 521 else: 522 tests_to_run = list([ 523 Test(target, main_args.flavor, main_args.build_dir, props) for 524 target, props in sorted(filtered_tests.iteritems()) 525 ]) 526 527 for phase in phases: 528 phase.run(tests_to_run) 529