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