detect.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import os
  2. import sys
  3. from emscripten_helpers import (
  4. run_closure_compiler,
  5. create_engine_file,
  6. add_js_libraries,
  7. add_js_pre,
  8. add_js_externs,
  9. create_template_zip,
  10. )
  11. from methods import get_compiler_version
  12. from SCons.Util import WhereIs
  13. def is_active():
  14. return True
  15. def get_name():
  16. return "JavaScript"
  17. def can_build():
  18. return WhereIs("emcc") is not None
  19. def get_opts():
  20. from SCons.Variables import BoolVariable
  21. return [
  22. ("initial_memory", "Initial WASM memory (in MiB)", 32),
  23. # Matches default values from before Emscripten 3.1.27. New defaults are too low for Godot.
  24. ("stack_size", "WASM stack size (in KiB)", 5120),
  25. ("default_pthread_stack_size", "WASM pthread default stack size (in KiB)", 2048),
  26. BoolVariable("use_assertions", "Use Emscripten runtime assertions", False),
  27. BoolVariable("use_ubsan", "Use Emscripten undefined behavior sanitizer (UBSAN)", False),
  28. BoolVariable("use_asan", "Use Emscripten address sanitizer (ASAN)", False),
  29. BoolVariable("use_lsan", "Use Emscripten leak sanitizer (LSAN)", False),
  30. BoolVariable("use_safe_heap", "Use Emscripten SAFE_HEAP sanitizer", False),
  31. # eval() can be a security concern, so it can be disabled.
  32. BoolVariable("javascript_eval", "Enable JavaScript eval interface", True),
  33. BoolVariable("threads_enabled", "Enable WebAssembly Threads support (limited browser support)", False),
  34. BoolVariable("gdnative_enabled", "Enable WebAssembly GDNative support (produces bigger binaries)", False),
  35. BoolVariable("use_closure_compiler", "Use closure compiler to minimize JavaScript code", False),
  36. ]
  37. def get_flags():
  38. return [
  39. ("tools", False),
  40. ("builtin_pcre2_with_jit", False),
  41. ]
  42. def configure(env):
  43. try:
  44. env["initial_memory"] = int(env["initial_memory"])
  45. except Exception:
  46. print("Initial memory must be a valid integer")
  47. sys.exit(255)
  48. ## Build type
  49. if env["target"].startswith("release"):
  50. # Use -Os to prioritize optimizing for reduced file size. This is
  51. # particularly valuable for the web platform because it directly
  52. # decreases download time.
  53. # -Os reduces file size by around 5 MiB over -O3. -Oz only saves about
  54. # 100 KiB over -Os, which does not justify the negative impact on
  55. # run-time performance.
  56. if env["optimize"] != "none":
  57. env.Append(CCFLAGS=["-Os"])
  58. env.Append(LINKFLAGS=["-Os"])
  59. if env["target"] == "release_debug":
  60. # Retain function names for backtraces at the cost of file size.
  61. env.Append(LINKFLAGS=["--profiling-funcs"])
  62. else: # "debug"
  63. env.Append(CCFLAGS=["-O1", "-g"])
  64. env.Append(LINKFLAGS=["-O1", "-g"])
  65. env["use_assertions"] = True
  66. if env["use_assertions"]:
  67. env.Append(LINKFLAGS=["-s", "ASSERTIONS=1"])
  68. if env["tools"]:
  69. if not env["threads_enabled"]:
  70. print('Note: Forcing "threads_enabled=yes" as it is required for the web editor.')
  71. env["threads_enabled"] = "yes"
  72. if env["initial_memory"] < 64:
  73. print('Note: Forcing "initial_memory=64" as it is required for the web editor.')
  74. env["initial_memory"] = 64
  75. else:
  76. # Disable rtti on non-tools (template) builds.
  77. # This helps keep the file size down.
  78. env.Append(CCFLAGS=["-fno-rtti"])
  79. # Don't use dynamic_cast, necessary with no-rtti.
  80. env.Append(CPPDEFINES=["NO_SAFE_CAST"])
  81. env.Append(LINKFLAGS=["-s", "INITIAL_MEMORY=%sMB" % env["initial_memory"]])
  82. ## Copy env variables.
  83. env["ENV"] = os.environ
  84. # LTO
  85. if env["lto"] == "auto": # Full LTO for production.
  86. env["lto"] = "full"
  87. if env["lto"] != "none":
  88. if env["lto"] == "thin":
  89. env.Append(CCFLAGS=["-flto=thin"])
  90. env.Append(LINKFLAGS=["-flto=thin"])
  91. else:
  92. env.Append(CCFLAGS=["-flto"])
  93. env.Append(LINKFLAGS=["-flto"])
  94. # Sanitizers
  95. if env["use_ubsan"]:
  96. env.Append(CCFLAGS=["-fsanitize=undefined"])
  97. env.Append(LINKFLAGS=["-fsanitize=undefined"])
  98. if env["use_asan"]:
  99. env.Append(CCFLAGS=["-fsanitize=address"])
  100. env.Append(LINKFLAGS=["-fsanitize=address"])
  101. if env["use_lsan"]:
  102. env.Append(CCFLAGS=["-fsanitize=leak"])
  103. env.Append(LINKFLAGS=["-fsanitize=leak"])
  104. if env["use_safe_heap"]:
  105. env.Append(LINKFLAGS=["-s", "SAFE_HEAP=1"])
  106. # Closure compiler
  107. if env["use_closure_compiler"]:
  108. # For emscripten support code.
  109. env.Append(LINKFLAGS=["--closure", "1"])
  110. # Register builder for our Engine files
  111. jscc = env.Builder(generator=run_closure_compiler, suffix=".cc.js", src_suffix=".js")
  112. env.Append(BUILDERS={"BuildJS": jscc})
  113. # Add helper method for adding libraries, externs, pre-js.
  114. env["JS_LIBS"] = []
  115. env["JS_PRE"] = []
  116. env["JS_EXTERNS"] = []
  117. env.AddMethod(add_js_libraries, "AddJSLibraries")
  118. env.AddMethod(add_js_pre, "AddJSPre")
  119. env.AddMethod(add_js_externs, "AddJSExterns")
  120. # Add method that joins/compiles our Engine files.
  121. env.AddMethod(create_engine_file, "CreateEngineFile")
  122. # Add method for creating the final zip file
  123. env.AddMethod(create_template_zip, "CreateTemplateZip")
  124. # Closure compiler extern and support for ecmascript specs (const, let, etc).
  125. env["ENV"]["EMCC_CLOSURE_ARGS"] = "--language_in ECMASCRIPT_2021"
  126. env["CC"] = "emcc"
  127. env["CXX"] = "em++"
  128. env["AR"] = "emar"
  129. env["RANLIB"] = "emranlib"
  130. # Use TempFileMunge since some AR invocations are too long for cmd.exe.
  131. # Use POSIX-style paths, required with TempFileMunge.
  132. env["ARCOM_POSIX"] = env["ARCOM"].replace("$TARGET", "$TARGET.posix").replace("$SOURCES", "$SOURCES.posix")
  133. env["ARCOM"] = "${TEMPFILE(ARCOM_POSIX)}"
  134. # All intermediate files are just object files.
  135. env["OBJPREFIX"] = ""
  136. env["OBJSUFFIX"] = ".o"
  137. env["PROGPREFIX"] = ""
  138. # Program() output consists of multiple files, so specify suffixes manually at builder.
  139. env["PROGSUFFIX"] = ""
  140. env["LIBPREFIX"] = "lib"
  141. env["LIBSUFFIX"] = ".a"
  142. env["LIBPREFIXES"] = ["$LIBPREFIX"]
  143. env["LIBSUFFIXES"] = ["$LIBSUFFIX"]
  144. # Get version info for checks below.
  145. cc_semver = tuple(get_compiler_version(env) or (3, 1, 39))
  146. env.Prepend(CPPPATH=["#platform/javascript"])
  147. env.Append(CPPDEFINES=["JAVASCRIPT_ENABLED", "UNIX_ENABLED"])
  148. if env["javascript_eval"]:
  149. env.Append(CPPDEFINES=["JAVASCRIPT_EVAL_ENABLED"])
  150. stack_size_opt = "STACK_SIZE" if cc_semver >= (3, 1, 25) else "TOTAL_STACK"
  151. env.Append(LINKFLAGS=["-s", "%s=%sKB" % (stack_size_opt, env["stack_size"])])
  152. # Thread support (via SharedArrayBuffer).
  153. if env["threads_enabled"]:
  154. stack_size_opt = "STACK_SIZE" if cc_semver >= (3, 1, 25) else "TOTAL_STACK"
  155. env.Append(LINKFLAGS=["-s", "%s=%sKB" % (stack_size_opt, env["stack_size"])])
  156. env.Append(CPPDEFINES=["PTHREAD_NO_RENAME"])
  157. env.Append(CCFLAGS=["-s", "USE_PTHREADS=1"])
  158. env.Append(LINKFLAGS=["-s", "USE_PTHREADS=1"])
  159. env.Append(LINKFLAGS=["-s", "DEFAULT_PTHREAD_STACK_SIZE=%sKB" % env["default_pthread_stack_size"]])
  160. env.Append(LINKFLAGS=["-s", "PTHREAD_POOL_SIZE=8"])
  161. env.Append(LINKFLAGS=["-s", "WASM_MEM_MAX=2048MB"])
  162. env.extra_suffix = ".threads" + env.extra_suffix
  163. else:
  164. env.Append(CPPDEFINES=["NO_THREADS"])
  165. if env["lto"] != "none":
  166. # Workaround https://github.com/emscripten-core/emscripten/issues/19781.
  167. if cc_semver >= (3, 1, 42) and cc_semver < (3, 1, 46):
  168. env.Append(LINKFLAGS=["-Wl,-u,scalbnf"])
  169. # Workaround https://github.com/emscripten-core/emscripten/issues/16836.
  170. if cc_semver >= (3, 1, 47):
  171. env.Append(LINKFLAGS=["-Wl,-u,_emscripten_run_callback_on_thread"])
  172. if env["gdnative_enabled"]:
  173. if cc_semver < (2, 0, 10):
  174. print("GDNative support requires emscripten >= 2.0.10, detected: %s.%s.%s" % cc_semver)
  175. sys.exit(255)
  176. if env["threads_enabled"] and cc_semver < (3, 1, 14):
  177. print("Threads and GDNative requires emscripten => 3.1.14, detected: %s.%s.%s" % cc_semver)
  178. sys.exit(255)
  179. env.Append(CCFLAGS=["-s", "RELOCATABLE=1"])
  180. env.Append(LINKFLAGS=["-s", "RELOCATABLE=1"])
  181. # Weak symbols are broken upstream: https://github.com/emscripten-core/emscripten/issues/12819
  182. env.Append(CPPDEFINES=["ZSTD_HAVE_WEAK_SYMBOLS=0"])
  183. env.extra_suffix = ".gdnative" + env.extra_suffix
  184. # WASM_BIGINT is needed since emscripten ≥ 3.1.41
  185. if cc_semver >= (3, 1, 41):
  186. env.Append(LINKFLAGS=["-s", "WASM_BIGINT"])
  187. # Reduce code size by generating less support code (e.g. skip NodeJS support).
  188. env.Append(LINKFLAGS=["-s", "ENVIRONMENT=web,worker"])
  189. # Wrap the JavaScript support code around a closure named Godot.
  190. env.Append(LINKFLAGS=["-s", "MODULARIZE=1", "-s", "EXPORT_NAME='Godot'"])
  191. # Allow increasing memory buffer size during runtime. This is efficient
  192. # when using WebAssembly (in comparison to asm.js) and works well for
  193. # us since we don't know requirements at compile-time.
  194. env.Append(LINKFLAGS=["-s", "ALLOW_MEMORY_GROWTH=1"])
  195. # This setting just makes WebGL 2 APIs available, it does NOT disable WebGL 1.
  196. env.Append(LINKFLAGS=["-s", "USE_WEBGL2=1"])
  197. # Breaking change since emscripten 3.1.51
  198. # https://github.com/emscripten-core/emscripten/blob/main/ChangeLog.md#3151---121323
  199. if cc_semver >= (3, 1, 51):
  200. # Enables the use of *glGetProcAddress()
  201. env.Append(LINKFLAGS=["-s", "GL_ENABLE_GET_PROC_ADDRESS=1"])
  202. # Do not call main immediately when the support code is ready.
  203. env.Append(LINKFLAGS=["-s", "INVOKE_RUN=0"])
  204. # Allow use to take control of swapping WebGL buffers.
  205. env.Append(LINKFLAGS=["-s", "OFFSCREEN_FRAMEBUFFER=1"])
  206. # callMain for manual start, cwrap for the mono version.
  207. env.Append(LINKFLAGS=["-s", "EXPORTED_RUNTIME_METHODS=['callMain','cwrap']"])
  208. # Add code that allow exiting runtime.
  209. env.Append(LINKFLAGS=["-s", "EXIT_RUNTIME=1"])