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