1#!/usr/bin/env python3 2# PYTHON_ARGCOMPLETE_OKAY 3# - 4# SPDX-License-Identifier: BSD-2-Clause 5# 6# Copyright (c) 2018 Alex Richardson <arichardson@FreeBSD.org> 7# 8# Redistribution and use in source and binary forms, with or without 9# modification, are permitted provided that the following conditions 10# are met: 11# 1. Redistributions of source code must retain the above copyright 12# notice, this list of conditions and the following disclaimer. 13# 2. Redistributions in binary form must reproduce the above copyright 14# notice, this list of conditions and the following disclaimer in the 15# documentation and/or other materials provided with the distribution. 16# 17# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 18# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 21# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 23# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 24# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 25# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 26# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 27# SUCH DAMAGE. 28# 29# 30 31# This script makes it easier to build on non-FreeBSD systems by bootstrapping 32# bmake and inferring required compiler variables. 33# 34# On FreeBSD you can use it the same way as just calling make: 35# `MAKEOBJDIRPREFIX=~/obj ./tools/build/make.py buildworld -DWITH_FOO` 36# 37# On Linux and MacOS you will either need to set XCC/XCXX/XLD/XCPP or pass 38# --cross-bindir to specify the path to the cross-compiler bindir: 39# `MAKEOBJDIRPREFIX=~/obj ./tools/build/make.py 40# --cross-bindir=/path/to/cross/compiler buildworld -DWITH_FOO TARGET=foo 41# TARGET_ARCH=bar` 42import argparse 43import os 44import shlex 45import shutil 46import subprocess 47import sys 48from pathlib import Path 49 50 51def run(cmd, **kwargs): 52 cmd = list(map(str, cmd)) # convert all Path objects to str 53 debug("Running", cmd) 54 subprocess.check_call(cmd, **kwargs) 55 56 57def bootstrap_bmake(source_root, objdir_prefix): 58 bmake_source_dir = source_root / "contrib/bmake" 59 bmake_build_dir = objdir_prefix / "bmake-build" 60 bmake_install_dir = objdir_prefix / "bmake-install" 61 bmake_binary = bmake_install_dir / "bin/bmake" 62 63 if (bmake_install_dir / "bin/bmake").exists(): 64 return bmake_binary 65 print("Bootstrapping bmake...") 66 # TODO: check if the host system bmake is new enough and use that instead 67 if not bmake_build_dir.exists(): 68 os.makedirs(str(bmake_build_dir)) 69 env = os.environ.copy() 70 global new_env_vars 71 env.update(new_env_vars) 72 73 configure_args = [ 74 "--with-default-sys-path=" + str(bmake_install_dir / "share/mk"), 75 "--with-machine=amd64", # TODO? "--with-machine-arch=amd64", 76 "--without-filemon", "--prefix=" + str(bmake_install_dir)] 77 run(["sh", bmake_source_dir / "boot-strap"] + configure_args, 78 cwd=str(bmake_build_dir), env=env) 79 80 run(["sh", bmake_source_dir / "boot-strap", "op=install"] + configure_args, 81 cwd=str(bmake_build_dir)) 82 print("Finished bootstrapping bmake...") 83 return bmake_binary 84 85 86def debug(*args, **kwargs): 87 global parsed_args 88 if parsed_args.debug: 89 print(*args, **kwargs) 90 91 92def is_make_var_set(var): 93 return any( 94 x.startswith(var + "=") or x == ("-D" + var) for x in sys.argv[1:]) 95 96 97def check_required_make_env_var(varname, binary_name, bindir): 98 global new_env_vars 99 if os.getenv(varname): 100 return 101 if not bindir: 102 sys.exit("Could not infer value for $" + varname + ". Either set $" + 103 varname + " or pass --cross-bindir=/cross/compiler/dir/bin") 104 # try to infer the path to the tool 105 guess = os.path.join(bindir, binary_name) 106 if not os.path.isfile(guess): 107 sys.exit("Could not infer value for $" + varname + ": " + guess + 108 " does not exist") 109 new_env_vars[varname] = guess 110 debug("Inferred", varname, "as", guess) 111 global parsed_args 112 if parsed_args.debug: 113 run([guess, "--version"]) 114 115def check_xtool_make_env_var(varname, binary_name): 116 # Avoid calling brew --prefix on macOS if all variables are already set: 117 if os.getenv(varname): 118 return 119 global parsed_args 120 if parsed_args.cross_bindir is None: 121 parsed_args.cross_bindir = default_cross_toolchain() 122 return check_required_make_env_var(varname, binary_name, 123 parsed_args.cross_bindir) 124 125def default_cross_toolchain(): 126 # default to homebrew-installed clang on MacOS if available 127 if sys.platform.startswith("darwin"): 128 if shutil.which("brew"): 129 llvm_dir = subprocess.run(["brew", "--prefix", "llvm"], 130 capture_output=True).stdout.strip() 131 debug("Inferred LLVM dir as", llvm_dir) 132 try: 133 if llvm_dir and Path(llvm_dir.decode("utf-8"), "bin").exists(): 134 return str(Path(llvm_dir.decode("utf-8"), "bin")) 135 except OSError: 136 return None 137 return None 138 139 140if __name__ == "__main__": 141 parser = argparse.ArgumentParser( 142 formatter_class=argparse.ArgumentDefaultsHelpFormatter) 143 parser.add_argument("--host-bindir", 144 help="Directory to look for cc/c++/cpp/ld to build " 145 "host (" + sys.platform + ") binaries", 146 default="/usr/bin") 147 parser.add_argument("--cross-bindir", default=None, 148 help="Directory to look for cc/c++/cpp/ld to build " 149 "target binaries (only needed if XCC/XCPP/XLD " 150 "are not set)") 151 parser.add_argument("--cross-compiler-type", choices=("clang", "gcc"), 152 default="clang", 153 help="Compiler type to find in --cross-bindir (only " 154 "needed if XCC/XCPP/XLD are not set)" 155 "Note: using CC is currently highly experimental") 156 parser.add_argument("--host-compiler-type", choices=("cc", "clang", "gcc"), 157 default="cc", 158 help="Compiler type to find in --host-bindir (only " 159 "needed if CC/CPP/CXX are not set). ") 160 parser.add_argument("--debug", action="store_true", 161 help="Print information on inferred env vars") 162 parser.add_argument("--bootstrap-toolchain", action="store_true", 163 help="Bootstrap the toolchain instead of using an " 164 "external one (experimental and not recommended)") 165 parser.add_argument("--clean", action="store_true", 166 help="Do a clean rebuild instead of building with " 167 "-DWITHOUT_CLEAN") 168 parser.add_argument("--no-clean", action="store_false", dest="clean", 169 help="Do a clean rebuild instead of building with " 170 "-DWITHOUT_CLEAN") 171 try: 172 import argcomplete # bash completion: 173 174 argcomplete.autocomplete(parser) 175 except ImportError: 176 pass 177 parsed_args, bmake_args = parser.parse_known_args() 178 179 MAKEOBJDIRPREFIX = os.getenv("MAKEOBJDIRPREFIX") 180 if not MAKEOBJDIRPREFIX: 181 sys.exit("MAKEOBJDIRPREFIX is not set, cannot continue!") 182 if not Path(MAKEOBJDIRPREFIX).is_dir(): 183 sys.exit( 184 "Chosen MAKEOBJDIRPREFIX=" + MAKEOBJDIRPREFIX + " doesn't exit!") 185 objdir_prefix = Path(MAKEOBJDIRPREFIX).absolute() 186 source_root = Path(__file__).absolute().parent.parent.parent 187 188 new_env_vars = {} 189 if not sys.platform.startswith("freebsd"): 190 if not is_make_var_set("TARGET") or not is_make_var_set("TARGET_ARCH"): 191 if "universe" not in sys.argv and "tinderbox" not in sys.argv: 192 sys.exit("TARGET= and TARGET_ARCH= must be set explicitly " 193 "when building on non-FreeBSD") 194 if not parsed_args.bootstrap_toolchain: 195 # infer values for CC/CXX/CPP 196 if parsed_args.host_compiler_type == "gcc": 197 default_cc, default_cxx, default_cpp = ("gcc", "g++", "cpp") 198 # FIXME: this should take values like `clang-9` and then look for 199 # clang-cpp-9, etc. Would alleviate the need to set the bindir on 200 # ubuntu/debian at least. 201 elif parsed_args.host_compiler_type == "clang": 202 default_cc, default_cxx, default_cpp = ( 203 "clang", "clang++", "clang-cpp") 204 else: 205 default_cc, default_cxx, default_cpp = ("cc", "c++", "cpp") 206 207 check_required_make_env_var("CC", default_cc, parsed_args.host_bindir) 208 check_required_make_env_var("CXX", default_cxx, 209 parsed_args.host_bindir) 210 check_required_make_env_var("CPP", default_cpp, 211 parsed_args.host_bindir) 212 # Using the default value for LD is fine (but not for XLD!) 213 214 # On non-FreeBSD we need to explicitly pass XCC/XLD/X_COMPILER_TYPE 215 use_cross_gcc = parsed_args.cross_compiler_type == "gcc" 216 check_xtool_make_env_var("XCC", "gcc" if use_cross_gcc else "clang") 217 check_xtool_make_env_var("XCXX", "g++" if use_cross_gcc else "clang++") 218 check_xtool_make_env_var("XCPP", 219 "cpp" if use_cross_gcc else "clang-cpp") 220 check_xtool_make_env_var("XLD", "ld" if use_cross_gcc else "ld.lld") 221 222 # We also need to set STRIPBIN if there is no working strip binary 223 # in $PATH. 224 if not shutil.which("strip"): 225 if sys.platform.startswith("darwin"): 226 # On macOS systems we have to use /usr/bin/strip. 227 sys.exit("Cannot find required tool 'strip'. Please install " 228 "the host compiler and command line tools.") 229 if parsed_args.host_compiler_type == "clang": 230 strip_binary = "llvm-strip" 231 else: 232 strip_binary = "strip" 233 check_required_make_env_var("STRIPBIN", strip_binary, 234 parsed_args.host_bindir) 235 if os.getenv("STRIPBIN") or "STRIPBIN" in new_env_vars: 236 # If we are setting STRIPBIN, we have to set XSTRIPBIN to the 237 # default if it is not set otherwise already. 238 if not os.getenv("XSTRIPBIN") and not is_make_var_set("XSTRIPBIN"): 239 # Use the bootstrapped elftoolchain strip: 240 new_env_vars["XSTRIPBIN"] = "strip" 241 242 bmake_binary = bootstrap_bmake(source_root, objdir_prefix) 243 # at -j1 cleandir+obj is unbearably slow. AUTO_OBJ helps a lot 244 debug("Adding -DWITH_AUTO_OBJ") 245 bmake_args.append("-DWITH_AUTO_OBJ") 246 if parsed_args.clean is False: 247 bmake_args.append("-DWITHOUT_CLEAN") 248 if (parsed_args.clean is None and not is_make_var_set("NO_CLEAN") 249 and not is_make_var_set("WITHOUT_CLEAN")): 250 # Avoid accidentally deleting all of the build tree and wasting lots of 251 # time cleaning directories instead of just doing a rm -rf ${.OBJDIR} 252 want_clean = input("You did not set -DWITHOUT_CLEAN/--clean/--no-clean." 253 " Did you really mean to do a clean build? y/[N] ") 254 if not want_clean.lower().startswith("y"): 255 bmake_args.append("-DWITHOUT_CLEAN") 256 257 env_cmd_str = " ".join( 258 shlex.quote(k + "=" + v) for k, v in new_env_vars.items()) 259 make_cmd_str = " ".join( 260 shlex.quote(s) for s in [str(bmake_binary)] + bmake_args) 261 debug("Running `env ", env_cmd_str, " ", make_cmd_str, "`", sep="") 262 os.environ.update(new_env_vars) 263 264 # Fedora defines bash function wrapper for some shell commands and this 265 # makes 'which <command>' return the function's source code instead of 266 # the binary path. Undefine it to restore the original behavior. 267 os.unsetenv("BASH_FUNC_which%%") 268 os.unsetenv("BASH_FUNC_ml%%") 269 os.unsetenv("BASH_FUNC_module%%") 270 271 os.chdir(str(source_root)) 272 os.execv(str(bmake_binary), [str(bmake_binary)] + bmake_args) 273