Debian Codegraph @

platform/windows/detect.py

raw symbols SCIP
1 import os
2 import re
3 import subprocess
4 import sys
5 from typing import TYPE_CHECKING
6
7 import methods
8 from methods import print_error, print_warning
9 from platform_methods import detect_arch, validate_arch
10
11 if TYPE_CHECKING:
12 from SCons.Script.SConscript import SConsEnvironment
13
14 # To match other platforms
15 STACK_SIZE = 8388608
16 STACK_SIZE_SANITIZERS = 30 * 1024 * 1024
17
18
19 def get_name():
20 return "Windows"
21
22
23 def try_cmd(test, prefix, arch, check_clang=False):
24 archs = ["x86_64", "x86_32", "arm64", "arm32"]
25 if arch:
26 archs = [arch]
27 if os.name == "nt":
28 archs += [""]
29
30 for a in archs:
31 try:
32 out = subprocess.Popen(
33 get_mingw_bin_prefix(prefix, a) + test,
34 shell=True,
35 stderr=subprocess.PIPE,
36 stdout=subprocess.PIPE,
37 )
38 outs, errs = out.communicate()
39 if out.returncode == 0:
40 if check_clang and not outs.startswith(b"clang"):
41 return False
42 return True
43 except Exception:
44 pass
45
46 return False
47
48
49 def can_build():
50 if os.name == "nt":
51 # Building natively on Windows
52 return True
53
54 if os.name == "posix":
55 # Cross-compiling with MinGW-w64 (old MinGW32 is not supported)
56 prefix = os.getenv("MINGW_PREFIX", "")
57
58 if try_cmd("gcc --version", prefix, "") or try_cmd("clang --version", prefix, ""):
59 return True
60
61 return False
62
63
64 def get_mingw_bin_prefix(prefix, arch):
65 bin_prefix = (os.path.normpath(os.path.join(prefix, "bin")) + os.sep) if prefix else ""
66 ARCH_PREFIXES = {
67 "x86_64": "x86_64-w64-mingw32-",
68 "x86_32": "i686-w64-mingw32-",
69 "arm32": "armv7-w64-mingw32-",
70 "arm64": "aarch64-w64-mingw32-",
71 }
72 arch_prefix = ARCH_PREFIXES[arch] if arch else ""
73 return bin_prefix + arch_prefix
74
75
76 def get_detected(env: "SConsEnvironment", tool: str) -> str:
77 checks = [
78 get_mingw_bin_prefix(env["mingw_prefix"], env["arch"]) + tool,
79 get_mingw_bin_prefix(env["mingw_prefix"], "") + tool,
80 ]
81 return str(env.Detect(checks))
82
83
84 def detect_build_env_arch():
85 msvc_target_aliases = {
86 "amd64": "x86_64",
87 "i386": "x86_32",
88 "i486": "x86_32",
89 "i586": "x86_32",
90 "i686": "x86_32",
91 "x86": "x86_32",
92 "x64": "x86_64",
93 "x86_64": "x86_64",
94 "arm": "arm32",
95 "arm64": "arm64",
96 "aarch64": "arm64",
97 }
98 if os.getenv("VCINSTALLDIR") or os.getenv("VCTOOLSINSTALLDIR"):
99 if os.getenv("Platform"):
100 msvc_arch = os.getenv("Platform").lower()
101 if msvc_arch in msvc_target_aliases.keys():
102 return msvc_target_aliases[msvc_arch]
103
104 if os.getenv("VSCMD_ARG_TGT_ARCH"):
105 msvc_arch = os.getenv("VSCMD_ARG_TGT_ARCH").lower()
106 if msvc_arch in msvc_target_aliases.keys():
107 return msvc_target_aliases[msvc_arch]
108
109 # Pre VS 2017 checks.
110 if os.getenv("VCINSTALLDIR"):
111 PATH = os.getenv("PATH").upper()
112 VCINSTALLDIR = os.getenv("VCINSTALLDIR").upper()
113 path_arch = {
114 "BIN\\x86_ARM;": "arm32",
115 "BIN\\amd64_ARM;": "arm32",
116 "BIN\\x86_ARM64;": "arm64",
117 "BIN\\amd64_ARM64;": "arm64",
118 "BIN\\x86_amd64;": "a86_64",
119 "BIN\\amd64;": "x86_64",
120 "BIN\\amd64_x86;": "x86_32",
121 "BIN;": "x86_32",
122 }
123 for path, arch in path_arch.items():
124 final_path = VCINSTALLDIR + path
125 if final_path in PATH:
126 return arch
127
128 # VS 2017 and newer.
129 if os.getenv("VCTOOLSINSTALLDIR"):
130 host_path_index = os.getenv("PATH").upper().find(os.getenv("VCTOOLSINSTALLDIR").upper() + "BIN\\HOST")
131 if host_path_index > -1:
132 first_path_arch = os.getenv("PATH")[host_path_index:].split(";")[0].rsplit("\\", 1)[-1].lower()
133 if first_path_arch in msvc_target_aliases.keys():
134 return msvc_target_aliases[first_path_arch]
135
136 msys_target_aliases = {
137 "mingw32": "x86_32",
138 "mingw64": "x86_64",
139 "ucrt64": "x86_64",
140 "clang64": "x86_64",
141 "clang32": "x86_32",
142 "clangarm64": "arm64",
143 }
144 if os.getenv("MSYSTEM"):
145 msys_arch = os.getenv("MSYSTEM").lower()
146 if msys_arch in msys_target_aliases.keys():
147 return msys_target_aliases[msys_arch]
148
149 return ""
150
151
152 def get_tools(env: "SConsEnvironment"):
153 from SCons.Tool.MSCommon import msvc_exists
154
155 if os.name != "nt" or env.get("use_mingw") or not msvc_exists():
156 return ["mingw"]
157 else:
158 msvc_arch_aliases = {"x86_32": "x86", "arm32": "arm"}
159 env["TARGET_ARCH"] = msvc_arch_aliases.get(env["arch"], env["arch"])
160 env["MSVC_VERSION"] = env["MSVS_VERSION"] = env.get("msvc_version")
161 return ["msvc", "mslink", "mslib"]
162
163
164 def get_opts():
165 from SCons.Variables import BoolVariable, EnumVariable
166
167 mingw = os.getenv("MINGW_PREFIX", "")
168
169 # Direct3D 12 SDK dependencies folder.
170 d3d12_deps_folder = os.getenv("LOCALAPPDATA")
171 if d3d12_deps_folder:
172 d3d12_deps_folder = os.path.join(d3d12_deps_folder, "Godot", "build_deps")
173 else:
174 # Cross-compiling, the deps install script puts things in `bin`.
175 # Getting an absolute path to it is a bit hacky in Python.
176 try:
177 import inspect
178
179 caller_frame = inspect.stack()[1]
180 caller_script_dir = os.path.dirname(os.path.abspath(caller_frame[1]))
181 d3d12_deps_folder = os.path.join(caller_script_dir, "bin", "build_deps")
182 except Exception: # Give up.
183 d3d12_deps_folder = ""
184
185 return [
186 ("mingw_prefix", "MinGW prefix", mingw),
187 EnumVariable("windows_subsystem", "Windows subsystem", "gui", ["gui", "console"], ignorecase=2),
188 ("msvc_version", "MSVC version to use. Handled automatically by SCons if omitted.", ""),
189 BoolVariable("use_mingw", "Use the Mingw compiler, even if MSVC is installed.", False),
190 BoolVariable("use_llvm", "Use the LLVM compiler", False),
191 BoolVariable("use_static_cpp", "Link MinGW/MSVC C++ runtime libraries statically", True),
192 BoolVariable("use_asan", "Use address sanitizer (ASAN)", False),
193 BoolVariable("use_ubsan", "Use LLVM compiler undefined behavior sanitizer (UBSAN)", False),
194 BoolVariable("debug_crt", "Compile with MSVC's debug CRT (/MDd)", False),
195 BoolVariable("incremental_link", "Use MSVC incremental linking. May increase or decrease build times.", False),
196 BoolVariable("silence_msvc", "Silence MSVC's cl/link stdout bloat, redirecting any errors to stderr.", True),
197 ("angle_libs", "Path to the ANGLE static libraries", ""),
198 # Direct3D 12 support.
199 (
200 "mesa_libs",
201 "Path to the MESA/NIR static libraries (required for D3D12)",
202 os.path.join(d3d12_deps_folder, "mesa"),
203 ),
204 (
205 "agility_sdk_path",
206 "Path to the Agility SDK distribution (optional for D3D12)",
207 os.path.join(d3d12_deps_folder, "agility_sdk"),
208 ),
209 BoolVariable(
210 "agility_sdk_multiarch",
211 "Whether the Agility SDK DLLs will be stored in arch-specific subdirectories",
212 False,
213 ),
214 BoolVariable("use_pix", "Use PIX (Performance tuning and debugging for DirectX 12) runtime", False),
215 (
216 "pix_path",
217 "Path to the PIX runtime distribution (optional for D3D12)",
218 os.path.join(d3d12_deps_folder, "pix"),
219 ),
220 ]
221
222
223 def get_doc_classes():
224 return [
225 "EditorExportPlatformWindows",
226 ]
227
228
229 def get_doc_path():
230 return "doc_classes"
231
232
233 def get_flags():
234 arch = detect_build_env_arch() or detect_arch()
235
236 return {
237 "arch": arch,
238 "d3d12": True,
239 "supported": ["d3d12", "dcomp", "library", "mono", "xaudio2"],
240 }
241
242
243 def configure_msvc(env: "SConsEnvironment"):
244 """Configure env to work with MSVC"""
245
246 ## Build type
247
248 # TODO: Re-evaluate the need for this / streamline with common config.
249 if env["target"] == "template_release" and env["library_type"] == "executable":
250 env.Append(LINKFLAGS=["/ENTRY:mainCRTStartup"])
251
252 if env["windows_subsystem"] == "gui":
253 env.Append(LINKFLAGS=["/SUBSYSTEM:WINDOWS"])
254 else:
255 env.Append(LINKFLAGS=["/SUBSYSTEM:CONSOLE"])
256 env.AppendUnique(CPPDEFINES=["WINDOWS_SUBSYSTEM_CONSOLE"])
257
258 ## Compile/link flags
259
260 if env["use_llvm"]:
261 env["CC"] = "clang-cl"
262 env["CXX"] = "clang-cl"
263 env["LINK"] = "lld-link"
264 env["AR"] = "llvm-lib"
265
266 env.AppendUnique(CPPDEFINES=["R128_STDC_ONLY"])
267 env.extra_suffix = ".llvm" + env.extra_suffix
268
269 # Ensure intellisense tools like `compile_commands.json` play nice with MSVC syntax.
270 env["CPPDEFPREFIX"] = "-D"
271 env["INCPREFIX"] = "-I"
272 env.AppendUnique(CPPDEFINES=[("alloca", "_alloca")])
273
274 if env["silence_msvc"] and not env.GetOption("clean"):
275 from tempfile import mkstemp
276
277 # Ensure we have a location to write captured output to, in case of false positives.
278 capture_path = methods.base_folder / "platform" / "windows" / "msvc_capture.log"
279 with open(capture_path, "wt", encoding="utf-8"):
280 pass
281
282 old_spawn = env["SPAWN"]
283 re_redirect_stream = re.compile(r"^[12]?>")
284 re_cl_capture = re.compile(r"^.+\.(c|cc|cpp|cxx|c[+]{2})$", re.IGNORECASE)
285 re_link_capture = re.compile(r'\s{3}\S.+\s(?:"[^"]+.lib"|\S+.lib)\s.+\s(?:"[^"]+.exp"|\S+.exp)')
286
287 def spawn_capture(sh, escape, cmd, args, env):
288 # We only care about cl/link, process everything else as normal.
289 if args[0] not in ["cl", "link"]:
290 return old_spawn(sh, escape, cmd, args, env)
291
292 # Process as normal if the user is manually rerouting output.
293 for arg in args:
294 if re_redirect_stream.match(arg):
295 return old_spawn(sh, escape, cmd, args, env)
296
297 tmp_stdout, tmp_stdout_name = mkstemp()
298 os.close(tmp_stdout)
299 args.append(f">{tmp_stdout_name}")
300 ret = old_spawn(sh, escape, cmd, args, env)
301
302 try:
303 with open(tmp_stdout_name, "r", encoding=sys.stdout.encoding, errors="replace") as tmp_stdout:
304 lines = tmp_stdout.read().splitlines()
305 os.remove(tmp_stdout_name)
306 except OSError:
307 pass
308
309 # Early process no lines (OSError)
310 if not lines:
311 return ret
312
313 is_cl = args[0] == "cl"
314 content = ""
315 caught = False
316 for line in lines:
317 # These conditions are far from all-encompassing, but are specialized
318 # for what can be reasonably expected to show up in the repository.
319 if not caught and (is_cl and re_cl_capture.match(line)) or (not is_cl and re_link_capture.match(line)):
320 caught = True
321 try:
322 with open(capture_path, "a", encoding=sys.stdout.encoding, errors="replace") as log:
323 log.write(line + "\n")
324 except OSError:
325 print_warning(f'Failed to log captured line: "{line}".')
326 continue
327 content += line + "\n"
328 # Content remaining assumed to be an error/warning.
329 if content:
330 sys.stderr.write(content)
331
332 return ret
333
334 env["SPAWN"] = spawn_capture
335
336 if env["debug_crt"]:
337 # Always use dynamic runtime, static debug CRT breaks thread_local.
338 env.AppendUnique(CCFLAGS=["/MDd"])
339 else:
340 if env["use_static_cpp"]:
341 env.AppendUnique(CCFLAGS=["/MT"])
342 else:
343 env.AppendUnique(CCFLAGS=["/MD"])
344
345 # MSVC incremental linking is broken and may _increase_ link time (GH-77968).
346 if not env["incremental_link"]:
347 env.Append(LINKFLAGS=["/INCREMENTAL:NO"])
348
349 if env["arch"] == "x86_32":
350 env["x86_libtheora_opt_vc"] = True
351
352 env.Append(CCFLAGS=["/fp:strict"])
353
354 env.AppendUnique(CCFLAGS=["/Gd", "/GR", "/nologo"])
355 env.AppendUnique(CCFLAGS=["/utf-8"]) # Force to use Unicode encoding.
356 env.AppendUnique(CCFLAGS=["/bigobj"]) # Support big objects.
357
358 env.AppendUnique(
359 CPPDEFINES=[
360 "WINDOWS_ENABLED",
361 "WASAPI_ENABLED",
362 "WINMIDI_ENABLED",
363 "TYPED_METHOD_BIND",
364 "WIN32",
365 ("WINVER", "0x0A00"),
366 ("_WIN32_WINNT", "0x0A00"),
367 ]
368 )
369 env.AppendUnique(CPPDEFINES=["NOMINMAX"]) # disable bogus min/max WinDef.h macros
370 if env["arch"] == "x86_64":
371 env.AppendUnique(CPPDEFINES=["_WIN64"])
372
373 # Sanitizers
374 prebuilt_lib_extra_suffix = ""
375 if env["use_asan"]:
376 env.extra_suffix += ".san"
377 prebuilt_lib_extra_suffix = ".san"
378 env.AppendUnique(CPPDEFINES=["SANITIZERS_ENABLED"])
379 env.Append(CCFLAGS=["/fsanitize=address"])
380 env.Append(LINKFLAGS=["/INFERASANLIBS"])
381
382 ## Libs
383
384 LIBS = [
385 "winmm",
386 "dsound",
387 "kernel32",
388 "ole32",
389 "oleaut32",
390 "sapi",
391 "user32",
392 "gdi32",
393 "IPHLPAPI",
394 "Shlwapi",
395 "Shcore",
396 "wsock32",
397 "Ws2_32",
398 "shell32",
399 "advapi32",
400 "dinput8",
401 "dxguid",
402 "imm32",
403 "bcrypt",
404 "Crypt32",
405 "Avrt",
406 "dwmapi",
407 "dwrite",
408 "wbemuuid",
409 "ntdll",
410 "hid",
411 ]
412
413 if env.debug_features:
414 LIBS += ["psapi", "dbghelp"]
415
416 if env["accesskit"]:
417 if env["accesskit_sdk_path"] != "":
418 env.Prepend(CPPPATH=[env["accesskit_sdk_path"] + "/include"])
419 if env["arch"] == "arm64":
420 env.Append(LIBPATH=[env["accesskit_sdk_path"] + "/lib/windows/arm64/msvc/static"])
421 elif env["arch"] == "x86_64":
422 env.Append(LIBPATH=[env["accesskit_sdk_path"] + "/lib/windows/x86_64/msvc/static"])
423 elif env["arch"] == "x86_32":
424 env.Append(LIBPATH=[env["accesskit_sdk_path"] + "/lib/windows/x86/msvc/static"])
425 LIBS += [
426 "accesskit",
427 "uiautomationcore",
428 "runtimeobject",
429 "propsys",
430 "oleaut32",
431 "user32",
432 "userenv",
433 "ntdll",
434 ]
435 else:
436 env.Append(CPPDEFINES=["ACCESSKIT_DYNAMIC"])
437 env.Append(CPPDEFINES=["ACCESSKIT_ENABLED"])
438
439 if env["vulkan"]:
440 env.AppendUnique(CPPDEFINES=["VULKAN_ENABLED", "RD_ENABLED"])
441 if not env["use_volk"]:
442 LIBS += ["vulkan"]
443
444 if env["sdl"]:
445 env.Append(CPPDEFINES=["SDL_ENABLED"])
446
447 if env["d3d12"]:
448 check_d3d12_installed(env, env["arch"] + "-msvc")
449
450 env.AppendUnique(CPPDEFINES=["D3D12_ENABLED", "RD_ENABLED"])
451 LIBS += ["dxgi", "dxguid"]
452 LIBS += ["version"] # Mesa dependency.
453
454 # PIX
455 if env["arch"] not in ["x86_64", "arm64"] or env["pix_path"] == "" or not os.path.exists(env["pix_path"]):
456 env["use_pix"] = False
457
458 if env["use_pix"]:
459 arch_subdir = "arm64" if env["arch"] == "arm64" else "x64"
460
461 env.Append(LIBPATH=[env["pix_path"] + "/bin/" + arch_subdir])
462 LIBS += ["WinPixEventRuntime"]
463
464 if os.path.exists(env["mesa_libs"] + "-" + env["arch"] + "-msvc"):
465 env.Append(LIBPATH=[env["mesa_libs"] + "-" + env["arch"] + "-msvc/bin"])
466 else:
467 env.Append(LIBPATH=[env["mesa_libs"] + "/bin"])
468 LIBS += ["libNIR.windows." + env["arch"] + prebuilt_lib_extra_suffix]
469
470 if env["opengl3"]:
471 env.AppendUnique(CPPDEFINES=["GLES3_ENABLED"])
472 if env["angle_libs"] != "":
473 env.AppendUnique(CPPDEFINES=["EGL_STATIC"])
474 env.Append(LIBPATH=[env["angle_libs"]])
475 LIBS += [
476 "libANGLE.windows." + env["arch"] + prebuilt_lib_extra_suffix,
477 "libEGL.windows." + env["arch"] + prebuilt_lib_extra_suffix,
478 "libGLES.windows." + env["arch"] + prebuilt_lib_extra_suffix,
479 ]
480 LIBS += ["dxgi", "d3d9", "d3d11"]
481 env.Prepend(CPPPATH=["#thirdparty/angle/include"])
482
483 if env["target"] in ["editor", "template_debug"]:
484 LIBS += ["psapi", "dbghelp"]
485
486 if env["use_llvm"]:
487 LIBS += [f"clang_rt.builtins-{env['arch']}"]
488
489 env.Append(LINKFLAGS=[p + env["LIBSUFFIX"] for p in LIBS])
490
491 ## LTO
492
493 if env["lto"] == "auto": # No LTO by default for MSVC, doesn't help.
494 env["lto"] = "none"
495
496 if env["lto"] != "none":
497 if env["lto"] == "thin":
498 if not env["use_llvm"]:
499 print("ThinLTO is only compatible with LLVM, use `use_llvm=yes` or `lto=full`.")
500 sys.exit(255)
501
502 env.AppendUnique(CCFLAGS=["-flto=thin"])
503 elif env["use_llvm"]:
504 env.AppendUnique(CCFLAGS=["-flto"])
505 else:
506 env.AppendUnique(CCFLAGS=["/GL"])
507 if env["progress"]:
508 env.AppendUnique(LINKFLAGS=["/LTCG:STATUS"])
509 else:
510 env.AppendUnique(LINKFLAGS=["/LTCG"])
511 env.AppendUnique(ARFLAGS=["/LTCG"])
512
513 env.Append(LINKFLAGS=["/NATVIS:platform\\windows\\godot.natvis"])
514
515 if env["use_asan"]:
516 env.AppendUnique(LINKFLAGS=["/STACK:" + str(STACK_SIZE_SANITIZERS)])
517 else:
518 env.AppendUnique(LINKFLAGS=["/STACK:" + str(STACK_SIZE)])
519
520
521 def get_ar_version(env):
522 ret = {
523 "major": -1,
524 "minor": -1,
525 "patch": -1,
526 "is_llvm": False,
527 }
528 try:
529 output = (
530 subprocess.check_output([env.subst(env["AR"]), "--version"], shell=(os.name == "nt"))
531 .strip()
532 .decode("utf-8")
533 )
534 except (subprocess.CalledProcessError, OSError):
535 print_warning("Couldn't check version of `ar`.")
536 return ret
537
538 match = re.search(r"GNU ar(?: \(GNU Binutils\)| version) (\d+)\.(\d+)(?:\.(\d+))?", output)
539 if match:
540 ret["major"] = int(match[1])
541 ret["minor"] = int(match[2])
542 if match[3]:
543 ret["patch"] = int(match[3])
544 else:
545 ret["patch"] = 0
546 return ret
547
548 match = re.search(r"LLVM version (\d+)\.(\d+)\.(\d+)", output)
549 if match:
550 ret["major"] = int(match[1])
551 ret["minor"] = int(match[2])
552 ret["patch"] = int(match[3])
553 ret["is_llvm"] = True
554 return ret
555
556 print_warning("Couldn't parse version of `ar`.")
557 return ret
558
559
560 def get_is_ar_thin_supported(env):
561 """Check whether `ar --thin` is supported. It is only supported since Binutils 2.38 or LLVM 14."""
562 ar_version = get_ar_version(env)
563 if ar_version["major"] == -1:
564 return False
565
566 if ar_version["is_llvm"]:
567 return ar_version["major"] >= 14
568
569 if ar_version["major"] == 2:
570 return ar_version["minor"] >= 38
571
572 print_warning("Unknown Binutils `ar` version.")
573 return False
574
575
576 WINPATHSEP_RE = re.compile(r"\\([^\"'\\]|$)")
577
578
579 def tempfile_arg_esc_func(arg):
580 from SCons.Subst import quote_spaces
581
582 arg = quote_spaces(arg)
583 # GCC requires double Windows slashes, let's use UNIX separator
584 return WINPATHSEP_RE.sub(r"/\1", arg)
585
586
587 def configure_mingw(env: "SConsEnvironment"):
588 if os.getenv("MSYSTEM") == "MSYS":
589 print_error(
590 "Running from base MSYS2 console/environment, use target specific environment instead (e.g., mingw32, mingw64, clang32, clang64)."
591 )
592 sys.exit(255)
593
594 if (env_arch := detect_build_env_arch()) and env["arch"] != env_arch:
595 print_error(
596 f"Arch argument ({env['arch']}) is not matching MSYS2 console/environment that is being used to run SCons ({env_arch}).\n"
597 "Run SCons again without arch argument (example: scons p=windows) and SCons will attempt to detect what MSYS2 compiler will be executed and inform you."
598 )
599 sys.exit(255)
600
601 if not try_cmd("gcc --version", env["mingw_prefix"], env["arch"]) and not try_cmd(
602 "clang --version", env["mingw_prefix"], env["arch"]
603 ):
604 print_error("No valid compilers found, use MINGW_PREFIX environment variable to set MinGW path.")
605 sys.exit(255)
606
607 # Workaround for MinGW. See:
608 # https://www.scons.org/wiki/LongCmdLinesOnWin32
609 env.use_windows_spawn_fix()
610
611 # HACK: For some reason, Windows-native shells have their MinGW tools
612 # frequently fail as a result of parsing path separators incorrectly.
613 # For some other reason, this issue is circumvented entirely if the
614 # `mingw_prefix` bin is prepended to PATH.
615 if os.sep == "\\":
616 env.PrependENVPath("PATH", os.path.join(env["mingw_prefix"], "bin"))
617
618 # In case the command line to AR is too long, use a response file.
619 env["ARCOM_ORIG"] = env["ARCOM"]
620 env["ARCOM"] = "${TEMPFILE('$ARCOM_ORIG', '$ARCOMSTR')}"
621 env["TEMPFILESUFFIX"] = ".rsp"
622 if os.name == "nt":
623 env["TEMPFILEARGESCFUNC"] = tempfile_arg_esc_func
624
625 ## Build type
626
627 if not env["use_llvm"] and not try_cmd("gcc --version", env["mingw_prefix"], env["arch"]):
628 env["use_llvm"] = True
629
630 if env["use_llvm"] and not try_cmd("clang --version", env["mingw_prefix"], env["arch"]):
631 env["use_llvm"] = False
632
633 if not env["use_llvm"] and try_cmd("gcc --version", env["mingw_prefix"], env["arch"], True):
634 print("Detected GCC to be a wrapper for Clang.")
635 env["use_llvm"] = True
636
637 if env["windows_subsystem"] == "gui":
638 env.Append(LINKFLAGS=["-Wl,--subsystem,windows"])
639 else:
640 env.Append(LINKFLAGS=["-Wl,--subsystem,console"])
641 env.AppendUnique(CPPDEFINES=["WINDOWS_SUBSYSTEM_CONSOLE"])
642
643 ## Compiler configuration
644
645 if env["arch"] == "x86_32":
646 if env["use_static_cpp"]:
647 env.Append(LINKFLAGS=["-static"])
648 env.Append(LINKFLAGS=["-static-libgcc"])
649 env.Append(LINKFLAGS=["-static-libstdc++"])
650 else:
651 if env["use_static_cpp"]:
652 env.Append(LINKFLAGS=["-static"])
653
654 # NOTE: Big objects have historically broken LTO on mingw-gcc specifically. While that no
655 # longer appears to be the case, this notice is retained for posterity.
656 env.AppendUnique(CCFLAGS=["-Wa,-mbig-obj"]) # Support big objects.
657
658 if env["arch"] == "x86_32":
659 env["x86_libtheora_opt_gcc"] = True
660
661 env.Append(CCFLAGS=["-ffp-contract=off"])
662
663 if env["use_llvm"]:
664 env["CC"] = get_detected(env, "clang")
665 env["CXX"] = get_detected(env, "clang++")
666 env["AR"] = get_detected(env, "ar")
667 env["RANLIB"] = get_detected(env, "ranlib")
668 env["AS"] = get_detected(env, "clang")
669 env.Append(ASFLAGS=["-c"])
670 env.extra_suffix = ".llvm" + env.extra_suffix
671 else:
672 env["CC"] = get_detected(env, "gcc")
673 env["CXX"] = get_detected(env, "g++")
674 env["AR"] = get_detected(env, "gcc-ar" if os.name != "nt" else "ar")
675 env["RANLIB"] = get_detected(env, "gcc-ranlib")
676 env["AS"] = get_detected(env, "gcc")
677 env.Append(ASFLAGS=["-c"])
678
679 env["RC"] = get_detected(env, "windres")
680 ARCH_TARGETS = {
681 "x86_32": "pe-i386",
682 "x86_64": "pe-x86-64",
683 "arm32": "armv7-w64-mingw32",
684 "arm64": "aarch64-w64-mingw32",
685 }
686 env.AppendUnique(RCFLAGS=f"--target={ARCH_TARGETS[env['arch']]}")
687
688 env["OBJCOPY"] = get_detected(env, "objcopy")
689 env["STRIP"] = get_detected(env, "strip")
690
691 ## LTO
692
693 if env["lto"] == "auto": # Enable LTO for production with MinGW.
694 env["lto"] = "thin" if env["use_llvm"] else "full"
695
696 if env["lto"] != "none":
697 if env["lto"] == "thin":
698 if not env["use_llvm"]:
699 print("ThinLTO is only compatible with LLVM, use `use_llvm=yes` or `lto=full`.")
700 sys.exit(255)
701 env.Append(CCFLAGS=["-flto=thin"])
702 env.Append(LINKFLAGS=["-flto=thin"])
703 elif not env["use_llvm"] and env.GetOption("num_jobs") > 1:
704 env.Append(CCFLAGS=["-flto"])
705 env.Append(LINKFLAGS=["-flto=" + str(env.GetOption("num_jobs"))])
706 else:
707 env.Append(CCFLAGS=["-flto"])
708 env.Append(LINKFLAGS=["-flto"])
709 if not env["use_llvm"]:
710 # For mingw-gcc LTO, disable linker plugin and enable whole program to work around GH-102867.
711 env.Append(CCFLAGS=["-fno-use-linker-plugin", "-fwhole-program"])
712 env.Append(LINKFLAGS=["-fno-use-linker-plugin", "-fwhole-program"])
713
714 if env["use_asan"]:
715 env.Append(LINKFLAGS=["-Wl,--stack," + str(STACK_SIZE_SANITIZERS)])
716 else:
717 env.Append(LINKFLAGS=["-Wl,--stack," + str(STACK_SIZE)])
718
719 ## Compile flags
720
721 if not env["use_llvm"]:
722 env.Append(CCFLAGS=["-mwindows"])
723
724 if env["use_asan"] or env["use_ubsan"]:
725 if not env["use_llvm"]:
726 print("GCC does not support sanitizers on Windows.")
727 sys.exit(255)
728 if env["arch"] not in ["x86_32", "x86_64"]:
729 print("Sanitizers are only supported for x86_32 and x86_64.")
730 sys.exit(255)
731
732 env.extra_suffix += ".san"
733 env.AppendUnique(CPPDEFINES=["SANITIZERS_ENABLED"])
734 san_flags = []
735 if env["use_asan"]:
736 san_flags.append("-fsanitize=address")
737 if env["use_ubsan"]:
738 san_flags.append("-fsanitize=undefined")
739 # Disable the vptr check since it gets triggered on any COM interface calls.
740 san_flags.append("-fno-sanitize=vptr")
741 env.Append(CFLAGS=san_flags)
742 env.Append(CCFLAGS=san_flags)
743 env.Append(LINKFLAGS=san_flags)
744
745 if get_is_ar_thin_supported(env):
746 env.Append(ARFLAGS=["--thin"])
747
748 env.Append(CPPDEFINES=["WINDOWS_ENABLED", "WASAPI_ENABLED", "WINMIDI_ENABLED"])
749 env.Append(
750 CPPDEFINES=[
751 ("WINVER", "0x0A00"),
752 ("_WIN32_WINNT", "0x0A00"),
753 ]
754 )
755 env.Append(
756 LIBS=[
757 "mingw32",
758 "dsound",
759 "ole32",
760 "d3d9",
761 "winmm",
762 "gdi32",
763 "iphlpapi",
764 "shell32",
765 "shlwapi",
766 "shcore",
767 "wsock32",
768 "ws2_32",
769 "kernel32",
770 "oleaut32",
771 "sapi",
772 "dinput8",
773 "dxguid",
774 "ksuser",
775 "imm32",
776 "bcrypt",
777 "crypt32",
778 "avrt",
779 "uuid",
780 "dwmapi",
781 "dwrite",
782 "wbemuuid",
783 "ntdll",
784 "hid",
785 ]
786 )
787
788 if env["accesskit"]:
789 if env["accesskit_sdk_path"] != "":
790 env.Prepend(CPPPATH=[env["accesskit_sdk_path"] + "/include"])
791 if env["use_llvm"]:
792 if env["arch"] == "arm64":
793 env.Append(LIBPATH=[env["accesskit_sdk_path"] + "/lib/windows/arm64/mingw-llvm/static/"])
794 elif env["arch"] == "x86_64":
795 env.Append(LIBPATH=[env["accesskit_sdk_path"] + "/lib/windows/x86_64/mingw-llvm/static/"])
796 elif env["arch"] == "x86_32":
797 env.Append(LIBPATH=[env["accesskit_sdk_path"] + "/lib/windows/x86/mingw-llvm/static/"])
798 else:
799 if env["arch"] == "x86_64":
800 env.Append(LIBPATH=[env["accesskit_sdk_path"] + "/lib/windows/x86_64/mingw/static/"])
801 elif env["arch"] == "x86_32":
802 env.Append(LIBPATH=[env["accesskit_sdk_path"] + "/lib/windows/x86/mingw/static/"])
803 env.Append(LIBPATH=["#bin/obj/platform/windows"])
804 env.Append(
805 LIBS=[
806 "accesskit",
807 "uiautomationcore." + env["arch"],
808 "runtimeobject",
809 "propsys",
810 "oleaut32",
811 "user32",
812 "userenv",
813 "ntdll",
814 ]
815 )
816 else:
817 env.Append(CPPDEFINES=["ACCESSKIT_DYNAMIC"])
818 env.Append(LIBPATH=["#platform/windows"])
819 env.Append(CPPDEFINES=["ACCESSKIT_ENABLED"])
820
821 if env.debug_features:
822 env.Append(LIBS=["psapi", "dbghelp"])
823
824 if env["vulkan"]:
825 env.Append(CPPDEFINES=["VULKAN_ENABLED", "RD_ENABLED"])
826 if not env["use_volk"]:
827 env.Append(LIBS=["vulkan"])
828
829 if env["sdl"]:
830 env.Append(CPPDEFINES=["SDL_ENABLED"])
831
832 if env["d3d12"]:
833 if env["use_llvm"]:
834 check_d3d12_installed(env, env["arch"] + "-llvm")
835 else:
836 check_d3d12_installed(env, env["arch"] + "-gcc")
837
838 env.AppendUnique(CPPDEFINES=["D3D12_ENABLED", "RD_ENABLED"])
839 env.Append(LIBS=["dxgi", "dxguid"])
840
841 # PIX
842 if env["arch"] not in ["x86_64", "arm64"] or env["pix_path"] == "" or not os.path.exists(env["pix_path"]):
843 env["use_pix"] = False
844
845 if env["use_pix"]:
846 arch_subdir = "arm64" if env["arch"] == "arm64" else "x64"
847
848 env.Append(LIBPATH=[env["pix_path"] + "/bin/" + arch_subdir])
849 env.Append(LIBS=["WinPixEventRuntime"])
850
851 if env["use_llvm"] and os.path.exists(env["mesa_libs"] + "-" + env["arch"] + "-llvm"):
852 env.Append(LIBPATH=[env["mesa_libs"] + "-" + env["arch"] + "-llvm/bin"])
853 elif not env["use_llvm"] and os.path.exists(env["mesa_libs"] + "-" + env["arch"] + "-gcc"):
854 env.Append(LIBPATH=[env["mesa_libs"] + "-" + env["arch"] + "-gcc/bin"])
855 else:
856 env.Append(LIBPATH=[env["mesa_libs"] + "/bin"])
857 env.Append(LIBS=["libNIR.windows." + env["arch"]])
858 env.Append(LIBS=["version"]) # Mesa dependency.
859
860 if env["opengl3"]:
861 env.Append(CPPDEFINES=["GLES3_ENABLED"])
862 if env["angle_libs"] != "":
863 env.AppendUnique(CPPDEFINES=["EGL_STATIC"])
864 env.Append(LIBPATH=[env["angle_libs"]])
865 env.Append(
866 LIBS=[
867 "EGL.windows." + env["arch"],
868 "GLES.windows." + env["arch"],
869 "ANGLE.windows." + env["arch"],
870 ]
871 )
872 env.Append(LIBS=["dxgi", "d3d9", "d3d11"])
873 env.Prepend(CPPPATH=["#thirdparty/angle/include"])
874
875 env.Append(CPPDEFINES=["MINGW_ENABLED", ("MINGW_HAS_SECURE_API", 1)])
876
877 # dlltool
878 env["DEF"] = get_detected(env, "dlltool")
879 env["DEFCOM"] = "$DEF $DEFFLAGS -d $SOURCE -l $TARGET"
880 env["DEFCOMSTR"] = "$CXXCOMSTR"
881 env["DEFPREFIX"] = "$LIBPREFIX"
882 env["DEFSUFFIX"] = ".${__env__['arch']}$LIBSUFFIX"
883 env["DEFSRCSUFFIX"] = ".${__env__['arch']}.def"
884 DEF_ALIASES = {
885 "x86_32": "i386",
886 "x86_64": "i386:x86-64",
887 "arm32": "arm",
888 "arm64": "arm64",
889 }
890 env.Append(DEFFLAGS=["-m", DEF_ALIASES[env["arch"]]])
891 if env["arch"] == "x86_32":
892 env.Append(DEFFLAGS=["-k"])
893 else:
894 env.Append(DEFFLAGS=["--no-leading-underscore"])
895
896 env.Append(
897 BUILDERS={
898 "DEFLIB": env.Builder(
899 action=env.Run("$DEFCOM", "$DEFCOMSTR"),
900 prefix="$DEFPREFIX",
901 suffix="$DEFSUFFIX",
902 src_suffix="$DEFSRCSUFFIX",
903 emitter=methods.redirect_emitter,
904 )
905 }
906 )
907
908
909 def configure(env: "SConsEnvironment"):
910 # Validate arch.
911 supported_arches = ["x86_32", "x86_64", "arm32", "arm64"]
912 validate_arch(env["arch"], get_name(), supported_arches)
913
914 # At this point the env has been set up with basic tools/compilers.
915 env.Prepend(CPPPATH=["#platform/windows"])
916
917 env.msvc = "mingw" not in env["TOOLS"]
918 if env.msvc:
919 configure_msvc(env)
920 else:
921 configure_mingw(env)
922
923
924 def check_d3d12_installed(env, suffix):
925 if not os.path.exists(env["mesa_libs"]) and not os.path.exists(env["mesa_libs"] + "-" + suffix):
926 print_error(
927 "The Direct3D 12 rendering driver requires dependencies to be installed.\n"
928 "You can install them by running `python misc\\scripts\\install_d3d12_sdk_windows.py`.\n"
929 "See the documentation for more information:\n"
930 "\thttps://docs.godotengine.org/en/latest/engine_details/development/compiling/compiling_for_windows.html\n"
931 "Alternatively, disable this driver by compiling with `d3d12=no` explicitly."
932 )
933 sys.exit(255)