3 # Copyright (c) 2004-2005 The Regents of The University of Michigan
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.
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.
29 # Authors: Steve Reinhardt
31 ###################################################
33 # SCons top-level build description (SConstruct) file.
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).
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.
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
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
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
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
64 ###################################################
66 # Python library imports
70 # Check for recent-enough Python and SCons versions. If your system's
71 # default installation of Python is not recent enough, you can use a
72 # non-default installation of the Python interpreter by either (1)
73 # rearranging your PATH so that scons finds the non-default 'python'
74 # first or (2) explicitly invoking an alternative interpreter on the
75 # scons script, e.g., "/usr/local/bin/python2.4 `which scons` [args]".
76 EnsurePythonVersion(2,4)
78 # Ironically, SCons 0.96 dies if you give EnsureSconsVersion a
79 # 3-element version number.
80 min_scons_version
= (0,96,91)
82 EnsureSConsVersion(*min_scons_version
)
84 print "Error checking current SCons version."
85 print "SCons", ".".join(map(str,min_scons_version
)), "or greater required."
89 # The absolute path to the current directory (where this file lives).
90 ROOT
= Dir('.').abspath
92 # Paths to the M5 and external source trees.
93 SRCDIR
= os
.path
.join(ROOT
, 'src')
95 # tell python where to find m5 python code
96 sys
.path
.append(os
.path
.join(ROOT
, 'src/python'))
98 ###################################################
100 # Figure out which configurations to set up based on the path(s) of
103 ###################################################
105 # Find default configuration & binary.
106 Default(os
.environ
.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
108 # Ask SCons which directory it was invoked from.
109 launch_dir
= GetLaunchDir()
111 # Make targets relative to invocation directory
112 abs_targets
= map(lambda x
: os
.path
.normpath(os
.path
.join(launch_dir
, str(x
))),
115 # helper function: find last occurrence of element in list
116 def rfind(l
, elt
, offs
= -1):
117 for i
in range(len(l
)+offs
, 0, -1):
120 raise ValueError, "element not found"
122 # helper function: compare dotted version numbers.
123 # E.g., compare_version('1.3.25', '1.4.1')
124 # returns -1, 0, 1 if v1 is <, ==, > v2
125 def compare_versions(v1
, v2
):
126 # Convert dotted strings to lists
127 v1
= map(int, v1
.split('.'))
128 v2
= map(int, v2
.split('.'))
129 # Compare corresponding elements of lists
130 for n1
,n2
in zip(v1
, v2
):
131 if n1
< n2
: return -1
133 # all corresponding values are equal... see if one has extra values
134 if len(v1
) < len(v2
): return -1
135 if len(v1
) > len(v2
): return 1
138 # Each target must have 'build' in the interior of the path; the
139 # directory below this will determine the build parameters. For
140 # example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
141 # recognize that ALPHA_SE specifies the configuration because it
142 # follow 'build' in the bulid path.
144 # Generate a list of the unique build roots and configs that the
145 # collected targets reference.
148 for t
in abs_targets
:
149 path_dirs
= t
.split('/')
151 build_top
= rfind(path_dirs
, 'build', -2)
153 print "Error: no non-leaf 'build' dir found on target path", t
155 this_build_root
= os
.path
.join('/',*path_dirs
[:build_top
+1])
157 build_root
= this_build_root
159 if this_build_root
!= build_root
:
160 print "Error: build targets not under same build root\n"\
161 " %s\n %s" % (build_root
, this_build_root
)
163 build_path
= os
.path
.join('/',*path_dirs
[:build_top
+2])
164 if build_path
not in build_paths
:
165 build_paths
.append(build_path
)
167 ###################################################
169 # Set up the default build environment. This environment is copied
170 # and modified according to each selected configuration.
172 ###################################################
174 env
= Environment(ENV
= os
.environ
, # inherit user's environment vars
178 #Parse CC/CXX early so that we use the correct compiler for
179 # to test for dependencies/versions/libraries/includes
180 if ARGUMENTS
.get('CC', None):
181 env
['CC'] = ARGUMENTS
.get('CC')
183 if ARGUMENTS
.get('CXX', None):
184 env
['CXX'] = ARGUMENTS
.get('CXX')
186 env
.SConsignFile(os
.path
.join(build_root
,"sconsign"))
188 # Default duplicate option is to use hard links, but this messes up
189 # when you use emacs to edit a file in the target dir, as emacs moves
190 # file to file~ then copies to file, breaking the link. Symbolic
191 # (soft) links work better.
192 env
.SetOption('duplicate', 'soft-copy')
194 # I waffle on this setting... it does avoid a few painful but
195 # unnecessary builds, but it also seems to make trivial builds take
198 env
.TargetSignatures('content')
200 # M5_PLY is used by isa_parser.py to find the PLY package.
201 env
.Append(ENV
= { 'M5_PLY' : Dir('ext/ply') })
203 # Set up default C++ compiler flags
204 env
.Append(CCFLAGS
='-pipe')
205 env
.Append(CCFLAGS
='-fno-strict-aliasing')
206 env
.Append(CCFLAGS
=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
207 if sys
.platform
== 'cygwin':
208 # cygwin has some header file issues...
209 env
.Append(CCFLAGS
=Split("-Wno-uninitialized"))
210 env
.Append(CPPPATH
=[Dir('ext/dnet')])
213 if not env
.has_key('SWIG'):
214 print 'Error: SWIG utility not found.'
215 print ' Please install (see http://www.swig.org) and retry.'
218 # Check for appropriate SWIG version
219 swig_version
= os
.popen('swig -version').read().split()
220 # First 3 words should be "SWIG Version x.y.z"
221 if swig_version
[0] != 'SWIG' or swig_version
[1] != 'Version':
222 print 'Error determining SWIG version.'
225 min_swig_version
= '1.3.28'
226 if compare_versions(swig_version
[2], min_swig_version
) < 0:
227 print 'Error: SWIG version', min_swig_version
, 'or newer required.'
228 print ' Installed version:', swig_version
[2]
231 # Set up SWIG flags & scanner
232 env
.Append(SWIGFLAGS
=Split('-c++ -python -modern $_CPPINCFLAGS'))
236 swig_inc_re
= '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
238 swig_scanner
= SCons
.Scanner
.ClassicCPP("SwigScan", ".i", "CPPPATH",
241 env
.Append(SCANNERS
= swig_scanner
)
243 # Platform-specific configuration. Note again that we assume that all
244 # builds under a given build root run on the same host platform.
245 conf
= Configure(env
,
246 conf_dir
= os
.path
.join(build_root
, '.scons_config'),
247 log_file
= os
.path
.join(build_root
, 'scons_config.log'))
249 # Find Python include and library directories for embedding the
250 # interpreter. For consistency, we will use the same Python
251 # installation used to run scons (and thus this script). If you want
252 # to link in an alternate version, see above for instructions on how
253 # to invoke scons with a different copy of the Python interpreter.
255 # Get brief Python version name (e.g., "python2.4") for locating
256 # include & library files
257 py_version_name
= 'python' + sys
.version
[:3]
259 # include path, e.g. /usr/local/include/python2.4
260 py_header_path
= os
.path
.join(sys
.exec_prefix
, 'include', py_version_name
)
261 env
.Append(CPPPATH
= py_header_path
)
262 # verify that it works
263 if not conf
.CheckHeader('Python.h', '<>'):
264 print "Error: can't find Python.h header in", py_header_path
267 # add library path too if it's not in the default place
269 if sys
.exec_prefix
!= '/usr':
270 py_lib_path
= os
.path
.join(sys
.exec_prefix
, 'lib')
271 elif sys
.platform
== 'cygwin':
272 # cygwin puts the .dll in /bin for some reason
275 env
.Append(LIBPATH
= py_lib_path
)
276 print 'Adding', py_lib_path
, 'to LIBPATH for', py_version_name
277 if not conf
.CheckLib(py_version_name
):
278 print "Error: can't find Python library", py_version_name
281 # On Solaris you need to use libsocket for socket ops
282 if not conf
.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
283 if not conf
.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
284 print "Can't find library with socket calls (e.g. accept())"
287 # Check for zlib. If the check passes, libz will be automatically
288 # added to the LIBS environment variable.
289 if not conf
.CheckLibWithHeader('z', 'zlib.h', 'C++'):
290 print 'Error: did not find needed zlib compression library '\
291 'and/or zlib.h header file.'
292 print ' Please install zlib and try again.'
295 # Check for <fenv.h> (C99 FP environment control)
296 have_fenv
= conf
.CheckHeader('fenv.h', '<>')
298 print "Warning: Header file <fenv.h> not found."
299 print " This host has no IEEE FP rounding mode control."
302 mysql_config
= WhereIs('mysql_config')
303 have_mysql
= mysql_config
!= None
305 # Check MySQL version.
307 mysql_version
= os
.popen(mysql_config
+ ' --version').read()
308 min_mysql_version
= '4.1'
309 if compare_versions(mysql_version
, min_mysql_version
) < 0:
310 print 'Warning: MySQL', min_mysql_version
, 'or newer required.'
311 print ' Version', mysql_version
, 'detected.'
314 # Set up mysql_config commands.
316 mysql_config_include
= mysql_config
+ ' --include'
317 if os
.system(mysql_config_include
+ ' > /dev/null') != 0:
318 # older mysql_config versions don't support --include, use
320 mysql_config_include
= mysql_config
+ ' --cflags | sed s/\\\'//g'
321 # This seems to work in all versions
322 mysql_config_libs
= mysql_config
+ ' --libs'
326 # Define the universe of supported ISAs
327 env
['ALL_ISA_LIST'] = ['alpha', 'sparc', 'mips']
329 # Define the universe of supported CPU models
330 env
['ALL_CPU_LIST'] = ['AtomicSimpleCPU', 'TimingSimpleCPU',
333 if os
.path
.isdir(os
.path
.join(SRCDIR
, 'src/encumbered/cpu/full')):
334 env
['ALL_CPU_LIST'] += ['FullCPU']
336 # Sticky options get saved in the options file so they persist from
337 # one invocation to the next (unless overridden, in which case the new
338 # value becomes sticky).
339 sticky_opts
= Options(args
=ARGUMENTS
)
340 sticky_opts
.AddOptions(
341 EnumOption('TARGET_ISA', 'Target ISA', 'alpha', env
['ALL_ISA_LIST']),
342 BoolOption('FULL_SYSTEM', 'Full-system support', False),
343 # There's a bug in scons 0.96.1 that causes ListOptions with list
344 # values (more than one value) not to be able to be restored from
345 # a saved option file. If this causes trouble then upgrade to
346 # scons 0.96.90 or later.
347 ListOption('CPU_MODELS', 'CPU models', 'AtomicSimpleCPU,TimingSimpleCPU,O3CPU',
348 env
['ALL_CPU_LIST']),
349 BoolOption('ALPHA_TLASER',
350 'Model Alpha TurboLaser platform (vs. Tsunami)', False),
351 BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
352 BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
354 BoolOption('SS_COMPATIBLE_FP',
355 'Make floating-point results compatible with SimpleScalar',
357 BoolOption('USE_SSE2',
358 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
360 BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql
),
361 BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv
),
362 BoolOption('USE_CHECKER', 'Use checker for detailed CPU models', False),
363 ('CC', 'C compiler', os
.environ
.get('CC', env
['CC'])),
364 ('CXX', 'C++ compiler', os
.environ
.get('CXX', env
['CXX'])),
365 BoolOption('BATCH', 'Use batch pool for build and tests', False),
366 ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
368 'Override the default PYTHONHOME for this system (use with caution)',
369 '%s:%s' % (sys
.prefix
, sys
.exec_prefix
))
372 # Non-sticky options only apply to the current build.
373 nonsticky_opts
= Options(args
=ARGUMENTS
)
374 nonsticky_opts
.AddOptions(
375 BoolOption('update_ref', 'Update test reference outputs', False)
378 # These options get exported to #defines in config/*.hh (see src/SConscript).
379 env
.ExportOptions
= ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
380 'USE_MYSQL', 'NO_FAST_ALLOC', 'SS_COMPATIBLE_FP', \
381 'USE_CHECKER', 'PYTHONHOME', 'TARGET_ISA']
383 # Define a handy 'no-op' action
384 def no_action(target
, source
, env
):
387 env
.NoAction
= Action(no_action
, None)
389 ###################################################
391 # Define a SCons builder for configuration flag headers.
393 ###################################################
395 # This function generates a config header file that #defines the
396 # option symbol to the current option setting (0 or 1). The source
397 # operands are the name of the option and a Value node containing the
398 # value of the option.
399 def build_config_file(target
, source
, env
):
400 (option
, value
) = [s
.get_contents() for s
in source
]
401 f
= file(str(target
[0]), 'w')
402 print >> f
, '#define', option
, value
406 # Generate the message to be printed when building the config file.
407 def build_config_file_string(target
, source
, env
):
408 (option
, value
) = [s
.get_contents() for s
in source
]
409 return "Defining %s as %s in %s." % (option
, value
, target
[0])
411 # Combine the two functions into a scons Action object.
412 config_action
= Action(build_config_file
, build_config_file_string
)
414 # The emitter munges the source & target node lists to reflect what
415 # we're really doing.
416 def config_emitter(target
, source
, env
):
417 # extract option name from Builder arg
418 option
= str(target
[0])
419 # True target is config header file
420 target
= os
.path
.join('config', option
.lower() + '.hh')
422 if isinstance(val
, bool):
425 elif isinstance(val
, str):
426 val
= '"' + val
+ '"'
428 # Sources are option name & value (packaged in SCons Value nodes)
429 return ([target
], [Value(option
), Value(val
)])
431 config_builder
= Builder(emitter
= config_emitter
, action
= config_action
)
433 env
.Append(BUILDERS
= { 'ConfigFile' : config_builder
})
435 ###################################################
437 # Define a SCons builder for copying files. This is used by the
438 # Python zipfile code in src/python/SConscript, but is placed up here
439 # since it's potentially more generally applicable.
441 ###################################################
443 copy_builder
= Builder(action
= Copy("$TARGET", "$SOURCE"))
445 env
.Append(BUILDERS
= { 'CopyFile' : copy_builder
})
447 ###################################################
449 # Define a simple SCons builder to concatenate files.
451 # Used to append the Python zip archive to the executable.
453 ###################################################
455 concat_builder
= Builder(action
= Action(['cat $SOURCES > $TARGET',
456 'chmod +x $TARGET']))
458 env
.Append(BUILDERS
= { 'Concat' : concat_builder
})
463 Usage: scons [scons options] [build options] [target(s)]
467 # libelf build is shared across all configs in the build root.
468 env
.SConscript('ext/libelf/SConscript',
469 build_dir
= os
.path
.join(build_root
, 'libelf'),
472 ###################################################
474 # This function is used to set up a directory with switching headers
476 ###################################################
478 def make_switching_dir(dirname
, switch_headers
, env
):
479 # Generate the header. target[0] is the full path of the output
480 # header to generate. 'source' is a dummy variable, since we get the
481 # list of ISAs from env['ALL_ISA_LIST'].
482 def gen_switch_hdr(target
, source
, env
):
483 fname
= str(target
[0])
484 basename
= os
.path
.basename(fname
)
486 f
.write('#include "arch/isa_specific.hh"\n')
488 for isa
in env
['ALL_ISA_LIST']:
489 f
.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
490 % (cond
, isa
.upper(), dirname
, isa
, basename
))
492 f
.write('#else\n#error "THE_ISA not set"\n#endif\n')
496 # String to print when generating header
497 def gen_switch_hdr_string(target
, source
, env
):
498 return "Generating switch header " + str(target
[0])
500 # Build SCons Action object. 'varlist' specifies env vars that this
501 # action depends on; when env['ALL_ISA_LIST'] changes these actions
502 # should get re-executed.
503 switch_hdr_action
= Action(gen_switch_hdr
, gen_switch_hdr_string
,
504 varlist
=['ALL_ISA_LIST'])
506 # Instantiate actions for each header
507 for hdr
in switch_headers
:
508 env
.Command(hdr
, [], switch_hdr_action
)
510 env
.make_switching_dir
= make_switching_dir
512 ###################################################
514 # Define build environments for selected configurations.
516 ###################################################
521 for build_path
in build_paths
:
522 print "Building in", build_path
523 # build_dir is the tail component of build path, and is used to
524 # determine the build parameters (e.g., 'ALPHA_SE')
525 (build_root
, build_dir
) = os
.path
.split(build_path
)
526 # Make a copy of the build-root environment to use for this config.
527 env
= base_env
.Copy()
529 # Set env options according to the build directory config.
530 sticky_opts
.files
= []
531 # Options for $BUILD_ROOT/$BUILD_DIR are stored in
532 # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
533 # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
534 current_opts_file
= os
.path
.join(build_root
, 'options', build_dir
)
535 if os
.path
.isfile(current_opts_file
):
536 sticky_opts
.files
.append(current_opts_file
)
537 print "Using saved options file %s" % current_opts_file
539 # Build dir-specific options file doesn't exist.
541 # Make sure the directory is there so we can create it later
542 opt_dir
= os
.path
.dirname(current_opts_file
)
543 if not os
.path
.isdir(opt_dir
):
546 # Get default build options from source tree. Options are
547 # normally determined by name of $BUILD_DIR, but can be
548 # overriden by 'default=' arg on command line.
549 default_opts_file
= os
.path
.join('build_opts',
550 ARGUMENTS
.get('default', build_dir
))
551 if os
.path
.isfile(default_opts_file
):
552 sticky_opts
.files
.append(default_opts_file
)
553 print "Options file %s not found,\n using defaults in %s" \
554 % (current_opts_file
, default_opts_file
)
556 print "Error: cannot find options file %s or %s" \
557 % (current_opts_file
, default_opts_file
)
560 # Apply current option settings to env
561 sticky_opts
.Update(env
)
562 nonsticky_opts
.Update(env
)
564 help_text
+= "Sticky options for %s:\n" % build_dir \
565 + sticky_opts
.GenerateHelpText(env
) \
566 + "\nNon-sticky options for %s:\n" % build_dir \
567 + nonsticky_opts
.GenerateHelpText(env
)
569 # Process option settings.
571 if not have_fenv
and env
['USE_FENV']:
572 print "Warning: <fenv.h> not available; " \
573 "forcing USE_FENV to False in", build_dir
+ "."
574 env
['USE_FENV'] = False
576 if not env
['USE_FENV']:
577 print "Warning: No IEEE FP rounding mode control in", build_dir
+ "."
578 print " FP results may deviate slightly from other platforms."
581 env
.Append(LIBS
=['efence'])
585 print "Warning: MySQL not available; " \
586 "forcing USE_MYSQL to False in", build_dir
+ "."
587 env
['USE_MYSQL'] = False
589 print "Compiling in", build_dir
, "with MySQL support."
590 env
.ParseConfig(mysql_config_libs
)
591 env
.ParseConfig(mysql_config_include
)
593 # Save sticky option settings back to current options file
594 sticky_opts
.Save(current_opts_file
, env
)
596 # Do this after we save setting back, or else we'll tack on an
597 # extra 'qdo' every time we run scons.
599 env
['CC'] = env
['BATCH_CMD'] + ' ' + env
['CC']
600 env
['CXX'] = env
['BATCH_CMD'] + ' ' + env
['CXX']
603 env
.Append(CCFLAGS
='-msse2')
605 # The src/SConscript file sets up the build rules in 'env' according
606 # to the configured options. It returns a list of environments,
607 # one for each variant build (debug, opt, etc.)
608 envList
= SConscript('src/SConscript', build_dir
= build_path
,
611 # Set up the regression tests for each build.
613 SConscript('tests/SConscript',
614 build_dir
= os
.path
.join(build_path
, 'tests', e
.Label
),
615 exports
= { 'env' : e
}, duplicate
= False)
620 ###################################################
622 # Let SCons do its thing. At this point SCons will use the defined
623 # build environments to build the requested targets.
625 ###################################################