2
0

detect.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. import os
  2. import sys
  3. import platform
  4. from distutils.version import LooseVersion
  5. def is_active():
  6. return True
  7. def get_name():
  8. return "Android"
  9. def can_build():
  10. return ("ANDROID_NDK_ROOT" in os.environ) or ("ANDROID_SDK_ROOT" in os.environ) or ("ANDROID_HOME" in os.environ)
  11. def get_platform(platform):
  12. return int(platform.split("-")[1])
  13. def get_opts():
  14. from SCons.Variables import BoolVariable, EnumVariable
  15. return [
  16. ("ANDROID_NDK_ROOT", "Path to the Android NDK", get_android_ndk_root()),
  17. ("ANDROID_SDK_ROOT", "Path to the Android SDK", get_android_sdk_root()),
  18. ("ndk_platform", 'Target platform (android-<api>, e.g. "android-18")', "android-18"),
  19. EnumVariable("android_arch", "Target architecture", "armv7", ("armv7", "arm64v8", "x86", "x86_64")),
  20. BoolVariable("android_neon", "Enable NEON support (armv7 only)", True),
  21. ]
  22. # Return the ANDROID_SDK_ROOT environment variable.
  23. # While ANDROID_HOME has been deprecated, it's used as a fallback for backward
  24. # compatibility purposes.
  25. def get_android_sdk_root():
  26. if "ANDROID_SDK_ROOT" in os.environ:
  27. return os.environ.get("ANDROID_SDK_ROOT", 0)
  28. else:
  29. return os.environ.get("ANDROID_HOME", 0)
  30. # Return the ANDROID_NDK_ROOT environment variable.
  31. # If the env variable is already defined, we use it with the expectation that
  32. # the user knows what they're doing (e.g: testing a new NDK version).
  33. # Otherwise, we generate one for this build using the ANDROID_SDK_ROOT env
  34. # variable and the project ndk version.
  35. def get_android_ndk_root():
  36. if "ANDROID_NDK_ROOT" in os.environ:
  37. return os.environ.get("ANDROID_NDK_ROOT", 0)
  38. else:
  39. return get_android_sdk_root() + "/ndk/" + get_project_ndk_version()
  40. def get_flags():
  41. return [
  42. ("tools", False),
  43. ]
  44. def create(env):
  45. tools = env["TOOLS"]
  46. if "mingw" in tools:
  47. tools.remove("mingw")
  48. if "applelink" in tools:
  49. tools.remove("applelink")
  50. env.Tool("gcc")
  51. return env.Clone(tools=tools)
  52. # Check if ANDROID_NDK_ROOT is valid.
  53. # If not, install the ndk using ANDROID_SDK_ROOT and sdkmanager.
  54. def install_ndk_if_needed(env):
  55. print("Checking for Android NDK...")
  56. env_ndk_version = get_env_ndk_version(env["ANDROID_NDK_ROOT"])
  57. if env_ndk_version is None:
  58. # Reinstall the ndk and update ANDROID_NDK_ROOT.
  59. print("Installing Android NDK...")
  60. if env["ANDROID_SDK_ROOT"] is None:
  61. raise Exception("Invalid ANDROID_SDK_ROOT environment variable.")
  62. import subprocess
  63. extension = ".bat" if os.name == "nt" else ""
  64. sdkmanager_path = env["ANDROID_SDK_ROOT"] + "/cmdline-tools/latest/bin/sdkmanager" + extension
  65. ndk_download_args = "ndk;" + get_project_ndk_version()
  66. subprocess.check_call([sdkmanager_path, ndk_download_args])
  67. env["ANDROID_NDK_ROOT"] = env["ANDROID_SDK_ROOT"] + "/ndk/" + get_project_ndk_version()
  68. print("ANDROID_NDK_ROOT: " + env["ANDROID_NDK_ROOT"])
  69. def configure(env):
  70. install_ndk_if_needed(env)
  71. # Workaround for MinGW. See:
  72. # http://www.scons.org/wiki/LongCmdLinesOnWin32
  73. if os.name == "nt":
  74. import subprocess
  75. def mySubProcess(cmdline, env):
  76. # print("SPAWNED : " + cmdline)
  77. startupinfo = subprocess.STARTUPINFO()
  78. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  79. proc = subprocess.Popen(
  80. cmdline,
  81. stdin=subprocess.PIPE,
  82. stdout=subprocess.PIPE,
  83. stderr=subprocess.PIPE,
  84. startupinfo=startupinfo,
  85. shell=False,
  86. env=env,
  87. )
  88. data, err = proc.communicate()
  89. rv = proc.wait()
  90. if rv:
  91. print("=====")
  92. print(err)
  93. print("=====")
  94. return rv
  95. def mySpawn(sh, escape, cmd, args, env):
  96. newargs = " ".join(args[1:])
  97. cmdline = cmd + " " + newargs
  98. rv = 0
  99. if len(cmdline) > 32000 and cmd.endswith("ar"):
  100. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  101. for i in range(3, len(args)):
  102. rv = mySubProcess(cmdline + args[i], env)
  103. if rv:
  104. break
  105. else:
  106. rv = mySubProcess(cmdline, env)
  107. return rv
  108. env["SPAWN"] = mySpawn
  109. # Architecture
  110. if env["android_arch"] not in ["armv7", "arm64v8", "x86", "x86_64"]:
  111. env["android_arch"] = "armv7"
  112. neon_text = ""
  113. if env["android_arch"] == "armv7" and env["android_neon"]:
  114. neon_text = " (with NEON)"
  115. print("Building for Android (" + env["android_arch"] + ")" + neon_text)
  116. can_vectorize = True
  117. if env["android_arch"] == "x86":
  118. env["ARCH"] = "arch-x86"
  119. env.extra_suffix = ".x86" + env.extra_suffix
  120. target_subpath = "x86-4.9"
  121. abi_subpath = "i686-linux-android"
  122. arch_subpath = "x86"
  123. env["x86_libtheora_opt_gcc"] = True
  124. if env["android_arch"] == "x86_64":
  125. if get_platform(env["ndk_platform"]) < 21:
  126. print(
  127. "WARNING: android_arch=x86_64 is not supported by ndk_platform lower than android-21; setting ndk_platform=android-21"
  128. )
  129. env["ndk_platform"] = "android-21"
  130. env["ARCH"] = "arch-x86_64"
  131. env.extra_suffix = ".x86_64" + env.extra_suffix
  132. target_subpath = "x86_64-4.9"
  133. abi_subpath = "x86_64-linux-android"
  134. arch_subpath = "x86_64"
  135. env["x86_libtheora_opt_gcc"] = True
  136. elif env["android_arch"] == "armv7":
  137. env["ARCH"] = "arch-arm"
  138. target_subpath = "arm-linux-androideabi-4.9"
  139. abi_subpath = "arm-linux-androideabi"
  140. arch_subpath = "armeabi-v7a"
  141. if env["android_neon"]:
  142. env.extra_suffix = ".armv7.neon" + env.extra_suffix
  143. else:
  144. env.extra_suffix = ".armv7" + env.extra_suffix
  145. elif env["android_arch"] == "arm64v8":
  146. if get_platform(env["ndk_platform"]) < 21:
  147. print(
  148. "WARNING: android_arch=arm64v8 is not supported by ndk_platform lower than android-21; setting ndk_platform=android-21"
  149. )
  150. env["ndk_platform"] = "android-21"
  151. env["ARCH"] = "arch-arm64"
  152. target_subpath = "aarch64-linux-android-4.9"
  153. abi_subpath = "aarch64-linux-android"
  154. arch_subpath = "arm64-v8a"
  155. env.extra_suffix = ".armv8" + env.extra_suffix
  156. # Build type
  157. if env["target"].startswith("release"):
  158. if env["optimize"] == "speed": # optimize for speed (default)
  159. env.Append(LINKFLAGS=["-O2"])
  160. env.Append(CCFLAGS=["-O2", "-fomit-frame-pointer"])
  161. env.Append(CPPDEFINES=["NDEBUG"])
  162. else: # optimize for size
  163. env.Append(CCFLAGS=["-Os"])
  164. env.Append(CPPDEFINES=["NDEBUG"])
  165. env.Append(LINKFLAGS=["-Os"])
  166. if can_vectorize:
  167. env.Append(CCFLAGS=["-ftree-vectorize"])
  168. if env["target"] == "release_debug":
  169. env.Append(CPPDEFINES=["DEBUG_ENABLED"])
  170. elif env["target"] == "debug":
  171. env.Append(LINKFLAGS=["-O0"])
  172. env.Append(CCFLAGS=["-O0", "-g", "-fno-limit-debug-info"])
  173. env.Append(CPPDEFINES=["_DEBUG", "DEBUG_ENABLED"])
  174. env.Append(CPPFLAGS=["-UNDEBUG"])
  175. # Compiler configuration
  176. env["SHLIBSUFFIX"] = ".so"
  177. if env["PLATFORM"] == "win32":
  178. env.Tool("gcc")
  179. env.use_windows_spawn_fix()
  180. if sys.platform.startswith("linux"):
  181. host_subpath = "linux-x86_64"
  182. elif sys.platform.startswith("darwin"):
  183. host_subpath = "darwin-x86_64"
  184. elif sys.platform.startswith("win"):
  185. if platform.machine().endswith("64"):
  186. host_subpath = "windows-x86_64"
  187. else:
  188. host_subpath = "windows"
  189. compiler_path = env["ANDROID_NDK_ROOT"] + "/toolchains/llvm/prebuilt/" + host_subpath + "/bin"
  190. gcc_toolchain_path = env["ANDROID_NDK_ROOT"] + "/toolchains/" + target_subpath + "/prebuilt/" + host_subpath
  191. tools_path = gcc_toolchain_path + "/" + abi_subpath + "/bin"
  192. # For Clang to find NDK tools in preference of those system-wide
  193. env.PrependENVPath("PATH", tools_path)
  194. ccache_path = os.environ.get("CCACHE")
  195. if ccache_path is None:
  196. env["CC"] = compiler_path + "/clang"
  197. env["CXX"] = compiler_path + "/clang++"
  198. else:
  199. # there aren't any ccache wrappers available for Android,
  200. # to enable caching we need to prepend the path to the ccache binary
  201. env["CC"] = ccache_path + " " + compiler_path + "/clang"
  202. env["CXX"] = ccache_path + " " + compiler_path + "/clang++"
  203. env["AR"] = tools_path + "/ar"
  204. env["RANLIB"] = tools_path + "/ranlib"
  205. env["AS"] = tools_path + "/as"
  206. common_opts = ["-fno-integrated-as", "-gcc-toolchain", gcc_toolchain_path]
  207. # Compile flags
  208. env.Append(CPPFLAGS=["-isystem", env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/include"])
  209. env.Append(CPPFLAGS=["-isystem", env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++abi/include"])
  210. # Disable exceptions and rtti on non-tools (template) builds
  211. if env["tools"]:
  212. env.Append(CXXFLAGS=["-frtti"])
  213. else:
  214. env.Append(CXXFLAGS=["-fno-rtti", "-fno-exceptions"])
  215. # Don't use dynamic_cast, necessary with no-rtti.
  216. env.Append(CPPDEFINES=["NO_SAFE_CAST"])
  217. lib_sysroot = env["ANDROID_NDK_ROOT"] + "/platforms/" + env["ndk_platform"] + "/" + env["ARCH"]
  218. # Using NDK unified headers (NDK r15+)
  219. sysroot = env["ANDROID_NDK_ROOT"] + "/sysroot"
  220. env.Append(CPPFLAGS=["--sysroot=" + sysroot])
  221. env.Append(CPPFLAGS=["-isystem", sysroot + "/usr/include/" + abi_subpath])
  222. env.Append(CPPFLAGS=["-isystem", env["ANDROID_NDK_ROOT"] + "/sources/android/support/include"])
  223. # For unified headers this define has to be set manually
  224. env.Append(CPPDEFINES=[("__ANDROID_API__", str(get_platform(env["ndk_platform"])))])
  225. env.Append(
  226. CCFLAGS="-fpic -ffunction-sections -funwind-tables -fstack-protector-strong -fvisibility=hidden -fno-strict-aliasing".split()
  227. )
  228. env.Append(CPPDEFINES=["NO_STATVFS", "GLES_ENABLED"])
  229. env["neon_enabled"] = False
  230. if env["android_arch"] == "x86":
  231. target_opts = ["-target", "i686-none-linux-android"]
  232. # The NDK adds this if targeting API < 21, so we can drop it when Godot targets it at least
  233. env.Append(CCFLAGS=["-mstackrealign"])
  234. elif env["android_arch"] == "x86_64":
  235. target_opts = ["-target", "x86_64-none-linux-android"]
  236. elif env["android_arch"] == "armv7":
  237. target_opts = ["-target", "armv7-none-linux-androideabi"]
  238. env.Append(CCFLAGS="-march=armv7-a -mfloat-abi=softfp".split())
  239. env.Append(CPPDEFINES=["__ARM_ARCH_7__", "__ARM_ARCH_7A__"])
  240. if env["android_neon"]:
  241. env["neon_enabled"] = True
  242. env.Append(CCFLAGS=["-mfpu=neon"])
  243. env.Append(CPPDEFINES=["__ARM_NEON__"])
  244. else:
  245. env.Append(CCFLAGS=["-mfpu=vfpv3-d16"])
  246. elif env["android_arch"] == "arm64v8":
  247. target_opts = ["-target", "aarch64-none-linux-android"]
  248. env.Append(CCFLAGS=["-mfix-cortex-a53-835769"])
  249. env.Append(CPPDEFINES=["__ARM_ARCH_8A__"])
  250. env.Append(CCFLAGS=target_opts)
  251. env.Append(CCFLAGS=common_opts)
  252. # Link flags
  253. ndk_version = get_env_ndk_version(env["ANDROID_NDK_ROOT"])
  254. if ndk_version != None and LooseVersion(ndk_version) >= LooseVersion("17.1.4828580"):
  255. env.Append(LINKFLAGS=["-Wl,--exclude-libs,libgcc.a", "-Wl,--exclude-libs,libatomic.a", "-nostdlib++"])
  256. else:
  257. env.Append(
  258. LINKFLAGS=[
  259. env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/libandroid_support.a"
  260. ]
  261. )
  262. env.Append(LINKFLAGS=["-shared", "--sysroot=" + lib_sysroot, "-Wl,--warn-shared-textrel"])
  263. env.Append(LIBPATH=[env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/"])
  264. env.Append(
  265. LINKFLAGS=[env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/libc++_shared.so"]
  266. )
  267. if env["android_arch"] == "armv7":
  268. env.Append(LINKFLAGS="-Wl,--fix-cortex-a8".split())
  269. env.Append(LINKFLAGS="-Wl,--no-undefined -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now".split())
  270. env.Append(LINKFLAGS="-Wl,-soname,libgodot_android.so -Wl,--gc-sections".split())
  271. env.Append(LINKFLAGS=target_opts)
  272. env.Append(LINKFLAGS=common_opts)
  273. env.Append(
  274. LIBPATH=[
  275. env["ANDROID_NDK_ROOT"]
  276. + "/toolchains/"
  277. + target_subpath
  278. + "/prebuilt/"
  279. + host_subpath
  280. + "/lib/gcc/"
  281. + abi_subpath
  282. + "/4.9.x"
  283. ]
  284. )
  285. env.Append(
  286. LIBPATH=[
  287. env["ANDROID_NDK_ROOT"]
  288. + "/toolchains/"
  289. + target_subpath
  290. + "/prebuilt/"
  291. + host_subpath
  292. + "/"
  293. + abi_subpath
  294. + "/lib"
  295. ]
  296. )
  297. env.Prepend(CPPPATH=["#platform/android"])
  298. env.Append(CPPDEFINES=["ANDROID_ENABLED", "UNIX_ENABLED", "NO_FCNTL"])
  299. env.Append(LIBS=["OpenSLES", "EGL", "GLESv3", "GLESv2", "android", "log", "z", "dl"])
  300. # Return the project NDK version.
  301. # This is kept in sync with the value in 'platform/android/java/app/config.gradle'.
  302. def get_project_ndk_version():
  303. return "21.4.7075529"
  304. # Return NDK version string in source.properties (adapted from the Chromium project).
  305. def get_env_ndk_version(path):
  306. if path is None:
  307. return None
  308. prop_file_path = os.path.join(path, "source.properties")
  309. try:
  310. with open(prop_file_path) as prop_file:
  311. for line in prop_file:
  312. key_value = list(map(lambda x: x.strip(), line.split("=")))
  313. if key_value[0] == "Pkg.Revision":
  314. return key_value[1]
  315. except Exception:
  316. print("Could not read source prop file '%s'" % prop_file_path)
  317. return None