SConstruct revision 3053
1# -*- mode:python -*-
2
3# Copyright (c) 2004-2005 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
31###################################################
32#
33# SCons top-level build description (SConstruct) file.
34#
35# While in this directory ('m5'), just type 'scons' to build the default
36# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
37# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
38# the optimized full-system version).
39#
40# You can build M5 in a different directory as long as there is a
41# 'build/<CONFIG>' somewhere along the target path.  The build system
42# expects that all configs under the same build directory are being
43# built for the same host system.
44#
45# Examples:
46#
47#   The following two commands are equivalent.  The '-u' option tells
48#   scons to search up the directory tree for this SConstruct file.
49#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
50#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
51#
52#   The following two commands are equivalent and demonstrate building
53#   in a directory outside of the source tree.  The '-C' option tells
54#   scons to chdir to the specified directory to find this SConstruct
55#   file.
56#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
57#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
58#
59# You can use 'scons -H' to print scons options.  If you're in this
60# 'm5' directory (or use -u or -C to tell scons where to find this
61# file), you can use 'scons -h' to print all the M5-specific build
62# options as well.
63#
64###################################################
65
66# Python library imports
67import sys
68import os
69
70# Check for recent-enough Python and SCons versions.  If your system's
71# default installation of Python is not recent enough, you can use a
72# non-default installation of the Python interpreter by either (1)
73# rearranging your PATH so that scons finds the non-default 'python'
74# first or (2) explicitly invoking an alternative interpreter on the
75# scons script, e.g., "/usr/local/bin/python2.4 `which scons` [args]".
76EnsurePythonVersion(2,4)
77
78# Ironically, SCons 0.96 dies if you give EnsureSconsVersion a
79# 3-element version number.
80min_scons_version = (0,96,91)
81try:
82    EnsureSConsVersion(*min_scons_version)
83except:
84    print "Error checking current SCons version."
85    print "SCons", ".".join(map(str,min_scons_version)), "or greater required."
86    Exit(2)
87    
88
89# The absolute path to the current directory (where this file lives).
90ROOT = Dir('.').abspath
91
92# Paths to the M5 and external source trees.
93SRCDIR = os.path.join(ROOT, 'src')
94
95# tell python where to find m5 python code
96sys.path.append(os.path.join(ROOT, 'src/python'))
97
98###################################################
99#
100# Figure out which configurations to set up based on the path(s) of
101# the target(s).
102#
103###################################################
104
105# Find default configuration & binary.
106Default(os.environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
107
108# Ask SCons which directory it was invoked from.
109launch_dir = GetLaunchDir()
110
111# Make targets relative to invocation directory
112abs_targets = map(lambda x: os.path.normpath(os.path.join(launch_dir, str(x))),
113                  BUILD_TARGETS)
114
115# helper function: find last occurrence of element in list
116def rfind(l, elt, offs = -1):
117    for i in range(len(l)+offs, 0, -1):
118        if l[i] == elt:
119            return i
120    raise ValueError, "element not found"
121
122# helper function: compare dotted version numbers.
123# E.g., compare_version('1.3.25', '1.4.1')
124# returns -1, 0, 1 if v1 is <, ==, > v2
125def compare_versions(v1, v2):
126    # Convert dotted strings to lists
127    v1 = map(int, v1.split('.'))
128    v2 = map(int, v2.split('.'))
129    # Compare corresponding elements of lists
130    for n1,n2 in zip(v1, v2):
131        if n1 < n2: return -1
132        if n1 > n2: return  1
133    # all corresponding values are equal... see if one has extra values
134    if len(v1) < len(v2): return -1
135    if len(v1) > len(v2): return  1
136    return 0
137
138# Each target must have 'build' in the interior of the path; the
139# directory below this will determine the build parameters.  For
140# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
141# recognize that ALPHA_SE specifies the configuration because it
142# follow 'build' in the bulid path.
143
144# Generate a list of the unique build roots and configs that the
145# collected targets reference.
146build_paths = []
147build_root = None
148for t in abs_targets:
149    path_dirs = t.split('/')
150    try:
151        build_top = rfind(path_dirs, 'build', -2)
152    except:
153        print "Error: no non-leaf 'build' dir found on target path", t
154        Exit(1)
155    this_build_root = os.path.join('/',*path_dirs[:build_top+1])
156    if not build_root:
157        build_root = this_build_root
158    else:
159        if this_build_root != build_root:
160            print "Error: build targets not under same build root\n"\
161                  "  %s\n  %s" % (build_root, this_build_root)
162            Exit(1)
163    build_path = os.path.join('/',*path_dirs[:build_top+2])
164    if build_path not in build_paths:
165        build_paths.append(build_path)
166
167###################################################
168#
169# Set up the default build environment.  This environment is copied
170# and modified according to each selected configuration.
171#
172###################################################
173
174env = Environment(ENV = os.environ,  # inherit user's environment vars
175                  ROOT = ROOT,
176                  SRCDIR = SRCDIR)
177
178env.SConsignFile(os.path.join(build_root,"sconsign"))
179
180# Default duplicate option is to use hard links, but this messes up
181# when you use emacs to edit a file in the target dir, as emacs moves
182# file to file~ then copies to file, breaking the link.  Symbolic
183# (soft) links work better.
184env.SetOption('duplicate', 'soft-copy')
185
186# I waffle on this setting... it does avoid a few painful but
187# unnecessary builds, but it also seems to make trivial builds take
188# noticeably longer.
189if False:
190    env.TargetSignatures('content')
191
192# M5_PLY is used by isa_parser.py to find the PLY package.
193env.Append(ENV = { 'M5_PLY' : Dir('ext/ply') })
194
195# Set up default C++ compiler flags
196env.Append(CCFLAGS='-pipe')
197env.Append(CCFLAGS='-fno-strict-aliasing')
198env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
199if sys.platform == 'cygwin':
200    # cygwin has some header file issues...
201    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
202env.Append(CPPPATH=[Dir('ext/dnet')])
203
204# Find Python include and library directories for embedding the
205# interpreter.  For consistency, we will use the same Python
206# installation used to run scons (and thus this script).  If you want
207# to link in an alternate version, see above for instructions on how
208# to invoke scons with a different copy of the Python interpreter.
209
210# Get brief Python version name (e.g., "python2.4") for locating
211# include & library files
212py_version_name = 'python' + sys.version[:3]
213
214# include path, e.g. /usr/local/include/python2.4
215env.Append(CPPPATH = os.path.join(sys.exec_prefix, 'include', py_version_name))
216env.Append(LIBS = py_version_name)
217# add library path too if it's not in the default place
218if sys.exec_prefix != '/usr':
219    env.Append(LIBPATH = os.path.join(sys.exec_prefix, 'lib'))
220
221# Check for SWIG
222if not env.has_key('SWIG'):
223    print 'Error: SWIG utility not found.'
224    print '       Please install (see http://www.swig.org) and retry.'
225    Exit(1)
226
227# Check for appropriate SWIG version
228swig_version = os.popen('swig -version').read().split()
229# First 3 words should be "SWIG Version x.y.z"
230if swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
231    print 'Error determining SWIG version.'
232    Exit(1)
233
234min_swig_version = '1.3.28'
235if compare_versions(swig_version[2], min_swig_version) < 0:
236    print 'Error: SWIG version', min_swig_version, 'or newer required.'
237    print '       Installed version:', swig_version[2]
238    Exit(1)
239
240# Set up SWIG flags & scanner
241env.Append(SWIGFLAGS=Split('-c++ -python -modern $_CPPINCFLAGS'))
242
243import SCons.Scanner
244
245swig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
246
247swig_scanner = SCons.Scanner.ClassicCPP("SwigScan", ".i", "CPPPATH",
248                                        swig_inc_re)
249
250env.Append(SCANNERS = swig_scanner)
251
252# Platform-specific configuration.  Note again that we assume that all
253# builds under a given build root run on the same host platform.
254conf = Configure(env,
255                 conf_dir = os.path.join(build_root, '.scons_config'),
256                 log_file = os.path.join(build_root, 'scons_config.log'))
257
258# Check for zlib.  If the check passes, libz will be automatically
259# added to the LIBS environment variable.
260if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++'):
261    print 'Error: did not find needed zlib compression library '\
262          'and/or zlib.h header file.'
263    print '       Please install zlib and try again.'
264    Exit(1)
265
266# Check for <fenv.h> (C99 FP environment control)
267have_fenv = conf.CheckHeader('fenv.h', '<>')
268if not have_fenv:
269    print "Warning: Header file <fenv.h> not found."
270    print "         This host has no IEEE FP rounding mode control."
271
272# Check for mysql.
273mysql_config = WhereIs('mysql_config')
274have_mysql = mysql_config != None
275
276# Check MySQL version.
277if have_mysql:
278    mysql_version = os.popen(mysql_config + ' --version').read()
279    min_mysql_version = '4.1'
280    if compare_versions(mysql_version, min_mysql_version) < 0:
281        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
282        print '         Version', mysql_version, 'detected.'
283        have_mysql = False
284
285# Set up mysql_config commands.
286if have_mysql:
287    mysql_config_include = mysql_config + ' --include'
288    if os.system(mysql_config_include + ' > /dev/null') != 0:
289        # older mysql_config versions don't support --include, use
290        # --cflags instead
291        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
292    # This seems to work in all versions
293    mysql_config_libs = mysql_config + ' --libs'
294
295env = conf.Finish()
296
297# Define the universe of supported ISAs
298env['ALL_ISA_LIST'] = ['alpha', 'sparc', 'mips']
299
300# Define the universe of supported CPU models
301env['ALL_CPU_LIST'] = ['AtomicSimpleCPU', 'TimingSimpleCPU',
302                       'FullCPU', 'O3CPU',
303                       'OzoneCPU']
304
305# Sticky options get saved in the options file so they persist from
306# one invocation to the next (unless overridden, in which case the new
307# value becomes sticky).
308sticky_opts = Options(args=ARGUMENTS)
309sticky_opts.AddOptions(
310    EnumOption('TARGET_ISA', 'Target ISA', 'alpha', env['ALL_ISA_LIST']),
311    BoolOption('FULL_SYSTEM', 'Full-system support', False),
312    # There's a bug in scons 0.96.1 that causes ListOptions with list
313    # values (more than one value) not to be able to be restored from
314    # a saved option file.  If this causes trouble then upgrade to
315    # scons 0.96.90 or later.
316    ListOption('CPU_MODELS', 'CPU models', 'AtomicSimpleCPU,TimingSimpleCPU',
317               env['ALL_CPU_LIST']),
318    BoolOption('ALPHA_TLASER',
319               'Model Alpha TurboLaser platform (vs. Tsunami)', False),
320    BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
321    BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
322               False),
323    BoolOption('SS_COMPATIBLE_FP',
324               'Make floating-point results compatible with SimpleScalar',
325               False),
326    BoolOption('USE_SSE2',
327               'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
328               False),
329    BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
330    BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
331    BoolOption('USE_CHECKER', 'Use checker for detailed CPU models', False),
332    ('CC', 'C compiler', os.environ.get('CC', env['CC'])),
333    ('CXX', 'C++ compiler', os.environ.get('CXX', env['CXX'])),
334    BoolOption('BATCH', 'Use batch pool for build and tests', False),
335    ('BATCH_CMD', 'Batch pool submission command name', 'qdo')
336    )
337
338# Non-sticky options only apply to the current build.
339nonsticky_opts = Options(args=ARGUMENTS)
340nonsticky_opts.AddOptions(
341    BoolOption('update_ref', 'Update test reference outputs', False)
342    )
343
344# These options get exported to #defines in config/*.hh (see src/SConscript).
345env.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
346                     'USE_MYSQL', 'NO_FAST_ALLOC', 'SS_COMPATIBLE_FP', \
347                     'USE_CHECKER']
348
349# Define a handy 'no-op' action
350def no_action(target, source, env):
351    return 0
352
353env.NoAction = Action(no_action, None)
354
355###################################################
356#
357# Define a SCons builder for configuration flag headers.
358#
359###################################################
360
361# This function generates a config header file that #defines the
362# option symbol to the current option setting (0 or 1).  The source
363# operands are the name of the option and a Value node containing the
364# value of the option.
365def build_config_file(target, source, env):
366    (option, value) = [s.get_contents() for s in source]
367    f = file(str(target[0]), 'w')
368    print >> f, '#define', option, value
369    f.close()
370    return None
371
372# Generate the message to be printed when building the config file.
373def build_config_file_string(target, source, env):
374    (option, value) = [s.get_contents() for s in source]
375    return "Defining %s as %s in %s." % (option, value, target[0])
376
377# Combine the two functions into a scons Action object.
378config_action = Action(build_config_file, build_config_file_string)
379
380# The emitter munges the source & target node lists to reflect what
381# we're really doing.
382def config_emitter(target, source, env):
383    # extract option name from Builder arg
384    option = str(target[0])
385    # True target is config header file
386    target = os.path.join('config', option.lower() + '.hh')
387    # Force value to 0/1 even if it's a Python bool
388    val = int(eval(str(env[option])))
389    # Sources are option name & value (packaged in SCons Value nodes)
390    return ([target], [Value(option), Value(val)])
391
392config_builder = Builder(emitter = config_emitter, action = config_action)
393
394env.Append(BUILDERS = { 'ConfigFile' : config_builder })
395
396###################################################
397#
398# Define a SCons builder for copying files.  This is used by the
399# Python zipfile code in src/python/SConscript, but is placed up here
400# since it's potentially more generally applicable.
401#
402###################################################
403
404copy_builder = Builder(action = Copy("$TARGET", "$SOURCE"))
405
406env.Append(BUILDERS = { 'CopyFile' : copy_builder })
407
408###################################################
409#
410# Define a simple SCons builder to concatenate files.
411#
412# Used to append the Python zip archive to the executable.
413#
414###################################################
415
416concat_builder = Builder(action = Action(['cat $SOURCES > $TARGET',
417                                          'chmod +x $TARGET']))
418
419env.Append(BUILDERS = { 'Concat' : concat_builder })
420
421
422# base help text
423help_text = '''
424Usage: scons [scons options] [build options] [target(s)]
425
426'''
427
428# libelf build is shared across all configs in the build root.
429env.SConscript('ext/libelf/SConscript',
430               build_dir = os.path.join(build_root, 'libelf'),
431               exports = 'env')
432
433###################################################
434#
435# Define build environments for selected configurations.
436#
437###################################################
438
439# rename base env
440base_env = env
441
442for build_path in build_paths:
443    print "Building in", build_path
444    # build_dir is the tail component of build path, and is used to
445    # determine the build parameters (e.g., 'ALPHA_SE')
446    (build_root, build_dir) = os.path.split(build_path)
447    # Make a copy of the build-root environment to use for this config.
448    env = base_env.Copy()
449
450    # Set env options according to the build directory config.
451    sticky_opts.files = []
452    # Options for $BUILD_ROOT/$BUILD_DIR are stored in
453    # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
454    # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
455    current_opts_file = os.path.join(build_root, 'options', build_dir)
456    if os.path.isfile(current_opts_file):
457        sticky_opts.files.append(current_opts_file)
458        print "Using saved options file %s" % current_opts_file
459    else:
460        # Build dir-specific options file doesn't exist.
461
462        # Make sure the directory is there so we can create it later
463        opt_dir = os.path.dirname(current_opts_file)
464        if not os.path.isdir(opt_dir):
465            os.mkdir(opt_dir)
466
467        # Get default build options from source tree.  Options are
468        # normally determined by name of $BUILD_DIR, but can be
469        # overriden by 'default=' arg on command line.
470        default_opts_file = os.path.join('build_opts',
471                                         ARGUMENTS.get('default', build_dir))
472        if os.path.isfile(default_opts_file):
473            sticky_opts.files.append(default_opts_file)
474            print "Options file %s not found,\n  using defaults in %s" \
475                  % (current_opts_file, default_opts_file)
476        else:
477            print "Error: cannot find options file %s or %s" \
478                  % (current_opts_file, default_opts_file)
479            Exit(1)
480
481    # Apply current option settings to env
482    sticky_opts.Update(env)
483    nonsticky_opts.Update(env)
484
485    help_text += "Sticky options for %s:\n" % build_dir \
486                 + sticky_opts.GenerateHelpText(env) \
487                 + "\nNon-sticky options for %s:\n" % build_dir \
488                 + nonsticky_opts.GenerateHelpText(env)
489
490    # Process option settings.
491
492    if not have_fenv and env['USE_FENV']:
493        print "Warning: <fenv.h> not available; " \
494              "forcing USE_FENV to False in", build_dir + "."
495        env['USE_FENV'] = False
496
497    if not env['USE_FENV']:
498        print "Warning: No IEEE FP rounding mode control in", build_dir + "."
499        print "         FP results may deviate slightly from other platforms."
500
501    if env['EFENCE']:
502        env.Append(LIBS=['efence'])
503
504    if env['USE_MYSQL']:
505        if not have_mysql:
506            print "Warning: MySQL not available; " \
507                  "forcing USE_MYSQL to False in", build_dir + "."
508            env['USE_MYSQL'] = False
509        else:
510            print "Compiling in", build_dir, "with MySQL support."
511            env.ParseConfig(mysql_config_libs)
512            env.ParseConfig(mysql_config_include)
513
514    # Save sticky option settings back to current options file
515    sticky_opts.Save(current_opts_file, env)
516
517    # Do this after we save setting back, or else we'll tack on an
518    # extra 'qdo' every time we run scons.
519    if env['BATCH']:
520        env['CC']  = env['BATCH_CMD'] + ' ' + env['CC']
521        env['CXX'] = env['BATCH_CMD'] + ' ' + env['CXX']
522
523    if env['USE_SSE2']:
524        env.Append(CCFLAGS='-msse2')
525
526    # The src/SConscript file sets up the build rules in 'env' according
527    # to the configured options.  It returns a list of environments,
528    # one for each variant build (debug, opt, etc.)
529    envList = SConscript('src/SConscript', build_dir = build_path,
530                         exports = 'env')
531
532    # Set up the regression tests for each build.
533    for e in envList:
534        SConscript('tests/SConscript',
535                   build_dir = os.path.join(build_path, 'tests', e.Label),
536                   exports = { 'env' : e }, duplicate = False)
537
538Help(help_text)
539
540###################################################
541#
542# Let SCons do its thing.  At this point SCons will use the defined
543# build environments to build the requested targets.
544#
545###################################################
546
547