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