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