SConstruct revision 2653
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# Default libraries
173env.Append(LIBS=['z'])
174
175# Platform-specific configuration.  Note again that we assume that all
176# builds under a given build root run on the same host platform.
177conf = Configure(env,
178                 conf_dir = os.path.join(build_root, '.scons_config'),
179                 log_file = os.path.join(build_root, 'scons_config.log'))
180
181# Check for <fenv.h> (C99 FP environment control)
182have_fenv = conf.CheckHeader('fenv.h', '<>')
183if not have_fenv:
184    print "Warning: Header file <fenv.h> not found."
185    print "         This host has no IEEE FP rounding mode control."
186
187# Check for mysql.
188mysql_config = WhereIs('mysql_config')
189have_mysql = mysql_config != None
190
191# Check MySQL version.
192if have_mysql:
193    mysql_version = os.popen(mysql_config + ' --version').read()
194    mysql_version = mysql_version.split('.')
195    mysql_major = int(mysql_version[0])
196    mysql_minor = int(mysql_version[1])
197    # This version check is probably overly conservative, but it deals
198    # with the versions we have installed.
199    if mysql_major < 4 or (mysql_major == 4 and mysql_minor < 1):
200        print "Warning: MySQL v4.1 or newer required."
201        have_mysql = False
202
203# Set up mysql_config commands.
204if have_mysql:
205    mysql_config_include = mysql_config + ' --include'
206    if os.system(mysql_config_include + ' > /dev/null') != 0:
207        # older mysql_config versions don't support --include, use
208        # --cflags instead
209        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
210    # This seems to work in all versions
211    mysql_config_libs = mysql_config + ' --libs'
212
213env = conf.Finish()
214
215# Define the universe of supported ISAs
216env['ALL_ISA_LIST'] = ['alpha', 'sparc', 'mips']
217
218# Define the universe of supported CPU models
219env['ALL_CPU_LIST'] = ['AtomicSimpleCPU', 'TimingSimpleCPU',
220                       'FullCPU', 'AlphaFullCPU']
221
222# Sticky options get saved in the options file so they persist from
223# one invocation to the next (unless overridden, in which case the new
224# value becomes sticky).
225sticky_opts = Options(args=ARGUMENTS)
226sticky_opts.AddOptions(
227    EnumOption('TARGET_ISA', 'Target ISA', 'alpha', env['ALL_ISA_LIST']),
228    BoolOption('FULL_SYSTEM', 'Full-system support', False),
229    # There's a bug in scons 0.96.1 that causes ListOptions with list
230    # values (more than one value) not to be able to be restored from
231    # a saved option file.  If this causes trouble then upgrade to
232    # scons 0.96.90 or later.
233    ListOption('CPU_MODELS', 'CPU models', 'AtomicSimpleCPU,TimingSimpleCPU',
234               env['ALL_CPU_LIST']),
235    BoolOption('ALPHA_TLASER',
236               'Model Alpha TurboLaser platform (vs. Tsunami)', False),
237    BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
238    BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
239               False),
240    BoolOption('SS_COMPATIBLE_FP',
241               'Make floating-point results compatible with SimpleScalar',
242               False),
243    BoolOption('USE_SSE2',
244               'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
245               False),
246    BoolOption('STATS_BINNING', 'Bin statistics by CPU mode', have_mysql),
247    BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
248    BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
249    ('CC', 'C compiler', os.environ.get('CC', env['CC'])),
250    ('CXX', 'C++ compiler', os.environ.get('CXX', env['CXX'])),
251    BoolOption('BATCH', 'Use batch pool for build and tests', False),
252    ('BATCH_CMD', 'Batch pool submission command name', 'qdo')
253    )
254
255# Non-sticky options only apply to the current build.
256nonsticky_opts = Options(args=ARGUMENTS)
257nonsticky_opts.AddOptions(
258    BoolOption('update_ref', 'Update test reference outputs', False)
259    )
260
261# These options get exported to #defines in config/*.hh (see m5/SConscript).
262env.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
263                     'USE_MYSQL', 'NO_FAST_ALLOC', 'SS_COMPATIBLE_FP', \
264                     'STATS_BINNING']
265
266# Define a handy 'no-op' action
267def no_action(target, source, env):
268    return 0
269
270env.NoAction = Action(no_action, None)
271
272###################################################
273#
274# Define a SCons builder for configuration flag headers.
275#
276###################################################
277
278# This function generates a config header file that #defines the
279# option symbol to the current option setting (0 or 1).  The source
280# operands are the name of the option and a Value node containing the
281# value of the option.
282def build_config_file(target, source, env):
283    (option, value) = [s.get_contents() for s in source]
284    f = file(str(target[0]), 'w')
285    print >> f, '#define', option, value
286    f.close()
287    return None
288
289# Generate the message to be printed when building the config file.
290def build_config_file_string(target, source, env):
291    (option, value) = [s.get_contents() for s in source]
292    return "Defining %s as %s in %s." % (option, value, target[0])
293
294# Combine the two functions into a scons Action object.
295config_action = Action(build_config_file, build_config_file_string)
296
297# The emitter munges the source & target node lists to reflect what
298# we're really doing.
299def config_emitter(target, source, env):
300    # extract option name from Builder arg
301    option = str(target[0])
302    # True target is config header file
303    target = os.path.join('config', option.lower() + '.hh')
304    # Force value to 0/1 even if it's a Python bool
305    val = int(eval(str(env[option])))
306    # Sources are option name & value (packaged in SCons Value nodes)
307    return ([target], [Value(option), Value(val)])
308
309config_builder = Builder(emitter = config_emitter, action = config_action)
310
311env.Append(BUILDERS = { 'ConfigFile' : config_builder })
312
313# base help text
314help_text = '''
315Usage: scons [scons options] [build options] [target(s)]
316
317'''
318
319# libelf build is shared across all configs in the build root.
320env.SConscript('ext/libelf/SConscript',
321               build_dir = os.path.join(build_root, 'libelf'),
322               exports = 'env')
323
324###################################################
325#
326# Define build environments for selected configurations.
327#
328###################################################
329
330# rename base env
331base_env = env
332
333for build_path in build_paths:
334    print "Building in", build_path
335    # build_dir is the tail component of build path, and is used to
336    # determine the build parameters (e.g., 'ALPHA_SE')
337    (build_root, build_dir) = os.path.split(build_path)
338    # Make a copy of the build-root environment to use for this config.
339    env = base_env.Copy()
340
341    # Set env options according to the build directory config.
342    sticky_opts.files = []
343    # Options for $BUILD_ROOT/$BUILD_DIR are stored in
344    # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
345    # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
346    current_opts_file = os.path.join(build_root, 'options', build_dir)
347    if os.path.isfile(current_opts_file):
348        sticky_opts.files.append(current_opts_file)
349        print "Using saved options file %s" % current_opts_file
350    else:
351        # Build dir-specific options file doesn't exist.
352
353        # Make sure the directory is there so we can create it later
354        opt_dir = os.path.dirname(current_opts_file)
355        if not os.path.isdir(opt_dir):
356            os.mkdir(opt_dir)
357
358        # Get default build options from source tree.  Options are
359        # normally determined by name of $BUILD_DIR, but can be
360        # overriden by 'default=' arg on command line.
361        default_opts_file = os.path.join('build_opts',
362                                         ARGUMENTS.get('default', build_dir))
363        if os.path.isfile(default_opts_file):
364            sticky_opts.files.append(default_opts_file)
365            print "Options file %s not found,\n  using defaults in %s" \
366                  % (current_opts_file, default_opts_file)
367        else:
368            print "Error: cannot find options file %s or %s" \
369                  % (current_opts_file, default_opts_file)
370            Exit(1)
371
372    # Apply current option settings to env
373    sticky_opts.Update(env)
374    nonsticky_opts.Update(env)
375
376    help_text += "Sticky options for %s:\n" % build_dir \
377                 + sticky_opts.GenerateHelpText(env) \
378                 + "\nNon-sticky options for %s:\n" % build_dir \
379                 + nonsticky_opts.GenerateHelpText(env)
380
381    # Process option settings.
382
383    if not have_fenv and env['USE_FENV']:
384        print "Warning: <fenv.h> not available; " \
385              "forcing USE_FENV to False in", build_dir + "."
386        env['USE_FENV'] = False
387
388    if not env['USE_FENV']:
389        print "Warning: No IEEE FP rounding mode control in", build_dir + "."
390        print "         FP results may deviate slightly from other platforms."
391
392    if env['EFENCE']:
393        env.Append(LIBS=['efence'])
394
395    if env['USE_MYSQL']:
396        if not have_mysql:
397            print "Warning: MySQL not available; " \
398                  "forcing USE_MYSQL to False in", build_dir + "."
399            env['USE_MYSQL'] = False
400        else:
401            print "Compiling in", build_dir, "with MySQL support."
402            env.ParseConfig(mysql_config_libs)
403            env.ParseConfig(mysql_config_include)
404
405    # Save sticky option settings back to current options file
406    sticky_opts.Save(current_opts_file, env)
407
408    # Do this after we save setting back, or else we'll tack on an
409    # extra 'qdo' every time we run scons.
410    if env['BATCH']:
411        env['CC']  = env['BATCH_CMD'] + ' ' + env['CC']
412        env['CXX'] = env['BATCH_CMD'] + ' ' + env['CXX']
413
414    if env['USE_SSE2']:
415        env.Append(CCFLAGS='-msse2')
416
417    # The m5/SConscript file sets up the build rules in 'env' according
418    # to the configured options.  It returns a list of environments,
419    # one for each variant build (debug, opt, etc.)
420    envList = SConscript('src/SConscript', build_dir = build_path,
421                         exports = 'env', duplicate = False)
422
423    # Set up the regression tests for each build.
424#    for e in envList:
425#        SConscript('m5-test/SConscript',
426#                   build_dir = os.path.join(build_dir, 'test', e.Label),
427#                   exports = { 'env' : e }, duplicate = False)
428
429Help(help_text)
430
431###################################################
432#
433# Let SCons do its thing.  At this point SCons will use the defined
434# build environments to build the requested targets.
435#
436###################################################
437
438