detect.py 14 KB

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