detect.py 33 KB

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