detect.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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-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. # 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 (" + 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 ndk_platform=android-21"
  125. )
  126. env["ndk_platform"] = "android-21"
  127. env["ARCH"] = "arch-x86_64"
  128. env.extra_suffix = ".x86_64" + env.extra_suffix
  129. target_subpath = "x86_64-4.9"
  130. abi_subpath = "x86_64-linux-android"
  131. arch_subpath = "x86_64"
  132. env["x86_libtheora_opt_gcc"] = True
  133. elif env["android_arch"] == "armv7":
  134. env["ARCH"] = "arch-arm"
  135. target_subpath = "arm-linux-androideabi-4.9"
  136. abi_subpath = "arm-linux-androideabi"
  137. arch_subpath = "armeabi-v7a"
  138. if env["android_neon"]:
  139. env.extra_suffix = ".armv7.neon" + env.extra_suffix
  140. else:
  141. env.extra_suffix = ".armv7" + env.extra_suffix
  142. elif env["android_arch"] == "arm64v8":
  143. if get_platform(env["ndk_platform"]) < 21:
  144. print(
  145. "WARNING: android_arch=arm64v8 is not supported by ndk_platform lower than android-21; setting ndk_platform=android-21"
  146. )
  147. env["ndk_platform"] = "android-21"
  148. env["ARCH"] = "arch-arm64"
  149. target_subpath = "aarch64-linux-android-4.9"
  150. abi_subpath = "aarch64-linux-android"
  151. arch_subpath = "arm64-v8a"
  152. env.extra_suffix = ".armv8" + env.extra_suffix
  153. # Build type
  154. if env["target"].startswith("release"):
  155. if env["optimize"] == "speed": # optimize for speed (default)
  156. env.Append(LINKFLAGS=["-O2"])
  157. env.Append(CCFLAGS=["-O2", "-fomit-frame-pointer"])
  158. elif env["optimize"] == "size": # optimize for size
  159. env.Append(CCFLAGS=["-Os"])
  160. env.Append(LINKFLAGS=["-Os"])
  161. env.Append(CPPDEFINES=["NDEBUG"])
  162. if can_vectorize:
  163. env.Append(CCFLAGS=["-ftree-vectorize"])
  164. if env["target"] == "release_debug":
  165. env.Append(CPPDEFINES=["DEBUG_ENABLED"])
  166. elif env["target"] == "debug":
  167. env.Append(LINKFLAGS=["-O0"])
  168. env.Append(CCFLAGS=["-O0", "-g", "-fno-limit-debug-info"])
  169. env.Append(CPPDEFINES=["_DEBUG", "DEBUG_ENABLED"])
  170. env.Append(CPPFLAGS=["-UNDEBUG"])
  171. # Compiler configuration
  172. env["SHLIBSUFFIX"] = ".so"
  173. if env["PLATFORM"] == "win32":
  174. env.Tool("gcc")
  175. env.use_windows_spawn_fix()
  176. if sys.platform.startswith("linux"):
  177. host_subpath = "linux-x86_64"
  178. elif sys.platform.startswith("darwin"):
  179. host_subpath = "darwin-x86_64"
  180. elif sys.platform.startswith("win"):
  181. if platform.machine().endswith("64"):
  182. host_subpath = "windows-x86_64"
  183. else:
  184. host_subpath = "windows"
  185. compiler_path = env["ANDROID_NDK_ROOT"] + "/toolchains/llvm/prebuilt/" + host_subpath + "/bin"
  186. gcc_toolchain_path = env["ANDROID_NDK_ROOT"] + "/toolchains/" + target_subpath + "/prebuilt/" + host_subpath
  187. tools_path = gcc_toolchain_path + "/" + abi_subpath + "/bin"
  188. # For Clang to find NDK tools in preference of those system-wide
  189. env.PrependENVPath("PATH", tools_path)
  190. ccache_path = os.environ.get("CCACHE")
  191. if ccache_path is None:
  192. env["CC"] = compiler_path + "/clang"
  193. env["CXX"] = compiler_path + "/clang++"
  194. else:
  195. # there aren't any ccache wrappers available for Android,
  196. # to enable caching we need to prepend the path to the ccache binary
  197. env["CC"] = ccache_path + " " + compiler_path + "/clang"
  198. env["CXX"] = ccache_path + " " + compiler_path + "/clang++"
  199. env["AR"] = tools_path + "/ar"
  200. env["RANLIB"] = tools_path + "/ranlib"
  201. env["AS"] = tools_path + "/as"
  202. common_opts = ["-fno-integrated-as", "-gcc-toolchain", gcc_toolchain_path]
  203. # Compile flags
  204. env.Append(CPPFLAGS=["-isystem", env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/include"])
  205. env.Append(CPPFLAGS=["-isystem", env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++abi/include"])
  206. # Disable exceptions and rtti on non-tools (template) builds
  207. if env["tools"]:
  208. env.Append(CXXFLAGS=["-frtti"])
  209. else:
  210. env.Append(CXXFLAGS=["-fno-rtti", "-fno-exceptions"])
  211. # Don't use dynamic_cast, necessary with no-rtti.
  212. env.Append(CPPDEFINES=["NO_SAFE_CAST"])
  213. lib_sysroot = env["ANDROID_NDK_ROOT"] + "/platforms/" + env["ndk_platform"] + "/" + env["ARCH"]
  214. # Using NDK unified headers (NDK r15+)
  215. sysroot = env["ANDROID_NDK_ROOT"] + "/sysroot"
  216. env.Append(CPPFLAGS=["--sysroot=" + sysroot])
  217. env.Append(CPPFLAGS=["-isystem", sysroot + "/usr/include/" + abi_subpath])
  218. env.Append(CPPFLAGS=["-isystem", env["ANDROID_NDK_ROOT"] + "/sources/android/support/include"])
  219. # For unified headers this define has to be set manually
  220. env.Append(CPPDEFINES=[("__ANDROID_API__", str(get_platform(env["ndk_platform"])))])
  221. env.Append(
  222. CCFLAGS="-fpic -ffunction-sections -funwind-tables -fstack-protector-strong -fvisibility=hidden -fno-strict-aliasing".split()
  223. )
  224. env.Append(CPPDEFINES=["NO_STATVFS", "GLES_ENABLED"])
  225. if get_platform(env["ndk_platform"]) >= 24:
  226. env.Append(CPPDEFINES=[("_FILE_OFFSET_BITS", 64)])
  227. env["neon_enabled"] = False
  228. if env["android_arch"] == "x86":
  229. target_opts = ["-target", "i686-none-linux-android"]
  230. # The NDK adds this if targeting API < 21, so we can drop it when Godot targets it at least
  231. env.Append(CCFLAGS=["-mstackrealign"])
  232. elif env["android_arch"] == "x86_64":
  233. target_opts = ["-target", "x86_64-none-linux-android"]
  234. elif env["android_arch"] == "armv7":
  235. target_opts = ["-target", "armv7-none-linux-androideabi"]
  236. env.Append(CCFLAGS="-march=armv7-a -mfloat-abi=softfp".split())
  237. env.Append(CPPDEFINES=["__ARM_ARCH_7__", "__ARM_ARCH_7A__"])
  238. if env["android_neon"]:
  239. env["neon_enabled"] = True
  240. env.Append(CCFLAGS=["-mfpu=neon"])
  241. env.Append(CPPDEFINES=["__ARM_NEON__"])
  242. else:
  243. env.Append(CCFLAGS=["-mfpu=vfpv3-d16"])
  244. elif env["android_arch"] == "arm64v8":
  245. target_opts = ["-target", "aarch64-none-linux-android"]
  246. env.Append(CCFLAGS=["-mfix-cortex-a53-835769"])
  247. env.Append(CPPDEFINES=["__ARM_ARCH_8A__"])
  248. env.Append(CCFLAGS=target_opts)
  249. env.Append(CCFLAGS=common_opts)
  250. # Link flags
  251. ndk_version = get_env_ndk_version(env["ANDROID_NDK_ROOT"])
  252. if ndk_version != None and LooseVersion(ndk_version) >= LooseVersion("17.1.4828580"):
  253. env.Append(LINKFLAGS=["-Wl,--exclude-libs,libgcc.a", "-Wl,--exclude-libs,libatomic.a", "-nostdlib++"])
  254. else:
  255. env.Append(
  256. LINKFLAGS=[
  257. env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/libandroid_support.a"
  258. ]
  259. )
  260. env.Append(LINKFLAGS=["-shared", "--sysroot=" + lib_sysroot, "-Wl,--warn-shared-textrel"])
  261. env.Append(LIBPATH=[env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/"])
  262. env.Append(
  263. LINKFLAGS=[env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/libc++_shared.so"]
  264. )
  265. if env["android_arch"] == "armv7":
  266. env.Append(LINKFLAGS="-Wl,--fix-cortex-a8".split())
  267. env.Append(LINKFLAGS="-Wl,--no-undefined -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now".split())
  268. env.Append(LINKFLAGS="-Wl,-soname,libgodot_android.so -Wl,--gc-sections".split())
  269. env.Append(LINKFLAGS=target_opts)
  270. env.Append(LINKFLAGS=common_opts)
  271. env.Append(
  272. LIBPATH=[
  273. env["ANDROID_NDK_ROOT"]
  274. + "/toolchains/"
  275. + target_subpath
  276. + "/prebuilt/"
  277. + host_subpath
  278. + "/lib/gcc/"
  279. + abi_subpath
  280. + "/4.9.x"
  281. ]
  282. )
  283. env.Append(
  284. LIBPATH=[
  285. env["ANDROID_NDK_ROOT"]
  286. + "/toolchains/"
  287. + target_subpath
  288. + "/prebuilt/"
  289. + host_subpath
  290. + "/"
  291. + abi_subpath
  292. + "/lib"
  293. ]
  294. )
  295. env.Prepend(CPPPATH=["#platform/android"])
  296. env.Append(CPPDEFINES=["ANDROID_ENABLED", "UNIX_ENABLED", "NO_FCNTL"])
  297. env.Append(LIBS=["OpenSLES", "EGL", "GLESv3", "GLESv2", "android", "log", "z", "dl"])
  298. # Return the project NDK version.
  299. # This is kept in sync with the value in 'platform/android/java/app/config.gradle'.
  300. def get_project_ndk_version():
  301. return "21.4.7075529"
  302. # Return NDK version string in source.properties (adapted from the Chromium project).
  303. def get_env_ndk_version(path):
  304. if path is None:
  305. return None
  306. prop_file_path = os.path.join(path, "source.properties")
  307. try:
  308. with open(prop_file_path) as prop_file:
  309. for line in prop_file:
  310. key_value = list(map(lambda x: x.strip(), line.split("=")))
  311. if key_value[0] == "Pkg.Revision":
  312. return key_value[1]
  313. except Exception:
  314. print("Could not read source prop file '%s'" % prop_file_path)
  315. return None