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 51# List of targets that are independent of TARGET/TARGET_ARCH and thus do not 52# need them to be set. Keep in the same order as Makefile documents them (if 53# they are documented). 54mach_indep_targets = [ 55 "cleanuniverse", 56 "universe", 57 "universe-toolchain", 58 "tinderbox" 59 "worlds", 60 "kernels", 61 "kernel-toolchains", 62 "targets", 63 "toolchains", 64 "makeman", 65 "sysent", 66] 67 68 69def run(cmd, **kwargs): 70 cmd = list(map(str, cmd)) # convert all Path objects to str 71 debug("Running", cmd) 72 subprocess.check_call(cmd, **kwargs) 73 74 75def bootstrap_bmake(source_root, objdir_prefix): 76 bmake_source_dir = source_root / "contrib/bmake" 77 bmake_build_dir = objdir_prefix / "bmake-build" 78 bmake_install_dir = objdir_prefix / "bmake-install" 79 bmake_binary = bmake_install_dir / "bin/bmake" 80 81 if (bmake_install_dir / "bin/bmake").exists(): 82 return bmake_binary 83 print("Bootstrapping bmake...") 84 # TODO: check if the host system bmake is new enough and use that instead 85 if not bmake_build_dir.exists(): 86 os.makedirs(str(bmake_build_dir)) 87 env = os.environ.copy() 88 global new_env_vars 89 env.update(new_env_vars) 90 91 configure_args = [ 92 "--with-default-sys-path=" + str(bmake_install_dir / "share/mk"), 93 "--with-machine=amd64", # TODO? "--with-machine-arch=amd64", 94 "--without-filemon", "--prefix=" + str(bmake_install_dir)] 95 run(["sh", bmake_source_dir / "boot-strap"] + configure_args, 96 cwd=str(bmake_build_dir), env=env) 97 98 run(["sh", bmake_source_dir / "boot-strap", "op=install"] + configure_args, 99 cwd=str(bmake_build_dir)) 100 print("Finished bootstrapping bmake...") 101 return bmake_binary 102 103 104def debug(*args, **kwargs): 105 global parsed_args 106 if parsed_args.debug: 107 print(*args, **kwargs) 108 109 110def is_make_var_set(var): 111 return any( 112 x.startswith(var + "=") or x == ("-D" + var) for x in sys.argv[1:]) 113 114 115def check_required_make_env_var(varname, binary_name, bindir): 116 global new_env_vars 117 if os.getenv(varname): 118 return 119 if not bindir: 120 sys.exit("Could not infer value for $" + varname + ". Either set $" + 121 varname + " or pass --cross-bindir=/cross/compiler/dir/bin") 122 # try to infer the path to the tool 123 guess = os.path.join(bindir, binary_name) 124 if not os.path.isfile(guess): 125 sys.exit("Could not infer value for $" + varname + ": " + guess + 126 " does not exist") 127 new_env_vars[varname] = guess 128 debug("Inferred", varname, "as", guess) 129 global parsed_args 130 if parsed_args.debug: 131 run([guess, "--version"]) 132 133 134def check_xtool_make_env_var(varname, binary_name): 135 # Avoid calling brew --prefix on macOS if all variables are already set: 136 if os.getenv(varname): 137 return 138 global parsed_args 139 if parsed_args.cross_bindir is None: 140 parsed_args.cross_bindir = default_cross_toolchain() 141 return check_required_make_env_var(varname, binary_name, 142 parsed_args.cross_bindir) 143 144 145def default_cross_toolchain(): 146 # default to homebrew-installed clang on MacOS if available 147 if sys.platform.startswith("darwin"): 148 if shutil.which("brew"): 149 llvm_dir = subprocess.run(["brew", "--prefix", "llvm"], 150 capture_output=True).stdout.strip() 151 debug("Inferred LLVM dir as", llvm_dir) 152 try: 153 if llvm_dir and Path(llvm_dir.decode("utf-8"), "bin").exists(): 154 return str(Path(llvm_dir.decode("utf-8"), "bin")) 155 except OSError: 156 return None 157 return None 158 159 160if __name__ == "__main__": 161 parser = argparse.ArgumentParser( 162 formatter_class=argparse.ArgumentDefaultsHelpFormatter) 163 parser.add_argument("--host-bindir", 164 help="Directory to look for cc/c++/cpp/ld to build " 165 "host (" + sys.platform + ") binaries", 166 default="/usr/bin") 167 parser.add_argument("--cross-bindir", default=None, 168 help="Directory to look for cc/c++/cpp/ld to build " 169 "target binaries (only needed if XCC/XCPP/XLD " 170 "are not set)") 171 parser.add_argument("--cross-compiler-type", choices=("clang", "gcc"), 172 default="clang", 173 help="Compiler type to find in --cross-bindir (only " 174 "needed if XCC/XCPP/XLD are not set)" 175 "Note: using CC is currently highly experimental") 176 parser.add_argument("--host-compiler-type", choices=("cc", "clang", "gcc"), 177 default="cc", 178 help="Compiler type to find in --host-bindir (only " 179 "needed if CC/CPP/CXX are not set). ") 180 parser.add_argument("--debug", action="store_true", 181 help="Print information on inferred env vars") 182 parser.add_argument("--bootstrap-toolchain", action="store_true", 183 help="Bootstrap the toolchain instead of using an " 184 "external one (experimental and not recommended)") 185 parser.add_argument("--clean", action="store_true", 186 help="Do a clean rebuild instead of building with " 187 "-DWITHOUT_CLEAN") 188 parser.add_argument("--no-clean", action="store_false", dest="clean", 189 help="Do a clean rebuild instead of building with " 190 "-DWITHOUT_CLEAN") 191 try: 192 import argcomplete # bash completion: 193 194 argcomplete.autocomplete(parser) 195 except ImportError: 196 pass 197 parsed_args, bmake_args = parser.parse_known_args() 198 199 MAKEOBJDIRPREFIX = os.getenv("MAKEOBJDIRPREFIX") 200 if not MAKEOBJDIRPREFIX: 201 sys.exit("MAKEOBJDIRPREFIX is not set, cannot continue!") 202 if not Path(MAKEOBJDIRPREFIX).is_dir(): 203 sys.exit( 204 "Chosen MAKEOBJDIRPREFIX=" + MAKEOBJDIRPREFIX + " doesn't exit!") 205 objdir_prefix = Path(MAKEOBJDIRPREFIX).absolute() 206 source_root = Path(__file__).absolute().parent.parent.parent 207 208 new_env_vars = {} 209 if not sys.platform.startswith("freebsd"): 210 if not is_make_var_set("TARGET") or not is_make_var_set("TARGET_ARCH"): 211 if not set(sys.argv).intersection(set(mach_indep_targets)): 212 sys.exit("TARGET= and TARGET_ARCH= must be set explicitly " 213 "when building on non-FreeBSD") 214 if not parsed_args.bootstrap_toolchain: 215 # infer values for CC/CXX/CPP 216 if parsed_args.host_compiler_type == "gcc": 217 default_cc, default_cxx, default_cpp = ("gcc", "g++", "cpp") 218 # FIXME: this should take values like `clang-9` and then look for 219 # clang-cpp-9, etc. Would alleviate the need to set the bindir on 220 # ubuntu/debian at least. 221 elif parsed_args.host_compiler_type == "clang": 222 default_cc, default_cxx, default_cpp = ( 223 "clang", "clang++", "clang-cpp") 224 else: 225 default_cc, default_cxx, default_cpp = ("cc", "c++", "cpp") 226 227 check_required_make_env_var("CC", default_cc, parsed_args.host_bindir) 228 check_required_make_env_var("CXX", default_cxx, 229 parsed_args.host_bindir) 230 check_required_make_env_var("CPP", default_cpp, 231 parsed_args.host_bindir) 232 # Using the default value for LD is fine (but not for XLD!) 233 234 # On non-FreeBSD we need to explicitly pass XCC/XLD/X_COMPILER_TYPE 235 use_cross_gcc = parsed_args.cross_compiler_type == "gcc" 236 check_xtool_make_env_var("XCC", "gcc" if use_cross_gcc else "clang") 237 check_xtool_make_env_var("XCXX", "g++" if use_cross_gcc else "clang++") 238 check_xtool_make_env_var("XCPP", 239 "cpp" if use_cross_gcc else "clang-cpp") 240 check_xtool_make_env_var("XLD", "ld" if use_cross_gcc else "ld.lld") 241 242 # We also need to set STRIPBIN if there is no working strip binary 243 # in $PATH. 244 if not shutil.which("strip"): 245 if sys.platform.startswith("darwin"): 246 # On macOS systems we have to use /usr/bin/strip. 247 sys.exit("Cannot find required tool 'strip'. Please install " 248 "the host compiler and command line tools.") 249 if parsed_args.host_compiler_type == "clang": 250 strip_binary = "llvm-strip" 251 else: 252 strip_binary = "strip" 253 check_required_make_env_var("STRIPBIN", strip_binary, 254 parsed_args.host_bindir) 255 if os.getenv("STRIPBIN") or "STRIPBIN" in new_env_vars: 256 # If we are setting STRIPBIN, we have to set XSTRIPBIN to the 257 # default if it is not set otherwise already. 258 if not os.getenv("XSTRIPBIN") and not is_make_var_set("XSTRIPBIN"): 259 # Use the bootstrapped elftoolchain strip: 260 new_env_vars["XSTRIPBIN"] = "strip" 261 262 bmake_binary = bootstrap_bmake(source_root, objdir_prefix) 263 # at -j1 cleandir+obj is unbearably slow. AUTO_OBJ helps a lot 264 debug("Adding -DWITH_AUTO_OBJ") 265 bmake_args.append("-DWITH_AUTO_OBJ") 266 if parsed_args.clean is False: 267 bmake_args.append("-DWITHOUT_CLEAN") 268 if (parsed_args.clean is None and not is_make_var_set("NO_CLEAN") 269 and not is_make_var_set("WITHOUT_CLEAN")): 270 # Avoid accidentally deleting all of the build tree and wasting lots of 271 # time cleaning directories instead of just doing a rm -rf ${.OBJDIR} 272 want_clean = input("You did not set -DWITHOUT_CLEAN/--(no-)clean." 273 " Did you really mean to do a clean build? y/[N] ") 274 if not want_clean.lower().startswith("y"): 275 bmake_args.append("-DWITHOUT_CLEAN") 276 277 env_cmd_str = " ".join( 278 shlex.quote(k + "=" + v) for k, v in new_env_vars.items()) 279 make_cmd_str = " ".join( 280 shlex.quote(s) for s in [str(bmake_binary)] + bmake_args) 281 debug("Running `env ", env_cmd_str, " ", make_cmd_str, "`", sep="") 282 os.environ.update(new_env_vars) 283 284 # Fedora defines bash function wrapper for some shell commands and this 285 # makes 'which <command>' return the function's source code instead of 286 # the binary path. Undefine it to restore the original behavior. 287 os.unsetenv("BASH_FUNC_which%%") 288 os.unsetenv("BASH_FUNC_ml%%") 289 os.unsetenv("BASH_FUNC_module%%") 290 291 os.chdir(str(source_root)) 292 os.execv(str(bmake_binary), [str(bmake_binary)] + bmake_args) 293