SConstruct (5397:58e5b68f7095) SConstruct (5398:9727ba4600de)
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
66import sys
67import os
68import re
69
70from os.path import isdir, isfile, join as joinpath
71
72import SCons
73
74# Check for recent-enough Python and SCons versions. If your system's
75# default installation of Python is not recent enough, you can use a
76# non-default installation of the Python interpreter by either (1)
77# rearranging your PATH so that scons finds the non-default 'python'
78# first or (2) explicitly invoking an alternative interpreter on the
79# scons script, e.g., "/usr/local/bin/python2.4 `which scons` [args]".
80EnsurePythonVersion(2,4)
81
82# Import subprocess after we check the version since it doesn't exist in
83# Python < 2.4.
84import subprocess
85
86# helper function: compare arrays or strings of version numbers.
87# E.g., compare_version((1,3,25), (1,4,1)')
88# returns -1, 0, 1 if v1 is <, ==, > v2
89def compare_versions(v1, v2):
90 def make_version_list(v):
91 if isinstance(v, (list,tuple)):
92 return v
93 elif isinstance(v, str):
94 return map(int, v.split('.'))
95 else:
96 raise TypeError
97
98 v1 = make_version_list(v1)
99 v2 = make_version_list(v2)
100 # Compare corresponding elements of lists
101 for n1,n2 in zip(v1, v2):
102 if n1 < n2: return -1
103 if n1 > n2: return 1
104 # all corresponding values are equal... see if one has extra values
105 if len(v1) < len(v2): return -1
106 if len(v1) > len(v2): return 1
107 return 0
108
109# SCons version numbers need special processing because they can have
110# charecters and an release date embedded in them. This function does
111# the magic to extract them in a similar way to the SCons internal function
112# function does and then checks that the current version is not contained in
113# a list of version tuples (bad_ver_strs)
114def CheckSCons(bad_ver_strs):
115 def scons_ver(v):
116 num_parts = v.split(' ')[0].split('.')
117 major = int(num_parts[0])
118 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'),
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
66import sys
67import os
68import re
69
70from os.path import isdir, isfile, join as joinpath
71
72import SCons
73
74# Check for recent-enough Python and SCons versions. If your system's
75# default installation of Python is not recent enough, you can use a
76# non-default installation of the Python interpreter by either (1)
77# rearranging your PATH so that scons finds the non-default 'python'
78# first or (2) explicitly invoking an alternative interpreter on the
79# scons script, e.g., "/usr/local/bin/python2.4 `which scons` [args]".
80EnsurePythonVersion(2,4)
81
82# Import subprocess after we check the version since it doesn't exist in
83# Python < 2.4.
84import subprocess
85
86# helper function: compare arrays or strings of version numbers.
87# E.g., compare_version((1,3,25), (1,4,1)')
88# returns -1, 0, 1 if v1 is <, ==, > v2
89def compare_versions(v1, v2):
90 def make_version_list(v):
91 if isinstance(v, (list,tuple)):
92 return v
93 elif isinstance(v, str):
94 return map(int, v.split('.'))
95 else:
96 raise TypeError
97
98 v1 = make_version_list(v1)
99 v2 = make_version_list(v2)
100 # Compare corresponding elements of lists
101 for n1,n2 in zip(v1, v2):
102 if n1 < n2: return -1
103 if n1 > n2: return 1
104 # all corresponding values are equal... see if one has extra values
105 if len(v1) < len(v2): return -1
106 if len(v1) > len(v2): return 1
107 return 0
108
109# SCons version numbers need special processing because they can have
110# charecters and an release date embedded in them. This function does
111# the magic to extract them in a similar way to the SCons internal function
112# function does and then checks that the current version is not contained in
113# a list of version tuples (bad_ver_strs)
114def CheckSCons(bad_ver_strs):
115 def scons_ver(v):
116 num_parts = v.split(' ')[0].split('.')
117 major = int(num_parts[0])
118 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 # This range has a bug with linking directories into the build dir
147 # that only have header files in them
148 ('0.97.0d20071212', '0.98.0')
149 ))
150
151
152# The absolute path to the current directory (where this file lives).
153ROOT = Dir('.').abspath
154
155# Path to the M5 source tree.
156SRCDIR = joinpath(ROOT, 'src')
157
158# tell python where to find m5 python code
159sys.path.append(joinpath(ROOT, 'src/python'))
160
161def check_style_hook(ui):
162 ui.readconfig(joinpath(ROOT, '.hg', 'hgrc'))
163 style_hook = ui.config('hooks', 'pretxncommit.style', None)
164
165 if not style_hook:
166 print """\
167You're missing the M5 style hook.
168Please install the hook so we can ensure that all code fits a common style.
169
170All you'd need to do is add the following lines to your repository .hg/hgrc
171or your personal .hgrc
172----------------
173
174[extensions]
175style = %s/util/style.py
176
177[hooks]
178pretxncommit.style = python:style.check_whitespace
179""" % (ROOT)
180 sys.exit(1)
181
182if ARGUMENTS.get('IGNORE_STYLE') != 'True' and isdir(joinpath(ROOT, '.hg')):
183 try:
184 from mercurial import ui
185 check_style_hook(ui.ui())
186 except ImportError:
187 pass
188
189###################################################
190#
191# Figure out which configurations to set up based on the path(s) of
192# the target(s).
193#
194###################################################
195
196# Find default configuration & binary.
197Default(os.environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
198
199# helper function: find last occurrence of element in list
200def rfind(l, elt, offs = -1):
201 for i in range(len(l)+offs, 0, -1):
202 if l[i] == elt:
203 return i
204 raise ValueError, "element not found"
205
206# Each target must have 'build' in the interior of the path; the
207# directory below this will determine the build parameters. For
208# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
209# recognize that ALPHA_SE specifies the configuration because it
210# follow 'build' in the bulid path.
211
212# Generate absolute paths to targets so we can see where the build dir is
213if COMMAND_LINE_TARGETS:
214 # Ask SCons which directory it was invoked from
215 launch_dir = GetLaunchDir()
216 # Make targets relative to invocation directory
217 abs_targets = map(lambda x: os.path.normpath(joinpath(launch_dir, str(x))),
218 COMMAND_LINE_TARGETS)
219else:
220 # Default targets are relative to root of tree
221 abs_targets = map(lambda x: os.path.normpath(joinpath(ROOT, str(x))),
222 DEFAULT_TARGETS)
223
224
225# Generate a list of the unique build roots and configs that the
226# collected targets reference.
227build_paths = []
228build_root = None
229for t in abs_targets:
230 path_dirs = t.split('/')
231 try:
232 build_top = rfind(path_dirs, 'build', -2)
233 except:
234 print "Error: no non-leaf 'build' dir found on target path", t
235 Exit(1)
236 this_build_root = joinpath('/',*path_dirs[:build_top+1])
237 if not build_root:
238 build_root = this_build_root
239 else:
240 if this_build_root != build_root:
241 print "Error: build targets not under same build root\n"\
242 " %s\n %s" % (build_root, this_build_root)
243 Exit(1)
244 build_path = joinpath('/',*path_dirs[:build_top+2])
245 if build_path not in build_paths:
246 build_paths.append(build_path)
247
248# Make sure build_root exists (might not if this is the first build there)
249if not isdir(build_root):
250 os.mkdir(build_root)
251
252###################################################
253#
254# Set up the default build environment. This environment is copied
255# and modified according to each selected configuration.
256#
257###################################################
258
259env = Environment(ENV = os.environ, # inherit user's environment vars
260 ROOT = ROOT,
261 SRCDIR = SRCDIR)
262
263Export('env')
264
265env.SConsignFile(joinpath(build_root,"sconsign"))
266
267# Default duplicate option is to use hard links, but this messes up
268# when you use emacs to edit a file in the target dir, as emacs moves
269# file to file~ then copies to file, breaking the link. Symbolic
270# (soft) links work better.
271env.SetOption('duplicate', 'soft-copy')
272
273# I waffle on this setting... it does avoid a few painful but
274# unnecessary builds, but it also seems to make trivial builds take
275# noticeably longer.
276if False:
277 env.TargetSignatures('content')
278
279#
280# Set up global sticky options... these are common to an entire build
281# tree (not specific to a particular build like ALPHA_SE)
282#
283
284# Option validators & converters for global sticky options
285def PathListMakeAbsolute(val):
286 if not val:
287 return val
288 f = lambda p: os.path.abspath(os.path.expanduser(p))
289 return ':'.join(map(f, val.split(':')))
290
291def PathListAllExist(key, val, env):
292 if not val:
293 return
294 paths = val.split(':')
295 for path in paths:
296 if not isdir(path):
297 raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
298
299global_sticky_opts_file = joinpath(build_root, 'options.global')
300
301global_sticky_opts = Options(global_sticky_opts_file, args=ARGUMENTS)
302
303global_sticky_opts.AddOptions(
304 ('CC', 'C compiler', os.environ.get('CC', env['CC'])),
305 ('CXX', 'C++ compiler', os.environ.get('CXX', env['CXX'])),
306 ('BATCH', 'Use batch pool for build and tests', False),
307 ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
308 ('EXTRAS', 'Add Extra directories to the compilation', '',
309 PathListAllExist, PathListMakeAbsolute)
310 )
311
312
313# base help text
314help_text = '''
315Usage: scons [scons options] [build options] [target(s)]
316
317'''
318
319help_text += "Global sticky options:\n" \
320 + global_sticky_opts.GenerateHelpText(env)
321
322# Update env with values from ARGUMENTS & file global_sticky_opts_file
323global_sticky_opts.Update(env)
324
325# Save sticky option settings back to current options file
326global_sticky_opts.Save(global_sticky_opts_file, env)
327
328# Parse EXTRAS option to build list of all directories where we're
329# look for sources etc. This list is exported as base_dir_list.
330base_dir_list = [joinpath(ROOT, 'src')]
331if env['EXTRAS']:
332 base_dir_list += env['EXTRAS'].split(':')
333
334Export('base_dir_list')
335
336# M5_PLY is used by isa_parser.py to find the PLY package.
337env.Append(ENV = { 'M5_PLY' : str(Dir('ext/ply')) })
338env['GCC'] = False
339env['SUNCC'] = False
340env['ICC'] = False
341env['GCC'] = subprocess.Popen(env['CXX'] + ' --version', shell=True,
342 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
343 close_fds=True).communicate()[0].find('GCC') >= 0
344env['SUNCC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True,
345 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
346 close_fds=True).communicate()[0].find('Sun C++') >= 0
347env['ICC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True,
348 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
349 close_fds=True).communicate()[0].find('Intel') >= 0
350if env['GCC'] + env['SUNCC'] + env['ICC'] > 1:
351 print 'Error: How can we have two at the same time?'
352 Exit(1)
353
354
355# Set up default C++ compiler flags
356if env['GCC']:
357 env.Append(CCFLAGS='-pipe')
358 env.Append(CCFLAGS='-fno-strict-aliasing')
359 env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
360elif env['ICC']:
361 pass #Fix me... add warning flags once we clean up icc warnings
362elif env['SUNCC']:
363 env.Append(CCFLAGS='-Qoption ccfe')
364 env.Append(CCFLAGS='-features=gcc')
365 env.Append(CCFLAGS='-features=extensions')
366 env.Append(CCFLAGS='-library=stlport4')
367 env.Append(CCFLAGS='-xar')
368# env.Append(CCFLAGS='-instances=semiexplicit')
369else:
370 print 'Error: Don\'t know what compiler options to use for your compiler.'
371 print ' Please fix SConstruct and src/SConscript and try again.'
372 Exit(1)
373
374# Do this after we save setting back, or else we'll tack on an
375# extra 'qdo' every time we run scons.
376if env['BATCH']:
377 env['CC'] = env['BATCH_CMD'] + ' ' + env['CC']
378 env['CXX'] = env['BATCH_CMD'] + ' ' + env['CXX']
379
380if sys.platform == 'cygwin':
381 # cygwin has some header file issues...
382 env.Append(CCFLAGS=Split("-Wno-uninitialized"))
383env.Append(CPPPATH=[Dir('ext/dnet')])
384
385# Check for SWIG
386if not env.has_key('SWIG'):
387 print 'Error: SWIG utility not found.'
388 print ' Please install (see http://www.swig.org) and retry.'
389 Exit(1)
390
391# Check for appropriate SWIG version
392swig_version = os.popen('swig -version').read().split()
393# First 3 words should be "SWIG Version x.y.z"
394if len(swig_version) < 3 or \
395 swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
396 print 'Error determining SWIG version.'
397 Exit(1)
398
399min_swig_version = '1.3.28'
400if compare_versions(swig_version[2], min_swig_version) < 0:
401 print 'Error: SWIG version', min_swig_version, 'or newer required.'
402 print ' Installed version:', swig_version[2]
403 Exit(1)
404
405# Set up SWIG flags & scanner
406swig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
407env.Append(SWIGFLAGS=swig_flags)
408
409# filter out all existing swig scanners, they mess up the dependency
410# stuff for some reason
411scanners = []
412for scanner in env['SCANNERS']:
413 skeys = scanner.skeys
414 if skeys == '.i':
415 continue
416
417 if isinstance(skeys, (list, tuple)) and '.i' in skeys:
418 continue
419
420 scanners.append(scanner)
421
422# add the new swig scanner that we like better
423from SCons.Scanner import ClassicCPP as CPPScanner
424swig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
425scanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
426
427# replace the scanners list that has what we want
428env['SCANNERS'] = scanners
429
430# Platform-specific configuration. Note again that we assume that all
431# builds under a given build root run on the same host platform.
432conf = Configure(env,
433 conf_dir = joinpath(build_root, '.scons_config'),
434 log_file = joinpath(build_root, 'scons_config.log'))
435
436# Check if we should compile a 64 bit binary on Mac OS X/Darwin
437try:
438 import platform
439 uname = platform.uname()
440 if uname[0] == 'Darwin' and compare_versions(uname[2], '9.0.0') >= 0:
441 if int(subprocess.Popen('sysctl -n hw.cpu64bit_capable', shell=True,
442 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
443 close_fds=True).communicate()[0][0]):
444 env.Append(CCFLAGS='-arch x86_64')
445 env.Append(CFLAGS='-arch x86_64')
446 env.Append(LINKFLAGS='-arch x86_64')
447 env.Append(ASFLAGS='-arch x86_64')
448except:
449 pass
450
451# Recent versions of scons substitute a "Null" object for Configure()
452# when configuration isn't necessary, e.g., if the "--help" option is
453# present. Unfortuantely this Null object always returns false,
454# breaking all our configuration checks. We replace it with our own
455# more optimistic null object that returns True instead.
456if not conf:
457 def NullCheck(*args, **kwargs):
458 return True
459
460 class NullConf:
461 def __init__(self, env):
462 self.env = env
463 def Finish(self):
464 return self.env
465 def __getattr__(self, mname):
466 return NullCheck
467
468 conf = NullConf(env)
469
470# Find Python include and library directories for embedding the
471# interpreter. For consistency, we will use the same Python
472# installation used to run scons (and thus this script). If you want
473# to link in an alternate version, see above for instructions on how
474# to invoke scons with a different copy of the Python interpreter.
475
476# Get brief Python version name (e.g., "python2.4") for locating
477# include & library files
478py_version_name = 'python' + sys.version[:3]
479
480# include path, e.g. /usr/local/include/python2.4
481py_header_path = joinpath(sys.exec_prefix, 'include', py_version_name)
482env.Append(CPPPATH = py_header_path)
483# verify that it works
484if not conf.CheckHeader('Python.h', '<>'):
485 print "Error: can't find Python.h header in", py_header_path
486 Exit(1)
487
488# add library path too if it's not in the default place
489py_lib_path = None
490if sys.exec_prefix != '/usr':
491 py_lib_path = joinpath(sys.exec_prefix, 'lib')
492elif sys.platform == 'cygwin':
493 # cygwin puts the .dll in /bin for some reason
494 py_lib_path = '/bin'
495if py_lib_path:
496 env.Append(LIBPATH = py_lib_path)
497 print 'Adding', py_lib_path, 'to LIBPATH for', py_version_name
498if not conf.CheckLib(py_version_name):
499 print "Error: can't find Python library", py_version_name
500 Exit(1)
501
502# On Solaris you need to use libsocket for socket ops
503if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
504 if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
505 print "Can't find library with socket calls (e.g. accept())"
506 Exit(1)
507
508# Check for zlib. If the check passes, libz will be automatically
509# added to the LIBS environment variable.
510if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
511 print 'Error: did not find needed zlib compression library '\
512 'and/or zlib.h header file.'
513 print ' Please install zlib and try again.'
514 Exit(1)
515
516# Check for <fenv.h> (C99 FP environment control)
517have_fenv = conf.CheckHeader('fenv.h', '<>')
518if not have_fenv:
519 print "Warning: Header file <fenv.h> not found."
520 print " This host has no IEEE FP rounding mode control."
521
522# Check for mysql.
523mysql_config = WhereIs('mysql_config')
524have_mysql = mysql_config != None
525
526# Check MySQL version.
527if have_mysql:
528 mysql_version = os.popen(mysql_config + ' --version').read()
529 min_mysql_version = '4.1'
530 if compare_versions(mysql_version, min_mysql_version) < 0:
531 print 'Warning: MySQL', min_mysql_version, 'or newer required.'
532 print ' Version', mysql_version, 'detected.'
533 have_mysql = False
534
535# Set up mysql_config commands.
536if have_mysql:
537 mysql_config_include = mysql_config + ' --include'
538 if os.system(mysql_config_include + ' > /dev/null') != 0:
539 # older mysql_config versions don't support --include, use
540 # --cflags instead
541 mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
542 # This seems to work in all versions
543 mysql_config_libs = mysql_config + ' --libs'
544
545env = conf.Finish()
546
547# Define the universe of supported ISAs
548all_isa_list = [ ]
549Export('all_isa_list')
550
551# Define the universe of supported CPU models
552all_cpu_list = [ ]
553default_cpus = [ ]
554Export('all_cpu_list', 'default_cpus')
555
556# Sticky options get saved in the options file so they persist from
557# one invocation to the next (unless overridden, in which case the new
558# value becomes sticky).
559sticky_opts = Options(args=ARGUMENTS)
560Export('sticky_opts')
561
562# Non-sticky options only apply to the current build.
563nonsticky_opts = Options(args=ARGUMENTS)
564Export('nonsticky_opts')
565
566# Walk the tree and execute all SConsopts scripts that wil add to the
567# above options
568for base_dir in base_dir_list:
569 for root, dirs, files in os.walk(base_dir):
570 if 'SConsopts' in files:
571 print "Reading", joinpath(root, 'SConsopts')
572 SConscript(joinpath(root, 'SConsopts'))
573
574all_isa_list.sort()
575all_cpu_list.sort()
576default_cpus.sort()
577
578sticky_opts.AddOptions(
579 EnumOption('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
580 BoolOption('FULL_SYSTEM', 'Full-system support', False),
581 # There's a bug in scons 0.96.1 that causes ListOptions with list
582 # values (more than one value) not to be able to be restored from
583 # a saved option file. If this causes trouble then upgrade to
584 # scons 0.96.90 or later.
585 ListOption('CPU_MODELS', 'CPU models', default_cpus, all_cpu_list),
586 BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
587 BoolOption('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
588 False),
589 BoolOption('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
590 False),
591 BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
592 False),
593 BoolOption('SS_COMPATIBLE_FP',
594 'Make floating-point results compatible with SimpleScalar',
595 False),
596 BoolOption('USE_SSE2',
597 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
598 False),
599 BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
600 BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
601 BoolOption('USE_CHECKER', 'Use checker for detailed CPU models', False),
602 ('PYTHONHOME',
603 'Override the default PYTHONHOME for this system (use with caution)',
604 '%s:%s' % (sys.prefix, sys.exec_prefix)),
605 )
606
607nonsticky_opts.AddOptions(
608 BoolOption('update_ref', 'Update test reference outputs', False)
609 )
610
611# These options get exported to #defines in config/*.hh (see src/SConscript).
612env.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
613 'USE_MYSQL', 'NO_FAST_ALLOC', 'FAST_ALLOC_DEBUG', \
614 'FAST_ALLOC_STATS', 'SS_COMPATIBLE_FP', \
615 'USE_CHECKER', 'PYTHONHOME', 'TARGET_ISA']
616
617# Define a handy 'no-op' action
618def no_action(target, source, env):
619 return 0
620
621env.NoAction = Action(no_action, None)
622
623###################################################
624#
625# Define a SCons builder for configuration flag headers.
626#
627###################################################
628
629# This function generates a config header file that #defines the
630# option symbol to the current option setting (0 or 1). The source
631# operands are the name of the option and a Value node containing the
632# value of the option.
633def build_config_file(target, source, env):
634 (option, value) = [s.get_contents() for s in source]
635 f = file(str(target[0]), 'w')
636 print >> f, '#define', option, value
637 f.close()
638 return None
639
640# Generate the message to be printed when building the config file.
641def build_config_file_string(target, source, env):
642 (option, value) = [s.get_contents() for s in source]
643 return "Defining %s as %s in %s." % (option, value, target[0])
644
645# Combine the two functions into a scons Action object.
646config_action = Action(build_config_file, build_config_file_string)
647
648# The emitter munges the source & target node lists to reflect what
649# we're really doing.
650def config_emitter(target, source, env):
651 # extract option name from Builder arg
652 option = str(target[0])
653 # True target is config header file
654 target = joinpath('config', option.lower() + '.hh')
655 val = env[option]
656 if isinstance(val, bool):
657 # Force value to 0/1
658 val = int(val)
659 elif isinstance(val, str):
660 val = '"' + val + '"'
661
662 # Sources are option name & value (packaged in SCons Value nodes)
663 return ([target], [Value(option), Value(val)])
664
665config_builder = Builder(emitter = config_emitter, action = config_action)
666
667env.Append(BUILDERS = { 'ConfigFile' : config_builder })
668
669###################################################
670#
671# Define a SCons builder for copying files. This is used by the
672# Python zipfile code in src/python/SConscript, but is placed up here
673# since it's potentially more generally applicable.
674#
675###################################################
676
677copy_builder = Builder(action = Copy("$TARGET", "$SOURCE"))
678
679env.Append(BUILDERS = { 'CopyFile' : copy_builder })
680
681###################################################
682#
683# Define a simple SCons builder to concatenate files.
684#
685# Used to append the Python zip archive to the executable.
686#
687###################################################
688
689concat_builder = Builder(action = Action(['cat $SOURCES > $TARGET',
690 'chmod +x $TARGET']))
691
692env.Append(BUILDERS = { 'Concat' : concat_builder })
693
694
695# libelf build is shared across all configs in the build root.
696env.SConscript('ext/libelf/SConscript',
697 build_dir = joinpath(build_root, 'libelf'),
698 exports = 'env')
699
700###################################################
701#
702# This function is used to set up a directory with switching headers
703#
704###################################################
705
706env['ALL_ISA_LIST'] = all_isa_list
707def make_switching_dir(dirname, switch_headers, env):
708 # Generate the header. target[0] is the full path of the output
709 # header to generate. 'source' is a dummy variable, since we get the
710 # list of ISAs from env['ALL_ISA_LIST'].
711 def gen_switch_hdr(target, source, env):
712 fname = str(target[0])
713 basename = os.path.basename(fname)
714 f = open(fname, 'w')
715 f.write('#include "arch/isa_specific.hh"\n')
716 cond = '#if'
717 for isa in all_isa_list:
718 f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
719 % (cond, isa.upper(), dirname, isa, basename))
720 cond = '#elif'
721 f.write('#else\n#error "THE_ISA not set"\n#endif\n')
722 f.close()
723 return 0
724
725 # String to print when generating header
726 def gen_switch_hdr_string(target, source, env):
727 return "Generating switch header " + str(target[0])
728
729 # Build SCons Action object. 'varlist' specifies env vars that this
730 # action depends on; when env['ALL_ISA_LIST'] changes these actions
731 # should get re-executed.
732 switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
733 varlist=['ALL_ISA_LIST'])
734
735 # Instantiate actions for each header
736 for hdr in switch_headers:
737 env.Command(hdr, [], switch_hdr_action)
738Export('make_switching_dir')
739
740###################################################
741#
742# Define build environments for selected configurations.
743#
744###################################################
745
746# rename base env
747base_env = env
748
749for build_path in build_paths:
750 print "Building in", build_path
751
752 # Make a copy of the build-root environment to use for this config.
753 env = base_env.Copy()
754 env['BUILDDIR'] = build_path
755
756 # build_dir is the tail component of build path, and is used to
757 # determine the build parameters (e.g., 'ALPHA_SE')
758 (build_root, build_dir) = os.path.split(build_path)
759
760 # Set env options according to the build directory config.
761 sticky_opts.files = []
762 # Options for $BUILD_ROOT/$BUILD_DIR are stored in
763 # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
764 # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
765 current_opts_file = joinpath(build_root, 'options', build_dir)
766 if isfile(current_opts_file):
767 sticky_opts.files.append(current_opts_file)
768 print "Using saved options file %s" % current_opts_file
769 else:
770 # Build dir-specific options file doesn't exist.
771
772 # Make sure the directory is there so we can create it later
773 opt_dir = os.path.dirname(current_opts_file)
774 if not isdir(opt_dir):
775 os.mkdir(opt_dir)
776
777 # Get default build options from source tree. Options are
778 # normally determined by name of $BUILD_DIR, but can be
779 # overriden by 'default=' arg on command line.
780 default_opts_file = joinpath('build_opts',
781 ARGUMENTS.get('default', build_dir))
782 if isfile(default_opts_file):
783 sticky_opts.files.append(default_opts_file)
784 print "Options file %s not found,\n using defaults in %s" \
785 % (current_opts_file, default_opts_file)
786 else:
787 print "Error: cannot find options file %s or %s" \
788 % (current_opts_file, default_opts_file)
789 Exit(1)
790
791 # Apply current option settings to env
792 sticky_opts.Update(env)
793 nonsticky_opts.Update(env)
794
795 help_text += "\nSticky options for %s:\n" % build_dir \
796 + sticky_opts.GenerateHelpText(env) \
797 + "\nNon-sticky options for %s:\n" % build_dir \
798 + nonsticky_opts.GenerateHelpText(env)
799
800 # Process option settings.
801
802 if not have_fenv and env['USE_FENV']:
803 print "Warning: <fenv.h> not available; " \
804 "forcing USE_FENV to False in", build_dir + "."
805 env['USE_FENV'] = False
806
807 if not env['USE_FENV']:
808 print "Warning: No IEEE FP rounding mode control in", build_dir + "."
809 print " FP results may deviate slightly from other platforms."
810
811 if env['EFENCE']:
812 env.Append(LIBS=['efence'])
813
814 if env['USE_MYSQL']:
815 if not have_mysql:
816 print "Warning: MySQL not available; " \
817 "forcing USE_MYSQL to False in", build_dir + "."
818 env['USE_MYSQL'] = False
819 else:
820 print "Compiling in", build_dir, "with MySQL support."
821 env.ParseConfig(mysql_config_libs)
822 env.ParseConfig(mysql_config_include)
823
824 # Save sticky option settings back to current options file
825 sticky_opts.Save(current_opts_file, env)
826
827 if env['USE_SSE2']:
828 env.Append(CCFLAGS='-msse2')
829
830 # The src/SConscript file sets up the build rules in 'env' according
831 # to the configured options. It returns a list of environments,
832 # one for each variant build (debug, opt, etc.)
833 envList = SConscript('src/SConscript', build_dir = build_path,
834 exports = 'env')
835
836 # Set up the regression tests for each build.
837 for e in envList:
838 SConscript('tests/SConscript',
839 build_dir = joinpath(build_path, 'tests', e.Label),
840 exports = { 'env' : e }, duplicate = False)
841
842Help(help_text)
843
844
845###################################################
846#
847# Let SCons do its thing. At this point SCons will use the defined
848# build environments to build the requested targets.
849#
850###################################################
851
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# Platform-specific configuration. Note again that we assume that all
428# builds under a given build root run on the same host platform.
429conf = Configure(env,
430 conf_dir = joinpath(build_root, '.scons_config'),
431 log_file = joinpath(build_root, 'scons_config.log'))
432
433# Check if we should compile a 64 bit binary on Mac OS X/Darwin
434try:
435 import platform
436 uname = platform.uname()
437 if uname[0] == 'Darwin' and compare_versions(uname[2], '9.0.0') >= 0:
438 if int(subprocess.Popen('sysctl -n hw.cpu64bit_capable', shell=True,
439 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
440 close_fds=True).communicate()[0][0]):
441 env.Append(CCFLAGS='-arch x86_64')
442 env.Append(CFLAGS='-arch x86_64')
443 env.Append(LINKFLAGS='-arch x86_64')
444 env.Append(ASFLAGS='-arch x86_64')
445except:
446 pass
447
448# Recent versions of scons substitute a "Null" object for Configure()
449# when configuration isn't necessary, e.g., if the "--help" option is
450# present. Unfortuantely this Null object always returns false,
451# breaking all our configuration checks. We replace it with our own
452# more optimistic null object that returns True instead.
453if not conf:
454 def NullCheck(*args, **kwargs):
455 return True
456
457 class NullConf:
458 def __init__(self, env):
459 self.env = env
460 def Finish(self):
461 return self.env
462 def __getattr__(self, mname):
463 return NullCheck
464
465 conf = NullConf(env)
466
467# Find Python include and library directories for embedding the
468# interpreter. For consistency, we will use the same Python
469# installation used to run scons (and thus this script). If you want
470# to link in an alternate version, see above for instructions on how
471# to invoke scons with a different copy of the Python interpreter.
472
473# Get brief Python version name (e.g., "python2.4") for locating
474# include & library files
475py_version_name = 'python' + sys.version[:3]
476
477# include path, e.g. /usr/local/include/python2.4
478py_header_path = joinpath(sys.exec_prefix, 'include', py_version_name)
479env.Append(CPPPATH = py_header_path)
480# verify that it works
481if not conf.CheckHeader('Python.h', '<>'):
482 print "Error: can't find Python.h header in", py_header_path
483 Exit(1)
484
485# add library path too if it's not in the default place
486py_lib_path = None
487if sys.exec_prefix != '/usr':
488 py_lib_path = joinpath(sys.exec_prefix, 'lib')
489elif sys.platform == 'cygwin':
490 # cygwin puts the .dll in /bin for some reason
491 py_lib_path = '/bin'
492if py_lib_path:
493 env.Append(LIBPATH = py_lib_path)
494 print 'Adding', py_lib_path, 'to LIBPATH for', py_version_name
495if not conf.CheckLib(py_version_name):
496 print "Error: can't find Python library", py_version_name
497 Exit(1)
498
499# On Solaris you need to use libsocket for socket ops
500if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
501 if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
502 print "Can't find library with socket calls (e.g. accept())"
503 Exit(1)
504
505# Check for zlib. If the check passes, libz will be automatically
506# added to the LIBS environment variable.
507if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
508 print 'Error: did not find needed zlib compression library '\
509 'and/or zlib.h header file.'
510 print ' Please install zlib and try again.'
511 Exit(1)
512
513# Check for <fenv.h> (C99 FP environment control)
514have_fenv = conf.CheckHeader('fenv.h', '<>')
515if not have_fenv:
516 print "Warning: Header file <fenv.h> not found."
517 print " This host has no IEEE FP rounding mode control."
518
519# Check for mysql.
520mysql_config = WhereIs('mysql_config')
521have_mysql = mysql_config != None
522
523# Check MySQL version.
524if have_mysql:
525 mysql_version = os.popen(mysql_config + ' --version').read()
526 min_mysql_version = '4.1'
527 if compare_versions(mysql_version, min_mysql_version) < 0:
528 print 'Warning: MySQL', min_mysql_version, 'or newer required.'
529 print ' Version', mysql_version, 'detected.'
530 have_mysql = False
531
532# Set up mysql_config commands.
533if have_mysql:
534 mysql_config_include = mysql_config + ' --include'
535 if os.system(mysql_config_include + ' > /dev/null') != 0:
536 # older mysql_config versions don't support --include, use
537 # --cflags instead
538 mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
539 # This seems to work in all versions
540 mysql_config_libs = mysql_config + ' --libs'
541
542env = conf.Finish()
543
544# Define the universe of supported ISAs
545all_isa_list = [ ]
546Export('all_isa_list')
547
548# Define the universe of supported CPU models
549all_cpu_list = [ ]
550default_cpus = [ ]
551Export('all_cpu_list', 'default_cpus')
552
553# Sticky options get saved in the options file so they persist from
554# one invocation to the next (unless overridden, in which case the new
555# value becomes sticky).
556sticky_opts = Options(args=ARGUMENTS)
557Export('sticky_opts')
558
559# Non-sticky options only apply to the current build.
560nonsticky_opts = Options(args=ARGUMENTS)
561Export('nonsticky_opts')
562
563# Walk the tree and execute all SConsopts scripts that wil add to the
564# above options
565for base_dir in base_dir_list:
566 for root, dirs, files in os.walk(base_dir):
567 if 'SConsopts' in files:
568 print "Reading", joinpath(root, 'SConsopts')
569 SConscript(joinpath(root, 'SConsopts'))
570
571all_isa_list.sort()
572all_cpu_list.sort()
573default_cpus.sort()
574
575sticky_opts.AddOptions(
576 EnumOption('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
577 BoolOption('FULL_SYSTEM', 'Full-system support', False),
578 # There's a bug in scons 0.96.1 that causes ListOptions with list
579 # values (more than one value) not to be able to be restored from
580 # a saved option file. If this causes trouble then upgrade to
581 # scons 0.96.90 or later.
582 ListOption('CPU_MODELS', 'CPU models', default_cpus, all_cpu_list),
583 BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
584 BoolOption('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
585 False),
586 BoolOption('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
587 False),
588 BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
589 False),
590 BoolOption('SS_COMPATIBLE_FP',
591 'Make floating-point results compatible with SimpleScalar',
592 False),
593 BoolOption('USE_SSE2',
594 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
595 False),
596 BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
597 BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
598 BoolOption('USE_CHECKER', 'Use checker for detailed CPU models', False),
599 ('PYTHONHOME',
600 'Override the default PYTHONHOME for this system (use with caution)',
601 '%s:%s' % (sys.prefix, sys.exec_prefix)),
602 )
603
604nonsticky_opts.AddOptions(
605 BoolOption('update_ref', 'Update test reference outputs', False)
606 )
607
608# These options get exported to #defines in config/*.hh (see src/SConscript).
609env.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
610 'USE_MYSQL', 'NO_FAST_ALLOC', 'FAST_ALLOC_DEBUG', \
611 'FAST_ALLOC_STATS', 'SS_COMPATIBLE_FP', \
612 'USE_CHECKER', 'PYTHONHOME', 'TARGET_ISA']
613
614# Define a handy 'no-op' action
615def no_action(target, source, env):
616 return 0
617
618env.NoAction = Action(no_action, None)
619
620###################################################
621#
622# Define a SCons builder for configuration flag headers.
623#
624###################################################
625
626# This function generates a config header file that #defines the
627# option symbol to the current option setting (0 or 1). The source
628# operands are the name of the option and a Value node containing the
629# value of the option.
630def build_config_file(target, source, env):
631 (option, value) = [s.get_contents() for s in source]
632 f = file(str(target[0]), 'w')
633 print >> f, '#define', option, value
634 f.close()
635 return None
636
637# Generate the message to be printed when building the config file.
638def build_config_file_string(target, source, env):
639 (option, value) = [s.get_contents() for s in source]
640 return "Defining %s as %s in %s." % (option, value, target[0])
641
642# Combine the two functions into a scons Action object.
643config_action = Action(build_config_file, build_config_file_string)
644
645# The emitter munges the source & target node lists to reflect what
646# we're really doing.
647def config_emitter(target, source, env):
648 # extract option name from Builder arg
649 option = str(target[0])
650 # True target is config header file
651 target = joinpath('config', option.lower() + '.hh')
652 val = env[option]
653 if isinstance(val, bool):
654 # Force value to 0/1
655 val = int(val)
656 elif isinstance(val, str):
657 val = '"' + val + '"'
658
659 # Sources are option name & value (packaged in SCons Value nodes)
660 return ([target], [Value(option), Value(val)])
661
662config_builder = Builder(emitter = config_emitter, action = config_action)
663
664env.Append(BUILDERS = { 'ConfigFile' : config_builder })
665
666###################################################
667#
668# Define a SCons builder for copying files. This is used by the
669# Python zipfile code in src/python/SConscript, but is placed up here
670# since it's potentially more generally applicable.
671#
672###################################################
673
674copy_builder = Builder(action = Copy("$TARGET", "$SOURCE"))
675
676env.Append(BUILDERS = { 'CopyFile' : copy_builder })
677
678###################################################
679#
680# Define a simple SCons builder to concatenate files.
681#
682# Used to append the Python zip archive to the executable.
683#
684###################################################
685
686concat_builder = Builder(action = Action(['cat $SOURCES > $TARGET',
687 'chmod +x $TARGET']))
688
689env.Append(BUILDERS = { 'Concat' : concat_builder })
690
691
692# libelf build is shared across all configs in the build root.
693env.SConscript('ext/libelf/SConscript',
694 build_dir = joinpath(build_root, 'libelf'),
695 exports = 'env')
696
697###################################################
698#
699# This function is used to set up a directory with switching headers
700#
701###################################################
702
703env['ALL_ISA_LIST'] = all_isa_list
704def make_switching_dir(dirname, switch_headers, env):
705 # Generate the header. target[0] is the full path of the output
706 # header to generate. 'source' is a dummy variable, since we get the
707 # list of ISAs from env['ALL_ISA_LIST'].
708 def gen_switch_hdr(target, source, env):
709 fname = str(target[0])
710 basename = os.path.basename(fname)
711 f = open(fname, 'w')
712 f.write('#include "arch/isa_specific.hh"\n')
713 cond = '#if'
714 for isa in all_isa_list:
715 f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
716 % (cond, isa.upper(), dirname, isa, basename))
717 cond = '#elif'
718 f.write('#else\n#error "THE_ISA not set"\n#endif\n')
719 f.close()
720 return 0
721
722 # String to print when generating header
723 def gen_switch_hdr_string(target, source, env):
724 return "Generating switch header " + str(target[0])
725
726 # Build SCons Action object. 'varlist' specifies env vars that this
727 # action depends on; when env['ALL_ISA_LIST'] changes these actions
728 # should get re-executed.
729 switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
730 varlist=['ALL_ISA_LIST'])
731
732 # Instantiate actions for each header
733 for hdr in switch_headers:
734 env.Command(hdr, [], switch_hdr_action)
735Export('make_switching_dir')
736
737###################################################
738#
739# Define build environments for selected configurations.
740#
741###################################################
742
743# rename base env
744base_env = env
745
746for build_path in build_paths:
747 print "Building in", build_path
748
749 # Make a copy of the build-root environment to use for this config.
750 env = base_env.Copy()
751 env['BUILDDIR'] = build_path
752
753 # build_dir is the tail component of build path, and is used to
754 # determine the build parameters (e.g., 'ALPHA_SE')
755 (build_root, build_dir) = os.path.split(build_path)
756
757 # Set env options according to the build directory config.
758 sticky_opts.files = []
759 # Options for $BUILD_ROOT/$BUILD_DIR are stored in
760 # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
761 # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
762 current_opts_file = joinpath(build_root, 'options', build_dir)
763 if isfile(current_opts_file):
764 sticky_opts.files.append(current_opts_file)
765 print "Using saved options file %s" % current_opts_file
766 else:
767 # Build dir-specific options file doesn't exist.
768
769 # Make sure the directory is there so we can create it later
770 opt_dir = os.path.dirname(current_opts_file)
771 if not isdir(opt_dir):
772 os.mkdir(opt_dir)
773
774 # Get default build options from source tree. Options are
775 # normally determined by name of $BUILD_DIR, but can be
776 # overriden by 'default=' arg on command line.
777 default_opts_file = joinpath('build_opts',
778 ARGUMENTS.get('default', build_dir))
779 if isfile(default_opts_file):
780 sticky_opts.files.append(default_opts_file)
781 print "Options file %s not found,\n using defaults in %s" \
782 % (current_opts_file, default_opts_file)
783 else:
784 print "Error: cannot find options file %s or %s" \
785 % (current_opts_file, default_opts_file)
786 Exit(1)
787
788 # Apply current option settings to env
789 sticky_opts.Update(env)
790 nonsticky_opts.Update(env)
791
792 help_text += "\nSticky options for %s:\n" % build_dir \
793 + sticky_opts.GenerateHelpText(env) \
794 + "\nNon-sticky options for %s:\n" % build_dir \
795 + nonsticky_opts.GenerateHelpText(env)
796
797 # Process option settings.
798
799 if not have_fenv and env['USE_FENV']:
800 print "Warning: <fenv.h> not available; " \
801 "forcing USE_FENV to False in", build_dir + "."
802 env['USE_FENV'] = False
803
804 if not env['USE_FENV']:
805 print "Warning: No IEEE FP rounding mode control in", build_dir + "."
806 print " FP results may deviate slightly from other platforms."
807
808 if env['EFENCE']:
809 env.Append(LIBS=['efence'])
810
811 if env['USE_MYSQL']:
812 if not have_mysql:
813 print "Warning: MySQL not available; " \
814 "forcing USE_MYSQL to False in", build_dir + "."
815 env['USE_MYSQL'] = False
816 else:
817 print "Compiling in", build_dir, "with MySQL support."
818 env.ParseConfig(mysql_config_libs)
819 env.ParseConfig(mysql_config_include)
820
821 # Save sticky option settings back to current options file
822 sticky_opts.Save(current_opts_file, env)
823
824 if env['USE_SSE2']:
825 env.Append(CCFLAGS='-msse2')
826
827 # The src/SConscript file sets up the build rules in 'env' according
828 # to the configured options. It returns a list of environments,
829 # one for each variant build (debug, opt, etc.)
830 envList = SConscript('src/SConscript', build_dir = build_path,
831 exports = 'env')
832
833 # Set up the regression tests for each build.
834 for e in envList:
835 SConscript('tests/SConscript',
836 build_dir = joinpath(build_path, 'tests', e.Label),
837 exports = { 'env' : e }, duplicate = False)
838
839Help(help_text)
840
841
842###################################################
843#
844# Let SCons do its thing. At this point SCons will use the defined
845# build environments to build the requested targets.
846#
847###################################################
848