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