detect.py 32 KB

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