SConstruct revision 2655
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###################################################
30#
31# SCons top-level build description (SConstruct) file.
32#
33# While in this directory ('m5'), just type 'scons' to build the default
34# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
35# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
36# the optimized full-system version).
37#
38# You can build M5 in a different directory as long as there is a
39# 'build/<CONFIG>' somewhere along the target path.  The build system
40# expdects that all configs under the same build directory are being
41# built for the same host system.
42#
43# Examples:
44#   These two commands are equivalent.  The '-u' option tells scons to
45#   search up the directory tree for this SConstruct file.
46#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
47#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
48#   These two commands are equivalent and demonstrate building in a
49#   directory outside of the source tree.  The '-C' option tells scons
50#   to chdir to the specified directory to find this SConstruct file.
51#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
52#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
53#
54# You can use 'scons -H' to print scons options.  If you're in this
55# 'm5' directory (or use -u or -C to tell scons where to find this
56# file), you can use 'scons -h' to print all the M5-specific build
57# options as well.
58#
59###################################################
60
61# Python library imports
62import sys
63import os
64
65# Check for recent-enough Python and SCons versions
66EnsurePythonVersion(2,3)
67
68# Ironically, SCons 0.96 dies if you give EnsureSconsVersion a
69# 3-element version number.
70min_scons_version = (0,96,91)
71try:
72    EnsureSConsVersion(*min_scons_version)
73except:
74    print "Error checking current SCons version."
75    print "SCons", ".".join(map(str,min_scons_version)), "or greater required."
76    Exit(2)
77    
78
79# The absolute path to the current directory (where this file lives).
80ROOT = Dir('.').abspath
81
82# Paths to the M5 and external source trees.
83SRCDIR = os.path.join(ROOT, 'src')
84
85# tell python where to find m5 python code
86sys.path.append(os.path.join(ROOT, 'src/python'))
87
88###################################################
89#
90# Figure out which configurations to set up based on the path(s) of
91# the target(s).
92#
93###################################################
94
95# Find default configuration & binary.
96Default(os.environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
97
98# Ask SCons which directory it was invoked from.
99launch_dir = GetLaunchDir()
100
101# Make targets relative to invocation directory
102abs_targets = map(lambda x: os.path.normpath(os.path.join(launch_dir, str(x))),
103                  BUILD_TARGETS)
104
105# helper function: find last occurrence of element in list
106def rfind(l, elt, offs = -1):
107    for i in range(len(l)+offs, 0, -1):
108        if l[i] == elt:
109            return i
110    raise ValueError, "element not found"
111
112# Each target must have 'build' in the interior of the path; the
113# directory below this will determine the build parameters.  For
114# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
115# recognize that ALPHA_SE specifies the configuration because it
116# follow 'build' in the bulid path.
117
118# Generate a list of the unique build roots and configs that the
119# collected targets reference.
120build_paths = []
121build_root = None
122for t in abs_targets:
123    path_dirs = t.split('/')
124    try:
125        build_top = rfind(path_dirs, 'build', -2)
126    except:
127        print "Error: no non-leaf 'build' dir found on target path", t
128        Exit(1)
129    this_build_root = os.path.join('/',*path_dirs[:build_top+1])
130    if not build_root:
131        build_root = this_build_root
132    else:
133        if this_build_root != build_root:
134            print "Error: build targets not under same build root\n"\
135                  "  %s\n  %s" % (build_root, this_build_root)
136            Exit(1)
137    build_path = os.path.join('/',*path_dirs[:build_top+2])
138    if build_path not in build_paths:
139        build_paths.append(build_path)
140
141###################################################
142#
143# Set up the default build environment.  This environment is copied
144# and modified according to each selected configuration.
145#
146###################################################
147
148env = Environment(ENV = os.environ,  # inherit user's environment vars
149                  ROOT = ROOT,
150                  SRCDIR = SRCDIR)
151
152env.SConsignFile("sconsign")
153
154# I waffle on this setting... it does avoid a few painful but
155# unnecessary builds, but it also seems to make trivial builds take
156# noticeably longer.
157if False:
158    env.TargetSignatures('content')
159
160# M5_PLY is used by isa_parser.py to find the PLY package.
161env.Append(ENV = { 'M5_PLY' : Dir('ext/ply') })
162
163# Set up default C++ compiler flags
164env.Append(CCFLAGS='-pipe')
165env.Append(CCFLAGS='-fno-strict-aliasing')
166env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
167if sys.platform == 'cygwin':
168    # cygwin has some header file issues...
169    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
170env.Append(CPPPATH=[Dir('ext/dnet')])
171
172# Environment args for linking in Python interpreter.
173# Should really have an option for setting the version instead of
174# having 2.4 hardwired in here...
175env.Append(CPPPATH='/usr/include/python2.4')
176env.Append(LIBS='python2.4')
177
178# Other default libraries
179env.Append(LIBS=['z'])
180
181# Platform-specific configuration.  Note again that we assume that all
182# builds under a given build root run on the same host platform.
183conf = Configure(env,
184                 conf_dir = os.path.join(build_root, '.scons_config'),
185                 log_file = os.path.join(build_root, 'scons_config.log'))
186
187# Check for <fenv.h> (C99 FP environment control)
188have_fenv = conf.CheckHeader('fenv.h', '<>')
189if not have_fenv:
190    print "Warning: Header file <fenv.h> not found."
191    print "         This host has no IEEE FP rounding mode control."
192
193# Check for mysql.
194mysql_config = WhereIs('mysql_config')
195have_mysql = mysql_config != None
196
197# Check MySQL version.
198if have_mysql:
199    mysql_version = os.popen(mysql_config + ' --version').read()
200    mysql_version = mysql_version.split('.')
201    mysql_major = int(mysql_version[0])
202    mysql_minor = int(mysql_version[1])
203    # This version check is probably overly conservative, but it deals
204    # with the versions we have installed.
205    if mysql_major < 4 or (mysql_major == 4 and mysql_minor < 1):
206        print "Warning: MySQL v4.1 or newer required."
207        have_mysql = False
208
209# Set up mysql_config commands.
210if have_mysql:
211    mysql_config_include = mysql_config + ' --include'
212    if os.system(mysql_config_include + ' > /dev/null') != 0:
213        # older mysql_config versions don't support --include, use
214        # --cflags instead
215        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
216    # This seems to work in all versions
217    mysql_config_libs = mysql_config + ' --libs'
218
219env = conf.Finish()
220
221# Define the universe of supported ISAs
222env['ALL_ISA_LIST'] = ['alpha', 'sparc', 'mips']
223
224# Define the universe of supported CPU models
225env['ALL_CPU_LIST'] = ['AtomicSimpleCPU', 'TimingSimpleCPU',
226                       'FullCPU', 'AlphaFullCPU']
227
228# Sticky options get saved in the options file so they persist from
229# one invocation to the next (unless overridden, in which case the new
230# value becomes sticky).
231sticky_opts = Options(args=ARGUMENTS)
232sticky_opts.AddOptions(
233    EnumOption('TARGET_ISA', 'Target ISA', 'alpha', env['ALL_ISA_LIST']),
234    BoolOption('FULL_SYSTEM', 'Full-system support', False),
235    # There's a bug in scons 0.96.1 that causes ListOptions with list
236    # values (more than one value) not to be able to be restored from
237    # a saved option file.  If this causes trouble then upgrade to
238    # scons 0.96.90 or later.
239    ListOption('CPU_MODELS', 'CPU models', 'AtomicSimpleCPU,TimingSimpleCPU',
240               env['ALL_CPU_LIST']),
241    BoolOption('ALPHA_TLASER',
242               'Model Alpha TurboLaser platform (vs. Tsunami)', False),
243    BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
244    BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
245               False),
246    BoolOption('SS_COMPATIBLE_FP',
247               'Make floating-point results compatible with SimpleScalar',
248               False),
249    BoolOption('USE_SSE2',
250               'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
251               False),
252    BoolOption('STATS_BINNING', 'Bin statistics by CPU mode', have_mysql),
253    BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
254    BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
255    ('CC', 'C compiler', os.environ.get('CC', env['CC'])),
256    ('CXX', 'C++ compiler', os.environ.get('CXX', env['CXX'])),
257    BoolOption('BATCH', 'Use batch pool for build and tests', False),
258    ('BATCH_CMD', 'Batch pool submission command name', 'qdo')
259    )
260
261# Non-sticky options only apply to the current build.
262nonsticky_opts = Options(args=ARGUMENTS)
263nonsticky_opts.AddOptions(
264    BoolOption('update_ref', 'Update test reference outputs', False)
265    )
266
267# These options get exported to #defines in config/*.hh (see m5/SConscript).
268env.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
269                     'USE_MYSQL', 'NO_FAST_ALLOC', 'SS_COMPATIBLE_FP', \
270                     'STATS_BINNING']
271
272# Define a handy 'no-op' action
273def no_action(target, source, env):
274    return 0
275
276env.NoAction = Action(no_action, None)
277
278###################################################
279#
280# Define a SCons builder for configuration flag headers.
281#
282###################################################
283
284# This function generates a config header file that #defines the
285# option symbol to the current option setting (0 or 1).  The source
286# operands are the name of the option and a Value node containing the
287# value of the option.
288def build_config_file(target, source, env):
289    (option, value) = [s.get_contents() for s in source]
290    f = file(str(target[0]), 'w')
291    print >> f, '#define', option, value
292    f.close()
293    return None
294
295# Generate the message to be printed when building the config file.
296def build_config_file_string(target, source, env):
297    (option, value) = [s.get_contents() for s in source]
298    return "Defining %s as %s in %s." % (option, value, target[0])
299
300# Combine the two functions into a scons Action object.
301config_action = Action(build_config_file, build_config_file_string)
302
303# The emitter munges the source & target node lists to reflect what
304# we're really doing.
305def config_emitter(target, source, env):
306    # extract option name from Builder arg
307    option = str(target[0])
308    # True target is config header file
309    target = os.path.join('config', option.lower() + '.hh')
310    # Force value to 0/1 even if it's a Python bool
311    val = int(eval(str(env[option])))
312    # Sources are option name & value (packaged in SCons Value nodes)
313    return ([target], [Value(option), Value(val)])
314
315config_builder = Builder(emitter = config_emitter, action = config_action)
316
317env.Append(BUILDERS = { 'ConfigFile' : config_builder })
318
319###################################################
320#
321# Define a SCons builder for copying files.  This is used by the
322# Python zipfile code in src/python/SConscript, but is placed up here
323# since it's potentially more generally applicable.
324#
325###################################################
326
327copy_builder = Builder(action = Copy("$TARGET", "$SOURCE"))
328
329env.Append(BUILDERS = { 'CopyFile' : copy_builder })
330
331###################################################
332#
333# Define a simple SCons builder to concatenate files.
334#
335# Used to append the Python zip archive to the executable.
336#
337###################################################
338
339concat_builder = Builder(action = Action(['cat $SOURCES > $TARGET',
340                                          'chmod +x $TARGET']))
341
342env.Append(BUILDERS = { 'Concat' : concat_builder })
343
344
345# base help text
346help_text = '''
347Usage: scons [scons options] [build options] [target(s)]
348
349'''
350
351# libelf build is shared across all configs in the build root.
352env.SConscript('ext/libelf/SConscript',
353               build_dir = os.path.join(build_root, 'libelf'),
354               exports = 'env')
355
356###################################################
357#
358# Define build environments for selected configurations.
359#
360###################################################
361
362# rename base env
363base_env = env
364
365for build_path in build_paths:
366    print "Building in", build_path
367    # build_dir is the tail component of build path, and is used to
368    # determine the build parameters (e.g., 'ALPHA_SE')
369    (build_root, build_dir) = os.path.split(build_path)
370    # Make a copy of the build-root environment to use for this config.
371    env = base_env.Copy()
372
373    # Set env options according to the build directory config.
374    sticky_opts.files = []
375    # Options for $BUILD_ROOT/$BUILD_DIR are stored in
376    # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
377    # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
378    current_opts_file = os.path.join(build_root, 'options', build_dir)
379    if os.path.isfile(current_opts_file):
380        sticky_opts.files.append(current_opts_file)
381        print "Using saved options file %s" % current_opts_file
382    else:
383        # Build dir-specific options file doesn't exist.
384
385        # Make sure the directory is there so we can create it later
386        opt_dir = os.path.dirname(current_opts_file)
387        if not os.path.isdir(opt_dir):
388            os.mkdir(opt_dir)
389
390        # Get default build options from source tree.  Options are
391        # normally determined by name of $BUILD_DIR, but can be
392        # overriden by 'default=' arg on command line.
393        default_opts_file = os.path.join('build_opts',
394                                         ARGUMENTS.get('default', build_dir))
395        if os.path.isfile(default_opts_file):
396            sticky_opts.files.append(default_opts_file)
397            print "Options file %s not found,\n  using defaults in %s" \
398                  % (current_opts_file, default_opts_file)
399        else:
400            print "Error: cannot find options file %s or %s" \
401                  % (current_opts_file, default_opts_file)
402            Exit(1)
403
404    # Apply current option settings to env
405    sticky_opts.Update(env)
406    nonsticky_opts.Update(env)
407
408    help_text += "Sticky options for %s:\n" % build_dir \
409                 + sticky_opts.GenerateHelpText(env) \
410                 + "\nNon-sticky options for %s:\n" % build_dir \
411                 + nonsticky_opts.GenerateHelpText(env)
412
413    # Process option settings.
414
415    if not have_fenv and env['USE_FENV']:
416        print "Warning: <fenv.h> not available; " \
417              "forcing USE_FENV to False in", build_dir + "."
418        env['USE_FENV'] = False
419
420    if not env['USE_FENV']:
421        print "Warning: No IEEE FP rounding mode control in", build_dir + "."
422        print "         FP results may deviate slightly from other platforms."
423
424    if env['EFENCE']:
425        env.Append(LIBS=['efence'])
426
427    if env['USE_MYSQL']:
428        if not have_mysql:
429            print "Warning: MySQL not available; " \
430                  "forcing USE_MYSQL to False in", build_dir + "."
431            env['USE_MYSQL'] = False
432        else:
433            print "Compiling in", build_dir, "with MySQL support."
434            env.ParseConfig(mysql_config_libs)
435            env.ParseConfig(mysql_config_include)
436
437    # Save sticky option settings back to current options file
438    sticky_opts.Save(current_opts_file, env)
439
440    # Do this after we save setting back, or else we'll tack on an
441    # extra 'qdo' every time we run scons.
442    if env['BATCH']:
443        env['CC']  = env['BATCH_CMD'] + ' ' + env['CC']
444        env['CXX'] = env['BATCH_CMD'] + ' ' + env['CXX']
445
446    if env['USE_SSE2']:
447        env.Append(CCFLAGS='-msse2')
448
449    # The m5/SConscript file sets up the build rules in 'env' according
450    # to the configured options.  It returns a list of environments,
451    # one for each variant build (debug, opt, etc.)
452    envList = SConscript('src/SConscript', build_dir = build_path,
453                         exports = 'env', duplicate = False)
454
455    # Set up the regression tests for each build.
456#    for e in envList:
457#        SConscript('m5-test/SConscript',
458#                   build_dir = os.path.join(build_dir, 'test', e.Label),
459#                   exports = { 'env' : e }, duplicate = False)
460
461Help(help_text)
462
463###################################################
464#
465# Let SCons do its thing.  At this point SCons will use the defined
466# build environments to build the requested targets.
467#
468###################################################
469
470