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
69 from os
.path
import join
as joinpath
71 # Check for recent-enough Python and SCons versions. If your system's
72 # default installation of Python is not recent enough, you can use a
73 # non-default installation of the Python interpreter by either (1)
74 # rearranging your PATH so that scons finds the non-default 'python'
75 # first or (2) explicitly invoking an alternative interpreter on the
76 # scons script, e.g., "/usr/local/bin/python2.4 `which scons` [args]".
77 EnsurePythonVersion(2,4)
79 # Ironically, SCons 0.96 dies if you give EnsureSconsVersion a
80 # 3-element version number.
81 min_scons_version
= (0,96,91)
83 EnsureSConsVersion(*min_scons_version
)
85 print "Error checking current SCons version."
86 print "SCons", ".".join(map(str,min_scons_version
)), "or greater required."
90 # The absolute path to the current directory (where this file lives).
91 ROOT
= Dir('.').abspath
93 # Path to the M5 source tree.
94 SRCDIR
= joinpath(ROOT
, 'src')
96 # tell python where to find m5 python code
97 sys
.path
.append(joinpath(ROOT
, 'src/python'))
99 ###################################################
101 # Figure out which configurations to set up based on the path(s) of
104 ###################################################
106 # Find default configuration & binary.
107 Default(os
.environ
.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
109 # helper function: find last occurrence of element in list
110 def rfind(l
, elt
, offs
= -1):
111 for i
in range(len(l
)+offs
, 0, -1):
114 raise ValueError, "element not found"
116 # helper function: compare dotted version numbers.
117 # E.g., compare_version('1.3.25', '1.4.1')
118 # returns -1, 0, 1 if v1 is <, ==, > v2
119 def compare_versions(v1
, v2
):
120 # Convert dotted strings to lists
121 v1
= map(int, v1
.split('.'))
122 v2
= map(int, v2
.split('.'))
123 # Compare corresponding elements of lists
124 for n1
,n2
in zip(v1
, v2
):
125 if n1
< n2
: return -1
127 # all corresponding values are equal... see if one has extra values
128 if len(v1
) < len(v2
): return -1
129 if len(v1
) > len(v2
): return 1
132 # Each target must have 'build' in the interior of the path; the
133 # directory below this will determine the build parameters. For
134 # example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
135 # recognize that ALPHA_SE specifies the configuration because it
136 # follow 'build' in the bulid path.
138 # Generate absolute paths to targets so we can see where the build dir is
139 if COMMAND_LINE_TARGETS
:
140 # Ask SCons which directory it was invoked from
141 launch_dir
= GetLaunchDir()
142 # Make targets relative to invocation directory
143 abs_targets
= map(lambda x
: os
.path
.normpath(joinpath(launch_dir
, str(x
))),
144 COMMAND_LINE_TARGETS
)
146 # Default targets are relative to root of tree
147 abs_targets
= map(lambda x
: os
.path
.normpath(joinpath(ROOT
, str(x
))),
151 # Generate a list of the unique build roots and configs that the
152 # collected targets reference.
155 for t
in abs_targets
:
156 path_dirs
= t
.split('/')
158 build_top
= rfind(path_dirs
, 'build', -2)
160 print "Error: no non-leaf 'build' dir found on target path", t
162 this_build_root
= joinpath('/',*path_dirs
[:build_top
+1])
164 build_root
= this_build_root
166 if this_build_root
!= build_root
:
167 print "Error: build targets not under same build root\n"\
168 " %s\n %s" % (build_root
, this_build_root
)
170 build_path
= joinpath('/',*path_dirs
[:build_top
+2])
171 if build_path
not in build_paths
:
172 build_paths
.append(build_path
)
174 ###################################################
176 # Set up the default build environment. This environment is copied
177 # and modified according to each selected configuration.
179 ###################################################
181 env
= Environment(ENV
= os
.environ
, # inherit user's environment vars
185 #Parse CC/CXX early so that we use the correct compiler for
186 # to test for dependencies/versions/libraries/includes
187 if ARGUMENTS
.get('CC', None):
188 env
['CC'] = ARGUMENTS
.get('CC')
190 if ARGUMENTS
.get('CXX', None):
191 env
['CXX'] = ARGUMENTS
.get('CXX')
193 env
.SConsignFile(joinpath(build_root
,"sconsign"))
195 # Default duplicate option is to use hard links, but this messes up
196 # when you use emacs to edit a file in the target dir, as emacs moves
197 # file to file~ then copies to file, breaking the link. Symbolic
198 # (soft) links work better.
199 env
.SetOption('duplicate', 'soft-copy')
201 # I waffle on this setting... it does avoid a few painful but
202 # unnecessary builds, but it also seems to make trivial builds take
205 env
.TargetSignatures('content')
207 # M5_PLY is used by isa_parser.py to find the PLY package.
208 env
.Append(ENV
= { 'M5_PLY' : Dir('ext/ply') })
210 # Set up default C++ compiler flags
211 env
.Append(CCFLAGS
='-pipe')
212 env
.Append(CCFLAGS
='-fno-strict-aliasing')
213 env
.Append(CCFLAGS
=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
214 if sys
.platform
== 'cygwin':
215 # cygwin has some header file issues...
216 env
.Append(CCFLAGS
=Split("-Wno-uninitialized"))
217 env
.Append(CPPPATH
=[Dir('ext/dnet')])
220 if not env
.has_key('SWIG'):
221 print 'Error: SWIG utility not found.'
222 print ' Please install (see http://www.swig.org) and retry.'
225 # Check for appropriate SWIG version
226 swig_version
= os
.popen('swig -version').read().split()
227 # First 3 words should be "SWIG Version x.y.z"
228 if swig_version
[0] != 'SWIG' or swig_version
[1] != 'Version':
229 print 'Error determining SWIG version.'
232 min_swig_version
= '1.3.28'
233 if compare_versions(swig_version
[2], min_swig_version
) < 0:
234 print 'Error: SWIG version', min_swig_version
, 'or newer required.'
235 print ' Installed version:', swig_version
[2]
238 # Set up SWIG flags & scanner
239 env
.Append(SWIGFLAGS
=Split('-c++ -python -modern $_CPPINCFLAGS'))
243 swig_inc_re
= '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
245 swig_scanner
= SCons
.Scanner
.ClassicCPP("SwigScan", ".i", "CPPPATH",
248 env
.Append(SCANNERS
= swig_scanner
)
250 # Platform-specific configuration. Note again that we assume that all
251 # builds under a given build root run on the same host platform.
252 conf
= Configure(env
,
253 conf_dir
= joinpath(build_root
, '.scons_config'),
254 log_file
= joinpath(build_root
, 'scons_config.log'))
256 # Find Python include and library directories for embedding the
257 # interpreter. For consistency, we will use the same Python
258 # installation used to run scons (and thus this script). If you want
259 # to link in an alternate version, see above for instructions on how
260 # to invoke scons with a different copy of the Python interpreter.
262 # Get brief Python version name (e.g., "python2.4") for locating
263 # include & library files
264 py_version_name
= 'python' + sys
.version
[:3]
266 # include path, e.g. /usr/local/include/python2.4
267 py_header_path
= joinpath(sys
.exec_prefix
, 'include', py_version_name
)
268 env
.Append(CPPPATH
= py_header_path
)
269 # verify that it works
270 if not conf
.CheckHeader('Python.h', '<>'):
271 print "Error: can't find Python.h header in", py_header_path
274 # add library path too if it's not in the default place
276 if sys
.exec_prefix
!= '/usr':
277 py_lib_path
= joinpath(sys
.exec_prefix
, 'lib')
278 elif sys
.platform
== 'cygwin':
279 # cygwin puts the .dll in /bin for some reason
282 env
.Append(LIBPATH
= py_lib_path
)
283 print 'Adding', py_lib_path
, 'to LIBPATH for', py_version_name
284 if not conf
.CheckLib(py_version_name
):
285 print "Error: can't find Python library", py_version_name
288 # On Solaris you need to use libsocket for socket ops
289 if not conf
.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
290 if not conf
.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
291 print "Can't find library with socket calls (e.g. accept())"
294 # Check for zlib. If the check passes, libz will be automatically
295 # added to the LIBS environment variable.
296 if not conf
.CheckLibWithHeader('z', 'zlib.h', 'C++'):
297 print 'Error: did not find needed zlib compression library '\
298 'and/or zlib.h header file.'
299 print ' Please install zlib and try again.'
302 # Check for <fenv.h> (C99 FP environment control)
303 have_fenv
= conf
.CheckHeader('fenv.h', '<>')
305 print "Warning: Header file <fenv.h> not found."
306 print " This host has no IEEE FP rounding mode control."
309 mysql_config
= WhereIs('mysql_config')
310 have_mysql
= mysql_config
!= None
312 # Check MySQL version.
314 mysql_version
= os
.popen(mysql_config
+ ' --version').read()
315 min_mysql_version
= '4.1'
316 if compare_versions(mysql_version
, min_mysql_version
) < 0:
317 print 'Warning: MySQL', min_mysql_version
, 'or newer required.'
318 print ' Version', mysql_version
, 'detected.'
321 # Set up mysql_config commands.
323 mysql_config_include
= mysql_config
+ ' --include'
324 if os
.system(mysql_config_include
+ ' > /dev/null') != 0:
325 # older mysql_config versions don't support --include, use
327 mysql_config_include
= mysql_config
+ ' --cflags | sed s/\\\'//g'
328 # This seems to work in all versions
329 mysql_config_libs
= mysql_config
+ ' --libs'
333 # Define the universe of supported ISAs
334 env
['ALL_ISA_LIST'] = ['alpha', 'sparc', 'mips']
336 # Define the universe of supported CPU models
337 env
['ALL_CPU_LIST'] = ['AtomicSimpleCPU', 'TimingSimpleCPU',
340 if os
.path
.isdir(joinpath(SRCDIR
, 'encumbered/cpu/full')):
341 env
['ALL_CPU_LIST'] += ['FullCPU']
343 # Sticky options get saved in the options file so they persist from
344 # one invocation to the next (unless overridden, in which case the new
345 # value becomes sticky).
346 sticky_opts
= Options(args
=ARGUMENTS
)
347 sticky_opts
.AddOptions(
348 EnumOption('TARGET_ISA', 'Target ISA', 'alpha', env
['ALL_ISA_LIST']),
349 BoolOption('FULL_SYSTEM', 'Full-system support', False),
350 # There's a bug in scons 0.96.1 that causes ListOptions with list
351 # values (more than one value) not to be able to be restored from
352 # a saved option file. If this causes trouble then upgrade to
353 # scons 0.96.90 or later.
354 ListOption('CPU_MODELS', 'CPU models', 'AtomicSimpleCPU,TimingSimpleCPU,O3CPU',
355 env
['ALL_CPU_LIST']),
356 BoolOption('ALPHA_TLASER',
357 'Model Alpha TurboLaser platform (vs. Tsunami)', False),
358 BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
359 BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
361 BoolOption('SS_COMPATIBLE_FP',
362 'Make floating-point results compatible with SimpleScalar',
364 BoolOption('USE_SSE2',
365 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
367 BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql
),
368 BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv
),
369 BoolOption('USE_CHECKER', 'Use checker for detailed CPU models', False),
370 ('CC', 'C compiler', os
.environ
.get('CC', env
['CC'])),
371 ('CXX', 'C++ compiler', os
.environ
.get('CXX', env
['CXX'])),
372 BoolOption('BATCH', 'Use batch pool for build and tests', False),
373 ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
375 'Override the default PYTHONHOME for this system (use with caution)',
376 '%s:%s' % (sys
.prefix
, sys
.exec_prefix
))
379 # Non-sticky options only apply to the current build.
380 nonsticky_opts
= Options(args
=ARGUMENTS
)
381 nonsticky_opts
.AddOptions(
382 BoolOption('update_ref', 'Update test reference outputs', False)
385 # These options get exported to #defines in config/*.hh (see src/SConscript).
386 env
.ExportOptions
= ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
387 'USE_MYSQL', 'NO_FAST_ALLOC', 'SS_COMPATIBLE_FP', \
388 'USE_CHECKER', 'PYTHONHOME', 'TARGET_ISA']
390 # Define a handy 'no-op' action
391 def no_action(target
, source
, env
):
394 env
.NoAction
= Action(no_action
, None)
396 ###################################################
398 # Define a SCons builder for configuration flag headers.
400 ###################################################
402 # This function generates a config header file that #defines the
403 # option symbol to the current option setting (0 or 1). The source
404 # operands are the name of the option and a Value node containing the
405 # value of the option.
406 def build_config_file(target
, source
, env
):
407 (option
, value
) = [s
.get_contents() for s
in source
]
408 f
= file(str(target
[0]), 'w')
409 print >> f
, '#define', option
, value
413 # Generate the message to be printed when building the config file.
414 def build_config_file_string(target
, source
, env
):
415 (option
, value
) = [s
.get_contents() for s
in source
]
416 return "Defining %s as %s in %s." % (option
, value
, target
[0])
418 # Combine the two functions into a scons Action object.
419 config_action
= Action(build_config_file
, build_config_file_string
)
421 # The emitter munges the source & target node lists to reflect what
422 # we're really doing.
423 def config_emitter(target
, source
, env
):
424 # extract option name from Builder arg
425 option
= str(target
[0])
426 # True target is config header file
427 target
= joinpath('config', option
.lower() + '.hh')
429 if isinstance(val
, bool):
432 elif isinstance(val
, str):
433 val
= '"' + val
+ '"'
435 # Sources are option name & value (packaged in SCons Value nodes)
436 return ([target
], [Value(option
), Value(val
)])
438 config_builder
= Builder(emitter
= config_emitter
, action
= config_action
)
440 env
.Append(BUILDERS
= { 'ConfigFile' : config_builder
})
442 ###################################################
444 # Define a SCons builder for copying files. This is used by the
445 # Python zipfile code in src/python/SConscript, but is placed up here
446 # since it's potentially more generally applicable.
448 ###################################################
450 copy_builder
= Builder(action
= Copy("$TARGET", "$SOURCE"))
452 env
.Append(BUILDERS
= { 'CopyFile' : copy_builder
})
454 ###################################################
456 # Define a simple SCons builder to concatenate files.
458 # Used to append the Python zip archive to the executable.
460 ###################################################
462 concat_builder
= Builder(action
= Action(['cat $SOURCES > $TARGET',
463 'chmod +x $TARGET']))
465 env
.Append(BUILDERS
= { 'Concat' : concat_builder
})
470 Usage: scons [scons options] [build options] [target(s)]
474 # libelf build is shared across all configs in the build root.
475 env
.SConscript('ext/libelf/SConscript',
476 build_dir
= joinpath(build_root
, 'libelf'),
479 ###################################################
481 # This function is used to set up a directory with switching headers
483 ###################################################
485 def make_switching_dir(dirname
, switch_headers
, env
):
486 # Generate the header. target[0] is the full path of the output
487 # header to generate. 'source' is a dummy variable, since we get the
488 # list of ISAs from env['ALL_ISA_LIST'].
489 def gen_switch_hdr(target
, source
, env
):
490 fname
= str(target
[0])
491 basename
= os
.path
.basename(fname
)
493 f
.write('#include "arch/isa_specific.hh"\n')
495 for isa
in env
['ALL_ISA_LIST']:
496 f
.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
497 % (cond
, isa
.upper(), dirname
, isa
, basename
))
499 f
.write('#else\n#error "THE_ISA not set"\n#endif\n')
503 # String to print when generating header
504 def gen_switch_hdr_string(target
, source
, env
):
505 return "Generating switch header " + str(target
[0])
507 # Build SCons Action object. 'varlist' specifies env vars that this
508 # action depends on; when env['ALL_ISA_LIST'] changes these actions
509 # should get re-executed.
510 switch_hdr_action
= Action(gen_switch_hdr
, gen_switch_hdr_string
,
511 varlist
=['ALL_ISA_LIST'])
513 # Instantiate actions for each header
514 for hdr
in switch_headers
:
515 env
.Command(hdr
, [], switch_hdr_action
)
517 env
.make_switching_dir
= make_switching_dir
519 ###################################################
521 # Define build environments for selected configurations.
523 ###################################################
528 for build_path
in build_paths
:
529 print "Building in", build_path
530 # build_dir is the tail component of build path, and is used to
531 # determine the build parameters (e.g., 'ALPHA_SE')
532 (build_root
, build_dir
) = os
.path
.split(build_path
)
533 # Make a copy of the build-root environment to use for this config.
534 env
= base_env
.Copy()
536 # Set env options according to the build directory config.
537 sticky_opts
.files
= []
538 # Options for $BUILD_ROOT/$BUILD_DIR are stored in
539 # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
540 # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
541 current_opts_file
= joinpath(build_root
, 'options', build_dir
)
542 if os
.path
.isfile(current_opts_file
):
543 sticky_opts
.files
.append(current_opts_file
)
544 print "Using saved options file %s" % current_opts_file
546 # Build dir-specific options file doesn't exist.
548 # Make sure the directory is there so we can create it later
549 opt_dir
= os
.path
.dirname(current_opts_file
)
550 if not os
.path
.isdir(opt_dir
):
553 # Get default build options from source tree. Options are
554 # normally determined by name of $BUILD_DIR, but can be
555 # overriden by 'default=' arg on command line.
556 default_opts_file
= joinpath('build_opts',
557 ARGUMENTS
.get('default', build_dir
))
558 if os
.path
.isfile(default_opts_file
):
559 sticky_opts
.files
.append(default_opts_file
)
560 print "Options file %s not found,\n using defaults in %s" \
561 % (current_opts_file
, default_opts_file
)
563 print "Error: cannot find options file %s or %s" \
564 % (current_opts_file
, default_opts_file
)
567 # Apply current option settings to env
568 sticky_opts
.Update(env
)
569 nonsticky_opts
.Update(env
)
571 help_text
+= "Sticky options for %s:\n" % build_dir \
572 + sticky_opts
.GenerateHelpText(env
) \
573 + "\nNon-sticky options for %s:\n" % build_dir \
574 + nonsticky_opts
.GenerateHelpText(env
)
576 # Process option settings.
578 if not have_fenv
and env
['USE_FENV']:
579 print "Warning: <fenv.h> not available; " \
580 "forcing USE_FENV to False in", build_dir
+ "."
581 env
['USE_FENV'] = False
583 if not env
['USE_FENV']:
584 print "Warning: No IEEE FP rounding mode control in", build_dir
+ "."
585 print " FP results may deviate slightly from other platforms."
588 env
.Append(LIBS
=['efence'])
592 print "Warning: MySQL not available; " \
593 "forcing USE_MYSQL to False in", build_dir
+ "."
594 env
['USE_MYSQL'] = False
596 print "Compiling in", build_dir
, "with MySQL support."
597 env
.ParseConfig(mysql_config_libs
)
598 env
.ParseConfig(mysql_config_include
)
600 # Save sticky option settings back to current options file
601 sticky_opts
.Save(current_opts_file
, env
)
603 # Do this after we save setting back, or else we'll tack on an
604 # extra 'qdo' every time we run scons.
606 env
['CC'] = env
['BATCH_CMD'] + ' ' + env
['CC']
607 env
['CXX'] = env
['BATCH_CMD'] + ' ' + env
['CXX']
610 env
.Append(CCFLAGS
='-msse2')
612 # The src/SConscript file sets up the build rules in 'env' according
613 # to the configured options. It returns a list of environments,
614 # one for each variant build (debug, opt, etc.)
615 envList
= SConscript('src/SConscript', build_dir
= build_path
,
618 # Set up the regression tests for each build.
620 SConscript('tests/SConscript',
621 build_dir
= joinpath(build_path
, 'tests', e
.Label
),
622 exports
= { 'env' : e
}, duplicate
= False)
627 ###################################################
629 # Let SCons do its thing. At this point SCons will use the defined
630 # build environments to build the requested targets.
632 ###################################################