class_loader_context.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. // Copyright 2020 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 dexpreopt
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "strconv"
  19. "android/soong/android"
  20. "github.com/google/blueprint/proptools"
  21. )
  22. // This comment describes the following:
  23. // 1. the concept of class loader context (CLC) and its relation to classpath
  24. // 2. how PackageManager constructs CLC from shared libraries and their dependencies
  25. // 3. build-time vs. run-time CLC and why this matters for dexpreopt
  26. // 4. manifest fixer: a tool that adds missing <uses-library> tags to the manifests
  27. // 5. build system support for CLC
  28. //
  29. // 1. Class loader context
  30. // -----------------------
  31. //
  32. // Java libraries and apps that have run-time dependency on other libraries should list the used
  33. // libraries in their manifest (AndroidManifest.xml file). Each used library should be specified in
  34. // a <uses-library> tag that has the library name and an optional attribute specifying if the
  35. // library is optional or required. Required libraries are necessary for the library/app to run (it
  36. // will fail at runtime if the library cannot be loaded), and optional libraries are used only if
  37. // they are present (if not, the library/app can run without them).
  38. //
  39. // The libraries listed in <uses-library> tags are in the classpath of a library/app.
  40. //
  41. // Besides libraries, an app may also use another APK (for example in the case of split APKs), or
  42. // anything that gets added by the app dynamically. In general, it is impossible to know at build
  43. // time what the app may use at runtime. In the build system we focus on the known part: libraries.
  44. //
  45. // Class loader context (CLC) is a tree-like structure that describes class loader hierarchy. The
  46. // build system uses CLC in a more narrow sense: it is a tree of libraries that represents
  47. // transitive closure of all <uses-library> dependencies of a library/app. The top-level elements of
  48. // a CLC are the direct <uses-library> dependencies specified in the manifest (aka. classpath). Each
  49. // node of a CLC tree is a <uses-library> which may have its own <uses-library> sub-nodes.
  50. //
  51. // Because <uses-library> dependencies are, in general, a graph and not necessarily a tree, CLC may
  52. // contain subtrees for the same library multiple times. In other words, CLC is the dependency graph
  53. // "unfolded" to a tree. The duplication is only on a logical level, and the actual underlying class
  54. // loaders are not duplicated (at runtime there is a single class loader instance for each library).
  55. //
  56. // Example: A has <uses-library> tags B, C and D; C has <uses-library tags> B and D;
  57. //
  58. // D has <uses-library> E; B and E have no <uses-library> dependencies. The CLC is:
  59. // A
  60. // ├── B
  61. // ├── C
  62. // │ ├── B
  63. // │ └── D
  64. // │ └── E
  65. // └── D
  66. // └── E
  67. //
  68. // CLC defines the lookup order of libraries when resolving Java classes used by the library/app.
  69. // The lookup order is important because libraries may contain duplicate classes, and the class is
  70. // resolved to the first match.
  71. //
  72. // 2. PackageManager and "shared" libraries
  73. // ----------------------------------------
  74. //
  75. // In order to load an APK at runtime, PackageManager (in frameworks/base) creates a CLC. It adds
  76. // the libraries listed in the <uses-library> tags in the app's manifest as top-level CLC elements.
  77. // For each of the used libraries PackageManager gets all its <uses-library> dependencies (specified
  78. // as tags in the manifest of that library) and adds a nested CLC for each dependency. This process
  79. // continues recursively until all leaf nodes of the constructed CLC tree are libraries that have no
  80. // <uses-library> dependencies.
  81. //
  82. // PackageManager is aware only of "shared" libraries. The definition of "shared" here differs from
  83. // its usual meaning (as in shared vs. static). In Android, Java "shared" libraries are those listed
  84. // in /system/etc/permissions/platform.xml file. This file is installed on device. Each entry in it
  85. // contains the name of a "shared" library, a path to its DEX jar file and a list of dependencies
  86. // (other "shared" libraries that this one uses at runtime and specifies them in <uses-library> tags
  87. // in its manifest).
  88. //
  89. // In other words, there are two sources of information that allow PackageManager to construct CLC
  90. // at runtime: <uses-library> tags in the manifests and "shared" library dependencies in
  91. // /system/etc/permissions/platform.xml.
  92. //
  93. // 3. Build-time and run-time CLC and dexpreopt
  94. // --------------------------------------------
  95. //
  96. // CLC is needed not only when loading a library/app, but also when compiling it. Compilation may
  97. // happen either on device (known as "dexopt") or during the build (known as "dexpreopt"). Since
  98. // dexopt takes place on device, it has the same information as PackageManager (manifests and
  99. // shared library dependencies). Dexpreopt, on the other hand, takes place on host and in a totally
  100. // different environment, and it has to get the same information from the build system (see the
  101. // section about build system support below).
  102. //
  103. // Thus, the build-time CLC used by dexpreopt and the run-time CLC used by PackageManager are
  104. // the same thing, but computed in two different ways.
  105. //
  106. // It is important that build-time and run-time CLCs coincide, otherwise the AOT-compiled code
  107. // created by dexpreopt will be rejected. In order to check the equality of build-time and
  108. // run-time CLCs, the dex2oat compiler records build-time CLC in the *.odex files (in the
  109. // "classpath" field of the OAT file header). To find the stored CLC, use the following command:
  110. // `oatdump --oat-file=<FILE> | grep '^classpath = '`.
  111. //
  112. // Mismatch between build-time and run-time CLC is reported in logcat during boot (search with
  113. // `logcat | grep -E 'ClassLoaderContext [a-z ]+ mismatch'`. Mismatch is bad for performance, as it
  114. // forces the library/app to either be dexopted, or to run without any optimizations (e.g. the app's
  115. // code may need to be extracted in memory from the APK, a very expensive operation).
  116. //
  117. // A <uses-library> can be either optional or required. From dexpreopt standpoint, required library
  118. // must be present at build time (its absence is a build error). An optional library may be either
  119. // present or absent at build time: if present, it will be added to the CLC, passed to dex2oat and
  120. // recorded in the *.odex file; otherwise, if the library is absent, it will be skipped and not
  121. // added to CLC. If there is a mismatch between built-time and run-time status (optional library is
  122. // present in one case, but not the other), then the build-time and run-time CLCs won't match and
  123. // the compiled code will be rejected. It is unknown at build time if the library will be present at
  124. // runtime, therefore either including or excluding it may cause CLC mismatch.
  125. //
  126. // 4. Manifest fixer
  127. // -----------------
  128. //
  129. // Sometimes <uses-library> tags are missing from the source manifest of a library/app. This may
  130. // happen for example if one of the transitive dependencies of the library/app starts using another
  131. // <uses-library>, and the library/app's manifest isn't updated to include it.
  132. //
  133. // Soong can compute some of the missing <uses-library> tags for a given library/app automatically
  134. // as SDK libraries in the transitive dependency closure of the library/app. The closure is needed
  135. // because a library/app may depend on a static library that may in turn depend on an SDK library,
  136. // (possibly transitively via another library).
  137. //
  138. // Not all <uses-library> tags can be computed in this way, because some of the <uses-library>
  139. // dependencies are not SDK libraries, or they are not reachable via transitive dependency closure.
  140. // But when possible, allowing Soong to calculate the manifest entries is less prone to errors and
  141. // simplifies maintenance. For example, consider a situation when many apps use some static library
  142. // that adds a new <uses-library> dependency -- all the apps will have to be updated. That is
  143. // difficult to maintain.
  144. //
  145. // Soong computes the libraries that need to be in the manifest as the top-level libraries in CLC.
  146. // These libraries are passed to the manifest_fixer.
  147. //
  148. // All libraries added to the manifest should be "shared" libraries, so that PackageManager can look
  149. // up their dependencies and reconstruct the nested subcontexts at runtime. There is no build check
  150. // to ensure this, it is an assumption.
  151. //
  152. // 5. Build system support
  153. // -----------------------
  154. //
  155. // In order to construct CLC for dexpreopt and manifest_fixer, the build system needs to know all
  156. // <uses-library> dependencies of the dexpreopted library/app (including transitive dependencies).
  157. // For each <uses-librarry> dependency it needs to know the following information:
  158. //
  159. // - the real name of the <uses-library> (it may be different from the module name)
  160. // - build-time (on host) and run-time (on device) paths to the DEX jar file of the library
  161. // - whether this library is optional or required
  162. // - all <uses-library> dependencies
  163. //
  164. // Since the build system doesn't have access to the manifest contents (it cannot read manifests at
  165. // the time of build rule generation), it is necessary to copy this information to the Android.bp
  166. // and Android.mk files. For blueprints, the relevant properties are `uses_libs` and
  167. // `optional_uses_libs`. For makefiles, relevant variables are `LOCAL_USES_LIBRARIES` and
  168. // `LOCAL_OPTIONAL_USES_LIBRARIES`. It is preferable to avoid specifying these properties explicilty
  169. // when they can be computed automatically by Soong (as the transitive closure of SDK library
  170. // dependencies).
  171. //
  172. // Some of the Java libraries that are used as <uses-library> are not SDK libraries (they are
  173. // defined as `java_library` rather than `java_sdk_library` in the Android.bp files). In order for
  174. // the build system to handle them automatically like SDK libraries, it is possible to set a
  175. // property `provides_uses_lib` or variable `LOCAL_PROVIDES_USES_LIBRARY` on the blueprint/makefile
  176. // module of such library. This property can also be used to specify real library name in cases
  177. // when it differs from the module name.
  178. //
  179. // Because the information from the manifests has to be duplicated in the Android.bp/Android.mk
  180. // files, there is a danger that it may get out of sync. To guard against that, the build system
  181. // generates a rule that checks the metadata in the build files against the contents of a manifest
  182. // (verify_uses_libraries). The manifest can be available as a source file, or as part of a prebuilt
  183. // APK. Note that reading the manifests at the Ninja stage of the build is fine, unlike the build
  184. // rule generation phase.
  185. //
  186. // ClassLoaderContext is a structure that represents CLC.
  187. type ClassLoaderContext struct {
  188. // The name of the library.
  189. Name string
  190. // If the library is optional or required.
  191. Optional bool
  192. // On-host build path to the library dex file (used in dex2oat argument --class-loader-context).
  193. Host android.Path
  194. // On-device install path (used in dex2oat argument --stored-class-loader-context).
  195. Device string
  196. // Nested sub-CLC for dependencies.
  197. Subcontexts []*ClassLoaderContext
  198. }
  199. // excludeLibs excludes the libraries from this ClassLoaderContext.
  200. //
  201. // This treats the supplied context as being immutable (as it may come from a dependency). So, it
  202. // implements copy-on-exclusion logic. That means that if any of the excluded libraries are used
  203. // within this context then this will return a deep copy of this without those libraries.
  204. //
  205. // If this ClassLoaderContext matches one of the libraries to exclude then this returns (nil, true)
  206. // to indicate that this context should be excluded from the containing list.
  207. //
  208. // If any of this ClassLoaderContext's Subcontexts reference the excluded libraries then this
  209. // returns a pointer to a copy of this without the excluded libraries and true to indicate that this
  210. // was copied.
  211. //
  212. // Otherwise, this returns a pointer to this and false to indicate that this was not copied.
  213. func (c *ClassLoaderContext) excludeLibs(excludedLibs []string) (*ClassLoaderContext, bool) {
  214. if android.InList(c.Name, excludedLibs) {
  215. return nil, true
  216. }
  217. if excludedList, modified := excludeLibsFromCLCList(c.Subcontexts, excludedLibs); modified {
  218. clcCopy := *c
  219. clcCopy.Subcontexts = excludedList
  220. return &clcCopy, true
  221. }
  222. return c, false
  223. }
  224. // ClassLoaderContextMap is a map from SDK version to CLC. There is a special entry with key
  225. // AnySdkVersion that stores unconditional CLC that is added regardless of the target SDK version.
  226. //
  227. // Conditional CLC is for compatibility libraries which didn't exist prior to a certain SDK version
  228. // (say, N), but classes in them were in the bootclasspath jars, etc., and in version N they have
  229. // been separated into a standalone <uses-library>. Compatibility libraries should only be in the
  230. // CLC if the library/app that uses them has `targetSdkVersion` less than N in the manifest.
  231. //
  232. // Currently only apps (but not libraries) use conditional CLC.
  233. //
  234. // Target SDK version information is unavailable to the build system at rule generation time, so
  235. // the build system doesn't know whether conditional CLC is needed for a given app or not. So it
  236. // generates a build rule that includes conditional CLC for all versions, extracts the target SDK
  237. // version from the manifest, and filters the CLCs based on that version. Exact final CLC that is
  238. // passed to dex2oat is unknown to the build system, and gets known only at Ninja stage.
  239. type ClassLoaderContextMap map[int][]*ClassLoaderContext
  240. // Compatibility libraries. Some are optional, and some are required: this is the default that
  241. // affects how they are handled by the Soong logic that automatically adds implicit SDK libraries
  242. // to the manifest_fixer, but an explicit `uses_libs`/`optional_uses_libs` can override this.
  243. var OrgApacheHttpLegacy = "org.apache.http.legacy"
  244. var AndroidTestBase = "android.test.base"
  245. var AndroidTestMock = "android.test.mock"
  246. var AndroidHidlBase = "android.hidl.base-V1.0-java"
  247. var AndroidHidlManager = "android.hidl.manager-V1.0-java"
  248. // Compatibility libraries grouped by version/optionality (for convenience, to avoid repeating the
  249. // same lists in multiple places).
  250. var OptionalCompatUsesLibs28 = []string{
  251. OrgApacheHttpLegacy,
  252. }
  253. var OptionalCompatUsesLibs30 = []string{
  254. AndroidTestBase,
  255. AndroidTestMock,
  256. }
  257. var CompatUsesLibs29 = []string{
  258. AndroidHidlManager,
  259. AndroidHidlBase,
  260. }
  261. var OptionalCompatUsesLibs = append(android.CopyOf(OptionalCompatUsesLibs28), OptionalCompatUsesLibs30...)
  262. var CompatUsesLibs = android.CopyOf(CompatUsesLibs29)
  263. const UnknownInstallLibraryPath = "error"
  264. // AnySdkVersion means that the class loader context is needed regardless of the targetSdkVersion
  265. // of the app. The numeric value affects the key order in the map and, as a result, the order of
  266. // arguments passed to construct_context.py (high value means that the unconditional context goes
  267. // last). We use the converntional "current" SDK level (10000), but any big number would do as well.
  268. const AnySdkVersion int = android.FutureApiLevelInt
  269. // Add class loader context for the given library to the map entry for the given SDK version.
  270. func (clcMap ClassLoaderContextMap) addContext(ctx android.ModuleInstallPathContext, sdkVer int, lib string,
  271. optional bool, hostPath, installPath android.Path, nestedClcMap ClassLoaderContextMap) error {
  272. // For prebuilts, library should have the same name as the source module.
  273. lib = android.RemoveOptionalPrebuiltPrefix(lib)
  274. devicePath := UnknownInstallLibraryPath
  275. if installPath == nil {
  276. if android.InList(lib, CompatUsesLibs) || android.InList(lib, OptionalCompatUsesLibs) {
  277. // Assume that compatibility libraries are installed in /system/framework.
  278. installPath = android.PathForModuleInstall(ctx, "framework", lib+".jar")
  279. } else {
  280. // For some stub libraries the only known thing is the name of their implementation
  281. // library, but the library itself is unavailable (missing or part of a prebuilt). In
  282. // such cases we still need to add the library to <uses-library> tags in the manifest,
  283. // but we cannot use it for dexpreopt.
  284. }
  285. }
  286. if installPath != nil {
  287. devicePath = android.InstallPathToOnDevicePath(ctx, installPath.(android.InstallPath))
  288. }
  289. // Nested class loader context shouldn't have conditional part (it is allowed only at the top level).
  290. for ver, _ := range nestedClcMap {
  291. if ver != AnySdkVersion {
  292. _, clcPaths := ComputeClassLoaderContextDependencies(nestedClcMap)
  293. return fmt.Errorf("nested class loader context shouldn't have conditional part: %+v", clcPaths)
  294. }
  295. }
  296. subcontexts := nestedClcMap[AnySdkVersion]
  297. // Check if the library with this name is already present in unconditional top-level CLC.
  298. for _, clc := range clcMap[sdkVer] {
  299. if clc.Name != lib {
  300. // Ok, a different library.
  301. } else if clc.Host == hostPath && clc.Device == devicePath {
  302. // Ok, the same library with the same paths. Don't re-add it, but don't raise an error
  303. // either, as the same library may be reachable via different transitional dependencies.
  304. return nil
  305. } else {
  306. // Fail, as someone is trying to add the same library with different paths. This likely
  307. // indicates an error somewhere else, like trying to add a stub library.
  308. return fmt.Errorf("a <uses-library> named %q is already in class loader context,"+
  309. "but the library paths are different:\t\n", lib)
  310. }
  311. }
  312. clcMap[sdkVer] = append(clcMap[sdkVer], &ClassLoaderContext{
  313. Name: lib,
  314. Optional: optional,
  315. Host: hostPath,
  316. Device: devicePath,
  317. Subcontexts: subcontexts,
  318. })
  319. return nil
  320. }
  321. // Add class loader context for the given SDK version. Don't fail on unknown build/install paths, as
  322. // libraries with unknown paths still need to be processed by manifest_fixer (which doesn't care
  323. // about paths). For the subset of libraries that are used in dexpreopt, their build/install paths
  324. // are validated later before CLC is used (in validateClassLoaderContext).
  325. func (clcMap ClassLoaderContextMap) AddContext(ctx android.ModuleInstallPathContext, sdkVer int,
  326. lib string, optional bool, hostPath, installPath android.Path, nestedClcMap ClassLoaderContextMap) {
  327. err := clcMap.addContext(ctx, sdkVer, lib, optional, hostPath, installPath, nestedClcMap)
  328. if err != nil {
  329. ctx.ModuleErrorf(err.Error())
  330. }
  331. }
  332. // Merge the other class loader context map into this one, do not override existing entries.
  333. // The implicitRootLib parameter is the name of the library for which the other class loader
  334. // context map was constructed. If the implicitRootLib is itself a <uses-library>, it should be
  335. // already present in the class loader context (with the other context as its subcontext) -- in
  336. // that case do not re-add the other context. Otherwise add the other context at the top-level.
  337. func (clcMap ClassLoaderContextMap) AddContextMap(otherClcMap ClassLoaderContextMap, implicitRootLib string) {
  338. if otherClcMap == nil {
  339. return
  340. }
  341. // If the implicit root of the merged map is already present as one of top-level subtrees, do
  342. // not merge it second time.
  343. for _, clc := range clcMap[AnySdkVersion] {
  344. if clc.Name == implicitRootLib {
  345. return
  346. }
  347. }
  348. for sdkVer, otherClcs := range otherClcMap {
  349. for _, otherClc := range otherClcs {
  350. alreadyHave := false
  351. for _, clc := range clcMap[sdkVer] {
  352. if clc.Name == otherClc.Name {
  353. alreadyHave = true
  354. break
  355. }
  356. }
  357. if !alreadyHave {
  358. clcMap[sdkVer] = append(clcMap[sdkVer], otherClc)
  359. }
  360. }
  361. }
  362. }
  363. // Returns top-level libraries in the CLC (conditional CLC, i.e. compatibility libraries are not
  364. // included). This is the list of libraries that should be in the <uses-library> tags in the
  365. // manifest. Some of them may be present in the source manifest, others are added by manifest_fixer.
  366. // Required and optional libraries are in separate lists.
  367. func (clcMap ClassLoaderContextMap) UsesLibs() (required []string, optional []string) {
  368. if clcMap != nil {
  369. clcs := clcMap[AnySdkVersion]
  370. required = make([]string, 0, len(clcs))
  371. optional = make([]string, 0, len(clcs))
  372. for _, clc := range clcs {
  373. if clc.Optional {
  374. optional = append(optional, clc.Name)
  375. } else {
  376. required = append(required, clc.Name)
  377. }
  378. }
  379. }
  380. return required, optional
  381. }
  382. func (clcMap ClassLoaderContextMap) Dump() string {
  383. jsonCLC := toJsonClassLoaderContext(clcMap)
  384. bytes, err := json.MarshalIndent(jsonCLC, "", " ")
  385. if err != nil {
  386. panic(err)
  387. }
  388. return string(bytes)
  389. }
  390. func (clcMap ClassLoaderContextMap) DumpForFlag() string {
  391. jsonCLC := toJsonClassLoaderContext(clcMap)
  392. bytes, err := json.Marshal(jsonCLC)
  393. if err != nil {
  394. panic(err)
  395. }
  396. return proptools.ShellEscapeIncludingSpaces(string(bytes))
  397. }
  398. // excludeLibsFromCLCList excludes the libraries from the ClassLoaderContext in this list.
  399. //
  400. // This treats the supplied list as being immutable (as it may come from a dependency). So, it
  401. // implements copy-on-exclusion logic. That means that if any of the excluded libraries are used
  402. // within the contexts in the list then this will return a deep copy of the list without those
  403. // libraries.
  404. //
  405. // If any of the ClassLoaderContext in the list reference the excluded libraries then this returns a
  406. // copy of this list without the excluded libraries and true to indicate that this was copied.
  407. //
  408. // Otherwise, this returns the list and false to indicate that this was not copied.
  409. func excludeLibsFromCLCList(clcList []*ClassLoaderContext, excludedLibs []string) ([]*ClassLoaderContext, bool) {
  410. modifiedList := false
  411. copiedList := make([]*ClassLoaderContext, 0, len(clcList))
  412. for _, clc := range clcList {
  413. resultClc, modifiedClc := clc.excludeLibs(excludedLibs)
  414. if resultClc != nil {
  415. copiedList = append(copiedList, resultClc)
  416. }
  417. modifiedList = modifiedList || modifiedClc
  418. }
  419. if modifiedList {
  420. return copiedList, true
  421. } else {
  422. return clcList, false
  423. }
  424. }
  425. // ExcludeLibs excludes the libraries from the ClassLoaderContextMap.
  426. //
  427. // If the list o libraries is empty then this returns the ClassLoaderContextMap.
  428. //
  429. // This treats the ClassLoaderContextMap as being immutable (as it may come from a dependency). So,
  430. // it implements copy-on-exclusion logic. That means that if any of the excluded libraries are used
  431. // within the contexts in the map then this will return a deep copy of the map without those
  432. // libraries.
  433. //
  434. // Otherwise, this returns the map unchanged.
  435. func (clcMap ClassLoaderContextMap) ExcludeLibs(excludedLibs []string) ClassLoaderContextMap {
  436. if len(excludedLibs) == 0 {
  437. return clcMap
  438. }
  439. excludedClcMap := make(ClassLoaderContextMap)
  440. modifiedMap := false
  441. for sdkVersion, clcList := range clcMap {
  442. excludedList, modifiedList := excludeLibsFromCLCList(clcList, excludedLibs)
  443. if len(excludedList) != 0 {
  444. excludedClcMap[sdkVersion] = excludedList
  445. }
  446. modifiedMap = modifiedMap || modifiedList
  447. }
  448. if modifiedMap {
  449. return excludedClcMap
  450. } else {
  451. return clcMap
  452. }
  453. }
  454. // Now that the full unconditional context is known, reconstruct conditional context.
  455. // Apply filters for individual libraries, mirroring what the PackageManager does when it
  456. // constructs class loader context on device.
  457. //
  458. // TODO(b/132357300): remove "android.hidl.manager" and "android.hidl.base" for non-system apps.
  459. func fixClassLoaderContext(clcMap ClassLoaderContextMap) {
  460. required, optional := clcMap.UsesLibs()
  461. usesLibs := append(required, optional...)
  462. for sdkVer, clcs := range clcMap {
  463. if sdkVer == AnySdkVersion {
  464. continue
  465. }
  466. fixedClcs := []*ClassLoaderContext{}
  467. for _, clc := range clcs {
  468. if android.InList(clc.Name, usesLibs) {
  469. // skip compatibility libraries that are already included in unconditional context
  470. } else if clc.Name == AndroidTestMock && !android.InList("android.test.runner", usesLibs) {
  471. // android.test.mock is only needed as a compatibility library (in conditional class
  472. // loader context) if android.test.runner is used, otherwise skip it
  473. } else {
  474. fixedClcs = append(fixedClcs, clc)
  475. }
  476. clcMap[sdkVer] = fixedClcs
  477. }
  478. }
  479. }
  480. // Return true if all build/install library paths are valid (including recursive subcontexts),
  481. // otherwise return false. A build path is valid if it's not nil. An install path is valid if it's
  482. // not equal to a special "error" value.
  483. func validateClassLoaderContext(clcMap ClassLoaderContextMap) (bool, error) {
  484. for sdkVer, clcs := range clcMap {
  485. if valid, err := validateClassLoaderContextRec(sdkVer, clcs); !valid || err != nil {
  486. return valid, err
  487. }
  488. }
  489. return true, nil
  490. }
  491. // Helper function for validateClassLoaderContext() that handles recursion.
  492. func validateClassLoaderContextRec(sdkVer int, clcs []*ClassLoaderContext) (bool, error) {
  493. for _, clc := range clcs {
  494. if clc.Host == nil || clc.Device == UnknownInstallLibraryPath {
  495. if sdkVer == AnySdkVersion {
  496. // Return error if dexpreopt doesn't know paths to one of the <uses-library>
  497. // dependencies. In the future we may need to relax this and just disable dexpreopt.
  498. if clc.Host == nil {
  499. return false, fmt.Errorf("invalid build path for <uses-library> \"%s\"", clc.Name)
  500. } else {
  501. return false, fmt.Errorf("invalid install path for <uses-library> \"%s\"", clc.Name)
  502. }
  503. } else {
  504. // No error for compatibility libraries, as Soong doesn't know if they are needed
  505. // (this depends on the targetSdkVersion in the manifest), but the CLC is invalid.
  506. return false, nil
  507. }
  508. }
  509. if valid, err := validateClassLoaderContextRec(sdkVer, clc.Subcontexts); !valid || err != nil {
  510. return valid, err
  511. }
  512. }
  513. return true, nil
  514. }
  515. // Returns a slice of library names and a slice of build paths for all possible dependencies that
  516. // the class loader context may refer to.
  517. // Perform a depth-first preorder traversal of the class loader context tree for each SDK version.
  518. func ComputeClassLoaderContextDependencies(clcMap ClassLoaderContextMap) (names []string, paths android.Paths) {
  519. for _, clcs := range clcMap {
  520. currentNames, currentPaths := ComputeClassLoaderContextDependenciesRec(clcs)
  521. names = append(names, currentNames...)
  522. paths = append(paths, currentPaths...)
  523. }
  524. return android.FirstUniqueStrings(names), android.FirstUniquePaths(paths)
  525. }
  526. // Helper function for ComputeClassLoaderContextDependencies() that handles recursion.
  527. func ComputeClassLoaderContextDependenciesRec(clcs []*ClassLoaderContext) (names []string, paths android.Paths) {
  528. for _, clc := range clcs {
  529. subNames, subPaths := ComputeClassLoaderContextDependenciesRec(clc.Subcontexts)
  530. names = append(names, clc.Name)
  531. paths = append(paths, clc.Host)
  532. names = append(names, subNames...)
  533. paths = append(paths, subPaths...)
  534. }
  535. return names, paths
  536. }
  537. // Class loader contexts that come from Make via JSON dexpreopt.config. JSON CLC representation is
  538. // the same as Soong representation except that SDK versions and paths are represented with strings.
  539. type jsonClassLoaderContext struct {
  540. Name string
  541. Optional bool
  542. Host string
  543. Device string
  544. Subcontexts []*jsonClassLoaderContext
  545. }
  546. // A map from SDK version (represented with a JSON string) to JSON CLCs.
  547. type jsonClassLoaderContextMap map[string][]*jsonClassLoaderContext
  548. // Convert JSON CLC map to Soong represenation.
  549. func fromJsonClassLoaderContext(ctx android.PathContext, jClcMap jsonClassLoaderContextMap) ClassLoaderContextMap {
  550. clcMap := make(ClassLoaderContextMap)
  551. for sdkVerStr, clcs := range jClcMap {
  552. sdkVer, ok := strconv.Atoi(sdkVerStr)
  553. if ok != nil {
  554. if sdkVerStr == "any" {
  555. sdkVer = AnySdkVersion
  556. } else {
  557. android.ReportPathErrorf(ctx, "failed to parse SDK version in dexpreopt.config: '%s'", sdkVerStr)
  558. }
  559. }
  560. clcMap[sdkVer] = fromJsonClassLoaderContextRec(ctx, clcs)
  561. }
  562. return clcMap
  563. }
  564. // Recursive helper for fromJsonClassLoaderContext.
  565. func fromJsonClassLoaderContextRec(ctx android.PathContext, jClcs []*jsonClassLoaderContext) []*ClassLoaderContext {
  566. clcs := make([]*ClassLoaderContext, 0, len(jClcs))
  567. for _, clc := range jClcs {
  568. clcs = append(clcs, &ClassLoaderContext{
  569. Name: clc.Name,
  570. Optional: clc.Optional,
  571. Host: constructPath(ctx, clc.Host),
  572. Device: clc.Device,
  573. Subcontexts: fromJsonClassLoaderContextRec(ctx, clc.Subcontexts),
  574. })
  575. }
  576. return clcs
  577. }
  578. // Convert Soong CLC map to JSON representation for Make.
  579. func toJsonClassLoaderContext(clcMap ClassLoaderContextMap) jsonClassLoaderContextMap {
  580. jClcMap := make(jsonClassLoaderContextMap)
  581. for sdkVer, clcs := range clcMap {
  582. sdkVerStr := fmt.Sprintf("%d", sdkVer)
  583. if sdkVer == AnySdkVersion {
  584. sdkVerStr = "any"
  585. }
  586. jClcMap[sdkVerStr] = toJsonClassLoaderContextRec(clcs)
  587. }
  588. return jClcMap
  589. }
  590. // Recursive helper for toJsonClassLoaderContext.
  591. func toJsonClassLoaderContextRec(clcs []*ClassLoaderContext) []*jsonClassLoaderContext {
  592. jClcs := make([]*jsonClassLoaderContext, len(clcs))
  593. for i, clc := range clcs {
  594. var host string
  595. if clc.Host == nil {
  596. // Defer build failure to when this CLC is actually used.
  597. host = fmt.Sprintf("implementation-jar-for-%s-is-not-available.jar", clc.Name)
  598. } else {
  599. host = clc.Host.String()
  600. }
  601. jClcs[i] = &jsonClassLoaderContext{
  602. Name: clc.Name,
  603. Optional: clc.Optional,
  604. Host: host,
  605. Device: clc.Device,
  606. Subcontexts: toJsonClassLoaderContextRec(clc.Subcontexts),
  607. }
  608. }
  609. return jClcs
  610. }