blob: ebb8959d1816de2bf391098d13f92264620652ba [file] [log] [blame]
Ulya Trafimovicheb268862020-10-20 15:16:38 +01001// 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
15package dexpreopt
16
17import (
Paul Duffinb1b4d852021-07-13 17:03:50 +010018 "encoding/json"
Ulya Trafimovicheb268862020-10-20 15:16:38 +010019 "fmt"
Ulya Trafimovichc9f2b942020-12-23 15:41:29 +000020 "sort"
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +000021 "strconv"
Ulya Trafimovicheb268862020-10-20 15:16:38 +010022 "strings"
23
24 "android/soong/android"
25)
26
Ulya Trafimovich480d1742020-11-20 15:30:03 +000027// This comment describes the following:
28// 1. the concept of class loader context (CLC) and its relation to classpath
29// 2. how PackageManager constructs CLC from shared libraries and their dependencies
30// 3. build-time vs. run-time CLC and why this matters for dexpreopt
31// 4. manifest fixer: a tool that adds missing <uses-library> tags to the manifests
32// 5. build system support for CLC
33//
34// 1. Class loader context
35// -----------------------
36//
37// Java libraries and apps that have run-time dependency on other libraries should list the used
38// libraries in their manifest (AndroidManifest.xml file). Each used library should be specified in
39// a <uses-library> tag that has the library name and an optional attribute specifying if the
40// library is optional or required. Required libraries are necessary for the library/app to run (it
41// will fail at runtime if the library cannot be loaded), and optional libraries are used only if
42// they are present (if not, the library/app can run without them).
43//
44// The libraries listed in <uses-library> tags are in the classpath of a library/app.
45//
46// Besides libraries, an app may also use another APK (for example in the case of split APKs), or
47// anything that gets added by the app dynamically. In general, it is impossible to know at build
48// time what the app may use at runtime. In the build system we focus on the known part: libraries.
49//
50// Class loader context (CLC) is a tree-like structure that describes class loader hierarchy. The
51// build system uses CLC in a more narrow sense: it is a tree of libraries that represents
52// transitive closure of all <uses-library> dependencies of a library/app. The top-level elements of
53// a CLC are the direct <uses-library> dependencies specified in the manifest (aka. classpath). Each
54// node of a CLC tree is a <uses-library> which may have its own <uses-library> sub-nodes.
55//
56// Because <uses-library> dependencies are, in general, a graph and not necessarily a tree, CLC may
57// contain subtrees for the same library multiple times. In other words, CLC is the dependency graph
58// "unfolded" to a tree. The duplication is only on a logical level, and the actual underlying class
59// loaders are not duplicated (at runtime there is a single class loader instance for each library).
60//
61// Example: A has <uses-library> tags B, C and D; C has <uses-library tags> B and D;
62// D has <uses-library> E; B and E have no <uses-library> dependencies. The CLC is:
63// A
64// ├── B
65// ├── C
66// │ ├── B
67// │ └── D
68// │ └── E
69// └── D
70// └── E
71//
72// CLC defines the lookup order of libraries when resolving Java classes used by the library/app.
73// The lookup order is important because libraries may contain duplicate classes, and the class is
74// resolved to the first match.
75//
76// 2. PackageManager and "shared" libraries
77// ----------------------------------------
78//
79// In order to load an APK at runtime, PackageManager (in frameworks/base) creates a CLC. It adds
80// the libraries listed in the <uses-library> tags in the app's manifest as top-level CLC elements.
81// For each of the used libraries PackageManager gets all its <uses-library> dependencies (specified
82// as tags in the manifest of that library) and adds a nested CLC for each dependency. This process
83// continues recursively until all leaf nodes of the constructed CLC tree are libraries that have no
84// <uses-library> dependencies.
85//
86// PackageManager is aware only of "shared" libraries. The definition of "shared" here differs from
87// its usual meaning (as in shared vs. static). In Android, Java "shared" libraries are those listed
88// in /system/etc/permissions/platform.xml file. This file is installed on device. Each entry in it
89// contains the name of a "shared" library, a path to its DEX jar file and a list of dependencies
90// (other "shared" libraries that this one uses at runtime and specifies them in <uses-library> tags
91// in its manifest).
92//
93// In other words, there are two sources of information that allow PackageManager to construct CLC
94// at runtime: <uses-library> tags in the manifests and "shared" library dependencies in
95// /system/etc/permissions/platform.xml.
96//
97// 3. Build-time and run-time CLC and dexpreopt
98// --------------------------------------------
99//
100// CLC is needed not only when loading a library/app, but also when compiling it. Compilation may
101// happen either on device (known as "dexopt") or during the build (known as "dexpreopt"). Since
102// dexopt takes place on device, it has the same information as PackageManager (manifests and
103// shared library dependencies). Dexpreopt, on the other hand, takes place on host and in a totally
104// different environment, and it has to get the same information from the build system (see the
105// section about build system support below).
106//
107// Thus, the build-time CLC used by dexpreopt and the run-time CLC used by PackageManager are
108// the same thing, but computed in two different ways.
109//
110// It is important that build-time and run-time CLCs coincide, otherwise the AOT-compiled code
111// created by dexpreopt will be rejected. In order to check the equality of build-time and
112// run-time CLCs, the dex2oat compiler records build-time CLC in the *.odex files (in the
113// "classpath" field of the OAT file header). To find the stored CLC, use the following command:
114// `oatdump --oat-file=<FILE> | grep '^classpath = '`.
115//
116// Mismatch between build-time and run-time CLC is reported in logcat during boot (search with
117// `logcat | grep -E 'ClassLoaderContext [a-z ]+ mismatch'`. Mismatch is bad for performance, as it
118// forces the library/app to either be dexopted, or to run without any optimizations (e.g. the app's
119// code may need to be extracted in memory from the APK, a very expensive operation).
120//
121// A <uses-library> can be either optional or required. From dexpreopt standpoint, required library
122// must be present at build time (its absence is a build error). An optional library may be either
123// present or absent at build time: if present, it will be added to the CLC, passed to dex2oat and
124// recorded in the *.odex file; otherwise, if the library is absent, it will be skipped and not
125// added to CLC. If there is a mismatch between built-time and run-time status (optional library is
126// present in one case, but not the other), then the build-time and run-time CLCs won't match and
127// the compiled code will be rejected. It is unknown at build time if the library will be present at
128// runtime, therefore either including or excluding it may cause CLC mismatch.
129//
130// 4. Manifest fixer
131// -----------------
132//
133// Sometimes <uses-library> tags are missing from the source manifest of a library/app. This may
134// happen for example if one of the transitive dependencies of the library/app starts using another
135// <uses-library>, and the library/app's manifest isn't updated to include it.
136//
137// Soong can compute some of the missing <uses-library> tags for a given library/app automatically
138// as SDK libraries in the transitive dependency closure of the library/app. The closure is needed
139// because a library/app may depend on a static library that may in turn depend on an SDK library,
140// (possibly transitively via another library).
141//
142// Not all <uses-library> tags can be computed in this way, because some of the <uses-library>
143// dependencies are not SDK libraries, or they are not reachable via transitive dependency closure.
144// But when possible, allowing Soong to calculate the manifest entries is less prone to errors and
145// simplifies maintenance. For example, consider a situation when many apps use some static library
146// that adds a new <uses-library> dependency -- all the apps will have to be updated. That is
147// difficult to maintain.
148//
149// Soong computes the libraries that need to be in the manifest as the top-level libraries in CLC.
150// These libraries are passed to the manifest_fixer.
151//
152// All libraries added to the manifest should be "shared" libraries, so that PackageManager can look
153// up their dependencies and reconstruct the nested subcontexts at runtime. There is no build check
154// to ensure this, it is an assumption.
155//
156// 5. Build system support
157// -----------------------
158//
159// In order to construct CLC for dexpreopt and manifest_fixer, the build system needs to know all
160// <uses-library> dependencies of the dexpreopted library/app (including transitive dependencies).
161// For each <uses-librarry> dependency it needs to know the following information:
162//
163// - the real name of the <uses-library> (it may be different from the module name)
164// - build-time (on host) and run-time (on device) paths to the DEX jar file of the library
165// - whether this library is optional or required
166// - all <uses-library> dependencies
167//
168// Since the build system doesn't have access to the manifest contents (it cannot read manifests at
169// the time of build rule generation), it is necessary to copy this information to the Android.bp
170// and Android.mk files. For blueprints, the relevant properties are `uses_libs` and
171// `optional_uses_libs`. For makefiles, relevant variables are `LOCAL_USES_LIBRARIES` and
172// `LOCAL_OPTIONAL_USES_LIBRARIES`. It is preferable to avoid specifying these properties explicilty
173// when they can be computed automatically by Soong (as the transitive closure of SDK library
174// dependencies).
175//
176// Some of the Java libraries that are used as <uses-library> are not SDK libraries (they are
177// defined as `java_library` rather than `java_sdk_library` in the Android.bp files). In order for
178// the build system to handle them automatically like SDK libraries, it is possible to set a
179// property `provides_uses_lib` or variable `LOCAL_PROVIDES_USES_LIBRARY` on the blueprint/makefile
180// module of such library. This property can also be used to specify real library name in cases
181// when it differs from the module name.
182//
183// Because the information from the manifests has to be duplicated in the Android.bp/Android.mk
184// files, there is a danger that it may get out of sync. To guard against that, the build system
185// generates a rule that checks the metadata in the build files against the contents of a manifest
186// (verify_uses_libraries). The manifest can be available as a source file, or as part of a prebuilt
187// APK. Note that reading the manifests at the Ninja stage of the build is fine, unlike the build
188// rule generation phase.
189//
190// ClassLoaderContext is a structure that represents CLC.
191//
192type ClassLoaderContext struct {
193 // The name of the library.
194 Name string
195
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100196 // If the library is optional or required.
197 Optional bool
198
Ulya Trafimovich480d1742020-11-20 15:30:03 +0000199 // On-host build path to the library dex file (used in dex2oat argument --class-loader-context).
200 Host android.Path
201
202 // On-device install path (used in dex2oat argument --stored-class-loader-context).
203 Device string
204
205 // Nested sub-CLC for dependencies.
206 Subcontexts []*ClassLoaderContext
207}
208
209// ClassLoaderContextMap is a map from SDK version to CLC. There is a special entry with key
210// AnySdkVersion that stores unconditional CLC that is added regardless of the target SDK version.
211//
212// Conditional CLC is for compatibility libraries which didn't exist prior to a certain SDK version
213// (say, N), but classes in them were in the bootclasspath jars, etc., and in version N they have
214// been separated into a standalone <uses-library>. Compatibility libraries should only be in the
215// CLC if the library/app that uses them has `targetSdkVersion` less than N in the manifest.
216//
217// Currently only apps (but not libraries) use conditional CLC.
218//
219// Target SDK version information is unavailable to the build system at rule generation time, so
220// the build system doesn't know whether conditional CLC is needed for a given app or not. So it
221// generates a build rule that includes conditional CLC for all versions, extracts the target SDK
222// version from the manifest, and filters the CLCs based on that version. Exact final CLC that is
223// passed to dex2oat is unknown to the build system, and gets known only at Ninja stage.
224//
225type ClassLoaderContextMap map[int][]*ClassLoaderContext
226
227// Compatibility libraries. Some are optional, and some are required: this is the default that
228// affects how they are handled by the Soong logic that automatically adds implicit SDK libraries
229// to the manifest_fixer, but an explicit `uses_libs`/`optional_uses_libs` can override this.
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100230var OrgApacheHttpLegacy = "org.apache.http.legacy"
231var AndroidTestBase = "android.test.base"
232var AndroidTestMock = "android.test.mock"
233var AndroidHidlBase = "android.hidl.base-V1.0-java"
234var AndroidHidlManager = "android.hidl.manager-V1.0-java"
235
Ulya Trafimovich480d1742020-11-20 15:30:03 +0000236// Compatibility libraries grouped by version/optionality (for convenience, to avoid repeating the
237// same lists in multiple places).
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100238var OptionalCompatUsesLibs28 = []string{
239 OrgApacheHttpLegacy,
240}
241var OptionalCompatUsesLibs30 = []string{
242 AndroidTestBase,
243 AndroidTestMock,
244}
245var CompatUsesLibs29 = []string{
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100246 AndroidHidlManager,
Ulya Trafimovichc9f2b942020-12-23 15:41:29 +0000247 AndroidHidlBase,
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100248}
249var OptionalCompatUsesLibs = append(android.CopyOf(OptionalCompatUsesLibs28), OptionalCompatUsesLibs30...)
250var CompatUsesLibs = android.CopyOf(CompatUsesLibs29)
251
252const UnknownInstallLibraryPath = "error"
253
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000254// AnySdkVersion means that the class loader context is needed regardless of the targetSdkVersion
255// of the app. The numeric value affects the key order in the map and, as a result, the order of
256// arguments passed to construct_context.py (high value means that the unconditional context goes
257// last). We use the converntional "current" SDK level (10000), but any big number would do as well.
258const AnySdkVersion int = android.FutureApiLevelInt
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100259
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000260// Add class loader context for the given library to the map entry for the given SDK version.
261func (clcMap ClassLoaderContextMap) addContext(ctx android.ModuleInstallPathContext, sdkVer int, lib string,
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100262 optional bool, hostPath, installPath android.Path, nestedClcMap ClassLoaderContextMap) error {
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100263
Ulya Trafimovich69c1aa92021-07-14 16:07:41 +0100264 // For prebuilts, library should have the same name as the source module.
265 lib = android.RemoveOptionalPrebuiltPrefix(lib)
266
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000267 devicePath := UnknownInstallLibraryPath
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100268 if installPath == nil {
269 if android.InList(lib, CompatUsesLibs) || android.InList(lib, OptionalCompatUsesLibs) {
270 // Assume that compatibility libraries are installed in /system/framework.
271 installPath = android.PathForModuleInstall(ctx, "framework", lib+".jar")
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100272 } else {
273 // For some stub libraries the only known thing is the name of their implementation
274 // library, but the library itself is unavailable (missing or part of a prebuilt). In
275 // such cases we still need to add the library to <uses-library> tags in the manifest,
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000276 // but we cannot use it for dexpreopt.
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100277 }
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100278 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000279 if installPath != nil {
280 devicePath = android.InstallPathToOnDevicePath(ctx, installPath.(android.InstallPath))
281 }
282
Ulya Trafimovich5e13a732020-11-03 15:33:03 +0000283 // Nested class loader context shouldn't have conditional part (it is allowed only at the top level).
284 for ver, _ := range nestedClcMap {
285 if ver != AnySdkVersion {
286 clcStr, _ := ComputeClassLoaderContext(nestedClcMap)
287 return fmt.Errorf("nested class loader context shouldn't have conditional part: %s", clcStr)
288 }
289 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000290 subcontexts := nestedClcMap[AnySdkVersion]
291
Ulya Trafimovich840efb62021-07-15 14:34:40 +0100292 // Check if the library with this name is already present in unconditional top-level CLC.
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000293 for _, clc := range clcMap[sdkVer] {
Ulya Trafimovich840efb62021-07-15 14:34:40 +0100294 if clc.Name != lib {
295 // Ok, a different library.
296 } else if clc.Host == hostPath && clc.Device == devicePath {
297 // Ok, the same library with the same paths. Don't re-add it, but don't raise an error
298 // either, as the same library may be reachable via different transitional dependencies.
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000299 return nil
Ulya Trafimovich840efb62021-07-15 14:34:40 +0100300 } else {
301 // Fail, as someone is trying to add the same library with different paths. This likely
302 // indicates an error somewhere else, like trying to add a stub library.
303 return fmt.Errorf("a <uses-library> named %q is already in class loader context,"+
304 "but the library paths are different:\t\n", lib)
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000305 }
306 }
307
308 clcMap[sdkVer] = append(clcMap[sdkVer], &ClassLoaderContext{
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000309 Name: lib,
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100310 Optional: optional,
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000311 Host: hostPath,
312 Device: devicePath,
313 Subcontexts: subcontexts,
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000314 })
Ulya Trafimovich69612672020-10-20 17:41:54 +0100315 return nil
316}
317
Ulya Trafimovich88bb6f62020-12-16 16:16:11 +0000318// Add class loader context for the given SDK version. Don't fail on unknown build/install paths, as
319// libraries with unknown paths still need to be processed by manifest_fixer (which doesn't care
320// about paths). For the subset of libraries that are used in dexpreopt, their build/install paths
321// are validated later before CLC is used (in validateClassLoaderContext).
Ulya Trafimovich7bc1cf52021-01-05 15:41:55 +0000322func (clcMap ClassLoaderContextMap) AddContext(ctx android.ModuleInstallPathContext, sdkVer int,
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100323 lib string, optional bool, hostPath, installPath android.Path, nestedClcMap ClassLoaderContextMap) {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000324
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100325 err := clcMap.addContext(ctx, sdkVer, lib, optional, hostPath, installPath, nestedClcMap)
Ulya Trafimovich7bc1cf52021-01-05 15:41:55 +0000326 if err != nil {
327 ctx.ModuleErrorf(err.Error())
328 }
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100329}
330
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000331// Merge the other class loader context map into this one, do not override existing entries.
Ulya Trafimovich18554242020-11-03 15:55:11 +0000332// The implicitRootLib parameter is the name of the library for which the other class loader
333// context map was constructed. If the implicitRootLib is itself a <uses-library>, it should be
334// already present in the class loader context (with the other context as its subcontext) -- in
335// that case do not re-add the other context. Otherwise add the other context at the top-level.
336func (clcMap ClassLoaderContextMap) AddContextMap(otherClcMap ClassLoaderContextMap, implicitRootLib string) {
337 if otherClcMap == nil {
338 return
339 }
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
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000349 for sdkVer, otherClcs := range otherClcMap {
350 for _, otherClc := range otherClcs {
351 alreadyHave := false
352 for _, clc := range clcMap[sdkVer] {
353 if clc.Name == otherClc.Name {
354 alreadyHave = true
355 break
356 }
357 }
358 if !alreadyHave {
359 clcMap[sdkVer] = append(clcMap[sdkVer], otherClc)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100360 }
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100361 }
362 }
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100363}
364
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000365// Returns top-level libraries in the CLC (conditional CLC, i.e. compatibility libraries are not
366// included). This is the list of libraries that should be in the <uses-library> tags in the
367// manifest. Some of them may be present in the source manifest, others are added by manifest_fixer.
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100368// Required and optional libraries are in separate lists.
369func (clcMap ClassLoaderContextMap) UsesLibs() (required []string, optional []string) {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000370 if clcMap != nil {
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000371 clcs := clcMap[AnySdkVersion]
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100372 required = make([]string, 0, len(clcs))
373 optional = make([]string, 0, len(clcs))
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000374 for _, clc := range clcs {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100375 if clc.Optional {
376 optional = append(optional, clc.Name)
377 } else {
378 required = append(required, clc.Name)
379 }
Ulya Trafimovicha8c28e22020-10-06 17:24:19 +0100380 }
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100381 }
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100382 return required, optional
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100383}
384
Paul Duffinb1b4d852021-07-13 17:03:50 +0100385func (clcMap ClassLoaderContextMap) Dump() string {
386 jsonCLC := toJsonClassLoaderContext(clcMap)
387 bytes, err := json.MarshalIndent(jsonCLC, "", " ")
388 if err != nil {
389 panic(err)
390 }
391 return string(bytes)
392}
393
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100394// Now that the full unconditional context is known, reconstruct conditional context.
395// Apply filters for individual libraries, mirroring what the PackageManager does when it
396// constructs class loader context on device.
397//
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000398// TODO(b/132357300): remove "android.hidl.manager" and "android.hidl.base" for non-system apps.
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100399//
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000400func fixClassLoaderContext(clcMap ClassLoaderContextMap) {
Ulya Trafimovichfc0f6e32021-08-12 16:16:11 +0100401 required, optional := clcMap.UsesLibs()
402 usesLibs := append(required, optional...)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100403
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000404 for sdkVer, clcs := range clcMap {
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100405 if sdkVer == AnySdkVersion {
406 continue
407 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000408 fixedClcs := []*ClassLoaderContext{}
409 for _, clc := range clcs {
410 if android.InList(clc.Name, usesLibs) {
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100411 // skip compatibility libraries that are already included in unconditional context
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000412 } else if clc.Name == AndroidTestMock && !android.InList("android.test.runner", usesLibs) {
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100413 // android.test.mock is only needed as a compatibility library (in conditional class
414 // loader context) if android.test.runner is used, otherwise skip it
415 } else {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000416 fixedClcs = append(fixedClcs, clc)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100417 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000418 clcMap[sdkVer] = fixedClcs
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100419 }
420 }
421}
422
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000423// Return true if all build/install library paths are valid (including recursive subcontexts),
424// otherwise return false. A build path is valid if it's not nil. An install path is valid if it's
425// not equal to a special "error" value.
426func validateClassLoaderContext(clcMap ClassLoaderContextMap) (bool, error) {
427 for sdkVer, clcs := range clcMap {
428 if valid, err := validateClassLoaderContextRec(sdkVer, clcs); !valid || err != nil {
429 return valid, err
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100430 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000431 }
432 return true, nil
433}
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100434
Ulya Trafimovich480d1742020-11-20 15:30:03 +0000435// Helper function for validateClassLoaderContext() that handles recursion.
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000436func validateClassLoaderContextRec(sdkVer int, clcs []*ClassLoaderContext) (bool, error) {
437 for _, clc := range clcs {
438 if clc.Host == nil || clc.Device == UnknownInstallLibraryPath {
439 if sdkVer == AnySdkVersion {
440 // Return error if dexpreopt doesn't know paths to one of the <uses-library>
441 // dependencies. In the future we may need to relax this and just disable dexpreopt.
Ulya Trafimovich78210f62020-12-02 13:06:47 +0000442 if clc.Host == nil {
443 return false, fmt.Errorf("invalid build path for <uses-library> \"%s\"", clc.Name)
444 } else {
445 return false, fmt.Errorf("invalid install path for <uses-library> \"%s\"", clc.Name)
446 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000447 } else {
448 // No error for compatibility libraries, as Soong doesn't know if they are needed
449 // (this depends on the targetSdkVersion in the manifest), but the CLC is invalid.
450 return false, nil
451 }
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100452 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000453 if valid, err := validateClassLoaderContextRec(sdkVer, clc.Subcontexts); !valid || err != nil {
454 return valid, err
455 }
456 }
457 return true, nil
458}
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100459
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000460// Return the class loader context as a string, and a slice of build paths for all dependencies.
461// Perform a depth-first preorder traversal of the class loader context tree for each SDK version.
462// Return the resulting string and a slice of on-host build paths to all library dependencies.
463func ComputeClassLoaderContext(clcMap ClassLoaderContextMap) (clcStr string, paths android.Paths) {
Ulya Trafimovichc9f2b942020-12-23 15:41:29 +0000464 // CLC for different SDK versions should come in specific order that agrees with PackageManager.
465 // Since PackageManager processes SDK versions in ascending order and prepends compatibility
466 // libraries at the front, the required order is descending, except for AnySdkVersion that has
467 // numerically the largest order, but must be the last one. Example of correct order: [30, 29,
468 // 28, AnySdkVersion]. There are Soong tests to ensure that someone doesn't change this by
469 // accident, but there is no way to guard against changes in the PackageManager, except for
470 // grepping logcat on the first boot for absence of the following messages:
471 //
472 // `logcat | grep -E 'ClassLoaderContext [a-z ]+ mismatch`
473 //
474 versions := make([]int, 0, len(clcMap))
475 for ver, _ := range clcMap {
476 if ver != AnySdkVersion {
477 versions = append(versions, ver)
478 }
479 }
480 sort.Sort(sort.Reverse(sort.IntSlice(versions))) // descending order
481 versions = append(versions, AnySdkVersion)
482
483 for _, sdkVer := range versions {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000484 sdkVerStr := fmt.Sprintf("%d", sdkVer)
485 if sdkVer == AnySdkVersion {
486 sdkVerStr = "any" // a special keyword that means any SDK version
487 }
488 hostClc, targetClc, hostPaths := computeClassLoaderContextRec(clcMap[sdkVer])
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100489 if hostPaths != nil {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000490 clcStr += fmt.Sprintf(" --host-context-for-sdk %s %s", sdkVerStr, hostClc)
491 clcStr += fmt.Sprintf(" --target-context-for-sdk %s %s", sdkVerStr, targetClc)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100492 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000493 paths = append(paths, hostPaths...)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100494 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000495 return clcStr, android.FirstUniquePaths(paths)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100496}
497
Ulya Trafimovich480d1742020-11-20 15:30:03 +0000498// Helper function for ComputeClassLoaderContext() that handles recursion.
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000499func computeClassLoaderContextRec(clcs []*ClassLoaderContext) (string, string, android.Paths) {
500 var paths android.Paths
501 var clcsHost, clcsTarget []string
502
503 for _, clc := range clcs {
504 subClcHost, subClcTarget, subPaths := computeClassLoaderContextRec(clc.Subcontexts)
505 if subPaths != nil {
506 subClcHost = "{" + subClcHost + "}"
507 subClcTarget = "{" + subClcTarget + "}"
508 }
509
510 clcsHost = append(clcsHost, "PCL["+clc.Host.String()+"]"+subClcHost)
511 clcsTarget = append(clcsTarget, "PCL["+clc.Device+"]"+subClcTarget)
512
513 paths = append(paths, clc.Host)
514 paths = append(paths, subPaths...)
515 }
516
517 clcHost := strings.Join(clcsHost, "#")
518 clcTarget := strings.Join(clcsTarget, "#")
519
520 return clcHost, clcTarget, paths
521}
522
Ulya Trafimovich5ec68892020-12-08 17:52:34 +0000523// Class loader contexts that come from Make via JSON dexpreopt.config. JSON CLC representation is
Ulya Trafimovich65556a82021-02-11 16:48:53 +0000524// the same as Soong representation except that SDK versions and paths are represented with strings.
Ulya Trafimovich5ec68892020-12-08 17:52:34 +0000525type jsonClassLoaderContext struct {
Ulya Trafimovich65556a82021-02-11 16:48:53 +0000526 Name string
Ulya Trafimovich5ec68892020-12-08 17:52:34 +0000527 Host string
528 Device string
Ulya Trafimovich65556a82021-02-11 16:48:53 +0000529 Subcontexts []*jsonClassLoaderContext
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100530}
531
Ulya Trafimovich5ec68892020-12-08 17:52:34 +0000532// A map from SDK version (represented with a JSON string) to JSON CLCs.
Ulya Trafimovich65556a82021-02-11 16:48:53 +0000533type jsonClassLoaderContextMap map[string][]*jsonClassLoaderContext
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000534
Ulya Trafimovich5ec68892020-12-08 17:52:34 +0000535// Convert JSON CLC map to Soong represenation.
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000536func fromJsonClassLoaderContext(ctx android.PathContext, jClcMap jsonClassLoaderContextMap) ClassLoaderContextMap {
537 clcMap := make(ClassLoaderContextMap)
Ulya Trafimovich5ec68892020-12-08 17:52:34 +0000538 for sdkVerStr, clcs := range jClcMap {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000539 sdkVer, ok := strconv.Atoi(sdkVerStr)
540 if ok != nil {
541 if sdkVerStr == "any" {
542 sdkVer = AnySdkVersion
543 } else {
544 android.ReportPathErrorf(ctx, "failed to parse SDK version in dexpreopt.config: '%s'", sdkVerStr)
545 }
546 }
Ulya Trafimovich5ec68892020-12-08 17:52:34 +0000547 clcMap[sdkVer] = fromJsonClassLoaderContextRec(ctx, clcs)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100548 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000549 return clcMap
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100550}
Ulya Trafimovich5ec68892020-12-08 17:52:34 +0000551
552// Recursive helper for fromJsonClassLoaderContext.
Ulya Trafimovich65556a82021-02-11 16:48:53 +0000553func fromJsonClassLoaderContextRec(ctx android.PathContext, jClcs []*jsonClassLoaderContext) []*ClassLoaderContext {
Ulya Trafimovich5ec68892020-12-08 17:52:34 +0000554 clcs := make([]*ClassLoaderContext, 0, len(jClcs))
Ulya Trafimovich65556a82021-02-11 16:48:53 +0000555 for _, clc := range jClcs {
Ulya Trafimovich5ec68892020-12-08 17:52:34 +0000556 clcs = append(clcs, &ClassLoaderContext{
Ulya Trafimovich65556a82021-02-11 16:48:53 +0000557 Name: clc.Name,
Ulya Trafimovich5ec68892020-12-08 17:52:34 +0000558 Host: constructPath(ctx, clc.Host),
559 Device: clc.Device,
560 Subcontexts: fromJsonClassLoaderContextRec(ctx, clc.Subcontexts),
561 })
562 }
563 return clcs
564}
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000565
566// Convert Soong CLC map to JSON representation for Make.
567func toJsonClassLoaderContext(clcMap ClassLoaderContextMap) jsonClassLoaderContextMap {
568 jClcMap := make(jsonClassLoaderContextMap)
569 for sdkVer, clcs := range clcMap {
570 sdkVerStr := fmt.Sprintf("%d", sdkVer)
571 jClcMap[sdkVerStr] = toJsonClassLoaderContextRec(clcs)
572 }
573 return jClcMap
574}
575
576// Recursive helper for toJsonClassLoaderContext.
Ulya Trafimovich65556a82021-02-11 16:48:53 +0000577func toJsonClassLoaderContextRec(clcs []*ClassLoaderContext) []*jsonClassLoaderContext {
578 jClcs := make([]*jsonClassLoaderContext, len(clcs))
Jeongik Cha19ade892021-04-22 20:55:21 +0900579 for i, clc := range clcs {
580 jClcs[i] = &jsonClassLoaderContext{
Ulya Trafimovich65556a82021-02-11 16:48:53 +0000581 Name: clc.Name,
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000582 Host: clc.Host.String(),
583 Device: clc.Device,
584 Subcontexts: toJsonClassLoaderContextRec(clc.Subcontexts),
Jeongik Cha19ade892021-04-22 20:55:21 +0900585 }
Ulya Trafimovich76b08522021-01-14 17:52:43 +0000586 }
587 return jClcs
588}