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