SConstruct revision 5522
16019Shines@cs.fsu.edu# -*- mode:python -*-
27399SAli.Saidi@ARM.com
37399SAli.Saidi@ARM.com# Copyright (c) 2004-2005 The Regents of The University of Michigan
47399SAli.Saidi@ARM.com# All rights reserved.
57399SAli.Saidi@ARM.com#
67399SAli.Saidi@ARM.com# Redistribution and use in source and binary forms, with or without
77399SAli.Saidi@ARM.com# modification, are permitted provided that the following conditions are
87399SAli.Saidi@ARM.com# met: redistributions of source code must retain the above copyright
97399SAli.Saidi@ARM.com# notice, this list of conditions and the following disclaimer;
107399SAli.Saidi@ARM.com# redistributions in binary form must reproduce the above copyright
117399SAli.Saidi@ARM.com# notice, this list of conditions and the following disclaimer in the
127399SAli.Saidi@ARM.com# documentation and/or other materials provided with the distribution;
137399SAli.Saidi@ARM.com# neither the name of the copyright holders nor the names of its
146019Shines@cs.fsu.edu# contributors may be used to endorse or promote products derived from
156019Shines@cs.fsu.edu# this software without specific prior written permission.
166019Shines@cs.fsu.edu#
176019Shines@cs.fsu.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
186019Shines@cs.fsu.edu# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
196019Shines@cs.fsu.edu# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
206019Shines@cs.fsu.edu# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
216019Shines@cs.fsu.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
226019Shines@cs.fsu.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
236019Shines@cs.fsu.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
246019Shines@cs.fsu.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
256019Shines@cs.fsu.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
266019Shines@cs.fsu.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
276019Shines@cs.fsu.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
286019Shines@cs.fsu.edu#
296019Shines@cs.fsu.edu# Authors: Steve Reinhardt
306019Shines@cs.fsu.edu
316019Shines@cs.fsu.edu###################################################
326019Shines@cs.fsu.edu#
336019Shines@cs.fsu.edu# SCons top-level build description (SConstruct) file.
346019Shines@cs.fsu.edu#
356019Shines@cs.fsu.edu# While in this directory ('m5'), just type 'scons' to build the default
366019Shines@cs.fsu.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
376019Shines@cs.fsu.edu# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
386019Shines@cs.fsu.edu# the optimized full-system version).
396019Shines@cs.fsu.edu#
406019Shines@cs.fsu.edu# You can build M5 in a different directory as long as there is a
416019Shines@cs.fsu.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
427399SAli.Saidi@ARM.com# expects that all configs under the same build directory are being
436019Shines@cs.fsu.edu# built for the same host system.
446019Shines@cs.fsu.edu#
456019Shines@cs.fsu.edu# Examples:
466019Shines@cs.fsu.edu#
476019Shines@cs.fsu.edu#   The following two commands are equivalent.  The '-u' option tells
486019Shines@cs.fsu.edu#   scons to search up the directory tree for this SConstruct file.
496019Shines@cs.fsu.edu#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
506019Shines@cs.fsu.edu#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
516019Shines@cs.fsu.edu#
526019Shines@cs.fsu.edu#   The following two commands are equivalent and demonstrate building
536019Shines@cs.fsu.edu#   in a directory outside of the source tree.  The '-C' option tells
546019Shines@cs.fsu.edu#   scons to chdir to the specified directory to find this SConstruct
557399SAli.Saidi@ARM.com#   file.
567399SAli.Saidi@ARM.com#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
577399SAli.Saidi@ARM.com#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
587399SAli.Saidi@ARM.com#
597399SAli.Saidi@ARM.com# You can use 'scons -H' to print scons options.  If you're in this
607399SAli.Saidi@ARM.com# 'm5' directory (or use -u or -C to tell scons where to find this
617399SAli.Saidi@ARM.com# file), you can use 'scons -h' to print all the M5-specific build
627399SAli.Saidi@ARM.com# options as well.
637399SAli.Saidi@ARM.com#
647399SAli.Saidi@ARM.com###################################################
656019Shines@cs.fsu.edu
667399SAli.Saidi@ARM.comimport sys
677399SAli.Saidi@ARM.comimport os
686019Shines@cs.fsu.eduimport re
697399SAli.Saidi@ARM.com
707399SAli.Saidi@ARM.comfrom os.path import isdir, isfile, join as joinpath
717399SAli.Saidi@ARM.com
727399SAli.Saidi@ARM.comimport SCons
736019Shines@cs.fsu.edu
747399SAli.Saidi@ARM.com# Check for recent-enough Python and SCons versions.  If your system's
756019Shines@cs.fsu.edu# default installation of Python is not recent enough, you can use a
767399SAli.Saidi@ARM.com# non-default installation of the Python interpreter by either (1)
777399SAli.Saidi@ARM.com# rearranging your PATH so that scons finds the non-default 'python'
787399SAli.Saidi@ARM.com# first or (2) explicitly invoking an alternative interpreter on the
797399SAli.Saidi@ARM.com# scons script, e.g., "/usr/local/bin/python2.4 `which scons` [args]".
807399SAli.Saidi@ARM.comEnsurePythonVersion(2,4)
817399SAli.Saidi@ARM.com
827399SAli.Saidi@ARM.com# Import subprocess after we check the version since it doesn't exist in
836019Shines@cs.fsu.edu# Python < 2.4.
847399SAli.Saidi@ARM.comimport subprocess
857399SAli.Saidi@ARM.com
867399SAli.Saidi@ARM.com# helper function: compare arrays or strings of version numbers.
876019Shines@cs.fsu.edu# E.g., compare_version((1,3,25), (1,4,1)')
887399SAli.Saidi@ARM.com# returns -1, 0, 1 if v1 is <, ==, > v2
897399SAli.Saidi@ARM.comdef compare_versions(v1, v2):
907399SAli.Saidi@ARM.com    def make_version_list(v):
917399SAli.Saidi@ARM.com        if isinstance(v, (list,tuple)):
927399SAli.Saidi@ARM.com            return v
936019Shines@cs.fsu.edu        elif isinstance(v, str):
947399SAli.Saidi@ARM.com            return map(int, v.split('.'))
957399SAli.Saidi@ARM.com        else:
966019Shines@cs.fsu.edu            raise TypeError
977399SAli.Saidi@ARM.com
987399SAli.Saidi@ARM.com    v1 = make_version_list(v1)
997399SAli.Saidi@ARM.com    v2 = make_version_list(v2)
1007399SAli.Saidi@ARM.com    # Compare corresponding elements of lists
1017399SAli.Saidi@ARM.com    for n1,n2 in zip(v1, v2):
1026019Shines@cs.fsu.edu        if n1 < n2: return -1
1037399SAli.Saidi@ARM.com        if n1 > n2: return  1
1047399SAli.Saidi@ARM.com    # all corresponding values are equal... see if one has extra values
1057399SAli.Saidi@ARM.com    if len(v1) < len(v2): return -1
1067399SAli.Saidi@ARM.com    if len(v1) > len(v2): return  1
1077399SAli.Saidi@ARM.com    return 0
1086019Shines@cs.fsu.edu
1097402SAli.Saidi@ARM.com# SCons version numbers need special processing because they can have
1107402SAli.Saidi@ARM.com# charecters and an release date embedded in them. This function does
1117402SAli.Saidi@ARM.com# the magic to extract them in a similar way to the SCons internal function
1127399SAli.Saidi@ARM.com# function does and then checks that the current version is not contained in
1136019Shines@cs.fsu.edu# a list of version tuples (bad_ver_strs)
1147399SAli.Saidi@ARM.comdef CheckSCons(bad_ver_strs):
1156019Shines@cs.fsu.edu    def scons_ver(v):
1166019Shines@cs.fsu.edu        num_parts = v.split(' ')[0].split('.')
1176019Shines@cs.fsu.edu        major = int(num_parts[0])
1186019Shines@cs.fsu.edu        minor = int(re.match('\d+', num_parts[1]).group())
119        rev = 0
120        rdate = 0
121        if len(num_parts) > 2:
122            try: rev = int(re.match('\d+', num_parts[2]).group())
123            except: pass
124            rev_parts = num_parts[2].split('d')
125            if len(rev_parts) > 1:
126                rdate = int(re.match('\d+', rev_parts[1]).group())
127
128        return (major, minor, rev, rdate)
129
130    sc_ver = scons_ver(SCons.__version__)
131    for bad_ver in bad_ver_strs:
132        bv = (scons_ver(bad_ver[0]), scons_ver(bad_ver[1]))
133        if  compare_versions(sc_ver, bv[0]) != -1 and\
134            compare_versions(sc_ver, bv[1]) != 1:
135            print "The version of SCons that you have installed: ", SCons.__version__
136            print "has a bug that prevents it from working correctly with M5."
137            print "Please install a version NOT contained within the following",
138            print "ranges (inclusive):"
139            for bad_ver in bad_ver_strs:
140                print "    %s - %s" % bad_ver
141            Exit(2)
142
143CheckSCons(( 
144    # We need a version that is 0.96.91 or newer
145    ('0.0.0', '0.96.90'), 
146    ))
147
148
149# The absolute path to the current directory (where this file lives).
150ROOT = Dir('.').abspath
151
152# Path to the M5 source tree.
153SRCDIR = joinpath(ROOT, 'src')
154
155# tell python where to find m5 python code
156sys.path.append(joinpath(ROOT, 'src/python'))
157
158def check_style_hook(ui):
159    ui.readconfig(joinpath(ROOT, '.hg', 'hgrc'))
160    style_hook = ui.config('hooks', 'pretxncommit.style', None)
161
162    if not style_hook:
163        print """\
164You're missing the M5 style hook.
165Please install the hook so we can ensure that all code fits a common style.
166
167All you'd need to do is add the following lines to your repository .hg/hgrc
168or your personal .hgrc
169----------------
170
171[extensions]
172style = %s/util/style.py
173
174[hooks]
175pretxncommit.style = python:style.check_whitespace
176""" % (ROOT)
177        sys.exit(1)
178
179if ARGUMENTS.get('IGNORE_STYLE') != 'True' and isdir(joinpath(ROOT, '.hg')):
180    try:
181        from mercurial import ui
182        check_style_hook(ui.ui())
183    except ImportError:
184        pass
185
186###################################################
187#
188# Figure out which configurations to set up based on the path(s) of
189# the target(s).
190#
191###################################################
192
193# Find default configuration & binary.
194Default(os.environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
195
196# helper function: find last occurrence of element in list
197def rfind(l, elt, offs = -1):
198    for i in range(len(l)+offs, 0, -1):
199        if l[i] == elt:
200            return i
201    raise ValueError, "element not found"
202
203# Each target must have 'build' in the interior of the path; the
204# directory below this will determine the build parameters.  For
205# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
206# recognize that ALPHA_SE specifies the configuration because it
207# follow 'build' in the bulid path.
208
209# Generate absolute paths to targets so we can see where the build dir is
210if COMMAND_LINE_TARGETS:
211    # Ask SCons which directory it was invoked from
212    launch_dir = GetLaunchDir()
213    # Make targets relative to invocation directory
214    abs_targets = map(lambda x: os.path.normpath(joinpath(launch_dir, str(x))),
215                      COMMAND_LINE_TARGETS)
216else:
217    # Default targets are relative to root of tree
218    abs_targets = map(lambda x: os.path.normpath(joinpath(ROOT, str(x))),
219                      DEFAULT_TARGETS)
220
221
222# Generate a list of the unique build roots and configs that the
223# collected targets reference.
224build_paths = []
225build_root = None
226for t in abs_targets:
227    path_dirs = t.split('/')
228    try:
229        build_top = rfind(path_dirs, 'build', -2)
230    except:
231        print "Error: no non-leaf 'build' dir found on target path", t
232        Exit(1)
233    this_build_root = joinpath('/',*path_dirs[:build_top+1])
234    if not build_root:
235        build_root = this_build_root
236    else:
237        if this_build_root != build_root:
238            print "Error: build targets not under same build root\n"\
239                  "  %s\n  %s" % (build_root, this_build_root)
240            Exit(1)
241    build_path = joinpath('/',*path_dirs[:build_top+2])
242    if build_path not in build_paths:
243        build_paths.append(build_path)
244
245# Make sure build_root exists (might not if this is the first build there)
246if not isdir(build_root):
247    os.mkdir(build_root)
248
249###################################################
250#
251# Set up the default build environment.  This environment is copied
252# and modified according to each selected configuration.
253#
254###################################################
255
256env = Environment(ENV = os.environ,  # inherit user's environment vars
257                  ROOT = ROOT,
258                  SRCDIR = SRCDIR)
259
260Export('env')
261
262env.SConsignFile(joinpath(build_root,"sconsign"))
263
264# Default duplicate option is to use hard links, but this messes up
265# when you use emacs to edit a file in the target dir, as emacs moves
266# file to file~ then copies to file, breaking the link.  Symbolic
267# (soft) links work better.
268env.SetOption('duplicate', 'soft-copy')
269
270# I waffle on this setting... it does avoid a few painful but
271# unnecessary builds, but it also seems to make trivial builds take
272# noticeably longer.
273if False:
274    env.TargetSignatures('content')
275
276#
277# Set up global sticky options... these are common to an entire build
278# tree (not specific to a particular build like ALPHA_SE)
279#
280
281# Option validators & converters for global sticky options
282def PathListMakeAbsolute(val):
283    if not val:
284        return val
285    f = lambda p: os.path.abspath(os.path.expanduser(p))
286    return ':'.join(map(f, val.split(':')))
287
288def PathListAllExist(key, val, env):
289    if not val:
290        return
291    paths = val.split(':')
292    for path in paths:
293        if not isdir(path):
294            raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
295
296global_sticky_opts_file = joinpath(build_root, 'options.global')
297
298global_sticky_opts = Options(global_sticky_opts_file, args=ARGUMENTS)
299
300global_sticky_opts.AddOptions(
301    ('CC', 'C compiler', os.environ.get('CC', env['CC'])),
302    ('CXX', 'C++ compiler', os.environ.get('CXX', env['CXX'])),
303    ('BATCH', 'Use batch pool for build and tests', False),
304    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
305    ('EXTRAS', 'Add Extra directories to the compilation', '',
306     PathListAllExist, PathListMakeAbsolute)
307    )    
308
309
310# base help text
311help_text = '''
312Usage: scons [scons options] [build options] [target(s)]
313
314'''
315
316help_text += "Global sticky options:\n" \
317             + global_sticky_opts.GenerateHelpText(env)
318
319# Update env with values from ARGUMENTS & file global_sticky_opts_file
320global_sticky_opts.Update(env)
321
322# Save sticky option settings back to current options file
323global_sticky_opts.Save(global_sticky_opts_file, env)
324
325# Parse EXTRAS option to build list of all directories where we're
326# look for sources etc.  This list is exported as base_dir_list.
327base_dir_list = [joinpath(ROOT, 'src')]
328if env['EXTRAS']:
329    base_dir_list += env['EXTRAS'].split(':')
330
331Export('base_dir_list')
332
333# M5_PLY is used by isa_parser.py to find the PLY package.
334env.Append(ENV = { 'M5_PLY' : str(Dir('ext/ply')) })
335env['GCC'] = False
336env['SUNCC'] = False
337env['ICC'] = False
338env['GCC'] = subprocess.Popen(env['CXX'] + ' --version', shell=True,
339        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
340        close_fds=True).communicate()[0].find('GCC') >= 0
341env['SUNCC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True,
342        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
343        close_fds=True).communicate()[0].find('Sun C++') >= 0
344env['ICC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True,
345        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
346        close_fds=True).communicate()[0].find('Intel') >= 0
347if env['GCC'] + env['SUNCC'] + env['ICC'] > 1:
348    print 'Error: How can we have two at the same time?'
349    Exit(1)
350
351
352# Set up default C++ compiler flags
353if env['GCC']:
354    env.Append(CCFLAGS='-pipe')
355    env.Append(CCFLAGS='-fno-strict-aliasing')
356    env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
357elif env['ICC']:
358    pass #Fix me... add warning flags once we clean up icc warnings
359elif env['SUNCC']:
360    env.Append(CCFLAGS='-Qoption ccfe')
361    env.Append(CCFLAGS='-features=gcc')
362    env.Append(CCFLAGS='-features=extensions')
363    env.Append(CCFLAGS='-library=stlport4')
364    env.Append(CCFLAGS='-xar')
365#    env.Append(CCFLAGS='-instances=semiexplicit')
366else:
367    print 'Error: Don\'t know what compiler options to use for your compiler.'
368    print '       Please fix SConstruct and src/SConscript and try again.'
369    Exit(1)
370
371# Do this after we save setting back, or else we'll tack on an
372# extra 'qdo' every time we run scons.
373if env['BATCH']:
374    env['CC']  = env['BATCH_CMD'] + ' ' + env['CC']
375    env['CXX'] = env['BATCH_CMD'] + ' ' + env['CXX']
376
377if sys.platform == 'cygwin':
378    # cygwin has some header file issues...
379    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
380env.Append(CPPPATH=[Dir('ext/dnet')])
381
382# Check for SWIG
383if not env.has_key('SWIG'):
384    print 'Error: SWIG utility not found.'
385    print '       Please install (see http://www.swig.org) and retry.'
386    Exit(1)
387
388# Check for appropriate SWIG version
389swig_version = os.popen('swig -version').read().split()
390# First 3 words should be "SWIG Version x.y.z"
391if len(swig_version) < 3 or \
392        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
393    print 'Error determining SWIG version.'
394    Exit(1)
395
396min_swig_version = '1.3.28'
397if compare_versions(swig_version[2], min_swig_version) < 0:
398    print 'Error: SWIG version', min_swig_version, 'or newer required.'
399    print '       Installed version:', swig_version[2]
400    Exit(1)
401
402# Set up SWIG flags & scanner
403swig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
404env.Append(SWIGFLAGS=swig_flags)
405
406# filter out all existing swig scanners, they mess up the dependency
407# stuff for some reason
408scanners = []
409for scanner in env['SCANNERS']:
410    skeys = scanner.skeys
411    if skeys == '.i':
412        continue
413
414    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
415        continue
416
417    scanners.append(scanner)
418
419# add the new swig scanner that we like better
420from SCons.Scanner import ClassicCPP as CPPScanner
421swig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
422scanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
423
424# replace the scanners list that has what we want
425env['SCANNERS'] = scanners
426
427# Add a custom Check function to the Configure context so that we can
428# figure out if the compiler adds leading underscores to global
429# variables.  This is needed for the autogenerated asm files that we
430# use for embedding the python code.
431def CheckLeading(context):
432    context.Message("Checking for leading underscore in global variables...")
433    # 1) Define a global variable called x from asm so the C compiler
434    #    won't change the symbol at all.
435    # 2) Declare that variable.
436    # 3) Use the variable
437    #
438    # If the compiler prepends an underscore, this will successfully
439    # link because the external symbol 'x' will be called '_x' which
440    # was defined by the asm statement.  If the compiler does not
441    # prepend an underscore, this will not successfully link because
442    # '_x' will have been defined by assembly, while the C portion of
443    # the code will be trying to use 'x'
444    ret = context.TryLink('''
445        asm(".globl _x; _x: .byte 0");
446        extern int x;
447        int main() { return x; }
448        ''', extension=".c")
449    context.env.Append(LEADING_UNDERSCORE=ret)
450    context.Result(ret)
451    return ret
452
453# Platform-specific configuration.  Note again that we assume that all
454# builds under a given build root run on the same host platform.
455conf = Configure(env,
456                 conf_dir = joinpath(build_root, '.scons_config'),
457                 log_file = joinpath(build_root, 'scons_config.log'),
458                 custom_tests = { 'CheckLeading' : CheckLeading })
459
460# Check for leading underscores.  Don't really need to worry either
461# way so don't need to check the return code.
462conf.CheckLeading()
463
464# Check if we should compile a 64 bit binary on Mac OS X/Darwin
465try:
466    import platform
467    uname = platform.uname()
468    if uname[0] == 'Darwin' and compare_versions(uname[2], '9.0.0') >= 0:
469        if int(subprocess.Popen('sysctl -n hw.cpu64bit_capable', shell=True,
470               stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
471               close_fds=True).communicate()[0][0]):
472            env.Append(CCFLAGS='-arch x86_64')
473            env.Append(CFLAGS='-arch x86_64')
474            env.Append(LINKFLAGS='-arch x86_64')
475            env.Append(ASFLAGS='-arch x86_64')
476except:
477    pass
478
479# Recent versions of scons substitute a "Null" object for Configure()
480# when configuration isn't necessary, e.g., if the "--help" option is
481# present.  Unfortuantely this Null object always returns false,
482# breaking all our configuration checks.  We replace it with our own
483# more optimistic null object that returns True instead.
484if not conf:
485    def NullCheck(*args, **kwargs):
486        return True
487
488    class NullConf:
489        def __init__(self, env):
490            self.env = env
491        def Finish(self):
492            return self.env
493        def __getattr__(self, mname):
494            return NullCheck
495
496    conf = NullConf(env)
497
498# Find Python include and library directories for embedding the
499# interpreter.  For consistency, we will use the same Python
500# installation used to run scons (and thus this script).  If you want
501# to link in an alternate version, see above for instructions on how
502# to invoke scons with a different copy of the Python interpreter.
503
504# Get brief Python version name (e.g., "python2.4") for locating
505# include & library files
506py_version_name = 'python' + sys.version[:3]
507
508# include path, e.g. /usr/local/include/python2.4
509py_header_path = joinpath(sys.exec_prefix, 'include', py_version_name)
510env.Append(CPPPATH = py_header_path)
511# verify that it works
512if not conf.CheckHeader('Python.h', '<>'):
513    print "Error: can't find Python.h header in", py_header_path
514    Exit(1)
515
516# add library path too if it's not in the default place
517py_lib_path = None
518if sys.exec_prefix != '/usr':
519    py_lib_path = joinpath(sys.exec_prefix, 'lib')
520elif sys.platform == 'cygwin':
521    # cygwin puts the .dll in /bin for some reason
522    py_lib_path = '/bin'
523if py_lib_path:
524    env.Append(LIBPATH = py_lib_path)
525    print 'Adding', py_lib_path, 'to LIBPATH for', py_version_name
526if not conf.CheckLib(py_version_name):
527    print "Error: can't find Python library", py_version_name
528    Exit(1)
529
530# On Solaris you need to use libsocket for socket ops
531if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
532   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
533       print "Can't find library with socket calls (e.g. accept())"
534       Exit(1)
535
536# Check for zlib.  If the check passes, libz will be automatically
537# added to the LIBS environment variable.
538if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
539    print 'Error: did not find needed zlib compression library '\
540          'and/or zlib.h header file.'
541    print '       Please install zlib and try again.'
542    Exit(1)
543
544# Check for <fenv.h> (C99 FP environment control)
545have_fenv = conf.CheckHeader('fenv.h', '<>')
546if not have_fenv:
547    print "Warning: Header file <fenv.h> not found."
548    print "         This host has no IEEE FP rounding mode control."
549
550# Check for mysql.
551mysql_config = WhereIs('mysql_config')
552have_mysql = mysql_config != None
553
554# Check MySQL version.
555if have_mysql:
556    mysql_version = os.popen(mysql_config + ' --version').read()
557    min_mysql_version = '4.1'
558    if compare_versions(mysql_version, min_mysql_version) < 0:
559        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
560        print '         Version', mysql_version, 'detected.'
561        have_mysql = False
562
563# Set up mysql_config commands.
564if have_mysql:
565    mysql_config_include = mysql_config + ' --include'
566    if os.system(mysql_config_include + ' > /dev/null') != 0:
567        # older mysql_config versions don't support --include, use
568        # --cflags instead
569        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
570    # This seems to work in all versions
571    mysql_config_libs = mysql_config + ' --libs'
572
573env = conf.Finish()
574
575# Define the universe of supported ISAs
576all_isa_list = [ ]
577Export('all_isa_list')
578
579# Define the universe of supported CPU models
580all_cpu_list = [ ]
581default_cpus = [ ]
582Export('all_cpu_list', 'default_cpus')
583
584# Sticky options get saved in the options file so they persist from
585# one invocation to the next (unless overridden, in which case the new
586# value becomes sticky).
587sticky_opts = Options(args=ARGUMENTS)
588Export('sticky_opts')
589
590# Non-sticky options only apply to the current build.
591nonsticky_opts = Options(args=ARGUMENTS)
592Export('nonsticky_opts')
593
594# Walk the tree and execute all SConsopts scripts that wil add to the
595# above options
596for base_dir in base_dir_list:
597    for root, dirs, files in os.walk(base_dir):
598        if 'SConsopts' in files:
599            print "Reading", joinpath(root, 'SConsopts')
600            SConscript(joinpath(root, 'SConsopts'))
601
602all_isa_list.sort()
603all_cpu_list.sort()
604default_cpus.sort()
605
606sticky_opts.AddOptions(
607    EnumOption('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
608    BoolOption('FULL_SYSTEM', 'Full-system support', False),
609    # There's a bug in scons 0.96.1 that causes ListOptions with list
610    # values (more than one value) not to be able to be restored from
611    # a saved option file.  If this causes trouble then upgrade to
612    # scons 0.96.90 or later.
613    ListOption('CPU_MODELS', 'CPU models', default_cpus, all_cpu_list),
614    BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
615    BoolOption('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
616               False),
617    BoolOption('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
618               False),
619    BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
620               False),
621    BoolOption('SS_COMPATIBLE_FP',
622               'Make floating-point results compatible with SimpleScalar',
623               False),
624    BoolOption('USE_SSE2',
625               'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
626               False),
627    BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
628    BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
629    BoolOption('USE_CHECKER', 'Use checker for detailed CPU models', False),
630    )
631
632nonsticky_opts.AddOptions(
633    BoolOption('update_ref', 'Update test reference outputs', False)
634    )
635
636# These options get exported to #defines in config/*.hh (see src/SConscript).
637env.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
638                     'USE_MYSQL', 'NO_FAST_ALLOC', 'FAST_ALLOC_DEBUG', \
639                     'FAST_ALLOC_STATS', 'SS_COMPATIBLE_FP', \
640                     'USE_CHECKER', 'TARGET_ISA']
641
642# Define a handy 'no-op' action
643def no_action(target, source, env):
644    return 0
645
646env.NoAction = Action(no_action, None)
647
648###################################################
649#
650# Define a SCons builder for configuration flag headers.
651#
652###################################################
653
654# This function generates a config header file that #defines the
655# option symbol to the current option setting (0 or 1).  The source
656# operands are the name of the option and a Value node containing the
657# value of the option.
658def build_config_file(target, source, env):
659    (option, value) = [s.get_contents() for s in source]
660    f = file(str(target[0]), 'w')
661    print >> f, '#define', option, value
662    f.close()
663    return None
664
665# Generate the message to be printed when building the config file.
666def build_config_file_string(target, source, env):
667    (option, value) = [s.get_contents() for s in source]
668    return "Defining %s as %s in %s." % (option, value, target[0])
669
670# Combine the two functions into a scons Action object.
671config_action = Action(build_config_file, build_config_file_string)
672
673# The emitter munges the source & target node lists to reflect what
674# we're really doing.
675def config_emitter(target, source, env):
676    # extract option name from Builder arg
677    option = str(target[0])
678    # True target is config header file
679    target = joinpath('config', option.lower() + '.hh')
680    val = env[option]
681    if isinstance(val, bool):
682        # Force value to 0/1
683        val = int(val)
684    elif isinstance(val, str):
685        val = '"' + val + '"'
686
687    # Sources are option name & value (packaged in SCons Value nodes)
688    return ([target], [Value(option), Value(val)])
689
690config_builder = Builder(emitter = config_emitter, action = config_action)
691
692env.Append(BUILDERS = { 'ConfigFile' : config_builder })
693
694###################################################
695#
696# Define a SCons builder for copying files.  This is used by the
697# Python zipfile code in src/python/SConscript, but is placed up here
698# since it's potentially more generally applicable.
699#
700###################################################
701
702copy_builder = Builder(action = Copy("$TARGET", "$SOURCE"))
703
704env.Append(BUILDERS = { 'CopyFile' : copy_builder })
705
706###################################################
707#
708# Define a simple SCons builder to concatenate files.
709#
710# Used to append the Python zip archive to the executable.
711#
712###################################################
713
714concat_builder = Builder(action = Action(['cat $SOURCES > $TARGET',
715                                          'chmod +x $TARGET']))
716
717env.Append(BUILDERS = { 'Concat' : concat_builder })
718
719
720# libelf build is shared across all configs in the build root.
721env.SConscript('ext/libelf/SConscript',
722               build_dir = joinpath(build_root, 'libelf'),
723               exports = 'env')
724
725###################################################
726#
727# This function is used to set up a directory with switching headers
728#
729###################################################
730
731env['ALL_ISA_LIST'] = all_isa_list
732def make_switching_dir(dirname, switch_headers, env):
733    # Generate the header.  target[0] is the full path of the output
734    # header to generate.  'source' is a dummy variable, since we get the
735    # list of ISAs from env['ALL_ISA_LIST'].
736    def gen_switch_hdr(target, source, env):
737        fname = str(target[0])
738        basename = os.path.basename(fname)
739        f = open(fname, 'w')
740        f.write('#include "arch/isa_specific.hh"\n')
741        cond = '#if'
742        for isa in all_isa_list:
743            f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
744                    % (cond, isa.upper(), dirname, isa, basename))
745            cond = '#elif'
746        f.write('#else\n#error "THE_ISA not set"\n#endif\n')
747        f.close()
748        return 0
749
750    # String to print when generating header
751    def gen_switch_hdr_string(target, source, env):
752        return "Generating switch header " + str(target[0])
753
754    # Build SCons Action object. 'varlist' specifies env vars that this
755    # action depends on; when env['ALL_ISA_LIST'] changes these actions
756    # should get re-executed.
757    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
758                               varlist=['ALL_ISA_LIST'])
759
760    # Instantiate actions for each header
761    for hdr in switch_headers:
762        env.Command(hdr, [], switch_hdr_action)
763Export('make_switching_dir')
764
765###################################################
766#
767# Define build environments for selected configurations.
768#
769###################################################
770
771# rename base env
772base_env = env
773
774for build_path in build_paths:
775    print "Building in", build_path
776
777    # Make a copy of the build-root environment to use for this config.
778    env = base_env.Copy()
779    env['BUILDDIR'] = build_path
780
781    # build_dir is the tail component of build path, and is used to
782    # determine the build parameters (e.g., 'ALPHA_SE')
783    (build_root, build_dir) = os.path.split(build_path)
784
785    # Set env options according to the build directory config.
786    sticky_opts.files = []
787    # Options for $BUILD_ROOT/$BUILD_DIR are stored in
788    # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
789    # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
790    current_opts_file = joinpath(build_root, 'options', build_dir)
791    if isfile(current_opts_file):
792        sticky_opts.files.append(current_opts_file)
793        print "Using saved options file %s" % current_opts_file
794    else:
795        # Build dir-specific options file doesn't exist.
796
797        # Make sure the directory is there so we can create it later
798        opt_dir = os.path.dirname(current_opts_file)
799        if not isdir(opt_dir):
800            os.mkdir(opt_dir)
801
802        # Get default build options from source tree.  Options are
803        # normally determined by name of $BUILD_DIR, but can be
804        # overriden by 'default=' arg on command line.
805        default_opts_file = joinpath('build_opts',
806                                     ARGUMENTS.get('default', build_dir))
807        if isfile(default_opts_file):
808            sticky_opts.files.append(default_opts_file)
809            print "Options file %s not found,\n  using defaults in %s" \
810                  % (current_opts_file, default_opts_file)
811        else:
812            print "Error: cannot find options file %s or %s" \
813                  % (current_opts_file, default_opts_file)
814            Exit(1)
815
816    # Apply current option settings to env
817    sticky_opts.Update(env)
818    nonsticky_opts.Update(env)
819
820    help_text += "\nSticky options for %s:\n" % build_dir \
821                 + sticky_opts.GenerateHelpText(env) \
822                 + "\nNon-sticky options for %s:\n" % build_dir \
823                 + nonsticky_opts.GenerateHelpText(env)
824
825    # Process option settings.
826
827    if not have_fenv and env['USE_FENV']:
828        print "Warning: <fenv.h> not available; " \
829              "forcing USE_FENV to False in", build_dir + "."
830        env['USE_FENV'] = False
831
832    if not env['USE_FENV']:
833        print "Warning: No IEEE FP rounding mode control in", build_dir + "."
834        print "         FP results may deviate slightly from other platforms."
835
836    if env['EFENCE']:
837        env.Append(LIBS=['efence'])
838
839    if env['USE_MYSQL']:
840        if not have_mysql:
841            print "Warning: MySQL not available; " \
842                  "forcing USE_MYSQL to False in", build_dir + "."
843            env['USE_MYSQL'] = False
844        else:
845            print "Compiling in", build_dir, "with MySQL support."
846            env.ParseConfig(mysql_config_libs)
847            env.ParseConfig(mysql_config_include)
848
849    # Save sticky option settings back to current options file
850    sticky_opts.Save(current_opts_file, env)
851
852    if env['USE_SSE2']:
853        env.Append(CCFLAGS='-msse2')
854
855    # The src/SConscript file sets up the build rules in 'env' according
856    # to the configured options.  It returns a list of environments,
857    # one for each variant build (debug, opt, etc.)
858    envList = SConscript('src/SConscript', build_dir = build_path,
859                         exports = 'env')
860
861    # Set up the regression tests for each build.
862    for e in envList:
863        SConscript('tests/SConscript',
864                   build_dir = joinpath(build_path, 'tests', e.Label),
865                   exports = { 'env' : e }, duplicate = False)
866
867Help(help_text)
868
869
870###################################################
871#
872# Let SCons do its thing.  At this point SCons will use the defined
873# build environments to build the requested targets.
874#
875###################################################
876
877