113540Sandrea.mondelli@ucf.edu#!/usr/bin/env python2.7
212870Sgabeblack@google.com#
312870Sgabeblack@google.com# Copyright 2018 Google, Inc.
412870Sgabeblack@google.com#
512870Sgabeblack@google.com# Redistribution and use in source and binary forms, with or without
612870Sgabeblack@google.com# modification, are permitted provided that the following conditions are
712870Sgabeblack@google.com# met: redistributions of source code must retain the above copyright
812870Sgabeblack@google.com# notice, this list of conditions and the following disclaimer;
912870Sgabeblack@google.com# redistributions in binary form must reproduce the above copyright
1012870Sgabeblack@google.com# notice, this list of conditions and the following disclaimer in the
1112870Sgabeblack@google.com# documentation and/or other materials provided with the distribution;
1212870Sgabeblack@google.com# neither the name of the copyright holders nor the names of its
1312870Sgabeblack@google.com# contributors may be used to endorse or promote products derived from
1412870Sgabeblack@google.com# this software without specific prior written permission.
1512870Sgabeblack@google.com#
1612870Sgabeblack@google.com# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1712870Sgabeblack@google.com# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1812870Sgabeblack@google.com# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1912870Sgabeblack@google.com# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2012870Sgabeblack@google.com# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2112870Sgabeblack@google.com# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2212870Sgabeblack@google.com# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2312870Sgabeblack@google.com# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2412870Sgabeblack@google.com# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2512870Sgabeblack@google.com# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2612870Sgabeblack@google.com# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2712870Sgabeblack@google.com#
2812870Sgabeblack@google.com# Authors: Gabe Black
2912870Sgabeblack@google.com
3012870Sgabeblack@google.comfrom __future__ import print_function
3112870Sgabeblack@google.com
3212870Sgabeblack@google.comimport argparse
3313003Sgabeblack@google.comimport collections
3413003Sgabeblack@google.comimport difflib
3512870Sgabeblack@google.comimport functools
3612870Sgabeblack@google.comimport inspect
3712870Sgabeblack@google.comimport itertools
3812870Sgabeblack@google.comimport json
3913000Sgabeblack@google.comimport multiprocessing.pool
4012870Sgabeblack@google.comimport os
4113003Sgabeblack@google.comimport re
4212870Sgabeblack@google.comimport subprocess
4312870Sgabeblack@google.comimport sys
4412870Sgabeblack@google.com
4512870Sgabeblack@google.comscript_path = os.path.abspath(inspect.getfile(inspect.currentframe()))
4612870Sgabeblack@google.comscript_dir = os.path.dirname(script_path)
4712870Sgabeblack@google.comconfig_path = os.path.join(script_dir, 'config.py')
4813705Sgabeblack@google.com# Parent directories if checked out as part of gem5.
4913705Sgabeblack@google.comsystemc_dir = os.path.dirname(script_dir)
5013705Sgabeblack@google.comsrc_dir = os.path.dirname(systemc_dir)
5113705Sgabeblack@google.comcheckout_dir = os.path.dirname(src_dir)
5212870Sgabeblack@google.com
5312870Sgabeblack@google.comsystemc_rel_path = 'systemc'
5412870Sgabeblack@google.comtests_rel_path = os.path.join(systemc_rel_path, 'tests')
5512870Sgabeblack@google.comjson_rel_path = os.path.join(tests_rel_path, 'tests.json')
5612870Sgabeblack@google.com
5712870Sgabeblack@google.com
5812870Sgabeblack@google.com
5912870Sgabeblack@google.comdef scons(*args):
6012870Sgabeblack@google.com    args = ['scons'] + list(args)
6112870Sgabeblack@google.com    subprocess.check_call(args)
6212870Sgabeblack@google.com
6312870Sgabeblack@google.com
6412870Sgabeblack@google.com
6512870Sgabeblack@google.comclass Test(object):
6612870Sgabeblack@google.com    def __init__(self, target, suffix, build_dir, props):
6712870Sgabeblack@google.com        self.target = target
6812870Sgabeblack@google.com        self.suffix = suffix
6912870Sgabeblack@google.com        self.build_dir = build_dir
7013003Sgabeblack@google.com        self.props = {}
7112870Sgabeblack@google.com
7212870Sgabeblack@google.com        for key, val in props.iteritems():
7313003Sgabeblack@google.com            self.set_prop(key, val)
7413003Sgabeblack@google.com
7513003Sgabeblack@google.com    def set_prop(self, key, val):
7613003Sgabeblack@google.com        setattr(self, key, val)
7713003Sgabeblack@google.com        self.props[key] = val
7812870Sgabeblack@google.com
7912870Sgabeblack@google.com    def dir(self):
8012870Sgabeblack@google.com        return os.path.join(self.build_dir, tests_rel_path, self.path)
8112870Sgabeblack@google.com
8212870Sgabeblack@google.com    def src_dir(self):
8312897Sgabeblack@google.com        return os.path.join(script_dir, self.path)
8412870Sgabeblack@google.com
8513134Sgabeblack@google.com    def expected_returncode_file(self):
8613134Sgabeblack@google.com        return os.path.join(self.src_dir(), 'expected_returncode')
8713134Sgabeblack@google.com
8812870Sgabeblack@google.com    def golden_dir(self):
8912870Sgabeblack@google.com        return os.path.join(self.src_dir(), 'golden')
9012870Sgabeblack@google.com
9112870Sgabeblack@google.com    def bin(self):
9212870Sgabeblack@google.com        return '.'.join([self.name, self.suffix])
9312870Sgabeblack@google.com
9412870Sgabeblack@google.com    def full_path(self):
9512870Sgabeblack@google.com        return os.path.join(self.dir(), self.bin())
9612870Sgabeblack@google.com
9712870Sgabeblack@google.com    def m5out_dir(self):
9812870Sgabeblack@google.com        return os.path.join(self.dir(), 'm5out.' + self.suffix)
9912870Sgabeblack@google.com
10013002Sgabeblack@google.com    def returncode_file(self):
10113002Sgabeblack@google.com        return os.path.join(self.m5out_dir(), 'returncode')
10213002Sgabeblack@google.com
10312870Sgabeblack@google.com
10412870Sgabeblack@google.com
10512870Sgabeblack@google.comtest_phase_classes = {}
10612870Sgabeblack@google.com
10712870Sgabeblack@google.comclass TestPhaseMeta(type):
10812870Sgabeblack@google.com    def __init__(cls, name, bases, d):
10912870Sgabeblack@google.com        if not d.pop('abstract', False):
11012870Sgabeblack@google.com            test_phase_classes[d['name']] = cls
11112870Sgabeblack@google.com
11212870Sgabeblack@google.com        super(TestPhaseMeta, cls).__init__(name, bases, d)
11312870Sgabeblack@google.com
11412870Sgabeblack@google.comclass TestPhaseBase(object):
11512870Sgabeblack@google.com    __metaclass__ = TestPhaseMeta
11612870Sgabeblack@google.com    abstract = True
11712870Sgabeblack@google.com
11812870Sgabeblack@google.com    def __init__(self, main_args, *args):
11912870Sgabeblack@google.com        self.main_args = main_args
12012870Sgabeblack@google.com        self.args = args
12112870Sgabeblack@google.com
12212870Sgabeblack@google.com    def __lt__(self, other):
12312870Sgabeblack@google.com        return self.number < other.number
12412870Sgabeblack@google.com
12512870Sgabeblack@google.comclass CompilePhase(TestPhaseBase):
12612870Sgabeblack@google.com    name = 'compile'
12712870Sgabeblack@google.com    number = 1
12812870Sgabeblack@google.com
12912870Sgabeblack@google.com    def run(self, tests):
13012870Sgabeblack@google.com        targets = list([test.full_path() for test in tests])
13113183Sgabeblack@google.com
13213183Sgabeblack@google.com        parser = argparse.ArgumentParser()
13313183Sgabeblack@google.com        parser.add_argument('-j', type=int, default=0)
13413183Sgabeblack@google.com        args, leftovers = parser.parse_known_args(self.args)
13513183Sgabeblack@google.com        if args.j == 0:
13613183Sgabeblack@google.com            self.args = ('-j', str(self.main_args.j)) + self.args
13713183Sgabeblack@google.com
13813705Sgabeblack@google.com        scons_args = [ '--directory', self.main_args.scons_dir,
13913705Sgabeblack@google.com                       'USE_SYSTEMC=1' ] + list(self.args) + targets
14012870Sgabeblack@google.com        scons(*scons_args)
14112870Sgabeblack@google.com
14212870Sgabeblack@google.comclass RunPhase(TestPhaseBase):
14312870Sgabeblack@google.com    name = 'execute'
14412870Sgabeblack@google.com    number = 2
14512870Sgabeblack@google.com
14612870Sgabeblack@google.com    def run(self, tests):
14713000Sgabeblack@google.com        parser = argparse.ArgumentParser()
14813000Sgabeblack@google.com        parser.add_argument('--timeout', type=int, metavar='SECONDS',
14913183Sgabeblack@google.com                            help='Time limit for each run in seconds, '
15013183Sgabeblack@google.com                            '0 to disable.',
15113183Sgabeblack@google.com                            default=60)
15213183Sgabeblack@google.com        parser.add_argument('-j', type=int, default=0,
15313000Sgabeblack@google.com                help='How many tests to run in parallel.')
15413000Sgabeblack@google.com        args = parser.parse_args(self.args)
15513000Sgabeblack@google.com
15613000Sgabeblack@google.com        timeout_cmd = [
15713000Sgabeblack@google.com            'timeout',
15813000Sgabeblack@google.com            '--kill-after', str(args.timeout * 2),
15913000Sgabeblack@google.com            str(args.timeout)
16013000Sgabeblack@google.com        ]
16113000Sgabeblack@google.com        def run_test(test):
16213000Sgabeblack@google.com            cmd = []
16313000Sgabeblack@google.com            if args.timeout:
16413000Sgabeblack@google.com                cmd.extend(timeout_cmd)
16513000Sgabeblack@google.com            cmd.extend([
16613461Sgabeblack@google.com                os.path.abspath(test.full_path()),
16713181Sgabeblack@google.com                '-rd', os.path.abspath(test.m5out_dir()),
16812870Sgabeblack@google.com                '--listener-mode=off',
16913003Sgabeblack@google.com                '--quiet',
17013461Sgabeblack@google.com                os.path.abspath(config_path),
17113000Sgabeblack@google.com            ])
17213002Sgabeblack@google.com            # Ensure the output directory exists.
17313002Sgabeblack@google.com            if not os.path.exists(test.m5out_dir()):
17413002Sgabeblack@google.com                os.makedirs(test.m5out_dir())
17513001Sgabeblack@google.com            try:
17613461Sgabeblack@google.com                subprocess.check_call(cmd, cwd=os.path.dirname(test.dir()))
17713001Sgabeblack@google.com            except subprocess.CalledProcessError, error:
17813001Sgabeblack@google.com                returncode = error.returncode
17913001Sgabeblack@google.com            else:
18013001Sgabeblack@google.com                returncode = 0
18113002Sgabeblack@google.com            with open(test.returncode_file(), 'w') as rc:
18213001Sgabeblack@google.com                rc.write('%d\n' % returncode)
18313000Sgabeblack@google.com
18413183Sgabeblack@google.com        j = self.main_args.j if args.j == 0 else args.j
18513183Sgabeblack@google.com
18613000Sgabeblack@google.com        runnable = filter(lambda t: not t.compile_only, tests)
18713183Sgabeblack@google.com        if j == 1:
18813000Sgabeblack@google.com            map(run_test, runnable)
18913000Sgabeblack@google.com        else:
19013183Sgabeblack@google.com            tp = multiprocessing.pool.ThreadPool(j)
19113000Sgabeblack@google.com            map(lambda t: tp.apply_async(run_test, (t,)), runnable)
19213000Sgabeblack@google.com            tp.close()
19313000Sgabeblack@google.com            tp.join()
19412870Sgabeblack@google.com
19513003Sgabeblack@google.comclass Checker(object):
19613003Sgabeblack@google.com    def __init__(self, ref, test, tag):
19713003Sgabeblack@google.com        self.ref = ref
19813003Sgabeblack@google.com        self.test = test
19913003Sgabeblack@google.com        self.tag = tag
20013003Sgabeblack@google.com
20113003Sgabeblack@google.com    def check(self):
20213240Sgabeblack@google.com        with open(self.test) as test_f, open(self.ref) as ref_f:
20313003Sgabeblack@google.com            return test_f.read() == ref_f.read()
20413003Sgabeblack@google.com
20513055Sgabeblack@google.comdef tagged_filt(tag, num):
20613178Sgabeblack@google.com    return (r'\n{}: \({}{}\) .*\n(In file: .*\n)?'
20713055Sgabeblack@google.com            r'(In process: [\w.]* @ .*\n)?').format(tag, tag[0], num)
20813055Sgabeblack@google.com
20913137Sgabeblack@google.comdef error_filt(num):
21013137Sgabeblack@google.com    return tagged_filt('Error', num)
21113137Sgabeblack@google.com
21213055Sgabeblack@google.comdef warning_filt(num):
21313055Sgabeblack@google.com    return tagged_filt('Warning', num)
21413055Sgabeblack@google.com
21513055Sgabeblack@google.comdef info_filt(num):
21613055Sgabeblack@google.com    return tagged_filt('Info', num)
21713055Sgabeblack@google.com
21813242Sgabeblack@google.comclass DiffingChecker(Checker):
21913242Sgabeblack@google.com    def __init__(self, ref, test, tag, out_dir):
22013242Sgabeblack@google.com        super(DiffingChecker, self).__init__(ref, test, tag)
22113242Sgabeblack@google.com        self.out_dir = out_dir
22213242Sgabeblack@google.com
22313242Sgabeblack@google.com    def diffing_check(self, ref_lines, test_lines):
22413242Sgabeblack@google.com        test_file = os.path.basename(self.test)
22513242Sgabeblack@google.com        ref_file = os.path.basename(self.ref)
22613242Sgabeblack@google.com
22713242Sgabeblack@google.com        diff_file = '.'.join([ref_file, 'diff'])
22813242Sgabeblack@google.com        diff_path = os.path.join(self.out_dir, diff_file)
22913242Sgabeblack@google.com        if test_lines != ref_lines:
23013242Sgabeblack@google.com            with open(diff_path, 'w') as diff_f:
23113242Sgabeblack@google.com                for line in difflib.unified_diff(
23213242Sgabeblack@google.com                        ref_lines, test_lines,
23313242Sgabeblack@google.com                        fromfile=ref_file,
23413242Sgabeblack@google.com                        tofile=test_file):
23513242Sgabeblack@google.com                    diff_f.write(line)
23613242Sgabeblack@google.com            return False
23713242Sgabeblack@google.com        else:
23813242Sgabeblack@google.com            if os.path.exists(diff_path):
23913242Sgabeblack@google.com                os.unlink(diff_path)
24013242Sgabeblack@google.com            return True
24113242Sgabeblack@google.com
24213242Sgabeblack@google.comclass LogChecker(DiffingChecker):
24313003Sgabeblack@google.com    def merge_filts(*filts):
24413003Sgabeblack@google.com        filts = map(lambda f: '(' + f + ')', filts)
24513003Sgabeblack@google.com        filts = '|'.join(filts)
24613003Sgabeblack@google.com        return re.compile(filts, flags=re.MULTILINE)
24713003Sgabeblack@google.com
24813139Sgabeblack@google.com    # The reporting mechanism will print the actual filename when running in
24913139Sgabeblack@google.com    # gem5, and the "golden" output will say "<removed by verify.py>". We want
25013139Sgabeblack@google.com    # to strip out both versions to make comparing the output sensible.
25113139Sgabeblack@google.com    in_file_filt = r'^In file: ((<removed by verify\.pl>)|([a-zA-Z0-9.:_/]*))$'
25213139Sgabeblack@google.com
25313003Sgabeblack@google.com    ref_filt = merge_filts(
25413003Sgabeblack@google.com        r'^\nInfo: /OSCI/SystemC: Simulation stopped by user.\n',
25513004Sgabeblack@google.com        r'^SystemC Simulation\n',
25613055Sgabeblack@google.com        r'^\nInfo: \(I804\) /IEEE_Std_1666/deprecated: ' +
25713055Sgabeblack@google.com        r'You can turn off(.*\n){7}',
25813056Sgabeblack@google.com        r'^\nInfo: \(I804\) /IEEE_Std_1666/deprecated: \n' +
25913056Sgabeblack@google.com        r'    sc_clock\(const char(.*\n){3}',
26013037Sgabeblack@google.com        warning_filt(540),
26113010Sgabeblack@google.com        warning_filt(571),
26213055Sgabeblack@google.com        info_filt(804),
26313250Sgabeblack@google.com        info_filt(704),
26413139Sgabeblack@google.com        in_file_filt,
26513003Sgabeblack@google.com    )
26613003Sgabeblack@google.com    test_filt = merge_filts(
26713055Sgabeblack@google.com        r'^Global frequency set at \d* ticks per second\n',
26813181Sgabeblack@google.com        r'^info: Entering event queue @ \d*\.  Starting simulation\.\.\.\n',
26913213Sgabeblack@google.com        r'warn: Ignoring request to set stack size\.\n',
27013055Sgabeblack@google.com        info_filt(804),
27113139Sgabeblack@google.com        in_file_filt,
27213003Sgabeblack@google.com    )
27313003Sgabeblack@google.com
27413003Sgabeblack@google.com    def apply_filters(self, data, filts):
27513003Sgabeblack@google.com        re.sub(filt, '', data)
27613003Sgabeblack@google.com
27713003Sgabeblack@google.com    def check(self):
27813003Sgabeblack@google.com        with open(self.test) as test_f, open(self.ref) as ref_f:
27913003Sgabeblack@google.com            test = re.sub(self.test_filt, '', test_f.read())
28013003Sgabeblack@google.com            ref = re.sub(self.ref_filt, '', ref_f.read())
28113242Sgabeblack@google.com            return self.diffing_check(ref.splitlines(True),
28213242Sgabeblack@google.com                                      test.splitlines(True))
28313242Sgabeblack@google.com
28413242Sgabeblack@google.comclass VcdChecker(DiffingChecker):
28513242Sgabeblack@google.com    def check(self):
28613242Sgabeblack@google.com        with open (self.test) as test_f, open(self.ref) as ref_f:
28713242Sgabeblack@google.com            ref = ref_f.read().splitlines(True)
28813242Sgabeblack@google.com            test = test_f.read().splitlines(True)
28913242Sgabeblack@google.com            # Strip off the first seven lines of the test output which are
29013242Sgabeblack@google.com            # date and version information.
29113242Sgabeblack@google.com            test = test[7:]
29213242Sgabeblack@google.com
29313242Sgabeblack@google.com            return self.diffing_check(ref, test)
29413003Sgabeblack@google.com
29513009Sgabeblack@google.comclass GoldenDir(object):
29613009Sgabeblack@google.com    def __init__(self, path, platform):
29713009Sgabeblack@google.com        self.path = path
29813009Sgabeblack@google.com        self.platform = platform
29913009Sgabeblack@google.com
30013009Sgabeblack@google.com        contents = os.listdir(path)
30113009Sgabeblack@google.com        suffix = '.' + platform
30213009Sgabeblack@google.com        suffixed = filter(lambda c: c.endswith(suffix), contents)
30313009Sgabeblack@google.com        bases = map(lambda t: t[:-len(platform)], suffixed)
30413009Sgabeblack@google.com        common = filter(lambda t: not t.startswith(tuple(bases)), contents)
30513009Sgabeblack@google.com
30613009Sgabeblack@google.com        self.entries = {}
30713009Sgabeblack@google.com        class Entry(object):
30813009Sgabeblack@google.com            def __init__(self, e_path):
30913009Sgabeblack@google.com                self.used = False
31013009Sgabeblack@google.com                self.path = os.path.join(path, e_path)
31113009Sgabeblack@google.com
31213009Sgabeblack@google.com            def use(self):
31313009Sgabeblack@google.com                self.used = True
31413009Sgabeblack@google.com
31513009Sgabeblack@google.com        for entry in contents:
31613009Sgabeblack@google.com            self.entries[entry] = Entry(entry)
31713009Sgabeblack@google.com
31813009Sgabeblack@google.com    def entry(self, name):
31913009Sgabeblack@google.com        def match(n):
32013009Sgabeblack@google.com            return (n == name) or n.startswith(name + '.')
32113009Sgabeblack@google.com        matches = { n: e for n, e in self.entries.items() if match(n) }
32213009Sgabeblack@google.com
32313009Sgabeblack@google.com        for match in matches.values():
32413009Sgabeblack@google.com            match.use()
32513009Sgabeblack@google.com
32613009Sgabeblack@google.com        platform_name = '.'.join([ name, self.platform ])
32713009Sgabeblack@google.com        if platform_name in matches:
32813009Sgabeblack@google.com            return matches[platform_name].path
32913009Sgabeblack@google.com        if name in matches:
33013009Sgabeblack@google.com            return matches[name].path
33113009Sgabeblack@google.com        else:
33213009Sgabeblack@google.com            return None
33313009Sgabeblack@google.com
33413009Sgabeblack@google.com    def unused(self):
33513009Sgabeblack@google.com        items = self.entries.items()
33613009Sgabeblack@google.com        items = filter(lambda i: not i[1].used, items)
33713009Sgabeblack@google.com
33813009Sgabeblack@google.com        items.sort()
33913009Sgabeblack@google.com        sources = []
34013009Sgabeblack@google.com        i = 0
34113009Sgabeblack@google.com        while i < len(items):
34213009Sgabeblack@google.com            root = items[i][0]
34313009Sgabeblack@google.com            sources.append(root)
34413009Sgabeblack@google.com            i += 1
34513009Sgabeblack@google.com            while i < len(items) and items[i][0].startswith(root):
34613009Sgabeblack@google.com                i += 1
34713009Sgabeblack@google.com        return sources
34813009Sgabeblack@google.com
34912870Sgabeblack@google.comclass VerifyPhase(TestPhaseBase):
35012870Sgabeblack@google.com    name = 'verify'
35112870Sgabeblack@google.com    number = 3
35212870Sgabeblack@google.com
35313002Sgabeblack@google.com    def reset_status(self):
35413002Sgabeblack@google.com        self._passed = []
35513002Sgabeblack@google.com        self._failed = {}
35613002Sgabeblack@google.com
35713002Sgabeblack@google.com    def passed(self, test):
35813002Sgabeblack@google.com        self._passed.append(test)
35913002Sgabeblack@google.com
36013003Sgabeblack@google.com    def failed(self, test, cause, note=''):
36113003Sgabeblack@google.com        test.set_prop('note', note)
36213002Sgabeblack@google.com        self._failed.setdefault(cause, []).append(test)
36313002Sgabeblack@google.com
36413002Sgabeblack@google.com    def print_status(self):
36513002Sgabeblack@google.com        total_passed = len(self._passed)
36613002Sgabeblack@google.com        total_failed = sum(map(len, self._failed.values()))
36713002Sgabeblack@google.com        print()
36813002Sgabeblack@google.com        print('Passed: {passed:4} - Failed: {failed:4}'.format(
36913002Sgabeblack@google.com                  passed=total_passed, failed=total_failed))
37013002Sgabeblack@google.com
37113002Sgabeblack@google.com    def write_result_file(self, path):
37213003Sgabeblack@google.com        results = {
37313003Sgabeblack@google.com            'passed': map(lambda t: t.props, self._passed),
37413003Sgabeblack@google.com            'failed': {
37513003Sgabeblack@google.com                cause: map(lambda t: t.props, tests) for
37613002Sgabeblack@google.com                       cause, tests in self._failed.iteritems()
37713003Sgabeblack@google.com            }
37813002Sgabeblack@google.com        }
37913002Sgabeblack@google.com        with open(path, 'w') as rf:
38013002Sgabeblack@google.com            json.dump(results, rf)
38113002Sgabeblack@google.com
38213002Sgabeblack@google.com    def print_results(self):
38313002Sgabeblack@google.com        print()
38413002Sgabeblack@google.com        print('Passed:')
38513003Sgabeblack@google.com        for path in sorted(list([ t.path for t in self._passed ])):
38613003Sgabeblack@google.com            print('    ', path)
38713002Sgabeblack@google.com
38813002Sgabeblack@google.com        print()
38913002Sgabeblack@google.com        print('Failed:')
39013002Sgabeblack@google.com
39113003Sgabeblack@google.com        causes = []
39213003Sgabeblack@google.com        for cause, tests in sorted(self._failed.items()):
39313003Sgabeblack@google.com            block = '  ' + cause.capitalize() + ':\n'
39413003Sgabeblack@google.com            for test in sorted(tests, key=lambda t: t.path):
39513003Sgabeblack@google.com                block += '    ' + test.path
39613003Sgabeblack@google.com                if test.note:
39713003Sgabeblack@google.com                    block += ' - ' + test.note
39813003Sgabeblack@google.com                block += '\n'
39913003Sgabeblack@google.com            causes.append(block)
40013002Sgabeblack@google.com
40113003Sgabeblack@google.com        print('\n'.join(causes))
40213002Sgabeblack@google.com
40312870Sgabeblack@google.com    def run(self, tests):
40413002Sgabeblack@google.com        parser = argparse.ArgumentParser()
40513002Sgabeblack@google.com        result_opts = parser.add_mutually_exclusive_group()
40613002Sgabeblack@google.com        result_opts.add_argument('--result-file', action='store_true',
40713002Sgabeblack@google.com                help='Create a results.json file in the current directory.')
40813002Sgabeblack@google.com        result_opts.add_argument('--result-file-at', metavar='PATH',
40913002Sgabeblack@google.com                help='Create a results json file at the given path.')
41013183Sgabeblack@google.com        parser.add_argument('--no-print-results', action='store_true',
41113183Sgabeblack@google.com                help='Don\'t print a list of tests that passed or failed')
41213002Sgabeblack@google.com        args = parser.parse_args(self.args)
41312870Sgabeblack@google.com
41413002Sgabeblack@google.com        self.reset_status()
41513002Sgabeblack@google.com
41613002Sgabeblack@google.com        runnable = filter(lambda t: not t.compile_only, tests)
41713002Sgabeblack@google.com        compile_only = filter(lambda t: t.compile_only, tests)
41813002Sgabeblack@google.com
41913002Sgabeblack@google.com        for test in compile_only:
42013002Sgabeblack@google.com            if os.path.exists(test.full_path()):
42113002Sgabeblack@google.com                self.passed(test)
42213002Sgabeblack@google.com            else:
42313002Sgabeblack@google.com                self.failed(test, 'compile failed')
42413002Sgabeblack@google.com
42513002Sgabeblack@google.com        for test in runnable:
42613002Sgabeblack@google.com            with open(test.returncode_file()) as rc:
42713002Sgabeblack@google.com                returncode = int(rc.read())
42813002Sgabeblack@google.com
42913134Sgabeblack@google.com            expected_returncode = 0
43013134Sgabeblack@google.com            if os.path.exists(test.expected_returncode_file()):
43113134Sgabeblack@google.com                with open(test.expected_returncode_file()) as erc:
43213134Sgabeblack@google.com                    expected_returncode = int(erc.read())
43313134Sgabeblack@google.com
43413003Sgabeblack@google.com            if returncode == 124:
43513002Sgabeblack@google.com                self.failed(test, 'time out')
43613003Sgabeblack@google.com                continue
43713134Sgabeblack@google.com            elif returncode != expected_returncode:
43813134Sgabeblack@google.com                if expected_returncode == 0:
43913134Sgabeblack@google.com                    self.failed(test, 'abort')
44013134Sgabeblack@google.com                else:
44113134Sgabeblack@google.com                    self.failed(test, 'missed abort')
44213003Sgabeblack@google.com                continue
44313003Sgabeblack@google.com
44413003Sgabeblack@google.com            out_dir = test.m5out_dir()
44513003Sgabeblack@google.com
44613003Sgabeblack@google.com            Diff = collections.namedtuple(
44713003Sgabeblack@google.com                    'Diff', 'ref, test, tag, ref_filter')
44813003Sgabeblack@google.com
44913003Sgabeblack@google.com            diffs = []
45013003Sgabeblack@google.com
45113009Sgabeblack@google.com            gd = GoldenDir(test.golden_dir(), 'linux64')
45213009Sgabeblack@google.com
45313009Sgabeblack@google.com            missing = []
45413003Sgabeblack@google.com            log_file = '.'.join([test.name, 'log'])
45513009Sgabeblack@google.com            log_path = gd.entry(log_file)
45613003Sgabeblack@google.com            simout_path = os.path.join(out_dir, 'simout')
45713003Sgabeblack@google.com            if not os.path.exists(simout_path):
45813009Sgabeblack@google.com                missing.append('log output')
45913009Sgabeblack@google.com            elif log_path:
46013009Sgabeblack@google.com                diffs.append(LogChecker(log_path, simout_path,
46113009Sgabeblack@google.com                                        log_file, out_dir))
46213009Sgabeblack@google.com
46313009Sgabeblack@google.com            for name in gd.unused():
46413009Sgabeblack@google.com                test_path = os.path.join(out_dir, name)
46513009Sgabeblack@google.com                ref_path = gd.entry(name)
46613009Sgabeblack@google.com                if not os.path.exists(test_path):
46713009Sgabeblack@google.com                    missing.append(name)
46813242Sgabeblack@google.com                elif name.endswith('.vcd'):
46913242Sgabeblack@google.com                    diffs.append(VcdChecker(ref_path, test_path,
47013242Sgabeblack@google.com                                            name, out_dir))
47113009Sgabeblack@google.com                else:
47213009Sgabeblack@google.com                    diffs.append(Checker(ref_path, test_path, name))
47313009Sgabeblack@google.com
47413009Sgabeblack@google.com            if missing:
47513009Sgabeblack@google.com                self.failed(test, 'missing output', ' '.join(missing))
47613009Sgabeblack@google.com                continue
47713003Sgabeblack@google.com
47813003Sgabeblack@google.com            failed_diffs = filter(lambda d: not d.check(), diffs)
47913003Sgabeblack@google.com            if failed_diffs:
48013003Sgabeblack@google.com                tags = map(lambda d: d.tag, failed_diffs)
48113003Sgabeblack@google.com                self.failed(test, 'failed diffs', ' '.join(tags))
48213003Sgabeblack@google.com                continue
48313003Sgabeblack@google.com
48413003Sgabeblack@google.com            self.passed(test)
48513002Sgabeblack@google.com
48613183Sgabeblack@google.com        if not args.no_print_results:
48713002Sgabeblack@google.com            self.print_results()
48813002Sgabeblack@google.com
48913002Sgabeblack@google.com        self.print_status()
49013002Sgabeblack@google.com
49113002Sgabeblack@google.com        result_path = None
49213002Sgabeblack@google.com        if args.result_file:
49313002Sgabeblack@google.com            result_path = os.path.join(os.getcwd(), 'results.json')
49413002Sgabeblack@google.com        elif args.result_file_at:
49513002Sgabeblack@google.com            result_path = args.result_file_at
49613002Sgabeblack@google.com
49713002Sgabeblack@google.com        if result_path:
49813002Sgabeblack@google.com            self.write_result_file(result_path)
49912870Sgabeblack@google.com
50012870Sgabeblack@google.com
50112870Sgabeblack@google.comparser = argparse.ArgumentParser(description='SystemC test utility')
50212870Sgabeblack@google.com
50312870Sgabeblack@google.comparser.add_argument('build_dir', metavar='BUILD_DIR',
50412870Sgabeblack@google.com                    help='The build directory (ie. build/ARM).')
50512870Sgabeblack@google.com
50612870Sgabeblack@google.comparser.add_argument('--update-json', action='store_true',
50712870Sgabeblack@google.com                    help='Update the json manifest of tests.')
50812870Sgabeblack@google.com
50912870Sgabeblack@google.comparser.add_argument('--flavor', choices=['debug', 'opt', 'fast'],
51012870Sgabeblack@google.com                    default='opt',
51112870Sgabeblack@google.com                    help='Flavor of binary to test.')
51212870Sgabeblack@google.com
51312870Sgabeblack@google.comparser.add_argument('--list', action='store_true',
51412870Sgabeblack@google.com                    help='List the available tests')
51512870Sgabeblack@google.com
51613183Sgabeblack@google.comparser.add_argument('-j', type=int, default=1,
51713183Sgabeblack@google.com                    help='Default level of parallelism, can be overriden '
51813183Sgabeblack@google.com                    'for individual stages')
51913183Sgabeblack@google.com
52013705Sgabeblack@google.comparser.add_argument('-C', '--scons-dir', metavar='SCONS_DIR',
52113705Sgabeblack@google.com                    default=checkout_dir,
52213705Sgabeblack@google.com                    help='Directory to run scons from')
52313705Sgabeblack@google.com
52412903Sgabeblack@google.comfilter_opts = parser.add_mutually_exclusive_group()
52512903Sgabeblack@google.comfilter_opts.add_argument('--filter', default='True',
52612903Sgabeblack@google.com                         help='Python expression which filters tests based '
52712903Sgabeblack@google.com                         'on their properties')
52812903Sgabeblack@google.comfilter_opts.add_argument('--filter-file', default=None,
52912903Sgabeblack@google.com                         type=argparse.FileType('r'),
53012903Sgabeblack@google.com                         help='Same as --filter, but read from a file')
53112870Sgabeblack@google.com
53212870Sgabeblack@google.comdef collect_phases(args):
53312870Sgabeblack@google.com    phase_groups = [list(g) for k, g in
53412870Sgabeblack@google.com                    itertools.groupby(args, lambda x: x != '--phase') if k]
53512870Sgabeblack@google.com    main_args = parser.parse_args(phase_groups[0][1:])
53612870Sgabeblack@google.com    phases = []
53712870Sgabeblack@google.com    names = []
53812870Sgabeblack@google.com    for group in phase_groups[1:]:
53912870Sgabeblack@google.com        name = group[0]
54012870Sgabeblack@google.com        if name in names:
54112870Sgabeblack@google.com            raise RuntimeException('Phase %s specified more than once' % name)
54212870Sgabeblack@google.com        phase = test_phase_classes[name]
54312870Sgabeblack@google.com        phases.append(phase(main_args, *group[1:]))
54412870Sgabeblack@google.com    phases.sort()
54512870Sgabeblack@google.com    return main_args, phases
54612870Sgabeblack@google.com
54712870Sgabeblack@google.commain_args, phases = collect_phases(sys.argv)
54812870Sgabeblack@google.com
54912870Sgabeblack@google.comif len(phases) == 0:
55012870Sgabeblack@google.com    phases = [
55112870Sgabeblack@google.com        CompilePhase(main_args),
55212870Sgabeblack@google.com        RunPhase(main_args),
55312870Sgabeblack@google.com        VerifyPhase(main_args)
55412870Sgabeblack@google.com    ]
55512870Sgabeblack@google.com
55612870Sgabeblack@google.com
55712870Sgabeblack@google.com
55812870Sgabeblack@google.comjson_path = os.path.join(main_args.build_dir, json_rel_path)
55912870Sgabeblack@google.com
56012870Sgabeblack@google.comif main_args.update_json:
56113705Sgabeblack@google.com    scons('--directory', main_args.scons_dir, os.path.join(json_path))
56212870Sgabeblack@google.com
56312870Sgabeblack@google.comwith open(json_path) as f:
56412870Sgabeblack@google.com    test_data = json.load(f)
56512870Sgabeblack@google.com
56612903Sgabeblack@google.com    if main_args.filter_file:
56712903Sgabeblack@google.com        f = main_args.filter_file
56812903Sgabeblack@google.com        filt = compile(f.read(), f.name, 'eval')
56912903Sgabeblack@google.com    else:
57012903Sgabeblack@google.com        filt = compile(main_args.filter, '<string>', 'eval')
57112903Sgabeblack@google.com
57212903Sgabeblack@google.com    filtered_tests = {
57312903Sgabeblack@google.com        target: props for (target, props) in
57412903Sgabeblack@google.com                    test_data.iteritems() if eval(filt, dict(props))
57512903Sgabeblack@google.com    }
57612903Sgabeblack@google.com
57713101Sgabeblack@google.com    if len(filtered_tests) == 0:
57813101Sgabeblack@google.com        print('All tests were filtered out.')
57913101Sgabeblack@google.com        exit()
58013101Sgabeblack@google.com
58112870Sgabeblack@google.com    if main_args.list:
58212903Sgabeblack@google.com        for target, props in sorted(filtered_tests.iteritems()):
58312870Sgabeblack@google.com            print('%s.%s' % (target, main_args.flavor))
58412870Sgabeblack@google.com            for key, val in props.iteritems():
58512870Sgabeblack@google.com                print('    %s: %s' % (key, val))
58612937Sgabeblack@google.com        print('Total tests: %d' % len(filtered_tests))
58712870Sgabeblack@google.com    else:
58812903Sgabeblack@google.com        tests_to_run = list([
58912903Sgabeblack@google.com            Test(target, main_args.flavor, main_args.build_dir, props) for
59012903Sgabeblack@google.com                target, props in sorted(filtered_tests.iteritems())
59112903Sgabeblack@google.com        ])
59212870Sgabeblack@google.com
59312870Sgabeblack@google.com        for phase in phases:
59412870Sgabeblack@google.com            phase.run(tests_to_run)
595