Debian Codegraph @

build/moz.configure/toolchain.configure

raw
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/.
6
7 # Environment variables that impact the compilation step
8 # ==============================================================
9 option(
10 env="HOST_CPPFLAGS",
11 help="Extra flags for Preprocessing host sources",
12 nargs=1,
13 default="",
14 )
15
16
17 option(
18 env="HOST_CFLAGS",
19 help="Extra flags for compiling host C sources",
20 nargs=1,
21 default="",
22 )
23
24
25 option(
26 env="HOST_CXXFLAGS",
27 help="Extra flags for compiling host C++ sources",
28 nargs=1,
29 default="",
30 )
31
32
33 option(
34 env="HOST_LDFLAGS",
35 help="Extra flags for linking host object files",
36 nargs=1,
37 default="",
38 )
39
40
41 option(
42 env="CPPFLAGS",
43 help="Extra flags for preprocessing sources",
44 nargs=1,
45 default="",
46 )
47
48
49 option(
50 env="CFLAGS",
51 help="Extra flags for compiling C sources",
52 nargs=1,
53 default="",
54 )
55
56
57 option(
58 env="CXXFLAGS",
59 help="Extra flags for compiling C++ sources",
60 nargs=1,
61 default="",
62 )
63
64
65 option(
66 env="ASFLAGS",
67 help="Extra flags for assembling sources",
68 nargs=1,
69 default="",
70 )
71
72
73 option(
74 env="LDFLAGS",
75 help="Extra flags for linking object files",
76 nargs=1,
77 default="",
78 )
79
80
81 option(
82 env="LIBS",
83 help="Extra libraries for linking object files",
84 nargs=1,
85 default="",
86 )
87
88
89 option(
90 env="MOZ_OPTIMIZE_FLAGS",
91 help="Extra optimization flags",
92 nargs=1,
93 )
94
95
96 # Code optimization
97 # ==============================================================
98
99 option("--disable-optimize", nargs="?", help="Disable optimizations via compiler flags")
100
101
102 @depends(target, when="MOZ_PGO")
103 def forced_pgo_optimization_level(target):
104 if target.kernel == "Linux" and target.os != "Android":
105 return "-O3"
106
107
108 @imports(_from="mozbuild.shellutil", _import="quote")
109 def check_optimize_flags(src, flags):
110 for flag in reversed(flags):
111 if flag.startswith(("-O", "/O")):
112 if flag[2:] == "0":
113 die(
114 f"Optimization enabled through {src} but last optimization flag is {flag} which disables optimizations"
115 )
116 break
117 else:
118 die(
119 f"Optimization enabled through {src} but no optimization flag found in {quote(*flags)}"
120 )
121 return flags
122
123
124 @depends("--enable-optimize", "MOZ_OPTIMIZE_FLAGS")
125 @imports(_from="mozbuild.shellutil", _import="split")
126 def configured_moz_optimize_flags(enable_optimize, env_flags):
127 if len(enable_optimize):
128 return check_optimize_flags("--enable-optimize", split(enable_optimize[0]))
129 if len(env_flags):
130 return check_optimize_flags("MOZ_OPTIMIZE_FLAGS", split(env_flags[0]))
131
132
133 @depends("--enable-optimize", "MOZ_OPTIMIZE_FLAGS")
134 def moz_optimize(enable_optimize, env_flags):
135 return "1" if enable_optimize or env_flags else None
136
137
138 set_config("MOZ_OPTIMIZE", moz_optimize)
139
140
141 @depends(
142 target, moz_optimize, configured_moz_optimize_flags, forced_pgo_optimization_level
143 )
144 @imports(_from="mozbuild.shellutil", _import="split")
145 def moz_optimize_flags(
146 target, moz_optimize, configured_moz_optimize_flags, forced_pgo_optimization_level
147 ):
148 if configured_moz_optimize_flags:
149 return configured_moz_optimize_flags
150
151 if moz_optimize and forced_pgo_optimization_level:
152 return [forced_pgo_optimization_level]
153
154 if target.kernel == "Darwin":
155 return ["-O3"]
156 elif target.kernel in ("Linux", "WINNT"):
157 return ["-O2"]
158 else:
159 return ["-O"]
160
161
162 # Android NDK
163 # ==============================================================
164
165
166 @depends("--disable-compile-environment", target)
167 def compiling_android(compile_env, target):
168 return compile_env and target.os == "Android"
169
170
171 include("android-ndk.configure", when=compiling_android)
172
173 with only_when(target_is_osx):
174 # MacOS deployment target version
175 # ==============================================================
176 # This needs to happen before any compilation test is done.
177
178 option(
179 "--enable-macos-target",
180 env="MACOSX_DEPLOYMENT_TARGET",
181 nargs=1,
182 default=depends(target, developer_options)
183 # We continue to target 10.15 on Intel, but can target 11.0 for
184 # aarch64 since the earliest hardware was released alongside 11.0.
185 # For local builds, we want to target 10.15 regardless of the
186 # underlying platform to catch any errors or warnings that wouldn't
187 # show up when targeting 11.0, since these would later show up on
188 # CI for Intel builds.
189 (lambda t, d: "11.0" if (t.cpu == "aarch64" and not d) else "10.15"),
190 help="Set the minimum MacOS version needed at runtime{|}",
191 )
192
193 @depends_if("--enable-macos-target", developer_options)
194 def macos_target(value, _):
195 return value[0]
196
197
198 @imports("plistlib")
199 @imports(_from="__builtin__", _import="open")
200 @imports(_from="__builtin__", _import="Exception")
201 def get_sdk_settings(sdk):
202 with open(os.path.join(sdk, "SDKSettings.plist"), "rb") as plist:
203 obj = plistlib.load(plist)
204 if not obj:
205 raise Exception(
206 "Error parsing SDKSettings.plist in the SDK directory: %s" % sdk
207 )
208 return obj
209
210
211 @imports(_from="__builtin__", _import="Exception")
212 def get_sdk_version_from_settings(sdk, settings):
213 if "Version" not in settings:
214 raise Exception(
215 "Error finding Version information in SDKSettings.plist from the SDK: %s"
216 % sdk
217 )
218 return Version(settings["Version"])
219
220
221 def get_sdk_version(sdk):
222 return get_sdk_version_from_settings(sdk, get_sdk_settings(sdk))
223
224
225 with only_when(host_is_osx | target_is_osx):
226 # MacOS SDK
227 # =========
228 option(
229 "--with-macos-sdk",
230 env="MACOS_SDK_DIR",
231 nargs=1,
232 help="Location of platform SDK to use",
233 )
234
235 def mac_sdk_min_version():
236 return "15.5"
237
238 @depends(
239 "--with-macos-sdk",
240 host,
241 bootstrap_path(
242 "MacOSX{}.sdk".format(mac_sdk_min_version()),
243 when=depends("--with-macos-sdk")(lambda x: not x),
244 allow_failure=True,
245 ),
246 )
247 @imports(_from="__builtin__", _import="Exception")
248 @imports(_from="os.path", _import="isdir")
249 @imports(_from="os", _import="listdir")
250 def macos_sdk(sdk, host, bootstrapped):
251 if bootstrapped:
252 sdk = [bootstrapped]
253 if sdk:
254 sdk = sdk[0]
255 try:
256 version = get_sdk_version(sdk)
257 except Exception as e:
258 die(e)
259 elif host.os == "OSX":
260 sdk = check_cmd_output(
261 "xcrun", "--show-sdk-path", onerror=lambda: ""
262 ).rstrip()
263 if not sdk:
264 die(
265 "Could not find the macOS SDK. Please use --with-macos-sdk to give "
266 "the path to a macOS SDK."
267 )
268 # Scan the parent directory xcrun returns for the most recent SDK.
269 sdk_dir = os.path.dirname(sdk)
270 versions = []
271 for d in listdir(sdk_dir):
272 if d.lower().startswith("macos"):
273 try:
274 sdk = os.path.join(sdk_dir, d)
275 versions.append((get_sdk_version(sdk), sdk))
276 except Exception:
277 pass
278 version, sdk = max(versions)
279 else:
280 die(
281 "Need a macOS SDK when targeting macOS. Please use --with-macos-sdk "
282 "to give the path to a macOS SDK."
283 )
284
285 if not isdir(sdk):
286 die(
287 "SDK not found in %s. When using --with-macos-sdk, you must specify a "
288 "valid SDK. SDKs are installed when the optional cross-development "
289 "tools are selected during the Xcode/Developer Tools installation."
290 % sdk
291 )
292 if version < Version(mac_sdk_min_version()):
293 die(
294 'SDK version "%s" is too old. Please upgrade to at least %s. Try '
295 "updating your system Xcode." % (version, mac_sdk_min_version())
296 )
297 return sdk
298
299 set_config("MACOS_SDK_DIR", macos_sdk)
300
301
302 with only_when(target_is_osx):
303 with only_when(cross_compiling):
304 option(
305 "--with-macos-private-frameworks",
306 env="MACOS_PRIVATE_FRAMEWORKS_DIR",
307 nargs=1,
308 help="Location of private frameworks to use",
309 )
310
311 @depends_if("--with-macos-private-frameworks")
312 @imports(_from="os.path", _import="isdir")
313 def macos_private_frameworks(value):
314 if value and not isdir(value[0]):
315 die(
316 "PrivateFrameworks not found not found in %s. When using "
317 "--with-macos-private-frameworks, you must specify a valid "
318 "directory",
319 value[0],
320 )
321 return value[0]
322
323 @depends(macos_private_frameworks, macos_sdk)
324 def macos_private_frameworks(value, sdk):
325 if value:
326 return value
327 return os.path.join(sdk or "/", "System/Library/PrivateFrameworks")
328
329 set_config("MACOS_PRIVATE_FRAMEWORKS_DIR", macos_private_frameworks)
330
331
332 with only_when(target_is_ios):
333 # iOS deployment target version
334 # ==============================================================
335 # This needs to happen before any compilation test is done.
336
337 option(
338 "--enable-ios-target",
339 env="IPHONEOS_DEPLOYMENT_TARGET",
340 nargs=1,
341 default="18.4",
342 help="Set the minimum iOS version needed at runtime",
343 )
344
345 @depends_if("--enable-ios-target")
346 def ios_target(value):
347 return value[0]
348
349
350 with only_when(target_is_ios):
351 # iOS SDK
352 # =======
353 option(
354 "--with-ios-sdk",
355 env="IPHONEOS_SDK_DIR",
356 nargs=1,
357 help="Location of platform SDK to use",
358 )
359
360 @depends(target)
361 def target_is_ios_simulator(target):
362 # x86_64-apple-ios is simulator
363 # aarch64-apple-ios is iphone
364 # aarch64-apple-ios-sim is simulator
365 return target.cpu == "x86_64" or target.raw_os == "ios-sim"
366
367 def ios_sdk_min_version():
368 return "18.4"
369
370 @depends(target_is_ios_simulator)
371 def ios_sdk_name(target_is_ios_simulator):
372 return "iPhone{}{}.sdk".format(
373 "Simulator" if target_is_ios_simulator else "OS",
374 ios_sdk_min_version(),
375 )
376
377 @depends(
378 "--with-ios-sdk",
379 host,
380 target,
381 target_is_ios_simulator,
382 bootstrap_path(ios_sdk_name, when=depends("--with-ios-sdk")(lambda x: not x)),
383 )
384 @imports(_from="__builtin__", _import="Exception")
385 @imports(_from="os.path", _import="isdir")
386 @imports(_from="os", _import="listdir")
387 def ios_sdk(sdk, host, target, target_is_ios_simulator, bootstrapped):
388 if bootstrapped:
389 sdk = [bootstrapped]
390 sdk_name = "iphonesimulator" if target_is_ios_simulator else "iphoneos"
391 if sdk:
392 sdk = sdk[0]
393 try:
394 settings = get_sdk_settings(sdk)
395 version = get_sdk_version_from_settings(sdk, settings)
396 except Exception as e:
397 die(e)
398 elif host.os == "OSX":
399 sdk = check_cmd_output(
400 "xcrun", "--show-sdk-path", "--sdk", sdk_name, onerror=lambda: ""
401 ).rstrip()
402 if not sdk:
403 die(
404 "Could not find the iOS SDK. Please use --with-ios-sdk to give "
405 "the path to a iOS SDK."
406 )
407 # Scan the parent directory xcrun returns for the most recent SDK.
408 sdk_dir = os.path.dirname(sdk)
409 versions = []
410 for d in listdir(sdk_dir):
411 if d.lower().startswith(sdk_name):
412 try:
413 sdk = os.path.join(sdk_dir, d)
414 settings = get_sdk_settings(sdk)
415 version = get_sdk_version_from_settings(sdk, settings)
416 versions.append((version, sdk, settings))
417 except Exception:
418 pass
419 version, sdk, settings = max(versions)
420 else:
421 die(
422 "Need an iOS SDK when targeting iOS. Please use --with-ios-sdk "
423 "to give the path to a iOS SDK."
424 )
425
426 if not isdir(sdk):
427 die(
428 "SDK not found in %s. When using --with-ios-sdk, you must specify a "
429 "valid SDK. SDKs are installed when the optional cross-development "
430 "tools are selected during the Xcode installation." % sdk
431 )
432
433 supported_targets = settings.get("SupportedTargets")
434 if supported_targets:
435 supported_archs = supported_targets.get(sdk_name, {}).get("Archs", [])
436 cpu = {
437 "aarch64": "arm64",
438 }.get(target.cpu, str(target.cpu))
439 if cpu not in supported_archs:
440 die("The SDK in %s does not support target %s" % (sdk, target.alias))
441 else:
442 log.warning(
443 "Cannot check whether the iOS SDK is for the right target, "
444 "assuming it is."
445 )
446 if version < Version(ios_sdk_min_version()):
447 die(
448 'SDK version "%s" is too old. Please upgrade to at least %s. Try '
449 "updating your system Xcode." % (version, ios_sdk_min_version())
450 )
451 return sdk
452
453 set_config("IPHONEOS_SDK_DIR", ios_sdk)
454
455
456 # GC rooting and hazard analysis.
457 # ==============================================================
458 option(env="MOZ_HAZARD", help="Build for the GC rooting hazard analysis")
459
460
461 @depends("MOZ_HAZARD")
462 def hazard_analysis(value):
463 if value:
464 return True
465
466
467 # Cross-compilation related things.
468 # ==============================================================
469 option(
470 "--with-toolchain-prefix",
471 env="TOOLCHAIN_PREFIX",
472 nargs=1,
473 help="Prefix for the target toolchain",
474 )
475
476
477 @depends("--with-toolchain-prefix", host, target, cross_compiling)
478 def toolchain_prefix(value, host, target, cross_compiling):
479 if value:
480 return tuple(value)
481 # We don't want a toolchain prefix by default when building on mac for mac.
482 if cross_compiling and not (target.os == "OSX" and host.os == "OSX"):
483 return ("%s-" % target.toolchain, "%s-" % target.alias)
484
485
486 # Compilers
487 # ==============================================================
488 include("compilers-util.configure")
489
490
491 def try_preprocess(
492 configure_cache, compiler, language, source, onerror=None, wrapper=[]
493 ):
494 return try_invoke_compiler(
495 configure_cache, compiler, language, source, ["-E"], onerror, wrapper
496 )
497
498
499 @imports(_from="mozbuild.configure.constants", _import="CompilerType")
500 @imports(_from="mozbuild.configure.constants", _import="CPU_preprocessor_checks")
501 @imports(_from="mozbuild.configure.constants", _import="kernel_preprocessor_checks")
502 @imports(_from="mozbuild.configure.constants", _import="OS_preprocessor_checks")
503 @imports(_from="textwrap", _import="dedent")
504 @imports(_from="__builtin__", _import="Exception")
505 def get_compiler_info(configure_cache, compiler, language):
506 """Returns information about the given `compiler` (command line in the
507 form of a list or tuple), in the given `language`.
508
509 The returned information includes:
510 - the compiler type (clang-cl, clang or gcc)
511 - the compiler version
512 - the compiler supported language
513 - the compiler supported language version
514 """
515 # Xcode clang versions are different from the underlying llvm version (they
516 # instead are aligned with the Xcode version). Fortunately, we can tell
517 # apart plain clang from Xcode clang, and convert the Xcode clang version
518 # into the more or less corresponding plain clang version.
519 check = dedent(
520 """\
521 #if defined(_MSC_VER) && defined(__clang__) && defined(_MT)
522 %COMPILER "clang-cl"
523 %VERSION __clang_major__.__clang_minor__.__clang_patchlevel__
524 #elif defined(__clang__)
525 %COMPILER "clang"
526 %VERSION __clang_major__.__clang_minor__.__clang_patchlevel__
527 # ifdef __apple_build_version__
528 %XCODE 1
529 # endif
530 #elif defined(__GNUC__) && !defined(__MINGW32__)
531 %COMPILER "gcc"
532 %VERSION __GNUC__.__GNUC_MINOR__.__GNUC_PATCHLEVEL__
533 #endif
534
535 #if __cplusplus
536 %cplusplus __cplusplus
537 #elif __STDC_VERSION__
538 %STDC_VERSION __STDC_VERSION__
539 #endif
540 """
541 )
542
543 # While we're doing some preprocessing, we might as well do some more
544 # preprocessor-based tests at the same time, to check the toolchain
545 # matches what we want.
546 for name, preprocessor_checks in (
547 ("CPU", CPU_preprocessor_checks),
548 ("KERNEL", kernel_preprocessor_checks),
549 ("OS", OS_preprocessor_checks),
550 ):
551 for n, (value, condition) in enumerate(preprocessor_checks.items()):
552 check += dedent(
553 """\
554 #%(if)s %(condition)s
555 %%%(name)s "%(value)s"
556 """
557 % {
558 "if": "elif" if n else "if",
559 "condition": condition,
560 "name": name,
561 "value": value,
562 }
563 )
564 check += "#endif\n"
565
566 # Also check for endianness. The advantage of living in modern times is
567 # that all the modern compilers we support now have __BYTE_ORDER__ defined
568 # by the preprocessor.
569 check += dedent(
570 """\
571 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
572 %ENDIANNESS "little"
573 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
574 %ENDIANNESS "big"
575 #endif
576 """
577 )
578
579 result = try_preprocess(configure_cache, compiler, language, check)
580
581 if not result:
582 raise FatalCheckError("Unknown compiler or compiler not supported.")
583
584 # Metadata emitted by preprocessors such as GCC with LANG=ja_JP.utf-8 may
585 # have non-ASCII characters. Treat the output as bytearray.
586 data = {}
587 for line in result.splitlines():
588 if line.startswith("%"):
589 k, _, v = line.partition(" ")
590 k = k.lstrip("%")
591 data[k] = v.replace(" ", "").lstrip('"').rstrip('"')
592 log.debug("%s = %s", k, data[k])
593
594 try:
595 type = CompilerType(data["COMPILER"])
596 except Exception:
597 raise FatalCheckError("Unknown compiler or compiler not supported.")
598
599 cplusplus = int(data.get("cplusplus", "0L").rstrip("L"))
600 stdc_version = int(data.get("STDC_VERSION", "0L").rstrip("L"))
601
602 version = data.get("VERSION")
603 if version:
604 version = Version(version)
605 if data.get("XCODE"):
606 # Derived from https://en.wikipedia.org/wiki/Xcode#Toolchain_versions
607 # with enough granularity for major.minor version checks further
608 # down the line
609 if version < "9.1":
610 version = Version("4.0.0.or.less")
611 elif version < "10.0":
612 version = Version("5.0.2")
613 elif version < "10.0.1":
614 version = Version("6.0.1")
615 elif version < "11.0":
616 version = Version("7.0.0")
617 elif version < "11.0.3":
618 version = Version("8.0.0")
619 elif version < "12.0":
620 version = Version("9.0.0")
621 elif version < "12.0.5":
622 version = Version("10.0.0")
623 elif version < "13.0":
624 version = Version("11.1.0")
625 elif version < "13.0.1":
626 version = Version("12.0.0")
627 elif version < "14.0":
628 version = Version("13.0.0")
629 elif version < "14.3":
630 version = Version("14.0.0")
631 elif version < "15.0":
632 version = Version("15.0.0")
633 elif version < "16.0":
634 version = Version("16.0.0")
635 else:
636 version = Version("17.0.6.or.more")
637
638 return namespace(
639 type=type,
640 version=version,
641 cpu=data.get("CPU"),
642 kernel=data.get("KERNEL"),
643 endianness=data.get("ENDIANNESS"),
644 os=data.get("OS"),
645 language="C++" if cplusplus else "C",
646 language_version=cplusplus if cplusplus else stdc_version,
647 xcode=bool(data.get("XCODE")),
648 )
649
650
651 def same_arch_different_bits():
652 return (
653 ("x86", "x86_64"),
654 ("ppc", "ppc64"),
655 ("sparc", "sparc64"),
656 )
657
658
659 @imports(_from="mozbuild.shellutil", _import="quote")
660 @imports(_from="mozbuild.configure.constants", _import="OS_preprocessor_checks")
661 def check_compiler(configure_cache, compiler, language, target, android_version):
662 info = get_compiler_info(configure_cache, compiler, language)
663
664 flags = []
665
666 # Check language standards
667 # --------------------------------------------------------------------
668 if language != info.language:
669 raise FatalCheckError(
670 "`%s` is not a %s compiler." % (quote(*compiler), language)
671 )
672
673 # Note: We do a strict version check because there sometimes are backwards
674 # incompatible changes in the standard, and not all code that compiles as
675 # C17 compiles as C23.
676 c17_version = 201710
677 if info.language == "C" and info.language_version != c17_version:
678 if info.type == "clang-cl":
679 flags.append("-Xclang")
680 flags.append("-std=gnu17")
681
682 cxx17_version = 201703
683 if info.language == "C++":
684 if info.language_version != cxx17_version:
685 # MSVC headers include C++17 features, but don't guard them
686 # with appropriate checks.
687 if info.type == "clang-cl":
688 flags.append("-std:c++17")
689 else:
690 flags.append("-std=gnu++17")
691
692 # Check compiler target
693 # --------------------------------------------------------------------
694 has_target = False
695 if target.os == "Android" and android_version:
696 # This makes clang define __ANDROID_API__ and use versioned library
697 # directories from the NDK.
698 toolchain = "%s%d" % (target.toolchain, android_version)
699 else:
700 toolchain = target.toolchain
701
702 if info.type == "clang":
703 # Add the target explicitly when the target is aarch64 macosx, because
704 # the Xcode clang target is named differently, and we need to work around
705 # https://github.com/rust-lang/rust-bindgen/issues/1871 and
706 # https://github.com/alexcrichton/cc-rs/issues/542 so we always want
707 # the target on the command line, even if the compiler would default to
708 # that.
709 if info.xcode and target.os == "OSX" and target.cpu == "aarch64":
710 if "--target=arm64-apple-darwin" not in compiler:
711 flags.append("--target=arm64-apple-darwin")
712 has_target = True
713 elif target.os == "iOS":
714 target_flag = "--target=%s" % toolchain
715 if target_flag not in compiler:
716 flags.append(target_flag)
717 has_target = True
718 elif (
719 not info.kernel
720 or info.kernel != target.kernel
721 or not info.endianness
722 or info.endianness != target.endianness
723 ):
724 flags.append("--target=%s" % toolchain)
725 has_target = True
726
727 # Add target flag when there is an OS mismatch (e.g. building for Android on
728 # Linux). However, only do this if the target OS is in our whitelist, to
729 # keep things the same on other platforms.
730 elif target.os in OS_preprocessor_checks and (
731 not info.os or info.os != target.os
732 ):
733 flags.append("--target=%s" % toolchain)
734 has_target = True
735
736 if not has_target and (not info.cpu or info.cpu != target.cpu):
737 same_arch = same_arch_different_bits()
738 if (target.cpu, info.cpu) in same_arch:
739 flags.append("-m32")
740 elif (info.cpu, target.cpu) in same_arch:
741 flags.append("-m64")
742 elif info.type == "clang-cl" and target.cpu == "aarch64":
743 flags.append("--target=%s" % toolchain)
744 elif info.type == "clang":
745 flags.append("--target=%s" % toolchain)
746
747 return namespace(
748 type=info.type,
749 version=info.version,
750 target_cpu=info.cpu,
751 target_kernel=info.kernel,
752 target_endianness=info.endianness,
753 target_os=info.os,
754 flags=flags,
755 )
756
757
758 @imports(_from="__builtin__", _import="open")
759 @imports("json")
760 @imports("os")
761 def get_vc_paths(host, topsrcdir):
762 def vswhere(args):
763 program_files = os.environ.get("PROGRAMFILES(X86)") or os.environ.get(
764 "PROGRAMFILES"
765 )
766 if not program_files:
767 return []
768 vswhere = os.path.join(
769 program_files, "Microsoft Visual Studio", "Installer", "vswhere.exe"
770 )
771 if not os.path.exists(vswhere):
772 return []
773 return json.loads(check_cmd_output(vswhere, "-format", "json", *args))
774
775 variant = "arm64" if host.cpu == "aarch64" else "x86.x64"
776 for install in vswhere(
777 [
778 "-products",
779 "*",
780 "-requires",
781 f"Microsoft.VisualStudio.Component.VC.Tools.{variant}",
782 ]
783 ):
784 path = install["installationPath"]
785 tools_version = (
786 open(
787 os.path.join(
788 path, r"VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt"
789 ),
790 "r",
791 )
792 .read()
793 .strip()
794 )
795 tools_path = os.path.join(path, r"VC\Tools\MSVC", tools_version)
796 yield (Version(install["installationVersion"]), tools_path)
797
798
799 @depends(target, host)
800 def is_windows(target, host):
801 return host.kernel == "WINNT" or target.kernel == "WINNT"
802
803
804 # Calling this a sysroot is a little weird, but it's the terminology clang went
805 # with with its -winsysroot flag.
806 option(
807 env="WINSYSROOT",
808 nargs=1,
809 when=is_windows,
810 help='Path to a Windows "sysroot" (directory containing MSVC, SDKs)',
811 )
812
813
814 @depends(
815 "WINSYSROOT",
816 bootstrap_path(
817 "vs",
818 when=depends("WINSYSROOT", when=is_windows)(lambda x: not x),
819 ),
820 when=is_windows,
821 )
822 def winsysroot(winsysroot, bootstrapped):
823 if bootstrapped:
824 return bootstrapped
825 if winsysroot:
826 return winsysroot[0]
827
828
829 option(
830 env="VC_PATH",
831 nargs=1,
832 when=is_windows,
833 help="Path to the Microsoft Visual C/C++ compiler",
834 )
835
836
837 @depends(
838 host,
839 build_environment,
840 "VC_PATH",
841 winsysroot,
842 when=is_windows,
843 )
844 @imports("os")
845 @imports(_from="operator", _import="itemgetter")
846 def vc_compiler_paths_for_version(host, env, vc_path, winsysroot):
847 if winsysroot:
848 if vc_path:
849 die("WINSYSROOT and VC_PATH cannot be set together.")
850 base_vc_path = os.path.join(winsysroot, "VC", "Tools", "MSVC")
851 versions = os.listdir(base_vc_path)
852 vc_path = [os.path.join(base_vc_path, str(max(Version(v) for v in versions)))]
853 if vc_path:
854 # Use an arbitrary version, it doesn't matter.
855 all_versions = [(Version("15"), vc_path[0])]
856 elif host.kernel != "WINNT":
857 # Don't try to do anything when VC_PATH is not set on cross-compiles.
858 return
859 else:
860 all_versions = sorted(get_vc_paths(host, env.topsrcdir), key=itemgetter(0))
861 if not all_versions:
862 return
863 # Choose the newest version.
864 path = all_versions[-1][1]
865 host_dir = {
866 "x86_64": "Hostx64",
867 "x86": "Hostx86",
868 "aarch64": "Hostarm64",
869 }.get(host.cpu)
870 if host_dir:
871 path = os.path.join(path, "bin", host_dir)
872 return {
873 "x64": [os.path.join(path, "x64")],
874 # The cross toolchains require DLLs from the native x64 toolchain.
875 "x86": [os.path.join(path, "x86"), os.path.join(path, "x64")],
876 "arm64": [os.path.join(path, "arm64"), os.path.join(path, "x64")],
877 }
878
879
880 @depends(target, host, vc_compiler_paths_for_version, when=is_windows)
881 def vc_compiler_path(target, host, paths):
882 cpu = target.cpu if target.os == "WINNT" else host.cpu
883 vc_target = {
884 "x86": "x86",
885 "x86_64": "x64",
886 "arm": "arm",
887 "aarch64": "arm64",
888 }.get(cpu)
889 if not paths:
890 return
891 return paths.get(vc_target)
892
893
894 @depends(vc_compiler_path, original_path)
895 @imports("os")
896 @imports(_from="os", _import="environ")
897 def vc_toolchain_search_path(vc_compiler_path, original_path):
898 result = list(original_path)
899
900 if vc_compiler_path:
901 # The second item, if there is one, is necessary to have in $PATH for
902 # Windows to load the required DLLs from there.
903 if len(vc_compiler_path) > 1:
904 environ["PATH"] = os.pathsep.join(result + vc_compiler_path[1:])
905
906 # The first item is where the programs are going to be
907 result.append(vc_compiler_path[0])
908
909 return result
910
911
912 @depends_if(vc_compiler_path, when=is_windows)
913 def vc_compiler_version(vc_compiler_path):
914 version = Version(
915 os.path.basename(
916 os.path.dirname(os.path.dirname(os.path.dirname(vc_compiler_path[0])))
917 )
918 )
919 # MSVC path with version 14.x is actually version 19.x
920 if version.major == 14:
921 return Version(f"19.{version.minor}")
922
923
924 @depends_if(vc_compiler_version)
925 def msvs_version(vc_compiler_version):
926 # clang-cl emulates the same version scheme as cl. And MSVS_VERSION needs to
927 # be set for GYP on Windows.
928 if vc_compiler_version >= Version("19.30"):
929 return "2022"
930 configure_error("Only Visual Studio 2022 or newer are supported")
931
932 return ""
933
934
935 set_config("MSVS_VERSION", msvs_version)
936
937
938 clang_search_path = bootstrap_search_path("clang/bin")
939
940
941 @depends(
942 bootstrap_path("rustc/bin", when=moz_automation),
943 original_path,
944 )
945 @imports("os")
946 @imports(_from="os", _import="environ")
947 def rust_search_path(rust_path, original_path):
948 result = []
949 # The order we search for a rust compiler is:
950 # - bootstrap directory (only used by CI at the moment)
951 # - rustup install directory ($CARGO_HOME/bin)
952 # - $PATH
953 cargo_home = environ.get("CARGO_HOME", "")
954 if cargo_home:
955 cargo_home = os.path.abspath(cargo_home)
956 else:
957 cargo_home = os.path.expanduser(os.path.join("~", ".cargo"))
958 rustup_path = os.path.join(cargo_home, "bin")
959 if rust_path:
960 result.append(rust_path)
961 result.append(rustup_path)
962 result.extend(original_path)
963 return result
964
965
966 # Prepend the mozilla-build msys2 path, since otherwise we can get mismatched
967 # cygwin dll errors during configure if we get called from another msys2
968 # environment, see bug 1801826.
969 @depends(
970 mozillabuild_bin_paths, clang_search_path, rust_search_path, target, original_path
971 )
972 @imports("os")
973 def altered_path(
974 mozillabuild_bin_paths, clang_search_path, rust_search_path, target, original_path
975 ):
976 altered_path = mozillabuild_bin_paths
977 if target.kernel == "Darwin":
978 # The rust compiler wants to execute dsymutil, but it does so in a
979 # non-configurable way (https://github.com/rust-lang/rust/issues/52728)
980 # so we add the clang path.
981 path = clang_search_path
982 else:
983 path = original_path
984 # cargo needs the rust search path to find cargo-$subcommand.
985 path += rust_search_path
986 for p in path:
987 if p not in altered_path:
988 altered_path.append(p)
989 return os.pathsep.join(altered_path)
990
991
992 set_config("PATH", altered_path)
993
994
995 # Compiler wrappers
996 # ==============================================================
997 option(
998 "--with-compiler-wrapper",
999 env="COMPILER_WRAPPER",
1000 nargs=1,
1001 help="Enable compiling with wrappers such as distcc and ccache",
1002 )
1003
1004 option("--with-ccache", env="CCACHE", nargs="?", help="Enable compiling with ccache")
1005
1006
1007 @depends_if("--with-ccache")
1008 def ccache(value):
1009 if len(value):
1010 return value
1011 # If --with-ccache was given without an explicit value, we default to
1012 # 'ccache'.
1013 return "ccache"
1014
1015
1016 ccache = check_prog(
1017 "CCACHE",
1018 progs=(),
1019 input=ccache,
1020 paths=bootstrap_search_path(
1021 "sccache", when=depends("CCACHE")(lambda c: len(c) and c[0] == "sccache")
1022 ),
1023 allow_missing=True,
1024 )
1025
1026 option(env="CCACHE_PREFIX", nargs=1, help="Compiler prefix to use when using ccache")
1027
1028 ccache_prefix = depends_if("CCACHE_PREFIX")(lambda prefix: prefix[0])
1029 set_config("CCACHE_PREFIX", ccache_prefix)
1030
1031 # Distinguish ccache from sccache.
1032
1033
1034 @depends_if(ccache)
1035 def ccache_is_sccache(ccache):
1036 return check_cmd_output(ccache, "--version").startswith("sccache")
1037
1038
1039 @depends(ccache, ccache_is_sccache)
1040 def using_ccache(ccache, ccache_is_sccache):
1041 return ccache and not ccache_is_sccache
1042
1043
1044 @depends_if(ccache, ccache_is_sccache)
1045 def using_sccache(ccache, ccache_is_sccache):
1046 return ccache and ccache_is_sccache
1047
1048
1049 option(env="RUSTC_WRAPPER", nargs=1, help="Wrap rust compilation with given tool")
1050
1051
1052 @depends(ccache, ccache_is_sccache, "RUSTC_WRAPPER")
1053 @imports(_from="textwrap", _import="dedent")
1054 @imports("os")
1055 def check_sccache_version(ccache, ccache_is_sccache, rustc_wrapper):
1056 sccache_min_version = Version("0.2.13")
1057
1058 def check_version(path):
1059 out = check_cmd_output(path, "--version")
1060 version = Version(out.rstrip().split()[-1])
1061 if version < sccache_min_version:
1062 die(
1063 dedent(
1064 """\
1065 sccache %s or later is required. sccache in use at %s has
1066 version %s.
1067
1068 Please upgrade or acquire a new version with |./mach bootstrap|.
1069 """
1070 ),
1071 sccache_min_version,
1072 path,
1073 version,
1074 )
1075
1076 if ccache and ccache_is_sccache:
1077 check_version(ccache)
1078
1079 if rustc_wrapper and (
1080 os.path.splitext(os.path.basename(rustc_wrapper[0]))[0].lower() == "sccache"
1081 ):
1082 check_version(rustc_wrapper[0])
1083
1084
1085 set_config("MOZ_USING_CCACHE", using_ccache)
1086 set_config("MOZ_USING_SCCACHE", using_sccache)
1087
1088 option(env="SCCACHE_VERBOSE_STATS", help="Print verbose sccache stats after build")
1089
1090
1091 @depends(using_sccache, "SCCACHE_VERBOSE_STATS")
1092 def sccache_verbose_stats(using_sccache, verbose_stats):
1093 return using_sccache and bool(verbose_stats)
1094
1095
1096 set_config("SCCACHE_VERBOSE_STATS", sccache_verbose_stats)
1097
1098
1099 @depends("--with-compiler-wrapper", ccache)
1100 @imports(_from="mozbuild.shellutil", _import="split", _as="shell_split")
1101 def compiler_wrapper(wrapper, ccache):
1102 if wrapper:
1103 raw_wrapper = wrapper[0]
1104 wrapper = shell_split(raw_wrapper)
1105 wrapper_program = find_program(wrapper[0])
1106 if not wrapper_program:
1107 die(
1108 "Cannot find `%s` from the given compiler wrapper `%s`",
1109 wrapper[0],
1110 raw_wrapper,
1111 )
1112 wrapper[0] = wrapper_program
1113
1114 if ccache:
1115 if wrapper:
1116 return tuple([ccache] + wrapper)
1117 else:
1118 return (ccache,)
1119 elif wrapper:
1120 return tuple(wrapper)
1121
1122
1123 @dependable
1124 def wasm():
1125 return split_triplet("wasm32-wasi", allow_wasi=True)
1126
1127
1128 @template
1129 def default_c_compilers(host_or_target, other_c_compiler=None):
1130 """Template defining the set of default C compilers for the host and
1131 target platforms.
1132 `host_or_target` is either `host` or `target` (the @depends functions
1133 from init.configure.
1134 `other_c_compiler` is the `target` C compiler when `host_or_target` is `host`.
1135 """
1136 assert host_or_target in {host, target, wasm}
1137
1138 other_c_compiler = () if other_c_compiler is None else (other_c_compiler,)
1139
1140 @depends(host_or_target, target, toolchain_prefix, *other_c_compiler)
1141 def default_c_compilers(
1142 host_or_target, target, toolchain_prefix, *other_c_compiler
1143 ):
1144 if host_or_target.kernel == "WINNT":
1145 if host_or_target.abi:
1146 if host_or_target.abi == "msvc":
1147 supported = types = ("clang-cl",)
1148 elif host_or_target.abi == "mingw":
1149 supported = types = ("clang",)
1150 else:
1151 supported = types = ("clang-cl", "clang")
1152 elif host_or_target.kernel == "Darwin":
1153 types = ("clang",)
1154 supported = ("clang", "gcc")
1155 elif host_or_target.kernel == "WASI":
1156 supported = types = ("clang",)
1157 else:
1158 supported = types = ("clang", "gcc")
1159
1160 info = other_c_compiler[0] if other_c_compiler else None
1161 if info and info.type in supported:
1162 # When getting default C compilers for the host, we prioritize the
1163 # same compiler as the target C compiler.
1164 prioritized = info.compiler
1165 if info.type == "gcc":
1166 same_arch = same_arch_different_bits()
1167 if (
1168 target.cpu != host_or_target.cpu
1169 and (target.cpu, host_or_target.cpu) not in same_arch
1170 and (host_or_target.cpu, target.cpu) not in same_arch
1171 ):
1172 # If the target C compiler is GCC, and it can't be used with
1173 # -m32/-m64 for the host, it's probably toolchain-prefixed,
1174 # so we prioritize a raw 'gcc' instead.
1175 prioritized = info.type
1176 if target.os != "WINNT" and host_or_target.os == "WINNT":
1177 # When cross-compiling on Windows, don't prioritize. We'll fallback
1178 # to checking for clang-cl first.
1179 pass
1180 else:
1181 types = [prioritized] + [t for t in types if t != info.type]
1182
1183 gcc = ("gcc",)
1184 if toolchain_prefix and host_or_target is target:
1185 gcc = tuple("%sgcc" % p for p in toolchain_prefix) + gcc
1186
1187 result = []
1188 for type in types:
1189 if type == "gcc":
1190 result.extend(gcc)
1191 else:
1192 result.append(type)
1193
1194 return tuple(result)
1195
1196 return default_c_compilers
1197
1198
1199 @template
1200 def default_cxx_compilers(c_compiler, other_c_compiler=None, other_cxx_compiler=None):
1201 """Template defining the set of default C++ compilers for the host and
1202 target platforms.
1203 `c_compiler` is the @depends function returning a Compiler instance for
1204 the desired platform.
1205
1206 Because the build system expects the C and C++ compilers to be from the
1207 same compiler suite, we derive the default C++ compilers from the C
1208 compiler that was found if none was provided.
1209
1210 We also factor in the target C++ compiler when getting the default host
1211 C++ compiler, using the target C++ compiler if the host and target C
1212 compilers are the same.
1213 """
1214
1215 assert (other_c_compiler is None) == (other_cxx_compiler is None)
1216 if other_c_compiler is not None:
1217 other_compilers = (other_c_compiler, other_cxx_compiler)
1218 else:
1219 other_compilers = ()
1220
1221 @depends(c_compiler, *other_compilers)
1222 def default_cxx_compilers(c_compiler, *other_compilers):
1223 if other_compilers:
1224 other_c_compiler, other_cxx_compiler = other_compilers
1225 if other_c_compiler.compiler == c_compiler.compiler:
1226 return (other_cxx_compiler.compiler,)
1227
1228 dir = os.path.dirname(c_compiler.compiler)
1229 file = os.path.basename(c_compiler.compiler)
1230
1231 if c_compiler.type == "gcc":
1232 return (os.path.join(dir, file.replace("gcc", "g++")),)
1233
1234 if c_compiler.type == "clang":
1235 return (os.path.join(dir, file.replace("clang", "clang++")),)
1236
1237 return (c_compiler.compiler,)
1238
1239 return default_cxx_compilers
1240
1241
1242 @template
1243 def provided_program(env_var, when=None):
1244 """Template handling cases where a program can be specified either as a
1245 path or as a path with applicable arguments.
1246 """
1247
1248 @depends_if(env_var, when=when)
1249 @imports(_from="itertools", _import="takewhile")
1250 @imports(_from="mozbuild.shellutil", _import="split", _as="shell_split")
1251 def provided(cmd):
1252 # Assume the first dash-prefixed item (and any subsequent items) are
1253 # command-line options, the item before the dash-prefixed item is
1254 # the program we're looking for, and anything before that is a wrapper
1255 # of some kind (e.g. sccache).
1256 cmd = shell_split(cmd[0])
1257
1258 without_flags = list(takewhile(lambda x: not x.startswith("-"), cmd))
1259
1260 return namespace(
1261 wrapper=without_flags[:-1],
1262 program=without_flags[-1],
1263 flags=cmd[len(without_flags) :],
1264 )
1265
1266 return provided
1267
1268
1269 @template
1270 def sysroot(host_or_target, target_sysroot=None):
1271 assert target_sysroot or host_or_target is target
1272 bootstrap_target_when = target_is_linux_or_wasi
1273 if host_or_target is host:
1274 host_or_target_str = "host"
1275 opt = "--with-host-sysroot"
1276 env = "HOST_SYSROOT"
1277 when = depends(host)(lambda h: h.kernel == "Linux")
1278
1279 # Only bootstrap a host sysroot when using a bootstrapped target sysroot
1280 # or when the target doesn't use a bootstrapped sysroot in the first place.
1281 @depends(when, bootstrap_target_when, target_sysroot.bootstrapped)
1282 def bootstrap_when(when, bootstrap_target_when, bootstrapped):
1283 return when and (bootstrapped or not bootstrap_target_when)
1284
1285 else:
1286 assert host_or_target is target
1287 host_or_target_str = "target"
1288 opt = "--with-sysroot"
1289 env = "SYSROOT"
1290 when = target_is_linux_or_wasi
1291 bootstrap_when = bootstrap_target_when
1292
1293 option(
1294 opt,
1295 env=env,
1296 nargs=1,
1297 when=when,
1298 help="Use the given sysroot directory for %s build" % host_or_target_str,
1299 )
1300
1301 sysroot_input = depends(opt, when=when)(lambda x: x)
1302 bootstrap_sysroot = depends(bootstrap_when, sysroot_input)(
1303 # Only bootstrap when no flag was explicitly given (either --with or --without)
1304 lambda bootstrap, input: bootstrap
1305 and not input
1306 and input.origin == "default"
1307 )
1308
1309 @depends(
1310 sysroot_input,
1311 host_or_target,
1312 macos_sdk,
1313 ios_sdk,
1314 bootstrap_path(
1315 depends(host_or_target)(lambda t: "sysroot-{}".format(t.toolchain)),
1316 when=bootstrap_sysroot,
1317 ),
1318 )
1319 @imports("os")
1320 def sysroot(sysroot_input, host_or_target, macos_sdk, ios_sdk, path):
1321 version = None
1322 if sysroot_input:
1323 path = sysroot_input[0]
1324 elif host_or_target.os == "OSX" and macos_sdk:
1325 path = macos_sdk
1326 elif host_or_target.os == "iOS" and ios_sdk:
1327 path = ios_sdk
1328 if path:
1329 # Find the version of libstdc++ headears in the sysroot
1330 include = os.path.join(path, "usr/include/c++")
1331 if os.path.isdir(include):
1332 with os.scandir(include) as d:
1333 version = max(Version(e.name) for e in d if e.is_dir())
1334 log.info("Using %s sysroot in %s", host_or_target_str, path)
1335 return namespace(
1336 path=path,
1337 bootstrapped=bool(path and not sysroot_input),
1338 stdcxx_version=version,
1339 )
1340
1341 return sysroot
1342
1343
1344 target_sysroot = sysroot(target)
1345
1346
1347 # Use `system_lib_option` instead of `option` for options that enable building
1348 # with a system library for which the development headers are not available in
1349 # the bootstrapped sysroots.
1350 @template
1351 def system_lib_option(name, *args, **kwargs):
1352 option(name, *args, **kwargs)
1353
1354 @depends(
1355 name,
1356 target_sysroot.bootstrapped,
1357 when=kwargs.get("when"),
1358 )
1359 def no_system_lib_in_sysroot(value, bootstrapped):
1360 if bootstrapped and value:
1361 die(
1362 "%s is not supported with bootstrapped sysroot. "
1363 "Drop the option, or use --without-sysroot or --disable-bootstrap",
1364 value.format(name),
1365 )
1366
1367
1368 host_sysroot = sysroot(host, target_sysroot)
1369
1370
1371 @template
1372 def multiarch_dir(host_or_target):
1373 sysroot = {
1374 host: host_sysroot,
1375 target: target_sysroot,
1376 }[host_or_target]
1377
1378 @depends(host_or_target, when=sysroot.path)
1379 def multiarch_dir(target):
1380 if target.cpu == "x86":
1381 # Turn e.g. i686-linux-gnu into i386-linux-gnu
1382 return target.toolchain.replace(target.raw_cpu, "i386")
1383 return target.toolchain
1384
1385 return multiarch_dir
1386
1387
1388 target_multiarch_dir = multiarch_dir(target)
1389 host_multiarch_dir = multiarch_dir(host)
1390
1391
1392 def minimum_gcc_version():
1393 return Version("8.1.0")
1394
1395
1396 @template
1397 def compiler(
1398 language,
1399 host_or_target,
1400 c_compiler=None,
1401 other_compiler=None,
1402 other_c_compiler=None,
1403 ):
1404 """Template handling the generic base checks for the compiler for the
1405 given `language` on the given platform (`host_or_target`).
1406 `host_or_target` is either `host` or `target` (the @depends functions
1407 from init.configure.
1408 When the language is 'C++', `c_compiler` is the result of the `compiler`
1409 template for the language 'C' for the same `host_or_target`.
1410 When `host_or_target` is `host`, `other_compiler` is the result of the
1411 `compiler` template for the same `language` for `target`.
1412 When `host_or_target` is `host` and the language is 'C++',
1413 `other_c_compiler` is the result of the `compiler` template for the
1414 language 'C' for `target`.
1415 """
1416 assert host_or_target in {host, target, wasm}
1417 assert language in ("C", "C++")
1418 assert language == "C" or c_compiler is not None
1419 assert host_or_target is target or other_compiler is not None
1420 assert language == "C" or host_or_target is target or other_c_compiler is not None
1421
1422 host_or_target_str = {
1423 host: "host",
1424 target: "target",
1425 wasm: "wasm",
1426 }[host_or_target]
1427
1428 sysroot = {
1429 host: host_sysroot,
1430 target: target_sysroot,
1431 wasm: dependable(lambda: namespace(path=None)),
1432 }[host_or_target]
1433
1434 multiarch_dir = {
1435 host: host_multiarch_dir,
1436 target: target_multiarch_dir,
1437 wasm: never,
1438 }[host_or_target]
1439
1440 var = {
1441 ("C", target): "CC",
1442 ("C++", target): "CXX",
1443 ("C", host): "HOST_CC",
1444 ("C++", host): "HOST_CXX",
1445 ("C", wasm): "WASM_CC",
1446 ("C++", wasm): "WASM_CXX",
1447 }[language, host_or_target]
1448
1449 default_compilers = {
1450 "C": lambda: default_c_compilers(host_or_target, other_compiler),
1451 "C++": lambda: default_cxx_compilers(
1452 c_compiler, other_c_compiler, other_compiler
1453 ),
1454 }[language]()
1455
1456 what = "the %s %s compiler" % (host_or_target_str, language)
1457
1458 option(env=var, nargs=1, help="Path to %s" % what)
1459
1460 # Handle the compiler given by the user through one of the CC/CXX/HOST_CC/
1461 # HOST_CXX variables.
1462 provided_compiler = provided_program(var)
1463
1464 # Normally, we'd use `var` instead of `_var`, but the interaction with
1465 # old-configure complicates things, and for now, we a) can't take the plain
1466 # result from check_prog as CC/CXX/HOST_CC/HOST_CXX and b) have to let
1467 # old-configure AC_SUBST it (because it's autoconf doing it, not us)
1468 compiler = check_prog(
1469 "_%s" % var,
1470 what=what,
1471 progs=default_compilers,
1472 input=provided_compiler.program,
1473 paths=clang_search_path,
1474 )
1475
1476 @depends(
1477 configure_cache,
1478 compiler,
1479 provided_compiler,
1480 compiler_wrapper,
1481 host_or_target,
1482 sysroot,
1483 macos_target,
1484 ios_target,
1485 android_version,
1486 vc_compiler_version,
1487 multiarch_dir,
1488 winsysroot,
1489 host,
1490 )
1491 @checking("whether %s can be used" % what, lambda x: bool(x))
1492 @imports(_from="mozbuild.shellutil", _import="quote")
1493 @imports("os")
1494 def valid_compiler(
1495 configure_cache,
1496 compiler,
1497 provided_compiler,
1498 compiler_wrapper,
1499 host_or_target,
1500 sysroot,
1501 macos_target,
1502 ios_target,
1503 android_version,
1504 vc_compiler_version,
1505 multiarch_dir,
1506 winsysroot,
1507 host,
1508 ):
1509 wrapper = list(compiler_wrapper or ())
1510 flags = []
1511 if sysroot.path:
1512 if host_or_target.kernel == "Darwin":
1513 # While --sysroot and -isysroot are roughly equivalent, when not using
1514 # -isysroot on mac, clang takes the SDKROOT environment variable into
1515 # consideration, which may be set by python and break things.
1516 flags.extend(("-isysroot", sysroot.path))
1517 else:
1518 flags.extend(("--sysroot", sysroot.path))
1519 if provided_compiler:
1520 wrapper.extend(provided_compiler.wrapper)
1521 flags.extend(provided_compiler.flags)
1522
1523 info = check_compiler(
1524 configure_cache,
1525 wrapper + [compiler] + flags,
1526 language,
1527 host_or_target,
1528 android_version,
1529 )
1530
1531 if host_or_target.os == "OSX" and macos_target:
1532 flags.append("-mmacosx-version-min=%s" % macos_target)
1533 if host_or_target.os == "iOS" and ios_target:
1534 flags.append("-mios-version-min=%s" % ios_target)
1535
1536 # When not given an explicit compatibility version, clang-cl tries
1537 # to get one from MSVC, which might not even be the one used by the
1538 # build. And when it can't find one, its default might also not match
1539 # what the build is using. So if we were able to figure out the version
1540 # we're building with, explicitly use that.
1541 # This also means that, as a side effect, clang-cl will not try to find
1542 # MSVC, which saves a little overhead.
1543 if info.type == "clang-cl" and vc_compiler_version:
1544 flags.append(f"-fms-compatibility-version={vc_compiler_version}")
1545
1546 if info.type == "clang" and language == "C++" and host_or_target.os == "OSX":
1547 flags.append("-stdlib=libc++")
1548
1549 # Check that the additional flags we got are enough to not require any
1550 # more flags. If we get an exception, just ignore it; it's liable to be
1551 # invalid command-line flags, which means the compiler we're checking
1552 # doesn't support those command-line flags and will fail one or more of
1553 # the checks below.
1554 try:
1555 if info.flags:
1556 flags += info.flags
1557 info = check_compiler(
1558 configure_cache,
1559 wrapper + [compiler] + flags,
1560 language,
1561 host_or_target,
1562 android_version,
1563 )
1564 except FatalCheckError:
1565 pass
1566
1567 if not info.target_cpu or info.target_cpu != host_or_target.cpu:
1568 raise FatalCheckError(
1569 "%s %s compiler target CPU (%s) does not match --%s CPU (%s)"
1570 % (
1571 host_or_target_str.capitalize(),
1572 language,
1573 info.target_cpu or "unknown",
1574 host_or_target_str,
1575 host_or_target.raw_cpu,
1576 )
1577 )
1578
1579 if not info.target_kernel or (info.target_kernel != host_or_target.kernel):
1580 raise FatalCheckError(
1581 "%s %s compiler target kernel (%s) does not match --%s kernel (%s)"
1582 % (
1583 host_or_target_str.capitalize(),
1584 language,
1585 info.target_kernel or "unknown",
1586 host_or_target_str,
1587 host_or_target.kernel,
1588 )
1589 )
1590
1591 if not info.target_endianness or (
1592 info.target_endianness != host_or_target.endianness
1593 ):
1594 raise FatalCheckError(
1595 "%s %s compiler target endianness (%s) does not match --%s "
1596 "endianness (%s)"
1597 % (
1598 host_or_target_str.capitalize(),
1599 language,
1600 info.target_endianness or "unknown",
1601 host_or_target_str,
1602 host_or_target.endianness,
1603 )
1604 )
1605
1606 # Compiler version checks
1607 # ===================================================
1608 # Check the compiler version here instead of in `compiler_version` so
1609 # that the `checking` message doesn't pretend the compiler can be used
1610 # to then bail out one line later.
1611 if info.type == "gcc":
1612 if host_or_target.os == "Android":
1613 raise FatalCheckError(
1614 "GCC is not supported on Android.\n"
1615 "Please use clang from the Android NDK instead."
1616 )
1617 gcc_version = minimum_gcc_version()
1618 if info.version < gcc_version:
1619 raise FatalCheckError(
1620 "Only GCC %d.%d or newer is supported (found version %s)."
1621 % (gcc_version.major, gcc_version.minor, info.version)
1622 )
1623
1624 # Force GCC to use the C++ headers from the sysroot, and to prefer the
1625 # sysroot system headers to /usr/include.
1626 # Non-Debian GCC also doesn't look at headers in multiarch directory.
1627 if sysroot.bootstrapped and sysroot.stdcxx_version:
1628 version = sysroot.stdcxx_version
1629 for path in (
1630 "usr/include/c++/{}".format(version),
1631 "usr/include/{}/c++/{}".format(multiarch_dir, version),
1632 "usr/include/{}".format(multiarch_dir),
1633 "usr/include",
1634 ):
1635 flags.extend(("-isystem", os.path.join(sysroot.path, path)))
1636
1637 if info.type == "clang-cl":
1638 if info.version < "9.0.0":
1639 raise FatalCheckError(
1640 "Only clang-cl 9.0 or newer is supported (found version %s)"
1641 % info.version
1642 )
1643 if winsysroot and host.os != "WINNT":
1644 overlay = os.path.join(winsysroot, "overlay.yaml")
1645 if os.path.exists(overlay):
1646 overlay_flags = ["-Xclang", "-ivfsoverlay", "-Xclang", overlay]
1647 if info.version >= "16.0" or (
1648 # clang-cl 15 normally doesn't support the root-relative
1649 # overlay we use, but the bootstrapped clang-cl 15 is patched
1650 # to support it, so check we're using a patched version.
1651 info.version >= "15.0"
1652 and try_preprocess(
1653 configure_cache,
1654 [compiler] + flags + overlay_flags,
1655 language,
1656 "",
1657 onerror=lambda: False,
1658 wrapper=wrapper,
1659 )
1660 ):
1661 flags.extend(overlay_flags)
1662
1663 if (info.type, host_or_target.abi) in (
1664 ("clang", "msvc"),
1665 ("clang-cl", "mingw"),
1666 ):
1667 raise FatalCheckError("Unknown compiler or compiler not supported.")
1668
1669 # If you want to bump the version check here ensure the version
1670 # is known for Xcode in get_compiler_info.
1671 if info.type == "clang" and info.version < "8.0":
1672 raise FatalCheckError(
1673 "Only clang/llvm 8.0 or newer is supported (found version %s)."
1674 % info.version
1675 )
1676
1677 if host_or_target.kernel == "WASI":
1678 if info.type != "clang":
1679 raise FatalCheckError(
1680 "Only clang is supported for %s" % host_or_target.alias
1681 )
1682 if info.version < "8.0":
1683 raise FatalCheckError(
1684 "Only clang/llvm 8.0 or newer is supported for %s (found version %s)."
1685 % (host_or_target.alias, info.version)
1686 )
1687
1688 if host_or_target.os == "Android":
1689 # Need at least clang 13 for compiler-rt/libunwind being the default.
1690 if info.type == "clang" and info.version < "13.0":
1691 raise FatalCheckError(
1692 "Only clang/llvm 13.0 or newer is supported for %s (found version %s)."
1693 % (host_or_target.alias, info.version)
1694 )
1695
1696 if host_or_target.os == "WINNT" and info.type == "gcc":
1697 raise FatalCheckError(
1698 "Firefox cannot be built with mingw-gcc and requires a mingw-clang toolchain to work."
1699 )
1700
1701 if info.flags:
1702 raise FatalCheckError("Unknown compiler or compiler not supported.")
1703
1704 return namespace(
1705 wrapper=wrapper,
1706 compiler=compiler,
1707 flags=flags,
1708 type=info.type,
1709 version=info.version,
1710 language=language,
1711 )
1712
1713 @depends(valid_compiler)
1714 @checking("%s version" % what)
1715 def compiler_version(compiler):
1716 return compiler.version
1717
1718 if language == "C++":
1719
1720 @depends(valid_compiler, c_compiler)
1721 def valid_compiler(compiler, c_compiler):
1722 if compiler.type != c_compiler.type:
1723 die(
1724 "The %s C compiler is %s, while the %s C++ compiler is "
1725 "%s. Need to use the same compiler suite.",
1726 host_or_target_str,
1727 c_compiler.type,
1728 host_or_target_str,
1729 compiler.type,
1730 )
1731
1732 if compiler.version != c_compiler.version:
1733 die(
1734 "The %s C compiler is version %s, while the %s C++ "
1735 "compiler is version %s. Need to use the same compiler "
1736 "version.",
1737 host_or_target_str,
1738 c_compiler.version,
1739 host_or_target_str,
1740 compiler.version,
1741 )
1742 return compiler
1743
1744 # This excludes WASM_CC from the list.
1745 if var in ("CC", "CXX", "HOST_CC", "HOST_CXX"):
1746 # FIXME: we should return a plain list here.
1747 @depends_if(valid_compiler)
1748 @imports(_from="mozbuild.shellutil", _import="quote")
1749 def value(x):
1750 return quote(*x.wrapper, x.compiler, *x.flags)
1751
1752 set_config(var, value)
1753
1754 # Set CC_TYPE/CC_VERSION/HOST_CC_TYPE/HOST_CC_VERSION to allow
1755 # old-configure to do some of its still existing checks.
1756 if language == "C":
1757 set_config("%s_TYPE" % var, valid_compiler.type)
1758 set_config(
1759 "%s_VERSION" % var, depends(valid_compiler.version)(lambda v: str(v))
1760 )
1761
1762 valid_compiler = compiler_class(valid_compiler, host_or_target)
1763
1764 def compiler_error():
1765 raise FatalCheckError(
1766 "Failed compiling a simple %s source with %s" % (language, what)
1767 )
1768
1769 valid_compiler.try_compile(check_msg="%s works" % what, onerror=compiler_error)
1770
1771 set_config("%s_BASE_FLAGS" % var, valid_compiler.flags)
1772
1773 # Set CPP/CXXCPP for both the build system and old-configure. We don't
1774 # need to check this works for preprocessing, because we already relied
1775 # on $CC -E/$CXX -E doing preprocessing work to validate the compiler
1776 # in the first place.
1777 if host_or_target is target:
1778 pp_var = {
1779 "C": "CPP",
1780 "C++": "CXXCPP",
1781 }[language]
1782
1783 preprocessor = depends_if(valid_compiler)(
1784 lambda x: list(x.wrapper) + [x.compiler, "-E"] + list(x.flags)
1785 )
1786
1787 set_config(pp_var, preprocessor)
1788
1789 if language == "C":
1790 linker_var = {
1791 target: "LD",
1792 host: "HOST_LD",
1793 }.get(host_or_target)
1794
1795 if linker_var:
1796
1797 @deprecated_option(env=linker_var, nargs=1)
1798 def linker(value):
1799 if value:
1800 return value[0]
1801
1802 @depends(linker)
1803 def unused_linker(linker):
1804 if linker:
1805 log.warning(
1806 "The value of %s is not used by this build system." % linker_var
1807 )
1808
1809 return valid_compiler
1810
1811
1812 c_compiler = compiler("C", target)
1813 cxx_compiler = compiler("C++", target, c_compiler=c_compiler)
1814 host_c_compiler = compiler("C", host, other_compiler=c_compiler)
1815 host_cxx_compiler = compiler(
1816 "C++",
1817 host,
1818 c_compiler=host_c_compiler,
1819 other_compiler=cxx_compiler,
1820 other_c_compiler=c_compiler,
1821 )
1822
1823
1824 @template
1825 def windows_abi(host_or_target, c_compiler):
1826 @depends(host_or_target)
1827 def windows_abi(host_or_target):
1828 if host_or_target.os == "WINNT":
1829 return host_or_target.abi
1830
1831 @depends(host_or_target, windows_abi)
1832 def need_windows_abi_from_compiler(host_or_target, windows_abi):
1833 return host_or_target.os == "WINNT" and windows_abi is None
1834
1835 @depends(host_or_target, c_compiler, when=need_windows_abi_from_compiler)
1836 def windows_abi_from_compiler(host_or_target, c_compiler):
1837 if host_or_target.os == "WINNT":
1838 if c_compiler.type == "clang-cl":
1839 return "msvc"
1840 return "mingw"
1841
1842 return windows_abi | windows_abi_from_compiler
1843
1844
1845 target_windows_abi = windows_abi(target, c_compiler)
1846 host_windows_abi = windows_abi(host, host_c_compiler)
1847
1848
1849 # Generic compiler-based conditions.
1850 building_with_gcc = depends(c_compiler)(lambda info: info.type == "gcc")
1851 building_with_gnu_compatible_cc = depends(c_compiler)(
1852 lambda info: info.type != "clang-cl"
1853 )
1854
1855
1856 @depends(cxx_compiler, ccache_prefix)
1857 @imports("os")
1858 def cxx_is_icecream(info, ccache_prefix):
1859 if (
1860 os.path.islink(info.compiler)
1861 and os.path.basename(os.readlink(info.compiler)) == "icecc"
1862 ):
1863 return True
1864 if ccache_prefix and os.path.basename(ccache_prefix) == "icecc":
1865 return True
1866
1867
1868 set_config("CXX_IS_ICECREAM", cxx_is_icecream)
1869
1870
1871 # Libstdc++ compatibility hacks
1872 # ==============================================================
1873 #
1874 @depends(target, host)
1875 def target_or_host_is_linux(target, host):
1876 return any(t.os == "GNU" and t.kernel == "Linux" for t in (target, host))
1877
1878
1879 option(
1880 "--enable-stdcxx-compat",
1881 env="MOZ_STDCXX_COMPAT",
1882 help="Enable compatibility with older libstdc++",
1883 when=target_or_host_is_linux,
1884 )
1885
1886
1887 @depends("--enable-stdcxx-compat", when=target_or_host_is_linux)
1888 def stdcxx_compat(value):
1889 if value:
1890 return True
1891
1892
1893 set_config("MOZ_STDCXX_COMPAT", True, when=stdcxx_compat)
1894
1895
1896 # Linker detection
1897 # ==============================================================
1898 # The policy is as follows:
1899 # For Windows:
1900 # - the linker is picked via the LINKER environment variable per windows.configure,
1901 # but ought to be lld-link in any case.
1902 # For macOS:
1903 # - the linker is lld if the clang used is >= 15 (per LLVM version, not Xcode version).
1904 # - the linker is also lld on local developer builds if the clang used is >= 13 (per LLVM
1905 # version, not Xcode version)
1906 # - otherwise the linker is ld64, either from XCode on macOS, or from cctools-ports when
1907 # cross-compiling.
1908 # For other OSes:
1909 # - on local developer builds: lld if present and the compiler is clang. Otherwise gold
1910 # is used if present otherwise, whatever the compiler uses by default.
1911 # - on release/official builds: whatever the compiler uses by default, except when the
1912 # compiler is clang, in which case lld is preferred when it's new enough.
1913 @template
1914 def is_not_winnt_or_sunos(host_or_target):
1915 @depends(host_or_target)
1916 def is_not_winnt_or_sunos(host_or_target):
1917 if host_or_target.kernel not in ("WINNT", "SunOS"):
1918 return True
1919
1920 return is_not_winnt_or_sunos
1921
1922
1923 is_linker_option_enabled = is_not_winnt_or_sunos(target)
1924
1925
1926 @deprecated_option("--enable-gold", env="MOZ_FORCE_GOLD", when=is_linker_option_enabled)
1927 def enable_gold(value):
1928 if value:
1929 die("--enable-gold is deprecated, use --enable-linker=gold instead")
1930 else:
1931 die("--disable-gold is deprecated, use --enable-linker=something_else instead")
1932
1933
1934 option(
1935 "--enable-linker",
1936 nargs=1,
1937 help="Select the linker {bfd, gold, ld64, lld, lld-*, mold}",
1938 when=is_linker_option_enabled,
1939 )
1940
1941
1942 # No-op to enable depending on --enable-linker from default_elfhack in
1943 # toolkit/moz.configure.
1944 @depends("--enable-linker", when=is_linker_option_enabled)
1945 def enable_linker(linker):
1946 return linker
1947
1948
1949 @template
1950 def select_linker_tmpl(host_or_target):
1951 if host_or_target is target:
1952 deps = depends(
1953 "--enable-linker",
1954 c_compiler,
1955 developer_options,
1956 extra_toolchain_flags,
1957 target,
1958 stdcxx_compat,
1959 when=is_linker_option_enabled,
1960 )
1961 host_or_target_str = "target"
1962 else:
1963 deps = depends(
1964 dependable(None),
1965 host_c_compiler,
1966 developer_options,
1967 dependable(None),
1968 host,
1969 stdcxx_compat,
1970 when=is_not_winnt_or_sunos(host_or_target),
1971 )
1972 host_or_target_str = "host"
1973
1974 @deps
1975 @checking(f"for {host_or_target_str} linker", lambda x: x.KIND)
1976 @imports("os")
1977 @imports("shutil")
1978 def select_linker(
1979 linker, c_compiler, developer_options, toolchain_flags, target, stdcxx_compat
1980 ):
1981 if linker:
1982 linker = linker[0]
1983 else:
1984 linker = None
1985
1986 def is_valid_linker(linker):
1987 if target.kernel == "Darwin":
1988 valid_linkers = ("ld64", "lld")
1989 else:
1990 valid_linkers = ("bfd", "gold", "lld", "mold")
1991 if linker in valid_linkers:
1992 return True
1993 if "lld" in valid_linkers and linker.startswith("lld-"):
1994 return True
1995 return False
1996
1997 if linker and not is_valid_linker(linker):
1998 # Check that we are trying to use a supported linker
1999 die("Unsupported linker " + linker)
2000
2001 # Check the kind of linker
2002 version_check = ["-Wl,--version"]
2003 cmd_base = c_compiler.wrapper + [c_compiler.compiler] + c_compiler.flags
2004
2005 def try_linker(linker):
2006 # Generate the compiler flag
2007 if linker == "ld64":
2008 linker_flag = ["-fuse-ld=ld"]
2009 elif linker:
2010 linker_flag = ["-fuse-ld=" + linker]
2011 else:
2012 linker_flag = []
2013 cmd = cmd_base + linker_flag + version_check
2014 if toolchain_flags:
2015 cmd += toolchain_flags
2016
2017 # ld64 doesn't have anything to print out a version. It does print out
2018 # "ld64: For information on command line options please use 'man ld'."
2019 # but that would require doing two attempts, one with --version, that
2020 # would fail, and another with --help.
2021 # Instead, abuse its LD_PRINT_OPTIONS feature to detect a message
2022 # specific to it on stderr when it fails to process --version.
2023 env = dict(os.environ)
2024 env["LD_PRINT_OPTIONS"] = "1"
2025 # Some locales might not print out the strings we are looking for, so
2026 # ensure consistent output.
2027 env["LC_ALL"] = "C"
2028 retcode, stdout, stderr = get_cmd_output(*cmd, env=env)
2029 if retcode == 1 and "Logging ld64 options" in stderr:
2030 kind = "ld64"
2031
2032 elif retcode != 0:
2033 return None
2034
2035 elif "mold" in stdout:
2036 kind = "mold"
2037
2038 elif "GNU ld" in stdout:
2039 # We are using the normal linker
2040 kind = "bfd"
2041
2042 elif "GNU gold" in stdout:
2043 kind = "gold"
2044
2045 elif "LLD" in stdout:
2046 kind = "lld"
2047
2048 else:
2049 kind = "unknown"
2050
2051 if kind == "unknown" or is_valid_linker(kind):
2052 return namespace(
2053 KIND=kind,
2054 LINKER_FLAG=linker_flag,
2055 )
2056
2057 result = None
2058 if linker:
2059 result = try_linker(linker)
2060 if result is None:
2061 die("Could not use {} as linker".format(linker))
2062
2063 if (
2064 result is None
2065 and c_compiler.type == "clang"
2066 and (
2067 (
2068 target.kernel != "Darwin"
2069 and (developer_options or c_compiler.version >= "15.0")
2070 )
2071 or (
2072 target.kernel == "Darwin"
2073 and (
2074 (developer_options and c_compiler.version >= "13.0")
2075 or c_compiler.version >= "15.0"
2076 )
2077 )
2078 )
2079 ):
2080 result = try_linker("lld")
2081
2082 if result is None and developer_options and not stdcxx_compat:
2083 result = try_linker("gold")
2084
2085 if result is None:
2086 result = try_linker(None)
2087
2088 if result is None:
2089 die("Failed to find an adequate linker")
2090
2091 if stdcxx_compat and result.KIND == "gold":
2092 die("--enable-stdcxx-compat is not compatible with the gold linker")
2093
2094 # If an explicit linker was given, error out if what we found is different.
2095 if linker and not linker.startswith(result.KIND):
2096 die("Could not use {} as linker".format(linker))
2097
2098 return result
2099
2100 return select_linker
2101
2102
2103 select_linker = select_linker_tmpl(target)
2104
2105
2106 @template
2107 def linker_ldflags_tmpl(host_or_target):
2108 if host_or_target is target:
2109 deps = depends_if(
2110 select_linker,
2111 target,
2112 target_sysroot,
2113 target_multiarch_dir,
2114 android_sysroot,
2115 android_version,
2116 c_compiler,
2117 developer_options,
2118 )
2119 else:
2120 deps = depends_if(
2121 select_linker_tmpl(host),
2122 host,
2123 host_sysroot,
2124 host_multiarch_dir,
2125 dependable(None),
2126 dependable(None),
2127 host_c_compiler,
2128 developer_options,
2129 )
2130
2131 @deps
2132 @imports("os")
2133 def linker_ldflags(
2134 linker,
2135 target,
2136 sysroot,
2137 multiarch_dir,
2138 android_sysroot,
2139 android_version,
2140 c_compiler,
2141 developer_options,
2142 ):
2143 flags = list((linker and linker.LINKER_FLAG) or [])
2144 # rpath-link is irrelevant to wasm, see for more info https://github.com/emscripten-core/emscripten/issues/11076.
2145 if sysroot.path and multiarch_dir and target.os != "WASI":
2146 for d in ("lib", "usr/lib"):
2147 multiarch_lib_dir = os.path.join(sysroot.path, d, multiarch_dir)
2148 if os.path.exists(multiarch_lib_dir):
2149 # Non-Debian-patched binutils linkers (both BFD and gold) don't lookup
2150 # in multi-arch directories.
2151 flags.append("-Wl,-rpath-link,%s" % multiarch_lib_dir)
2152 # GCC also needs -L.
2153 if c_compiler.type == "gcc":
2154 flags.append("-L%s" % multiarch_lib_dir)
2155 if (
2156 c_compiler.type == "gcc"
2157 and sysroot.bootstrapped
2158 and sysroot.stdcxx_version
2159 ):
2160 flags.append(
2161 "-L{}/usr/lib/gcc/{}/{}".format(
2162 sysroot.path, multiarch_dir, sysroot.stdcxx_version
2163 )
2164 )
2165 if android_sysroot:
2166 # BFD/gold linkers need a manual --rpath-link for indirect
2167 # dependencies.
2168 flags += [
2169 "-Wl,--rpath-link={}/usr/lib/{}".format(
2170 android_sysroot, target.toolchain
2171 ),
2172 "-Wl,--rpath-link={}/usr/lib/{}/{}".format(
2173 android_sysroot, target.toolchain, android_version
2174 ),
2175 ]
2176 if (
2177 developer_options
2178 and linker
2179 and linker.KIND == "lld"
2180 and target.kernel != "WINNT"
2181 ):
2182 flags.append("-Wl,-O0")
2183 return flags
2184
2185 return linker_ldflags
2186
2187
2188 linker_ldflags = linker_ldflags_tmpl(target)
2189 host_linker_ldflags = linker_ldflags_tmpl(host)
2190
2191
2192 # There's a wrinkle with MinGW: linker configuration is not enabled, so
2193 # `select_linker` is never invoked. Hard-code around it.
2194 @depends(select_linker, target, c_compiler)
2195 def gcc_use_gnu_ld(select_linker, target, c_compiler):
2196 if select_linker is not None and target.kernel != "Darwin":
2197 return select_linker.KIND in ("bfd", "gold", "lld", "mold")
2198 if target.kernel == "WINNT" and c_compiler.type == "clang":
2199 return True
2200 return None
2201
2202
2203 # GCC_USE_GNU_LD=1 means the linker is command line compatible with GNU ld.
2204 set_config("GCC_USE_GNU_LD", gcc_use_gnu_ld)
2205
2206
2207 include("compile-checks.configure")
2208 include("arm.configure", when=depends(target.cpu)(lambda cpu: cpu == "arm"))
2209
2210 # Libstdc++ feature detection
2211 # ==============================================================
2212
2213 with only_when("--enable-debug"):
2214 using_libstdcxx = try_compile(
2215 language="C++",
2216 includes=["new"],
2217 body="#ifndef __GLIBCXX__\n#error 1\n#endif",
2218 when=depends(c_compiler)(lambda c: c.type != "clang-cl"),
2219 )
2220
2221 libstdcxx_assertions = depends(when=using_libstdcxx)("_GLIBCXX_ASSERTIONS")
2222
2223 using_libcxx = try_compile(
2224 language="C++",
2225 includes=["new"],
2226 body="#ifndef _LIBCPP_VERSION\n#error 1\n#endif",
2227 when=~using_libstdcxx,
2228 )
2229
2230 @depends(
2231 try_compile(language="C++", body="#if _LIBCPP_STD_VER >= 18\n#error 1\n#endif"),
2232 when=using_libcxx,
2233 )
2234 def libcxx_assertions(modern_libcxx):
2235 if modern_libcxx:
2236 return "_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_DEBUG"
2237 else:
2238 return "_LIBCPP_HARDENING_MODE_DEBUG"
2239
2240 @depends(
2241 libstdcxx_assertions,
2242 libcxx_assertions,
2243 when=libstdcxx_assertions | libcxx_assertions,
2244 )
2245 @checking("which standard c++ library assertions to use")
2246 def stdlibcxx_assertions(libstdcxx, libcxx):
2247 return libstdcxx or libcxx
2248
2249
2250 @depends(
2251 have_64_bit,
2252 try_compile(
2253 body='static_assert(sizeof(void *) == 8, "")', check_msg="for 64-bit OS"
2254 ),
2255 )
2256 def check_have_64_bit(have_64_bit, compiler_have_64_bit):
2257 if have_64_bit != compiler_have_64_bit:
2258 configure_error(
2259 "The target compiler does not agree with configure "
2260 "about the target bitness."
2261 )
2262
2263
2264 @depends(cxx_compiler, target)
2265 def needs_libstdcxx_newness_check(cxx_compiler, target):
2266 # We only have to care about this on Linux and MinGW.
2267 if cxx_compiler.type == "clang-cl":
2268 return
2269
2270 if target.kernel not in ("Linux", "WINNT"):
2271 return
2272
2273 if target.os == "Android":
2274 return
2275
2276 return True
2277
2278
2279 def die_on_old_libstdcxx():
2280 die(
2281 "The libstdc++ in use is not new enough. Please run "
2282 "./mach bootstrap to update your compiler, or update your system "
2283 "libstdc++ installation."
2284 )
2285
2286
2287 try_compile(
2288 includes=["cstddef"],
2289 body="\n".join(
2290 [
2291 # _GLIBCXX_RELEASE showed up in libstdc++ 7.
2292 "#if defined(__GLIBCXX__) && !defined(_GLIBCXX_RELEASE)",
2293 "# error libstdc++ not new enough",
2294 "#endif",
2295 "#if defined(_GLIBCXX_RELEASE)",
2296 "# if _GLIBCXX_RELEASE < %d" % minimum_gcc_version().major,
2297 "# error libstdc++ not new enough",
2298 "# else",
2299 " (void) 0",
2300 "# endif",
2301 "#endif",
2302 ]
2303 ),
2304 check_msg="for new enough STL headers from libstdc++",
2305 when=needs_libstdcxx_newness_check,
2306 onerror=die_on_old_libstdcxx,
2307 )
2308
2309
2310 @depends(c_compiler, target)
2311 def default_debug_flags(compiler_info, target):
2312 # Debug info is ON by default.
2313 if compiler_info.type == "clang-cl":
2314 return ("-Z7",)
2315 elif target.kernel == "WINNT" and compiler_info.type == "clang":
2316 return ("-g", "-gcodeview")
2317 # The oldest versions of supported compilers default to DWARF-4, but
2318 # newer versions may default to DWARF-5 or newer (e.g. clang 14), which
2319 # Valgrind doesn't support. Force-use DWARF-4.
2320 return ("-gdwarf-4",)
2321
2322
2323 option(env="MOZ_DEBUG_FLAGS", nargs=1, help="Debug compiler flags")
2324
2325 imply_option("--enable-debug-symbols", depends_if("--enable-debug")(lambda v: v))
2326
2327 option(
2328 "--disable-debug-symbols",
2329 nargs="?",
2330 help="Disable debug symbols using the given compiler flags",
2331 )
2332
2333 set_config("MOZ_DEBUG_SYMBOLS", depends_if("--enable-debug-symbols")(lambda _: True))
2334
2335
2336 @depends("MOZ_DEBUG_FLAGS", "--enable-debug-symbols", default_debug_flags)
2337 @imports(_from="mozbuild.shellutil", _import="split")
2338 def debug_flags(env_debug_flags, enable_debug_flags, default_debug_flags):
2339 # If MOZ_DEBUG_FLAGS is set, and --enable-debug-symbols is set to a value,
2340 # --enable-debug-symbols takes precedence. Note, the value of
2341 # --enable-debug-symbols may be implied by --enable-debug.
2342 if len(enable_debug_flags):
2343 return split(enable_debug_flags[0])
2344 if env_debug_flags:
2345 return split(env_debug_flags[0])
2346 return default_debug_flags
2347
2348
2349 set_config("MOZ_DEBUG_FLAGS", debug_flags)
2350
2351
2352 @depends(c_compiler, host)
2353 @imports(
2354 _from="mach.logging", _import="enable_blessed", _as="_enable_ansi_escape_codes"
2355 )
2356 def color_cflags(info, host):
2357 # We could test compiling with flags. By why incur the overhead when
2358 # color support should always be present in a specific toolchain
2359 # version?
2360
2361 # Code for auto-adding this flag to compiler invocations needs to
2362 # determine if an existing flag isn't already present. That is likely
2363 # using exact string matching on the returned value. So if the return
2364 # value changes to e.g. "<x>=always", exact string match may fail and
2365 # multiple color flags could be added. So examine downstream consumers
2366 # before adding flags to return values.
2367 if info.type == "gcc":
2368 return "-fdiagnostics-color"
2369 elif info.type in ["clang", "clang-cl"]:
2370 if host.os == "WINNT" and _enable_ansi_escape_codes():
2371 return "-fcolor-diagnostics -fansi-escape-codes"
2372 else:
2373 return "-fcolor-diagnostics"
2374 else:
2375 return ""
2376
2377
2378 set_config("COLOR_CFLAGS", color_cflags)
2379
2380 # Some standard library headers (notably bionic on Android) declare standard
2381 # functions (e.g. getchar()) and also #define macros for those standard
2382 # functions. libc++ deals with this by doing something like the following
2383 # (explanatory comments added):
2384 #
2385 # #ifdef FUNC
2386 # // Capture the definition of FUNC.
2387 # inline _LIBCPP_INLINE_VISIBILITY int __libcpp_FUNC(...) { return FUNC(...); }
2388 # #undef FUNC
2389 # // Use a real inline definition.
2390 # inline _LIBCPP_INLINE_VISIBILITY int FUNC(...) { return _libcpp_FUNC(...); }
2391 # #endif
2392 #
2393 # _LIBCPP_INLINE_VISIBILITY is typically defined as:
2394 #
2395 # __attribute__((__visibility__("hidden"), __always_inline__))
2396 #
2397 # Unfortunately, this interacts badly with our system header wrappers, as the:
2398 #
2399 # #pragma GCC visibility push(default)
2400 #
2401 # that they do prior to including the actual system header is treated by the
2402 # compiler as an explicit declaration of visibility on every function declared
2403 # in the header. Therefore, when the libc++ code above is encountered, it is
2404 # as though the compiler has effectively seen:
2405 #
2406 # int FUNC(...) __attribute__((__visibility__("default")));
2407 # int FUNC(...) __attribute__((__visibility__("hidden")));
2408 #
2409 # and the compiler complains about the mismatched visibility declarations.
2410 #
2411 # However, libc++ will only define _LIBCPP_INLINE_VISIBILITY if there is no
2412 # existing definition. We can therefore define it to the empty string (since
2413 # we are properly managing visibility ourselves) and avoid this whole mess.
2414 # Note that we don't need to do this with gcc, as libc++ detects gcc and
2415 # effectively does the same thing we are doing here.
2416 #
2417 # _LIBCPP_ALWAYS_INLINE needs a similar workarounds, since it too declares
2418 # hidden visibility.
2419 #
2420 # _LIBCPP_HIDE_FROM_ABI is a macro in libc++ versions in NDKs >=r19. It too
2421 # declares hidden visibility, but it also declares functions as excluded from
2422 # explicit instantiation (roughly: the function can be unused in the current
2423 # compilation, but does not then trigger an actual definition of the function;
2424 # it is assumed the real definition comes from elsewhere). We need to replicate
2425 # this setup.
2426
2427
2428 @depends(c_compiler, target)
2429 def libcxx_override_visibility(c_compiler, target):
2430 if c_compiler.type == "clang" and target.os == "Android":
2431 return namespace(
2432 empty="",
2433 hide_from_abi="__attribute__((__exclude_from_explicit_instantiation__))",
2434 )
2435
2436
2437 set_define("_LIBCPP_INLINE_VISIBILITY", libcxx_override_visibility.empty)
2438 set_define("_LIBCPP_ALWAYS_INLINE", libcxx_override_visibility.empty)
2439
2440 set_define("_LIBCPP_HIDE_FROM_ABI", libcxx_override_visibility.hide_from_abi)
2441
2442
2443 @depends(target, build_environment)
2444 def visibility_flags(target, env):
2445 if target.os != "WINNT":
2446 if target.kernel in ("Darwin", "FreeBSD", "OpenBSD"):
2447 return ("-fvisibility=hidden", "-fvisibility-inlines-hidden")
2448 return (
2449 "-I%s/system_wrappers" % os.path.join(env.dist),
2450 "-include",
2451 "%s/config/gcc_hidden.h" % env.topsrcdir,
2452 )
2453
2454
2455 @depends(target, visibility_flags)
2456 def wrap_system_includes(target, visibility_flags):
2457 if visibility_flags and target.kernel != "Darwin":
2458 return True
2459
2460
2461 set_define(
2462 "HAVE_VISIBILITY_HIDDEN_ATTRIBUTE",
2463 depends(visibility_flags)(lambda v: bool(v) or None),
2464 )
2465 set_define(
2466 "HAVE_VISIBILITY_ATTRIBUTE", depends(visibility_flags)(lambda v: bool(v) or None)
2467 )
2468 set_config("WRAP_SYSTEM_INCLUDES", wrap_system_includes)
2469 set_config("VISIBILITY_FLAGS", visibility_flags)
2470
2471
2472 # try harder, when checking for __thread support, see bug 521750 comment #33 and below
2473 # We pass linker_optimize_flags to the linker because if dead_strip is
2474 # enabled, the linker in xcode 4.1 will crash. Without this it would crash when
2475 # linking XUL.
2476
2477
2478 @depends(target, c_compiler)
2479 def check_thread(target, c_compiler):
2480 if target.cpu in ("mips32", "mips64"):
2481 # mips builds fail with TLS variables because of a binutils bug.
2482 # See bug 528687
2483 return False
2484 if target.os == "Android":
2485 # The custom dynamic linker doesn't support TLS variables
2486 return False
2487 if target.kernel == "OpenBSD":
2488 # OpenBSD doesn't have TLS support, and the test succeeds with clang++
2489 return False
2490 return c_compiler.type != "clang-cl"
2491
2492
2493 set_define(
2494 "HAVE_THREAD_TLS_KEYWORD",
2495 try_link(
2496 body="static __thread bool tlsIsMainThread = false; return tlsIsMainThread;",
2497 flags=linker_optimize_flags.ldflags,
2498 check_msg="for __thread keyword for TLS variables",
2499 when=check_thread,
2500 ),
2501 )
2502
2503
2504 @template
2505 def depend_cflags(host_or_target_c_compiler):
2506 @depends(host_or_target_c_compiler)
2507 def depend_cflags(host_or_target_c_compiler):
2508 if host_or_target_c_compiler.type != "clang-cl":
2509 return ["-MD", "-MP", "-MF $(MDDEPDIR)/$(@F).pp"]
2510 else:
2511 # clang-cl doesn't accept the normal -MD -MP -MF options that clang
2512 # does, but the underlying cc1 binary understands how to generate
2513 # dependency files. These options are based on analyzing what the
2514 # normal clang driver sends to cc1 when given the "correct"
2515 # dependency options.
2516 return [
2517 "-Xclang",
2518 "-MP",
2519 "-Xclang",
2520 "-dependency-file",
2521 "-Xclang",
2522 "$(MDDEPDIR)/$(@F).pp",
2523 "-Xclang",
2524 "-MT",
2525 "-Xclang",
2526 "$@",
2527 ]
2528
2529 return depend_cflags
2530
2531
2532 set_config("_DEPEND_CFLAGS", depend_cflags(c_compiler))
2533 set_config("_HOST_DEPEND_CFLAGS", depend_cflags(host_c_compiler))
2534
2535
2536 @depends(c_compiler)
2537 def preprocess_option(compiler):
2538 # The uses of PREPROCESS_OPTION depend on the spacing for -o/-Fi.
2539 if compiler.type in ("gcc", "clang"):
2540 return "-E -o "
2541 else:
2542 return "-P -Fi"
2543
2544
2545 set_config("PREPROCESS_OPTION", preprocess_option)
2546
2547
2548 # On Power ISA, determine compiler flags for VMX, VSX and VSX-3.
2549
2550 set_config(
2551 "PPC_VMX_FLAGS",
2552 ["-maltivec"],
2553 when=depends(target.cpu)(lambda cpu: cpu.startswith("ppc")),
2554 )
2555
2556 set_config(
2557 "PPC_VSX_FLAGS",
2558 ["-mvsx"],
2559 when=depends(target.cpu)(lambda cpu: cpu.startswith("ppc")),
2560 )
2561
2562 set_config(
2563 "PPC_VSX3_FLAGS",
2564 ["-mvsx", "-mcpu=power9"],
2565 when=depends(target.cpu)(lambda cpu: cpu.startswith("ppc")),
2566 )
2567
2568 # TARGET_XPCOM_ABI
2569 # ==============================================================
2570
2571 is_arm_eabi = c_compiler.try_compile(
2572 body="""
2573 #if defined(__ARM_EABI__)
2574 return 0;
2575 #else
2576 #error Not ARM EABI.
2577 #endif""",
2578 check_msg="for ARM EABI",
2579 when=building_with_gnu_compatible_cc
2580 & depends(target.cpu)(lambda cpu: cpu == "arm"),
2581 )
2582
2583
2584 @depends(target, is_arm_eabi, c_compiler)
2585 def target_xpcom_abi(target, is_arm_eabi, compiler):
2586 if compiler.type == "clang-cl":
2587 return f"{target.cpu}-msvc"
2588 elif target.cpu == "arm":
2589 target_compiler_abi = "eabi" if is_arm_eabi else "oabi"
2590 return f"{target.cpu}-{target_compiler_abi}-gcc3"
2591 else:
2592 return f"{target.cpu}-gcc3"
2593
2594
2595 set_config("TARGET_XPCOM_ABI", target_xpcom_abi)
2596 set_define("TARGET_XPCOM_ABI", depends(target_xpcom_abi)(lambda v: f'"{v}"'))
2597
2598 # ASAN
2599 # ==============================================================
2600
2601 option("--enable-address-sanitizer", help="Enable Address Sanitizer")
2602
2603
2604 @depends(when="--enable-address-sanitizer")
2605 def asan():
2606 return True
2607
2608
2609 with only_when(asan):
2610 option(
2611 env="MOZ_CLANG_RT_ASAN_LIB_PATH",
2612 nargs=1,
2613 help="Path to clang runtime asan library",
2614 )
2615
2616 @depends(
2617 c_compiler,
2618 target,
2619 "MOZ_CLANG_RT_ASAN_LIB_PATH",
2620 )
2621 @imports("os")
2622 @imports("glob")
2623 def clang_rt_asan_lib_path(c_compiler, target, clang_rt_asan_lib):
2624 if clang_rt_asan_lib:
2625 if os.path.exists(clang_rt_asan_lib[0]):
2626 return clang_rt_asan_lib[0]
2627 else:
2628 die(
2629 f"Specified MOZ_CLANG_RT_ASAN_LIB_PATH value '{clang_rt_asan_lib}' doesn't exist. "
2630 )
2631
2632 # Look for the ASan runtime binary
2633 if c_compiler.type == "clang-cl":
2634 cpu = {"x86": "i386"}.get(target.cpu, target.cpu)
2635 clang_rt_asan_lib = f"clang_rt.asan_dynamic-{cpu}.dll"
2636 subdir = "windows"
2637 elif target.os == "Android":
2638 cpu = {"x86": "i686"}.get(target.cpu, target.cpu)
2639 clang_rt_asan_lib = f"libclang_rt.asan-{cpu}-android.so"
2640 subdir = "linux"
2641 else:
2642 return
2643
2644 search_path = os.path.join(
2645 os.path.dirname(c_compiler.compiler),
2646 "..",
2647 "lib",
2648 "clang",
2649 "*",
2650 "lib",
2651 subdir,
2652 clang_rt_asan_lib,
2653 )
2654 if candidates := glob.glob(search_path):
2655 return candidates[0]
2656
2657 die(
2658 f"Couldn't find {clang_rt_asan_lib}. "
2659 f"It should be available in the same location as {c_compiler.type}."
2660 )
2661
2662 set_config("MOZ_CLANG_RT_ASAN_LIB_PATH", clang_rt_asan_lib_path)
2663
2664
2665 @depends(
2666 c_compiler,
2667 target,
2668 compilation_flags,
2669 linker_flags,
2670 build_environment,
2671 when=asan,
2672 )
2673 def asan_flags(c_compiler, target, compilation_flags, linker_flags, build_env):
2674 if c_compiler.type == "clang-cl":
2675 # Suppressing errors in recompiled code.
2676 if target.os == "WINNT":
2677 flag = f"-fsanitize-blacklist={build_env.topsrcdir}/build/sanitizers/asan_blacklist_win.txt"
2678 compilation_flags.cflags.append(flag)
2679 compilation_flags.cxxflags.append(flag)
2680
2681 asan_flag = "-fsanitize=address"
2682 compilation_flags.cflags.append(asan_flag)
2683 compilation_flags.cxxflags.append(asan_flag)
2684
2685 if c_compiler.type != "clang-cl":
2686 linker_flags.ldflags.extend([asan_flag, "-rdynamic"])
2687
2688
2689 set_define("MOZ_ASAN", True, when=asan)
2690 set_config("MOZ_ASAN", True, when=asan)
2691
2692 # MSAN
2693 # ==============================================================
2694
2695 option("--enable-memory-sanitizer", help="Enable Memory Sanitizer")
2696
2697
2698 @depends(when="--enable-memory-sanitizer")
2699 def msan():
2700 return True
2701
2702
2703 @depends(c_compiler, compilation_flags, linker_flags, when=msan)
2704 def msan_flags(c_compiler, compilation_flags, linker_flags):
2705 flags = ["-fsanitize=memory", "-fsanitize-memory-track-origins"]
2706 compilation_flags.cflags.extend(flags)
2707 compilation_flags.cxxflags.extend(flags)
2708 if c_compiler.type != "clang-cl":
2709 linker_flags.ldflags.extend(flags + ["-rdynamic"])
2710
2711
2712 set_define("MOZ_MSAN", True, when=msan)
2713 set_config("MOZ_MSAN", True, when=msan)
2714
2715 # TSAN
2716 # ==============================================================
2717
2718 option("--enable-thread-sanitizer", help="Enable Thread Sanitizer")
2719
2720
2721 @depends(when="--enable-thread-sanitizer")
2722 def tsan():
2723 return True
2724
2725
2726 @depends(c_compiler, compilation_flags, linker_flags, when=tsan)
2727 def tsan_flags(c_compiler, compilation_flags, linker_flags):
2728 flag = "-fsanitize=thread"
2729 compilation_flags.cflags.append(flag)
2730 compilation_flags.cxxflags.append(flag)
2731 if c_compiler.type != "clang-cl":
2732 linker_flags.ldflags.extend(["-fsanitize=thread", "-rdynamic"])
2733
2734
2735 set_define("MOZ_TSAN", True, when=tsan)
2736 set_config("MOZ_TSAN", True, when=tsan)
2737
2738 # UBSAN
2739 # ==============================================================
2740
2741 option(
2742 "--enable-undefined-sanitizer", nargs="*", help="Enable UndefinedBehavior Sanitizer"
2743 )
2744
2745
2746 @depends("--enable-undefined-sanitizer", moz_optimize)
2747 def ubsan(options, optimize):
2748 if not options:
2749 return
2750
2751 default_checks = [
2752 "bool",
2753 "bounds",
2754 "enum",
2755 "function",
2756 "integer-divide-by-zero",
2757 "pointer-overflow",
2758 "return",
2759 "vla-bound",
2760 ]
2761
2762 # adding object-size generates a warning if -O0 is set
2763 if optimize:
2764 default_checks.append("object-size")
2765
2766 checks = options if len(options) else default_checks
2767
2768 return checks
2769
2770
2771 @depends(
2772 ubsan, c_compiler, compilation_flags, linker_flags, build_environment, when=ubsan
2773 )
2774 @imports(_from="__builtin__", _import="open")
2775 @imports(_from="glob", _import="glob")
2776 @imports("shutil")
2777 def ubsan_flags(ubsan_checks, c_compiler, compilation_flags, linker_flags, build_env):
2778 ubsan_txt = os.path.join(build_env.topobjdir, "ubsan_blacklist.txt")
2779 with open(ubsan_txt, "w") as out_fd:
2780 for blacklist in glob(
2781 os.path.join(
2782 build_env.topsrcdir, "build", "sanitizers", "ubsan_*_blacklist.txt"
2783 )
2784 ):
2785 with open(blacklist) as in_fd:
2786 shutil.copyfileobj(in_fd, out_fd)
2787
2788 joined_ubsan_checks = ",".join(ubsan_checks)
2789
2790 flags = [
2791 f"-fsanitize={joined_ubsan_checks}",
2792 f"-fno-sanitize-recover={joined_ubsan_checks}",
2793 f"-fsanitize-blacklist={ubsan_txt}",
2794 ]
2795 compilation_flags.cflags.extend(flags)
2796 compilation_flags.cxxflags.extend(flags)
2797 if c_compiler.type != "clang-cl":
2798 linker_flags.ldflags.extend(["-fsanitize=undefined", "-rdynamic"])
2799
2800
2801 option(
2802 "--enable-signed-overflow-sanitizer",
2803 help="Enable UndefinedBehavior Sanitizer (Signed Integer Overflow Parts)",
2804 )
2805
2806
2807 @depends(when="--enable-signed-overflow-sanitizer")
2808 def ub_signed_overflow_san():
2809 return True
2810
2811
2812 @depends(
2813 c_compiler,
2814 compilation_flags,
2815 linker_flags,
2816 build_environment,
2817 when=ub_signed_overflow_san,
2818 )
2819 def ub_signed_overflow_san_flags(
2820 c_compiler, compilation_flags, linker_flags, build_env
2821 ):
2822 sanitizer_blacklist = os.path.join(
2823 build_env.topsrcdir,
2824 "build",
2825 "sanitizers",
2826 "ubsan_signed_overflow_blacklist.txt",
2827 )
2828 flags = [
2829 f"-fsanitize=signed-integer-overflow",
2830 f"-fsanitize-blacklist={sanitizer_blacklist}",
2831 ]
2832 compilation_flags.cflags.extend(flags)
2833 compilation_flags.cxxflags.extend(flags)
2834 if c_compiler.type != "clang-cl":
2835 linker_flags.ldflags.extend(["-fsanitize=signed-integer-overflow", "-rdynamic"])
2836
2837
2838 option(
2839 "--enable-unsigned-overflow-sanitizer",
2840 help="Enable UndefinedBehavior Sanitizer (Unsigned Integer Overflow Parts)",
2841 )
2842
2843
2844 @depends(when="--enable-unsigned-overflow-sanitizer")
2845 def ub_unsigned_overflow_san():
2846 return True
2847
2848
2849 @depends(
2850 c_compiler,
2851 compilation_flags,
2852 linker_flags,
2853 build_environment,
2854 when=ub_unsigned_overflow_san,
2855 )
2856 def ub_unsigned_overflow_san_flags(
2857 c_compiler, compilation_flags, linker_flags, build_env
2858 ):
2859 sanitizer_blacklist = os.path.join(
2860 build_env.topsrcdir,
2861 "build",
2862 "sanitizers",
2863 "ubsan_unsigned_overflow_blacklist.txt",
2864 )
2865 flags = [
2866 f"-fsanitize=unsigned-integer-overflow",
2867 f"-fsanitize-blacklist={sanitizer_blacklist}",
2868 ]
2869 compilation_flags.cflags.extend(flags)
2870 compilation_flags.cxxflags.extend(flags)
2871 if c_compiler.type != "clang-cl":
2872 linker_flags.ldflags.extend(
2873 ["-fsanitize=unsigned-integer-overflow", "-rdynamic"]
2874 )
2875
2876
2877 #
2878
2879 any_ubsan = ubsan | ub_signed_overflow_san | ub_unsigned_overflow_san
2880 set_define("MOZ_UBSAN", True, when=any_ubsan)
2881 set_config("MOZ_UBSAN", any_ubsan)
2882
2883
2884 # We only want to include windows.configure when we are compiling on
2885 # Windows, or for Windows.
2886 include("windows.configure", when=is_windows)
2887
2888 # Security Hardening
2889 # ==============================================================
2890
2891 option(
2892 "--enable-hardening",
2893 env="MOZ_SECURITY_HARDENING",
2894 help="Enables security hardening compiler options",
2895 )
2896
2897
2898 # This function is a bit confusing. It adds or removes hardening flags in
2899 # three stuations: if --enable-hardening is passed; if --disable-hardening
2900 # is passed, and if no flag is passed.
2901 #
2902 # At time of this comment writing, all flags are actually added in the
2903 # default no-flag case; making --enable-hardening the same as omitting the
2904 # flag. --disable-hardening will omit the security flags. (However, not all
2905 # possible security flags will be omitted by --disable-hardening, as many are
2906 # compiler-default options we do not explicitly enable.)
2907 @depends(
2908 "--enable-hardening",
2909 "--enable-address-sanitizer",
2910 "--enable-debug",
2911 "--enable-optimize",
2912 c_compiler,
2913 target,
2914 stdlibcxx_assertions,
2915 )
2916 def security_hardening_cflags(
2917 hardening_flag, asan, debug, optimize, c_compiler, target, cxx_assert
2918 ):
2919 compiler_is_gccish = c_compiler.type in ("gcc", "clang")
2920 mingw_clang = c_compiler.type == "clang" and target.os == "WINNT"
2921
2922 flags = []
2923 ldflags = []
2924 trivial_auto_var_init = []
2925
2926 # WASI compiler doesn't support security hardening cflags
2927 if target.os == "WASI":
2928 return
2929
2930 # ----------------------------------------------------------
2931 # If hardening is explicitly enabled, or not explicitly disabled
2932 if hardening_flag.origin == "default" or hardening_flag:
2933 # FORTIFY_SOURCE ------------------------------------
2934 # Require optimization for FORTIFY_SOURCE. See Bug 1417452
2935 # Also, undefine it before defining it just in case a distro adds it, see Bug 1418398
2936 if compiler_is_gccish and optimize and not asan:
2937 flags.append("-U_FORTIFY_SOURCE")
2938 flags.append("-D_FORTIFY_SOURCE=2")
2939
2940 # Lib c++ debug mode
2941 if cxx_assert:
2942 flags.append(f"-D{cxx_assert}")
2943
2944 # fstack-protector ------------------------------------
2945 # Enable only if hardening is not disabled and ASAN is
2946 # not on as ASAN will catch the crashes for us
2947 if compiler_is_gccish and not asan:
2948 flags.append("-fstack-protector-strong")
2949 ldflags.append("-fstack-protector-strong")
2950
2951 if (
2952 c_compiler.type == "clang"
2953 and c_compiler.version >= "11.0.1"
2954 and target.os not in ("WINNT", "OSX", "OpenBSD")
2955 and target.cpu in ("x86", "x86_64", "ppc64", "s390x")
2956 ):
2957 flags.append("-fstack-clash-protection")
2958 ldflags.append("-fstack-clash-protection")
2959
2960 # ftrivial-auto-var-init ------------------------------
2961 # Initialize local variables with a 0xAA pattern in clang builds.
2962 # Linux32 fails some xpcshell tests with -ftrivial-auto-var-init
2963 linux32 = target.kernel == "Linux" and target.cpu == "x86"
2964 if (
2965 (c_compiler.type == "clang" or c_compiler.type == "clang-cl")
2966 and c_compiler.version >= "8"
2967 and not linux32
2968 ):
2969 if c_compiler.type == "clang-cl":
2970 trivial_auto_var_init.append("-Xclang")
2971 trivial_auto_var_init.append("-ftrivial-auto-var-init=pattern")
2972 # Always enable on debug builds.
2973 if debug:
2974 flags.extend(trivial_auto_var_init)
2975
2976 if (c_compiler.type == "clang" and c_compiler.version >= "16") or (
2977 c_compiler.type == "gcc" and c_compiler.version >= "13"
2978 ):
2979 # Cannot use level 3 because we have many uses of the [0] GNU syntax.
2980 # Cannot use level 2 because sqlite3 and icu use the [1] GNU syntax.
2981 flags.append("-fstrict-flex-arrays=1")
2982
2983 # ASLR ------------------------------------------------
2984 # ASLR (dynamicbase) is enabled by default in clang-cl; but the
2985 # mingw-clang build requires it to be explicitly enabled
2986 if mingw_clang:
2987 ldflags.append("-Wl,--dynamicbase")
2988
2989 # Control Flow Guard (CFG) ----------------------------
2990 if (
2991 c_compiler.type == "clang-cl"
2992 and c_compiler.version >= "8"
2993 and (target.cpu != "aarch64" or c_compiler.version >= "8.0.1")
2994 ):
2995 if target.cpu == "aarch64" and c_compiler.version >= "10.0.0":
2996 # The added checks in clang 10 make arm64 builds crash. (Bug 1639318)
2997 flags.append("-guard:cf,nochecks")
2998 else:
2999 flags.append("-guard:cf")
3000 # nolongjmp is needed because clang doesn't emit the CFG tables of
3001 # setjmp return addresses https://bugs.llvm.org/show_bug.cgi?id=40057
3002 ldflags.append("-guard:cf,nolongjmp")
3003
3004 # ----------------------------------------------------------
3005 # If ASAN _is_ on, disable FORTIFY_SOURCE just to be safe
3006 if asan:
3007 flags.append("-D_FORTIFY_SOURCE=0")
3008
3009 # fno-common -----------------------------------------
3010 # Do not merge variables for ASAN; can detect some subtle bugs
3011 if asan:
3012 # clang-cl does not recognize the flag, it must be passed down to clang
3013 if c_compiler.type == "clang-cl":
3014 flags.append("-Xclang")
3015 flags.append("-fno-common")
3016
3017 return namespace(
3018 flags=flags,
3019 ldflags=ldflags,
3020 trivial_auto_var_init=trivial_auto_var_init,
3021 )
3022
3023
3024 set_config("MOZ_HARDENING_CFLAGS", security_hardening_cflags.flags)
3025 set_config("MOZ_HARDENING_LDFLAGS", security_hardening_cflags.ldflags)
3026 set_config(
3027 "MOZ_TRIVIAL_AUTO_VAR_INIT",
3028 security_hardening_cflags.trivial_auto_var_init,
3029 )
3030
3031
3032 # Intel Control-flow Enforcement Technology
3033 # ==============================================================
3034 # We keep this separate from the hardening flags above, because we want to be
3035 # able to easily remove the flags in the build files for certain executables.
3036 @depends(c_compiler, target)
3037 def cet_ldflags(c_compiler, target):
3038 ldflags = []
3039 if (
3040 c_compiler.type == "clang-cl"
3041 and c_compiler.version >= "11"
3042 and target.cpu == "x86_64"
3043 ):
3044 ldflags.append("-CETCOMPAT")
3045 return ldflags
3046
3047
3048 set_config("MOZ_CETCOMPAT_LDFLAGS", cet_ldflags)
3049
3050
3051 # Frame pointers
3052 # ==============================================================
3053 @depends(c_compiler)
3054 def frame_pointer_flags(compiler):
3055 if compiler.type == "clang-cl":
3056 return namespace(
3057 enable=["-Oy-"],
3058 disable=["-Oy"],
3059 )
3060 return namespace(
3061 enable=["-fno-omit-frame-pointer", "-funwind-tables"],
3062 disable=["-fomit-frame-pointer", "-funwind-tables"],
3063 )
3064
3065
3066 @depends(
3067 moz_optimize,
3068 moz_debug,
3069 target,
3070 "--enable-memory-sanitizer",
3071 "--enable-address-sanitizer",
3072 "--enable-undefined-sanitizer",
3073 )
3074 def frame_pointer_default(optimize, debug, target, msan, asan, ubsan):
3075 return bool(
3076 not optimize
3077 or debug
3078 or msan
3079 or asan
3080 or ubsan
3081 or (target.os == "WINNT" and target.cpu in ("x86", "aarch64"))
3082 or target.os == "OSX"
3083 )
3084
3085
3086 option(
3087 "--enable-frame-pointers",
3088 default=frame_pointer_default,
3089 help="{Enable|Disable} frame pointers",
3090 )
3091
3092
3093 @depends("--enable-frame-pointers", frame_pointer_flags)
3094 def frame_pointer_flags(enable, flags):
3095 if enable:
3096 return flags.enable
3097 return flags.disable
3098
3099
3100 set_config("MOZ_FRAMEPTR_FLAGS", frame_pointer_flags)
3101
3102
3103 # Stack unwinding without frame pointers
3104 # ==============================================================
3105
3106
3107 have_unwind = check_symbol(
3108 "_Unwind_Backtrace", when=check_header("unwind.h", when=target_is_unix)
3109 )
3110
3111
3112 # Code Coverage
3113 # ==============================================================
3114
3115 option("--enable-coverage", env="MOZ_CODE_COVERAGE", help="Enable code coverage")
3116
3117
3118 @depends("--enable-coverage")
3119 def code_coverage(value):
3120 if value:
3121 return True
3122
3123
3124 set_config("MOZ_CODE_COVERAGE", code_coverage)
3125 set_define("MOZ_CODE_COVERAGE", code_coverage)
3126
3127
3128 @depends(target, c_compiler, build_environment, when=code_coverage)
3129 @imports("os")
3130 @imports("re")
3131 @imports(_from="__builtin__", _import="open")
3132 def coverage_cflags(target, c_compiler, build_env):
3133 cflags = ["--coverage"]
3134
3135 # clang 11 no longer accepts this flag (its behavior became the default)
3136 if c_compiler.type in ("clang", "clang-cl") and c_compiler.version < "11.0.0":
3137 cflags += [
3138 "-Xclang",
3139 "-coverage-no-function-names-in-data",
3140 ]
3141
3142 exclude = []
3143 if target.os == "WINNT" and c_compiler.type == "clang-cl":
3144 # VS files
3145 exclude.append("^.*[vV][sS]20[0-9]{2}.*$")
3146 # Files in fetches directory.
3147 exclude.append("^.*[\\\\/]fetches[\\\\/].*$")
3148 elif target.os == "OSX":
3149 # Files in fetches directory.
3150 exclude.append("^.*/fetches/.*$")
3151 elif target.os == "GNU":
3152 # Files in fetches directory.
3153 exclude.append("^.*/fetches/.*$")
3154 # Files in /usr/
3155 exclude.append("^/usr/.*$")
3156
3157 if exclude:
3158 exclude = ";".join(exclude)
3159 cflags += [
3160 f"-fprofile-exclude-files={exclude}",
3161 ]
3162
3163 response_file_path = os.path.join(build_env.topobjdir, "code_coverage_cflags")
3164
3165 with open(response_file_path, "w") as f:
3166 f.write(" ".join(cflags))
3167
3168 return ["@{}".format(response_file_path)]
3169
3170
3171 set_config("COVERAGE_CFLAGS", coverage_cflags)
3172
3173 # Assembler detection
3174 # ==============================================================
3175
3176 option(env="AS", nargs=1, help="Path to the assembler")
3177
3178
3179 @depends(target, c_compiler)
3180 def as_info(target, c_compiler):
3181 if c_compiler.type == "clang-cl":
3182 ml = {
3183 "x86": "ml.exe",
3184 "x86_64": "ml64.exe",
3185 "aarch64": "armasm64.exe",
3186 }.get(target.cpu)
3187 return namespace(type="masm", names=(ml,))
3188 # When building with anything but clang-cl, we just use the C compiler as the assembler.
3189 return namespace(type="gcc", names=(c_compiler.compiler,))
3190
3191
3192 # One would expect the assembler to be specified merely as a program. But in
3193 # cases where the assembler is passed down into js/, it can be specified in
3194 # the same way as CC: a program + a list of argument flags. We might as well
3195 # permit the same behavior in general, even though it seems somewhat unusual.
3196 # So we have to do the same sort of dance as we did above with
3197 # `provided_compiler`.
3198 provided_assembler = provided_program("AS")
3199 assembler = check_prog(
3200 "_AS",
3201 input=provided_assembler.program,
3202 what="the assembler",
3203 progs=as_info.names,
3204 paths=vc_toolchain_search_path,
3205 )
3206
3207
3208 @depends(as_info, assembler, provided_assembler, c_compiler)
3209 def as_with_flags(as_info, assembler, provided_assembler, c_compiler):
3210 if provided_assembler:
3211 return provided_assembler.wrapper + [assembler] + provided_assembler.flags
3212
3213 if as_info.type == "masm":
3214 return assembler
3215
3216 assert as_info.type == "gcc"
3217
3218 # Need to add compiler wrappers and flags as appropriate.
3219 return c_compiler.wrapper + [assembler] + c_compiler.flags
3220
3221
3222 set_config("AS", as_with_flags)
3223
3224
3225 @depends(assembler, c_compiler, extra_toolchain_flags)
3226 @imports("subprocess")
3227 @imports(_from="os", _import="devnull")
3228 def gnu_as(assembler, c_compiler, toolchain_flags):
3229 # clang uses a compatible GNU assembler.
3230 if c_compiler.type == "clang":
3231 return True
3232
3233 if c_compiler.type == "gcc":
3234 cmd = [assembler] + c_compiler.flags
3235 if toolchain_flags:
3236 cmd += toolchain_flags
3237 cmd += ["-Wa,--version", "-c", "-o", devnull, "-x", "assembler", "-"]
3238 # We don't actually have to provide any input on stdin, `Popen.communicate` will
3239 # close the stdin pipe.
3240 # clang will error if it uses its integrated assembler for this target,
3241 # so handle failures gracefully.
3242 if "GNU" in check_cmd_output(*cmd, stdin=subprocess.PIPE, onerror=lambda: ""):
3243 return True
3244
3245
3246 set_config("GNU_AS", gnu_as)
3247
3248
3249 @depends(as_info, target)
3250 def as_dash_c_flag(as_info, target):
3251 # armasm64 doesn't understand -c.
3252 if as_info.type == "masm" and target.cpu == "aarch64":
3253 return ""
3254 else:
3255 return "-c"
3256
3257
3258 set_config("AS_DASH_C_FLAG", as_dash_c_flag)
3259
3260
3261 @depends(as_info, target)
3262 def as_outoption(as_info, target):
3263 # The uses of ASOUTOPTION depend on the spacing for -o/-Fo.
3264 if as_info.type == "masm" and target.cpu != "aarch64":
3265 return "-Fo"
3266
3267 return "-o "
3268
3269
3270 set_config("ASOUTOPTION", as_outoption)
3271
3272 # clang plugin handling
3273 # ==============================================================
3274
3275 option(
3276 "--enable-clang-plugin",
3277 env="ENABLE_CLANG_PLUGIN",
3278 help="Enable building with the Clang plugin (gecko specific static analyzers)",
3279 )
3280
3281
3282 set_config("ENABLE_CLANG_PLUGIN", True, when="--enable-clang-plugin")
3283 set_define("MOZ_CLANG_PLUGIN", True, when="--enable-clang-plugin")
3284
3285
3286 @depends(host_c_compiler, c_compiler, when="--enable-clang-plugin")
3287 def llvm_config(host_c_compiler, c_compiler):
3288 clang = None
3289 for compiler in (host_c_compiler, c_compiler):
3290 if compiler and compiler.type == "clang":
3291 clang = compiler.compiler
3292 break
3293 elif compiler and compiler.type == "clang-cl":
3294 clang = os.path.join(os.path.dirname(compiler.compiler), "clang")
3295 break
3296
3297 if not clang:
3298 die("Cannot --enable-clang-plugin when not building with clang")
3299 llvm_config = "llvm-config"
3300 out = check_cmd_output(clang, "--print-prog-name=llvm-config", onerror=lambda: None)
3301 if out:
3302 llvm_config = out.rstrip()
3303 return (llvm_config,)
3304
3305
3306 llvm_config = check_prog(
3307 "LLVM_CONFIG",
3308 llvm_config,
3309 what="llvm-config",
3310 when="--enable-clang-plugin",
3311 paths=clang_search_path,
3312 )
3313
3314
3315 @template
3316 def llvm_tool(name):
3317 @depends(host_c_compiler, c_compiler, bindgen_config_paths)
3318 def llvm_tool(host_c_compiler, c_compiler, bindgen_config_paths):
3319 clang = None
3320 for compiler in (host_c_compiler, c_compiler):
3321 if compiler and compiler.type == "clang":
3322 clang = compiler.compiler
3323 break
3324 elif compiler and compiler.type == "clang-cl":
3325 clang = os.path.join(os.path.dirname(compiler.compiler), "clang")
3326 break
3327
3328 if not clang and bindgen_config_paths:
3329 clang = bindgen_config_paths.clang_path
3330 tool = name
3331 if clang:
3332 out = check_cmd_output(
3333 clang, "--print-prog-name=%s" % tool, onerror=lambda: None
3334 )
3335 if out:
3336 tool = out.rstrip()
3337 return (tool,)
3338
3339 return llvm_tool
3340
3341
3342 llvm_objdump = check_prog(
3343 "LLVM_OBJDUMP",
3344 llvm_tool("llvm-objdump"),
3345 what="llvm-objdump",
3346 when="--enable-compile-environment",
3347 paths=clang_search_path,
3348 )
3349
3350
3351 # Force clang-cl compiler to treat input as C++
3352 # ==============================================================
3353 add_flag("-TP", cxx_compiler, when=target_is_windows & ~building_with_gnu_compatible_cc)
3354
3355 # Use the old libstdc++ ABI
3356 # ==============================================================
3357 add_flag(
3358 "-D_GLIBCXX_USE_CXX11_ABI=0",
3359 cxx_compiler,
3360 when=stdcxx_compat,
3361 )
3362 add_flag(
3363 "-D_GLIBCXX_USE_CXX11_ABI=0",
3364 host_cxx_compiler,
3365 when=stdcxx_compat,
3366 )
3367
3368
3369 # Always included configuration file
3370 # ==============================================================
3371 @depends(c_compiler, build_environment, build_project)
3372 def defines_cpp_flags(c_compiler, build_environment, build_project):
3373 if build_project == "js":
3374 config_h = "js/src/js-confdefs.h"
3375 else:
3376 config_h = "mozilla-config.h"
3377
3378 if c_compiler.type == "clang-cl":
3379 flag = "-FI"
3380 else:
3381 flag = "-include"
3382
3383 return ["-DMOZILLA_CLIENT", flag, f"{build_environment.topobjdir}/{config_h}"]
3384
3385
3386 set_config("OS_COMPILE_CFLAGS", defines_cpp_flags)
3387 set_config("OS_COMPILE_CXXFLAGS", defines_cpp_flags)
3388
3389
3390 # Support various fuzzing options
3391 # ==============================================================
3392 option("--enable-fuzzing", help="Enable fuzzing support")
3393
3394
3395 @depends(build_project)
3396 def js_build(build_project):
3397 return build_project == "js"
3398
3399
3400 option(
3401 "--enable-js-fuzzilli",
3402 when=js_build,
3403 help="Enable fuzzilli support for the JS engine",
3404 )
3405
3406
3407 option(
3408 "--enable-snapshot-fuzzing",
3409 help="Enable experimental snapshot fuzzing support",
3410 )
3411
3412
3413 imply_option("--enable-fuzzing", True, when="--enable-snapshot-fuzzing")
3414
3415
3416 @depends("--enable-snapshot-fuzzing")
3417 def enable_snapshot_fuzzing(value):
3418 if value:
3419 return True
3420
3421
3422 @depends("--enable-fuzzing", enable_snapshot_fuzzing)
3423 def enable_fuzzing(value, snapshot_fuzzing):
3424 if value or snapshot_fuzzing:
3425 return True
3426
3427
3428 @depends("--enable-js-fuzzilli", when=js_build)
3429 def enable_js_fuzzilli(value):
3430 if value:
3431 return True
3432
3433
3434 @depends(enable_fuzzing, enable_snapshot_fuzzing)
3435 def check_aflfuzzer(fuzzing, snapshot_fuzzing):
3436 if fuzzing and not snapshot_fuzzing:
3437 return True
3438
3439
3440 @depends(
3441 try_compile(
3442 body="__AFL_COMPILER;", check_msg="for AFL compiler", when=check_aflfuzzer
3443 )
3444 )
3445 def enable_aflfuzzer(afl):
3446 if afl:
3447 return True
3448
3449
3450 @depends(enable_fuzzing, enable_aflfuzzer, enable_snapshot_fuzzing, c_compiler, target)
3451 def enable_libfuzzer(fuzzing, afl, snapshot_fuzzing, c_compiler, target):
3452 if (
3453 fuzzing
3454 and not afl
3455 and not snapshot_fuzzing
3456 and c_compiler.type == "clang"
3457 and target.os != "Android"
3458 ):
3459 return True
3460
3461
3462 @depends(enable_fuzzing, enable_aflfuzzer, enable_libfuzzer, enable_js_fuzzilli)
3463 def enable_fuzzing_interfaces(fuzzing, afl, libfuzzer, enable_js_fuzzilli):
3464 if fuzzing and (afl or libfuzzer) and not enable_js_fuzzilli:
3465 return True
3466
3467
3468 set_config("FUZZING", enable_fuzzing)
3469 set_define("FUZZING", enable_fuzzing)
3470
3471 set_config("LIBFUZZER", enable_libfuzzer)
3472 set_define("LIBFUZZER", enable_libfuzzer)
3473
3474 set_config("AFLFUZZ", enable_aflfuzzer)
3475 set_define("AFLFUZZ", enable_aflfuzzer)
3476
3477 set_config("FUZZING_INTERFACES", enable_fuzzing_interfaces)
3478 set_define("FUZZING_INTERFACES", enable_fuzzing_interfaces)
3479
3480 set_config("FUZZING_JS_FUZZILLI", enable_js_fuzzilli)
3481 set_define("FUZZING_JS_FUZZILLI", enable_js_fuzzilli)
3482
3483 set_config("FUZZING_SNAPSHOT", enable_snapshot_fuzzing)
3484 set_define("FUZZING_SNAPSHOT", enable_snapshot_fuzzing)
3485
3486
3487 @depends(
3488 c_compiler.try_compile(
3489 flags=["-fsanitize=fuzzer-no-link"],
3490 when=enable_fuzzing,
3491 check_msg="whether the C compiler supports -fsanitize=fuzzer-no-link",
3492 ),
3493 tsan,
3494 enable_js_fuzzilli,
3495 )
3496 def libfuzzer_flags(value, tsan, enable_js_fuzzilli):
3497 if tsan:
3498 # With ThreadSanitizer, we should not use any libFuzzer instrumentation because
3499 # it is incompatible (e.g. there are races on global sanitizer coverage counters).
3500 # Instead we use an empty set of flags here but still build the fuzzing targets.
3501 # With this setup, we can still run files through these targets in TSan builds,
3502 # e.g. those obtained from regular fuzzing.
3503 # This code can be removed once libFuzzer has been made compatible with TSan.
3504 #
3505 # Also, this code needs to be kept in sync with certain gyp files, currently:
3506 # - dom/media/webrtc/transport/third_party/nICEr/nicer.gyp
3507 return namespace(no_link_flag_supported=False, use_flags=[])
3508
3509 if enable_js_fuzzilli:
3510 # Fuzzilli comes with its own trace-pc interceptors and flag requirements.
3511 no_link_flag_supported = False
3512 use_flags = ["-fsanitize-coverage=trace-pc-guard", "-g"]
3513 elif value:
3514 no_link_flag_supported = True
3515 # recommended for (and only supported by) clang >= 6
3516 use_flags = ["-fsanitize=fuzzer-no-link"]
3517 else:
3518 no_link_flag_supported = False
3519 use_flags = ["-fsanitize-coverage=trace-pc-guard,trace-cmp"]
3520
3521 return namespace(
3522 no_link_flag_supported=no_link_flag_supported,
3523 use_flags=use_flags,
3524 )
3525
3526
3527 @depends(libfuzzer_flags, when=enable_libfuzzer)
3528 def sancov(libfuzzer_flags):
3529 return any(
3530 flag.startswith(head)
3531 for head in ("-fsanitize-coverage", "-fsanitize=fuzzer")
3532 for flag in libfuzzer_flags.use_flags
3533 )
3534
3535
3536 set_config("HAVE_LIBFUZZER_FLAG_FUZZER_NO_LINK", libfuzzer_flags.no_link_flag_supported)
3537 set_config("LIBFUZZER_FLAGS", libfuzzer_flags.use_flags)
3538
3539
3540 # Required for stand-alone (sanitizer-less) libFuzzer.
3541 # ==============================================================
3542 @depends(libfuzzer_flags, linker_flags, when=enable_libfuzzer)
3543 def add_libfuzzer_flags(libfuzzer_flags, linker_flags):
3544 linker_flags.ldflags.extend(libfuzzer_flags.use_flags)
3545 linker_flags.ldflags.append("-rdynamic")
3546
3547
3548 # The LLVM symbolizer is used by all sanitizers
3549 check_prog(
3550 "LLVM_SYMBOLIZER",
3551 ("llvm-symbolizer",),
3552 allow_missing=True,
3553 paths=clang_search_path,
3554 when=asan | msan | tsan | any_ubsan | enable_fuzzing,
3555 )
3556
3557
3558 # Shared library building
3559 # ==============================================================
3560
3561
3562 # XXX: The use of makefile constructs in these variables is awful.
3563 @depends(target, c_compiler)
3564 def make_shared_library(target, compiler):
3565 if target.os == "WINNT":
3566 if compiler.type == "gcc":
3567 return namespace(
3568 mkshlib=["$(CXX)", "$(DSO_LDOPTS)", "-o", "$@"],
3569 mkcshlib=["$(CC)", "$(DSO_LDOPTS)", "-o", "$@"],
3570 )
3571 elif compiler.type == "clang":
3572 return namespace(
3573 mkshlib=[
3574 "$(CXX)",
3575 "$(DSO_LDOPTS)",
3576 "-Wl,-pdb,$(LINK_PDBFILE)",
3577 "-o",
3578 "$@",
3579 ],
3580 mkcshlib=[
3581 "$(CC)",
3582 "$(DSO_LDOPTS)",
3583 "-Wl,-pdb,$(LINK_PDBFILE)",
3584 "-o",
3585 "$@",
3586 ],
3587 )
3588 else:
3589 linker = [
3590 "$(LINKER)",
3591 "-NOLOGO",
3592 "-DLL",
3593 "-OUT:$@",
3594 "-PDB:$(LINK_PDBFILE)",
3595 "$(DSO_LDOPTS)",
3596 ]
3597 return namespace(
3598 mkshlib=linker,
3599 mkcshlib=linker,
3600 )
3601
3602 cc = ["$(CC)", "$(COMPUTED_C_LDFLAGS)"]
3603 cxx = ["$(CXX)", "$(COMPUTED_CXX_LDFLAGS)"]
3604 flags = ["$(DSO_LDOPTS)"]
3605 output = ["-o", "$@"]
3606
3607 if target.kernel == "Darwin":
3608 soname = []
3609 elif target.os == "NetBSD":
3610 soname = ["-Wl,-soname,$(DSO_SONAME)"]
3611 else:
3612 assert compiler.type in ("gcc", "clang")
3613
3614 soname = ["-Wl,-h,$(DSO_SONAME)"]
3615
3616 return namespace(
3617 mkshlib=cxx + flags + soname + output,
3618 mkcshlib=cc + flags + soname + output,
3619 )
3620
3621
3622 set_config("MKSHLIB", make_shared_library.mkshlib)
3623 set_config("MKCSHLIB", make_shared_library.mkcshlib)
3624
3625
3626 @depends(c_compiler, toolchain_prefix, when=target_is_windows)
3627 def rc_names(c_compiler, toolchain_prefix):
3628 if c_compiler.type in ("gcc", "clang"):
3629 return tuple("%s%s" % (p, "windres") for p in ("",) + (toolchain_prefix or ()))
3630 return ("llvm-rc",)
3631
3632
3633 check_prog("RC", rc_names, paths=clang_search_path, when=target_is_windows)
3634
3635
3636 @template
3637 def ar_config(c_compiler, toolchain_prefix=None):
3638 if not toolchain_prefix:
3639 toolchain_prefix = dependable(None)
3640
3641 @depends(toolchain_prefix, c_compiler)
3642 def ar_config(toolchain_prefix, c_compiler):
3643 if c_compiler.type == "clang-cl":
3644 return namespace(
3645 names=("llvm-lib",),
3646 flags=("-llvmlibthin", "-out:$@"),
3647 )
3648
3649 names = tuple("%s%s" % (p, "ar") for p in (toolchain_prefix or ()) + ("",))
3650 if c_compiler.type == "clang":
3651 # Get the llvm-ar path as per the output from clang --print-prog-name=llvm-ar
3652 # so that we directly get the one under the clang directory, rather than one
3653 # that might be in /usr/bin and that might point to one from a different version
3654 # of clang.
3655 out = check_cmd_output(
3656 c_compiler.compiler, "--print-prog-name=llvm-ar", onerror=lambda: None
3657 )
3658 llvm_ar = out.rstrip() if out else "llvm-ar"
3659 names = (llvm_ar,) + names
3660
3661 return namespace(
3662 names=names,
3663 flags=("crs", "$@"),
3664 )
3665
3666 return ar_config
3667
3668
3669 target_ar_config = ar_config(c_compiler, toolchain_prefix)
3670
3671 target_ar = check_prog("AR", target_ar_config.names, paths=clang_search_path)
3672
3673 set_config("AR_FLAGS", target_ar_config.flags)
3674
3675
3676 @depends(c_compiler, extra_toolchain_flags, target_ar, target_ar_config)
3677 @checking("whether ar supports response files")
3678 @imports("os")
3679 @imports(_from="__builtin__", _import="FileNotFoundError")
3680 @imports(_from="__builtin__", _import="open")
3681 @imports(_from="mozbuild.configure.util", _import="LineIO")
3682 def ar_supports_response_files(c_compiler, extra_toolchain_flags, ar, ar_config):
3683 lib_path = list_path = None
3684 with create_temporary_file(suffix=".o") as obj_path:
3685 if (
3686 try_invoke_compiler(
3687 # No configure_cache because it would not create the
3688 # expected output file.
3689 None,
3690 [c_compiler.compiler] + c_compiler.flags,
3691 c_compiler.language,
3692 "void foo() {}",
3693 ["-c", "-o", obj_path] + (extra_toolchain_flags or []),
3694 wrapper=c_compiler.wrapper,
3695 onerror=lambda: None,
3696 )
3697 is not None
3698 ):
3699 with create_temporary_file(suffix=".list") as list_path:
3700 with open(list_path, "w") as fd:
3701 fd.write(obj_path)
3702
3703 log.debug("Creating `%s` with content:", list_path)
3704 log.debug("| %s", obj_path)
3705
3706 with create_temporary_file(suffix=".a") as lib_path:
3707 os.remove(lib_path)
3708 ar_command = (
3709 [ar]
3710 + [x.replace("$@", lib_path) for x in ar_config.flags]
3711 + ["@" + list_path]
3712 )
3713 result = check_cmd_output(*ar_command, onerror=lambda: None)
3714 return result is not None
3715
3716
3717 set_config("AR_SUPPORTS_RESPONSE_FILE", True, when=ar_supports_response_files)
3718
3719 host_ar_config = ar_config(host_c_compiler)
3720
3721 check_prog("HOST_AR", host_ar_config.names, paths=clang_search_path)
3722
3723
3724 @depends(toolchain_prefix, c_compiler)
3725 def nm_names(toolchain_prefix, c_compiler):
3726 names = tuple("%s%s" % (p, "nm") for p in (toolchain_prefix or ()) + ("",))
3727 if c_compiler.type == "clang":
3728 # Get the llvm-nm path as per the output from clang --print-prog-name=llvm-nm
3729 # so that we directly get the one under the clang directory, rather than one
3730 # that might be in /usr/bin and that might point to one from a different version
3731 # of clang.
3732 out = check_cmd_output(
3733 c_compiler.compiler, "--print-prog-name=llvm-nm", onerror=lambda: None
3734 )
3735 llvm_nm = out.rstrip() if out else "llvm-nm"
3736 names = (llvm_nm,) + names
3737
3738 return names
3739
3740
3741 check_prog("NM", nm_names, paths=clang_search_path, when=target_has_linux_kernel)
3742
3743
3744 # We don't use it in the code, but it can be useful for debugging, so give
3745 # the user the option of enabling it.
3746 option("--enable-cpp-rtti", help="Enable C++ RTTI")
3747
3748
3749 @depends(compilation_flags, c_compiler, "--enable-cpp-rtti")
3750 def enable_cpp_rtti(compilation_flags, c_compiler, enable_rtti):
3751 if enable_rtti:
3752 return
3753 if c_compiler.type == "clang-cl":
3754 compilation_flags.cxxflags.append("-GR-")
3755 else:
3756 compilation_flags.cxxflags.append("-fno-rtti")
3757
3758
3759 option(
3760 "--enable-path-remapping",
3761 nargs="*",
3762 choices=("c", "rust"),
3763 help="Enable remapping source and object paths in compiled outputs",
3764 )
3765
3766
3767 @depends("--enable-path-remapping")
3768 def path_remapping(value):
3769 if len(value):
3770 return value
3771 if bool(value):
3772 return ["c", "rust"]
3773 return []
3774
3775
3776 @depends(
3777 target,
3778 build_environment,
3779 target_sysroot.path,
3780 valid_windows_sdk_dir,
3781 vc_path,
3782 when="--enable-path-remapping",
3783 )
3784 def path_remappings(target, build_env, sysroot_path, windows_sdk_dir, vc_path):
3785 win = target.kernel == "WINNT"
3786
3787 # The prefix maps are processed in the order they're specified on the
3788 # command line. Therefore, to accommodate object directories in the source
3789 # directory, it's important that we map the topobjdir before the topsrcdir,
3790 # 'cuz we might have /src/obj/=/o/ and /src/=/s/. The various other
3791 # directories might be subdirectories of topsrcdir as well, so they come
3792 # earlier still.
3793
3794 path_remappings = []
3795
3796 # We will have only one sysroot or SDK, so all can have the same mnemonic: K
3797 # for "kit" (since S is taken for "source"). See
3798 # https://blog.llvm.org/2019/11/deterministic-builds-with-clang-and-lld.html
3799 # for how to use the Windows `subst` command to map these in debuggers and
3800 # IDEs.
3801 if sysroot_path:
3802 path_remappings.append((sysroot_path, "k:/" if win else "/sysroot/"))
3803 if windows_sdk_dir:
3804 path_remappings.append(
3805 (windows_sdk_dir.path, "k:/" if win else "/windows_sdk/")
3806 )
3807 if vc_path:
3808 path_remappings.append((vc_path, "v:/" if win else "/vc/"))
3809
3810 path_remappings += [
3811 (build_env.topobjdir, "o:/" if win else "/topobjdir/"),
3812 (build_env.topsrcdir, "s:/" if win else "/topsrcdir/"),
3813 ]
3814
3815 path_remappings = [
3816 (normsep(old).rstrip("/") + "/", new) for old, new in path_remappings
3817 ]
3818
3819 # It is tempting to sort these, but we want the order to be the same across
3820 # machines so that we can share cache hits. Therefore we reject bad
3821 # configurations rather than trying to make the configuration good.
3822 for i in range(len(path_remappings) - 1):
3823 p = path_remappings[i][0]
3824 for q, _ in path_remappings[i + 1 :]:
3825 if q.startswith(p):
3826 die(f"Cannot remap paths because {p} is an ancestor of {q}")
3827
3828 return path_remappings
3829
3830
3831 @depends(target)
3832 def is_intel_target(target):
3833 return target.cpu in ("x86", "x86_64")
3834
3835
3836 @depends(target)
3837 def is_aarch64_target(target):
3838 return target.cpu == "aarch64"
3839
3840
3841 set_config("MMX_FLAGS", ["-mmmx"])
3842 set_config("SSE_FLAGS", ["-msse"])
3843 set_config("SSE2_FLAGS", ["-msse2"])
3844 set_config("SSSE3_FLAGS", ["-mssse3"])
3845 set_config("SSE4_2_FLAGS", ["-msse4.2"])
3846 set_config("FMA_FLAGS", ["-mfma"])
3847 set_config("AVX2_FLAGS", ["-mavx2"])
3848 set_config(
3849 "AVXVNNI_FLAGS",
3850 ["-mavxvnni"],
3851 try_compile(
3852 check_msg="for -mavxvnni support", flags=["-mavxvnni"], when=is_intel_target
3853 ),
3854 )
3855 set_config(
3856 "AVX512BW_FLAGS",
3857 ["-mavx512bw", "-mavx512f", "-mavx512dq", "-mavx512cd"],
3858 try_compile(
3859 check_msg="for -mavx512bw support",
3860 flags=["-mavx512bw", "-mavx512f", "-mavx512dq", "-mavx512cd"],
3861 when=is_intel_target,
3862 ),
3863 )
3864
3865 # AVX512VNNI can be based on either avx512bw or avx512vbmi. We choose the
3866 # former.
3867 set_config(
3868 "AVX512VNNI_FLAGS",
3869 ["-mavx512vnni", "-mavx512bw", "-mavx512f", "-mavx512dq", "-mavx512cd"],
3870 try_compile(
3871 check_msg="for -mavx512vnni support",
3872 flags=["-mavx512vnni", "-mavx512bw", "-mavx512f", "-mavx512dq", "-mavx512cd"],
3873 when=is_intel_target,
3874 ),
3875 )
3876
3877
3878 set_config(
3879 "NEON_I8MM_FLAGS",
3880 ["-march=armv8.2-a+i8mm"],
3881 try_compile(
3882 check_msg="for i8mm target feature",
3883 flags=["-march=armv8.2-a+i8mm"],
3884 when=is_aarch64_target,
3885 ),
3886 )
3887
3888 set_config(
3889 "SVE2_FLAGS",
3890 ["-march=armv9-a+sve2"],
3891 try_compile(
3892 check_msg="for ARM SVE2 target feature",
3893 flags=["-march=armv9-a+sve2"],
3894 when=is_aarch64_target,
3895 ),
3896 )
3897
3898 set_config(
3899 "DOTPROD_FLAGS",
3900 ["-march=armv8.2-a+dotprod"],
3901 try_compile(
3902 check_msg="for ARM dotprod target feature",
3903 flags=["-march=armv8.2-a+dotprod"],
3904 when=is_aarch64_target,
3905 ),
3906 )
3907
3908 # dtrace support
3909 ##
3910 option("--enable-dtrace", help="Build with dtrace support")
3911
3912 dtrace = check_header(
3913 "sys/sdt.h",
3914 when="--enable-dtrace",
3915 onerror=lambda: die("dtrace enabled but sys/sdt.h not found"),
3916 )
3917
3918 set_config("HAVE_DTRACE", True, when=dtrace)
3919 set_define("INCLUDE_MOZILLA_DTRACE", True, when=dtrace)