detect.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. import methods
  2. import os
  3. # To match other platforms
  4. STACK_SIZE = 8388608
  5. def is_active():
  6. return True
  7. def get_name():
  8. return "Windows"
  9. def can_build():
  10. if os.name == "nt":
  11. # Building natively on Windows
  12. # If VCINSTALLDIR is set in the OS environ, use traditional Godot logic to set up MSVC
  13. if os.getenv("VCINSTALLDIR"): # MSVC, manual setup
  14. return True
  15. # Otherwise, let SCons find MSVC if installed, or else Mingw.
  16. # Since we're just returning True here, if there's no compiler
  17. # installed, we'll get errors when it tries to build with the
  18. # null compiler.
  19. return True
  20. if os.name == "posix":
  21. # Cross-compiling with MinGW-w64 (old MinGW32 is not supported)
  22. mingw32 = "i686-w64-mingw32-"
  23. mingw64 = "x86_64-w64-mingw32-"
  24. if os.getenv("MINGW32_PREFIX"):
  25. mingw32 = os.getenv("MINGW32_PREFIX")
  26. if os.getenv("MINGW64_PREFIX"):
  27. mingw64 = os.getenv("MINGW64_PREFIX")
  28. test = "gcc --version > /dev/null 2>&1"
  29. if os.system(mingw64 + test) == 0 or os.system(mingw32 + test) == 0:
  30. return True
  31. return False
  32. def get_opts():
  33. from SCons.Variables import BoolVariable, EnumVariable
  34. mingw32 = ""
  35. mingw64 = ""
  36. if os.name == "posix":
  37. mingw32 = "i686-w64-mingw32-"
  38. mingw64 = "x86_64-w64-mingw32-"
  39. if os.getenv("MINGW32_PREFIX"):
  40. mingw32 = os.getenv("MINGW32_PREFIX")
  41. if os.getenv("MINGW64_PREFIX"):
  42. mingw64 = os.getenv("MINGW64_PREFIX")
  43. return [
  44. ("mingw_prefix_32", "MinGW prefix (Win32)", mingw32),
  45. ("mingw_prefix_64", "MinGW prefix (Win64)", mingw64),
  46. # Targeted Windows version: 7 (and later), minimum supported version
  47. # XP support dropped after EOL due to missing API for IPv6 and other issues
  48. # Vista support dropped after EOL due to GH-10243
  49. ("target_win_version", "Targeted Windows version, >= 0x0601 (Windows 7)", "0x0601"),
  50. BoolVariable("debug_symbols", "Add debugging symbols to release/release_debug builds", True),
  51. BoolVariable("separate_debug_symbols", "Create a separate file containing debugging symbols", False),
  52. ("msvc_version", "MSVC version to use. Ignored if VCINSTALLDIR is set in shell env.", None),
  53. BoolVariable("use_mingw", "Use the Mingw compiler, even if MSVC is installed.", False),
  54. BoolVariable("use_llvm", "Use the LLVM compiler", False),
  55. BoolVariable("use_thinlto", "Use ThinLTO", False),
  56. BoolVariable("use_static_cpp", "Link MinGW/MSVC C++ runtime libraries statically", True),
  57. BoolVariable("use_asan", "Use address sanitizer (ASAN)", False),
  58. ]
  59. def get_flags():
  60. return []
  61. def build_res_file(target, source, env):
  62. if env["bits"] == "32":
  63. cmdbase = env["mingw_prefix_32"]
  64. else:
  65. cmdbase = env["mingw_prefix_64"]
  66. cmdbase = cmdbase + "windres --include-dir . "
  67. import subprocess
  68. for x in range(len(source)):
  69. cmd = cmdbase + "-i " + str(source[x]) + " -o " + str(target[x])
  70. try:
  71. out = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE).communicate()
  72. if len(out[1]):
  73. return 1
  74. except Exception:
  75. return 1
  76. return 0
  77. def setup_msvc_manual(env):
  78. """Set up env to use MSVC manually, using VCINSTALLDIR"""
  79. if env["bits"] != "default":
  80. print(
  81. """
  82. Bits argument is not supported for MSVC compilation. Architecture depends on the Native/Cross Compile Tools Prompt/Developer Console
  83. (or Visual Studio settings) that is being used to run SCons. As a consequence, bits argument is disabled. Run scons again without bits
  84. argument (example: scons p=windows) and SCons will attempt to detect what MSVC compiler will be executed and inform you.
  85. """
  86. )
  87. raise SCons.Errors.UserError("Bits argument should not be used when using VCINSTALLDIR")
  88. # Force bits arg
  89. # (Actually msys2 mingw can support 64-bit, we could detect that)
  90. env["bits"] = "32"
  91. env["x86_libtheora_opt_vc"] = True
  92. # find compiler manually
  93. compiler_version_str = methods.detect_visual_c_compiler_version(env["ENV"])
  94. print("Found MSVC compiler: " + compiler_version_str)
  95. # If building for 64bit architecture, disable assembly optimisations for 32 bit builds (theora as of writing)... vc compiler for 64bit can not compile _asm
  96. if compiler_version_str == "amd64" or compiler_version_str == "x86_amd64":
  97. env["bits"] = "64"
  98. env["x86_libtheora_opt_vc"] = False
  99. print("Compiled program architecture will be a 64 bit executable (forcing bits=64).")
  100. elif compiler_version_str == "x86" or compiler_version_str == "amd64_x86":
  101. print("Compiled program architecture will be a 32 bit executable. (forcing bits=32).")
  102. else:
  103. print(
  104. "Failed to manually detect MSVC compiler architecture version... Defaulting to 32bit executable settings (forcing bits=32). Compilation attempt will continue, but SCons can not detect for what architecture this build is compiled for. You should check your settings/compilation setup, or avoid setting VCINSTALLDIR."
  105. )
  106. def setup_msvc_auto(env):
  107. """Set up MSVC using SCons's auto-detection logic"""
  108. # If MSVC_VERSION is set by SCons, we know MSVC is installed.
  109. # But we may want a different version or target arch.
  110. # The env may have already been set up with default MSVC tools, so
  111. # reset a few things so we can set it up with the tools we want.
  112. # (Ideally we'd decide on the tool config before configuring any
  113. # environment, and just set the env up once, but this function runs
  114. # on an existing env so this is the simplest way.)
  115. env["MSVC_SETUP_RUN"] = False # Need to set this to re-run the tool
  116. env["MSVS_VERSION"] = None
  117. env["MSVC_VERSION"] = None
  118. env["TARGET_ARCH"] = None
  119. if env["bits"] != "default":
  120. env["TARGET_ARCH"] = {"32": "x86", "64": "x86_64"}[env["bits"]]
  121. if env.has_key("msvc_version"):
  122. env["MSVC_VERSION"] = env["msvc_version"]
  123. env.Tool("msvc")
  124. env.Tool("mssdk") # we want the MS SDK
  125. # Note: actual compiler version can be found in env['MSVC_VERSION'], e.g. "14.1" for VS2015
  126. # Get actual target arch into bits (it may be "default" at this point):
  127. if env["TARGET_ARCH"] in ("amd64", "x86_64"):
  128. env["bits"] = "64"
  129. else:
  130. env["bits"] = "32"
  131. print("Found MSVC version %s, arch %s, bits=%s" % (env["MSVC_VERSION"], env["TARGET_ARCH"], env["bits"]))
  132. if env["TARGET_ARCH"] in ("amd64", "x86_64"):
  133. env["x86_libtheora_opt_vc"] = False
  134. def setup_mingw(env):
  135. """Set up env for use with mingw"""
  136. # Nothing to do here
  137. print("Using MinGW")
  138. pass
  139. def configure_msvc(env, manual_msvc_config):
  140. """Configure env to work with MSVC"""
  141. # Build type
  142. if env["target"] == "release":
  143. if env["optimize"] == "speed": # optimize for speed (default)
  144. env.Append(CCFLAGS=["/O2"])
  145. env.Append(LINKFLAGS=["/OPT:REF"])
  146. elif env["optimize"] == "size": # optimize for size
  147. env.Append(CCFLAGS=["/O1"])
  148. env.Append(LINKFLAGS=["/OPT:REF"])
  149. env.Append(LINKFLAGS=["/SUBSYSTEM:WINDOWS"])
  150. env.Append(LINKFLAGS=["/ENTRY:mainCRTStartup"])
  151. elif env["target"] == "release_debug":
  152. if env["optimize"] == "speed": # optimize for speed (default)
  153. env.Append(CCFLAGS=["/O2"])
  154. env.Append(LINKFLAGS=["/OPT:REF"])
  155. elif env["optimize"] == "size": # optimize for size
  156. env.Append(CCFLAGS=["/O1"])
  157. env.Append(LINKFLAGS=["/OPT:REF"])
  158. env.AppendUnique(CPPDEFINES=["DEBUG_ENABLED"])
  159. env.Append(LINKFLAGS=["/SUBSYSTEM:CONSOLE"])
  160. elif env["target"] == "debug":
  161. env.AppendUnique(CCFLAGS=["/Zi", "/FS", "/Od", "/EHsc"])
  162. env.AppendUnique(CPPDEFINES=["DEBUG_ENABLED"])
  163. env.Append(LINKFLAGS=["/SUBSYSTEM:CONSOLE"])
  164. env.Append(LINKFLAGS=["/DEBUG"])
  165. if env["debug_symbols"]:
  166. env.AppendUnique(CCFLAGS=["/Zi", "/FS"])
  167. env.AppendUnique(LINKFLAGS=["/DEBUG"])
  168. ## Compile/link flags
  169. if env["use_static_cpp"]:
  170. env.AppendUnique(CCFLAGS=["/MT"])
  171. else:
  172. env.AppendUnique(CCFLAGS=["/MD"])
  173. env.AppendUnique(CCFLAGS=["/Gd", "/GR", "/nologo"])
  174. # Force to use Unicode encoding
  175. env.AppendUnique(CCFLAGS=["/utf-8"])
  176. env.AppendUnique(CXXFLAGS=["/TP"]) # assume all sources are C++
  177. if manual_msvc_config: # should be automatic if SCons found it
  178. if os.getenv("WindowsSdkDir") is not None:
  179. env.Prepend(CPPPATH=[os.getenv("WindowsSdkDir") + "/Include"])
  180. else:
  181. print("Missing environment variable: WindowsSdkDir")
  182. env.AppendUnique(
  183. CPPDEFINES=[
  184. "WINDOWS_ENABLED",
  185. "OPENGL_ENABLED",
  186. "WASAPI_ENABLED",
  187. "WINMIDI_ENABLED",
  188. "TYPED_METHOD_BIND",
  189. "WIN32",
  190. "MSVC",
  191. "WINVER=%s" % env["target_win_version"],
  192. "_WIN32_WINNT=%s" % env["target_win_version"],
  193. ]
  194. )
  195. env.AppendUnique(CPPDEFINES=["NOMINMAX"]) # disable bogus min/max WinDef.h macros
  196. if env["bits"] == "64":
  197. env.AppendUnique(CPPDEFINES=["_WIN64"])
  198. ## Libs
  199. LIBS = [
  200. "winmm",
  201. "opengl32",
  202. "dsound",
  203. "kernel32",
  204. "ole32",
  205. "oleaut32",
  206. "user32",
  207. "gdi32",
  208. "IPHLPAPI",
  209. "Shlwapi",
  210. "wsock32",
  211. "Ws2_32",
  212. "shell32",
  213. "advapi32",
  214. "dinput8",
  215. "dxguid",
  216. "imm32",
  217. "bcrypt",
  218. "Avrt",
  219. "dwmapi",
  220. ]
  221. env.Append(LINKFLAGS=[p + env["LIBSUFFIX"] for p in LIBS])
  222. if manual_msvc_config:
  223. if os.getenv("WindowsSdkDir") is not None:
  224. env.Append(LIBPATH=[os.getenv("WindowsSdkDir") + "/Lib"])
  225. else:
  226. print("Missing environment variable: WindowsSdkDir")
  227. ## LTO
  228. if env["use_lto"]:
  229. env.AppendUnique(CCFLAGS=["/GL"])
  230. env.AppendUnique(ARFLAGS=["/LTCG"])
  231. if env["progress"]:
  232. env.AppendUnique(LINKFLAGS=["/LTCG:STATUS"])
  233. else:
  234. env.AppendUnique(LINKFLAGS=["/LTCG"])
  235. if manual_msvc_config:
  236. env.Prepend(CPPPATH=[p for p in os.getenv("INCLUDE").split(";")])
  237. env.Append(LIBPATH=[p for p in os.getenv("LIB").split(";")])
  238. # Sanitizers
  239. if env["use_asan"]:
  240. env.extra_suffix += ".s"
  241. env.Append(LINKFLAGS=["/INFERASANLIBS"])
  242. env.Append(CCFLAGS=["/fsanitize=address"])
  243. # Incremental linking fix
  244. env["BUILDERS"]["ProgramOriginal"] = env["BUILDERS"]["Program"]
  245. env["BUILDERS"]["Program"] = methods.precious_program
  246. env.AppendUnique(LINKFLAGS=["/STACK:" + str(STACK_SIZE)])
  247. def configure_mingw(env):
  248. # Workaround for MinGW. See:
  249. # http://www.scons.org/wiki/LongCmdLinesOnWin32
  250. env.use_windows_spawn_fix()
  251. ## Build type
  252. if env["target"] == "release":
  253. env.Append(CCFLAGS=["-msse2"])
  254. if env["optimize"] == "speed": # optimize for speed (default)
  255. if env["bits"] == "64":
  256. env.Append(CCFLAGS=["-O3"])
  257. else:
  258. env.Append(CCFLAGS=["-O2"])
  259. else: # optimize for size
  260. env.Prepend(CCFLAGS=["-Os"])
  261. env.Append(LINKFLAGS=["-Wl,--subsystem,windows"])
  262. if env["debug_symbols"]:
  263. env.Prepend(CCFLAGS=["-g2"])
  264. elif env["target"] == "release_debug":
  265. env.Append(CCFLAGS=["-O2"])
  266. env.Append(CPPDEFINES=["DEBUG_ENABLED"])
  267. if env["debug_symbols"]:
  268. env.Prepend(CCFLAGS=["-g2"])
  269. if env["optimize"] == "speed": # optimize for speed (default)
  270. env.Append(CCFLAGS=["-O2"])
  271. else: # optimize for size
  272. env.Prepend(CCFLAGS=["-Os"])
  273. elif env["target"] == "debug":
  274. env.Append(CCFLAGS=["-g3"])
  275. env.Append(CPPDEFINES=["DEBUG_ENABLED"])
  276. ## Compiler configuration
  277. if os.name == "nt":
  278. # Force splitting libmodules.a in multiple chunks to work around
  279. # issues reaching the linker command line size limit, which also
  280. # seem to induce huge slowdown for 'ar' (GH-30892).
  281. env["split_libmodules"] = True
  282. else:
  283. env["PROGSUFFIX"] = env["PROGSUFFIX"] + ".exe" # for linux cross-compilation
  284. if env["bits"] == "default":
  285. if os.name == "nt":
  286. env["bits"] = "64" if "PROGRAMFILES(X86)" in os.environ else "32"
  287. else: # default to 64-bit on Linux
  288. env["bits"] = "64"
  289. mingw_prefix = ""
  290. if env["bits"] == "32":
  291. if env["use_static_cpp"]:
  292. env.Append(LINKFLAGS=["-static"])
  293. env.Append(LINKFLAGS=["-static-libgcc"])
  294. env.Append(LINKFLAGS=["-static-libstdc++"])
  295. mingw_prefix = env["mingw_prefix_32"]
  296. else:
  297. if env["use_static_cpp"]:
  298. env.Append(LINKFLAGS=["-static"])
  299. mingw_prefix = env["mingw_prefix_64"]
  300. if env["use_llvm"]:
  301. env["CC"] = mingw_prefix + "clang"
  302. env["CXX"] = mingw_prefix + "clang++"
  303. env["AS"] = mingw_prefix + "as"
  304. env["AR"] = mingw_prefix + "ar"
  305. env["RANLIB"] = mingw_prefix + "ranlib"
  306. else:
  307. env["CC"] = mingw_prefix + "gcc"
  308. env["CXX"] = mingw_prefix + "g++"
  309. env["AS"] = mingw_prefix + "as"
  310. env["AR"] = mingw_prefix + "gcc-ar"
  311. env["RANLIB"] = mingw_prefix + "gcc-ranlib"
  312. env["x86_libtheora_opt_gcc"] = True
  313. if env["use_lto"]:
  314. if not env["use_llvm"] and env.GetOption("num_jobs") > 1:
  315. env.Append(CCFLAGS=["-flto"])
  316. env.Append(LINKFLAGS=["-flto=" + str(env.GetOption("num_jobs"))])
  317. else:
  318. if env["use_thinlto"]:
  319. env.Append(CCFLAGS=["-flto=thin"])
  320. env.Append(LINKFLAGS=["-flto=thin"])
  321. else:
  322. env.Append(CCFLAGS=["-flto"])
  323. env.Append(LINKFLAGS=["-flto"])
  324. env.Append(LINKFLAGS=["-Wl,--stack," + str(STACK_SIZE)])
  325. ## Compile flags
  326. env.Append(CCFLAGS=["-mwindows"])
  327. env.Append(LINKFLAGS=["-Wl,--nxcompat"]) # DEP protection. Not enabling ASLR for now, Mono crashes.
  328. env.Append(CPPDEFINES=["WINDOWS_ENABLED", "OPENGL_ENABLED", "WASAPI_ENABLED", "WINMIDI_ENABLED"])
  329. env.Append(CPPDEFINES=[("WINVER", env["target_win_version"]), ("_WIN32_WINNT", env["target_win_version"])])
  330. env.Append(
  331. LIBS=[
  332. "mingw32",
  333. "opengl32",
  334. "dsound",
  335. "ole32",
  336. "d3d9",
  337. "winmm",
  338. "gdi32",
  339. "iphlpapi",
  340. "shlwapi",
  341. "wsock32",
  342. "ws2_32",
  343. "kernel32",
  344. "oleaut32",
  345. "dinput8",
  346. "dxguid",
  347. "ksuser",
  348. "imm32",
  349. "bcrypt",
  350. "avrt",
  351. "uuid",
  352. "dwmapi",
  353. ]
  354. )
  355. env.Append(CPPDEFINES=["MINGW_ENABLED", ("MINGW_HAS_SECURE_API", 1)])
  356. # resrc
  357. env.Append(BUILDERS={"RES": env.Builder(action=build_res_file, suffix=".o", src_suffix=".rc")})
  358. def configure(env):
  359. # At this point the env has been set up with basic tools/compilers.
  360. env.Prepend(CPPPATH=["#platform/windows"])
  361. print("Configuring for Windows: target=%s, bits=%s" % (env["target"], env["bits"]))
  362. if os.name == "nt":
  363. env["ENV"] = os.environ # this makes build less repeatable, but simplifies some things
  364. env["ENV"]["TMP"] = os.environ["TMP"]
  365. # First figure out which compiler, version, and target arch we're using
  366. if os.getenv("VCINSTALLDIR") and not env["use_mingw"]:
  367. # Manual setup of MSVC
  368. setup_msvc_manual(env)
  369. env.msvc = True
  370. manual_msvc_config = True
  371. elif env.get("MSVC_VERSION", "") and not env["use_mingw"]:
  372. setup_msvc_auto(env)
  373. env.msvc = True
  374. manual_msvc_config = False
  375. else:
  376. setup_mingw(env)
  377. env.msvc = False
  378. # Now set compiler/linker flags
  379. if env.msvc:
  380. configure_msvc(env, manual_msvc_config)
  381. else: # MinGW
  382. configure_mingw(env)