SConscript revision 10260
1# -*- mode:python -*-
2
3# Copyright (c) 2004-2006 The Regents of The University of Michigan
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met: redistributions of source code must retain the above copyright
9# notice, this list of conditions and the following disclaimer;
10# redistributions in binary form must reproduce the above copyright
11# notice, this list of conditions and the following disclaimer in the
12# documentation and/or other materials provided with the distribution;
13# neither the name of the copyright holders nor the names of its
14# contributors may be used to endorse or promote products derived from
15# this software without specific prior written permission.
16#
17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28#
29# Authors: Steve Reinhardt
30#          Kevin Lim
31
32import os, signal
33import sys, time
34import glob
35from SCons.Script.SConscript import SConsEnvironment
36
37Import('env')
38
39env['DIFFOUT'] = File('diff-out')
40
41# get the termcap from the environment
42termcap = env['TERMCAP']
43
44# Dict that accumulates lists of tests by category (quick, medium, long)
45env.Tests = {}
46
47def contents(node):
48    return file(str(node)).read()
49
50# functions to parse return value from scons Execute()... not the same
51# as wait() etc., so python built-in os funcs don't work.
52def signaled(status):
53    return (status & 0x80) != 0;
54
55def signum(status):
56    return (status & 0x7f);
57
58# List of signals that indicate that we should retry the test rather
59# than consider it failed.
60retry_signals = (signal.SIGTERM, signal.SIGKILL, signal.SIGINT,
61                 signal.SIGQUIT, signal.SIGHUP)
62
63# regular expressions of lines to ignore when diffing outputs
64output_ignore_regexes = (
65    '^command line:',		# for stdout file
66    '^gem5 compiled ',		# for stderr file
67    '^gem5 started ',		# for stderr file
68    '^gem5 executing on ',	# for stderr file
69    '^Simulation complete at',	# for stderr file
70    '^Listening for',		# for stderr file
71    'listening for remote gdb',	# for stderr file
72    )
73
74output_ignore_args = ' '.join(["-I '"+s+"'" for s in output_ignore_regexes])
75
76output_ignore_args += ' --exclude=stats.txt --exclude=outdiff'
77
78def run_test(target, source, env):
79    """Check output from running test.
80
81    Targets are as follows:
82    target[0] : status
83
84    Sources are:
85    source[0] : gem5 binary
86    source[1] : tests/run.py script
87    source[2] : reference stats file
88
89    """
90    # make sure target files are all gone
91    for t in target:
92        if os.path.exists(t.abspath):
93            env.Execute(Delete(t.abspath))
94
95    tgt_dir = os.path.dirname(str(target[0]))
96
97    # Base command for running test.  We mess around with indirectly
98    # referring to files via SOURCES and TARGETS so that scons can mess
99    # with paths all it wants to and we still get the right files.
100    cmd = '${SOURCES[0]} -d %s -re ${SOURCES[1]} %s' % (tgt_dir, tgt_dir)
101
102    # Prefix test run with batch job submission command if appropriate.
103    # Batch command also supports timeout arg (in seconds, not minutes).
104    timeout = 15 * 60 # used to be a param, probably should be again
105    if env['BATCH']:
106        cmd = '%s -t %d %s' % (env['BATCH_CMD'], timeout, cmd)
107
108    # Create a default value for the status string, changed as needed
109    # based on the status.
110    status_str = "passed."
111
112    pre_exec_time = time.time()
113    status = env.Execute(env.subst(cmd, target=target, source=source))
114    if status == 0:
115        # gem5 terminated normally.
116        # Run diff on output & ref directories to find differences.
117        # Exclude the stats file since we will use diff-out on that.
118
119        # NFS file systems can be annoying and not have updated yet
120        # wait until we see the file modified
121        statsdiff = os.path.join(tgt_dir, 'statsdiff')
122        m_time = 0
123        nap = 0
124        while m_time < pre_exec_time and nap < 10:
125            try:
126                m_time = os.stat(statsdiff).st_mtime
127            except OSError:
128                pass
129            time.sleep(1)
130            nap += 1
131
132        outdiff = os.path.join(tgt_dir, 'outdiff')
133        # tack 'true' on the end so scons doesn't report diff's
134        # non-zero exit code as a build error
135        diffcmd = 'diff -ubrs %s ${SOURCES[2].dir} %s > %s; true' \
136                  % (output_ignore_args, tgt_dir, outdiff)
137        env.Execute(env.subst(diffcmd, target=target, source=source))
138        print "===== Output differences ====="
139        print contents(outdiff)
140        # Run diff-out on stats.txt file
141        diffcmd = '$DIFFOUT ${SOURCES[2]} %s > %s' \
142                  % (os.path.join(tgt_dir, 'stats.txt'), statsdiff)
143        diffcmd = env.subst(diffcmd, target=target, source=source)
144        diff_status = env.Execute(diffcmd, strfunction=None)
145        # If there is a difference, change the status string to say so
146        if diff_status != 0:
147            status_str = "CHANGED!"
148        print "===== Statistics differences ====="
149        print contents(statsdiff)
150
151    else: # gem5 exit status != 0
152        # Consider it a failed test unless the exit status is 2
153        status_str = "FAILED!"
154        # gem5 did not terminate properly, so no need to check the output
155        if signaled(status):
156            print 'gem5 terminated with signal', signum(status)
157            if signum(status) in retry_signals:
158                # Consider the test incomplete; don't create a 'status' output.
159                # Hand the return status to scons and let scons decide what
160                # to do about it (typically terminate unless run with -k).
161                return status
162        elif status == 2:
163            # The test was skipped, change the status string to say so
164            status_str = "skipped."
165        else:
166            print 'gem5 exited with non-zero status', status
167        # complete but failed execution (call to exit() with non-zero
168        # status, SIGABORT due to assertion failure, etc.)... fall through
169        # and generate FAILED status as if output comparison had failed
170
171    # Generate status file contents based on exit status of gem5 and diff-out
172    f = file(str(target[0]), 'w')
173    print >>f, tgt_dir, status_str
174    f.close()
175    # done
176    return 0
177
178def run_test_string(target, source, env):
179    return env.subst("Running test in ${TARGETS[0].dir}.",
180                     target=target, source=source)
181
182testAction = env.Action(run_test, run_test_string)
183
184def print_test(target, source, env):
185    # print the status with colours to make it easier to see what
186    # passed and what failed
187    line = contents(source[0])
188
189    # split the line to words and get the last one
190    words = line.split()
191    status = words[-1]
192
193    # if the test failed make it red, if it passed make it green, and
194    # skip the punctuation
195    if status == "FAILED!":
196        status = termcap.Red + status[:-1] + termcap.Normal + status[-1]
197    elif status == "CHANGED!":
198        status = termcap.Yellow + status[:-1] + termcap.Normal + status[-1]
199    elif status == "passed.":
200        status = termcap.Green + status[:-1] + termcap.Normal + status[-1]
201    elif status == "skipped.":
202        status = termcap.Cyan + status[:-1] + termcap.Normal + status[-1]
203
204    # put it back in the list and join with space
205    words[-1] = status
206    line = " ".join(words)
207
208    print '***** ' + line
209    return 0
210
211printAction = env.Action(print_test, strfunction = None)
212
213# Static vars for update_test:
214# - long-winded message about ignored sources
215ignore_msg = '''
216Note: The following file(s) will not be copied.  New non-standard
217      output files must be copied manually once before --update-ref will
218      recognize them as outputs.  Otherwise they are assumed to be
219      inputs and are ignored.
220'''
221# - reference files always needed
222needed_files = set(['simout', 'simerr', 'stats.txt', 'config.ini'])
223# - source files we always want to ignore
224known_ignores = set(['status', 'outdiff', 'statsdiff'])
225
226def update_test(target, source, env):
227    """Update reference test outputs.
228
229    Target is phony.  First two sources are the ref & new stats.txt file
230    files, respectively.  We actually copy everything in the
231    respective directories except the status & diff output files.
232
233    """
234    dest_dir = str(source[0].get_dir())
235    src_dir = str(source[1].get_dir())
236    dest_files = set(os.listdir(dest_dir))
237    src_files = set(os.listdir(src_dir))
238    # Copy all of the required files plus any existing dest files.
239    wanted_files = needed_files | dest_files
240    missing_files = wanted_files - src_files
241    if len(missing_files) > 0:
242        print "  WARNING: the following file(s) are missing " \
243              "and will not be updated:"
244        print "    ", " ,".join(missing_files)
245    copy_files = wanted_files - missing_files
246    warn_ignored_files = (src_files - copy_files) - known_ignores
247    if len(warn_ignored_files) > 0:
248        print ignore_msg,
249        print "       ", ", ".join(warn_ignored_files)
250    for f in copy_files:
251        if f in dest_files:
252            print "  Replacing file", f
253            dest_files.remove(f)
254        else:
255            print "  Creating new file", f
256        copyAction = Copy(os.path.join(dest_dir, f), os.path.join(src_dir, f))
257        copyAction.strfunction = None
258        env.Execute(copyAction)
259    return 0
260
261def update_test_string(target, source, env):
262    return env.subst("Updating ${SOURCES[0].dir} from ${SOURCES[1].dir}",
263                     target=target, source=source)
264
265updateAction = env.Action(update_test, update_test_string)
266
267def test_builder(env, ref_dir):
268    """Define a test."""
269
270    path = list(ref_dir.split('/'))
271
272    # target path (where test output goes) consists of category, mode,
273    # name, isa, opsys, and config (skips the 'ref' component)
274    assert(path.pop(-4) == 'ref')
275    tgt_dir = os.path.join(*path[-6:])
276
277    # local closure for prepending target path to filename
278    def tgt(f):
279        return os.path.join(tgt_dir, f)
280
281    ref_stats = os.path.join(ref_dir, 'stats.txt')
282    new_stats = tgt('stats.txt')
283    status_file = tgt('status')
284
285    env.Command([status_file, new_stats],
286                [env.M5Binary, 'run.py', ref_stats],
287                testAction)
288
289    # phony target to echo status
290    if GetOption('update_ref'):
291        p = env.Command(tgt('_update'),
292                        [ref_stats, new_stats, status_file],
293                        updateAction)
294    else:
295        p = env.Command(tgt('_print'), [status_file], printAction)
296
297    env.AlwaysBuild(p)
298
299
300# Figure out applicable configs based on build type
301configs = []
302if env['TARGET_ISA'] == 'alpha':
303    configs += ['tsunami-simple-atomic',
304                'tsunami-simple-timing',
305                'tsunami-simple-atomic-dual',
306                'tsunami-simple-timing-dual',
307                'twosys-tsunami-simple-atomic',
308                'tsunami-o3', 'tsunami-o3-dual',
309                'tsunami-minor', 'tsunami-minor-dual',
310                'tsunami-inorder',
311                'tsunami-switcheroo-full']
312if env['TARGET_ISA'] == 'sparc':
313    configs += ['t1000-simple-atomic',
314                't1000-simple-timing']
315if env['TARGET_ISA'] == 'arm':
316    configs += ['simple-atomic-dummychecker',
317                'o3-timing-checker',
318                'realview-simple-atomic',
319                'realview-simple-atomic-dual',
320                'realview-simple-timing',
321                'realview-simple-timing-dual',
322                'realview-o3',
323                'realview-o3-checker',
324                'realview-o3-dual',
325                'realview-minor',
326                'realview-minor-dual',
327                'realview-switcheroo-atomic',
328                'realview-switcheroo-timing',
329                'realview-switcheroo-o3',
330                'realview-switcheroo-full']
331if env['TARGET_ISA'] == 'x86':
332    configs += ['pc-simple-atomic',
333                'pc-simple-timing',
334                'pc-o3-timing',
335                'pc-switcheroo-full']
336
337configs += ['simple-atomic', 'simple-atomic-mp',
338            'simple-timing', 'simple-timing-mp',
339            'inorder-timing',
340            'minor-timing', 'minor-timing-mp',
341            'o3-timing', 'o3-timing-mp',
342            'rubytest', 'memtest',
343            'tgen-simple-mem', 'tgen-dram-ctrl']
344
345if env['PROTOCOL'] != 'None':
346    if env['PROTOCOL'] == 'MI_example':
347        configs += [c + "-ruby" for c in configs]
348    else:
349        configs = [c + "-ruby-" + env['PROTOCOL'] for c in configs]
350
351src = Dir('.').srcdir
352for config in configs:
353    dirs = src.glob('*/*/*/ref/%s/*/%s' % (env['TARGET_ISA'], config))
354    for d in dirs:
355        d = str(d)
356        if not os.path.exists(os.path.join(d, 'skip')):
357            test_builder(env, d)
358