detect.py 32 KB

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