Bug 1869043 add a main thread record of track audio outputs r=padenot
[gecko.git] / build / moz.configure / init.configure
blob11e22ee53682693837f89fa0658cd88ce8fd7f77
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=normalize_path(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             target_cpu, target_system = (
732                 ("aarch64", "android")
733                 if host.cpu == "aarch64"
734                 else ("arm", "androideabi")
735             )
736             return split_triplet(f"{target_cpu}-unknown-linux-{target_system}")
737         return host
738     # If --target was only given a cpu arch, expand it with the
739     # non-cpu part of the host. For mobile/android, expand it with
740     # unknown-linux-android.
741     target = value[0]
742     if "-" not in target:
743         if project == "mobile/android":
744             rest = "unknown-linux-android"
745             if target.startswith("arm"):
746                 rest += "eabi"
747         else:
748             cpu, rest = host.alias.split("-", 1)
749         target = "-".join((target, rest))
750         try:
751             return split_triplet(target)
752         except ValueError:
753             pass
755     try:
756         return split_triplet(config_sub(shell, target), allow_wasi=(project == "js"))
757     except ValueError as e:
758         die(e)
761 target = help_host_target | real_target
764 @depends(host, target)
765 @checking("whether cross compiling")
766 def cross_compiling(host, target):
767     return host != target
770 set_config("CROSS_COMPILE", cross_compiling)
771 set_define("CROSS_COMPILE", cross_compiling)
774 @depends(target)
775 def have_64_bit(target):
776     if target.bitness == 64:
777         return True
780 set_config("HAVE_64BIT_BUILD", have_64_bit)
781 set_define("HAVE_64BIT_BUILD", have_64_bit)
782 add_old_configure_assignment("HAVE_64BIT_BUILD", have_64_bit)
784 # Some third-party code bases depend on this being set for big-endians.
785 set_define(
786     "WORDS_BIGENDIAN", True, when=depends(target.endianness)(lambda e: e == "big")
790 # Autoconf needs these set
793 @depends(host)
794 def host_for_sub_configure(host):
795     return "--host=%s" % host.sub_configure_alias
798 @depends(target)
799 def target_for_sub_configure(target):
800     return "--target=%s" % target.sub_configure_alias
803 # These variables are for compatibility with the current moz.builds and
804 # old-configure. Eventually, we'll want to canonicalize better.
805 @depends(target)
806 def target_variables(target):
807     if target.kernel == "kFreeBSD":
808         os_target = "GNU/kFreeBSD"
809         os_arch = "GNU_kFreeBSD"
810     elif target.kernel == "Darwin" or (target.kernel == "Linux" and target.os == "GNU"):
811         os_target = target.kernel
812         os_arch = target.kernel
813     else:
814         os_target = target.os
815         os_arch = target.kernel
817     return namespace(
818         OS_TARGET=str(os_target),
819         OS_ARCH=str(os_arch),
820         INTEL_ARCHITECTURE=target.cpu in ("x86", "x86_64") or None,
821     )
824 set_config("OS_TARGET", target_variables.OS_TARGET)
825 add_old_configure_assignment("OS_TARGET", target_variables.OS_TARGET)
826 set_config("OS_ARCH", target_variables.OS_ARCH)
827 add_old_configure_assignment("OS_ARCH", target_variables.OS_ARCH)
828 obsolete_config("CPU_ARCH", replacement="TARGET_CPU")
829 set_config("INTEL_ARCHITECTURE", target_variables.INTEL_ARCHITECTURE)
830 set_config("TARGET_CPU", target.cpu)
831 add_old_configure_assignment("TARGET_CPU", target.cpu)
832 set_config("TARGET_RAW_CPU", target.raw_cpu)
833 set_config("TARGET_OS", target.os)
834 set_config("TARGET_RAW_OS", target.raw_os)
835 set_config("TARGET_ENDIANNESS", target.endianness)
838 @depends(host)
839 def host_variables(host):
840     if host.kernel == "kFreeBSD":
841         os_arch = "GNU_kFreeBSD"
842     else:
843         os_arch = host.kernel
844     return namespace(
845         HOST_OS_ARCH=os_arch,
846     )
849 set_config("HOST_CPU_ARCH", host.cpu)
850 set_config("HOST_OS_ARCH", host_variables.HOST_OS_ARCH)
851 add_old_configure_assignment("HOST_OS_ARCH", host_variables.HOST_OS_ARCH)
852 set_config("HOST_ALIAS", host.alias)
855 @depends(target)
856 def target_is_windows(target):
857     if target.kernel == "WINNT":
858         return True
861 @depends(host)
862 def host_is_windows(host):
863     if host.kernel == "WINNT":
864         return True
867 set_define("_WINDOWS", target_is_windows)
868 set_define("WIN32", target_is_windows)
869 set_define("XP_WIN", target_is_windows)
872 @depends(target)
873 def target_is_unix(target):
874     if target.kernel != "WINNT":
875         return True
878 set_define("XP_UNIX", target_is_unix)
881 @depends(target)
882 def target_is_darwin(target):
883     if target.kernel == "Darwin":
884         return True
887 set_define("XP_DARWIN", target_is_darwin)
890 @depends(target)
891 def target_is_osx(target):
892     if target.kernel == "Darwin" and target.os == "OSX":
893         return True
896 @depends(host)
897 def host_is_osx(host):
898     if host.os == "OSX":
899         return True
902 set_define("XP_MACOSX", target_is_osx)
905 @depends(target)
906 def target_has_linux_kernel(target):
907     if target.kernel == "Linux":
908         return True
911 set_define("XP_LINUX", target_has_linux_kernel)
914 @depends(target)
915 def target_is_linux_or_wasi(target):
916     if (target.kernel == "Linux" and target.os == "GNU") or target.kernel == "WASI":
917         return True
920 @depends(target)
921 def target_is_android(target):
922     if target.os == "Android":
923         return True
926 set_define("ANDROID", target_is_android)
929 @depends(target)
930 def target_is_openbsd(target):
931     if target.kernel == "OpenBSD":
932         return True
935 set_define("XP_OPENBSD", target_is_openbsd)
938 @depends(target)
939 def target_is_netbsd(target):
940     if target.kernel == "NetBSD":
941         return True
944 set_define("XP_NETBSD", target_is_netbsd)
947 @depends(target)
948 def target_is_freebsd(target):
949     if target.kernel == "FreeBSD":
950         return True
953 set_define("XP_FREEBSD", target_is_freebsd)
956 @depends(target)
957 def target_is_solaris(target):
958     if target.kernel == "SunOS":
959         return True
962 set_define("XP_SOLARIS", target_is_solaris)
965 @depends(target)
966 def target_is_sparc(target):
967     if target.cpu == "sparc64":
968         return True
971 set_define("SPARC64", target_is_sparc)
974 @depends(target, when=target_is_android)
975 def android_cpu_arch(target):
976     d = {
977         "aarch64": "arm64-v8a",
978         "arm": "armeabi-v7a",
979         "x86": "x86",
980         "x86_64": "x86_64",
981     }
982     if target.cpu not in d:
983         die(f"Cannot determine android_cpu_arch: unknown target.cpu: {target.cpu}")
984     return d[target.cpu]
987 set_config("ANDROID_CPU_ARCH", android_cpu_arch)
990 @depends("--enable-project", build_environment, "--help")
991 @imports(_from="os.path", _import="exists")
992 def include_project_configure(project, build_env, help):
993     if not project:
994         die("--enable-project is required.")
996     base_dir = build_env.topsrcdir
997     path = os.path.join(base_dir, project[0], "moz.configure")
998     if not exists(path):
999         die("Cannot find project %s", project[0])
1000     return path
1003 @depends("--enable-project")
1004 def build_project(project):
1005     return project[0]
1008 set_config("MOZ_BUILD_APP", build_project)
1009 set_define("MOZ_BUILD_APP", build_project)
1010 add_old_configure_assignment("MOZ_BUILD_APP", build_project)
1013 option(env="MOZILLA_OFFICIAL", help="Build an official release")
1016 @depends("MOZILLA_OFFICIAL")
1017 def mozilla_official(official):
1018     if official:
1019         return True
1022 set_config("MOZILLA_OFFICIAL", mozilla_official)
1023 set_define("MOZILLA_OFFICIAL", mozilla_official)
1024 add_old_configure_assignment("MOZILLA_OFFICIAL", mozilla_official)
1027 # Allow specifying custom paths to the version files used by the milestone() function below.
1028 option(
1029     "--with-version-file-path",
1030     nargs=1,
1031     help="Specify a custom path to app version files instead of auto-detecting",
1032     default=None,
1036 @depends("--with-version-file-path")
1037 def version_path(path):
1038     return path
1041 # Allow to easily build nightly with a release / beta configuration so that we
1042 # can have the same options we'd have on a release version.
1043 # This is useful for performance profiling, as there are things that we don't
1044 # enable in release (like the background hang monitor) that can affect
1045 # performance.
1046 option(
1047     "--as-milestone",
1048     help="Build with another milestone configuration (e.g., as release)",
1049     choices=("early-beta", "late-beta", "release"),
1050     default=None,
1054 # set RELEASE_OR_BETA and NIGHTLY_BUILD variables depending on the cycle we're in
1055 # The logic works like this:
1056 # - if we have "a1" in GRE_MILESTONE, we're building Nightly (define NIGHTLY_BUILD)
1057 # - otherwise, if we have "a" in GRE_MILESTONE, we're building Nightly or Aurora
1058 # - otherwise, we're building Release/Beta (define RELEASE_OR_BETA)
1059 @depends(
1060     build_environment,
1061     build_project,
1062     version_path,
1063     "--as-milestone",
1064     "--help",
1066 @imports(_from="__builtin__", _import="open")
1067 @imports("os")
1068 @imports("re")
1069 def milestone(build_env, build_project, version_path, as_milestone, _):
1070     versions = []
1071     paths = ["config/milestone.txt"]
1072     if build_project == "js":
1073         paths = paths * 3
1074     else:
1075         paths += [
1076             "browser/config/version.txt",
1077             "browser/config/version_display.txt",
1078         ]
1079     if version_path:
1080         version_path = version_path[0]
1081     else:
1082         version_path = os.path.join(build_project, "config")
1083     for f in ("version.txt", "version_display.txt"):
1084         f = os.path.join(version_path, f)
1085         if not os.path.exists(os.path.join(build_env.topsrcdir, f)):
1086             break
1087         paths.append(f)
1089     for p in paths:
1090         with open(os.path.join(build_env.topsrcdir, p), "r") as fh:
1091             content = fh.read().splitlines()
1092             if not content:
1093                 die("Could not find a version number in {}".format(p))
1094             versions.append(content[-1])
1096     is_early_beta_or_earlier = None
1097     if as_milestone:
1098         if "a1" not in versions[0]:
1099             # We could make this work with some effort
1100             die("--as-milestone only works on nightly builds")
1101         as_milestone = as_milestone[0]
1102         as_milestone_flag = "" if as_milestone == "release" else "b1"
1103         versions = [v.replace("a1", as_milestone_flag) for v in versions]
1104         if as_milestone == "early-beta":
1105             is_early_beta_or_earlier = True
1107     milestone, firefox_version, firefox_version_display = versions[:3]
1109     # version.txt content from the project directory if there is one, otherwise
1110     # the firefox version.
1111     app_version = versions[3] if len(versions) > 3 else firefox_version
1112     # version_display.txt content from the project directory if there is one,
1113     # otherwise version.txt content from the project directory, otherwise the
1114     # firefox version for display.
1115     app_version_display = versions[-1] if len(versions) > 3 else firefox_version_display
1117     is_nightly = is_release_or_beta = None
1119     if "a1" in milestone:
1120         is_nightly = True
1121     elif "a" not in milestone:
1122         is_release_or_beta = True
1124     major_version = milestone.split(".")[0]
1125     m = re.search(r"([ab]\d+)", milestone)
1126     ab_patch = m.group(1) if m else ""
1128     if not as_milestone:
1129         defines = os.path.join(build_env.topsrcdir, "build", "defines.sh")
1130         with open(defines, "r") as fh:
1131             for line in fh.read().splitlines():
1132                 line = line.strip()
1133                 if not line or line.startswith("#"):
1134                     continue
1135                 name, _, value = line.partition("=")
1136                 name = name.strip()
1137                 value = value.strip()
1138                 if name != "EARLY_BETA_OR_EARLIER":
1139                     die(
1140                         "Only the EARLY_BETA_OR_EARLIER variable can be set in build/defines.sh"
1141                     )
1142                 if value and any(x in app_version_display for x in "ab"):
1143                     is_early_beta_or_earlier = True
1145     # Only expose the major version milestone in the UA string and hide the
1146     # patch leve (bugs 572659 and 870868).
1147     #
1148     # Only expose major milestone and alpha version in the symbolversion
1149     # string; as the name suggests, we use it for symbol versioning on Linux.
1150     return namespace(
1151         version=milestone,
1152         uaversion="%s.0" % major_version,
1153         symbolversion="%s%s" % (major_version, ab_patch),
1154         is_nightly=is_nightly,
1155         is_release_or_beta=is_release_or_beta,
1156         is_early_beta_or_earlier=is_early_beta_or_earlier,
1157         is_esr=app_version_display.endswith("esr") or None,
1158         app_version=app_version,
1159         app_version_display=app_version_display,
1160     )
1163 set_config("GRE_MILESTONE", milestone.version)
1164 set_config("NIGHTLY_BUILD", milestone.is_nightly)
1165 set_define("NIGHTLY_BUILD", milestone.is_nightly)
1166 set_config("RELEASE_OR_BETA", milestone.is_release_or_beta)
1167 set_define("RELEASE_OR_BETA", milestone.is_release_or_beta)
1168 set_config("MOZ_ESR", milestone.is_esr)
1169 set_define("MOZ_ESR", milestone.is_esr)
1170 set_config("EARLY_BETA_OR_EARLIER", milestone.is_early_beta_or_earlier)
1171 set_define("EARLY_BETA_OR_EARLIER", milestone.is_early_beta_or_earlier)
1172 set_define("MOZILLA_VERSION", depends(milestone)(lambda m: '"%s"' % m.version))
1173 set_config("MOZILLA_VERSION", milestone.version)
1174 set_define("MOZILLA_VERSION_U", milestone.version)
1175 set_define("MOZILLA_UAVERSION", depends(milestone)(lambda m: '"%s"' % m.uaversion))
1176 set_config("MOZILLA_SYMBOLVERSION", milestone.symbolversion)
1177 # JS configure still want to look at this one.
1178 add_old_configure_assignment("MOZILLA_SYMBOLVERSION", milestone.symbolversion)
1180 set_config("MOZ_APP_VERSION", milestone.app_version)
1181 set_config("MOZ_APP_VERSION_DISPLAY", milestone.app_version_display)
1182 add_old_configure_assignment("MOZ_APP_VERSION", milestone.app_version)
1184 add_old_configure_assignment("NIGHTLY_BUILD", milestone.is_nightly)
1186 # The app update channel is 'default' when not supplied. The value is used in
1187 # the application's confvars.sh (and is made available to a project specific
1188 # moz.configure).
1189 option(
1190     "--enable-update-channel",
1191     nargs=1,
1192     help="Select application update channel",
1193     default="default",
1197 @depends("--enable-update-channel")
1198 def update_channel(channel):
1199     if not channel or channel[0] == "":
1200         return "default"
1201     return channel[0].lower()
1204 set_config("MOZ_UPDATE_CHANNEL", update_channel)
1205 set_define("MOZ_UPDATE_CHANNEL", update_channel)
1206 add_old_configure_assignment("MOZ_UPDATE_CHANNEL", update_channel)
1209 option(
1210     env="MOZBUILD_STATE_PATH",
1211     nargs=1,
1212     help="Path to a persistent state directory for the build system "
1213     "and related tools",
1217 @depends("MOZBUILD_STATE_PATH", "--help")
1218 @imports("os")
1219 def mozbuild_state_path(path, _):
1220     if path:
1221         return normalize_path(path[0])
1222     return normalize_path(os.path.expanduser(os.path.join("~", ".mozbuild")))
1225 @depends("MOZILLABUILD", shell, host_is_windows)
1226 @imports(_from="pathlib", _import="Path")
1227 def mozillabuild_bin_paths(mozillabuild, shell, host_is_windows):
1228     paths = []
1229     if not mozillabuild or not host_is_windows:
1230         return paths
1231     paths.append(os.path.dirname(shell))
1232     paths.append(str(Path(mozillabuild[0]) / "bin"))
1233     return paths
1236 @depends(mozillabuild_bin_paths)
1237 @imports("os")
1238 def prefer_mozillabuild_path(mozillabuild_bin_paths):
1239     return mozillabuild_bin_paths + os.environ["PATH"].split(os.pathsep)
1242 # milestone.is_nightly corresponds to cases NIGHTLY_BUILD is set.
1245 @depends(milestone)
1246 def enabled_in_nightly(milestone):
1247     return milestone.is_nightly
1250 # Branding
1251 # ==============================================================
1252 option(
1253     "--with-app-basename",
1254     env="MOZ_APP_BASENAME",
1255     nargs=1,
1256     help="Typically stays consistent for multiple branded versions of a "
1257     'given application (e.g. Aurora and Firefox both use "Firefox"), but '
1258     "may vary for full rebrandings (e.g. Iceweasel). Used for "
1259     'application.ini\'s "Name" field, which controls profile location in '
1260     'the absence of a "Profile" field (see below), and various system '
1261     "integration hooks (Unix remoting, Windows MessageWindow name, etc.",
1265 @depends("--with-app-basename", target_is_android)
1266 def moz_app_basename(value, target_is_android):
1267     if value:
1268         return value[0]
1269     if target_is_android:
1270         return "Fennec"
1271     return "Firefox"
1274 set_config(
1275     "MOZ_APP_BASENAME",
1276     moz_app_basename,
1277     when=depends(build_project)(lambda p: p != "js"),