detect.py 17 KB

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