blob: deaf77fe47a8df4513a96fae267a1d41cdc27af7 [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 (
18 "fmt"
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +000019 "strconv"
Ulya Trafimovicheb268862020-10-20 15:16:38 +010020 "strings"
21
22 "android/soong/android"
23)
24
Ulya Trafimovich480d1742020-11-20 15:30:03 +000025// This comment describes the following:
26// 1. the concept of class loader context (CLC) and its relation to classpath
27// 2. how PackageManager constructs CLC from shared libraries and their dependencies
28// 3. build-time vs. run-time CLC and why this matters for dexpreopt
29// 4. manifest fixer: a tool that adds missing <uses-library> tags to the manifests
30// 5. build system support for CLC
31//
32// 1. Class loader context
33// -----------------------
34//
35// Java libraries and apps that have run-time dependency on other libraries should list the used
36// libraries in their manifest (AndroidManifest.xml file). Each used library should be specified in
37// a <uses-library> tag that has the library name and an optional attribute specifying if the
38// library is optional or required. Required libraries are necessary for the library/app to run (it
39// will fail at runtime if the library cannot be loaded), and optional libraries are used only if
40// they are present (if not, the library/app can run without them).
41//
42// The libraries listed in <uses-library> tags are in the classpath of a library/app.
43//
44// Besides libraries, an app may also use another APK (for example in the case of split APKs), or
45// anything that gets added by the app dynamically. In general, it is impossible to know at build
46// time what the app may use at runtime. In the build system we focus on the known part: libraries.
47//
48// Class loader context (CLC) is a tree-like structure that describes class loader hierarchy. The
49// build system uses CLC in a more narrow sense: it is a tree of libraries that represents
50// transitive closure of all <uses-library> dependencies of a library/app. The top-level elements of
51// a CLC are the direct <uses-library> dependencies specified in the manifest (aka. classpath). Each
52// node of a CLC tree is a <uses-library> which may have its own <uses-library> sub-nodes.
53//
54// Because <uses-library> dependencies are, in general, a graph and not necessarily a tree, CLC may
55// contain subtrees for the same library multiple times. In other words, CLC is the dependency graph
56// "unfolded" to a tree. The duplication is only on a logical level, and the actual underlying class
57// loaders are not duplicated (at runtime there is a single class loader instance for each library).
58//
59// Example: A has <uses-library> tags B, C and D; C has <uses-library tags> B and D;
60// D has <uses-library> E; B and E have no <uses-library> dependencies. The CLC is:
61// A
62// ├── B
63// ├── C
64// │ ├── B
65// │ └── D
66// │ └── E
67// └── D
68// └── E
69//
70// CLC defines the lookup order of libraries when resolving Java classes used by the library/app.
71// The lookup order is important because libraries may contain duplicate classes, and the class is
72// resolved to the first match.
73//
74// 2. PackageManager and "shared" libraries
75// ----------------------------------------
76//
77// In order to load an APK at runtime, PackageManager (in frameworks/base) creates a CLC. It adds
78// the libraries listed in the <uses-library> tags in the app's manifest as top-level CLC elements.
79// For each of the used libraries PackageManager gets all its <uses-library> dependencies (specified
80// as tags in the manifest of that library) and adds a nested CLC for each dependency. This process
81// continues recursively until all leaf nodes of the constructed CLC tree are libraries that have no
82// <uses-library> dependencies.
83//
84// PackageManager is aware only of "shared" libraries. The definition of "shared" here differs from
85// its usual meaning (as in shared vs. static). In Android, Java "shared" libraries are those listed
86// in /system/etc/permissions/platform.xml file. This file is installed on device. Each entry in it
87// contains the name of a "shared" library, a path to its DEX jar file and a list of dependencies
88// (other "shared" libraries that this one uses at runtime and specifies them in <uses-library> tags
89// in its manifest).
90//
91// In other words, there are two sources of information that allow PackageManager to construct CLC
92// at runtime: <uses-library> tags in the manifests and "shared" library dependencies in
93// /system/etc/permissions/platform.xml.
94//
95// 3. Build-time and run-time CLC and dexpreopt
96// --------------------------------------------
97//
98// CLC is needed not only when loading a library/app, but also when compiling it. Compilation may
99// happen either on device (known as "dexopt") or during the build (known as "dexpreopt"). Since
100// dexopt takes place on device, it has the same information as PackageManager (manifests and
101// shared library dependencies). Dexpreopt, on the other hand, takes place on host and in a totally
102// different environment, and it has to get the same information from the build system (see the
103// section about build system support below).
104//
105// Thus, the build-time CLC used by dexpreopt and the run-time CLC used by PackageManager are
106// the same thing, but computed in two different ways.
107//
108// It is important that build-time and run-time CLCs coincide, otherwise the AOT-compiled code
109// created by dexpreopt will be rejected. In order to check the equality of build-time and
110// run-time CLCs, the dex2oat compiler records build-time CLC in the *.odex files (in the
111// "classpath" field of the OAT file header). To find the stored CLC, use the following command:
112// `oatdump --oat-file=<FILE> | grep '^classpath = '`.
113//
114// Mismatch between build-time and run-time CLC is reported in logcat during boot (search with
115// `logcat | grep -E 'ClassLoaderContext [a-z ]+ mismatch'`. Mismatch is bad for performance, as it
116// forces the library/app to either be dexopted, or to run without any optimizations (e.g. the app's
117// code may need to be extracted in memory from the APK, a very expensive operation).
118//
119// A <uses-library> can be either optional or required. From dexpreopt standpoint, required library
120// must be present at build time (its absence is a build error). An optional library may be either
121// present or absent at build time: if present, it will be added to the CLC, passed to dex2oat and
122// recorded in the *.odex file; otherwise, if the library is absent, it will be skipped and not
123// added to CLC. If there is a mismatch between built-time and run-time status (optional library is
124// present in one case, but not the other), then the build-time and run-time CLCs won't match and
125// the compiled code will be rejected. It is unknown at build time if the library will be present at
126// runtime, therefore either including or excluding it may cause CLC mismatch.
127//
128// 4. Manifest fixer
129// -----------------
130//
131// Sometimes <uses-library> tags are missing from the source manifest of a library/app. This may
132// happen for example if one of the transitive dependencies of the library/app starts using another
133// <uses-library>, and the library/app's manifest isn't updated to include it.
134//
135// Soong can compute some of the missing <uses-library> tags for a given library/app automatically
136// as SDK libraries in the transitive dependency closure of the library/app. The closure is needed
137// because a library/app may depend on a static library that may in turn depend on an SDK library,
138// (possibly transitively via another library).
139//
140// Not all <uses-library> tags can be computed in this way, because some of the <uses-library>
141// dependencies are not SDK libraries, or they are not reachable via transitive dependency closure.
142// But when possible, allowing Soong to calculate the manifest entries is less prone to errors and
143// simplifies maintenance. For example, consider a situation when many apps use some static library
144// that adds a new <uses-library> dependency -- all the apps will have to be updated. That is
145// difficult to maintain.
146//
147// Soong computes the libraries that need to be in the manifest as the top-level libraries in CLC.
148// These libraries are passed to the manifest_fixer.
149//
150// All libraries added to the manifest should be "shared" libraries, so that PackageManager can look
151// up their dependencies and reconstruct the nested subcontexts at runtime. There is no build check
152// to ensure this, it is an assumption.
153//
154// 5. Build system support
155// -----------------------
156//
157// In order to construct CLC for dexpreopt and manifest_fixer, the build system needs to know all
158// <uses-library> dependencies of the dexpreopted library/app (including transitive dependencies).
159// For each <uses-librarry> dependency it needs to know the following information:
160//
161// - the real name of the <uses-library> (it may be different from the module name)
162// - build-time (on host) and run-time (on device) paths to the DEX jar file of the library
163// - whether this library is optional or required
164// - all <uses-library> dependencies
165//
166// Since the build system doesn't have access to the manifest contents (it cannot read manifests at
167// the time of build rule generation), it is necessary to copy this information to the Android.bp
168// and Android.mk files. For blueprints, the relevant properties are `uses_libs` and
169// `optional_uses_libs`. For makefiles, relevant variables are `LOCAL_USES_LIBRARIES` and
170// `LOCAL_OPTIONAL_USES_LIBRARIES`. It is preferable to avoid specifying these properties explicilty
171// when they can be computed automatically by Soong (as the transitive closure of SDK library
172// dependencies).
173//
174// Some of the Java libraries that are used as <uses-library> are not SDK libraries (they are
175// defined as `java_library` rather than `java_sdk_library` in the Android.bp files). In order for
176// the build system to handle them automatically like SDK libraries, it is possible to set a
177// property `provides_uses_lib` or variable `LOCAL_PROVIDES_USES_LIBRARY` on the blueprint/makefile
178// module of such library. This property can also be used to specify real library name in cases
179// when it differs from the module name.
180//
181// Because the information from the manifests has to be duplicated in the Android.bp/Android.mk
182// files, there is a danger that it may get out of sync. To guard against that, the build system
183// generates a rule that checks the metadata in the build files against the contents of a manifest
184// (verify_uses_libraries). The manifest can be available as a source file, or as part of a prebuilt
185// APK. Note that reading the manifests at the Ninja stage of the build is fine, unlike the build
186// rule generation phase.
187//
188// ClassLoaderContext is a structure that represents CLC.
189//
190type ClassLoaderContext struct {
191 // The name of the library.
192 Name string
193
194 // On-host build path to the library dex file (used in dex2oat argument --class-loader-context).
195 Host android.Path
196
197 // On-device install path (used in dex2oat argument --stored-class-loader-context).
198 Device string
199
200 // Nested sub-CLC for dependencies.
201 Subcontexts []*ClassLoaderContext
202}
203
204// ClassLoaderContextMap is a map from SDK version to CLC. There is a special entry with key
205// AnySdkVersion that stores unconditional CLC that is added regardless of the target SDK version.
206//
207// Conditional CLC is for compatibility libraries which didn't exist prior to a certain SDK version
208// (say, N), but classes in them were in the bootclasspath jars, etc., and in version N they have
209// been separated into a standalone <uses-library>. Compatibility libraries should only be in the
210// CLC if the library/app that uses them has `targetSdkVersion` less than N in the manifest.
211//
212// Currently only apps (but not libraries) use conditional CLC.
213//
214// Target SDK version information is unavailable to the build system at rule generation time, so
215// the build system doesn't know whether conditional CLC is needed for a given app or not. So it
216// generates a build rule that includes conditional CLC for all versions, extracts the target SDK
217// version from the manifest, and filters the CLCs based on that version. Exact final CLC that is
218// passed to dex2oat is unknown to the build system, and gets known only at Ninja stage.
219//
220type ClassLoaderContextMap map[int][]*ClassLoaderContext
221
222// Compatibility libraries. Some are optional, and some are required: this is the default that
223// affects how they are handled by the Soong logic that automatically adds implicit SDK libraries
224// to the manifest_fixer, but an explicit `uses_libs`/`optional_uses_libs` can override this.
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100225var OrgApacheHttpLegacy = "org.apache.http.legacy"
226var AndroidTestBase = "android.test.base"
227var AndroidTestMock = "android.test.mock"
228var AndroidHidlBase = "android.hidl.base-V1.0-java"
229var AndroidHidlManager = "android.hidl.manager-V1.0-java"
230
Ulya Trafimovich480d1742020-11-20 15:30:03 +0000231// Compatibility libraries grouped by version/optionality (for convenience, to avoid repeating the
232// same lists in multiple places).
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100233var OptionalCompatUsesLibs28 = []string{
234 OrgApacheHttpLegacy,
235}
236var OptionalCompatUsesLibs30 = []string{
237 AndroidTestBase,
238 AndroidTestMock,
239}
240var CompatUsesLibs29 = []string{
241 AndroidHidlBase,
242 AndroidHidlManager,
243}
244var OptionalCompatUsesLibs = append(android.CopyOf(OptionalCompatUsesLibs28), OptionalCompatUsesLibs30...)
245var CompatUsesLibs = android.CopyOf(CompatUsesLibs29)
246
247const UnknownInstallLibraryPath = "error"
248
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000249// AnySdkVersion means that the class loader context is needed regardless of the targetSdkVersion
250// of the app. The numeric value affects the key order in the map and, as a result, the order of
251// arguments passed to construct_context.py (high value means that the unconditional context goes
252// last). We use the converntional "current" SDK level (10000), but any big number would do as well.
253const AnySdkVersion int = android.FutureApiLevelInt
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100254
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000255// Add class loader context for the given library to the map entry for the given SDK version.
256func (clcMap ClassLoaderContextMap) addContext(ctx android.ModuleInstallPathContext, sdkVer int, lib string,
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000257 hostPath, installPath android.Path, strict bool, nestedClcMap ClassLoaderContextMap) error {
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100258
259 // If missing dependencies are allowed, the build shouldn't fail when a <uses-library> is
260 // not found. However, this is likely to result is disabling dexpreopt, as it won't be
261 // possible to construct class loader context without on-host and on-device library paths.
262 strict = strict && !ctx.Config().AllowMissingDependencies()
263
264 if hostPath == nil && strict {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000265 return fmt.Errorf("unknown build path to <uses-library> \"%s\"", lib)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100266 }
267
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000268 devicePath := UnknownInstallLibraryPath
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100269 if installPath == nil {
270 if android.InList(lib, CompatUsesLibs) || android.InList(lib, OptionalCompatUsesLibs) {
271 // Assume that compatibility libraries are installed in /system/framework.
272 installPath = android.PathForModuleInstall(ctx, "framework", lib+".jar")
273 } else if strict {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000274 return fmt.Errorf("unknown install path to <uses-library> \"%s\"", lib)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100275 } else {
276 // For some stub libraries the only known thing is the name of their implementation
277 // library, but the library itself is unavailable (missing or part of a prebuilt). In
278 // such cases we still need to add the library to <uses-library> tags in the manifest,
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000279 // but we cannot use it for dexpreopt.
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100280 }
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100281 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000282 if installPath != nil {
283 devicePath = android.InstallPathToOnDevicePath(ctx, installPath.(android.InstallPath))
284 }
285
Ulya Trafimovich5e13a732020-11-03 15:33:03 +0000286 // Nested class loader context shouldn't have conditional part (it is allowed only at the top level).
287 for ver, _ := range nestedClcMap {
288 if ver != AnySdkVersion {
289 clcStr, _ := ComputeClassLoaderContext(nestedClcMap)
290 return fmt.Errorf("nested class loader context shouldn't have conditional part: %s", clcStr)
291 }
292 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000293 subcontexts := nestedClcMap[AnySdkVersion]
294
295 // If the library with this name is already present as one of the unconditional top-level
296 // components, do not re-add it.
297 for _, clc := range clcMap[sdkVer] {
298 if clc.Name == lib {
299 return nil
300 }
301 }
302
303 clcMap[sdkVer] = append(clcMap[sdkVer], &ClassLoaderContext{
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000304 Name: lib,
305 Host: hostPath,
306 Device: devicePath,
307 Subcontexts: subcontexts,
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000308 })
Ulya Trafimovich69612672020-10-20 17:41:54 +0100309 return nil
310}
311
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000312// Wrapper around addContext that reports errors.
313func (clcMap ClassLoaderContextMap) addContextOrReportError(ctx android.ModuleInstallPathContext, sdkVer int, lib string,
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000314 hostPath, installPath android.Path, strict bool, nestedClcMap ClassLoaderContextMap) {
Ulya Trafimovich69612672020-10-20 17:41:54 +0100315
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000316 err := clcMap.addContext(ctx, sdkVer, lib, hostPath, installPath, strict, nestedClcMap)
Ulya Trafimovich69612672020-10-20 17:41:54 +0100317 if err != nil {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000318 ctx.ModuleErrorf(err.Error())
Ulya Trafimovich69612672020-10-20 17:41:54 +0100319 }
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100320}
321
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000322// Add class loader context. Fail on unknown build/install paths.
323func (clcMap ClassLoaderContextMap) AddContext(ctx android.ModuleInstallPathContext, lib string,
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000324 hostPath, installPath android.Path) {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000325
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000326 clcMap.addContextOrReportError(ctx, AnySdkVersion, lib, hostPath, installPath, true, nil)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100327}
328
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000329// Add class loader context if the library exists. Don't fail on unknown build/install paths.
330func (clcMap ClassLoaderContextMap) MaybeAddContext(ctx android.ModuleInstallPathContext, lib *string,
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000331 hostPath, installPath android.Path) {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000332
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100333 if lib != nil {
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000334 clcMap.addContextOrReportError(ctx, AnySdkVersion, *lib, hostPath, installPath, false, nil)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100335 }
336}
337
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000338// Add class loader context for the given SDK version. Fail on unknown build/install paths.
339func (clcMap ClassLoaderContextMap) AddContextForSdk(ctx android.ModuleInstallPathContext, sdkVer int,
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000340 lib string, hostPath, installPath android.Path, nestedClcMap ClassLoaderContextMap) {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000341
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000342 clcMap.addContextOrReportError(ctx, sdkVer, lib, hostPath, installPath, true, nestedClcMap)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100343}
344
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000345// Merge the other class loader context map into this one, do not override existing entries.
Ulya Trafimovich18554242020-11-03 15:55:11 +0000346// The implicitRootLib parameter is the name of the library for which the other class loader
347// context map was constructed. If the implicitRootLib is itself a <uses-library>, it should be
348// already present in the class loader context (with the other context as its subcontext) -- in
349// that case do not re-add the other context. Otherwise add the other context at the top-level.
350func (clcMap ClassLoaderContextMap) AddContextMap(otherClcMap ClassLoaderContextMap, implicitRootLib string) {
351 if otherClcMap == nil {
352 return
353 }
354
355 // If the implicit root of the merged map is already present as one of top-level subtrees, do
356 // not merge it second time.
357 for _, clc := range clcMap[AnySdkVersion] {
358 if clc.Name == implicitRootLib {
359 return
360 }
361 }
362
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000363 for sdkVer, otherClcs := range otherClcMap {
364 for _, otherClc := range otherClcs {
365 alreadyHave := false
366 for _, clc := range clcMap[sdkVer] {
367 if clc.Name == otherClc.Name {
368 alreadyHave = true
369 break
370 }
371 }
372 if !alreadyHave {
373 clcMap[sdkVer] = append(clcMap[sdkVer], otherClc)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100374 }
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100375 }
376 }
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100377}
378
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000379// Returns top-level libraries in the CLC (conditional CLC, i.e. compatibility libraries are not
380// included). This is the list of libraries that should be in the <uses-library> tags in the
381// manifest. Some of them may be present in the source manifest, others are added by manifest_fixer.
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000382func (clcMap ClassLoaderContextMap) UsesLibs() (ulibs []string) {
383 if clcMap != nil {
Ulya Trafimovich78a71552020-11-25 14:20:52 +0000384 clcs := clcMap[AnySdkVersion]
385 ulibs = make([]string, 0, len(clcs))
386 for _, clc := range clcs {
387 ulibs = append(ulibs, clc.Name)
Ulya Trafimovicha8c28e22020-10-06 17:24:19 +0100388 }
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100389 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000390 return ulibs
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100391}
392
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100393// Now that the full unconditional context is known, reconstruct conditional context.
394// Apply filters for individual libraries, mirroring what the PackageManager does when it
395// constructs class loader context on device.
396//
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000397// TODO(b/132357300): remove "android.hidl.manager" and "android.hidl.base" for non-system apps.
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100398//
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000399func fixClassLoaderContext(clcMap ClassLoaderContextMap) {
400 usesLibs := clcMap.UsesLibs()
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100401
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000402 for sdkVer, clcs := range clcMap {
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100403 if sdkVer == AnySdkVersion {
404 continue
405 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000406 fixedClcs := []*ClassLoaderContext{}
407 for _, clc := range clcs {
408 if android.InList(clc.Name, usesLibs) {
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100409 // skip compatibility libraries that are already included in unconditional context
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000410 } else if clc.Name == AndroidTestMock && !android.InList("android.test.runner", usesLibs) {
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100411 // android.test.mock is only needed as a compatibility library (in conditional class
412 // loader context) if android.test.runner is used, otherwise skip it
413 } else {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000414 fixedClcs = append(fixedClcs, clc)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100415 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000416 clcMap[sdkVer] = fixedClcs
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100417 }
418 }
419}
420
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000421// Return true if all build/install library paths are valid (including recursive subcontexts),
422// otherwise return false. A build path is valid if it's not nil. An install path is valid if it's
423// not equal to a special "error" value.
424func validateClassLoaderContext(clcMap ClassLoaderContextMap) (bool, error) {
425 for sdkVer, clcs := range clcMap {
426 if valid, err := validateClassLoaderContextRec(sdkVer, clcs); !valid || err != nil {
427 return valid, err
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100428 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000429 }
430 return true, nil
431}
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100432
Ulya Trafimovich480d1742020-11-20 15:30:03 +0000433// Helper function for validateClassLoaderContext() that handles recursion.
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000434func validateClassLoaderContextRec(sdkVer int, clcs []*ClassLoaderContext) (bool, error) {
435 for _, clc := range clcs {
436 if clc.Host == nil || clc.Device == UnknownInstallLibraryPath {
437 if sdkVer == AnySdkVersion {
438 // Return error if dexpreopt doesn't know paths to one of the <uses-library>
439 // dependencies. In the future we may need to relax this and just disable dexpreopt.
Ulya Trafimovich78210f62020-12-02 13:06:47 +0000440 if clc.Host == nil {
441 return false, fmt.Errorf("invalid build path for <uses-library> \"%s\"", clc.Name)
442 } else {
443 return false, fmt.Errorf("invalid install path for <uses-library> \"%s\"", clc.Name)
444 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000445 } else {
446 // No error for compatibility libraries, as Soong doesn't know if they are needed
447 // (this depends on the targetSdkVersion in the manifest), but the CLC is invalid.
448 return false, nil
449 }
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100450 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000451 if valid, err := validateClassLoaderContextRec(sdkVer, clc.Subcontexts); !valid || err != nil {
452 return valid, err
453 }
454 }
455 return true, nil
456}
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100457
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000458// Return the class loader context as a string, and a slice of build paths for all dependencies.
459// Perform a depth-first preorder traversal of the class loader context tree for each SDK version.
460// Return the resulting string and a slice of on-host build paths to all library dependencies.
461func ComputeClassLoaderContext(clcMap ClassLoaderContextMap) (clcStr string, paths android.Paths) {
462 for _, sdkVer := range android.SortedIntKeys(clcMap) { // determinisitc traversal order
463 sdkVerStr := fmt.Sprintf("%d", sdkVer)
464 if sdkVer == AnySdkVersion {
465 sdkVerStr = "any" // a special keyword that means any SDK version
466 }
467 hostClc, targetClc, hostPaths := computeClassLoaderContextRec(clcMap[sdkVer])
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100468 if hostPaths != nil {
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000469 clcStr += fmt.Sprintf(" --host-context-for-sdk %s %s", sdkVerStr, hostClc)
470 clcStr += fmt.Sprintf(" --target-context-for-sdk %s %s", sdkVerStr, targetClc)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100471 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000472 paths = append(paths, hostPaths...)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100473 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000474 return clcStr, android.FirstUniquePaths(paths)
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100475}
476
Ulya Trafimovich480d1742020-11-20 15:30:03 +0000477// Helper function for ComputeClassLoaderContext() that handles recursion.
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000478func computeClassLoaderContextRec(clcs []*ClassLoaderContext) (string, string, android.Paths) {
479 var paths android.Paths
480 var clcsHost, clcsTarget []string
481
482 for _, clc := range clcs {
483 subClcHost, subClcTarget, subPaths := computeClassLoaderContextRec(clc.Subcontexts)
484 if subPaths != nil {
485 subClcHost = "{" + subClcHost + "}"
486 subClcTarget = "{" + subClcTarget + "}"
487 }
488
489 clcsHost = append(clcsHost, "PCL["+clc.Host.String()+"]"+subClcHost)
490 clcsTarget = append(clcsTarget, "PCL["+clc.Device+"]"+subClcTarget)
491
492 paths = append(paths, clc.Host)
493 paths = append(paths, subPaths...)
494 }
495
496 clcHost := strings.Join(clcsHost, "#")
497 clcTarget := strings.Join(clcsTarget, "#")
498
499 return clcHost, clcTarget, paths
500}
501
Ulya Trafimovich480d1742020-11-20 15:30:03 +0000502// JSON representation of <uses-library> paths on host and on device.
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100503type jsonLibraryPath struct {
504 Host string
505 Device string
506}
507
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000508// Class loader contexts that come from Make (via JSON dexpreopt.config) files have simpler
509// structure than Soong class loader contexts: they are flat maps from a <uses-library> name to its
510// on-host and on-device paths. There are no nested subcontexts. It is a limitation of the current
511// Make implementation.
512type jsonClassLoaderContext map[string]jsonLibraryPath
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100513
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000514// A map from SDK version (represented with a JSON string) to JSON class loader context.
515type jsonClassLoaderContextMap map[string]jsonClassLoaderContext
516
517// Convert JSON class loader context map to ClassLoaderContextMap.
518func fromJsonClassLoaderContext(ctx android.PathContext, jClcMap jsonClassLoaderContextMap) ClassLoaderContextMap {
519 clcMap := make(ClassLoaderContextMap)
520 for sdkVerStr, clc := range jClcMap {
521 sdkVer, ok := strconv.Atoi(sdkVerStr)
522 if ok != nil {
523 if sdkVerStr == "any" {
524 sdkVer = AnySdkVersion
525 } else {
526 android.ReportPathErrorf(ctx, "failed to parse SDK version in dexpreopt.config: '%s'", sdkVerStr)
527 }
528 }
529 for lib, path := range clc {
530 clcMap[sdkVer] = append(clcMap[sdkVer], &ClassLoaderContext{
531 Name: lib,
532 Host: constructPath(ctx, path.Host),
533 Device: path.Device,
534 Subcontexts: nil,
535 })
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100536 }
537 }
Ulya Trafimovich8cbc5d22020-11-03 15:15:46 +0000538 return clcMap
Ulya Trafimovicheb268862020-10-20 15:16:38 +0100539}