Bug 1837620 - Part 1.5: Rename IC flag to 'mayHaveFoldedStub' to make it clear that...
[gecko.git] / build / moz.configure / init.configure
blobfbd626bc73bd2c570e5dbe54a85d2f86f00fea6b
1 # -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
2 # vim: set filetype=python:
3 # This Source Code Form is subject to the terms of the Mozilla Public
4 # License, v. 2.0. If a copy of the MPL was not distributed with this
5 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 include("util.configure")
8 include("checks.configure")
10 # Make `toolkit` available when toolkit/moz.configure is not included.
11 toolkit = dependable(None)
12 # Likewise with `bindgen_config_paths` when
13 # build/moz.configure/bindgen.configure is not included.
14 bindgen_config_paths = dependable(None)
17 @depends("--help")
18 def build_environment(_):
19     topobjdir = os.path.realpath(".")
20     topsrcdir = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
21     dist = os.path.join(topobjdir, "dist")
23     return namespace(
24         topsrcdir=topsrcdir,
25         topobjdir=topobjdir,
26         dist=dist,
27     )
30 @depends(build_environment)
31 @imports(_import="json")
32 @imports(_from="pathlib", _import="Path")
33 def configure_cache(build_environment):
34     """
35     This cache is used to cache the results of compiler invocations
36     between different runs of configure and save them to the disk, which
37     results in a significant speed up of subsequent configure runs (15%-50%).
39     It is not currently thread safe because it is just a simple dictionary
40     wrapped in a dummy class (ConfigureCache). It could be improved to be
41     thread safe in the future, if we ever make configure parallelized, but
42     for now there is no advantage to doing so.
43     """
45     class ConfigureCache(dict):
46         pass
48     cache_file = Path(build_environment.topobjdir) / "configure.cache"
49     if cache_file.exists():
50         with cache_file.open() as f:
51             cache_data = json.load(f)
52     else:
53         cache_data = {}
55     cache = ConfigureCache(cache_data)
56     cache.version_checked_compilers = set()
58     return cache
61 set_config("TOPSRCDIR", build_environment.topsrcdir)
62 set_config("TOPOBJDIR", build_environment.topobjdir)
63 set_config("DIST", build_environment.dist)
65 add_old_configure_assignment("_topsrcdir", build_environment.topsrcdir)
66 add_old_configure_assignment("_objdir", build_environment.topobjdir)
67 add_old_configure_assignment("DIST", build_environment.dist)
69 option(env="MOZ_AUTOMATION", help="Enable options for automated builds")
70 set_config("MOZ_AUTOMATION", depends_if("MOZ_AUTOMATION")(lambda x: True))
73 option(env="OLD_CONFIGURE", nargs=1, help="Path to the old configure script")
75 option(env="MOZCONFIG", nargs=1, help="Mozconfig location")
78 # Read user mozconfig
79 # ==============================================================
80 # Note: the dependency on --help is only there to always read the mozconfig,
81 # even when --help is passed. Without this dependency, the function wouldn't
82 # be called when --help is passed, and the mozconfig wouldn't be read.
85 @depends("MOZCONFIG", "OLD_CONFIGURE", build_environment, "--help")
86 @imports(_from="mozbuild.mozconfig", _import="MozconfigLoader")
87 @imports(_from="mozboot.mozconfig", _import="find_mozconfig")
88 @imports("os")
89 def mozconfig(mozconfig, old_configure, build_env, help):
90     # Don't read the mozconfig for the js configure (yay backwards
91     # compatibility)
92     # While the long term goal is that js and top-level use the same configure
93     # and the same overall setup, including the possibility to use mozconfigs,
94     # figuring out what we want to do wrt mozconfig vs. command line and
95     # environment variable is not a clear-cut case, and it's more important to
96     # fix the immediate problem mozconfig causes to js developers by
97     # "temporarily" returning to the previous behavior of not loading the
98     # mozconfig for the js configure.
99     # Separately to the immediate problem for js developers, there is also the
100     # need to not load a mozconfig when running js configure as a subconfigure.
101     # Unfortunately, there is no direct way to tell whether the running
102     # configure is the js configure. The indirect way is to look at the
103     # OLD_CONFIGURE path, which points to js/src/old-configure.
104     # I expect we'll have figured things out for mozconfigs well before
105     # old-configure dies.
106     if (
107         old_configure
108         and os.path.dirname(os.path.abspath(old_configure[0])).endswith("/js/src")
109         or (mozconfig and mozconfig[0] == os.devnull)
110     ):
111         return {"path": None}
113     topsrcdir = build_env.topsrcdir
114     loader = MozconfigLoader(topsrcdir)
115     mozconfig = mozconfig[0] if mozconfig else None
116     mozconfig = find_mozconfig(topsrcdir, env={"MOZCONFIG": mozconfig})
117     mozconfig = loader.read_mozconfig(mozconfig)
119     return mozconfig
122 set_config("MOZCONFIG", depends(mozconfig)(lambda m: m["path"]))
125 # Mozilla-Build
126 # ==============================================================
127 option(env="MOZILLABUILD", nargs=1, help="Path to Mozilla Build (Windows-only)")
129 option(env="CONFIG_SHELL", nargs=1, help="Path to a POSIX shell")
131 # It feels dirty replicating this from python/mozbuild/mozbuild/mozconfig.py,
132 # but the end goal being that the configure script would go away...
135 @depends("CONFIG_SHELL", "MOZILLABUILD")
136 @checking("for a shell")
137 @imports("sys")
138 @imports(_from="pathlib", _import="Path")
139 def shell(value, mozillabuild):
140     if value:
141         return find_program(value[0])
142     shell = "sh"
143     if mozillabuild:
144         if (Path(mozillabuild[0]) / "msys2").exists():
145             shell = mozillabuild[0] + "/msys2/usr/bin/sh"
146         else:
147             shell = mozillabuild[0] + "/msys/bin/sh"
148     if sys.platform == "win32":
149         shell = shell + ".exe"
150     return find_program(shell)
153 # This defines a reasonable shell for when running with --help.
154 # If one was passed in the environment, though, fall back to that.
155 @depends("--help", "CONFIG_SHELL")
156 def help_shell(help, shell):
157     if help and not shell:
158         return "sh"
161 shell = help_shell | shell
164 # Python 3
165 # ========
166 @dependable
167 @checking("for Python 3", callback=lambda x: "%s (%s)" % (x.path, x.str_version))
168 @imports("sys")
169 @imports(_from="mach.site", _import="PythonVirtualenv")
170 @imports(_from="os.path", _import="realpath")
171 def virtualenv_python3():
172     return namespace(
173         # sys.executable is currently not updated for in-process activations. However,
174         # sys.prefix is, so we can calculate the python executable's path from there.
175         path=normsep(PythonVirtualenv(realpath(sys.prefix)).python_path),
176         str_version=".".join(str(i) for i in sys.version_info[0:3]),
177     )
180 set_config("PYTHON3", virtualenv_python3.path)
181 set_config("PYTHON3_VERSION", virtualenv_python3.str_version)
182 add_old_configure_assignment("PYTHON3", virtualenv_python3.path)
185 # Inject mozconfig options
186 # ==============================================================
187 # All options defined above this point can't be injected in mozconfig_options
188 # below, so collect them.
191 @template
192 def early_options():
193     @depends("--help")
194     @imports("__sandbox__")
195     def early_options(_):
196         return set(option.env for option in __sandbox__._options.values() if option.env)
198     return early_options
201 early_options = early_options()
204 @depends(mozconfig, early_options, "MOZ_AUTOMATION", "--help")
205 # This gives access to the sandbox. Don't copy this blindly.
206 @imports("__sandbox__")
207 @imports("os")
208 def mozconfig_options(mozconfig, early_options, automation, help):
209     if mozconfig["path"]:
210         if "MOZ_AUTOMATION_MOZCONFIG" in mozconfig["env"]["added"]:
211             if not automation:
212                 log.error(
213                     "%s directly or indirectly includes an in-tree " "mozconfig.",
214                     mozconfig["path"],
215                 )
216                 log.error(
217                     "In-tree mozconfigs make strong assumptions about "
218                     "and are only meant to be used by Mozilla "
219                     "automation."
220                 )
221                 die("Please don't use them.")
222         helper = __sandbox__._helper
223         log.info("Adding configure options from %s" % mozconfig["path"])
224         for arg in mozconfig["configure_args"]:
225             log.info("  %s" % arg)
226             # We could be using imply_option() here, but it has other
227             # contraints that don't really apply to the command-line
228             # emulation that mozconfig provides.
229             helper.add(arg, origin="mozconfig", args=helper._args)
231         def add(key, value):
232             if key.isupper():
233                 arg = "%s=%s" % (key, value)
234                 log.info("  %s" % arg)
235                 if key not in early_options:
236                     helper.add(arg, origin="mozconfig", args=helper._args)
238         for key, value in mozconfig["env"]["added"].items():
239             add(key, value)
240             os.environ[key] = value
241         for key, (_, value) in mozconfig["env"]["modified"].items():
242             add(key, value)
243             os.environ[key] = value
244         for key, value in mozconfig["vars"]["added"].items():
245             add(key, value)
246         for key, (_, value) in mozconfig["vars"]["modified"].items():
247             add(key, value)
250 @depends(build_environment, "--help")
251 @imports(_from="os.path", _import="exists")
252 def js_package(build_env, help):
253     return not exists(os.path.join(build_env.topsrcdir, "browser"))
256 # Source checkout and version control integration.
257 # ================================================
260 @depends(build_environment, "MOZ_AUTOMATION", js_package, "--help")
261 @checking("for vcs source checkout")
262 @imports("os")
263 def vcs_checkout_type(build_env, automation, js_package, help):
264     if os.path.exists(os.path.join(build_env.topsrcdir, ".hg")):
265         return "hg"
266     elif os.path.exists(os.path.join(build_env.topsrcdir, ".git")):
267         return "git"
268     elif automation and not js_package and not help:
269         raise FatalCheckError(
270             "unable to resolve VCS type; must run "
271             "from a source checkout when MOZ_AUTOMATION "
272             "is set"
273         )
276 # Resolve VCS binary for detected repository type.
279 # TODO remove hg.exe once bug 1382940 addresses ambiguous executables case.
280 hg = check_prog(
281     "HG",
282     (
283         "hg.exe",
284         "hg",
285     ),
286     allow_missing=True,
287     when=depends(vcs_checkout_type)(lambda x: x == "hg"),
289 git = check_prog(
290     "GIT",
291     ("git",),
292     allow_missing=True,
293     when=depends(vcs_checkout_type)(lambda x: x == "git"),
297 @depends_if(hg)
298 @checking("for Mercurial version")
299 @imports("os")
300 @imports("re")
301 def hg_version(hg):
302     # HGPLAIN in Mercurial 1.5+ forces stable output, regardless of set
303     # locale or encoding.
304     env = dict(os.environ)
305     env["HGPLAIN"] = "1"
307     out = check_cmd_output(hg, "--version", env=env)
309     match = re.search(r"Mercurial Distributed SCM \(version ([^\)]+)", out)
311     if not match:
312         raise FatalCheckError("unable to determine Mercurial version: %s" % out)
314     # The version string may be "unknown" for Mercurial run out of its own
315     # source checkout or for bad builds. But LooseVersion handles it.
317     return Version(match.group(1))
320 # Resolve Mercurial config items so other checks have easy access.
321 # Do NOT set this in the config because it may contain sensitive data
322 # like API keys.
325 @depends_all(build_environment, hg, hg_version)
326 @imports("os")
327 def hg_config(build_env, hg, version):
328     env = dict(os.environ)
329     env["HGPLAIN"] = "1"
331     # Warnings may get sent to stderr. But check_cmd_output() ignores
332     # stderr if exit code is 0. And the command should always succeed if
333     # `hg version` worked.
334     out = check_cmd_output(hg, "config", env=env, cwd=build_env.topsrcdir)
336     config = {}
338     for line in out.strip().splitlines():
339         key, value = [s.strip() for s in line.split("=", 1)]
340         config[key] = value
342     return config
345 @depends_if(git)
346 @checking("for Git version")
347 @imports("re")
348 def git_version(git):
349     out = check_cmd_output(git, "--version").rstrip()
351     match = re.search("git version (.*)$", out)
353     if not match:
354         raise FatalCheckError("unable to determine Git version: %s" % out)
356     return Version(match.group(1))
359 # Only set VCS_CHECKOUT_TYPE if we resolved the VCS binary.
360 # Require resolved VCS info when running in automation so automation's
361 # environment is more well-defined.
364 @depends(vcs_checkout_type, hg_version, git_version, "MOZ_AUTOMATION")
365 def exposed_vcs_checkout_type(vcs_checkout_type, hg, git, automation):
366     if vcs_checkout_type == "hg":
367         if hg:
368             return "hg"
370         if automation:
371             raise FatalCheckError("could not resolve Mercurial binary info")
373     elif vcs_checkout_type == "git":
374         if git:
375             return "git"
377         if automation:
378             raise FatalCheckError("could not resolve Git binary info")
379     elif vcs_checkout_type:
380         raise FatalCheckError("unhandled VCS type: %s" % vcs_checkout_type)
383 set_config("VCS_CHECKOUT_TYPE", exposed_vcs_checkout_type)
385 # Obtain a Repository interface for the current VCS repository.
388 @depends(build_environment, exposed_vcs_checkout_type, hg, git)
389 @imports(_from="mozversioncontrol", _import="get_repository_object")
390 def vcs_repository(build_env, vcs_checkout_type, hg, git):
391     if vcs_checkout_type == "hg":
392         return get_repository_object(build_env.topsrcdir, hg=hg)
393     elif vcs_checkout_type == "git":
394         return get_repository_object(build_env.topsrcdir, git=git)
395     elif vcs_checkout_type:
396         raise FatalCheckError("unhandled VCS type: %s" % vcs_checkout_type)
399 @depends_if(vcs_repository)
400 @checking("for sparse checkout")
401 def vcs_sparse_checkout(repo):
402     return repo.sparse_checkout_present()
405 set_config("VCS_SPARSE_CHECKOUT", vcs_sparse_checkout)
407 # The application/project to build
408 # ==============================================================
409 option(
410     "--enable-application",
411     nargs=1,
412     env="MOZ_BUILD_APP",
413     help="Application to build. Same as --enable-project.",
417 @depends("--enable-application")
418 def application(app):
419     if app:
420         return app
423 imply_option("--enable-project", application)
426 @depends(build_environment, js_package)
427 def default_project(build_env, js_package):
428     if js_package or build_env.topobjdir.endswith("/js/src"):
429         return "js"
430     return "browser"
433 option("--enable-project", nargs=1, default=default_project, help="Project to build")
436 # Artifact builds
437 # ==============================================================
439 option(
440     "--enable-artifact-builds",
441     env="MOZ_ARTIFACT_BUILDS",
442     help="Download and use prebuilt binary artifacts.",
446 @depends("--enable-artifact-builds")
447 def artifact_builds(value):
448     if value:
449         return True
452 set_config("MOZ_ARTIFACT_BUILDS", artifact_builds)
454 # Host and target systems
455 # ==============================================================
456 option("--host", nargs=1, help="Define the system type performing the build")
458 option(
459     "--target",
460     nargs=1,
461     help="Define the system type where the resulting executables will be " "used",
465 @imports(_from="mozbuild.configure.constants", _import="Abi")
466 @imports(_from="mozbuild.configure.constants", _import="CPU")
467 @imports(_from="mozbuild.configure.constants", _import="CPU_bitness")
468 @imports(_from="mozbuild.configure.constants", _import="Endianness")
469 @imports(_from="mozbuild.configure.constants", _import="Kernel")
470 @imports(_from="mozbuild.configure.constants", _import="OS")
471 @imports(_from="__builtin__", _import="ValueError")
472 def split_triplet(triplet, allow_wasi=False):
473     # The standard triplet is defined as
474     #   CPU_TYPE-VENDOR-OPERATING_SYSTEM
475     # There is also a quartet form:
476     #   CPU_TYPE-VENDOR-KERNEL-OPERATING_SYSTEM
477     # But we can consider the "KERNEL-OPERATING_SYSTEM" as one.
478     # Additionally, some may omit "unknown" when the vendor
479     # is not specified and emit
480     #   CPU_TYPE-OPERATING_SYSTEM
481     vendor = "unknown"
482     parts = triplet.split("-", 2)
483     if len(parts) == 3:
484         cpu, vendor, os = parts
485     elif len(parts) == 2:
486         cpu, os = parts
487     else:
488         raise ValueError("Unexpected triplet string: %s" % triplet)
490     # Autoconf uses config.sub to validate and canonicalize those triplets,
491     # but the granularity of its results has never been satisfying to our
492     # use, so we've had our own, different, canonicalization. We've also
493     # historically not been very consistent with how we use the canonicalized
494     # values. Hopefully, this will help us make things better.
495     # The tests are inherited from our decades-old autoconf-based configure,
496     # which can probably be improved/cleaned up because they are based on a
497     # mix of uname and config.guess output, while we now only use the latter,
498     # which presumably has a cleaner and leaner output. Let's refine later.
499     raw_os = os = os.replace("/", "_")
500     abi = None
501     sub_configure_alias = triplet
502     if "android" in os:
503         canonical_os = "Android"
504         canonical_kernel = "Linux"
505     elif os.startswith("linux"):
506         canonical_os = "GNU"
507         canonical_kernel = "Linux"
508     elif os.startswith("kfreebsd") and os.endswith("-gnu"):
509         canonical_os = "GNU"
510         canonical_kernel = "kFreeBSD"
511     elif os.startswith("gnu"):
512         canonical_os = canonical_kernel = "GNU"
513     elif os.startswith("mingw") or os in ("windows-msvc", "windows-gnu"):
514         canonical_os = canonical_kernel = "WINNT"
515         if not os.startswith("mingw"):
516             if os == "windows-msvc":
517                 abi = "msvc"
518             elif os == "windows-gnu":
519                 abi = "mingw"
520             # Many things down the line are looking for the string "mingw32"
521             # until they are all fixed, we pretend that's the raw os we had
522             # in the first place, even when we didn't.
523             sub_configure_alias = sub_configure_alias[: -len(os)] + "mingw32"
524             raw_os = "mingw32"
525     elif os.startswith("darwin"):
526         canonical_kernel = "Darwin"
527         canonical_os = "OSX"
528     elif os.startswith("dragonfly"):
529         canonical_os = canonical_kernel = "DragonFly"
530     elif os.startswith("freebsd"):
531         canonical_os = canonical_kernel = "FreeBSD"
532     elif os.startswith("netbsd"):
533         canonical_os = canonical_kernel = "NetBSD"
534     elif os.startswith("openbsd"):
535         canonical_os = canonical_kernel = "OpenBSD"
536     elif os.startswith("solaris"):
537         canonical_os = canonical_kernel = "SunOS"
538     elif os.startswith("wasi") and allow_wasi:
539         canonical_os = canonical_kernel = "WASI"
540     else:
541         raise ValueError("Unknown OS: %s" % os)
543     # The CPU granularity is probably not enough. Moving more things from
544     # old-configure will tell us if we need more
545     if cpu.endswith("86") or (cpu.startswith("i") and "86" in cpu):
546         canonical_cpu = "x86"
547         endianness = "little"
548     elif cpu in ("x86_64", "ia64"):
549         canonical_cpu = cpu
550         endianness = "little"
551     elif cpu in ("s390", "s390x"):
552         canonical_cpu = cpu
553         endianness = "big"
554     elif cpu in ("powerpc64", "ppc64", "powerpc64le", "ppc64le"):
555         canonical_cpu = "ppc64"
556         endianness = "little" if "le" in cpu else "big"
557     elif cpu in ("powerpc", "ppc", "rs6000") or cpu.startswith("powerpc"):
558         canonical_cpu = "ppc"
559         endianness = "big"
560     elif cpu in ("Alpha", "alpha", "ALPHA"):
561         canonical_cpu = "Alpha"
562         endianness = "little"
563     elif cpu.startswith("hppa") or cpu == "parisc":
564         canonical_cpu = "hppa"
565         endianness = "big"
566     elif cpu.startswith("sparc64") or cpu.startswith("sparcv9"):
567         canonical_cpu = "sparc64"
568         endianness = "big"
569     elif cpu.startswith("sparc") or cpu == "sun4u":
570         canonical_cpu = "sparc"
571         endianness = "big"
572     elif cpu.startswith("arm"):
573         canonical_cpu = "arm"
574         endianness = "big" if cpu.startswith(("armeb", "armbe")) else "little"
575     elif cpu in ("m68k"):
576         canonical_cpu = "m68k"
577         endianness = "big"
578     elif cpu in ("mips", "mipsel"):
579         canonical_cpu = "mips32"
580         endianness = "little" if "el" in cpu else "big"
581     elif cpu in ("mips64", "mips64el"):
582         canonical_cpu = "mips64"
583         endianness = "little" if "el" in cpu else "big"
584     elif cpu.startswith("aarch64"):
585         canonical_cpu = "aarch64"
586         endianness = "little"
587     elif cpu in ("riscv64", "riscv64gc"):
588         canonical_cpu = "riscv64"
589         endianness = "little"
590     elif cpu.startswith("loongarch64"):
591         canonical_cpu = "loongarch64"
592         endianness = "little"
593     elif cpu == "sh4":
594         canonical_cpu = "sh4"
595         endianness = "little"
596     elif cpu == "wasm32" and allow_wasi:
597         canonical_cpu = "wasm32"
598         endianness = "little"
599     else:
600         raise ValueError("Unknown CPU type: %s" % cpu)
602     # Toolchains, most notably for cross compilation may use cpu-os
603     # prefixes. We need to be more specific about the LLVM target on Mac
604     # so cross-language LTO will work correctly.
606     if os.startswith("darwin"):
607         toolchain = "%s-apple-%s" % (cpu, os)
608     else:
609         toolchain = "%s-%s" % (cpu, os)
611     return namespace(
612         alias=triplet,
613         cpu=CPU(canonical_cpu),
614         bitness=CPU_bitness[canonical_cpu],
615         kernel=Kernel(canonical_kernel),
616         os=OS(canonical_os),
617         endianness=Endianness(endianness),
618         # For now, only report the Windows ABI.
619         abi=abi and Abi(abi),
620         raw_cpu=cpu,
621         raw_os=raw_os,
622         toolchain=toolchain,
623         vendor=vendor,
624         sub_configure_alias=sub_configure_alias,
625     )
628 # This defines a fake target/host namespace for when running with --help
629 # If either --host or --target is passed on the command line, then fall
630 # back to the real deal.
631 @depends("--help", "--host", "--target")
632 def help_host_target(help, host, target):
633     if help and not host and not target:
634         return namespace(
635             alias="unknown-unknown-unknown",
636             cpu="unknown",
637             bitness="unknown",
638             kernel="unknown",
639             os="unknown",
640             endianness="unknown",
641             abi="unknown",
642             raw_cpu="unknown",
643             raw_os="unknown",
644             toolchain="unknown-unknown",
645         )
648 def config_sub(shell, triplet):
649     config_sub = os.path.join(os.path.dirname(__file__), "..", "autoconf", "config.sub")
650     # Config.sub doesn't like the *-windows-msvc/*-windows-gnu triplets, so
651     # munge those before and after calling config.sub.
652     suffix = None
653     munging = {
654         "-windows-msvc": "-mingw32",
655         "-windows-gnu": "-mingw32",
656     }
657     for check_suffix, replacement in munging.items():
658         if triplet.endswith(check_suffix):
659             suffix = check_suffix
660             triplet = triplet[: -len(suffix)] + replacement
661             break
662     result = check_cmd_output(shell, config_sub, triplet).strip()
663     if suffix:
664         assert result.endswith(replacement)
665         result = result[: -len(replacement)] + suffix
666     return result
669 @depends("--host", shell)
670 @checking("for host system type", lambda h: h.alias)
671 @imports("os")
672 @imports("sys")
673 @imports(_from="__builtin__", _import="ValueError")
674 def real_host(value, shell):
675     if not value and sys.platform == "win32":
676         arch = os.environ.get("PROCESSOR_ARCHITEW6432") or os.environ.get(
677             "PROCESSOR_ARCHITECTURE"
678         )
679         if arch == "AMD64":
680             return split_triplet("x86_64-pc-windows-msvc")
681         elif arch == "x86":
682             return split_triplet("i686-pc-windows-msvc")
684     if not value:
685         config_guess = os.path.join(
686             os.path.dirname(__file__), "..", "autoconf", "config.guess"
687         )
689         # Ensure that config.guess is determining the host triplet, not the target
690         # triplet
691         env = os.environ.copy()
692         env.pop("CC_FOR_BUILD", None)
693         env.pop("HOST_CC", None)
694         env.pop("CC", None)
696         host = check_cmd_output(shell, config_guess, env=env).strip()
697         try:
698             return split_triplet(host)
699         except ValueError:
700             pass
701     else:
702         host = value[0]
704     host = config_sub(shell, host)
706     try:
707         return split_triplet(host)
708     except ValueError as e:
709         die(e)
712 host = help_host_target | real_host
715 @depends("--target", real_host, shell, "--enable-project", "--enable-application")
716 @checking("for target system type", lambda t: t.alias)
717 @imports(_from="__builtin__", _import="ValueError")
718 def real_target(value, host, shell, project, application):
719     # Because --enable-project is implied by --enable-application, and
720     # implied options are not currently handled during --help, which is
721     # used get the build target in mozbuild.base, we manually check
722     # whether --enable-application was given, and fall back to
723     # --enable-project if not. Both can't be given contradictory values
724     # under normal circumstances, so it's fine.
725     if application:
726         project = application[0]
727     elif project:
728         project = project[0]
729     if not value:
730         if project == "mobile/android":
731             if host.raw_os == "mingw32":
732                 log.warning(
733                     "Building Firefox for Android on Windows is not fully "
734                     "supported. See https://bugzilla.mozilla.org/show_bug.cgi?"
735                     "id=1169873 for details."
736                 )
737             return split_triplet("arm-unknown-linux-androideabi")
738         return host
739     # If --target was only given a cpu arch, expand it with the
740     # non-cpu part of the host. For mobile/android, expand it with
741     # unknown-linux-android.
742     target = value[0]
743     if "-" not in target:
744         if project == "mobile/android":
745             rest = "unknown-linux-android"
746             if target.startswith("arm"):
747                 rest += "eabi"
748         else:
749             cpu, rest = host.alias.split("-", 1)
750         target = "-".join((target, rest))
751         try:
752             return split_triplet(target)
753         except ValueError:
754             pass
756     try:
757         return split_triplet(config_sub(shell, target), allow_wasi=(project == "js"))
758     except ValueError as e:
759         die(e)
762 target = help_host_target | real_target
765 @depends(host, target)
766 @checking("whether cross compiling")
767 def cross_compiling(host, target):
768     return host != target
771 set_config("CROSS_COMPILE", cross_compiling)
772 set_define("CROSS_COMPILE", cross_compiling)
775 @depends(target)
776 def have_64_bit(target):
777     if target.bitness == 64:
778         return True
781 set_config("HAVE_64BIT_BUILD", have_64_bit)
782 set_define("HAVE_64BIT_BUILD", have_64_bit)
783 add_old_configure_assignment("HAVE_64BIT_BUILD", have_64_bit)
786 # Autoconf needs these set
789 @depends(host)
790 def host_for_sub_configure(host):
791     return "--host=%s" % host.sub_configure_alias
794 @depends(target)
795 def target_for_sub_configure(target):
796     return "--target=%s" % target.sub_configure_alias
799 # These variables are for compatibility with the current moz.builds and
800 # old-configure. Eventually, we'll want to canonicalize better.
801 @depends(target)
802 def target_variables(target):
803     if target.kernel == "kFreeBSD":
804         os_target = "GNU/kFreeBSD"
805         os_arch = "GNU_kFreeBSD"
806     elif target.kernel == "Darwin" or (target.kernel == "Linux" and target.os == "GNU"):
807         os_target = target.kernel
808         os_arch = target.kernel
809     else:
810         os_target = target.os
811         os_arch = target.kernel
813     return namespace(
814         OS_TARGET=str(os_target),
815         OS_ARCH=str(os_arch),
816         INTEL_ARCHITECTURE=target.cpu in ("x86", "x86_64") or None,
817     )
820 set_config("OS_TARGET", target_variables.OS_TARGET)
821 add_old_configure_assignment("OS_TARGET", target_variables.OS_TARGET)
822 set_config("OS_ARCH", target_variables.OS_ARCH)
823 add_old_configure_assignment("OS_ARCH", target_variables.OS_ARCH)
824 set_config("CPU_ARCH", target.cpu)
825 add_old_configure_assignment("CPU_ARCH", target.cpu)
826 set_config("INTEL_ARCHITECTURE", target_variables.INTEL_ARCHITECTURE)
827 set_config("TARGET_CPU", target.raw_cpu)
828 set_config("TARGET_OS", target.os)
829 set_config("TARGET_RAW_OS", target.raw_os)
830 set_config("TARGET_ENDIANNESS", target.endianness)
833 @depends(host)
834 def host_variables(host):
835     if host.kernel == "kFreeBSD":
836         os_arch = "GNU_kFreeBSD"
837     else:
838         os_arch = host.kernel
839     return namespace(
840         HOST_OS_ARCH=os_arch,
841     )
844 set_config("HOST_CPU_ARCH", host.cpu)
845 set_config("HOST_OS_ARCH", host_variables.HOST_OS_ARCH)
846 add_old_configure_assignment("HOST_OS_ARCH", host_variables.HOST_OS_ARCH)
847 set_config("HOST_ALIAS", host.alias)
850 @depends(target)
851 def target_is_windows(target):
852     if target.kernel == "WINNT":
853         return True
856 @depends(host)
857 def host_is_windows(host):
858     if host.kernel == "WINNT":
859         return True
862 set_define("_WINDOWS", target_is_windows)
863 set_define("WIN32", target_is_windows)
864 set_define("XP_WIN", target_is_windows)
867 @depends(target)
868 def target_is_unix(target):
869     if target.kernel != "WINNT":
870         return True
873 set_define("XP_UNIX", target_is_unix)
876 @depends(target)
877 def target_is_darwin(target):
878     if target.kernel == "Darwin":
879         return True
882 set_define("XP_DARWIN", target_is_darwin)
885 @depends(target)
886 def target_is_osx(target):
887     if target.kernel == "Darwin" and target.os == "OSX":
888         return True
891 @depends(host)
892 def host_is_osx(host):
893     if host.os == "OSX":
894         return True
897 set_define("XP_MACOSX", target_is_osx)
900 @depends(target)
901 def target_has_linux_kernel(target):
902     if target.kernel == "Linux":
903         return True
906 set_define("XP_LINUX", target_has_linux_kernel)
909 @depends(target)
910 def target_is_linux_or_wasi(target):
911     if (target.kernel == "Linux" and target.os == "GNU") or target.kernel == "WASI":
912         return True
915 @depends(target)
916 def target_is_android(target):
917     if target.os == "Android":
918         return True
921 set_define("ANDROID", target_is_android)
924 @depends(target)
925 def target_is_openbsd(target):
926     if target.kernel == "OpenBSD":
927         return True
930 set_define("XP_OPENBSD", target_is_openbsd)
933 @depends(target)
934 def target_is_netbsd(target):
935     if target.kernel == "NetBSD":
936         return True
939 set_define("XP_NETBSD", target_is_netbsd)
942 @depends(target)
943 def target_is_freebsd(target):
944     if target.kernel == "FreeBSD":
945         return True
948 set_define("XP_FREEBSD", target_is_freebsd)
951 @depends(target)
952 def target_is_solaris(target):
953     if target.kernel == "SunOS":
954         return True
957 set_define("XP_SOLARIS", target_is_solaris)
960 @depends(target)
961 def target_is_sparc(target):
962     if target.cpu == "sparc64":
963         return True
966 set_define("SPARC64", target_is_sparc)
969 @depends(target, when=target_is_android)
970 def android_cpu_arch(target):
971     d = {
972         "aarch64": "arm64-v8a",
973         "arm": "armeabi-v7a",
974         "x86": "x86",
975         "x86_64": "x86_64",
976     }
977     if target.cpu not in d:
978         die(f"Cannot determine android_cpu_arch: unknown target.cpu: {target.cpu}")
979     return d[target.cpu]
982 set_config("ANDROID_CPU_ARCH", android_cpu_arch)
985 @depends("--enable-project", build_environment, "--help")
986 @imports(_from="os.path", _import="exists")
987 def include_project_configure(project, build_env, help):
988     if not project:
989         die("--enable-project is required.")
991     base_dir = build_env.topsrcdir
992     path = os.path.join(base_dir, project[0], "moz.configure")
993     if not exists(path):
994         die("Cannot find project %s", project[0])
995     return path
998 @depends("--enable-project")
999 def build_project(project):
1000     return project[0]
1003 set_config("MOZ_BUILD_APP", build_project)
1004 set_define("MOZ_BUILD_APP", build_project)
1005 add_old_configure_assignment("MOZ_BUILD_APP", build_project)
1008 option(env="MOZILLA_OFFICIAL", help="Build an official release")
1011 @depends("MOZILLA_OFFICIAL")
1012 def mozilla_official(official):
1013     if official:
1014         return True
1017 set_config("MOZILLA_OFFICIAL", mozilla_official)
1018 set_define("MOZILLA_OFFICIAL", mozilla_official)
1019 add_old_configure_assignment("MOZILLA_OFFICIAL", mozilla_official)
1022 # Allow specifying custom paths to the version files used by the milestone() function below.
1023 option(
1024     "--with-version-file-path",
1025     nargs=1,
1026     help="Specify a custom path to app version files instead of auto-detecting",
1027     default=None,
1031 @depends("--with-version-file-path")
1032 def version_path(path):
1033     return path
1036 # Allow to easily build nightly with a release / beta configuration so that we
1037 # can have the same options we'd have on a release version.
1038 # This is useful for performance profiling, as there are things that we don't
1039 # enable in release (like the background hang monitor) that can affect
1040 # performance.
1041 option(
1042     "--as-milestone",
1043     help="Build with another milestone configuration (e.g., as release)",
1044     choices=("early-beta", "late-beta", "release"),
1045     default=None,
1049 # set RELEASE_OR_BETA and NIGHTLY_BUILD variables depending on the cycle we're in
1050 # The logic works like this:
1051 # - if we have "a1" in GRE_MILESTONE, we're building Nightly (define NIGHTLY_BUILD)
1052 # - otherwise, if we have "a" in GRE_MILESTONE, we're building Nightly or Aurora
1053 # - otherwise, we're building Release/Beta (define RELEASE_OR_BETA)
1054 @depends(
1055     build_environment,
1056     build_project,
1057     version_path,
1058     "--as-milestone",
1059     "--help",
1061 @imports(_from="__builtin__", _import="open")
1062 @imports("os")
1063 @imports("re")
1064 def milestone(build_env, build_project, version_path, as_milestone, _):
1065     versions = []
1066     paths = ["config/milestone.txt"]
1067     if build_project == "js":
1068         paths = paths * 3
1069     else:
1070         paths += [
1071             "browser/config/version.txt",
1072             "browser/config/version_display.txt",
1073         ]
1074     if version_path:
1075         version_path = version_path[0]
1076     else:
1077         version_path = os.path.join(build_project, "config")
1078     for f in ("version.txt", "version_display.txt"):
1079         f = os.path.join(version_path, f)
1080         if not os.path.exists(os.path.join(build_env.topsrcdir, f)):
1081             break
1082         paths.append(f)
1084     for p in paths:
1085         with open(os.path.join(build_env.topsrcdir, p), "r") as fh:
1086             content = fh.read().splitlines()
1087             if not content:
1088                 die("Could not find a version number in {}".format(p))
1089             versions.append(content[-1])
1091     is_early_beta_or_earlier = None
1092     if as_milestone:
1093         if "a1" not in versions[0]:
1094             # We could make this work with some effort
1095             die("--as-milestone only works on nightly builds")
1096         as_milestone = as_milestone[0]
1097         as_milestone_flag = "" if as_milestone == "release" else "b1"
1098         versions = [v.replace("a1", as_milestone_flag) for v in versions]
1099         if as_milestone == "early-beta":
1100             is_early_beta_or_earlier = True
1102     milestone, firefox_version, firefox_version_display = versions[:3]
1104     # version.txt content from the project directory if there is one, otherwise
1105     # the firefox version.
1106     app_version = versions[3] if len(versions) > 3 else firefox_version
1107     # version_display.txt content from the project directory if there is one,
1108     # otherwise version.txt content from the project directory, otherwise the
1109     # firefox version for display.
1110     app_version_display = versions[-1] if len(versions) > 3 else firefox_version_display
1112     is_nightly = is_release_or_beta = None
1114     if "a1" in milestone:
1115         is_nightly = True
1116     elif "a" not in milestone:
1117         is_release_or_beta = True
1119     major_version = milestone.split(".")[0]
1120     m = re.search(r"([ab]\d+)", milestone)
1121     ab_patch = m.group(1) if m else ""
1123     if not as_milestone:
1124         defines = os.path.join(build_env.topsrcdir, "build", "defines.sh")
1125         with open(defines, "r") as fh:
1126             for line in fh.read().splitlines():
1127                 line = line.strip()
1128                 if not line or line.startswith("#"):
1129                     continue
1130                 name, _, value = line.partition("=")
1131                 name = name.strip()
1132                 value = value.strip()
1133                 if name != "EARLY_BETA_OR_EARLIER":
1134                     die(
1135                         "Only the EARLY_BETA_OR_EARLIER variable can be set in build/defines.sh"
1136                     )
1137                 if value and any(x in app_version_display for x in "ab"):
1138                     is_early_beta_or_earlier = True
1140     # Only expose the major version milestone in the UA string and hide the
1141     # patch leve (bugs 572659 and 870868).
1142     #
1143     # Only expose major milestone and alpha version in the symbolversion
1144     # string; as the name suggests, we use it for symbol versioning on Linux.
1145     return namespace(
1146         version=milestone,
1147         uaversion="%s.0" % major_version,
1148         symbolversion="%s%s" % (major_version, ab_patch),
1149         is_nightly=is_nightly,
1150         is_release_or_beta=is_release_or_beta,
1151         is_early_beta_or_earlier=is_early_beta_or_earlier,
1152         is_esr=app_version_display.endswith("esr") or None,
1153         app_version=app_version,
1154         app_version_display=app_version_display,
1155     )
1158 set_config("GRE_MILESTONE", milestone.version)
1159 set_config("NIGHTLY_BUILD", milestone.is_nightly)
1160 set_define("NIGHTLY_BUILD", milestone.is_nightly)
1161 set_config("RELEASE_OR_BETA", milestone.is_release_or_beta)
1162 set_define("RELEASE_OR_BETA", milestone.is_release_or_beta)
1163 set_config("MOZ_ESR", milestone.is_esr)
1164 set_define("MOZ_ESR", milestone.is_esr)
1165 set_config("EARLY_BETA_OR_EARLIER", milestone.is_early_beta_or_earlier)
1166 set_define("EARLY_BETA_OR_EARLIER", milestone.is_early_beta_or_earlier)
1167 set_define("MOZILLA_VERSION", depends(milestone)(lambda m: '"%s"' % m.version))
1168 set_config("MOZILLA_VERSION", milestone.version)
1169 set_define("MOZILLA_VERSION_U", milestone.version)
1170 set_define("MOZILLA_UAVERSION", depends(milestone)(lambda m: '"%s"' % m.uaversion))
1171 set_config("MOZILLA_SYMBOLVERSION", milestone.symbolversion)
1172 # JS configure still want to look at this one.
1173 add_old_configure_assignment("MOZILLA_SYMBOLVERSION", milestone.symbolversion)
1175 set_config("MOZ_APP_VERSION", milestone.app_version)
1176 set_config("MOZ_APP_VERSION_DISPLAY", milestone.app_version_display)
1177 add_old_configure_assignment("MOZ_APP_VERSION", milestone.app_version)
1179 add_old_configure_assignment("NIGHTLY_BUILD", milestone.is_nightly)
1181 # The app update channel is 'default' when not supplied. The value is used in
1182 # the application's confvars.sh (and is made available to a project specific
1183 # moz.configure).
1184 option(
1185     "--enable-update-channel",
1186     nargs=1,
1187     help="Select application update channel",
1188     default="default",
1192 @depends("--enable-update-channel")
1193 def update_channel(channel):
1194     if not channel or channel[0] == "":
1195         return "default"
1196     return channel[0].lower()
1199 set_config("MOZ_UPDATE_CHANNEL", update_channel)
1200 set_define("MOZ_UPDATE_CHANNEL", update_channel)
1201 add_old_configure_assignment("MOZ_UPDATE_CHANNEL", update_channel)
1204 option(
1205     env="MOZBUILD_STATE_PATH",
1206     nargs=1,
1207     help="Path to a persistent state directory for the build system "
1208     "and related tools",
1212 @depends("MOZBUILD_STATE_PATH", "--help")
1213 @imports("os")
1214 def mozbuild_state_path(path, _):
1215     if path:
1216         return normalize_path(path[0])
1217     return normalize_path(os.path.expanduser(os.path.join("~", ".mozbuild")))
1220 @depends("MOZILLABUILD", shell, host_is_windows)
1221 @imports(_from="pathlib", _import="Path")
1222 def mozillabuild_bin_paths(mozillabuild, shell, host_is_windows):
1223     paths = []
1224     if not mozillabuild or not host_is_windows:
1225         return paths
1226     paths.append(os.path.dirname(shell))
1227     paths.append(str(Path(mozillabuild[0]) / "bin"))
1228     return paths
1231 @depends(mozillabuild_bin_paths)
1232 @imports("os")
1233 def prefer_mozillabuild_path(mozillabuild_bin_paths):
1234     return mozillabuild_bin_paths + os.environ["PATH"].split(os.pathsep)
1237 # milestone.is_nightly corresponds to cases NIGHTLY_BUILD is set.
1240 @depends(milestone)
1241 def enabled_in_nightly(milestone):
1242     return milestone.is_nightly
1245 # Branding
1246 # ==============================================================
1247 option(
1248     "--with-app-basename",
1249     env="MOZ_APP_BASENAME",
1250     nargs=1,
1251     help="Typically stays consistent for multiple branded versions of a "
1252     'given application (e.g. Aurora and Firefox both use "Firefox"), but '
1253     "may vary for full rebrandings (e.g. Iceweasel). Used for "
1254     'application.ini\'s "Name" field, which controls profile location in '
1255     'the absence of a "Profile" field (see below), and various system '
1256     "integration hooks (Unix remoting, Windows MessageWindow name, etc.",
1260 @depends("--with-app-basename", target_is_android)
1261 def moz_app_basename(value, target_is_android):
1262     if value:
1263         return value[0]
1264     if target_is_android:
1265         return "Fennec"
1266     return "Firefox"
1269 set_config(
1270     "MOZ_APP_BASENAME",
1271     moz_app_basename,
1272     when=depends(build_project)(lambda p: p != "js"),