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