SConstruct revision 5871
12391SN/A# -*- mode:python -*-
22391SN/A
32391SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
42391SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
52391SN/A# All rights reserved.
62391SN/A#
72391SN/A# Redistribution and use in source and binary forms, with or without
82391SN/A# modification, are permitted provided that the following conditions are
92391SN/A# met: redistributions of source code must retain the above copyright
102391SN/A# notice, this list of conditions and the following disclaimer;
112391SN/A# redistributions in binary form must reproduce the above copyright
122391SN/A# notice, this list of conditions and the following disclaimer in the
132391SN/A# documentation and/or other materials provided with the distribution;
142391SN/A# neither the name of the copyright holders nor the names of its
152391SN/A# contributors may be used to endorse or promote products derived from
162391SN/A# this software without specific prior written permission.
172391SN/A#
182391SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
192391SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
202391SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
212391SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
222391SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
232391SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
242391SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
252391SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
262391SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
272391SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
282391SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
292391SN/A#
302391SN/A# Authors: Steve Reinhardt
312391SN/A#          Nathan Binkert
322391SN/A
332391SN/A###################################################
342391SN/A#
352391SN/A# SCons top-level build description (SConstruct) file.
362391SN/A#
372391SN/A# While in this directory ('m5'), just type 'scons' to build the default
382391SN/A# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
392391SN/A# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
402391SN/A# the optimized full-system version).
412391SN/A#
422592SN/A# You can build M5 in a different directory as long as there is a
432394SN/A# 'build/<CONFIG>' somewhere along the target path.  The build system
442391SN/A# expects that all configs under the same build directory are being
452391SN/A# built for the same host system.
462415SN/A#
472423SN/A# Examples:
482391SN/A#
492394SN/A#   The following two commands are equivalent.  The '-u' option tells
502391SN/A#   scons to search up the directory tree for this SConstruct file.
512423SN/A#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
522391SN/A#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
532630SN/A#
542415SN/A#   The following two commands are equivalent and demonstrate building
552415SN/A#   in a directory outside of the source tree.  The '-C' option tells
562415SN/A#   scons to chdir to the specified directory to find this SConstruct
572415SN/A#   file.
582415SN/A#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
592415SN/A#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
602415SN/A#
612415SN/A# You can use 'scons -H' to print scons options.  If you're in this
622415SN/A# 'm5' directory (or use -u or -C to tell scons where to find this
632415SN/A# file), you can use 'scons -h' to print all the M5-specific build
642415SN/A# options as well.
652415SN/A#
662415SN/A###################################################
672415SN/A
682415SN/A# Check for recent-enough Python and SCons versions.
692415SN/Atry:
702415SN/A    # Really old versions of scons only take two options for the
712415SN/A    # function, so check once without the revision and once with the
722565SN/A    # revision, the first instance will fail for stuff other than
732565SN/A    # 0.98, and the second will fail for 0.98.0
742391SN/A    EnsureSConsVersion(0, 98)
752391SN/A    EnsureSConsVersion(0, 98, 1)
762391SN/Aexcept SystemExit, e:
772391SN/A    print """
782391SN/AFor more details, see:
792391SN/A    http://m5sim.org/wiki/index.php/Compiling_M5
802391SN/A"""
812391SN/A    raise
822391SN/A
832391SN/A# We ensure the python version early because we have stuff that
842391SN/A# requires python 2.4
852391SN/Atry:
862391SN/A    EnsurePythonVersion(2, 4)
872391SN/Aexcept SystemExit, e:
882391SN/A    print """
892391SN/AYou can use a non-default installation of the Python interpreter by
902391SN/Aeither (1) rearranging your PATH so that scons finds the non-default
912391SN/A'python' first or (2) explicitly invoking an alternative interpreter
922391SN/Aon the scons script.
932541SN/A
942541SN/AFor more details, see:
952541SN/A    http://m5sim.org/wiki/index.php/Using_a_non-default_Python_installation
962541SN/A"""
972541SN/A    raise
982541SN/A
992541SN/Aimport os
1002541SN/Aimport re
1012391SN/Aimport subprocess
1022391SN/Aimport sys
1032391SN/A
1042391SN/Afrom os import mkdir, environ
1052416SN/Afrom os.path import abspath, basename, dirname, expanduser, normpath
1062391SN/Afrom os.path import exists,  isdir, isfile
1072391SN/Afrom os.path import join as joinpath, split as splitpath
1082391SN/A
1092391SN/Aimport SCons
1102391SN/Aimport SCons.Node
1112391SN/A
1122391SN/Adef read_command(cmd, **kwargs):
1132391SN/A    """run the command cmd, read the results and return them
1142391SN/A    this is sorta like `cmd` in shell"""
1152391SN/A    from subprocess import Popen, PIPE, STDOUT
1162391SN/A
1172391SN/A    no_exception = 'exception' in kwargs
1182408SN/A    exception = kwargs.pop('exception', None)
1192408SN/A    
1202408SN/A    kwargs.setdefault('shell', False)
1212409SN/A    kwargs.setdefault('stdout', PIPE)
1222409SN/A    kwargs.setdefault('stderr', STDOUT)
1232408SN/A    kwargs.setdefault('close_fds', True)
1242408SN/A    try:
1252413SN/A        subp = Popen(cmd, **kwargs)
1262630SN/A    except Exception, e:
1272413SN/A        if no_exception:
1282413SN/A            return exception
1292415SN/A        raise
1302639Sstever@eecs.umich.edu
1312630SN/A    return subp.communicate()[0]
1322416SN/A
1332415SN/A# helper function: compare arrays or strings of version numbers.
1342415SN/A# E.g., compare_version((1,3,25), (1,4,1)')
1352413SN/A# returns -1, 0, 1 if v1 is <, ==, > v2
1362413SN/Adef compare_versions(v1, v2):
1372413SN/A    def make_version_list(v):
1382413SN/A        if isinstance(v, (list,tuple)):
1392630SN/A            return v
1402413SN/A        elif isinstance(v, str):
1412413SN/A            return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
1422630SN/A        else:
1432413SN/A            raise TypeError
1442413SN/A
1452413SN/A    v1 = make_version_list(v1)
1462413SN/A    v2 = make_version_list(v2)
1472630SN/A    # Compare corresponding elements of lists
1482413SN/A    for n1,n2 in zip(v1, v2):
1492630SN/A        if n1 < n2: return -1
1502414SN/A        if n1 > n2: return  1
1512630SN/A    # all corresponding values are equal... see if one has extra values
1522413SN/A    if len(v1) < len(v2): return -1
1532630SN/A    if len(v1) > len(v2): return  1
1542630SN/A    return 0
1552418SN/A
1562413SN/A########################################################################
1572630SN/A#
1582630SN/A# Set up the base build environment.
1592631SN/A#
1602631SN/A########################################################################
1612631SN/Ause_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'PATH', 'RANLIB' ])
1622631SN/A
1632631SN/Ause_env = {}
1642418SN/Afor key,val in os.environ.iteritems():
1652413SN/A    if key in use_vars or key.startswith("M5"):
1662413SN/A        use_env[key] = val
1672413SN/A
1682420SN/Aenv = Environment(ENV=use_env)
1692630SN/Aenv.root = Dir(".")          # The current directory (where this file lives).
1702413SN/Aenv.srcdir = Dir("src")      # The source directory
1712413SN/A
1722413SN/A########################################################################
1732499SN/A#
1742413SN/A# Mercurial Stuff.
1752499SN/A#
1762499SN/A# If the M5 directory is a mercurial repository, we should do some
1772499SN/A# extra things.
1782640Sstever@eecs.umich.edu#
1792499SN/A########################################################################
1802519SN/A
1812519SN/Ahgdir = env.root.Dir(".hg")
1822640Sstever@eecs.umich.edu
1832462SN/Amercurial_style_message = """
1842462SN/AYou're missing the M5 style hook.
1852462SN/APlease install the hook so we can ensure that all code fits a common style.
1862413SN/A
1872413SN/AAll you'd need to do is add the following lines to your repository .hg/hgrc
1882413SN/Aor your personal .hgrc
1892413SN/A----------------
1902413SN/A
1912413SN/A[extensions]
1922413SN/Astyle = %s/util/style.py
1932640Sstever@eecs.umich.edu
1942640Sstever@eecs.umich.edu[hooks]
1952640Sstever@eecs.umich.edupretxncommit.style = python:style.check_whitespace
1962413SN/A""" % (env.root)
1972413SN/A
1982413SN/Amercurial_bin_not_found = """
1992413SN/AMercurial binary cannot be found, unfortunately this means that we
2002413SN/Acannot easily determine the version of M5 that you are running and
2012413SN/Athis makes error messages more difficult to collect.  Please consider
2022413SN/Ainstalling mercurial if you choose to post an error message
2032413SN/A"""
2042413SN/A
2052522SN/Amercurial_lib_not_found = """
2062522SN/AMercurial libraries cannot be found, ignoring style hook
2072413SN/AIf you are actually a M5 developer, please fix this and
2082522SN/Arun the style hook. It is important.
2092497SN/A"""
2102497SN/A
2112497SN/Aif hgdir.exists():
2122522SN/A    # 1) Grab repository revision if we know it.
2132497SN/A    cmd = "hg id -n -i -t -b"
2142522SN/A    try:
2152522SN/A        hg_info = read_command(cmd, cwd=env.root.abspath).strip()
2162522SN/A    except OSError:
2172413SN/A        hg_info = "Unknown"
2182413SN/A        print mercurial_bin_not_found
2192415SN/A
2202415SN/A    env['HG_INFO'] = hg_info
2212415SN/A
2222415SN/A    # 2) Ensure that the style hook is in place.
2232415SN/A    try:
2242413SN/A        ui = None
2252413SN/A        if ARGUMENTS.get('IGNORE_STYLE') != 'True':
2262630SN/A            from mercurial import ui
2272413SN/A            ui = ui.ui()
2282416SN/A    except ImportError:
2292413SN/A        print mercurial_lib_not_found
2302413SN/A
2312413SN/A    if ui is not None:
2322630SN/A        ui.readconfig(hgdir.File('hgrc').abspath)
2332413SN/A        style_hook = ui.config('hooks', 'pretxncommit.style', None)
2342413SN/A
2352413SN/A        if not style_hook:
2362413SN/A            print mercurial_style_message
2372413SN/A            sys.exit(1)
2382630SN/Aelse:
2392413SN/A    print ".hg directory not found"
2402413SN/A
2412413SN/A###################################################
2422413SN/A#
2432413SN/A# Figure out which configurations to set up based on the path(s) of
2442413SN/A# the target(s).
2452391SN/A#
2462391SN/A###################################################
2472391SN/A
2482391SN/A# Find default configuration & binary.
2492391SN/ADefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
2502391SN/A
2512391SN/A# helper function: find last occurrence of element in list
2522391SN/Adef rfind(l, elt, offs = -1):
2532391SN/A    for i in range(len(l)+offs, 0, -1):
2542391SN/A        if l[i] == elt:
2552391SN/A            return i
2562391SN/A    raise ValueError, "element not found"
2572391SN/A
2582391SN/A# Each target must have 'build' in the interior of the path; the
2592391SN/A# directory below this will determine the build parameters.  For
2602391SN/A# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2612391SN/A# recognize that ALPHA_SE specifies the configuration because it
2622391SN/A# follow 'build' in the bulid path.
2632391SN/A
2642391SN/A# Generate absolute paths to targets so we can see where the build dir is
2652391SN/Aif COMMAND_LINE_TARGETS:
2662391SN/A    # Ask SCons which directory it was invoked from
2672391SN/A    launch_dir = GetLaunchDir()
2682391SN/A    # Make targets relative to invocation directory
2692391SN/A    abs_targets = [ normpath(joinpath(launch_dir, str(x))) for x in \
2702391SN/A                    COMMAND_LINE_TARGETS]
2712391SN/Aelse:
2722391SN/A    # Default targets are relative to root of tree
2732391SN/A    abs_targets = [ normpath(joinpath(ROOT, str(x))) for x in \
2742391SN/A                    DEFAULT_TARGETS]
2752391SN/A
2762391SN/A
2772391SN/A# Generate a list of the unique build roots and configs that the
2782391SN/A# collected targets reference.
2792391SN/Avariant_paths = []
2802391SN/Abuild_root = None
2812391SN/Afor t in abs_targets:
2822391SN/A    path_dirs = t.split('/')
2832391SN/A    try:
2842391SN/A        build_top = rfind(path_dirs, 'build', -2)
2852391SN/A    except:
2862391SN/A        print "Error: no non-leaf 'build' dir found on target path", t
2872391SN/A        Exit(1)
2882391SN/A    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2892391SN/A    if not build_root:
2902391SN/A        build_root = this_build_root
2912391SN/A    else:
2922391SN/A        if this_build_root != build_root:
2932391SN/A            print "Error: build targets not under same build root\n"\
2942391SN/A                  "  %s\n  %s" % (build_root, this_build_root)
2952391SN/A            Exit(1)
2962391SN/A    variant_path = joinpath('/',*path_dirs[:build_top+2])
2972391SN/A    if variant_path not in variant_paths:
2982391SN/A        variant_paths.append(variant_path)
2992391SN/A
3002391SN/A# Make sure build_root exists (might not if this is the first build there)
3012391SN/Aif not isdir(build_root):
3022391SN/A    mkdir(build_root)
3032391SN/A
3042391SN/AExport('env')
3052391SN/A
3062391SN/Aenv.SConsignFile(joinpath(build_root, "sconsign"))
3072391SN/A
3082391SN/A# Default duplicate option is to use hard links, but this messes up
3092391SN/A# when you use emacs to edit a file in the target dir, as emacs moves
3102391SN/A# file to file~ then copies to file, breaking the link.  Symbolic
3112391SN/A# (soft) links work better.
3122391SN/Aenv.SetOption('duplicate', 'soft-copy')
3132391SN/A
3142391SN/A#
3152391SN/A# Set up global sticky variables... these are common to an entire build
3162391SN/A# tree (not specific to a particular build like ALPHA_SE)
3172391SN/A#
3182391SN/A
3192391SN/A# Variable validators & converters for global sticky variables
3202391SN/Adef PathListMakeAbsolute(val):
3212391SN/A    if not val:
3222391SN/A        return val
3232391SN/A    f = lambda p: abspath(expanduser(p))
3242391SN/A    return ':'.join(map(f, val.split(':')))
3252391SN/A
3262391SN/Adef PathListAllExist(key, val, env):
3272391SN/A    if not val:
3282391SN/A        return
3292391SN/A    paths = val.split(':')
3302391SN/A    for path in paths:
3312391SN/A        if not isdir(path):
3322391SN/A            raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
3332391SN/A
3342391SN/Aglobal_sticky_vars_file = joinpath(build_root, 'variables.global')
3352391SN/A
3362391SN/Aglobal_sticky_vars = Variables(global_sticky_vars_file, args=ARGUMENTS)
3372391SN/A
3382391SN/Aglobal_sticky_vars.AddVariables(
3392391SN/A    ('CC', 'C compiler', environ.get('CC', env['CC'])),
3402391SN/A    ('CXX', 'C++ compiler', environ.get('CXX', env['CXX'])),
3412391SN/A    ('BATCH', 'Use batch pool for build and tests', False),
3422391SN/A    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3432391SN/A    ('EXTRAS', 'Add Extra directories to the compilation', '',
3442391SN/A     PathListAllExist, PathListMakeAbsolute)
3452391SN/A    )    
3462391SN/A
3472391SN/A# base help text
3482391SN/Ahelp_text = '''
3492391SN/AUsage: scons [scons options] [build options] [target(s)]
3502391SN/A
3512391SN/AGlobal sticky options:
3522413SN/A'''
3532391SN/A
3542391SN/Ahelp_text += global_sticky_vars.GenerateHelpText(env)
3552391SN/A
3562391SN/A# Update env with values from ARGUMENTS & file global_sticky_vars_file
3572565SN/Aglobal_sticky_vars.Update(env)
3582391SN/A
3592391SN/A# Save sticky variable settings back to current variables file
3602391SN/Aglobal_sticky_vars.Save(global_sticky_vars_file, env)
3612391SN/A
3622391SN/A# Parse EXTRAS variable to build list of all directories where we're
3632391SN/A# look for sources etc.  This list is exported as base_dir_list.
3642565SN/Abase_dir = env.srcdir.abspath
3652565SN/Aif env['EXTRAS']:
3662391SN/A    extras_dir_list = env['EXTRAS'].split(':')
3672391SN/Aelse:
3682391SN/A    extras_dir_list = []
3692391SN/A
3702391SN/AExport('base_dir')
3712391SN/AExport('extras_dir_list')
3722565SN/A
3732391SN/A# M5_PLY is used by isa_parser.py to find the PLY package.
3742391SN/Aenv.Append(ENV = { 'M5_PLY' : str(Dir('ext/ply')) })
3752391SN/A
376CXX_version = read_command([env['CXX'],'--version'], exception=False)
377CXX_V = read_command([env['CXX'],'-V'], exception=False)
378
379env['GCC'] = CXX_version and CXX_version.find('g++') >= 0
380env['SUNCC'] = CXX_V and CXX_V.find('Sun C++') >= 0
381env['ICC'] = CXX_V and CXX_V.find('Intel') >= 0
382if env['GCC'] + env['SUNCC'] + env['ICC'] > 1:
383    print 'Error: How can we have two at the same time?'
384    Exit(1)
385
386# Set up default C++ compiler flags
387if env['GCC']:
388    env.Append(CCFLAGS='-pipe')
389    env.Append(CCFLAGS='-fno-strict-aliasing')
390    env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
391    env.Append(CXXFLAGS='-Wno-deprecated')
392elif env['ICC']:
393    pass #Fix me... add warning flags once we clean up icc warnings
394elif env['SUNCC']:
395    env.Append(CCFLAGS='-Qoption ccfe')
396    env.Append(CCFLAGS='-features=gcc')
397    env.Append(CCFLAGS='-features=extensions')
398    env.Append(CCFLAGS='-library=stlport4')
399    env.Append(CCFLAGS='-xar')
400    #env.Append(CCFLAGS='-instances=semiexplicit')
401else:
402    print 'Error: Don\'t know what compiler options to use for your compiler.'
403    print '       Please fix SConstruct and src/SConscript and try again.'
404    Exit(1)
405
406# Do this after we save setting back, or else we'll tack on an
407# extra 'qdo' every time we run scons.
408if env['BATCH']:
409    env['CC']     = env['BATCH_CMD'] + ' ' + env['CC']
410    env['CXX']    = env['BATCH_CMD'] + ' ' + env['CXX']
411    env['AS']     = env['BATCH_CMD'] + ' ' + env['AS']
412    env['AR']     = env['BATCH_CMD'] + ' ' + env['AR']
413    env['RANLIB'] = env['BATCH_CMD'] + ' ' + env['RANLIB']
414
415if sys.platform == 'cygwin':
416    # cygwin has some header file issues...
417    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
418env.Append(CPPPATH=[Dir('ext/dnet')])
419
420# Check for SWIG
421if not env.has_key('SWIG'):
422    print 'Error: SWIG utility not found.'
423    print '       Please install (see http://www.swig.org) and retry.'
424    Exit(1)
425
426# Check for appropriate SWIG version
427swig_version = read_command(('swig', '-version'), exception='').split()
428# First 3 words should be "SWIG Version x.y.z"
429if len(swig_version) < 3 or \
430        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
431    print 'Error determining SWIG version.'
432    Exit(1)
433
434min_swig_version = '1.3.28'
435if compare_versions(swig_version[2], min_swig_version) < 0:
436    print 'Error: SWIG version', min_swig_version, 'or newer required.'
437    print '       Installed version:', swig_version[2]
438    Exit(1)
439
440# Set up SWIG flags & scanner
441swig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
442env.Append(SWIGFLAGS=swig_flags)
443
444# filter out all existing swig scanners, they mess up the dependency
445# stuff for some reason
446scanners = []
447for scanner in env['SCANNERS']:
448    skeys = scanner.skeys
449    if skeys == '.i':
450        continue
451
452    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
453        continue
454
455    scanners.append(scanner)
456
457# add the new swig scanner that we like better
458from SCons.Scanner import ClassicCPP as CPPScanner
459swig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
460scanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
461
462# replace the scanners list that has what we want
463env['SCANNERS'] = scanners
464
465# Add a custom Check function to the Configure context so that we can
466# figure out if the compiler adds leading underscores to global
467# variables.  This is needed for the autogenerated asm files that we
468# use for embedding the python code.
469def CheckLeading(context):
470    context.Message("Checking for leading underscore in global variables...")
471    # 1) Define a global variable called x from asm so the C compiler
472    #    won't change the symbol at all.
473    # 2) Declare that variable.
474    # 3) Use the variable
475    #
476    # If the compiler prepends an underscore, this will successfully
477    # link because the external symbol 'x' will be called '_x' which
478    # was defined by the asm statement.  If the compiler does not
479    # prepend an underscore, this will not successfully link because
480    # '_x' will have been defined by assembly, while the C portion of
481    # the code will be trying to use 'x'
482    ret = context.TryLink('''
483        asm(".globl _x; _x: .byte 0");
484        extern int x;
485        int main() { return x; }
486        ''', extension=".c")
487    context.env.Append(LEADING_UNDERSCORE=ret)
488    context.Result(ret)
489    return ret
490
491# Platform-specific configuration.  Note again that we assume that all
492# builds under a given build root run on the same host platform.
493conf = Configure(env,
494                 conf_dir = joinpath(build_root, '.scons_config'),
495                 log_file = joinpath(build_root, 'scons_config.log'),
496                 custom_tests = { 'CheckLeading' : CheckLeading })
497
498# Check for leading underscores.  Don't really need to worry either
499# way so don't need to check the return code.
500conf.CheckLeading()
501
502# Check if we should compile a 64 bit binary on Mac OS X/Darwin
503try:
504    import platform
505    uname = platform.uname()
506    if uname[0] == 'Darwin' and compare_versions(uname[2], '9.0.0') >= 0:
507        if int(read_command('sysctl -n hw.cpu64bit_capable')[0]):
508            env.Append(CCFLAGS='-arch x86_64')
509            env.Append(CFLAGS='-arch x86_64')
510            env.Append(LINKFLAGS='-arch x86_64')
511            env.Append(ASFLAGS='-arch x86_64')
512except:
513    pass
514
515# Recent versions of scons substitute a "Null" object for Configure()
516# when configuration isn't necessary, e.g., if the "--help" option is
517# present.  Unfortuantely this Null object always returns false,
518# breaking all our configuration checks.  We replace it with our own
519# more optimistic null object that returns True instead.
520if not conf:
521    def NullCheck(*args, **kwargs):
522        return True
523
524    class NullConf:
525        def __init__(self, env):
526            self.env = env
527        def Finish(self):
528            return self.env
529        def __getattr__(self, mname):
530            return NullCheck
531
532    conf = NullConf(env)
533
534# Find Python include and library directories for embedding the
535# interpreter.  For consistency, we will use the same Python
536# installation used to run scons (and thus this script).  If you want
537# to link in an alternate version, see above for instructions on how
538# to invoke scons with a different copy of the Python interpreter.
539from distutils import sysconfig
540
541py_getvar = sysconfig.get_config_var
542
543py_version = 'python' + py_getvar('VERSION')
544
545py_general_include = sysconfig.get_python_inc()
546py_platform_include = sysconfig.get_python_inc(plat_specific=True)
547py_includes = [ py_general_include ]
548if py_platform_include != py_general_include:
549    py_includes.append(py_platform_include)
550
551py_lib_path = []
552# add the prefix/lib/pythonX.Y/config dir, but only if there is no
553# shared library in prefix/lib/.
554if not py_getvar('Py_ENABLE_SHARED'):
555    py_lib_path.append('-L' + py_getvar('LIBPL'))
556
557py_libs = []
558for lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
559    if lib not in py_libs:
560        py_libs.append(lib)
561py_libs.append('-l' + py_version)
562
563env.Append(CPPPATH=py_includes)
564env.Append(LIBPATH=py_lib_path)
565#env.Append(LIBS=py_libs)
566
567# verify that this stuff works
568if not conf.CheckHeader('Python.h', '<>'):
569    print "Error: can't find Python.h header in", py_includes
570    Exit(1)
571
572for lib in py_libs:
573    assert lib.startswith('-l')
574    lib = lib[2:]
575    if not conf.CheckLib(lib):
576        print "Error: can't find library %s required by python" % lib
577        Exit(1)
578
579# On Solaris you need to use libsocket for socket ops
580if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
581   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
582       print "Can't find library with socket calls (e.g. accept())"
583       Exit(1)
584
585# Check for zlib.  If the check passes, libz will be automatically
586# added to the LIBS environment variable.
587if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
588    print 'Error: did not find needed zlib compression library '\
589          'and/or zlib.h header file.'
590    print '       Please install zlib and try again.'
591    Exit(1)
592
593# Check for <fenv.h> (C99 FP environment control)
594have_fenv = conf.CheckHeader('fenv.h', '<>')
595if not have_fenv:
596    print "Warning: Header file <fenv.h> not found."
597    print "         This host has no IEEE FP rounding mode control."
598
599######################################################################
600#
601# Check for mysql.
602#
603mysql_config = WhereIs('mysql_config')
604have_mysql = bool(mysql_config)
605
606# Check MySQL version.
607if have_mysql:
608    mysql_version = read_command(mysql_config + ' --version')
609    min_mysql_version = '4.1'
610    if compare_versions(mysql_version, min_mysql_version) < 0:
611        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
612        print '         Version', mysql_version, 'detected.'
613        have_mysql = False
614
615# Set up mysql_config commands.
616if have_mysql:
617    mysql_config_include = mysql_config + ' --include'
618    if os.system(mysql_config_include + ' > /dev/null') != 0:
619        # older mysql_config versions don't support --include, use
620        # --cflags instead
621        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
622    # This seems to work in all versions
623    mysql_config_libs = mysql_config + ' --libs'
624
625######################################################################
626#
627# Finish the configuration
628#
629env = conf.Finish()
630
631######################################################################
632#
633# Collect all non-global variables
634#
635
636Export('env')
637
638# Define the universe of supported ISAs
639all_isa_list = [ ]
640Export('all_isa_list')
641
642# Define the universe of supported CPU models
643all_cpu_list = [ ]
644default_cpus = [ ]
645Export('all_cpu_list', 'default_cpus')
646
647# Sticky variables get saved in the variables file so they persist from
648# one invocation to the next (unless overridden, in which case the new
649# value becomes sticky).
650sticky_vars = Variables(args=ARGUMENTS)
651Export('sticky_vars')
652
653# Non-sticky variables only apply to the current build.
654nonsticky_vars = Variables(args=ARGUMENTS)
655Export('nonsticky_vars')
656
657# Walk the tree and execute all SConsopts scripts that wil add to the
658# above variables
659for bdir in [ base_dir ] + extras_dir_list:
660    for root, dirs, files in os.walk(bdir):
661        if 'SConsopts' in files:
662            print "Reading", joinpath(root, 'SConsopts')
663            SConscript(joinpath(root, 'SConsopts'))
664
665all_isa_list.sort()
666all_cpu_list.sort()
667default_cpus.sort()
668
669sticky_vars.AddVariables(
670    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
671    BoolVariable('FULL_SYSTEM', 'Full-system support', False),
672    ListVariable('CPU_MODELS', 'CPU models', default_cpus, all_cpu_list),
673    BoolVariable('NO_FAST_ALLOC', 'Disable fast object allocator', False),
674    BoolVariable('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
675                 False),
676    BoolVariable('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
677                 False),
678    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
679                 False),
680    BoolVariable('SS_COMPATIBLE_FP',
681                 'Make floating-point results compatible with SimpleScalar',
682                 False),
683    BoolVariable('USE_SSE2',
684                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
685                 False),
686    BoolVariable('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
687    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
688    BoolVariable('USE_CHECKER', 'Use checker for detailed CPU models', False),
689    )
690
691nonsticky_vars.AddVariables(
692    BoolVariable('update_ref', 'Update test reference outputs', False)
693    )
694
695# These variables get exported to #defines in config/*.hh (see src/SConscript).
696env.ExportVariables = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
697                       'USE_MYSQL', 'NO_FAST_ALLOC', 'FAST_ALLOC_DEBUG', \
698                       'FAST_ALLOC_STATS', 'SS_COMPATIBLE_FP', \
699                       'USE_CHECKER', 'TARGET_ISA']
700
701###################################################
702#
703# Define a SCons builder for configuration flag headers.
704#
705###################################################
706
707# This function generates a config header file that #defines the
708# variable symbol to the current variable setting (0 or 1).  The source
709# operands are the name of the variable and a Value node containing the
710# value of the variable.
711def build_config_file(target, source, env):
712    (variable, value) = [s.get_contents() for s in source]
713    f = file(str(target[0]), 'w')
714    print >> f, '#define', variable, value
715    f.close()
716    return None
717
718# Generate the message to be printed when building the config file.
719def build_config_file_string(target, source, env):
720    (variable, value) = [s.get_contents() for s in source]
721    return "Defining %s as %s in %s." % (variable, value, target[0])
722
723# Combine the two functions into a scons Action object.
724config_action = Action(build_config_file, build_config_file_string)
725
726# The emitter munges the source & target node lists to reflect what
727# we're really doing.
728def config_emitter(target, source, env):
729    # extract variable name from Builder arg
730    variable = str(target[0])
731    # True target is config header file
732    target = joinpath('config', variable.lower() + '.hh')
733    val = env[variable]
734    if isinstance(val, bool):
735        # Force value to 0/1
736        val = int(val)
737    elif isinstance(val, str):
738        val = '"' + val + '"'
739
740    # Sources are variable name & value (packaged in SCons Value nodes)
741    return ([target], [Value(variable), Value(val)])
742
743config_builder = Builder(emitter = config_emitter, action = config_action)
744
745env.Append(BUILDERS = { 'ConfigFile' : config_builder })
746
747# libelf build is shared across all configs in the build root.
748env.SConscript('ext/libelf/SConscript',
749               variant_dir = joinpath(build_root, 'libelf'))
750
751# gzstream build is shared across all configs in the build root.
752env.SConscript('ext/gzstream/SConscript',
753               variant_dir = joinpath(build_root, 'gzstream'))
754
755###################################################
756#
757# This function is used to set up a directory with switching headers
758#
759###################################################
760
761env['ALL_ISA_LIST'] = all_isa_list
762def make_switching_dir(dname, switch_headers, env):
763    # Generate the header.  target[0] is the full path of the output
764    # header to generate.  'source' is a dummy variable, since we get the
765    # list of ISAs from env['ALL_ISA_LIST'].
766    def gen_switch_hdr(target, source, env):
767        fname = str(target[0])
768        bname = basename(fname)
769        f = open(fname, 'w')
770        f.write('#include "arch/isa_specific.hh"\n')
771        cond = '#if'
772        for isa in all_isa_list:
773            f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
774                    % (cond, isa.upper(), dname, isa, bname))
775            cond = '#elif'
776        f.write('#else\n#error "THE_ISA not set"\n#endif\n')
777        f.close()
778        return 0
779
780    # String to print when generating header
781    def gen_switch_hdr_string(target, source, env):
782        return "Generating switch header " + str(target[0])
783
784    # Build SCons Action object. 'varlist' specifies env vars that this
785    # action depends on; when env['ALL_ISA_LIST'] changes these actions
786    # should get re-executed.
787    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
788                               varlist=['ALL_ISA_LIST'])
789
790    # Instantiate actions for each header
791    for hdr in switch_headers:
792        env.Command(hdr, [], switch_hdr_action)
793Export('make_switching_dir')
794
795###################################################
796#
797# Define build environments for selected configurations.
798#
799###################################################
800
801# rename base env
802base_env = env
803
804for variant_path in variant_paths:
805    print "Building in", variant_path
806
807    # Make a copy of the build-root environment to use for this config.
808    env = base_env.Clone()
809    env['BUILDDIR'] = variant_path
810
811    # variant_dir is the tail component of build path, and is used to
812    # determine the build parameters (e.g., 'ALPHA_SE')
813    (build_root, variant_dir) = splitpath(variant_path)
814
815    # Set env variables according to the build directory config.
816    sticky_vars.files = []
817    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
818    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
819    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
820    current_vars_file = joinpath(build_root, 'variables', variant_dir)
821    if isfile(current_vars_file):
822        sticky_vars.files.append(current_vars_file)
823        print "Using saved variables file %s" % current_vars_file
824    else:
825        # Build dir-specific variables file doesn't exist.
826
827        # Make sure the directory is there so we can create it later
828        opt_dir = dirname(current_vars_file)
829        if not isdir(opt_dir):
830            mkdir(opt_dir)
831
832        # Get default build variables from source tree.  Variables are
833        # normally determined by name of $VARIANT_DIR, but can be
834        # overriden by 'default=' arg on command line.
835        default_vars_file = joinpath('build_opts',
836                                     ARGUMENTS.get('default', variant_dir))
837        if isfile(default_vars_file):
838            sticky_vars.files.append(default_vars_file)
839            print "Variables file %s not found,\n  using defaults in %s" \
840                  % (current_vars_file, default_vars_file)
841        else:
842            print "Error: cannot find variables file %s or %s" \
843                  % (current_vars_file, default_vars_file)
844            Exit(1)
845
846    # Apply current variable settings to env
847    sticky_vars.Update(env)
848    nonsticky_vars.Update(env)
849
850    help_text += "\nSticky variables for %s:\n" % variant_dir \
851                 + sticky_vars.GenerateHelpText(env) \
852                 + "\nNon-sticky variables for %s:\n" % variant_dir \
853                 + nonsticky_vars.GenerateHelpText(env)
854
855    # Process variable settings.
856
857    if not have_fenv and env['USE_FENV']:
858        print "Warning: <fenv.h> not available; " \
859              "forcing USE_FENV to False in", variant_dir + "."
860        env['USE_FENV'] = False
861
862    if not env['USE_FENV']:
863        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
864        print "         FP results may deviate slightly from other platforms."
865
866    if env['EFENCE']:
867        env.Append(LIBS=['efence'])
868
869    if env['USE_MYSQL']:
870        if not have_mysql:
871            print "Warning: MySQL not available; " \
872                  "forcing USE_MYSQL to False in", variant_dir + "."
873            env['USE_MYSQL'] = False
874        else:
875            print "Compiling in", variant_dir, "with MySQL support."
876            env.ParseConfig(mysql_config_libs)
877            env.ParseConfig(mysql_config_include)
878
879    # Save sticky variable settings back to current variables file
880    sticky_vars.Save(current_vars_file, env)
881
882    if env['USE_SSE2']:
883        env.Append(CCFLAGS='-msse2')
884
885    # The src/SConscript file sets up the build rules in 'env' according
886    # to the configured variables.  It returns a list of environments,
887    # one for each variant build (debug, opt, etc.)
888    envList = SConscript('src/SConscript', variant_dir = variant_path,
889                         exports = 'env')
890
891    # Set up the regression tests for each build.
892    for e in envList:
893        SConscript('tests/SConscript',
894                   variant_dir = joinpath(variant_path, 'tests', e.Label),
895                   exports = { 'env' : e }, duplicate = False)
896
897Help(help_text)
898