detect.py 11 KB

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