Wait to set BUILD_DIR until *after* env is copied.
[gem5.git] / SConstruct
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
66 import sys
67 import os
68
69 from os.path import isdir, isfile, join as joinpath
70
71 import 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]".
79 EnsurePythonVersion(2,4)
80
81 # Import subprocess after we check the version since it doesn't exist in
82 # Python < 2.4.
83 import subprocess
84
85 # Ironically, SCons 0.96 dies if you give EnsureSconsVersion a
86 # 3-element version number.
87 min_scons_version = (0,96,91)
88 try:
89 EnsureSConsVersion(*min_scons_version)
90 except:
91 print "Error checking current SCons version."
92 print "SCons", ".".join(map(str,min_scons_version)), "or greater required."
93 Exit(2)
94
95
96 # The absolute path to the current directory (where this file lives).
97 ROOT = Dir('.').abspath
98
99 # Path to the M5 source tree.
100 SRCDIR = joinpath(ROOT, 'src')
101
102 # tell python where to find m5 python code
103 sys.path.append(joinpath(ROOT, 'src/python'))
104
105 def 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 """\
111 You're missing the M5 style hook.
112 Please install the hook so we can ensure that all code fits a common style.
113
114 All you'd need to do is add the following lines to your repository .hg/hgrc
115 or your personal .hgrc
116 ----------------
117
118 [extensions]
119 style = %s/util/style.py
120
121 [hooks]
122 pretxncommit.style = python:style.check_whitespace
123 """ % (ROOT)
124 sys.exit(1)
125
126 if 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.
141 Default(os.environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
142
143 # helper function: find last occurrence of element in list
144 def 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
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
153 def 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
173 if 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)
179 else:
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.
187 build_paths = []
188 build_root = None
189 for 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)
209 if 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
219 env = Environment(ENV = os.environ, # inherit user's environment vars
220 ROOT = ROOT,
221 SRCDIR = SRCDIR)
222
223 Export('env')
224
225 env.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.
231 env.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.
236 if 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
245 def 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
251 def 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
259 global_sticky_opts_file = joinpath(build_root, 'options.global')
260
261 global_sticky_opts = Options(global_sticky_opts_file, args=ARGUMENTS)
262
263 global_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
272 help_text = '''
273 Usage: scons [scons options] [build options] [target(s)]
274
275 '''
276
277 help_text += "Global sticky options:\n" \
278 + global_sticky_opts.GenerateHelpText(env)
279
280 # Update env with values from ARGUMENTS & file global_sticky_opts_file
281 global_sticky_opts.Update(env)
282
283 # Save sticky option settings back to current options file
284 global_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.
288 base_dir_list = [ROOT]
289 if env['EXTRAS']:
290 base_dir_list += env['EXTRAS'].split(':')
291
292 Export('base_dir_list')
293
294 # M5_PLY is used by isa_parser.py to find the PLY package.
295 env.Append(ENV = { 'M5_PLY' : str(Dir('ext/ply')) })
296 env['GCC'] = False
297 env['SUNCC'] = False
298 env['ICC'] = False
299 env['GCC'] = subprocess.Popen(env['CXX'] + ' --version', shell=True,
300 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
301 close_fds=True).communicate()[0].find('GCC') >= 0
302 env['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
305 env['ICC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True,
306 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
307 close_fds=True).communicate()[0].find('Intel') >= 0
308 if 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
314 if 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'))
318 elif env['ICC']:
319 pass #Fix me... add warning flags once we clean up icc warnings
320 elif 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')
327 else:
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
332 if sys.platform == 'cygwin':
333 # cygwin has some header file issues...
334 env.Append(CCFLAGS=Split("-Wno-uninitialized"))
335 env.Append(CPPPATH=[Dir('ext/dnet')])
336
337 # Check for SWIG
338 if 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
344 swig_version = os.popen('swig -version').read().split()
345 # First 3 words should be "SWIG Version x.y.z"
346 if 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
351 min_swig_version = '1.3.28'
352 if 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
358 swig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
359 env.Append(SWIGFLAGS=swig_flags)
360
361 # filter out all existing swig scanners, they mess up the dependency
362 # stuff for some reason
363 scanners = []
364 for 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
375 from SCons.Scanner import ClassicCPP as CPPScanner
376 swig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
377 scanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
378
379 # replace the scanners list that has what we want
380 env['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.
384 conf = 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
389 try:
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
401 except:
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.
409 if 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
431 py_version_name = 'python' + sys.version[:3]
432
433 # include path, e.g. /usr/local/include/python2.4
434 py_header_path = joinpath(sys.exec_prefix, 'include', py_version_name)
435 env.Append(CPPPATH = py_header_path)
436 # verify that it works
437 if 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
442 py_lib_path = None
443 if sys.exec_prefix != '/usr':
444 py_lib_path = joinpath(sys.exec_prefix, 'lib')
445 elif sys.platform == 'cygwin':
446 # cygwin puts the .dll in /bin for some reason
447 py_lib_path = '/bin'
448 if py_lib_path:
449 env.Append(LIBPATH = py_lib_path)
450 print 'Adding', py_lib_path, 'to LIBPATH for', py_version_name
451 if 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
456 if 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.
463 if 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)
470 have_fenv = conf.CheckHeader('fenv.h', '<>')
471 if 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.
476 mysql_config = WhereIs('mysql_config')
477 have_mysql = mysql_config != None
478
479 # Check MySQL version.
480 if 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.
489 if 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
498 env = conf.Finish()
499
500 # Define the universe of supported ISAs
501 all_isa_list = [ ]
502 Export('all_isa_list')
503
504 # Define the universe of supported CPU models
505 all_cpu_list = [ ]
506 default_cpus = [ ]
507 Export('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).
512 sticky_opts = Options(args=ARGUMENTS)
513 Export('sticky_opts')
514
515 # Non-sticky options only apply to the current build.
516 nonsticky_opts = Options(args=ARGUMENTS)
517 Export('nonsticky_opts')
518
519 # Walk the tree and execute all SConsopts scripts that wil add to the
520 # above options
521 for 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
527 all_isa_list.sort()
528 all_cpu_list.sort()
529 default_cpus.sort()
530
531 sticky_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('EFENCE', 'Link with Electric Fence malloc debugger',
541 False),
542 BoolOption('SS_COMPATIBLE_FP',
543 'Make floating-point results compatible with SimpleScalar',
544 False),
545 BoolOption('USE_SSE2',
546 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
547 False),
548 BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
549 BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
550 BoolOption('USE_CHECKER', 'Use checker for detailed CPU models', False),
551 BoolOption('BATCH', 'Use batch pool for build and tests', False),
552 ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
553 ('PYTHONHOME',
554 'Override the default PYTHONHOME for this system (use with caution)',
555 '%s:%s' % (sys.prefix, sys.exec_prefix)),
556 )
557
558 nonsticky_opts.AddOptions(
559 BoolOption('update_ref', 'Update test reference outputs', False)
560 )
561
562 # These options get exported to #defines in config/*.hh (see src/SConscript).
563 env.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
564 'USE_MYSQL', 'NO_FAST_ALLOC', 'SS_COMPATIBLE_FP', \
565 'USE_CHECKER', 'PYTHONHOME', 'TARGET_ISA']
566
567 # Define a handy 'no-op' action
568 def no_action(target, source, env):
569 return 0
570
571 env.NoAction = Action(no_action, None)
572
573 ###################################################
574 #
575 # Define a SCons builder for configuration flag headers.
576 #
577 ###################################################
578
579 # This function generates a config header file that #defines the
580 # option symbol to the current option setting (0 or 1). The source
581 # operands are the name of the option and a Value node containing the
582 # value of the option.
583 def build_config_file(target, source, env):
584 (option, value) = [s.get_contents() for s in source]
585 f = file(str(target[0]), 'w')
586 print >> f, '#define', option, value
587 f.close()
588 return None
589
590 # Generate the message to be printed when building the config file.
591 def build_config_file_string(target, source, env):
592 (option, value) = [s.get_contents() for s in source]
593 return "Defining %s as %s in %s." % (option, value, target[0])
594
595 # Combine the two functions into a scons Action object.
596 config_action = Action(build_config_file, build_config_file_string)
597
598 # The emitter munges the source & target node lists to reflect what
599 # we're really doing.
600 def config_emitter(target, source, env):
601 # extract option name from Builder arg
602 option = str(target[0])
603 # True target is config header file
604 target = joinpath('config', option.lower() + '.hh')
605 val = env[option]
606 if isinstance(val, bool):
607 # Force value to 0/1
608 val = int(val)
609 elif isinstance(val, str):
610 val = '"' + val + '"'
611
612 # Sources are option name & value (packaged in SCons Value nodes)
613 return ([target], [Value(option), Value(val)])
614
615 config_builder = Builder(emitter = config_emitter, action = config_action)
616
617 env.Append(BUILDERS = { 'ConfigFile' : config_builder })
618
619 ###################################################
620 #
621 # Define a SCons builder for copying files. This is used by the
622 # Python zipfile code in src/python/SConscript, but is placed up here
623 # since it's potentially more generally applicable.
624 #
625 ###################################################
626
627 copy_builder = Builder(action = Copy("$TARGET", "$SOURCE"))
628
629 env.Append(BUILDERS = { 'CopyFile' : copy_builder })
630
631 ###################################################
632 #
633 # Define a simple SCons builder to concatenate files.
634 #
635 # Used to append the Python zip archive to the executable.
636 #
637 ###################################################
638
639 concat_builder = Builder(action = Action(['cat $SOURCES > $TARGET',
640 'chmod +x $TARGET']))
641
642 env.Append(BUILDERS = { 'Concat' : concat_builder })
643
644
645 # libelf build is shared across all configs in the build root.
646 env.SConscript('ext/libelf/SConscript',
647 build_dir = joinpath(build_root, 'libelf'),
648 exports = 'env')
649
650 ###################################################
651 #
652 # This function is used to set up a directory with switching headers
653 #
654 ###################################################
655
656 env['ALL_ISA_LIST'] = all_isa_list
657 def make_switching_dir(dirname, switch_headers, env):
658 # Generate the header. target[0] is the full path of the output
659 # header to generate. 'source' is a dummy variable, since we get the
660 # list of ISAs from env['ALL_ISA_LIST'].
661 def gen_switch_hdr(target, source, env):
662 fname = str(target[0])
663 basename = os.path.basename(fname)
664 f = open(fname, 'w')
665 f.write('#include "arch/isa_specific.hh"\n')
666 cond = '#if'
667 for isa in all_isa_list:
668 f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
669 % (cond, isa.upper(), dirname, isa, basename))
670 cond = '#elif'
671 f.write('#else\n#error "THE_ISA not set"\n#endif\n')
672 f.close()
673 return 0
674
675 # String to print when generating header
676 def gen_switch_hdr_string(target, source, env):
677 return "Generating switch header " + str(target[0])
678
679 # Build SCons Action object. 'varlist' specifies env vars that this
680 # action depends on; when env['ALL_ISA_LIST'] changes these actions
681 # should get re-executed.
682 switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
683 varlist=['ALL_ISA_LIST'])
684
685 # Instantiate actions for each header
686 for hdr in switch_headers:
687 env.Command(hdr, [], switch_hdr_action)
688 Export('make_switching_dir')
689
690 ###################################################
691 #
692 # Define build environments for selected configurations.
693 #
694 ###################################################
695
696 # rename base env
697 base_env = env
698
699 for build_path in build_paths:
700 print "Building in", build_path
701
702 # Make a copy of the build-root environment to use for this config.
703 env = base_env.Copy()
704 env['BUILDDIR'] = build_path
705
706 # build_dir is the tail component of build path, and is used to
707 # determine the build parameters (e.g., 'ALPHA_SE')
708 (build_root, build_dir) = os.path.split(build_path)
709
710 # Set env options according to the build directory config.
711 sticky_opts.files = []
712 # Options for $BUILD_ROOT/$BUILD_DIR are stored in
713 # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
714 # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
715 current_opts_file = joinpath(build_root, 'options', build_dir)
716 if isfile(current_opts_file):
717 sticky_opts.files.append(current_opts_file)
718 print "Using saved options file %s" % current_opts_file
719 else:
720 # Build dir-specific options file doesn't exist.
721
722 # Make sure the directory is there so we can create it later
723 opt_dir = os.path.dirname(current_opts_file)
724 if not isdir(opt_dir):
725 os.mkdir(opt_dir)
726
727 # Get default build options from source tree. Options are
728 # normally determined by name of $BUILD_DIR, but can be
729 # overriden by 'default=' arg on command line.
730 default_opts_file = joinpath('build_opts',
731 ARGUMENTS.get('default', build_dir))
732 if isfile(default_opts_file):
733 sticky_opts.files.append(default_opts_file)
734 print "Options file %s not found,\n using defaults in %s" \
735 % (current_opts_file, default_opts_file)
736 else:
737 print "Error: cannot find options file %s or %s" \
738 % (current_opts_file, default_opts_file)
739 Exit(1)
740
741 # Apply current option settings to env
742 sticky_opts.Update(env)
743 nonsticky_opts.Update(env)
744
745 help_text += "\nSticky options for %s:\n" % build_dir \
746 + sticky_opts.GenerateHelpText(env) \
747 + "\nNon-sticky options for %s:\n" % build_dir \
748 + nonsticky_opts.GenerateHelpText(env)
749
750 # Process option settings.
751
752 if not have_fenv and env['USE_FENV']:
753 print "Warning: <fenv.h> not available; " \
754 "forcing USE_FENV to False in", build_dir + "."
755 env['USE_FENV'] = False
756
757 if not env['USE_FENV']:
758 print "Warning: No IEEE FP rounding mode control in", build_dir + "."
759 print " FP results may deviate slightly from other platforms."
760
761 if env['EFENCE']:
762 env.Append(LIBS=['efence'])
763
764 if env['USE_MYSQL']:
765 if not have_mysql:
766 print "Warning: MySQL not available; " \
767 "forcing USE_MYSQL to False in", build_dir + "."
768 env['USE_MYSQL'] = False
769 else:
770 print "Compiling in", build_dir, "with MySQL support."
771 env.ParseConfig(mysql_config_libs)
772 env.ParseConfig(mysql_config_include)
773
774 # Save sticky option settings back to current options file
775 sticky_opts.Save(current_opts_file, env)
776
777 # Do this after we save setting back, or else we'll tack on an
778 # extra 'qdo' every time we run scons.
779 if env['BATCH']:
780 env['CC'] = env['BATCH_CMD'] + ' ' + env['CC']
781 env['CXX'] = env['BATCH_CMD'] + ' ' + env['CXX']
782
783 if env['USE_SSE2']:
784 env.Append(CCFLAGS='-msse2')
785
786 # The src/SConscript file sets up the build rules in 'env' according
787 # to the configured options. It returns a list of environments,
788 # one for each variant build (debug, opt, etc.)
789 envList = SConscript('src/SConscript', build_dir = build_path,
790 exports = 'env')
791
792 # Set up the regression tests for each build.
793 for e in envList:
794 SConscript('tests/SConscript',
795 build_dir = joinpath(build_path, 'tests', e.Label),
796 exports = { 'env' : e }, duplicate = False)
797
798 Help(help_text)
799
800
801 ###################################################
802 #
803 # Let SCons do its thing. At this point SCons will use the defined
804 # build environments to build the requested targets.
805 #
806 ###################################################
807