SConstruct revision 12563:8d59ed22ae79
111103Snilay@cs.wisc.edu# -*- mode:python -*-
211103Snilay@cs.wisc.edu
310260SAndrew.Bardsley@arm.com# Copyright (c) 2013, 2015-2017 ARM Limited
410260SAndrew.Bardsley@arm.com# All rights reserved.
510260SAndrew.Bardsley@arm.com#
611680SCurtis.Dunham@arm.com# The license below extends only to copyright in the software and shall
711680SCurtis.Dunham@arm.com# not be construed as granting a license to any other intellectual
811680SCurtis.Dunham@arm.com# property including but not limited to intellectual property relating
911570SCurtis.Dunham@arm.com# to a hardware implementation of the functionality of the software
1011103Snilay@cs.wisc.edu# licensed hereunder.  You may use the software subject to the license
1110260SAndrew.Bardsley@arm.com# terms below provided that you ensure that this notice is replicated
1210260SAndrew.Bardsley@arm.com# unmodified and in its entirety in all distributions of the software,
1310260SAndrew.Bardsley@arm.com# modified or unmodified, in source code or in binary form.
1410260SAndrew.Bardsley@arm.com#
1510753Sstever@gmail.com# Copyright (c) 2011 Advanced Micro Devices, Inc.
1610753Sstever@gmail.com# Copyright (c) 2009 The Hewlett-Packard Development Company
1710753Sstever@gmail.com# Copyright (c) 2004-2005 The Regents of The University of Michigan
1810753Sstever@gmail.com# All rights reserved.
1910753Sstever@gmail.com#
2010753Sstever@gmail.com# Redistribution and use in source and binary forms, with or without
2110753Sstever@gmail.com# modification, are permitted provided that the following conditions are
2210753Sstever@gmail.com# met: redistributions of source code must retain the above copyright
2310753Sstever@gmail.com# notice, this list of conditions and the following disclaimer;
2410753Sstever@gmail.com# redistributions in binary form must reproduce the above copyright
2510753Sstever@gmail.com# notice, this list of conditions and the following disclaimer in the
2610753Sstever@gmail.com# documentation and/or other materials provided with the distribution;
2710753Sstever@gmail.com# neither the name of the copyright holders nor the names of its
2810753Sstever@gmail.com# contributors may be used to endorse or promote products derived from
2910753Sstever@gmail.com# this software without specific prior written permission.
3010753Sstever@gmail.com#
3110753Sstever@gmail.com# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
3210753Sstever@gmail.com# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
3310753Sstever@gmail.com# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
3410753Sstever@gmail.com# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
3510753Sstever@gmail.com# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
3610753Sstever@gmail.com# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3710753Sstever@gmail.com# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
3810753Sstever@gmail.com# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
3910753Sstever@gmail.com# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
4010753Sstever@gmail.com# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
4110753Sstever@gmail.com# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4210753Sstever@gmail.com#
4310753Sstever@gmail.com# Authors: Steve Reinhardt
4410753Sstever@gmail.com#          Nathan Binkert
4510753Sstever@gmail.com
4610753Sstever@gmail.com###################################################
4710753Sstever@gmail.com#
4810753Sstever@gmail.com# SCons top-level build description (SConstruct) file.
4910753Sstever@gmail.com#
5010753Sstever@gmail.com# While in this directory ('gem5'), just type 'scons' to build the default
5110753Sstever@gmail.com# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
5210753Sstever@gmail.com# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
5310753Sstever@gmail.com# the optimized full-system version).
5410753Sstever@gmail.com#
5510753Sstever@gmail.com# You can build gem5 in a different directory as long as there is a
5610753Sstever@gmail.com# 'build/<CONFIG>' somewhere along the target path.  The build system
5710753Sstever@gmail.com# expects that all configs under the same build directory are being
5810753Sstever@gmail.com# built for the same host system.
5910753Sstever@gmail.com#
6010753Sstever@gmail.com# Examples:
6110753Sstever@gmail.com#
6210753Sstever@gmail.com#   The following two commands are equivalent.  The '-u' option tells
6310753Sstever@gmail.com#   scons to search up the directory tree for this SConstruct file.
6410753Sstever@gmail.com#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
6510753Sstever@gmail.com#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
6610753Sstever@gmail.com#
6710753Sstever@gmail.com#   The following two commands are equivalent and demonstrate building
6810753Sstever@gmail.com#   in a directory outside of the source tree.  The '-C' option tells
6910753Sstever@gmail.com#   scons to chdir to the specified directory to find this SConstruct
7010753Sstever@gmail.com#   file.
7110753Sstever@gmail.com#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
7210753Sstever@gmail.com#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
7310753Sstever@gmail.com#
7410753Sstever@gmail.com# You can use 'scons -H' to print scons options.  If you're in this
7510753Sstever@gmail.com# 'gem5' directory (or use -u or -C to tell scons where to find this
7610753Sstever@gmail.com# file), you can use 'scons -h' to print all the gem5-specific build
7710753Sstever@gmail.com# options as well.
7810753Sstever@gmail.com#
7910753Sstever@gmail.com###################################################
8010753Sstever@gmail.com
8110753Sstever@gmail.comfrom __future__ import print_function
8210753Sstever@gmail.com
8310753Sstever@gmail.com# Global Python includes
8410753Sstever@gmail.comimport itertools
8510753Sstever@gmail.comimport os
8610753Sstever@gmail.comimport re
8710753Sstever@gmail.comimport shutil
8810753Sstever@gmail.comimport subprocess
8910753Sstever@gmail.comimport sys
9010753Sstever@gmail.com
9110753Sstever@gmail.comfrom os import mkdir, environ
9210753Sstever@gmail.comfrom os.path import abspath, basename, dirname, expanduser, normpath
9310753Sstever@gmail.comfrom os.path import exists,  isdir, isfile
9410753Sstever@gmail.comfrom os.path import join as joinpath, split as splitpath
9510753Sstever@gmail.com
9610753Sstever@gmail.com# SCons includes
9710753Sstever@gmail.comimport SCons
9810753Sstever@gmail.comimport SCons.Node
9910753Sstever@gmail.com
10010753Sstever@gmail.comfrom m5.util import compareVersions, readCommand
10110753Sstever@gmail.com
10210753Sstever@gmail.comhelp_texts = {
10310753Sstever@gmail.com    "options" : "",
10410753Sstever@gmail.com    "global_vars" : "",
10510753Sstever@gmail.com    "local_vars" : ""
10610753Sstever@gmail.com}
10710753Sstever@gmail.com
10810753Sstever@gmail.comExport("help_texts")
10910753Sstever@gmail.com
11010753Sstever@gmail.com
11110753Sstever@gmail.com# There's a bug in scons in that (1) by default, the help texts from
11210753Sstever@gmail.com# AddOption() are supposed to be displayed when you type 'scons -h'
11310753Sstever@gmail.com# and (2) you can override the help displayed by 'scons -h' using the
11410753Sstever@gmail.com# Help() function, but these two features are incompatible: once
11510753Sstever@gmail.com# you've overridden the help text using Help(), there's no way to get
11610753Sstever@gmail.com# at the help texts from AddOptions.  See:
11710753Sstever@gmail.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
11810753Sstever@gmail.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
11910753Sstever@gmail.com# This hack lets us extract the help text from AddOptions and
12010753Sstever@gmail.com# re-inject it via Help().  Ideally someday this bug will be fixed and
12110753Sstever@gmail.com# we can just use AddOption directly.
12210753Sstever@gmail.comdef AddLocalOption(*args, **kwargs):
12310753Sstever@gmail.com    col_width = 30
12410753Sstever@gmail.com
12510753Sstever@gmail.com    help = "  " + ", ".join(args)
12610753Sstever@gmail.com    if "help" in kwargs:
12710753Sstever@gmail.com        length = len(help)
12810753Sstever@gmail.com        if length >= col_width:
12910753Sstever@gmail.com            help += "\n" + " " * col_width
13010753Sstever@gmail.com        else:
13110753Sstever@gmail.com            help += " " * (col_width - length)
13210753Sstever@gmail.com        help += kwargs["help"]
13310753Sstever@gmail.com    help_texts["options"] += help + "\n"
13410753Sstever@gmail.com
13510753Sstever@gmail.com    AddOption(*args, **kwargs)
13610753Sstever@gmail.com
13710753Sstever@gmail.comAddLocalOption('--colors', dest='use_colors', action='store_true',
13810753Sstever@gmail.com               help="Add color to abbreviated scons output")
13910753Sstever@gmail.comAddLocalOption('--no-colors', dest='use_colors', action='store_false',
14010753Sstever@gmail.com               help="Don't add color to abbreviated scons output")
14110753Sstever@gmail.comAddLocalOption('--with-cxx-config', dest='with_cxx_config',
14210753Sstever@gmail.com               action='store_true',
14310753Sstever@gmail.com               help="Build with support for C++-based configuration")
14410753Sstever@gmail.comAddLocalOption('--default', dest='default', type='string', action='store',
14510753Sstever@gmail.com               help='Override which build_opts file to use for defaults')
14610753Sstever@gmail.comAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
14710753Sstever@gmail.com               help='Disable style checking hooks')
14810753Sstever@gmail.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
14910753Sstever@gmail.com               help='Disable Link-Time Optimization for fast')
15010753Sstever@gmail.comAddLocalOption('--force-lto', dest='force_lto', action='store_true',
15110753Sstever@gmail.com               help='Use Link-Time Optimization instead of partial linking' +
15210753Sstever@gmail.com                    ' when the compiler doesn\'t support using them together.')
15310753Sstever@gmail.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
15410753Sstever@gmail.com               help='Update test reference outputs')
15510753Sstever@gmail.comAddLocalOption('--verbose', dest='verbose', action='store_true',
15610753Sstever@gmail.com               help='Print full tool command lines')
15710753Sstever@gmail.comAddLocalOption('--without-python', dest='without_python',
15810753Sstever@gmail.com               action='store_true',
15910753Sstever@gmail.com               help='Build without Python configuration support')
16010753Sstever@gmail.comAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
16110753Sstever@gmail.com               action='store_true',
16210753Sstever@gmail.com               help='Disable linking against tcmalloc')
16310753Sstever@gmail.comAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
16410753Sstever@gmail.com               help='Build with Undefined Behavior Sanitizer if available')
16510753Sstever@gmail.comAddLocalOption('--with-asan', dest='with_asan', action='store_true',
16610753Sstever@gmail.com               help='Build with Address Sanitizer if available')
16710753Sstever@gmail.com
16810753Sstever@gmail.comif GetOption('no_lto') and GetOption('force_lto'):
16910753Sstever@gmail.com    print('--no-lto and --force-lto are mutually exclusive')
17010753Sstever@gmail.com    Exit(1)
17110753Sstever@gmail.com
17210753Sstever@gmail.com########################################################################
17310753Sstever@gmail.com#
17410753Sstever@gmail.com# Set up the main build environment.
17510753Sstever@gmail.com#
17610753Sstever@gmail.com########################################################################
17710753Sstever@gmail.com
17810753Sstever@gmail.commain = Environment()
17910753Sstever@gmail.com
18010753Sstever@gmail.comfrom gem5_scons import Transform
18110753Sstever@gmail.comfrom gem5_scons.util import get_termcap
18210753Sstever@gmail.comtermcap = get_termcap()
18310753Sstever@gmail.com
18410753Sstever@gmail.commain_dict_keys = main.Dictionary().keys()
18510753Sstever@gmail.com
18610753Sstever@gmail.com# Check that we have a C/C++ compiler
18710753Sstever@gmail.comif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
18810753Sstever@gmail.com    print("No C++ compiler installed (package g++ on Ubuntu and RedHat)")
18910753Sstever@gmail.com    Exit(1)
19010753Sstever@gmail.com
19110753Sstever@gmail.com###################################################
19210753Sstever@gmail.com#
19310753Sstever@gmail.com# Figure out which configurations to set up based on the path(s) of
19410753Sstever@gmail.com# the target(s).
19510753Sstever@gmail.com#
19610753Sstever@gmail.com###################################################
19710753Sstever@gmail.com
19810753Sstever@gmail.com# Find default configuration & binary.
19910753Sstever@gmail.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
20010753Sstever@gmail.com
20110753Sstever@gmail.com# helper function: find last occurrence of element in list
20210753Sstever@gmail.comdef rfind(l, elt, offs = -1):
20310753Sstever@gmail.com    for i in range(len(l)+offs, 0, -1):
20410753Sstever@gmail.com        if l[i] == elt:
20510753Sstever@gmail.com            return i
20610753Sstever@gmail.com    raise ValueError, "element not found"
20710753Sstever@gmail.com
20810753Sstever@gmail.com# Take a list of paths (or SCons Nodes) and return a list with all
20910753Sstever@gmail.com# paths made absolute and ~-expanded.  Paths will be interpreted
21010753Sstever@gmail.com# relative to the launch directory unless a different root is provided
21110753Sstever@gmail.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
21210753Sstever@gmail.com    return [abspath(joinpath(root, expanduser(str(p))))
21310753Sstever@gmail.com            for p in path_list]
21410753Sstever@gmail.com
21510753Sstever@gmail.com# Each target must have 'build' in the interior of the path; the
21610753Sstever@gmail.com# directory below this will determine the build parameters.  For
21710753Sstever@gmail.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
21810753Sstever@gmail.com# recognize that ALPHA_SE specifies the configuration because it
21910753Sstever@gmail.com# follow 'build' in the build path.
22010753Sstever@gmail.com
22110753Sstever@gmail.com# The funky assignment to "[:]" is needed to replace the list contents
22210753Sstever@gmail.com# in place rather than reassign the symbol to a new list, which
22310753Sstever@gmail.com# doesn't work (obviously!).
22410753Sstever@gmail.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
22510753Sstever@gmail.com
22610753Sstever@gmail.com# Generate a list of the unique build roots and configs that the
22710753Sstever@gmail.com# collected targets reference.
22810753Sstever@gmail.comvariant_paths = []
22910753Sstever@gmail.combuild_root = None
23010753Sstever@gmail.comfor t in BUILD_TARGETS:
23110753Sstever@gmail.com    path_dirs = t.split('/')
23210753Sstever@gmail.com    try:
23310753Sstever@gmail.com        build_top = rfind(path_dirs, 'build', -2)
23410753Sstever@gmail.com    except:
23510753Sstever@gmail.com        print("Error: no non-leaf 'build' dir found on target path", t)
23610753Sstever@gmail.com        Exit(1)
23710753Sstever@gmail.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
23810753Sstever@gmail.com    if not build_root:
23910753Sstever@gmail.com        build_root = this_build_root
24010753Sstever@gmail.com    else:
24110753Sstever@gmail.com        if this_build_root != build_root:
24210753Sstever@gmail.com            print("Error: build targets not under same build root\n"
24310753Sstever@gmail.com                  "  %s\n  %s" % (build_root, this_build_root))
24410753Sstever@gmail.com            Exit(1)
24510753Sstever@gmail.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
24610753Sstever@gmail.com    if variant_path not in variant_paths:
24710753Sstever@gmail.com        variant_paths.append(variant_path)
24810753Sstever@gmail.com
24910753Sstever@gmail.com# Make sure build_root exists (might not if this is the first build there)
25010753Sstever@gmail.comif not isdir(build_root):
25110753Sstever@gmail.com    mkdir(build_root)
25210753Sstever@gmail.commain['BUILDROOT'] = build_root
25310753Sstever@gmail.com
25410753Sstever@gmail.comExport('main')
25510753Sstever@gmail.com
25610753Sstever@gmail.commain.SConsignFile(joinpath(build_root, "sconsign"))
25710753Sstever@gmail.com
25810753Sstever@gmail.com# Default duplicate option is to use hard links, but this messes up
25910753Sstever@gmail.com# when you use emacs to edit a file in the target dir, as emacs moves
26010753Sstever@gmail.com# file to file~ then copies to file, breaking the link.  Symbolic
26110753Sstever@gmail.com# (soft) links work better.
26210753Sstever@gmail.commain.SetOption('duplicate', 'soft-copy')
26310753Sstever@gmail.com
26410753Sstever@gmail.com#
26510753Sstever@gmail.com# Set up global sticky variables... these are common to an entire build
26610753Sstever@gmail.com# tree (not specific to a particular build like ALPHA_SE)
26710753Sstever@gmail.com#
26810753Sstever@gmail.com
26910753Sstever@gmail.comglobal_vars_file = joinpath(build_root, 'variables.global')
27010753Sstever@gmail.com
27110753Sstever@gmail.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
27210753Sstever@gmail.com
27310753Sstever@gmail.comglobal_vars.AddVariables(
27410753Sstever@gmail.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
27510753Sstever@gmail.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
27610753Sstever@gmail.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
27710753Sstever@gmail.com    ('BATCH', 'Use batch pool for build and tests', False),
27810753Sstever@gmail.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
27910753Sstever@gmail.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
28010753Sstever@gmail.com    ('EXTRAS', 'Add extra directories to the compilation', '')
28110753Sstever@gmail.com    )
28210753Sstever@gmail.com
28310753Sstever@gmail.com# Update main environment with values from ARGUMENTS & global_vars_file
28410753Sstever@gmail.comglobal_vars.Update(main)
28510753Sstever@gmail.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
28610753Sstever@gmail.com
28710753Sstever@gmail.com# Save sticky variable settings back to current variables file
28810753Sstever@gmail.comglobal_vars.Save(global_vars_file, main)
28910753Sstever@gmail.com
29010753Sstever@gmail.com# Parse EXTRAS variable to build list of all directories where we're
29110753Sstever@gmail.com# look for sources etc.  This list is exported as extras_dir_list.
29210753Sstever@gmail.combase_dir = main.srcdir.abspath
29310753Sstever@gmail.comif main['EXTRAS']:
29410753Sstever@gmail.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
29510753Sstever@gmail.comelse:
29610753Sstever@gmail.com    extras_dir_list = []
29710753Sstever@gmail.com
29810753Sstever@gmail.comExport('base_dir')
29910753Sstever@gmail.comExport('extras_dir_list')
30010753Sstever@gmail.com
30110753Sstever@gmail.com# the ext directory should be on the #includes path
30210753Sstever@gmail.commain.Append(CPPPATH=[Dir('ext')])
30310753Sstever@gmail.com
30410753Sstever@gmail.com# Add shared top-level headers
30510753Sstever@gmail.commain.Prepend(CPPPATH=Dir('include'))
30610753Sstever@gmail.com
30710753Sstever@gmail.comif GetOption('verbose'):
30810753Sstever@gmail.com    def MakeAction(action, string, *args, **kwargs):
30910753Sstever@gmail.com        return Action(action, *args, **kwargs)
31010753Sstever@gmail.comelse:
31110753Sstever@gmail.com    MakeAction = Action
31210753Sstever@gmail.com    main['CCCOMSTR']        = Transform("CC")
31310753Sstever@gmail.com    main['CXXCOMSTR']       = Transform("CXX")
31410753Sstever@gmail.com    main['ASCOMSTR']        = Transform("AS")
31510753Sstever@gmail.com    main['ARCOMSTR']        = Transform("AR", 0)
31610753Sstever@gmail.com    main['LINKCOMSTR']      = Transform("LINK", 0)
31710753Sstever@gmail.com    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
31810753Sstever@gmail.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
31910753Sstever@gmail.com    main['M4COMSTR']        = Transform("M4")
32010753Sstever@gmail.com    main['SHCCCOMSTR']      = Transform("SHCC")
32110753Sstever@gmail.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
32210753Sstever@gmail.comExport('MakeAction')
32310753Sstever@gmail.com
32410753Sstever@gmail.com# Initialize the Link-Time Optimization (LTO) flags
32510753Sstever@gmail.commain['LTO_CCFLAGS'] = []
32610753Sstever@gmail.commain['LTO_LDFLAGS'] = []
32710753Sstever@gmail.com
32810753Sstever@gmail.com# According to the readme, tcmalloc works best if the compiler doesn't
32910753Sstever@gmail.com# assume that we're using the builtin malloc and friends. These flags
33010753Sstever@gmail.com# are compiler-specific, so we need to set them after we detect which
33110753Sstever@gmail.com# compiler we're using.
33210753Sstever@gmail.commain['TCMALLOC_CCFLAGS'] = []
33310753Sstever@gmail.com
33410753Sstever@gmail.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
33510753Sstever@gmail.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
33610753Sstever@gmail.com
33710753Sstever@gmail.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
33810753Sstever@gmail.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
33910753Sstever@gmail.comif main['GCC'] + main['CLANG'] > 1:
34010753Sstever@gmail.com    print('Error: How can we have two at the same time?')
34110753Sstever@gmail.com    Exit(1)
34210753Sstever@gmail.com
34310753Sstever@gmail.com# Set up default C++ compiler flags
34410753Sstever@gmail.comif main['GCC'] or main['CLANG']:
34510753Sstever@gmail.com    # As gcc and clang share many flags, do the common parts here
34610753Sstever@gmail.com    main.Append(CCFLAGS=['-pipe'])
34710753Sstever@gmail.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
34810753Sstever@gmail.com    # Enable -Wall and -Wextra and then disable the few warnings that
34910753Sstever@gmail.com    # we consistently violate
35010753Sstever@gmail.com    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
35110753Sstever@gmail.com                         '-Wno-sign-compare', '-Wno-unused-parameter'])
35210753Sstever@gmail.com    # We always compile using C++11
35310753Sstever@gmail.com    main.Append(CXXFLAGS=['-std=c++11'])
35410753Sstever@gmail.com    if sys.platform.startswith('freebsd'):
35510753Sstever@gmail.com        main.Append(CCFLAGS=['-I/usr/local/include'])
35610753Sstever@gmail.com        main.Append(CXXFLAGS=['-I/usr/local/include'])
35710753Sstever@gmail.com
35810753Sstever@gmail.com    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
35910753Sstever@gmail.com    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
36010753Sstever@gmail.com    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
36110753Sstever@gmail.com    shared_partial_flags = ['-r', '-nostdlib']
36210753Sstever@gmail.com    main.Append(PSHLINKFLAGS=shared_partial_flags)
36310753Sstever@gmail.com    main.Append(PLINKFLAGS=shared_partial_flags)
36410753Sstever@gmail.com
36510753Sstever@gmail.com    # Treat warnings as errors but white list some warnings that we
36610753Sstever@gmail.com    # want to allow (e.g., deprecation warnings).
36710753Sstever@gmail.com    main.Append(CCFLAGS=['-Werror',
36810753Sstever@gmail.com                         '-Wno-error=deprecated-declarations',
36910753Sstever@gmail.com                         '-Wno-error=deprecated',
37010753Sstever@gmail.com                        ])
37110753Sstever@gmail.comelse:
37210753Sstever@gmail.com    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
37310753Sstever@gmail.com    print("Don't know what compiler options to use for your compiler.")
37410753Sstever@gmail.com    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
37510753Sstever@gmail.com    print(termcap.Yellow + '       version:' + termcap.Normal, end = ' ')
37610753Sstever@gmail.com    if not CXX_version:
37710753Sstever@gmail.com        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
37810753Sstever@gmail.com              termcap.Normal)
37910753Sstever@gmail.com    else:
38010753Sstever@gmail.com        print(CXX_version.replace('\n', '<nl>'))
38110753Sstever@gmail.com    print("       If you're trying to use a compiler other than GCC")
38210753Sstever@gmail.com    print("       or clang, there appears to be something wrong with your")
38310753Sstever@gmail.com    print("       environment.")
38410753Sstever@gmail.com    print("       ")
38510753Sstever@gmail.com    print("       If you are trying to use a compiler other than those listed")
38610753Sstever@gmail.com    print("       above you will need to ease fix SConstruct and ")
38710753Sstever@gmail.com    print("       src/SConscript to support that compiler.")
38810753Sstever@gmail.com    Exit(1)
38910753Sstever@gmail.com
39010753Sstever@gmail.comif main['GCC']:
39110753Sstever@gmail.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
39210753Sstever@gmail.com    # level of c++11 support. See
39310753Sstever@gmail.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
39410753Sstever@gmail.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
39510753Sstever@gmail.com    if compareVersions(gcc_version, "4.8") < 0:
39610753Sstever@gmail.com        print('Error: gcc version 4.8 or newer required.')
39710753Sstever@gmail.com        print('       Installed version: ', gcc_version)
39810753Sstever@gmail.com        Exit(1)
39910753Sstever@gmail.com
40010753Sstever@gmail.com    main['GCC_VERSION'] = gcc_version
40110753Sstever@gmail.com
40210753Sstever@gmail.com    if compareVersions(gcc_version, '4.9') >= 0:
40310753Sstever@gmail.com        # Incremental linking with LTO is currently broken in gcc versions
40410753Sstever@gmail.com        # 4.9 and above. A version where everything works completely hasn't
40510753Sstever@gmail.com        # yet been identified.
40610753Sstever@gmail.com        #
40710753Sstever@gmail.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
40810753Sstever@gmail.com        main['BROKEN_INCREMENTAL_LTO'] = True
40910753Sstever@gmail.com    if compareVersions(gcc_version, '6.0') >= 0:
41010753Sstever@gmail.com        # gcc versions 6.0 and greater accept an -flinker-output flag which
41110753Sstever@gmail.com        # selects what type of output the linker should generate. This is
41210753Sstever@gmail.com        # necessary for incremental lto to work, but is also broken in
41310753Sstever@gmail.com        # current versions of gcc. It may not be necessary in future
41410753Sstever@gmail.com        # versions. We add it here since it might be, and as a reminder that
41510753Sstever@gmail.com        # it exists. It's excluded if lto is being forced.
41610753Sstever@gmail.com        #
41710753Sstever@gmail.com        # https://gcc.gnu.org/gcc-6/changes.html
41810753Sstever@gmail.com        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
41910753Sstever@gmail.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
42010753Sstever@gmail.com        if not GetOption('force_lto'):
42110753Sstever@gmail.com            main.Append(PSHLINKFLAGS='-flinker-output=rel')
42210753Sstever@gmail.com            main.Append(PLINKFLAGS='-flinker-output=rel')
42310753Sstever@gmail.com
42410753Sstever@gmail.com    # gcc from version 4.8 and above generates "rep; ret" instructions
42510753Sstever@gmail.com    # to avoid performance penalties on certain AMD chips. Older
42610753Sstever@gmail.com    # assemblers detect this as an error, "Error: expecting string
42710753Sstever@gmail.com    # instruction after `rep'"
42810753Sstever@gmail.com    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
42910753Sstever@gmail.com                                  '-o', '/dev/null'],
43010753Sstever@gmail.com                                 exception=False).split()
43110753Sstever@gmail.com
43210753Sstever@gmail.com    # version strings may contain extra distro-specific
43310753Sstever@gmail.com    # qualifiers, so play it safe and keep only what comes before
43410753Sstever@gmail.com    # the first hyphen
43510753Sstever@gmail.com    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
43610753Sstever@gmail.com
43710753Sstever@gmail.com    if not as_version or compareVersions(as_version, "2.23") < 0:
43810753Sstever@gmail.com        print(termcap.Yellow + termcap.Bold +
43910753Sstever@gmail.com            'Warning: This combination of gcc and binutils have' +
44010753Sstever@gmail.com            ' known incompatibilities.\n' +
44110753Sstever@gmail.com            '         If you encounter build problems, please update ' +
44210753Sstever@gmail.com            'binutils to 2.23.' +
44310753Sstever@gmail.com            termcap.Normal)
44410753Sstever@gmail.com
44510753Sstever@gmail.com    # Make sure we warn if the user has requested to compile with the
44610753Sstever@gmail.com    # Undefined Benahvior Sanitizer and this version of gcc does not
44710753Sstever@gmail.com    # support it.
44810753Sstever@gmail.com    if GetOption('with_ubsan') and \
44910753Sstever@gmail.com            compareVersions(gcc_version, '4.9') < 0:
45010753Sstever@gmail.com        print(termcap.Yellow + termcap.Bold +
45110753Sstever@gmail.com            'Warning: UBSan is only supported using gcc 4.9 and later.' +
45210753Sstever@gmail.com            termcap.Normal)
45310753Sstever@gmail.com
45410753Sstever@gmail.com    disable_lto = GetOption('no_lto')
45510753Sstever@gmail.com    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
45610753Sstever@gmail.com            not GetOption('force_lto'):
45710753Sstever@gmail.com        print(termcap.Yellow + termcap.Bold +
45810753Sstever@gmail.com            'Warning: Your compiler doesn\'t support incremental linking' +
45910753Sstever@gmail.com            ' and lto at the same time, so lto is being disabled. To force' +
46010753Sstever@gmail.com            ' lto on anyway, use the --force-lto option. That will disable' +
46110753Sstever@gmail.com            ' partial linking.' +
46210753Sstever@gmail.com            termcap.Normal)
46310753Sstever@gmail.com        disable_lto = True
46410753Sstever@gmail.com
46510753Sstever@gmail.com    # Add the appropriate Link-Time Optimization (LTO) flags
46610753Sstever@gmail.com    # unless LTO is explicitly turned off. Note that these flags
46710753Sstever@gmail.com    # are only used by the fast target.
46810753Sstever@gmail.com    if not disable_lto:
46910753Sstever@gmail.com        # Pass the LTO flag when compiling to produce GIMPLE
47010753Sstever@gmail.com        # output, we merely create the flags here and only append
47110753Sstever@gmail.com        # them later
47210753Sstever@gmail.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
47310753Sstever@gmail.com
47410753Sstever@gmail.com        # Use the same amount of jobs for LTO as we are running
47510753Sstever@gmail.com        # scons with
47610753Sstever@gmail.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
47710753Sstever@gmail.com
47810753Sstever@gmail.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
47910753Sstever@gmail.com                                  '-fno-builtin-realloc', '-fno-builtin-free'])
48010753Sstever@gmail.com
48110753Sstever@gmail.com    # add option to check for undeclared overrides
48210753Sstever@gmail.com    if compareVersions(gcc_version, "5.0") > 0:
48310753Sstever@gmail.com        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
48410753Sstever@gmail.com
48510753Sstever@gmail.com    # The address sanitizer is available for gcc >= 4.8
48610753Sstever@gmail.com    if GetOption('with_asan'):
48710753Sstever@gmail.com        if GetOption('with_ubsan') and \
48810753Sstever@gmail.com                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
48910753Sstever@gmail.com            env.Append(CCFLAGS=['-fsanitize=address,undefined',
49010753Sstever@gmail.com                                '-fno-omit-frame-pointer'],
49110753Sstever@gmail.com                       LINKFLAGS='-fsanitize=address,undefined')
49210753Sstever@gmail.com        else:
49310753Sstever@gmail.com            env.Append(CCFLAGS=['-fsanitize=address',
49410753Sstever@gmail.com                                '-fno-omit-frame-pointer'],
49510753Sstever@gmail.com                       LINKFLAGS='-fsanitize=address')
49610753Sstever@gmail.com    # Only gcc >= 4.9 supports UBSan, so check both the version
49710753Sstever@gmail.com    # and the command-line option before adding the compiler and
49810753Sstever@gmail.com    # linker flags.
49910753Sstever@gmail.com    elif GetOption('with_ubsan') and \
50010753Sstever@gmail.com            compareVersions(env['GCC_VERSION'], '4.9') >= 0:
50110753Sstever@gmail.com        env.Append(CCFLAGS='-fsanitize=undefined')
50210753Sstever@gmail.com        env.Append(LINKFLAGS='-fsanitize=undefined')
50310753Sstever@gmail.com
50410753Sstever@gmail.comelif main['CLANG']:
50510753Sstever@gmail.com    # Check for a supported version of clang, >= 3.1 is needed to
50610753Sstever@gmail.com    # support similar features as gcc 4.8. See
50710753Sstever@gmail.com    # http://clang.llvm.org/cxx_status.html for details
50810753Sstever@gmail.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
50910753Sstever@gmail.com    clang_version_match = clang_version_re.search(CXX_version)
51010753Sstever@gmail.com    if (clang_version_match):
51110753Sstever@gmail.com        clang_version = clang_version_match.groups()[0]
51210753Sstever@gmail.com        if compareVersions(clang_version, "3.1") < 0:
51310753Sstever@gmail.com            print('Error: clang version 3.1 or newer required.')
51410753Sstever@gmail.com            print('       Installed version:', clang_version)
51510753Sstever@gmail.com            Exit(1)
51610753Sstever@gmail.com    else:
51710753Sstever@gmail.com        print('Error: Unable to determine clang version.')
51810753Sstever@gmail.com        Exit(1)
51910753Sstever@gmail.com
52010753Sstever@gmail.com    # clang has a few additional warnings that we disable, extraneous
52110753Sstever@gmail.com    # parantheses are allowed due to Ruby's printing of the AST,
52210753Sstever@gmail.com    # finally self assignments are allowed as the generated CPU code
52310753Sstever@gmail.com    # is relying on this
52410753Sstever@gmail.com    main.Append(CCFLAGS=['-Wno-parentheses',
52510753Sstever@gmail.com                         '-Wno-self-assign',
52610753Sstever@gmail.com                         # Some versions of libstdc++ (4.8?) seem to
52710753Sstever@gmail.com                         # use struct hash and class hash
52810753Sstever@gmail.com                         # interchangeably.
52910753Sstever@gmail.com                         '-Wno-mismatched-tags',
53010753Sstever@gmail.com                         ])
53110753Sstever@gmail.com
53210753Sstever@gmail.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
53310753Sstever@gmail.com
53410753Sstever@gmail.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
53510753Sstever@gmail.com    # opposed to libstdc++, as the later is dated.
53610753Sstever@gmail.com    if sys.platform == "darwin":
53710753Sstever@gmail.com        main.Append(CXXFLAGS=['-stdlib=libc++'])
53810753Sstever@gmail.com        main.Append(LIBS=['c++'])
53910753Sstever@gmail.com
54010753Sstever@gmail.com    # On FreeBSD we need libthr.
54110753Sstever@gmail.com    if sys.platform.startswith('freebsd'):
54210753Sstever@gmail.com        main.Append(LIBS=['thr'])
54310753Sstever@gmail.com
54410753Sstever@gmail.com    # We require clang >= 3.1, so there is no need to check any
54510753Sstever@gmail.com    # versions here.
54610753Sstever@gmail.com    if GetOption('with_ubsan'):
54710753Sstever@gmail.com        if GetOption('with_asan'):
54810753Sstever@gmail.com            env.Append(CCFLAGS=['-fsanitize=address,undefined',
54910753Sstever@gmail.com                                '-fno-omit-frame-pointer'],
55010753Sstever@gmail.com                       LINKFLAGS='-fsanitize=address,undefined')
55110753Sstever@gmail.com        else:
55210753Sstever@gmail.com            env.Append(CCFLAGS='-fsanitize=undefined',
55310753Sstever@gmail.com                       LINKFLAGS='-fsanitize=undefined')
55410753Sstever@gmail.com
55510753Sstever@gmail.com    elif GetOption('with_asan'):
55610753Sstever@gmail.com        env.Append(CCFLAGS=['-fsanitize=address',
55710753Sstever@gmail.com                            '-fno-omit-frame-pointer'],
55810753Sstever@gmail.com                   LINKFLAGS='-fsanitize=address')
55910753Sstever@gmail.com
56010753Sstever@gmail.comelse:
56110753Sstever@gmail.com    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
56210753Sstever@gmail.com    print("Don't know what compiler options to use for your compiler.")
56310753Sstever@gmail.com    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
56410753Sstever@gmail.com    print(termcap.Yellow + '       version:' + termcap.Normal, end=' ')
56510753Sstever@gmail.com    if not CXX_version:
56610753Sstever@gmail.com        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
56710753Sstever@gmail.com              termcap.Normal)
56810753Sstever@gmail.com    else:
56910753Sstever@gmail.com        print(CXX_version.replace('\n', '<nl>'))
57010753Sstever@gmail.com    print("       If you're trying to use a compiler other than GCC")
57110753Sstever@gmail.com    print("       or clang, there appears to be something wrong with your")
57210753Sstever@gmail.com    print("       environment.")
57310753Sstever@gmail.com    print("       ")
57410753Sstever@gmail.com    print("       If you are trying to use a compiler other than those listed")
57510753Sstever@gmail.com    print("       above you will need to ease fix SConstruct and ")
57610753Sstever@gmail.com    print("       src/SConscript to support that compiler.")
57710753Sstever@gmail.com    Exit(1)
57810753Sstever@gmail.com
57910753Sstever@gmail.com# Set up common yacc/bison flags (needed for Ruby)
58010753Sstever@gmail.commain['YACCFLAGS'] = '-d'
58110753Sstever@gmail.commain['YACCHXXFILESUFFIX'] = '.hh'
58210753Sstever@gmail.com
58310753Sstever@gmail.com# Do this after we save setting back, or else we'll tack on an
58410753Sstever@gmail.com# extra 'qdo' every time we run scons.
58510753Sstever@gmail.comif main['BATCH']:
58610753Sstever@gmail.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
58710753Sstever@gmail.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
58810753Sstever@gmail.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
58910753Sstever@gmail.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
59010753Sstever@gmail.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
59110753Sstever@gmail.com
59210753Sstever@gmail.comif sys.platform == 'cygwin':
59310753Sstever@gmail.com    # cygwin has some header file issues...
59410753Sstever@gmail.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
59510753Sstever@gmail.com
59610753Sstever@gmail.com# Check for the protobuf compiler
59710753Sstever@gmail.comprotoc_version = readCommand([main['PROTOC'], '--version'],
59810753Sstever@gmail.com                             exception='').split()
59910753Sstever@gmail.com
60010753Sstever@gmail.com# First two words should be "libprotoc x.y.z"
60110753Sstever@gmail.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
60210753Sstever@gmail.com    print(termcap.Yellow + termcap.Bold +
60310753Sstever@gmail.com        'Warning: Protocol buffer compiler (protoc) not found.\n' +
60410753Sstever@gmail.com        '         Please install protobuf-compiler for tracing support.' +
60510753Sstever@gmail.com        termcap.Normal)
60610753Sstever@gmail.com    main['PROTOC'] = False
60710753Sstever@gmail.comelse:
60810753Sstever@gmail.com    # Based on the availability of the compress stream wrappers,
60910753Sstever@gmail.com    # require 2.1.0
61010753Sstever@gmail.com    min_protoc_version = '2.1.0'
61110753Sstever@gmail.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
61210753Sstever@gmail.com        print(termcap.Yellow + termcap.Bold +
61310753Sstever@gmail.com            'Warning: protoc version', min_protoc_version,
61410753Sstever@gmail.com            'or newer required.\n' +
61510753Sstever@gmail.com            '         Installed version:', protoc_version[1],
61610753Sstever@gmail.com            termcap.Normal)
61710753Sstever@gmail.com        main['PROTOC'] = False
61810753Sstever@gmail.com    else:
61910753Sstever@gmail.com        # Attempt to determine the appropriate include path and
62010753Sstever@gmail.com        # library path using pkg-config, that means we also need to
62110753Sstever@gmail.com        # check for pkg-config. Note that it is possible to use
62210753Sstever@gmail.com        # protobuf without the involvement of pkg-config. Later on we
62310753Sstever@gmail.com        # check go a library config check and at that point the test
62410753Sstever@gmail.com        # will fail if libprotobuf cannot be found.
62510753Sstever@gmail.com        if readCommand(['pkg-config', '--version'], exception=''):
62610753Sstever@gmail.com            try:
62710753Sstever@gmail.com                # Attempt to establish what linking flags to add for protobuf
62810753Sstever@gmail.com                # using pkg-config
62910753Sstever@gmail.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
63010753Sstever@gmail.com            except:
63110753Sstever@gmail.com                print(termcap.Yellow + termcap.Bold +
63210753Sstever@gmail.com                    'Warning: pkg-config could not get protobuf flags.' +
63310753Sstever@gmail.com                    termcap.Normal)
63410753Sstever@gmail.com
63510753Sstever@gmail.com
63610753Sstever@gmail.com# Check for 'timeout' from GNU coreutils. If present, regressions will
63710753Sstever@gmail.com# be run with a time limit. We require version 8.13 since we rely on
63810753Sstever@gmail.com# support for the '--foreground' option.
63910753Sstever@gmail.comif sys.platform.startswith('freebsd'):
64010753Sstever@gmail.com    timeout_lines = readCommand(['gtimeout', '--version'],
64110753Sstever@gmail.com                                exception='').splitlines()
64210753Sstever@gmail.comelse:
64310753Sstever@gmail.com    timeout_lines = readCommand(['timeout', '--version'],
64410753Sstever@gmail.com                                exception='').splitlines()
64510753Sstever@gmail.com# Get the first line and tokenize it
64610753Sstever@gmail.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
64710753Sstever@gmail.commain['TIMEOUT'] =  timeout_version and \
64810753Sstever@gmail.com    compareVersions(timeout_version[-1], '8.13') >= 0
64910753Sstever@gmail.com
65010753Sstever@gmail.com# Add a custom Check function to test for structure members.
65110753Sstever@gmail.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
65210753Sstever@gmail.com    context.Message("Checking for member %s in %s..." %
65311680SCurtis.Dunham@arm.com                    (member, decl))
654    text = """
655#include %(header)s
656int main(){
657  %(decl)s test;
658  (void)test.%(member)s;
659  return 0;
660};
661""" % { "header" : include_quotes[0] + include + include_quotes[1],
662        "decl" : decl,
663        "member" : member,
664        }
665
666    ret = context.TryCompile(text, extension=".cc")
667    context.Result(ret)
668    return ret
669
670# Platform-specific configuration.  Note again that we assume that all
671# builds under a given build root run on the same host platform.
672conf = Configure(main,
673                 conf_dir = joinpath(build_root, '.scons_config'),
674                 log_file = joinpath(build_root, 'scons_config.log'),
675                 custom_tests = {
676        'CheckMember' : CheckMember,
677        })
678
679# Check if we should compile a 64 bit binary on Mac OS X/Darwin
680try:
681    import platform
682    uname = platform.uname()
683    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
684        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
685            main.Append(CCFLAGS=['-arch', 'x86_64'])
686            main.Append(CFLAGS=['-arch', 'x86_64'])
687            main.Append(LINKFLAGS=['-arch', 'x86_64'])
688            main.Append(ASFLAGS=['-arch', 'x86_64'])
689except:
690    pass
691
692# Recent versions of scons substitute a "Null" object for Configure()
693# when configuration isn't necessary, e.g., if the "--help" option is
694# present.  Unfortuantely this Null object always returns false,
695# breaking all our configuration checks.  We replace it with our own
696# more optimistic null object that returns True instead.
697if not conf:
698    def NullCheck(*args, **kwargs):
699        return True
700
701    class NullConf:
702        def __init__(self, env):
703            self.env = env
704        def Finish(self):
705            return self.env
706        def __getattr__(self, mname):
707            return NullCheck
708
709    conf = NullConf(main)
710
711# Cache build files in the supplied directory.
712if main['M5_BUILD_CACHE']:
713    print('Using build cache located at', main['M5_BUILD_CACHE'])
714    CacheDir(main['M5_BUILD_CACHE'])
715
716main['USE_PYTHON'] = not GetOption('without_python')
717if main['USE_PYTHON']:
718    # Find Python include and library directories for embedding the
719    # interpreter. We rely on python-config to resolve the appropriate
720    # includes and linker flags. ParseConfig does not seem to understand
721    # the more exotic linker flags such as -Xlinker and -export-dynamic so
722    # we add them explicitly below. If you want to link in an alternate
723    # version of python, see above for instructions on how to invoke
724    # scons with the appropriate PATH set.
725    #
726    # First we check if python2-config exists, else we use python-config
727    python_config = readCommand(['which', 'python2-config'],
728                                exception='').strip()
729    if not os.path.exists(python_config):
730        python_config = readCommand(['which', 'python-config'],
731                                    exception='').strip()
732    py_includes = readCommand([python_config, '--includes'],
733                              exception='').split()
734    # Strip the -I from the include folders before adding them to the
735    # CPPPATH
736    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
737
738    # Read the linker flags and split them into libraries and other link
739    # flags. The libraries are added later through the call the CheckLib.
740    py_ld_flags = readCommand([python_config, '--ldflags'],
741        exception='').split()
742    py_libs = []
743    for lib in py_ld_flags:
744         if not lib.startswith('-l'):
745             main.Append(LINKFLAGS=[lib])
746         else:
747             lib = lib[2:]
748             if lib not in py_libs:
749                 py_libs.append(lib)
750
751    # verify that this stuff works
752    if not conf.CheckHeader('Python.h', '<>'):
753        print("Error: can't find Python.h header in", py_includes)
754        print("Install Python headers (package python-dev on " +
755              "Ubuntu and RedHat)")
756        Exit(1)
757
758    for lib in py_libs:
759        if not conf.CheckLib(lib):
760            print("Error: can't find library %s required by python" % lib)
761            Exit(1)
762
763# On Solaris you need to use libsocket for socket ops
764if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
765   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
766       print("Can't find library with socket calls (e.g. accept())")
767       Exit(1)
768
769# Check for zlib.  If the check passes, libz will be automatically
770# added to the LIBS environment variable.
771if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
772    print('Error: did not find needed zlib compression library '
773          'and/or zlib.h header file.')
774    print('       Please install zlib and try again.')
775    Exit(1)
776
777# If we have the protobuf compiler, also make sure we have the
778# development libraries. If the check passes, libprotobuf will be
779# automatically added to the LIBS environment variable. After
780# this, we can use the HAVE_PROTOBUF flag to determine if we have
781# got both protoc and libprotobuf available.
782main['HAVE_PROTOBUF'] = main['PROTOC'] and \
783    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
784                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
785
786# If we have the compiler but not the library, print another warning.
787if main['PROTOC'] and not main['HAVE_PROTOBUF']:
788    print(termcap.Yellow + termcap.Bold +
789        'Warning: did not find protocol buffer library and/or headers.\n' +
790    '       Please install libprotobuf-dev for tracing support.' +
791    termcap.Normal)
792
793# Check for librt.
794have_posix_clock = \
795    conf.CheckLibWithHeader(None, 'time.h', 'C',
796                            'clock_nanosleep(0,0,NULL,NULL);') or \
797    conf.CheckLibWithHeader('rt', 'time.h', 'C',
798                            'clock_nanosleep(0,0,NULL,NULL);')
799
800have_posix_timers = \
801    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
802                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
803
804if not GetOption('without_tcmalloc'):
805    if conf.CheckLib('tcmalloc'):
806        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
807    elif conf.CheckLib('tcmalloc_minimal'):
808        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
809    else:
810        print(termcap.Yellow + termcap.Bold +
811              "You can get a 12% performance improvement by "
812              "installing tcmalloc (libgoogle-perftools-dev package "
813              "on Ubuntu or RedHat)." + termcap.Normal)
814
815
816# Detect back trace implementations. The last implementation in the
817# list will be used by default.
818backtrace_impls = [ "none" ]
819
820backtrace_checker = 'char temp;' + \
821    ' backtrace_symbols_fd((void*)&temp, 0, 0);'
822if conf.CheckLibWithHeader(None, 'execinfo.h', 'C', backtrace_checker):
823    backtrace_impls.append("glibc")
824elif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
825                             backtrace_checker):
826    # NetBSD and FreeBSD need libexecinfo.
827    backtrace_impls.append("glibc")
828    main.Append(LIBS=['execinfo'])
829
830if backtrace_impls[-1] == "none":
831    default_backtrace_impl = "none"
832    print(termcap.Yellow + termcap.Bold +
833        "No suitable back trace implementation found." +
834        termcap.Normal)
835
836if not have_posix_clock:
837    print("Can't find library for POSIX clocks.")
838
839# Check for <fenv.h> (C99 FP environment control)
840have_fenv = conf.CheckHeader('fenv.h', '<>')
841if not have_fenv:
842    print("Warning: Header file <fenv.h> not found.")
843    print("         This host has no IEEE FP rounding mode control.")
844
845# Check for <png.h> (libpng library needed if wanting to dump
846# frame buffer image in png format)
847have_png = conf.CheckHeader('png.h', '<>')
848if not have_png:
849    print("Warning: Header file <png.h> not found.")
850    print("         This host has no libpng library.")
851    print("         Disabling support for PNG framebuffers.")
852
853# Check if we should enable KVM-based hardware virtualization. The API
854# we rely on exists since version 2.6.36 of the kernel, but somehow
855# the KVM_API_VERSION does not reflect the change. We test for one of
856# the types as a fall back.
857have_kvm = conf.CheckHeader('linux/kvm.h', '<>')
858if not have_kvm:
859    print("Info: Compatible header file <linux/kvm.h> not found, "
860          "disabling KVM support.")
861
862# Check if the TUN/TAP driver is available.
863have_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
864if not have_tuntap:
865    print("Info: Compatible header file <linux/if_tun.h> not found.")
866
867# x86 needs support for xsave. We test for the structure here since we
868# won't be able to run new tests by the time we know which ISA we're
869# targeting.
870have_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
871                                    '#include <linux/kvm.h>') != 0
872
873# Check if the requested target ISA is compatible with the host
874def is_isa_kvm_compatible(isa):
875    try:
876        import platform
877        host_isa = platform.machine()
878    except:
879        print("Warning: Failed to determine host ISA.")
880        return False
881
882    if not have_posix_timers:
883        print("Warning: Can not enable KVM, host seems to lack support "
884              "for POSIX timers")
885        return False
886
887    if isa == "arm":
888        return host_isa in ( "armv7l", "aarch64" )
889    elif isa == "x86":
890        if host_isa != "x86_64":
891            return False
892
893        if not have_kvm_xsave:
894            print("KVM on x86 requires xsave support in kernel headers.")
895            return False
896
897        return True
898    else:
899        return False
900
901
902# Check if the exclude_host attribute is available. We want this to
903# get accurate instruction counts in KVM.
904main['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
905    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
906
907
908######################################################################
909#
910# Finish the configuration
911#
912main = conf.Finish()
913
914######################################################################
915#
916# Collect all non-global variables
917#
918
919# Define the universe of supported ISAs
920all_isa_list = [ ]
921all_gpu_isa_list = [ ]
922Export('all_isa_list')
923Export('all_gpu_isa_list')
924
925class CpuModel(object):
926    '''The CpuModel class encapsulates everything the ISA parser needs to
927    know about a particular CPU model.'''
928
929    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
930    dict = {}
931
932    # Constructor.  Automatically adds models to CpuModel.dict.
933    def __init__(self, name, default=False):
934        self.name = name           # name of model
935
936        # This cpu is enabled by default
937        self.default = default
938
939        # Add self to dict
940        if name in CpuModel.dict:
941            raise AttributeError, "CpuModel '%s' already registered" % name
942        CpuModel.dict[name] = self
943
944Export('CpuModel')
945
946# Sticky variables get saved in the variables file so they persist from
947# one invocation to the next (unless overridden, in which case the new
948# value becomes sticky).
949sticky_vars = Variables(args=ARGUMENTS)
950Export('sticky_vars')
951
952# Sticky variables that should be exported
953export_vars = []
954Export('export_vars')
955
956# For Ruby
957all_protocols = []
958Export('all_protocols')
959protocol_dirs = []
960Export('protocol_dirs')
961slicc_includes = []
962Export('slicc_includes')
963
964# Walk the tree and execute all SConsopts scripts that wil add to the
965# above variables
966if GetOption('verbose'):
967    print("Reading SConsopts")
968for bdir in [ base_dir ] + extras_dir_list:
969    if not isdir(bdir):
970        print("Error: directory '%s' does not exist" % bdir)
971        Exit(1)
972    for root, dirs, files in os.walk(bdir):
973        if 'SConsopts' in files:
974            if GetOption('verbose'):
975                print("Reading", joinpath(root, 'SConsopts'))
976            SConscript(joinpath(root, 'SConsopts'))
977
978all_isa_list.sort()
979all_gpu_isa_list.sort()
980
981sticky_vars.AddVariables(
982    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
983    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
984    ListVariable('CPU_MODELS', 'CPU models',
985                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
986                 sorted(CpuModel.dict.keys())),
987    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
988                 False),
989    BoolVariable('SS_COMPATIBLE_FP',
990                 'Make floating-point results compatible with SimpleScalar',
991                 False),
992    BoolVariable('USE_SSE2',
993                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
994                 False),
995    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
996    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
997    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
998    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
999                 False),
1000    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
1001                 have_kvm),
1002    BoolVariable('USE_TUNTAP',
1003                 'Enable using a tap device to bridge to the host network',
1004                 have_tuntap),
1005    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
1006    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1007                  all_protocols),
1008    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
1009                 backtrace_impls[-1], backtrace_impls)
1010    )
1011
1012# These variables get exported to #defines in config/*.hh (see src/SConscript).
1013export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
1014                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
1015                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST',
1016                'USE_PNG']
1017
1018###################################################
1019#
1020# Define a SCons builder for configuration flag headers.
1021#
1022###################################################
1023
1024# This function generates a config header file that #defines the
1025# variable symbol to the current variable setting (0 or 1).  The source
1026# operands are the name of the variable and a Value node containing the
1027# value of the variable.
1028def build_config_file(target, source, env):
1029    (variable, value) = [s.get_contents() for s in source]
1030    f = file(str(target[0]), 'w')
1031    print('#define', variable, value, file=f)
1032    f.close()
1033    return None
1034
1035# Combine the two functions into a scons Action object.
1036config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1037
1038# The emitter munges the source & target node lists to reflect what
1039# we're really doing.
1040def config_emitter(target, source, env):
1041    # extract variable name from Builder arg
1042    variable = str(target[0])
1043    # True target is config header file
1044    target = joinpath('config', variable.lower() + '.hh')
1045    val = env[variable]
1046    if isinstance(val, bool):
1047        # Force value to 0/1
1048        val = int(val)
1049    elif isinstance(val, str):
1050        val = '"' + val + '"'
1051
1052    # Sources are variable name & value (packaged in SCons Value nodes)
1053    return ([target], [Value(variable), Value(val)])
1054
1055config_builder = Builder(emitter = config_emitter, action = config_action)
1056
1057main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1058
1059###################################################
1060#
1061# Builders for static and shared partially linked object files.
1062#
1063###################################################
1064
1065partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1066                                 src_suffix='$OBJSUFFIX',
1067                                 src_builder=['StaticObject', 'Object'],
1068                                 LINKFLAGS='$PLINKFLAGS',
1069                                 LIBS='')
1070
1071def partial_shared_emitter(target, source, env):
1072    for tgt in target:
1073        tgt.attributes.shared = 1
1074    return (target, source)
1075partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1076                                 emitter=partial_shared_emitter,
1077                                 src_suffix='$SHOBJSUFFIX',
1078                                 src_builder='SharedObject',
1079                                 SHLINKFLAGS='$PSHLINKFLAGS',
1080                                 LIBS='')
1081
1082main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1083                         'PartialStatic' : partial_static_builder })
1084
1085# builds in ext are shared across all configs in the build root.
1086ext_dir = abspath(joinpath(str(main.root), 'ext'))
1087ext_build_dirs = []
1088for root, dirs, files in os.walk(ext_dir):
1089    if 'SConscript' in files:
1090        build_dir = os.path.relpath(root, ext_dir)
1091        ext_build_dirs.append(build_dir)
1092        main.SConscript(joinpath(root, 'SConscript'),
1093                        variant_dir=joinpath(build_root, build_dir))
1094
1095main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1096
1097###################################################
1098#
1099# This builder and wrapper method are used to set up a directory with
1100# switching headers. Those are headers which are in a generic location and
1101# that include more specific headers from a directory chosen at build time
1102# based on the current build settings.
1103#
1104###################################################
1105
1106def build_switching_header(target, source, env):
1107    path = str(target[0])
1108    subdir = str(source[0])
1109    dp, fp = os.path.split(path)
1110    dp = os.path.relpath(os.path.realpath(dp),
1111                         os.path.realpath(env['BUILDDIR']))
1112    with open(path, 'w') as hdr:
1113        print('#include "%s/%s/%s"' % (dp, subdir, fp), file=hdr)
1114
1115switching_header_action = MakeAction(build_switching_header,
1116                                     Transform('GENERATE'))
1117
1118switching_header_builder = Builder(action=switching_header_action,
1119                                   source_factory=Value,
1120                                   single_source=True)
1121
1122main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1123
1124def switching_headers(self, headers, source):
1125    for header in headers:
1126        self.SwitchingHeader(header, source)
1127
1128main.AddMethod(switching_headers, 'SwitchingHeaders')
1129
1130###################################################
1131#
1132# Define build environments for selected configurations.
1133#
1134###################################################
1135
1136for variant_path in variant_paths:
1137    if not GetOption('silent'):
1138        print("Building in", variant_path)
1139
1140    # Make a copy of the build-root environment to use for this config.
1141    env = main.Clone()
1142    env['BUILDDIR'] = variant_path
1143
1144    # variant_dir is the tail component of build path, and is used to
1145    # determine the build parameters (e.g., 'ALPHA_SE')
1146    (build_root, variant_dir) = splitpath(variant_path)
1147
1148    # Set env variables according to the build directory config.
1149    sticky_vars.files = []
1150    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1151    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1152    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1153    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1154    if isfile(current_vars_file):
1155        sticky_vars.files.append(current_vars_file)
1156        if not GetOption('silent'):
1157            print("Using saved variables file %s" % current_vars_file)
1158    elif variant_dir in ext_build_dirs:
1159        # Things in ext are built without a variant directory.
1160        continue
1161    else:
1162        # Build dir-specific variables file doesn't exist.
1163
1164        # Make sure the directory is there so we can create it later
1165        opt_dir = dirname(current_vars_file)
1166        if not isdir(opt_dir):
1167            mkdir(opt_dir)
1168
1169        # Get default build variables from source tree.  Variables are
1170        # normally determined by name of $VARIANT_DIR, but can be
1171        # overridden by '--default=' arg on command line.
1172        default = GetOption('default')
1173        opts_dir = joinpath(main.root.abspath, 'build_opts')
1174        if default:
1175            default_vars_files = [joinpath(build_root, 'variables', default),
1176                                  joinpath(opts_dir, default)]
1177        else:
1178            default_vars_files = [joinpath(opts_dir, variant_dir)]
1179        existing_files = filter(isfile, default_vars_files)
1180        if existing_files:
1181            default_vars_file = existing_files[0]
1182            sticky_vars.files.append(default_vars_file)
1183            print("Variables file %s not found,\n  using defaults in %s"
1184                  % (current_vars_file, default_vars_file))
1185        else:
1186            print("Error: cannot find variables file %s or "
1187                  "default file(s) %s"
1188                  % (current_vars_file, ' or '.join(default_vars_files)))
1189            Exit(1)
1190
1191    # Apply current variable settings to env
1192    sticky_vars.Update(env)
1193
1194    help_texts["local_vars"] += \
1195        "Build variables for %s:\n" % variant_dir \
1196                 + sticky_vars.GenerateHelpText(env)
1197
1198    # Process variable settings.
1199
1200    if not have_fenv and env['USE_FENV']:
1201        print("Warning: <fenv.h> not available; "
1202              "forcing USE_FENV to False in", variant_dir + ".")
1203        env['USE_FENV'] = False
1204
1205    if not env['USE_FENV']:
1206        print("Warning: No IEEE FP rounding mode control in",
1207              variant_dir + ".")
1208        print("         FP results may deviate slightly from other platforms.")
1209
1210    if not have_png and env['USE_PNG']:
1211        print("Warning: <png.h> not available; "
1212              "forcing USE_PNG to False in", variant_dir + ".")
1213        env['USE_PNG'] = False
1214
1215    if env['USE_PNG']:
1216        env.Append(LIBS=['png'])
1217
1218    if env['EFENCE']:
1219        env.Append(LIBS=['efence'])
1220
1221    if env['USE_KVM']:
1222        if not have_kvm:
1223            print("Warning: Can not enable KVM, host seems to "
1224                  "lack KVM support")
1225            env['USE_KVM'] = False
1226        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1227            print("Info: KVM support disabled due to unsupported host and "
1228                  "target ISA combination")
1229            env['USE_KVM'] = False
1230
1231    if env['USE_TUNTAP']:
1232        if not have_tuntap:
1233            print("Warning: Can't connect EtherTap with a tap device.")
1234            env['USE_TUNTAP'] = False
1235
1236    if env['BUILD_GPU']:
1237        env.Append(CPPDEFINES=['BUILD_GPU'])
1238
1239    # Warn about missing optional functionality
1240    if env['USE_KVM']:
1241        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1242            print("Warning: perf_event headers lack support for the "
1243                  "exclude_host attribute. KVM instruction counts will "
1244                  "be inaccurate.")
1245
1246    # Save sticky variable settings back to current variables file
1247    sticky_vars.Save(current_vars_file, env)
1248
1249    if env['USE_SSE2']:
1250        env.Append(CCFLAGS=['-msse2'])
1251
1252    # The src/SConscript file sets up the build rules in 'env' according
1253    # to the configured variables.  It returns a list of environments,
1254    # one for each variant build (debug, opt, etc.)
1255    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1256
1257# base help text
1258Help('''
1259Usage: scons [scons options] [build variables] [target(s)]
1260
1261Extra scons options:
1262%(options)s
1263
1264Global build variables:
1265%(global_vars)s
1266
1267%(local_vars)s
1268''' % help_texts)
1269