SConscript revision 8492:1ad244a20877
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# Dict that accumulates lists of tests by category (quick, medium, long)
42env.Tests = {}
43
44def contents(node):
45    return file(str(node)).read()
46
47# functions to parse return value from scons Execute()... not the same
48# as wait() etc., so python built-in os funcs don't work.
49def signaled(status):
50    return (status & 0x80) != 0;
51
52def signum(status):
53    return (status & 0x7f);
54
55# List of signals that indicate that we should retry the test rather
56# than consider it failed.
57retry_signals = (signal.SIGTERM, signal.SIGKILL, signal.SIGINT,
58                 signal.SIGQUIT, signal.SIGHUP)
59
60# regular expressions of lines to ignore when diffing outputs
61output_ignore_regexes = (
62    '^command line:',		# for stdout file
63    '^M5 compiled ',		# for stderr file
64    '^M5 started ',		# for stderr file
65    '^M5 executing on ',	# for stderr file
66    '^Simulation complete at',	# for stderr file
67    '^Listening for',		# for stderr file
68    'listening for remote gdb',	# for stderr file
69    )
70
71output_ignore_args = ' '.join(["-I '"+s+"'" for s in output_ignore_regexes])
72
73output_ignore_args += ' --exclude=stats.txt --exclude=outdiff'
74
75def run_test(target, source, env):
76    """Check output from running test.
77
78    Targets are as follows:
79    target[0] : status
80
81    Sources are:
82    source[0] : M5 binary
83    source[1] : tests/run.py script
84    source[2] : reference stats file
85
86    """
87    # make sure target files are all gone
88    for t in target:
89        if os.path.exists(t.abspath):
90            env.Execute(Delete(t.abspath))
91
92    tgt_dir = os.path.dirname(str(target[0]))
93
94    # Base command for running test.  We mess around with indirectly
95    # referring to files via SOURCES and TARGETS so that scons can mess
96    # with paths all it wants to and we still get the right files.
97    cmd = '${SOURCES[0]} -d %s -re ${SOURCES[1]} %s' % (tgt_dir, tgt_dir)
98
99    # Prefix test run with batch job submission command if appropriate.
100    # Batch command also supports timeout arg (in seconds, not minutes).
101    timeout = 15 * 60 # used to be a param, probably should be again
102    if env['BATCH']:
103        cmd = '%s -t %d %s' % (env['BATCH_CMD'], timeout, cmd)
104
105    pre_exec_time = time.time()
106    status = env.Execute(env.subst(cmd, target=target, source=source))
107    if status == 0:
108        # M5 terminated normally.
109        # Run diff on output & ref directories to find differences.
110        # Exclude the stats file since we will use diff-out on that.
111
112        # NFS file systems can be annoying and not have updated yet
113        # wait until we see the file modified
114        statsdiff = os.path.join(tgt_dir, 'statsdiff')
115        m_time = 0
116        nap = 0
117        while m_time < pre_exec_time and nap < 10:
118            try:
119                m_time = os.stat(statsdiff).st_mtime
120            except OSError:
121                pass
122            time.sleep(1)
123            nap += 1
124
125        outdiff = os.path.join(tgt_dir, 'outdiff')
126        diffcmd = 'diff -ubrs %s ${SOURCES[2].dir} %s > %s' \
127                  % (output_ignore_args, tgt_dir, outdiff)
128        env.Execute(env.subst(diffcmd, target=target, source=source))
129        print "===== Output differences ====="
130        print contents(outdiff)
131        # Run diff-out on stats.txt file
132        diffcmd = '$DIFFOUT ${SOURCES[2]} %s > %s' \
133                  % (os.path.join(tgt_dir, 'stats.txt'), statsdiff)
134        diffcmd = env.subst(diffcmd, target=target, source=source)
135        status = env.Execute(diffcmd, strfunction=None)
136        print "===== Statistics differences ====="
137        print contents(statsdiff)
138
139    else: # m5 exit status != 0
140        # M5 did not terminate properly, so no need to check the output
141        if signaled(status):
142            print 'M5 terminated with signal', signum(status)
143            if signum(status) in retry_signals:
144                # Consider the test incomplete; don't create a 'status' output.
145                # Hand the return status to scons and let scons decide what
146                # to do about it (typically terminate unless run with -k).
147                return status
148        else:
149            print 'M5 exited with non-zero status', status
150        # complete but failed execution (call to exit() with non-zero
151        # status, SIGABORT due to assertion failure, etc.)... fall through
152        # and generate FAILED status as if output comparison had failed
153
154    # Generate status file contents based on exit status of m5 or diff-out
155    if status == 0:
156        status_str = "passed."
157    else:
158        status_str = "FAILED!"
159    f = file(str(target[0]), 'w')
160    print >>f, tgt_dir, status_str
161    f.close()
162    # done
163    return 0
164
165def run_test_string(target, source, env):
166    return env.subst("Running test in ${TARGETS[0].dir}.",
167                     target=target, source=source)
168
169testAction = env.Action(run_test, run_test_string)
170
171def print_test(target, source, env):
172    print '***** ' + contents(source[0])
173    return 0
174
175printAction = env.Action(print_test, strfunction = None)
176
177# Static vars for update_test:
178# - long-winded message about ignored sources
179ignore_msg = '''
180Note: The following file(s) will not be copied.  New non-standard
181      output files must be copied manually once before --update-ref will
182      recognize them as outputs.  Otherwise they are assumed to be
183      inputs and are ignored.
184'''
185# - reference files always needed
186needed_files = set(['simout', 'simerr', 'stats.txt', 'config.ini'])
187# - source files we always want to ignore
188known_ignores = set(['status', 'outdiff', 'statsdiff'])
189
190def update_test(target, source, env):
191    """Update reference test outputs.
192
193    Target is phony.  First two sources are the ref & new stats.txt file
194    files, respectively.  We actually copy everything in the
195    respective directories except the status & diff output files.
196
197    """
198    dest_dir = str(source[0].get_dir())
199    src_dir = str(source[1].get_dir())
200    dest_files = set(os.listdir(dest_dir))
201    src_files = set(os.listdir(src_dir))
202    # Copy all of the required files plus any existing dest files.
203    wanted_files = needed_files | dest_files
204    missing_files = wanted_files - src_files
205    if len(missing_files) > 0:
206        print "  WARNING: the following file(s) are missing " \
207              "and will not be updated:"
208        print "    ", " ,".join(missing_files)
209    copy_files = wanted_files - missing_files
210    warn_ignored_files = (src_files - copy_files) - known_ignores
211    if len(warn_ignored_files) > 0:
212        print ignore_msg,
213        print "       ", ", ".join(warn_ignored_files)
214    for f in copy_files:
215        if f in dest_files:
216            print "  Replacing file", f
217            dest_files.remove(f)
218        else:
219            print "  Creating new file", f
220        copyAction = Copy(os.path.join(dest_dir, f), os.path.join(src_dir, f))
221        copyAction.strfunction = None
222        env.Execute(copyAction)
223    return 0
224
225def update_test_string(target, source, env):
226    return env.subst("Updating ${SOURCES[0].dir} from ${SOURCES[1].dir}",
227                     target=target, source=source)
228
229updateAction = env.Action(update_test, update_test_string)
230
231def test_builder(env, ref_dir):
232    """Define a test."""
233
234    (category, name, _ref, isa, opsys, config) = ref_dir.split('/')
235    assert(_ref == 'ref')
236
237    # target path (where test output goes) is the same except without
238    # the 'ref' component
239    tgt_dir = os.path.join(category, name, isa, opsys, config)
240
241    # prepend file name with tgt_dir
242    def tgt(f):
243        return os.path.join(tgt_dir, f)
244
245    ref_stats = os.path.join(ref_dir, 'stats.txt')
246    new_stats = tgt('stats.txt')
247    status_file = tgt('status')
248
249    env.Command([status_file],
250                [env.M5Binary, 'run.py', ref_stats],
251                testAction)
252
253    # phony target to echo status
254    if GetOption('update_ref'):
255        p = env.Command(tgt('_update'),
256                        [ref_stats, new_stats, status_file],
257                        updateAction)
258    else:
259        p = env.Command(tgt('_print'), [status_file], printAction)
260
261    env.AlwaysBuild(p)
262
263
264# Figure out applicable configs based on build type
265configs = []
266if env['FULL_SYSTEM']:
267    if env['TARGET_ISA'] == 'alpha':
268        configs += ['tsunami-simple-atomic',
269                    'tsunami-simple-timing',
270                    'tsunami-simple-atomic-dual',
271                    'tsunami-simple-timing-dual',
272                    'twosys-tsunami-simple-atomic',
273                    'tsunami-o3', 'tsunami-o3-dual',
274                    'tsunami-inorder']
275    if env['TARGET_ISA'] == 'sparc':
276        configs += ['t1000-simple-atomic',
277                    't1000-simple-timing']
278    if env['TARGET_ISA'] == 'arm':
279        configs += ['realview-simple-atomic',
280                    'realview-simple-timing',
281                    'realview-o3']
282    if env['TARGET_ISA'] == 'x86':
283        configs += ['pc-simple-atomic',
284                    'pc-simple-timing']
285
286else:
287    configs += ['simple-atomic', 'simple-timing', 'o3-timing', 'memtest',
288                'simple-atomic-mp', 'simple-timing-mp', 'o3-timing-mp',
289                'inorder-timing', 'rubytest']
290
291if env['PROTOCOL'] != 'None':
292    if env['PROTOCOL'] == 'MI_example':
293        configs += [c + "-ruby" for c in configs]
294    else:
295        configs = [c + "-ruby-" + env['PROTOCOL'] for c in configs]
296
297cwd = os.getcwd()
298os.chdir(str(Dir('.').srcdir))
299for config in configs:
300    dirs = glob.glob('*/*/ref/%s/*/%s' % (env['TARGET_ISA'], config))
301    for d in dirs:
302        if not os.path.exists(os.path.join(d, 'skip')):
303            test_builder(env, d)
304os.chdir(cwd)
305