ndk_library.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. // Copyright 2016 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package cc
  15. import (
  16. "fmt"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "github.com/google/blueprint"
  21. "android/soong/android"
  22. )
  23. var (
  24. toolPath = pctx.SourcePathVariable("toolPath", "build/soong/cc/gen_stub_libs.py")
  25. genStubSrc = pctx.AndroidStaticRule("genStubSrc",
  26. blueprint.RuleParams{
  27. Command: "$toolPath --arch $arch --api $apiLevel --api-map " +
  28. "$apiMap $flags $in $out",
  29. CommandDeps: []string{"$toolPath"},
  30. }, "arch", "apiLevel", "apiMap", "flags")
  31. ndkLibrarySuffix = ".ndk"
  32. ndkPrebuiltSharedLibs = []string{
  33. "aaudio",
  34. "amidi",
  35. "android",
  36. "binder_ndk",
  37. "c",
  38. "camera2ndk",
  39. "dl",
  40. "EGL",
  41. "GLESv1_CM",
  42. "GLESv2",
  43. "GLESv3",
  44. "jnigraphics",
  45. "log",
  46. "mediandk",
  47. "nativewindow",
  48. "m",
  49. "neuralnetworks",
  50. "OpenMAXAL",
  51. "OpenSLES",
  52. "stdc++",
  53. "sync",
  54. "vulkan",
  55. "z",
  56. }
  57. ndkPrebuiltSharedLibraries = addPrefix(append([]string(nil), ndkPrebuiltSharedLibs...), "lib")
  58. // These libraries have migrated over to the new ndk_library, which is added
  59. // as a variation dependency via depsMutator.
  60. ndkMigratedLibs = []string{}
  61. ndkMigratedLibsLock sync.Mutex // protects ndkMigratedLibs writes during parallel BeginMutator
  62. )
  63. // Creates a stub shared library based on the provided version file.
  64. //
  65. // Example:
  66. //
  67. // ndk_library {
  68. // name: "libfoo",
  69. // symbol_file: "libfoo.map.txt",
  70. // first_version: "9",
  71. // }
  72. //
  73. type libraryProperties struct {
  74. // Relative path to the symbol map.
  75. // An example file can be seen here: TODO(danalbert): Make an example.
  76. Symbol_file *string
  77. // The first API level a library was available. A library will be generated
  78. // for every API level beginning with this one.
  79. First_version *string
  80. // The first API level that library should have the version script applied.
  81. // This defaults to the value of first_version, and should almost never be
  82. // used. This is only needed to work around platform bugs like
  83. // https://github.com/android-ndk/ndk/issues/265.
  84. Unversioned_until *string
  85. // Private property for use by the mutator that splits per-API level.
  86. ApiLevel string `blueprint:"mutated"`
  87. // True if this API is not yet ready to be shipped in the NDK. It will be
  88. // available in the platform for testing, but will be excluded from the
  89. // sysroot provided to the NDK proper.
  90. Draft bool
  91. }
  92. type stubDecorator struct {
  93. *libraryDecorator
  94. properties libraryProperties
  95. versionScriptPath android.ModuleGenPath
  96. installPath android.Path
  97. }
  98. // OMG GO
  99. func intMax(a int, b int) int {
  100. if a > b {
  101. return a
  102. } else {
  103. return b
  104. }
  105. }
  106. func normalizeNdkApiLevel(ctx android.BaseModuleContext, apiLevel string,
  107. arch android.Arch) (string, error) {
  108. if apiLevel == "current" {
  109. return apiLevel, nil
  110. }
  111. minVersion := ctx.Config().MinSupportedSdkVersion()
  112. firstArchVersions := map[android.ArchType]int{
  113. android.Arm: minVersion,
  114. android.Arm64: 21,
  115. android.X86: minVersion,
  116. android.X86_64: 21,
  117. }
  118. firstArchVersion, ok := firstArchVersions[arch.ArchType]
  119. if !ok {
  120. panic(fmt.Errorf("Arch %q not found in firstArchVersions", arch.ArchType))
  121. }
  122. if apiLevel == "minimum" {
  123. return strconv.Itoa(firstArchVersion), nil
  124. }
  125. // If the NDK drops support for a platform version, we don't want to have to
  126. // fix up every module that was using it as its SDK version. Clip to the
  127. // supported version here instead.
  128. version, err := strconv.Atoi(apiLevel)
  129. if err != nil {
  130. return "", fmt.Errorf("API level must be an integer (is %q)", apiLevel)
  131. }
  132. version = intMax(version, minVersion)
  133. return strconv.Itoa(intMax(version, firstArchVersion)), nil
  134. }
  135. func getFirstGeneratedVersion(firstSupportedVersion string, platformVersion int) (int, error) {
  136. if firstSupportedVersion == "current" {
  137. return platformVersion + 1, nil
  138. }
  139. return strconv.Atoi(firstSupportedVersion)
  140. }
  141. func shouldUseVersionScript(ctx android.BaseModuleContext, stub *stubDecorator) (bool, error) {
  142. // unversioned_until is normally empty, in which case we should use the version script.
  143. if String(stub.properties.Unversioned_until) == "" {
  144. return true, nil
  145. }
  146. if String(stub.properties.Unversioned_until) == "current" {
  147. if stub.properties.ApiLevel == "current" {
  148. return true, nil
  149. } else {
  150. return false, nil
  151. }
  152. }
  153. if stub.properties.ApiLevel == "current" {
  154. return true, nil
  155. }
  156. unversionedUntil, err := android.ApiStrToNum(ctx, String(stub.properties.Unversioned_until))
  157. if err != nil {
  158. return true, err
  159. }
  160. version, err := android.ApiStrToNum(ctx, stub.properties.ApiLevel)
  161. if err != nil {
  162. return true, err
  163. }
  164. return version >= unversionedUntil, nil
  165. }
  166. func generateStubApiVariants(mctx android.BottomUpMutatorContext, c *stubDecorator) {
  167. platformVersion := mctx.Config().PlatformSdkVersionInt()
  168. firstSupportedVersion, err := normalizeNdkApiLevel(mctx, String(c.properties.First_version),
  169. mctx.Arch())
  170. if err != nil {
  171. mctx.PropertyErrorf("first_version", err.Error())
  172. }
  173. firstGenVersion, err := getFirstGeneratedVersion(firstSupportedVersion, platformVersion)
  174. if err != nil {
  175. // In theory this is impossible because we've already run this through
  176. // normalizeNdkApiLevel above.
  177. mctx.PropertyErrorf("first_version", err.Error())
  178. }
  179. var versionStrs []string
  180. for version := firstGenVersion; version <= platformVersion; version++ {
  181. versionStrs = append(versionStrs, strconv.Itoa(version))
  182. }
  183. versionStrs = append(versionStrs, mctx.Config().PlatformVersionActiveCodenames()...)
  184. versionStrs = append(versionStrs, "current")
  185. modules := mctx.CreateVariations(versionStrs...)
  186. for i, module := range modules {
  187. module.(*Module).compiler.(*stubDecorator).properties.ApiLevel = versionStrs[i]
  188. }
  189. }
  190. func NdkApiMutator(mctx android.BottomUpMutatorContext) {
  191. if m, ok := mctx.Module().(*Module); ok {
  192. if m.Enabled() {
  193. if compiler, ok := m.compiler.(*stubDecorator); ok {
  194. generateStubApiVariants(mctx, compiler)
  195. }
  196. }
  197. }
  198. }
  199. func (c *stubDecorator) compilerInit(ctx BaseModuleContext) {
  200. c.baseCompiler.compilerInit(ctx)
  201. name := ctx.baseModuleName()
  202. if strings.HasSuffix(name, ndkLibrarySuffix) {
  203. ctx.PropertyErrorf("name", "Do not append %q manually, just use the base name", ndkLibrarySuffix)
  204. }
  205. ndkMigratedLibsLock.Lock()
  206. defer ndkMigratedLibsLock.Unlock()
  207. for _, lib := range ndkMigratedLibs {
  208. if lib == name {
  209. return
  210. }
  211. }
  212. ndkMigratedLibs = append(ndkMigratedLibs, name)
  213. }
  214. func addStubLibraryCompilerFlags(flags Flags) Flags {
  215. flags.Global.CFlags = append(flags.Global.CFlags,
  216. // We're knowingly doing some otherwise unsightly things with builtin
  217. // functions here. We're just generating stub libraries, so ignore it.
  218. "-Wno-incompatible-library-redeclaration",
  219. "-Wno-incomplete-setjmp-declaration",
  220. "-Wno-builtin-requires-header",
  221. "-Wno-invalid-noreturn",
  222. "-Wall",
  223. "-Werror",
  224. // These libraries aren't actually used. Don't worry about unwinding
  225. // (avoids the need to link an unwinder into a fake library).
  226. "-fno-unwind-tables",
  227. )
  228. // All symbols in the stubs library should be visible.
  229. if inList("-fvisibility=hidden", flags.Local.CFlags) {
  230. flags.Local.CFlags = append(flags.Local.CFlags, "-fvisibility=default")
  231. }
  232. return flags
  233. }
  234. func (stub *stubDecorator) compilerFlags(ctx ModuleContext, flags Flags, deps PathDeps) Flags {
  235. flags = stub.baseCompiler.compilerFlags(ctx, flags, deps)
  236. return addStubLibraryCompilerFlags(flags)
  237. }
  238. func compileStubLibrary(ctx ModuleContext, flags Flags, symbolFile, apiLevel, genstubFlags string) (Objects, android.ModuleGenPath) {
  239. arch := ctx.Arch().ArchType.String()
  240. stubSrcPath := android.PathForModuleGen(ctx, "stub.c")
  241. versionScriptPath := android.PathForModuleGen(ctx, "stub.map")
  242. symbolFilePath := android.PathForModuleSrc(ctx, symbolFile)
  243. apiLevelsJson := android.GetApiLevelsJson(ctx)
  244. ctx.Build(pctx, android.BuildParams{
  245. Rule: genStubSrc,
  246. Description: "generate stubs " + symbolFilePath.Rel(),
  247. Outputs: []android.WritablePath{stubSrcPath, versionScriptPath},
  248. Input: symbolFilePath,
  249. Implicits: []android.Path{apiLevelsJson},
  250. Args: map[string]string{
  251. "arch": arch,
  252. "apiLevel": apiLevel,
  253. "apiMap": apiLevelsJson.String(),
  254. "flags": genstubFlags,
  255. },
  256. })
  257. subdir := ""
  258. srcs := []android.Path{stubSrcPath}
  259. return compileObjs(ctx, flagsToBuilderFlags(flags), subdir, srcs, nil, nil), versionScriptPath
  260. }
  261. func (c *stubDecorator) compile(ctx ModuleContext, flags Flags, deps PathDeps) Objects {
  262. if !strings.HasSuffix(String(c.properties.Symbol_file), ".map.txt") {
  263. ctx.PropertyErrorf("symbol_file", "must end with .map.txt")
  264. }
  265. objs, versionScript := compileStubLibrary(ctx, flags, String(c.properties.Symbol_file),
  266. c.properties.ApiLevel, "")
  267. c.versionScriptPath = versionScript
  268. return objs
  269. }
  270. func (linker *stubDecorator) linkerDeps(ctx DepsContext, deps Deps) Deps {
  271. return Deps{}
  272. }
  273. func (linker *stubDecorator) Name(name string) string {
  274. return name + ndkLibrarySuffix
  275. }
  276. func (stub *stubDecorator) linkerFlags(ctx ModuleContext, flags Flags) Flags {
  277. stub.libraryDecorator.libName = ctx.baseModuleName()
  278. return stub.libraryDecorator.linkerFlags(ctx, flags)
  279. }
  280. func (stub *stubDecorator) link(ctx ModuleContext, flags Flags, deps PathDeps,
  281. objs Objects) android.Path {
  282. useVersionScript, err := shouldUseVersionScript(ctx, stub)
  283. if err != nil {
  284. ctx.ModuleErrorf(err.Error())
  285. }
  286. if useVersionScript {
  287. linkerScriptFlag := "-Wl,--version-script," + stub.versionScriptPath.String()
  288. flags.Local.LdFlags = append(flags.Local.LdFlags, linkerScriptFlag)
  289. flags.LdFlagsDeps = append(flags.LdFlagsDeps, stub.versionScriptPath)
  290. }
  291. return stub.libraryDecorator.link(ctx, flags, deps, objs)
  292. }
  293. func (stub *stubDecorator) nativeCoverage() bool {
  294. return false
  295. }
  296. func (stub *stubDecorator) install(ctx ModuleContext, path android.Path) {
  297. arch := ctx.Target().Arch.ArchType.Name
  298. apiLevel := stub.properties.ApiLevel
  299. // arm64 isn't actually a multilib toolchain, so unlike the other LP64
  300. // architectures it's just installed to lib.
  301. libDir := "lib"
  302. if ctx.toolchain().Is64Bit() && arch != "arm64" {
  303. libDir = "lib64"
  304. }
  305. installDir := getNdkInstallBase(ctx).Join(ctx, fmt.Sprintf(
  306. "platforms/android-%s/arch-%s/usr/%s", apiLevel, arch, libDir))
  307. stub.installPath = ctx.InstallFile(installDir, path.Base(), path)
  308. }
  309. func newStubLibrary() *Module {
  310. module, library := NewLibrary(android.DeviceSupported)
  311. library.BuildOnlyShared()
  312. module.stl = nil
  313. module.sanitize = nil
  314. library.StripProperties.Strip.None = BoolPtr(true)
  315. stub := &stubDecorator{
  316. libraryDecorator: library,
  317. }
  318. module.compiler = stub
  319. module.linker = stub
  320. module.installer = stub
  321. module.AddProperties(&stub.properties, &library.MutatedProperties)
  322. return module
  323. }
  324. // ndk_library creates a stub library that exposes dummy implementation
  325. // of functions and variables for use at build time only.
  326. func NdkLibraryFactory() android.Module {
  327. module := newStubLibrary()
  328. android.InitAndroidArchModule(module, android.DeviceSupported, android.MultilibBoth)
  329. module.ModuleBase.EnableNativeBridgeSupportByDefault()
  330. return module
  331. }