2
0

detect.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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)
  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', os.environ.get("ANDROID_NDK_ROOT", 0)),
  17. ('ndk_platform', 'Target platform (android-<api>, e.g. "android-18")', "android-18"),
  18. EnumVariable('android_arch', 'Target architecture', "armv7", ('armv7', 'arm64v8', 'x86', 'x86_64')),
  19. BoolVariable('android_neon', 'Enable NEON support (armv7 only)', True),
  20. BoolVariable('android_stl', 'Enable Android STL support (for modules)', True)
  21. ]
  22. def get_flags():
  23. return [
  24. ('tools', False),
  25. ]
  26. def create(env):
  27. tools = env['TOOLS']
  28. if "mingw" in tools:
  29. tools.remove('mingw')
  30. if "applelink" in tools:
  31. tools.remove("applelink")
  32. env.Tool('gcc')
  33. return env.Clone(tools=tools)
  34. def configure(env):
  35. # Workaround for MinGW. See:
  36. # http://www.scons.org/wiki/LongCmdLinesOnWin32
  37. if (os.name == "nt"):
  38. import subprocess
  39. def mySubProcess(cmdline, env):
  40. # print("SPAWNED : " + cmdline)
  41. startupinfo = subprocess.STARTUPINFO()
  42. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  43. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  44. stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env)
  45. data, err = proc.communicate()
  46. rv = proc.wait()
  47. if rv:
  48. print("=====")
  49. print(err)
  50. print("=====")
  51. return rv
  52. def mySpawn(sh, escape, cmd, args, env):
  53. newargs = ' '.join(args[1:])
  54. cmdline = cmd + " " + newargs
  55. rv = 0
  56. if len(cmdline) > 32000 and cmd.endswith("ar"):
  57. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  58. for i in range(3, len(args)):
  59. rv = mySubProcess(cmdline + args[i], env)
  60. if rv:
  61. break
  62. else:
  63. rv = mySubProcess(cmdline, env)
  64. return rv
  65. env['SPAWN'] = mySpawn
  66. ## Architecture
  67. if env['android_arch'] not in ['armv7', 'arm64v8', 'x86', 'x86_64']:
  68. env['android_arch'] = 'armv7'
  69. neon_text = ""
  70. if env["android_arch"] == "armv7" and env['android_neon']:
  71. neon_text = " (with NEON)"
  72. print("Building for Android (" + env['android_arch'] + ")" + neon_text)
  73. can_vectorize = True
  74. if env['android_arch'] == 'x86':
  75. env['ARCH'] = 'arch-x86'
  76. env.extra_suffix = ".x86" + env.extra_suffix
  77. target_subpath = "x86-4.9"
  78. abi_subpath = "i686-linux-android"
  79. arch_subpath = "x86"
  80. env["x86_libtheora_opt_gcc"] = True
  81. if env['android_arch'] == 'x86_64':
  82. if get_platform(env["ndk_platform"]) < 21:
  83. print("WARNING: android_arch=x86_64 is not supported by ndk_platform lower than android-21; setting ndk_platform=android-21")
  84. env["ndk_platform"] = "android-21"
  85. env['ARCH'] = 'arch-x86_64'
  86. env.extra_suffix = ".x86_64" + env.extra_suffix
  87. target_subpath = "x86_64-4.9"
  88. abi_subpath = "x86_64-linux-android"
  89. arch_subpath = "x86_64"
  90. env["x86_libtheora_opt_gcc"] = True
  91. elif env["android_arch"] == "armv7":
  92. env['ARCH'] = 'arch-arm'
  93. target_subpath = "arm-linux-androideabi-4.9"
  94. abi_subpath = "arm-linux-androideabi"
  95. arch_subpath = "armeabi-v7a"
  96. if env['android_neon']:
  97. env.extra_suffix = ".armv7.neon" + env.extra_suffix
  98. else:
  99. env.extra_suffix = ".armv7" + env.extra_suffix
  100. elif env["android_arch"] == "arm64v8":
  101. if get_platform(env["ndk_platform"]) < 21:
  102. print("WARNING: android_arch=arm64v8 is not supported by ndk_platform lower than android-21; setting ndk_platform=android-21")
  103. env["ndk_platform"] = "android-21"
  104. env['ARCH'] = 'arch-arm64'
  105. target_subpath = "aarch64-linux-android-4.9"
  106. abi_subpath = "aarch64-linux-android"
  107. arch_subpath = "arm64-v8a"
  108. env.extra_suffix = ".armv8" + env.extra_suffix
  109. ## Build type
  110. if (env["target"].startswith("release")):
  111. if (env["optimize"] == "speed"): #optimize for speed (default)
  112. env.Append(LINKFLAGS=['-O2'])
  113. env.Append(CCFLAGS=['-O2', '-fomit-frame-pointer'])
  114. env.Append(CPPDEFINES=['NDEBUG'])
  115. else: #optimize for size
  116. env.Append(CCFLAGS=['-Os'])
  117. env.Append(CPPDEFINES=['NDEBUG'])
  118. env.Append(LINKFLAGS=['-Os'])
  119. if (can_vectorize):
  120. env.Append(CCFLAGS=['-ftree-vectorize'])
  121. if (env["target"] == "release_debug"):
  122. env.Append(CPPDEFINES=['DEBUG_ENABLED'])
  123. elif (env["target"] == "debug"):
  124. env.Append(LINKFLAGS=['-O0'])
  125. env.Append(CCFLAGS=['-O0', '-g', '-fno-limit-debug-info'])
  126. env.Append(CPPDEFINES=['_DEBUG', 'DEBUG_ENABLED', 'DEBUG_MEMORY_ENABLED'])
  127. env.Append(CPPFLAGS=['-UNDEBUG'])
  128. ## Compiler configuration
  129. env['SHLIBSUFFIX'] = '.so'
  130. if env['PLATFORM'] == 'win32':
  131. env.Tool('gcc')
  132. env.use_windows_spawn_fix()
  133. mt_link = True
  134. if (sys.platform.startswith("linux")):
  135. host_subpath = "linux-x86_64"
  136. elif (sys.platform.startswith("darwin")):
  137. host_subpath = "darwin-x86_64"
  138. elif (sys.platform.startswith('win')):
  139. if (platform.machine().endswith('64')):
  140. host_subpath = "windows-x86_64"
  141. else:
  142. mt_link = False
  143. host_subpath = "windows"
  144. if env["android_arch"] == "arm64v8":
  145. mt_link = False
  146. compiler_path = env["ANDROID_NDK_ROOT"] + "/toolchains/llvm/prebuilt/" + host_subpath + "/bin"
  147. gcc_toolchain_path = env["ANDROID_NDK_ROOT"] + "/toolchains/" + target_subpath + "/prebuilt/" + host_subpath
  148. tools_path = gcc_toolchain_path + "/" + abi_subpath + "/bin"
  149. # For Clang to find NDK tools in preference of those system-wide
  150. env.PrependENVPath('PATH', tools_path)
  151. ccache_path = os.environ.get("CCACHE")
  152. if ccache_path is None:
  153. env['CC'] = compiler_path + '/clang'
  154. env['CXX'] = compiler_path + '/clang++'
  155. else:
  156. # there aren't any ccache wrappers available for Android,
  157. # to enable caching we need to prepend the path to the ccache binary
  158. env['CC'] = ccache_path + ' ' + compiler_path + '/clang'
  159. env['CXX'] = ccache_path + ' ' + compiler_path + '/clang++'
  160. env['AR'] = tools_path + "/ar"
  161. env['RANLIB'] = tools_path + "/ranlib"
  162. env['AS'] = tools_path + "/as"
  163. common_opts = ['-fno-integrated-as', '-gcc-toolchain', gcc_toolchain_path]
  164. ## Compile flags
  165. # Disable exceptions and rtti on non-tools (template) builds
  166. if env['tools'] or env['android_stl']:
  167. env.Append(CPPFLAGS=["-isystem", env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/include"])
  168. env.Append(CPPFLAGS=["-isystem", env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++abi/include"])
  169. env.Append(CXXFLAGS=['-frtti', "-std=gnu++14"])
  170. else:
  171. env.Append(CXXFLAGS=['-fno-rtti', '-fno-exceptions'])
  172. # Don't use dynamic_cast, necessary with no-rtti.
  173. env.Append(CPPDEFINES=['NO_SAFE_CAST'])
  174. lib_sysroot = env["ANDROID_NDK_ROOT"] + "/platforms/" + env['ndk_platform'] + "/" + env['ARCH']
  175. # Using NDK unified headers (NDK r15+)
  176. sysroot = env["ANDROID_NDK_ROOT"] + "/sysroot"
  177. env.Append(CPPFLAGS=["--sysroot=" + sysroot])
  178. env.Append(CPPFLAGS=["-isystem", sysroot + "/usr/include/" + abi_subpath])
  179. env.Append(CPPFLAGS=["-isystem", env["ANDROID_NDK_ROOT"] + "/sources/android/support/include"])
  180. # For unified headers this define has to be set manually
  181. env.Append(CPPDEFINES=[('__ANDROID_API__', str(get_platform(env['ndk_platform'])))])
  182. env.Append(CCFLAGS='-fpic -ffunction-sections -funwind-tables -fstack-protector-strong -fvisibility=hidden -fno-strict-aliasing'.split())
  183. env.Append(CPPDEFINES=['NO_STATVFS', 'GLES_ENABLED'])
  184. env['neon_enabled'] = False
  185. if env['android_arch'] == 'x86':
  186. target_opts = ['-target', 'i686-none-linux-android']
  187. # The NDK adds this if targeting API < 21, so we can drop it when Godot targets it at least
  188. env.Append(CCFLAGS=['-mstackrealign'])
  189. elif env['android_arch'] == 'x86_64':
  190. target_opts = ['-target', 'x86_64-none-linux-android']
  191. elif env["android_arch"] == "armv7":
  192. target_opts = ['-target', 'armv7-none-linux-androideabi']
  193. env.Append(CCFLAGS='-march=armv7-a -mfloat-abi=softfp'.split())
  194. env.Append(CPPDEFINES=['__ARM_ARCH_7__', '__ARM_ARCH_7A__'])
  195. if env['android_neon']:
  196. env['neon_enabled'] = True
  197. env.Append(CCFLAGS=['-mfpu=neon'])
  198. env.Append(CPPDEFINES=['__ARM_NEON__'])
  199. else:
  200. env.Append(CCFLAGS=['-mfpu=vfpv3-d16'])
  201. elif env["android_arch"] == "arm64v8":
  202. target_opts = ['-target', 'aarch64-none-linux-android']
  203. env.Append(CCFLAGS=['-mfix-cortex-a53-835769'])
  204. env.Append(CPPDEFINES=['__ARM_ARCH_8A__'])
  205. env.Append(CCFLAGS=target_opts)
  206. env.Append(CCFLAGS=common_opts)
  207. ## Link flags
  208. ndk_version = get_ndk_version(env["ANDROID_NDK_ROOT"])
  209. if ndk_version != None and LooseVersion(ndk_version) >= LooseVersion("17.1.4828580"):
  210. env.Append(LINKFLAGS=['-Wl,--exclude-libs,libgcc.a', '-Wl,--exclude-libs,libatomic.a', '-nostdlib++'])
  211. else:
  212. env.Append(LINKFLAGS=[env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/libandroid_support.a"])
  213. env.Append(LINKFLAGS=['-shared', '--sysroot=' + lib_sysroot, '-Wl,--warn-shared-textrel'])
  214. env.Append(LIBPATH=[env["ANDROID_NDK_ROOT"] + "/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/"])
  215. env.Append(LINKFLAGS=[env["ANDROID_NDK_ROOT"] +"/sources/cxx-stl/llvm-libc++/libs/" + arch_subpath + "/libc++_shared.so"])
  216. if env["android_arch"] == "armv7":
  217. env.Append(LINKFLAGS='-Wl,--fix-cortex-a8'.split())
  218. env.Append(LINKFLAGS='-Wl,--no-undefined -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now'.split())
  219. env.Append(LINKFLAGS='-Wl,-soname,libgodot_android.so -Wl,--gc-sections'.split())
  220. env.Append(LINKFLAGS=target_opts)
  221. env.Append(LINKFLAGS=common_opts)
  222. env.Append(LIBPATH=[env["ANDROID_NDK_ROOT"] + '/toolchains/' + target_subpath + '/prebuilt/' +
  223. host_subpath + '/lib/gcc/' + abi_subpath + '/4.9.x'])
  224. env.Append(LIBPATH=[env["ANDROID_NDK_ROOT"] +
  225. '/toolchains/' + target_subpath + '/prebuilt/' + host_subpath + '/' + abi_subpath + '/lib'])
  226. env.Prepend(CPPPATH=['#platform/android'])
  227. env.Append(CPPDEFINES=['ANDROID_ENABLED', 'UNIX_ENABLED', 'NO_FCNTL'])
  228. env.Append(LIBS=['OpenSLES', 'EGL', 'GLESv3', 'GLESv2', 'android', 'log', 'z', 'dl'])
  229. # Return NDK version string in source.properties (adapted from the Chromium project).
  230. def get_ndk_version(path):
  231. if path is None:
  232. return None
  233. prop_file_path = os.path.join(path, "source.properties")
  234. try:
  235. with open(prop_file_path) as prop_file:
  236. for line in prop_file:
  237. key_value = list(map(lambda x: x.strip(), line.split("=")))
  238. if key_value[0] == "Pkg.Revision":
  239. return key_value[1]
  240. except:
  241. print("Could not read source prop file '%s'" % prop_file_path)
  242. return None