SConstruct revision 12563
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2013, 2015-2017 ARM Limited
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
282665Ssaidi@eecs.umich.edu# contributors may be used to endorse or promote products derived from
292665Ssaidi@eecs.umich.edu# this software without specific prior written permission.
30955SN/A#
31955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
352632Sstever@eecs.umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
362632Sstever@eecs.umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
372632Sstever@eecs.umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
382632Sstever@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
402632Sstever@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
412632Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422761Sstever@eecs.umich.edu#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452632Sstever@eecs.umich.edu
462761Sstever@eecs.umich.edu###################################################
472761Sstever@eecs.umich.edu#
482761Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492632Sstever@eecs.umich.edu#
502632Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512761Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
522761Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532761Sstever@eecs.umich.edu# the optimized full-system version).
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
562632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572632Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582632Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
63955SN/A#   scons to search up the directory tree for this SConstruct file.
64955SN/A#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
65955SN/A#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
683918Ssaidi@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
694202Sbinkertn@umich.edu#   scons to chdir to the specified directory to find this SConstruct
703716Sstever@eecs.umich.edu#   file.
71955SN/A#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
722656Sstever@eecs.umich.edu#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
732656Sstever@eecs.umich.edu#
742656Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
752656Sstever@eecs.umich.edu# 'gem5' directory (or use -u or -C to tell scons where to find this
762656Sstever@eecs.umich.edu# file), you can use 'scons -h' to print all the gem5-specific build
772656Sstever@eecs.umich.edu# options as well.
782656Sstever@eecs.umich.edu#
792653Sstever@eecs.umich.edu###################################################
802653Sstever@eecs.umich.edu
812653Sstever@eecs.umich.edufrom __future__ import print_function
822653Sstever@eecs.umich.edu
832653Sstever@eecs.umich.edu# Global Python includes
842653Sstever@eecs.umich.eduimport itertools
852653Sstever@eecs.umich.eduimport os
862653Sstever@eecs.umich.eduimport re
872653Sstever@eecs.umich.eduimport shutil
882653Sstever@eecs.umich.eduimport subprocess
892653Sstever@eecs.umich.eduimport sys
901852SN/A
91955SN/Afrom os import mkdir, environ
92955SN/Afrom os.path import abspath, basename, dirname, expanduser, normpath
93955SN/Afrom os.path import exists,  isdir, isfile
943717Sstever@eecs.umich.edufrom os.path import join as joinpath, split as splitpath
953716Sstever@eecs.umich.edu
96955SN/A# SCons includes
971533SN/Aimport SCons
983716Sstever@eecs.umich.eduimport SCons.Node
991533SN/A
100955SN/Afrom m5.util import compareVersions, readCommand
101955SN/A
1022632Sstever@eecs.umich.eduhelp_texts = {
1032632Sstever@eecs.umich.edu    "options" : "",
104955SN/A    "global_vars" : "",
105955SN/A    "local_vars" : ""
106955SN/A}
107955SN/A
1082632Sstever@eecs.umich.eduExport("help_texts")
109955SN/A
1102632Sstever@eecs.umich.edu
1112632Sstever@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1122632Sstever@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1132632Sstever@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1142632Sstever@eecs.umich.edu# Help() function, but these two features are incompatible: once
1152632Sstever@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1162632Sstever@eecs.umich.edu# at the help texts from AddOptions.  See:
1173053Sstever@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1183053Sstever@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1193053Sstever@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1203053Sstever@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1213053Sstever@eecs.umich.edu# we can just use AddOption directly.
1223053Sstever@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1233053Sstever@eecs.umich.edu    col_width = 30
1243053Sstever@eecs.umich.edu
1253053Sstever@eecs.umich.edu    help = "  " + ", ".join(args)
1263053Sstever@eecs.umich.edu    if "help" in kwargs:
1273053Sstever@eecs.umich.edu        length = len(help)
1283053Sstever@eecs.umich.edu        if length >= col_width:
1293053Sstever@eecs.umich.edu            help += "\n" + " " * col_width
1303053Sstever@eecs.umich.edu        else:
1313053Sstever@eecs.umich.edu            help += " " * (col_width - length)
1323053Sstever@eecs.umich.edu        help += kwargs["help"]
1332632Sstever@eecs.umich.edu    help_texts["options"] += help + "\n"
1342632Sstever@eecs.umich.edu
1352632Sstever@eecs.umich.edu    AddOption(*args, **kwargs)
1362632Sstever@eecs.umich.edu
1372632Sstever@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1382632Sstever@eecs.umich.edu               help="Add color to abbreviated scons output")
1393718Sstever@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1403718Sstever@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1413718Sstever@eecs.umich.eduAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1423718Sstever@eecs.umich.edu               action='store_true',
1433718Sstever@eecs.umich.edu               help="Build with support for C++-based configuration")
1443718Sstever@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1453718Sstever@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1463718Sstever@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1473718Sstever@eecs.umich.edu               help='Disable style checking hooks')
1483718Sstever@eecs.umich.eduAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1493718Sstever@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1503718Sstever@eecs.umich.eduAddLocalOption('--force-lto', dest='force_lto', action='store_true',
1513718Sstever@eecs.umich.edu               help='Use Link-Time Optimization instead of partial linking' +
1522634Sstever@eecs.umich.edu                    ' when the compiler doesn\'t support using them together.')
1532634Sstever@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1542632Sstever@eecs.umich.edu               help='Update test reference outputs')
1552638Sstever@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1562632Sstever@eecs.umich.edu               help='Print full tool command lines')
1572632Sstever@eecs.umich.eduAddLocalOption('--without-python', dest='without_python',
1582632Sstever@eecs.umich.edu               action='store_true',
1592632Sstever@eecs.umich.edu               help='Build without Python configuration support')
1602632Sstever@eecs.umich.eduAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1612632Sstever@eecs.umich.edu               action='store_true',
1621858SN/A               help='Disable linking against tcmalloc')
1633716Sstever@eecs.umich.eduAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1642638Sstever@eecs.umich.edu               help='Build with Undefined Behavior Sanitizer if available')
1652638Sstever@eecs.umich.eduAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1662638Sstever@eecs.umich.edu               help='Build with Address Sanitizer if available')
1672638Sstever@eecs.umich.edu
1682638Sstever@eecs.umich.eduif GetOption('no_lto') and GetOption('force_lto'):
1692638Sstever@eecs.umich.edu    print('--no-lto and --force-lto are mutually exclusive')
1702638Sstever@eecs.umich.edu    Exit(1)
1713716Sstever@eecs.umich.edu
1722634Sstever@eecs.umich.edu########################################################################
1732634Sstever@eecs.umich.edu#
174955SN/A# Set up the main build environment.
175955SN/A#
176955SN/A########################################################################
177955SN/A
178955SN/Amain = Environment()
179955SN/A
180955SN/Afrom gem5_scons import Transform
181955SN/Afrom gem5_scons.util import get_termcap
1821858SN/Atermcap = get_termcap()
1831858SN/A
1842632Sstever@eecs.umich.edumain_dict_keys = main.Dictionary().keys()
1854202Sbinkertn@umich.edu
186955SN/A# Check that we have a C/C++ compiler
1873643Ssaidi@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
1883643Ssaidi@eecs.umich.edu    print("No C++ compiler installed (package g++ on Ubuntu and RedHat)")
1893643Ssaidi@eecs.umich.edu    Exit(1)
1903643Ssaidi@eecs.umich.edu
1913643Ssaidi@eecs.umich.edu###################################################
1923643Ssaidi@eecs.umich.edu#
1933643Ssaidi@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
1943643Ssaidi@eecs.umich.edu# the target(s).
1953716Sstever@eecs.umich.edu#
1961105SN/A###################################################
1972667Sstever@eecs.umich.edu
1982667Sstever@eecs.umich.edu# Find default configuration & binary.
1992667Sstever@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2002667Sstever@eecs.umich.edu
2012667Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
2022667Sstever@eecs.umich.edudef rfind(l, elt, offs = -1):
2031869SN/A    for i in range(len(l)+offs, 0, -1):
2041869SN/A        if l[i] == elt:
2051869SN/A            return i
2061869SN/A    raise ValueError, "element not found"
2071869SN/A
2081065SN/A# Take a list of paths (or SCons Nodes) and return a list with all
2092632Sstever@eecs.umich.edu# paths made absolute and ~-expanded.  Paths will be interpreted
2102632Sstever@eecs.umich.edu# relative to the launch directory unless a different root is provided
2113918Ssaidi@eecs.umich.edudef makePathListAbsolute(path_list, root=GetLaunchDir()):
2123918Ssaidi@eecs.umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
2133940Ssaidi@eecs.umich.edu            for p in path_list]
2143918Ssaidi@eecs.umich.edu
2153918Ssaidi@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
2163918Ssaidi@eecs.umich.edu# directory below this will determine the build parameters.  For
2173918Ssaidi@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2183918Ssaidi@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
2193918Ssaidi@eecs.umich.edu# follow 'build' in the build path.
2203940Ssaidi@eecs.umich.edu
2213940Ssaidi@eecs.umich.edu# The funky assignment to "[:]" is needed to replace the list contents
2223940Ssaidi@eecs.umich.edu# in place rather than reassign the symbol to a new list, which
2233942Ssaidi@eecs.umich.edu# doesn't work (obviously!).
2243940Ssaidi@eecs.umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2253918Ssaidi@eecs.umich.edu
2263918Ssaidi@eecs.umich.edu# Generate a list of the unique build roots and configs that the
227955SN/A# collected targets reference.
2281858SN/Avariant_paths = []
2293918Ssaidi@eecs.umich.edubuild_root = None
2303918Ssaidi@eecs.umich.edufor t in BUILD_TARGETS:
2313918Ssaidi@eecs.umich.edu    path_dirs = t.split('/')
2323918Ssaidi@eecs.umich.edu    try:
2333940Ssaidi@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
2343940Ssaidi@eecs.umich.edu    except:
2353918Ssaidi@eecs.umich.edu        print("Error: no non-leaf 'build' dir found on target path", t)
2363918Ssaidi@eecs.umich.edu        Exit(1)
2373918Ssaidi@eecs.umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2383918Ssaidi@eecs.umich.edu    if not build_root:
2393918Ssaidi@eecs.umich.edu        build_root = this_build_root
2403918Ssaidi@eecs.umich.edu    else:
2413918Ssaidi@eecs.umich.edu        if this_build_root != build_root:
2423918Ssaidi@eecs.umich.edu            print("Error: build targets not under same build root\n"
2433918Ssaidi@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root))
2443940Ssaidi@eecs.umich.edu            Exit(1)
2453918Ssaidi@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
2463918Ssaidi@eecs.umich.edu    if variant_path not in variant_paths:
2471851SN/A        variant_paths.append(variant_path)
2481851SN/A
2491858SN/A# Make sure build_root exists (might not if this is the first build there)
2502632Sstever@eecs.umich.eduif not isdir(build_root):
251955SN/A    mkdir(build_root)
2523053Sstever@eecs.umich.edumain['BUILDROOT'] = build_root
2533053Sstever@eecs.umich.edu
2543053Sstever@eecs.umich.eduExport('main')
2553053Sstever@eecs.umich.edu
2563053Sstever@eecs.umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
2573053Sstever@eecs.umich.edu
2583053Sstever@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
2593053Sstever@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
2603053Sstever@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
2613053Sstever@eecs.umich.edu# (soft) links work better.
2623053Sstever@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
2633053Sstever@eecs.umich.edu
2643053Sstever@eecs.umich.edu#
2653053Sstever@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
2663053Sstever@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
2673053Sstever@eecs.umich.edu#
2683053Sstever@eecs.umich.edu
2693053Sstever@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
2703053Sstever@eecs.umich.edu
2712667Sstever@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2722667Sstever@eecs.umich.edu
2732667Sstever@eecs.umich.eduglobal_vars.AddVariables(
2742667Sstever@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2752667Sstever@eecs.umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2762667Sstever@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2772667Sstever@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
2782667Sstever@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2792667Sstever@eecs.umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
2802667Sstever@eecs.umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
2812667Sstever@eecs.umich.edu    )
2822667Sstever@eecs.umich.edu
2832638Sstever@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
2842638Sstever@eecs.umich.eduglobal_vars.Update(main)
2852638Sstever@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
2863716Sstever@eecs.umich.edu
2873716Sstever@eecs.umich.edu# Save sticky variable settings back to current variables file
2881858SN/Aglobal_vars.Save(global_vars_file, main)
2893118Sstever@eecs.umich.edu
2903118Sstever@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
2913118Sstever@eecs.umich.edu# look for sources etc.  This list is exported as extras_dir_list.
2923118Sstever@eecs.umich.edubase_dir = main.srcdir.abspath
2933118Sstever@eecs.umich.eduif main['EXTRAS']:
2943118Sstever@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
2953118Sstever@eecs.umich.eduelse:
2963118Sstever@eecs.umich.edu    extras_dir_list = []
2973118Sstever@eecs.umich.edu
2983118Sstever@eecs.umich.eduExport('base_dir')
2993118Sstever@eecs.umich.eduExport('extras_dir_list')
3003716Sstever@eecs.umich.edu
3013118Sstever@eecs.umich.edu# the ext directory should be on the #includes path
3023118Sstever@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
3033118Sstever@eecs.umich.edu
3043118Sstever@eecs.umich.edu# Add shared top-level headers
3053118Sstever@eecs.umich.edumain.Prepend(CPPPATH=Dir('include'))
3063118Sstever@eecs.umich.edu
3073118Sstever@eecs.umich.eduif GetOption('verbose'):
3083118Sstever@eecs.umich.edu    def MakeAction(action, string, *args, **kwargs):
3093118Sstever@eecs.umich.edu        return Action(action, *args, **kwargs)
3103716Sstever@eecs.umich.eduelse:
3113118Sstever@eecs.umich.edu    MakeAction = Action
3123118Sstever@eecs.umich.edu    main['CCCOMSTR']        = Transform("CC")
3133118Sstever@eecs.umich.edu    main['CXXCOMSTR']       = Transform("CXX")
3143118Sstever@eecs.umich.edu    main['ASCOMSTR']        = Transform("AS")
3153118Sstever@eecs.umich.edu    main['ARCOMSTR']        = Transform("AR", 0)
3163118Sstever@eecs.umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
3173118Sstever@eecs.umich.edu    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
3183118Sstever@eecs.umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
3193118Sstever@eecs.umich.edu    main['M4COMSTR']        = Transform("M4")
3203118Sstever@eecs.umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
3213483Ssaidi@eecs.umich.edu    main['SHCXXCOMSTR']     = Transform("SHCXX")
3223494Ssaidi@eecs.umich.eduExport('MakeAction')
3233494Ssaidi@eecs.umich.edu
3243483Ssaidi@eecs.umich.edu# Initialize the Link-Time Optimization (LTO) flags
3253483Ssaidi@eecs.umich.edumain['LTO_CCFLAGS'] = []
3263483Ssaidi@eecs.umich.edumain['LTO_LDFLAGS'] = []
3273053Sstever@eecs.umich.edu
3283053Sstever@eecs.umich.edu# According to the readme, tcmalloc works best if the compiler doesn't
3293918Ssaidi@eecs.umich.edu# assume that we're using the builtin malloc and friends. These flags
3303053Sstever@eecs.umich.edu# are compiler-specific, so we need to set them after we detect which
3313053Sstever@eecs.umich.edu# compiler we're using.
3323053Sstever@eecs.umich.edumain['TCMALLOC_CCFLAGS'] = []
3333053Sstever@eecs.umich.edu
3343053Sstever@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
3351858SN/ACXX_V = readCommand([main['CXX'],'-V'], exception=False)
3361858SN/A
3371858SN/Amain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3381858SN/Amain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
3391858SN/Aif main['GCC'] + main['CLANG'] > 1:
3401858SN/A    print('Error: How can we have two at the same time?')
3411859SN/A    Exit(1)
3421858SN/A
3431858SN/A# Set up default C++ compiler flags
3441858SN/Aif main['GCC'] or main['CLANG']:
3451859SN/A    # As gcc and clang share many flags, do the common parts here
3461859SN/A    main.Append(CCFLAGS=['-pipe'])
3471862SN/A    main.Append(CCFLAGS=['-fno-strict-aliasing'])
3483053Sstever@eecs.umich.edu    # Enable -Wall and -Wextra and then disable the few warnings that
3493053Sstever@eecs.umich.edu    # we consistently violate
3503053Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
3513053Sstever@eecs.umich.edu                         '-Wno-sign-compare', '-Wno-unused-parameter'])
3521859SN/A    # We always compile using C++11
3531859SN/A    main.Append(CXXFLAGS=['-std=c++11'])
3541859SN/A    if sys.platform.startswith('freebsd'):
3551859SN/A        main.Append(CCFLAGS=['-I/usr/local/include'])
3561859SN/A        main.Append(CXXFLAGS=['-I/usr/local/include'])
3571859SN/A
3581859SN/A    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
3591859SN/A    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
3601862SN/A    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3611859SN/A    shared_partial_flags = ['-r', '-nostdlib']
3621859SN/A    main.Append(PSHLINKFLAGS=shared_partial_flags)
3631859SN/A    main.Append(PLINKFLAGS=shared_partial_flags)
3641858SN/A
3651858SN/A    # Treat warnings as errors but white list some warnings that we
3662139SN/A    # want to allow (e.g., deprecation warnings).
3674202Sbinkertn@umich.edu    main.Append(CCFLAGS=['-Werror',
3684202Sbinkertn@umich.edu                         '-Wno-error=deprecated-declarations',
3692139SN/A                         '-Wno-error=deprecated',
3702155SN/A                        ])
3714202Sbinkertn@umich.eduelse:
3724202Sbinkertn@umich.edu    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
3734202Sbinkertn@umich.edu    print("Don't know what compiler options to use for your compiler.")
3742155SN/A    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
3751869SN/A    print(termcap.Yellow + '       version:' + termcap.Normal, end = ' ')
3761869SN/A    if not CXX_version:
3771869SN/A        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
3781869SN/A              termcap.Normal)
3794202Sbinkertn@umich.edu    else:
3804202Sbinkertn@umich.edu        print(CXX_version.replace('\n', '<nl>'))
3814202Sbinkertn@umich.edu    print("       If you're trying to use a compiler other than GCC")
3824202Sbinkertn@umich.edu    print("       or clang, there appears to be something wrong with your")
3834202Sbinkertn@umich.edu    print("       environment.")
3844202Sbinkertn@umich.edu    print("       ")
3854202Sbinkertn@umich.edu    print("       If you are trying to use a compiler other than those listed")
3864202Sbinkertn@umich.edu    print("       above you will need to ease fix SConstruct and ")
3874202Sbinkertn@umich.edu    print("       src/SConscript to support that compiler.")
3884202Sbinkertn@umich.edu    Exit(1)
3894202Sbinkertn@umich.edu
3904202Sbinkertn@umich.eduif main['GCC']:
3914202Sbinkertn@umich.edu    # Check for a supported version of gcc. >= 4.8 is chosen for its
3924202Sbinkertn@umich.edu    # level of c++11 support. See
3934202Sbinkertn@umich.edu    # http://gcc.gnu.org/projects/cxx0x.html for details.
3944202Sbinkertn@umich.edu    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
3951869SN/A    if compareVersions(gcc_version, "4.8") < 0:
3964202Sbinkertn@umich.edu        print('Error: gcc version 4.8 or newer required.')
3971869SN/A        print('       Installed version: ', gcc_version)
3982508SN/A        Exit(1)
3992508SN/A
4002508SN/A    main['GCC_VERSION'] = gcc_version
4012508SN/A
4024202Sbinkertn@umich.edu    if compareVersions(gcc_version, '4.9') >= 0:
4031869SN/A        # Incremental linking with LTO is currently broken in gcc versions
4041869SN/A        # 4.9 and above. A version where everything works completely hasn't
4051869SN/A        # yet been identified.
4061869SN/A        #
4071869SN/A        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
4081869SN/A        main['BROKEN_INCREMENTAL_LTO'] = True
4091965SN/A    if compareVersions(gcc_version, '6.0') >= 0:
4101965SN/A        # gcc versions 6.0 and greater accept an -flinker-output flag which
4111965SN/A        # selects what type of output the linker should generate. This is
4121869SN/A        # necessary for incremental lto to work, but is also broken in
4131869SN/A        # current versions of gcc. It may not be necessary in future
4142733Sktlim@umich.edu        # versions. We add it here since it might be, and as a reminder that
4151869SN/A        # it exists. It's excluded if lto is being forced.
4161884SN/A        #
4171884SN/A        # https://gcc.gnu.org/gcc-6/changes.html
4183356Sbinkertn@umich.edu        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
4193356Sbinkertn@umich.edu        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
4203356Sbinkertn@umich.edu        if not GetOption('force_lto'):
4213356Sbinkertn@umich.edu            main.Append(PSHLINKFLAGS='-flinker-output=rel')
4221869SN/A            main.Append(PLINKFLAGS='-flinker-output=rel')
4231858SN/A
4241869SN/A    # gcc from version 4.8 and above generates "rep; ret" instructions
4251869SN/A    # to avoid performance penalties on certain AMD chips. Older
4261869SN/A    # assemblers detect this as an error, "Error: expecting string
4271858SN/A    # instruction after `rep'"
4282761Sstever@eecs.umich.edu    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
4291869SN/A                                  '-o', '/dev/null'],
4302733Sktlim@umich.edu                                 exception=False).split()
4313584Ssaidi@eecs.umich.edu
4321869SN/A    # version strings may contain extra distro-specific
4331869SN/A    # qualifiers, so play it safe and keep only what comes before
4341869SN/A    # the first hyphen
4351869SN/A    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
4361869SN/A
4371869SN/A    if not as_version or compareVersions(as_version, "2.23") < 0:
4381858SN/A        print(termcap.Yellow + termcap.Bold +
439955SN/A            'Warning: This combination of gcc and binutils have' +
440955SN/A            ' known incompatibilities.\n' +
4411869SN/A            '         If you encounter build problems, please update ' +
4421869SN/A            'binutils to 2.23.' +
4431869SN/A            termcap.Normal)
4441869SN/A
4451869SN/A    # Make sure we warn if the user has requested to compile with the
4461869SN/A    # Undefined Benahvior Sanitizer and this version of gcc does not
4471869SN/A    # support it.
4481869SN/A    if GetOption('with_ubsan') and \
4491869SN/A            compareVersions(gcc_version, '4.9') < 0:
4501869SN/A        print(termcap.Yellow + termcap.Bold +
4511869SN/A            'Warning: UBSan is only supported using gcc 4.9 and later.' +
4521869SN/A            termcap.Normal)
4531869SN/A
4541869SN/A    disable_lto = GetOption('no_lto')
4551869SN/A    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
4561869SN/A            not GetOption('force_lto'):
4571869SN/A        print(termcap.Yellow + termcap.Bold +
4581869SN/A            'Warning: Your compiler doesn\'t support incremental linking' +
4591869SN/A            ' and lto at the same time, so lto is being disabled. To force' +
4601869SN/A            ' lto on anyway, use the --force-lto option. That will disable' +
4611869SN/A            ' partial linking.' +
4621869SN/A            termcap.Normal)
4631869SN/A        disable_lto = True
4641869SN/A
4651869SN/A    # Add the appropriate Link-Time Optimization (LTO) flags
4661869SN/A    # unless LTO is explicitly turned off. Note that these flags
4671869SN/A    # are only used by the fast target.
4681869SN/A    if not disable_lto:
4691869SN/A        # Pass the LTO flag when compiling to produce GIMPLE
4703716Sstever@eecs.umich.edu        # output, we merely create the flags here and only append
4713356Sbinkertn@umich.edu        # them later
4723356Sbinkertn@umich.edu        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4733356Sbinkertn@umich.edu
4743356Sbinkertn@umich.edu        # Use the same amount of jobs for LTO as we are running
4753356Sbinkertn@umich.edu        # scons with
4763356Sbinkertn@umich.edu        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4773356Sbinkertn@umich.edu
4781869SN/A    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
4791869SN/A                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4801869SN/A
4811869SN/A    # add option to check for undeclared overrides
4821869SN/A    if compareVersions(gcc_version, "5.0") > 0:
4831869SN/A        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
4841869SN/A
4852655Sstever@eecs.umich.edu    # The address sanitizer is available for gcc >= 4.8
4862655Sstever@eecs.umich.edu    if GetOption('with_asan'):
4872655Sstever@eecs.umich.edu        if GetOption('with_ubsan') and \
4882655Sstever@eecs.umich.edu                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
4892655Sstever@eecs.umich.edu            env.Append(CCFLAGS=['-fsanitize=address,undefined',
4902655Sstever@eecs.umich.edu                                '-fno-omit-frame-pointer'],
4912655Sstever@eecs.umich.edu                       LINKFLAGS='-fsanitize=address,undefined')
4922655Sstever@eecs.umich.edu        else:
4932655Sstever@eecs.umich.edu            env.Append(CCFLAGS=['-fsanitize=address',
4942655Sstever@eecs.umich.edu                                '-fno-omit-frame-pointer'],
4952655Sstever@eecs.umich.edu                       LINKFLAGS='-fsanitize=address')
4962655Sstever@eecs.umich.edu    # Only gcc >= 4.9 supports UBSan, so check both the version
4972655Sstever@eecs.umich.edu    # and the command-line option before adding the compiler and
4982655Sstever@eecs.umich.edu    # linker flags.
4992655Sstever@eecs.umich.edu    elif GetOption('with_ubsan') and \
5002655Sstever@eecs.umich.edu            compareVersions(env['GCC_VERSION'], '4.9') >= 0:
5012655Sstever@eecs.umich.edu        env.Append(CCFLAGS='-fsanitize=undefined')
5022655Sstever@eecs.umich.edu        env.Append(LINKFLAGS='-fsanitize=undefined')
5032655Sstever@eecs.umich.edu
5042655Sstever@eecs.umich.eduelif main['CLANG']:
5052655Sstever@eecs.umich.edu    # Check for a supported version of clang, >= 3.1 is needed to
5062655Sstever@eecs.umich.edu    # support similar features as gcc 4.8. See
5072655Sstever@eecs.umich.edu    # http://clang.llvm.org/cxx_status.html for details
5082655Sstever@eecs.umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
5092655Sstever@eecs.umich.edu    clang_version_match = clang_version_re.search(CXX_version)
5102655Sstever@eecs.umich.edu    if (clang_version_match):
5112634Sstever@eecs.umich.edu        clang_version = clang_version_match.groups()[0]
5122634Sstever@eecs.umich.edu        if compareVersions(clang_version, "3.1") < 0:
5132634Sstever@eecs.umich.edu            print('Error: clang version 3.1 or newer required.')
5142634Sstever@eecs.umich.edu            print('       Installed version:', clang_version)
5152634Sstever@eecs.umich.edu            Exit(1)
5162634Sstever@eecs.umich.edu    else:
5172638Sstever@eecs.umich.edu        print('Error: Unable to determine clang version.')
5182638Sstever@eecs.umich.edu        Exit(1)
5193716Sstever@eecs.umich.edu
5202638Sstever@eecs.umich.edu    # clang has a few additional warnings that we disable, extraneous
5212638Sstever@eecs.umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
5221869SN/A    # finally self assignments are allowed as the generated CPU code
5231869SN/A    # is relying on this
5243546Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-parentheses',
5253546Sgblack@eecs.umich.edu                         '-Wno-self-assign',
5263546Sgblack@eecs.umich.edu                         # Some versions of libstdc++ (4.8?) seem to
5273546Sgblack@eecs.umich.edu                         # use struct hash and class hash
5284202Sbinkertn@umich.edu                         # interchangeably.
5293546Sgblack@eecs.umich.edu                         '-Wno-mismatched-tags',
5303546Sgblack@eecs.umich.edu                         ])
5313546Sgblack@eecs.umich.edu
5323546Sgblack@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5333546Sgblack@eecs.umich.edu
5343546Sgblack@eecs.umich.edu    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5353546Sgblack@eecs.umich.edu    # opposed to libstdc++, as the later is dated.
5363546Sgblack@eecs.umich.edu    if sys.platform == "darwin":
5373546Sgblack@eecs.umich.edu        main.Append(CXXFLAGS=['-stdlib=libc++'])
5383546Sgblack@eecs.umich.edu        main.Append(LIBS=['c++'])
5394202Sbinkertn@umich.edu
5403546Sgblack@eecs.umich.edu    # On FreeBSD we need libthr.
5413546Sgblack@eecs.umich.edu    if sys.platform.startswith('freebsd'):
5423546Sgblack@eecs.umich.edu        main.Append(LIBS=['thr'])
5433546Sgblack@eecs.umich.edu
5443546Sgblack@eecs.umich.edu    # We require clang >= 3.1, so there is no need to check any
5453546Sgblack@eecs.umich.edu    # versions here.
5463546Sgblack@eecs.umich.edu    if GetOption('with_ubsan'):
5473546Sgblack@eecs.umich.edu        if GetOption('with_asan'):
5483546Sgblack@eecs.umich.edu            env.Append(CCFLAGS=['-fsanitize=address,undefined',
5493546Sgblack@eecs.umich.edu                                '-fno-omit-frame-pointer'],
5503546Sgblack@eecs.umich.edu                       LINKFLAGS='-fsanitize=address,undefined')
5513546Sgblack@eecs.umich.edu        else:
5523546Sgblack@eecs.umich.edu            env.Append(CCFLAGS='-fsanitize=undefined',
5533546Sgblack@eecs.umich.edu                       LINKFLAGS='-fsanitize=undefined')
5543546Sgblack@eecs.umich.edu
5553546Sgblack@eecs.umich.edu    elif GetOption('with_asan'):
5563546Sgblack@eecs.umich.edu        env.Append(CCFLAGS=['-fsanitize=address',
5573546Sgblack@eecs.umich.edu                            '-fno-omit-frame-pointer'],
5583546Sgblack@eecs.umich.edu                   LINKFLAGS='-fsanitize=address')
5593546Sgblack@eecs.umich.edu
5604202Sbinkertn@umich.eduelse:
5613546Sgblack@eecs.umich.edu    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
5623546Sgblack@eecs.umich.edu    print("Don't know what compiler options to use for your compiler.")
5633546Sgblack@eecs.umich.edu    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
564955SN/A    print(termcap.Yellow + '       version:' + termcap.Normal, end=' ')
565955SN/A    if not CXX_version:
566955SN/A        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
567955SN/A              termcap.Normal)
5681858SN/A    else:
5691858SN/A        print(CXX_version.replace('\n', '<nl>'))
5701858SN/A    print("       If you're trying to use a compiler other than GCC")
5712632Sstever@eecs.umich.edu    print("       or clang, there appears to be something wrong with your")
5722632Sstever@eecs.umich.edu    print("       environment.")
5732632Sstever@eecs.umich.edu    print("       ")
5742632Sstever@eecs.umich.edu    print("       If you are trying to use a compiler other than those listed")
5752632Sstever@eecs.umich.edu    print("       above you will need to ease fix SConstruct and ")
5762634Sstever@eecs.umich.edu    print("       src/SConscript to support that compiler.")
5772638Sstever@eecs.umich.edu    Exit(1)
5782023SN/A
5792632Sstever@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
5802632Sstever@eecs.umich.edumain['YACCFLAGS'] = '-d'
5812632Sstever@eecs.umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
5822632Sstever@eecs.umich.edu
5832632Sstever@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
5843716Sstever@eecs.umich.edu# extra 'qdo' every time we run scons.
5852632Sstever@eecs.umich.eduif main['BATCH']:
5862632Sstever@eecs.umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5872632Sstever@eecs.umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5882632Sstever@eecs.umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5892632Sstever@eecs.umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5902023SN/A    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5912632Sstever@eecs.umich.edu
5922632Sstever@eecs.umich.eduif sys.platform == 'cygwin':
5931889SN/A    # cygwin has some header file issues...
5941889SN/A    main.Append(CCFLAGS=["-Wno-uninitialized"])
5952632Sstever@eecs.umich.edu
5962632Sstever@eecs.umich.edu# Check for the protobuf compiler
5972632Sstever@eecs.umich.eduprotoc_version = readCommand([main['PROTOC'], '--version'],
5982632Sstever@eecs.umich.edu                             exception='').split()
5993716Sstever@eecs.umich.edu
6003716Sstever@eecs.umich.edu# First two words should be "libprotoc x.y.z"
6012632Sstever@eecs.umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6022632Sstever@eecs.umich.edu    print(termcap.Yellow + termcap.Bold +
6032632Sstever@eecs.umich.edu        'Warning: Protocol buffer compiler (protoc) not found.\n' +
6042632Sstever@eecs.umich.edu        '         Please install protobuf-compiler for tracing support.' +
6052632Sstever@eecs.umich.edu        termcap.Normal)
6062632Sstever@eecs.umich.edu    main['PROTOC'] = False
6072632Sstever@eecs.umich.eduelse:
6082632Sstever@eecs.umich.edu    # Based on the availability of the compress stream wrappers,
6091888SN/A    # require 2.1.0
6101888SN/A    min_protoc_version = '2.1.0'
6111869SN/A    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6121869SN/A        print(termcap.Yellow + termcap.Bold +
6131858SN/A            'Warning: protoc version', min_protoc_version,
6142598SN/A            'or newer required.\n' +
6152598SN/A            '         Installed version:', protoc_version[1],
6162598SN/A            termcap.Normal)
6172598SN/A        main['PROTOC'] = False
6182598SN/A    else:
6191858SN/A        # Attempt to determine the appropriate include path and
6201858SN/A        # library path using pkg-config, that means we also need to
6211858SN/A        # check for pkg-config. Note that it is possible to use
6221858SN/A        # protobuf without the involvement of pkg-config. Later on we
6231858SN/A        # check go a library config check and at that point the test
6241858SN/A        # will fail if libprotobuf cannot be found.
6251858SN/A        if readCommand(['pkg-config', '--version'], exception=''):
6261858SN/A            try:
6271858SN/A                # Attempt to establish what linking flags to add for protobuf
6281871SN/A                # using pkg-config
6291858SN/A                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6301858SN/A            except:
6311858SN/A                print(termcap.Yellow + termcap.Bold +
6321858SN/A                    'Warning: pkg-config could not get protobuf flags.' +
6331858SN/A                    termcap.Normal)
6341858SN/A
6351858SN/A
6361858SN/A# Check for 'timeout' from GNU coreutils. If present, regressions will
6371858SN/A# be run with a time limit. We require version 8.13 since we rely on
6381858SN/A# support for the '--foreground' option.
6391858SN/Aif sys.platform.startswith('freebsd'):
6401859SN/A    timeout_lines = readCommand(['gtimeout', '--version'],
6411859SN/A                                exception='').splitlines()
6421869SN/Aelse:
6431888SN/A    timeout_lines = readCommand(['timeout', '--version'],
6442632Sstever@eecs.umich.edu                                exception='').splitlines()
6451869SN/A# Get the first line and tokenize it
6461884SN/Atimeout_version = timeout_lines[0].split() if timeout_lines else []
6471884SN/Amain['TIMEOUT'] =  timeout_version and \
6481884SN/A    compareVersions(timeout_version[-1], '8.13') >= 0
6491884SN/A
6501884SN/A# Add a custom Check function to test for structure members.
6511884SN/Adef CheckMember(context, include, decl, member, include_quotes="<>"):
6521965SN/A    context.Message("Checking for member %s in %s..." %
6531965SN/A                    (member, decl))
6541965SN/A    text = """
6552761Sstever@eecs.umich.edu#include %(header)s
6561869SN/Aint main(){
6571869SN/A  %(decl)s test;
6582632Sstever@eecs.umich.edu  (void)test.%(member)s;
6592667Sstever@eecs.umich.edu  return 0;
6601869SN/A};
6611869SN/A""" % { "header" : include_quotes[0] + include + include_quotes[1],
6622929Sktlim@umich.edu        "decl" : decl,
6632929Sktlim@umich.edu        "member" : member,
6643716Sstever@eecs.umich.edu        }
6652929Sktlim@umich.edu
666955SN/A    ret = context.TryCompile(text, extension=".cc")
6672598SN/A    context.Result(ret)
6682598SN/A    return ret
6693546Sgblack@eecs.umich.edu
670955SN/A# Platform-specific configuration.  Note again that we assume that all
671955SN/A# builds under a given build root run on the same host platform.
672955SN/Aconf = Configure(main,
6731530SN/A                 conf_dir = joinpath(build_root, '.scons_config'),
674955SN/A                 log_file = joinpath(build_root, 'scons_config.log'),
675955SN/A                 custom_tests = {
676955SN/A        '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