blob: 095e0c2762863a6a835db9f950c02258a0b37c1c [file] [log] [blame]
Jiyong Park9b409bc2019-10-11 14:59:13 +09001// Copyright (C) 2019 The Android Open Source Project
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 sdk
16
17import (
Paul Duffinc6ba1822022-05-06 09:38:02 +000018 "bytes"
19 "encoding/json"
Jiyong Park9b409bc2019-10-11 14:59:13 +090020 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000021 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000022 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090023 "strings"
24
Paul Duffin7d74e7b2020-03-06 12:30:13 +000025 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000026 "android/soong/cc"
Colin Crosscb0ac952021-07-20 13:17:15 -070027
Paul Duffin375058f2019-11-29 20:17:53 +000028 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090029 "github.com/google/blueprint/proptools"
30
31 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090032)
33
Paul Duffin64fb5262021-05-05 21:36:04 +010034// Environment variables that affect the generated snapshot
35// ========================================================
36//
Paul Duffin39abf8f2021-09-24 14:58:27 +010037// SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE
38// This allows the target build release (i.e. the release version of the build within which
39// the snapshot will be used) of the snapshot to be specified. If unspecified then it defaults
40// to the current build release version. Otherwise, it must be the name of one of the build
41// releases defined in nameToBuildRelease, e.g. S, T, etc..
42//
43// The generated snapshot must only be used in the specified target release. If the target
44// build release is not the current build release then the generated Android.bp file not be
45// checked for compatibility.
46//
47// e.g. if setting SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE=S will cause the generated snapshot
48// to be compatible with S.
49//
Paul Duffin64fb5262021-05-05 21:36:04 +010050
Jiyong Park9b409bc2019-10-11 14:59:13 +090051var pctx = android.NewPackageContext("android/soong/sdk")
52
Paul Duffin375058f2019-11-29 20:17:53 +000053var (
54 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
55 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000056 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000057 CommandDeps: []string{
58 "${config.Zip2ZipCmd}",
59 },
60 },
61 "destdir")
62
63 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
64 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -070065 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +000066 CommandDeps: []string{
67 "${config.SoongZipCmd}",
68 },
69 Rspfile: "$out.rsp",
70 RspfileContent: "$in",
71 },
72 "basedir")
73
74 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
75 blueprint.RuleParams{
Paul Duffin74f1dcd2022-07-18 13:18:23 +000076 Command: `${config.MergeZipsCmd} -s $out $in`,
Paul Duffin375058f2019-11-29 20:17:53 +000077 CommandDeps: []string{
78 "${config.MergeZipsCmd}",
79 },
80 })
81)
82
Paul Duffin43f7bf02021-05-05 22:00:51 +010083const (
Paul Duffinb01ac4b2022-05-24 20:10:05 +000084 soongSdkSnapshotVersionCurrent = "current"
Paul Duffin43f7bf02021-05-05 22:00:51 +010085)
86
Paul Duffinb645ec82019-11-27 17:43:54 +000087type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090088 content strings.Builder
89 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090090}
91
Paul Duffinb645ec82019-11-27 17:43:54 +000092// generatedFile abstracts operations for writing contents into a file and emit a build rule
93// for the file.
94type generatedFile struct {
95 generatedContents
96 path android.OutputPath
97}
98
Jiyong Park232e7852019-11-04 12:23:40 +090099func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +0900100 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +0000101 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +0900102 }
103}
104
Paul Duffinb645ec82019-11-27 17:43:54 +0000105func (gc *generatedContents) Indent() {
106 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +0900107}
108
Paul Duffinb645ec82019-11-27 17:43:54 +0000109func (gc *generatedContents) Dedent() {
110 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +0900111}
112
Paul Duffina08e4dc2021-06-22 18:19:19 +0100113// IndentedPrintf will add spaces to indent the line to the appropriate level before printing the
114// arguments.
115func (gc *generatedContents) IndentedPrintf(format string, args ...interface{}) {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000116 _, _ = fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100117}
118
119// UnindentedPrintf does not add spaces to indent the line to the appropriate level before printing
120// the arguments.
121func (gc *generatedContents) UnindentedPrintf(format string, args ...interface{}) {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000122 _, _ = fmt.Fprintf(&(gc.content), format, args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900123}
124
125func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800126 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100127
128 content := gf.content.String()
129
130 // ninja consumes newline characters in rspfile_content. Prevent it by
131 // escaping the backslash in the newline character. The extra backslash
132 // is removed when the rspfile is written to the actual script file
133 content = strings.ReplaceAll(content, "\n", "\\n")
134
Jiyong Park9b409bc2019-10-11 14:59:13 +0900135 rb.Command().
136 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100137 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100138 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900139 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
140 rb.Command().
141 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800142 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900143}
144
Paul Duffin13879572019-11-28 14:31:38 +0000145// Collect all the members.
146//
Paul Duffinb97b1572021-04-29 21:50:40 +0100147// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
148// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000149func (s *sdk) collectMembers(ctx android.ModuleContext) {
150 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000151 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
152 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf7b3d0d2021-09-02 14:29:21 +0100153 if memberTag, ok := tag.(android.SdkMemberDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100154 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900155
Paul Duffin5cca7c42021-05-26 10:16:01 +0100156 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
157 if memberType == nil {
158 return false
159 }
160
Paul Duffin13879572019-11-28 14:31:38 +0000161 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000162 if !memberType.IsInstance(child) {
163 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900164 }
Paul Duffin13879572019-11-28 14:31:38 +0000165
Paul Duffin6a7e9532020-03-20 17:50:07 +0000166 // Keep track of which multilib variants are used by the sdk.
167 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
168
Colin Cross313aa542023-12-13 13:47:44 -0800169 exportedComponentsInfo, _ := android.OtherModuleProvider(ctx, child, android.ExportedComponentsInfoProvider)
Paul Duffinb97b1572021-04-29 21:50:40 +0100170
Paul Duffin5e71e682022-11-23 18:09:54 +0000171 var container android.Module
Paul Duffinc6ba1822022-05-06 09:38:02 +0000172 if parent != ctx.Module() {
Paul Duffin5e71e682022-11-23 18:09:54 +0000173 container = parent.(android.Module)
Paul Duffinc6ba1822022-05-06 09:38:02 +0000174 }
175
Paul Duffin1938dba2022-07-26 23:53:00 +0000176 minApiLevel := android.MinApiLevelForSdkSnapshot(ctx, child)
177
Paul Duffina7208112021-04-23 21:20:20 +0100178 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100179 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
Paul Duffinc6ba1822022-05-06 09:38:02 +0000180 sdkVariant: s,
181 memberType: memberType,
Paul Duffin5e71e682022-11-23 18:09:54 +0000182 variant: child.(android.Module),
Paul Duffin1938dba2022-07-26 23:53:00 +0000183 minApiLevel: minApiLevel,
Paul Duffinc6ba1822022-05-06 09:38:02 +0000184 container: container,
185 export: export,
186 exportedComponentsInfo: exportedComponentsInfo,
Paul Duffinb97b1572021-04-29 21:50:40 +0100187 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000188
Paul Duffin2d3da312021-05-06 12:02:27 +0100189 // Recurse down into the member's dependencies as it may have dependencies that need to be
190 // automatically added to the sdk.
191 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900192 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000193
194 return false
Paul Duffin13879572019-11-28 14:31:38 +0000195 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000196}
197
Paul Duffincc3132e2021-04-24 01:10:30 +0100198// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
199// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000200//
Paul Duffincc3132e2021-04-24 01:10:30 +0100201// The sdkMember instances are then grouped into slices by member type. Within each such slice the
202// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000203//
Paul Duffincc3132e2021-04-24 01:10:30 +0100204// Finally, the member type slices are concatenated together to form a single slice. The order in
205// which they are concatenated is the order in which the member types were registered in the
206// android.SdkMemberTypesRegistry.
Paul Duffinf861df72022-07-01 15:56:06 +0000207func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, targetBuildRelease *buildRelease, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000208 byType := make(map[android.SdkMemberType][]*sdkMember)
209 byName := make(map[string]*sdkMember)
210
Paul Duffin21827262021-04-24 12:16:36 +0100211 for _, memberVariantDep := range memberVariantDeps {
212 memberType := memberVariantDep.memberType
213 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000214
215 name := ctx.OtherModuleName(variant)
216 member := byName[name]
217 if member == nil {
218 member = &sdkMember{memberType: memberType, name: name}
219 byName[name] = member
220 byType[memberType] = append(byType[memberType], member)
Liz Kammer96320df2022-05-12 20:40:00 -0400221 } else if member.memberType != memberType {
222 // validate whether this is the same member type or and overriding member type
223 if memberType.Overrides(member.memberType) {
224 member.memberType = memberType
225 } else if !member.memberType.Overrides(memberType) {
226 ctx.ModuleErrorf("Incompatible member types %q %q", member.memberType, memberType)
227 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000228 }
229
Paul Duffin1356d8c2020-02-25 19:26:33 +0000230 // Only append new variants to the list. This is needed because a member can be both
231 // exported by the sdk and also be a transitive sdk member.
232 member.variants = appendUniqueVariants(member.variants, variant)
233 }
Paul Duffin13879572019-11-28 14:31:38 +0000234 var members []*sdkMember
Paul Duffin62782de2021-07-14 12:05:16 +0100235 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffinf861df72022-07-01 15:56:06 +0000236 memberType := memberListProperty.memberType
237
238 if !isMemberTypeSupportedByTargetBuildRelease(memberType, targetBuildRelease) {
239 continue
240 }
241
242 membersOfType := byType[memberType]
Paul Duffin13879572019-11-28 14:31:38 +0000243 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900244 }
245
Paul Duffin6a7e9532020-03-20 17:50:07 +0000246 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900247}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900248
Paul Duffinf861df72022-07-01 15:56:06 +0000249// isMemberTypeSupportedByTargetBuildRelease returns true if the member type is supported by the
250// target build release.
251func isMemberTypeSupportedByTargetBuildRelease(memberType android.SdkMemberType, targetBuildRelease *buildRelease) bool {
252 supportedByTargetBuildRelease := true
253 supportedBuildReleases := memberType.SupportedBuildReleases()
254 if supportedBuildReleases == "" {
255 supportedBuildReleases = "S+"
256 }
257
258 set, err := parseBuildReleaseSet(supportedBuildReleases)
259 if err != nil {
260 panic(fmt.Errorf("member type %s has invalid supported build releases %q: %s",
261 memberType.SdkPropertyName(), supportedBuildReleases, err))
262 }
263 if !set.contains(targetBuildRelease) {
264 supportedByTargetBuildRelease = false
265 }
266 return supportedByTargetBuildRelease
267}
268
Paul Duffin5e71e682022-11-23 18:09:54 +0000269func appendUniqueVariants(variants []android.Module, newVariant android.Module) []android.Module {
Paul Duffin72910952020-01-20 18:16:30 +0000270 for _, v := range variants {
271 if v == newVariant {
272 return variants
273 }
274 }
275 return append(variants, newVariant)
276}
277
Paul Duffin51509a12022-04-06 12:48:09 +0000278// BUILD_NUMBER_FILE is the name of the file in the snapshot zip that will contain the number of
279// the build from which the snapshot was produced.
280const BUILD_NUMBER_FILE = "snapshot-creation-build-number.txt"
281
Jiyong Park73c54ee2019-10-22 20:31:18 +0900282// SDK directory structure
283// <sdk_root>/
284// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
285// <api_ver>/ : below this directory are all auto-generated
286// Android.bp : definition of 'sdk_snapshot' module is here
287// aidl/
288// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
289// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900290// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900291// include/
292// bionic/libc/include/stdlib.h : an exported header file
293// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900294// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900295// <arch>/include/ : arch-specific exported headers
296// <arch>/include_gen/ : arch-specific generated headers
297// <arch>/lib/
298// libFoo.so : a stub library
299
Paul Duffin1938dba2022-07-26 23:53:00 +0000300func (s sdk) targetBuildRelease(ctx android.ModuleContext) *buildRelease {
301 config := ctx.Config()
302 targetBuildReleaseEnv := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE", buildReleaseCurrent.name)
303 targetBuildRelease, err := nameToRelease(targetBuildReleaseEnv)
304 if err != nil {
305 ctx.ModuleErrorf("invalid SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE: %s", err)
306 targetBuildRelease = buildReleaseCurrent
307 }
308
309 return targetBuildRelease
310}
311
Jiyong Park232e7852019-11-04 12:23:40 +0900312// buildSnapshot is the main function in this source file. It creates rules to copy
313// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffinc6ba1822022-05-06 09:38:02 +0000314func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000315
Paul Duffin1938dba2022-07-26 23:53:00 +0000316 targetBuildRelease := s.targetBuildRelease(ctx)
317 targetApiLevel, err := android.ApiLevelFromUser(ctx, targetBuildRelease.name)
318 if err != nil {
319 targetApiLevel = android.FutureApiLevel
320 }
321
Paul Duffinb97b1572021-04-29 21:50:40 +0100322 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100323 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100324 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000325 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100326 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100327 }
Paul Duffin865171e2020-03-02 18:38:15 +0000328
Paul Duffinb97b1572021-04-29 21:50:40 +0100329 // Filter out any sdkMemberVariantDep that is a component of another.
330 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000331
Paul Duffin1938dba2022-07-26 23:53:00 +0000332 // Record the names of all the members, both explicitly specified and implicitly included. Also,
333 // record the names of any members that should be excluded from this snapshot.
Paul Duffinb97b1572021-04-29 21:50:40 +0100334 allMembersByName := make(map[string]struct{})
335 exportedMembersByName := make(map[string]struct{})
Paul Duffin1938dba2022-07-26 23:53:00 +0000336 excludedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100337
Paul Duffin1938dba2022-07-26 23:53:00 +0000338 addMember := func(name string, export bool, exclude bool) {
339 if exclude {
340 excludedMembersByName[name] = struct{}{}
341 return
342 }
343
Paul Duffinb97b1572021-04-29 21:50:40 +0100344 allMembersByName[name] = struct{}{}
345 if export {
346 exportedMembersByName[name] = struct{}{}
347 }
348 }
349
350 for _, memberVariantDep := range memberVariantDeps {
351 name := memberVariantDep.variant.Name()
352 export := memberVariantDep.export
353
Paul Duffin1938dba2022-07-26 23:53:00 +0000354 // If the minApiLevel of the member is greater than the target API level then exclude it from
355 // this snapshot.
356 exclude := memberVariantDep.minApiLevel.GreaterThan(targetApiLevel)
Spandan Dasb84dbb22023-03-08 22:06:35 +0000357 // Always include host variants (e.g. host tools) in the snapshot.
358 // Host variants should not be guarded by a min_sdk_version check. In fact, host variants
359 // do not have a `min_sdk_version`.
360 if memberVariantDep.Host() {
361 exclude = false
362 }
Paul Duffin1938dba2022-07-26 23:53:00 +0000363
364 addMember(name, export, exclude)
Paul Duffinb97b1572021-04-29 21:50:40 +0100365
366 // Add any components provided by the module.
367 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
Paul Duffin1938dba2022-07-26 23:53:00 +0000368 addMember(component, export, exclude)
Paul Duffinb97b1572021-04-29 21:50:40 +0100369 }
370
371 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
372 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000373 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000374 }
375
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000376 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900377
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000378 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000379
380 bpFile := &bpFile{
381 modules: make(map[string]*bpModule),
382 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000383
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000384 // Always add -current to the end
385 snapshotFileSuffix := "-current"
Paul Duffin43f7bf02021-05-05 22:00:51 +0100386
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000387 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000388 ctx: ctx,
389 sdk: s,
Paul Duffin13f02712020-03-06 12:30:43 +0000390 snapshotDir: snapshotDir.OutputPath,
391 copies: make(map[string]string),
392 filesToZip: []android.Path{bp.path},
393 bpFile: bpFile,
394 prebuiltModules: make(map[string]*bpModule),
395 allMembersByName: allMembersByName,
396 exportedMembersByName: exportedMembersByName,
Paul Duffin1938dba2022-07-26 23:53:00 +0000397 excludedMembersByName: excludedMembersByName,
Paul Duffin39abf8f2021-09-24 14:58:27 +0100398 targetBuildRelease: targetBuildRelease,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900399 }
Paul Duffinac37c502019-11-26 18:02:20 +0000400 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900401
Paul Duffin62131702021-05-07 01:10:01 +0100402 // If the sdk snapshot includes any license modules then add a package module which has a
403 // default_applicable_licenses property. That will prevent the LSC license process from updating
404 // the generated Android.bp file to add a package module that includes all licenses used by all
405 // the modules in that package. That would be unnecessary as every module in the sdk should have
406 // their own licenses property specified.
407 if hasLicenses {
408 pkg := bpFile.newModule("package")
409 property := "default_applicable_licenses"
410 pkg.AddCommentForProperty(property, `
411A default list here prevents the license LSC from adding its own list which would
412be unnecessary as every module in the sdk already has its own licenses property.
413`)
414 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
415 bpFile.AddModule(pkg)
416 }
417
Paul Duffin0df49682021-05-07 01:10:01 +0100418 // Group the variants for each member module together and then group the members of each member
419 // type together.
Paul Duffinf861df72022-07-01 15:56:06 +0000420 members := s.groupMemberVariantsByMemberThenType(ctx, targetBuildRelease, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100421
422 // Create the prebuilt modules for each of the member modules.
Paul Duffind19f8942021-07-14 12:08:37 +0100423 traits := s.gatherTraits()
Paul Duffin13ad94f2020-02-19 16:19:27 +0000424 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000425 memberType := member.memberType
Paul Duffin4e7d1c42022-05-13 13:12:19 +0000426 if !memberType.ArePrebuiltsRequired() {
427 continue
428 }
Paul Duffin3a4eb502020-03-19 16:11:18 +0000429
Paul Duffind19f8942021-07-14 12:08:37 +0100430 name := member.name
Paul Duffin1938dba2022-07-26 23:53:00 +0000431 if _, ok := excludedMembersByName[name]; ok {
432 continue
433 }
434
Paul Duffind19f8942021-07-14 12:08:37 +0100435 requiredTraits := traits[name]
436 if requiredTraits == nil {
437 requiredTraits = android.EmptySdkMemberTraitSet()
438 }
439
440 // Create the snapshot for the member.
441 memberCtx := &memberContext{ctx, builder, memberType, name, requiredTraits}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000442
443 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100444 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900445 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900446
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000447 // Create a transformer that will transform a module by replacing any references
Paul Duffin72910952020-01-20 18:16:30 +0000448 // to internal members with a unique module name and setting prefer: false.
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000449 snapshotTransformer := snapshotTransformation{
Paul Duffin64fb5262021-05-05 21:36:04 +0100450 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100451 }
Paul Duffin72910952020-01-20 18:16:30 +0000452
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000453 for _, module := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000454 // Prune any empty property sets.
Sam Delmerico35881362023-06-30 14:40:10 -0400455 module = transformModule(module, pruneEmptySetTransformer{})
Paul Duffina78f3a72020-02-21 16:29:35 +0000456
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000457 // Transform the module module to make it suitable for use in the snapshot.
Sam Delmerico35881362023-06-30 14:40:10 -0400458 module = transformModule(module, snapshotTransformer)
459 module = transformModule(module, emptyClasspathContentsTransformation{})
460 if module != nil {
461 bpFile.AddModule(module)
462 }
Paul Duffin43f7bf02021-05-05 22:00:51 +0100463 }
Paul Duffin26197a62021-04-24 00:34:10 +0100464
465 // generate Android.bp
466 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
467 generateBpContents(&bp.generatedContents, bpFile)
468
469 contents := bp.content.String()
Paul Duffin39abf8f2021-09-24 14:58:27 +0100470 // If the snapshot is being generated for the current build release then check the syntax to make
471 // sure that it is compatible.
Paul Duffin42a49f12022-08-17 22:09:55 +0000472 if targetBuildRelease == buildReleaseCurrent {
Paul Duffin39abf8f2021-09-24 14:58:27 +0100473 syntaxCheckSnapshotBpFile(ctx, contents)
474 }
Paul Duffin26197a62021-04-24 00:34:10 +0100475
476 bp.build(pctx, ctx, nil)
477
Paul Duffin51509a12022-04-06 12:48:09 +0000478 // Copy the build number file into the snapshot.
479 builder.CopyToSnapshot(ctx.Config().BuildNumberFile(ctx), BUILD_NUMBER_FILE)
480
Paul Duffin74f1dcd2022-07-18 13:18:23 +0000481 filesToZip := android.SortedUniquePaths(builder.filesToZip)
Paul Duffin26197a62021-04-24 00:34:10 +0100482
483 // zip them all
Paul Duffinc6ba1822022-05-06 09:38:02 +0000484 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100485 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100486 outputDesc := "Building snapshot for " + ctx.ModuleName()
487
488 // If there are no zips to merge then generate the output zip directly.
489 // Otherwise, generate an intermediate zip file into which other zips can be
490 // merged.
491 var zipFile android.OutputPath
492 var desc string
493 if len(builder.zipsToMerge) == 0 {
494 zipFile = outputZipFile
495 desc = outputDesc
496 } else {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000497 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100498 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100499 desc = "Building intermediate snapshot for " + ctx.ModuleName()
500 }
501
502 ctx.Build(pctx, android.BuildParams{
503 Description: desc,
504 Rule: zipFiles,
505 Inputs: filesToZip,
506 Output: zipFile,
507 Args: map[string]string{
508 "basedir": builder.snapshotDir.String(),
509 },
510 })
511
512 if len(builder.zipsToMerge) != 0 {
513 ctx.Build(pctx, android.BuildParams{
514 Description: outputDesc,
515 Rule: mergeZips,
516 Input: zipFile,
Paul Duffin74f1dcd2022-07-18 13:18:23 +0000517 Inputs: android.SortedUniquePaths(builder.zipsToMerge),
Paul Duffin26197a62021-04-24 00:34:10 +0100518 Output: outputZipFile,
519 })
520 }
521
Paul Duffinc6ba1822022-05-06 09:38:02 +0000522 modules := s.generateInfoData(ctx, memberVariantDeps)
523
524 // Output the modules information as pretty printed JSON.
525 info := newGeneratedFile(ctx, fmt.Sprintf("%s%s.info", ctx.ModuleName(), snapshotFileSuffix))
526 output, err := json.MarshalIndent(modules, "", " ")
527 if err != nil {
528 ctx.ModuleErrorf("error generating %q: %s", info, err)
529 }
530 builder.infoContents = string(output)
531 info.generatedContents.UnindentedPrintf("%s", output)
532 info.build(pctx, ctx, nil)
533 infoPath := info.path
534 installedInfo := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), infoPath.Base(), infoPath)
535 s.infoFile = android.OptionalPathForPath(installedInfo)
536
537 // Install the zip, making sure that the info file has been installed as well.
538 installedZip := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), outputZipFile.Base(), outputZipFile, installedInfo)
539 s.snapshotFile = android.OptionalPathForPath(installedZip)
540}
541
542type moduleInfo struct {
543 // The type of the module, e.g. java_sdk_library
544 moduleType string
545 // The name of the module.
546 name string
547 // A list of additional dependencies of the module.
548 deps []string
Paul Duffin958806b2022-05-16 13:10:47 +0000549 // Additional member specific properties.
550 // These will be added into the generated JSON alongside the above properties.
551 memberSpecific map[string]interface{}
Paul Duffinc6ba1822022-05-06 09:38:02 +0000552}
553
554func (m *moduleInfo) MarshalJSON() ([]byte, error) {
555 buffer := bytes.Buffer{}
556
557 separator := ""
558 writeObjectPair := func(key string, value interface{}) {
559 buffer.WriteString(fmt.Sprintf("%s%q: ", separator, key))
560 b, err := json.Marshal(value)
561 if err != nil {
562 panic(err)
563 }
564 buffer.Write(b)
565 separator = ","
566 }
567
568 buffer.WriteString("{")
569 writeObjectPair("@type", m.moduleType)
570 writeObjectPair("@name", m.name)
571 if m.deps != nil {
572 writeObjectPair("@deps", m.deps)
573 }
Cole Faust18994c72023-02-28 16:02:16 -0800574 for _, k := range android.SortedKeys(m.memberSpecific) {
Paul Duffin958806b2022-05-16 13:10:47 +0000575 v := m.memberSpecific[k]
Paul Duffinc6ba1822022-05-06 09:38:02 +0000576 writeObjectPair(k, v)
577 }
578 buffer.WriteString("}")
579 return buffer.Bytes(), nil
580}
581
582var _ json.Marshaler = (*moduleInfo)(nil)
583
584// generateInfoData creates a list of moduleInfo structures that will be marshalled into JSON.
585func (s *sdk) generateInfoData(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) interface{} {
586 modules := []*moduleInfo{}
587 sdkInfo := moduleInfo{
Paul Duffin958806b2022-05-16 13:10:47 +0000588 moduleType: "sdk",
589 name: ctx.ModuleName(),
590 memberSpecific: map[string]interface{}{},
Paul Duffinc6ba1822022-05-06 09:38:02 +0000591 }
592 modules = append(modules, &sdkInfo)
593
594 name2Info := map[string]*moduleInfo{}
595 getModuleInfo := func(module android.Module) *moduleInfo {
596 name := module.Name()
597 info := name2Info[name]
598 if info == nil {
599 moduleType := ctx.OtherModuleType(module)
600 // Remove any suffix added when creating modules dynamically.
601 moduleType = strings.Split(moduleType, "__")[0]
602 info = &moduleInfo{
603 moduleType: moduleType,
604 name: name,
605 }
Paul Duffin958806b2022-05-16 13:10:47 +0000606
Colin Cross313aa542023-12-13 13:47:44 -0800607 additionalSdkInfo, _ := android.OtherModuleProvider(ctx, module, android.AdditionalSdkInfoProvider)
Paul Duffin958806b2022-05-16 13:10:47 +0000608 info.memberSpecific = additionalSdkInfo.Properties
609
Paul Duffinc6ba1822022-05-06 09:38:02 +0000610 name2Info[name] = info
611 }
612 return info
613 }
614
615 for _, memberVariantDep := range memberVariantDeps {
616 propertyName := memberVariantDep.memberType.SdkPropertyName()
617 var list []string
Paul Duffin958806b2022-05-16 13:10:47 +0000618 if v, ok := sdkInfo.memberSpecific[propertyName]; ok {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000619 list = v.([]string)
620 }
621
622 memberName := memberVariantDep.variant.Name()
623 list = append(list, memberName)
Paul Duffin958806b2022-05-16 13:10:47 +0000624 sdkInfo.memberSpecific[propertyName] = android.SortedUniqueStrings(list)
Paul Duffinc6ba1822022-05-06 09:38:02 +0000625
626 if memberVariantDep.container != nil {
627 containerInfo := getModuleInfo(memberVariantDep.container)
628 containerInfo.deps = android.SortedUniqueStrings(append(containerInfo.deps, memberName))
629 }
630
631 // Make sure that the module info is created for each module.
632 getModuleInfo(memberVariantDep.variant)
633 }
634
Cole Faust18994c72023-02-28 16:02:16 -0800635 for _, memberName := range android.SortedKeys(name2Info) {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000636 info := name2Info[memberName]
637 modules = append(modules, info)
638 }
639
640 return modules
Paul Duffin26197a62021-04-24 00:34:10 +0100641}
642
Paul Duffinb97b1572021-04-29 21:50:40 +0100643// filterOutComponents removes any item from the deps list that is a component of another item in
644// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
645// then it will remove "foo.stubs" from the deps.
646func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
647 // Collate the set of components that all the modules added to the sdk provide.
648 components := map[string]*sdkMemberVariantDep{}
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000649 for i := range deps {
Paul Duffinb97b1572021-04-29 21:50:40 +0100650 dep := &deps[i]
651 for _, c := range dep.exportedComponentsInfo.Components {
652 components[c] = dep
653 }
654 }
655
656 // If no module provides components then return the input deps unfiltered.
657 if len(components) == 0 {
658 return deps
659 }
660
661 filtered := make([]sdkMemberVariantDep, 0, len(deps))
662 for _, dep := range deps {
663 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
664 if owner, ok := components[name]; ok {
665 // This is a component of another module that is a member of the sdk.
666
667 // If the component is exported but the owning module is not then the configuration is not
668 // supported.
669 if dep.export && !owner.export {
670 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
671 continue
672 }
673
674 // This module must not be added to the list of members of the sdk as that would result in a
675 // duplicate module in the sdk snapshot.
676 continue
677 }
678
679 filtered = append(filtered, dep)
680 }
681 return filtered
682}
683
Paul Duffinf88d8e02020-05-07 20:21:34 +0100684// Check the syntax of the generated Android.bp file contents and if they are
685// invalid then log an error with the contents (tagged with line numbers) and the
686// errors that were found so that it is easy to see where the problem lies.
687func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
688 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
689 if len(errs) != 0 {
690 message := &strings.Builder{}
691 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
692
693Generated Android.bp contents
694========================================================================
695`)
696 for i, line := range strings.Split(contents, "\n") {
697 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
698 }
699
700 _, _ = fmt.Fprint(message, `
701========================================================================
702
703Errors found:
704`)
705
706 for _, err := range errs {
707 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
708 }
709
710 ctx.ModuleErrorf("%s", message.String())
711 }
712}
713
Paul Duffin4b8b7932020-05-06 12:35:38 +0100714func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
715 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
716 if err != nil {
717 ctx.ModuleErrorf("error extracting common properties: %s", err)
718 }
719}
720
Paul Duffinfbe470e2021-04-24 12:37:13 +0100721// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
722type snapshotModuleStaticProperties struct {
723 Compile_multilib string `android:"arch_variant"`
724}
725
Paul Duffin2d1bb892021-04-24 11:32:59 +0100726// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
727type combinedSnapshotModuleProperties struct {
728 // The sdk variant from which this information was collected.
729 sdkVariant *sdk
730
731 // Static snapshot module properties.
732 staticProperties *snapshotModuleStaticProperties
733
734 // The dynamically generated member list properties.
735 dynamicProperties interface{}
736}
737
738// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100739func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
740 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100741 var list []*combinedSnapshotModuleProperties
742 for _, sdkVariant := range sdkVariants {
743 staticProperties := &snapshotModuleStaticProperties{
744 Compile_multilib: sdkVariant.multilibUsages.String(),
745 }
Paul Duffin62782de2021-07-14 12:05:16 +0100746 dynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100747
Paul Duffincd064672021-04-24 00:47:29 +0100748 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100749 sdkVariant: sdkVariant,
750 staticProperties: staticProperties,
751 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100752 }
753 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
754
755 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100756 }
Paul Duffincd064672021-04-24 00:47:29 +0100757
758 for _, memberVariantDep := range memberVariantDeps {
759 // If the member dependency is internal then do not add the dependency to the snapshot member
760 // list properties.
761 if !memberVariantDep.export {
762 continue
763 }
764
765 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin62782de2021-07-14 12:05:16 +0100766 memberListProperty := s.memberTypeListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100767 memberName := ctx.OtherModuleName(memberVariantDep.variant)
768
Paul Duffin13082052021-05-11 00:31:38 +0100769 if memberListProperty.getter == nil {
770 continue
771 }
772
Paul Duffincd064672021-04-24 00:47:29 +0100773 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100774 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100775 if !android.InList(memberName, memberList) {
776 memberList = append(memberList, memberName)
777 }
Paul Duffin13082052021-05-11 00:31:38 +0100778 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100779 }
780
Paul Duffin2d1bb892021-04-24 11:32:59 +0100781 return list
782}
783
784func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
785
786 // Extract the dynamic properties and add them to a list of propertiesContainer.
787 propertyContainers := []propertiesContainer{}
788 for _, i := range list {
789 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
790 sdkVariant: i.sdkVariant,
791 properties: i.dynamicProperties,
792 })
793 }
794
795 // Extract the common members, removing them from the original properties.
Paul Duffin62782de2021-07-14 12:05:16 +0100796 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100797 extractor := newCommonValueExtractor(commonDynamicProperties)
798 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
799
800 // Extract the static properties and add them to a list of propertiesContainer.
801 propertyContainers = []propertiesContainer{}
802 for _, i := range list {
803 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
804 sdkVariant: i.sdkVariant,
805 properties: i.staticProperties,
806 })
807 }
808
809 commonStaticProperties := &snapshotModuleStaticProperties{}
810 extractor = newCommonValueExtractor(commonStaticProperties)
811 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
812
813 return &combinedSnapshotModuleProperties{
814 sdkVariant: nil,
815 staticProperties: commonStaticProperties,
816 dynamicProperties: commonDynamicProperties,
817 }
818}
819
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000820type propertyTag struct {
821 name string
822}
823
Paul Duffin94289702021-09-09 15:38:32 +0100824var _ android.BpPropertyTag = propertyTag{}
825
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000826// BpPropertyTag instances to add to a property that contains references to other sdk members.
Paul Duffin0cb37b92020-03-04 14:52:46 +0000827//
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000828// These will ensure that the referenced modules are available, if required.
Paul Duffin13f02712020-03-06 12:30:43 +0000829var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000830var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000831
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000832type snapshotTransformation struct {
Paul Duffine6c0d842020-01-15 14:08:51 +0000833 identityTransformation
834 builder *snapshotBuilder
835}
836
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000837func (t snapshotTransformation) transformModule(module *bpModule) *bpModule {
Sam Delmerico35881362023-06-30 14:40:10 -0400838 if module != nil {
839 // If the module is an internal member then use a unique name for it.
840 name := module.Name()
841 module.setProperty("name", t.builder.snapshotSdkMemberName(name, true))
842 }
Paul Duffin72910952020-01-20 18:16:30 +0000843 return module
844}
845
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000846func (t snapshotTransformation) transformProperty(_ string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000847 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
848 required := tag == requiredSdkMemberReferencePropertyTag
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000849 return t.builder.snapshotSdkMemberNames(value.([]string), required), tag
Paul Duffin72910952020-01-20 18:16:30 +0000850 } else {
851 return value, tag
852 }
853}
854
Sam Delmerico35881362023-06-30 14:40:10 -0400855type emptyClasspathContentsTransformation struct {
856 identityTransformation
857}
858
859func (t emptyClasspathContentsTransformation) transformModule(module *bpModule) *bpModule {
860 classpathModuleTypes := []string{
861 "prebuilt_bootclasspath_fragment",
862 "prebuilt_systemserverclasspath_fragment",
863 }
864 if module != nil && android.InList(module.moduleType, classpathModuleTypes) {
865 if contents, ok := module.bpPropertySet.properties["contents"].([]string); ok {
866 if len(contents) == 0 {
867 return nil
868 }
869 }
870 }
871 return module
872}
873
Paul Duffina78f3a72020-02-21 16:29:35 +0000874type pruneEmptySetTransformer struct {
875 identityTransformation
876}
877
878var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
879
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000880func (t pruneEmptySetTransformer) transformPropertySetAfterContents(_ string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
Paul Duffina78f3a72020-02-21 16:29:35 +0000881 if len(propertySet.properties) == 0 {
882 return nil, nil
883 } else {
884 return propertySet, tag
885 }
886}
887
Paul Duffinb645ec82019-11-27 17:43:54 +0000888func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100889 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000890 for _, bpModule := range bpFile.order {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000891 contents.IndentedPrintf("\n")
892 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
893 outputPropertySet(contents, bpModule.bpPropertySet)
894 contents.IndentedPrintf("}\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000895 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000896}
897
898func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
899 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000900
Paul Duffin0df49682021-05-07 01:10:01 +0100901 addComment := func(name string) {
902 if text, ok := set.comments[name]; ok {
903 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100904 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100905 }
906 }
907 }
908
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000909 // Output the properties first, followed by the nested sets. This ensures a
910 // consistent output irrespective of whether property sets are created before
911 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000912 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000913 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000914
Paul Duffin0df49682021-05-07 01:10:01 +0100915 // Do not write property sets in the properties phase.
916 if _, ok := value.(*bpPropertySet); ok {
917 continue
918 }
919
920 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100921 reflectValue := reflect.ValueOf(value)
922 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000923 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000924
925 for _, name := range set.order {
926 value := set.getValue(name)
927
928 // Only write property sets in the sets phase.
929 switch v := value.(type) {
930 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100931 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100932 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000933 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100934 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000935 }
936 }
937
Paul Duffinb645ec82019-11-27 17:43:54 +0000938 contents.Dedent()
939}
940
Paul Duffina08e4dc2021-06-22 18:19:19 +0100941// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
942// by the value and then followed by a , and a newline.
943func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
944 contents.IndentedPrintf("%s: ", name)
945 outputUnnamedValue(contents, value)
946 contents.UnindentedPrintf(",\n")
947}
948
949// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
950// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
951// indented and all but the last line will end with a newline.
952func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
953 valueType := value.Type()
954 switch valueType.Kind() {
955 case reflect.Bool:
956 contents.UnindentedPrintf("%t", value.Bool())
957
958 case reflect.String:
959 contents.UnindentedPrintf("%q", value)
960
Paul Duffin51227d82021-05-18 12:54:27 +0100961 case reflect.Ptr:
962 outputUnnamedValue(contents, value.Elem())
963
Paul Duffina08e4dc2021-06-22 18:19:19 +0100964 case reflect.Slice:
965 length := value.Len()
966 if length == 0 {
967 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100968 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100969 firstValue := value.Index(0)
970 if length == 1 && !multiLineValue(firstValue) {
971 contents.UnindentedPrintf("[")
972 outputUnnamedValue(contents, firstValue)
973 contents.UnindentedPrintf("]")
974 } else {
975 contents.UnindentedPrintf("[\n")
976 contents.Indent()
977 for i := 0; i < length; i++ {
978 itemValue := value.Index(i)
979 contents.IndentedPrintf("")
980 outputUnnamedValue(contents, itemValue)
981 contents.UnindentedPrintf(",\n")
982 }
983 contents.Dedent()
984 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100985 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100986 }
987
Paul Duffin51227d82021-05-18 12:54:27 +0100988 case reflect.Struct:
989 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
990 v := value.Interface()
991 if _, ok := v.(android.BpPrintable); !ok {
992 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
993 }
994 contents.UnindentedPrintf("{\n")
995 contents.Indent()
996 for f := 0; f < valueType.NumField(); f++ {
997 fieldType := valueType.Field(f)
998 if fieldType.Anonymous {
999 continue
1000 }
1001 fieldValue := value.Field(f)
1002 fieldName := fieldType.Name
1003 propertyName := proptools.PropertyNameForField(fieldName)
1004 outputNamedValue(contents, propertyName, fieldValue)
1005 }
1006 contents.Dedent()
1007 contents.IndentedPrintf("}")
1008
Paul Duffina08e4dc2021-06-22 18:19:19 +01001009 default:
1010 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
1011 }
1012}
1013
Paul Duffin51227d82021-05-18 12:54:27 +01001014// multiLineValue returns true if the supplied value may require multiple lines in the output.
1015func multiLineValue(value reflect.Value) bool {
1016 kind := value.Kind()
1017 return kind == reflect.Slice || kind == reflect.Struct
1018}
1019
Paul Duffinac37c502019-11-26 18:02:20 +00001020func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001021 contents := &generatedContents{}
1022 generateBpContents(contents, s.builderForTests.bpFile)
1023 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +00001024}
1025
Paul Duffinc6ba1822022-05-06 09:38:02 +00001026func (s *sdk) GetInfoContentsForTests() string {
1027 return s.builderForTests.infoContents
1028}
1029
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001030type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +01001031 ctx android.ModuleContext
1032 sdk *sdk
1033
Paul Duffinb645ec82019-11-27 17:43:54 +00001034 snapshotDir android.OutputPath
1035 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +00001036
1037 // Map from destination to source of each copy - used to eliminate duplicates and
1038 // detect conflicts.
1039 copies map[string]string
1040
Paul Duffinb645ec82019-11-27 17:43:54 +00001041 filesToZip android.Paths
1042 zipsToMerge android.Paths
1043
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001044 // The path to an empty file.
1045 emptyFile android.WritablePath
1046
Paul Duffinb645ec82019-11-27 17:43:54 +00001047 prebuiltModules map[string]*bpModule
1048 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001049
1050 // The set of all members by name.
1051 allMembersByName map[string]struct{}
1052
1053 // The set of exported members by name.
1054 exportedMembersByName map[string]struct{}
Paul Duffin39abf8f2021-09-24 14:58:27 +01001055
Paul Duffin1938dba2022-07-26 23:53:00 +00001056 // The set of members which have been excluded from this snapshot; by name.
1057 excludedMembersByName map[string]struct{}
1058
Paul Duffin39abf8f2021-09-24 14:58:27 +01001059 // The target build release for which the snapshot is to be generated.
1060 targetBuildRelease *buildRelease
Paul Duffinc6ba1822022-05-06 09:38:02 +00001061
Paul Duffin958806b2022-05-16 13:10:47 +00001062 // The contents of the .info file that describes the sdk contents.
Paul Duffinc6ba1822022-05-06 09:38:02 +00001063 infoContents string
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001064}
1065
1066func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001067 if existing, ok := s.copies[dest]; ok {
1068 if existing != src.String() {
1069 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1070 return
1071 }
1072 } else {
1073 path := s.snapshotDir.Join(s.ctx, dest)
1074 s.ctx.Build(pctx, android.BuildParams{
1075 Rule: android.Cp,
1076 Input: src,
1077 Output: path,
1078 })
1079 s.filesToZip = append(s.filesToZip, path)
1080
1081 s.copies[dest] = src.String()
1082 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001083}
1084
Paul Duffin91547182019-11-12 19:39:36 +00001085func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1086 ctx := s.ctx
1087
1088 // Repackage the zip file so that the entries are in the destDir directory.
1089 // This will allow the zip file to be merged into the snapshot.
1090 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001091
1092 ctx.Build(pctx, android.BuildParams{
1093 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1094 Rule: repackageZip,
1095 Input: zipPath,
1096 Output: tmpZipPath,
1097 Args: map[string]string{
1098 "destdir": destDir,
1099 },
1100 })
Paul Duffin91547182019-11-12 19:39:36 +00001101
1102 // Add the repackaged zip file to the files to merge.
1103 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1104}
1105
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001106func (s *snapshotBuilder) EmptyFile() android.Path {
1107 if s.emptyFile == nil {
1108 ctx := s.ctx
1109 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1110 s.ctx.Build(pctx, android.BuildParams{
1111 Rule: android.Touch,
1112 Output: s.emptyFile,
1113 })
1114 }
1115
1116 return s.emptyFile
1117}
1118
Paul Duffin9d8d6092019-12-05 18:19:29 +00001119func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1120 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001121 if s.prebuiltModules[name] != nil {
1122 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1123 }
1124
1125 m := s.bpFile.newModule(moduleType)
1126 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001127
Paul Duffinbefa4b92020-03-04 14:22:45 +00001128 variant := member.Variants()[0]
1129
Paul Duffin13f02712020-03-06 12:30:43 +00001130 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001131 // An internal member is only referenced from the sdk snapshot which is in the
1132 // same package so can be marked as private.
1133 m.AddProperty("visibility", []string{"//visibility:private"})
1134 } else {
1135 // Extract visibility information from a member variant. All variants have the same
1136 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001137 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1138
1139 // Add any additional visibility rules needed for the prebuilts to reference each other.
1140 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1141 if err != nil {
1142 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1143 }
1144
1145 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001146 if len(visibility) != 0 {
1147 m.AddProperty("visibility", visibility)
1148 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001149 }
1150
Martin Stjernholm1e041092020-11-03 00:11:09 +00001151 // Where available copy apex_available properties from the member.
1152 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1153 apexAvailable := apexAware.ApexAvailable()
1154 if len(apexAvailable) == 0 {
1155 // //apex_available:platform is the default.
1156 apexAvailable = []string{android.AvailableToPlatform}
1157 }
1158
1159 // Add in any baseline apex available settings.
1160 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1161
1162 // Remove duplicates and sort.
1163 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1164 sort.Strings(apexAvailable)
1165
1166 m.AddProperty("apex_available", apexAvailable)
1167 }
1168
Paul Duffinb0bb3762021-05-06 16:48:05 +01001169 // The licenses are the same for all variants.
1170 mctx := s.ctx
Colin Cross313aa542023-12-13 13:47:44 -08001171 licenseInfo, _ := android.OtherModuleProvider(mctx, variant, android.LicenseInfoProvider)
Paul Duffinb0bb3762021-05-06 16:48:05 +01001172 if len(licenseInfo.Licenses) > 0 {
1173 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1174 }
1175
Paul Duffin865171e2020-03-02 18:38:15 +00001176 deviceSupported := false
1177 hostSupported := false
1178
1179 for _, variant := range member.Variants() {
1180 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001181 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001182 hostSupported = true
1183 } else if osClass == android.Device {
1184 deviceSupported = true
1185 }
1186 }
1187
1188 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001189
1190 s.prebuiltModules[name] = m
1191 s.prebuiltOrder = append(s.prebuiltOrder, m)
1192 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001193}
1194
Paul Duffin865171e2020-03-02 18:38:15 +00001195func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001196 // If neither device or host is supported then this module does not support either so will not
1197 // recognize the properties.
1198 if !deviceSupported && !hostSupported {
1199 return
1200 }
1201
Paul Duffin865171e2020-03-02 18:38:15 +00001202 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001203 bpModule.AddProperty("device_supported", false)
1204 }
Paul Duffin865171e2020-03-02 18:38:15 +00001205 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001206 bpModule.AddProperty("host_supported", true)
1207 }
1208}
1209
Paul Duffin13f02712020-03-06 12:30:43 +00001210func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1211 if required {
1212 return requiredSdkMemberReferencePropertyTag
1213 } else {
1214 return optionalSdkMemberReferencePropertyTag
1215 }
1216}
1217
1218func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1219 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001220}
1221
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001222// Get a name for sdk snapshot member. If the member is private then generate a snapshot specific
1223// name. As part of the processing this checks to make sure that any required members are part of
1224// the snapshot.
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001225func (s *snapshotBuilder) snapshotSdkMemberName(name string, required bool) string {
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001226 if _, ok := s.allMembersByName[name]; !ok {
Paul Duffin13f02712020-03-06 12:30:43 +00001227 if required {
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001228 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", name)
Paul Duffin13f02712020-03-06 12:30:43 +00001229 }
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001230 return name
Paul Duffin13f02712020-03-06 12:30:43 +00001231 }
1232
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001233 if s.isInternalMember(name) {
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001234 return s.ctx.ModuleName() + "_" + name
Paul Duffin72910952020-01-20 18:16:30 +00001235 } else {
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001236 return name
Paul Duffin72910952020-01-20 18:16:30 +00001237 }
1238}
1239
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001240func (s *snapshotBuilder) snapshotSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001241 var references []string = nil
1242 for _, m := range members {
Paul Duffin1938dba2022-07-26 23:53:00 +00001243 if _, ok := s.excludedMembersByName[m]; ok {
1244 continue
1245 }
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001246 references = append(references, s.snapshotSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001247 }
1248 return references
1249}
1250
Paul Duffin13f02712020-03-06 12:30:43 +00001251func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1252 _, ok := s.exportedMembersByName[memberName]
1253 return !ok
1254}
1255
Martin Stjernholm89238f42020-07-10 00:14:03 +01001256// Add the properties from the given SdkMemberProperties to the blueprint
1257// property set. This handles common properties in SdkMemberPropertiesBase and
1258// calls the member-specific AddToPropertySet for the rest.
1259func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1260 if memberProperties.Base().Compile_multilib != "" {
1261 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1262 }
1263
1264 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1265}
1266
Paul Duffin21827262021-04-24 12:16:36 +01001267// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1268type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001269 // The sdk variant that depends (possibly indirectly) on the member variant.
1270 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001271
1272 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001273 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001274
1275 // The variant that is added to the sdk.
Paul Duffin5e71e682022-11-23 18:09:54 +00001276 variant android.Module
Paul Duffinb97b1572021-04-29 21:50:40 +01001277
Paul Duffinc6ba1822022-05-06 09:38:02 +00001278 // The optional container of this member, i.e. the module that is depended upon by the sdk
1279 // (possibly transitively) and whose dependency on this module is why it was added to the sdk.
1280 // Is nil if this a direct dependency of the sdk.
Paul Duffin5e71e682022-11-23 18:09:54 +00001281 container android.Module
Paul Duffinc6ba1822022-05-06 09:38:02 +00001282
Paul Duffinb97b1572021-04-29 21:50:40 +01001283 // True if the member should be exported, i.e. accessible, from outside the sdk.
1284 export bool
1285
1286 // The names of additional component modules provided by the variant.
1287 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1938dba2022-07-26 23:53:00 +00001288
1289 // The minimum API level on which this module is supported.
1290 minApiLevel android.ApiLevel
Paul Duffin1356d8c2020-02-25 19:26:33 +00001291}
1292
Spandan Dasb84dbb22023-03-08 22:06:35 +00001293// Host returns true if the sdk member is a host variant (e.g. host tool)
1294func (s *sdkMemberVariantDep) Host() bool {
1295 return s.variant.Target().Os.Class == android.Host
1296}
1297
Paul Duffin13879572019-11-28 14:31:38 +00001298var _ android.SdkMember = (*sdkMember)(nil)
1299
Paul Duffin21827262021-04-24 12:16:36 +01001300// sdkMember groups all the variants of a specific member module together along with the name of the
1301// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001302type sdkMember struct {
1303 memberType android.SdkMemberType
1304 name string
Paul Duffin5e71e682022-11-23 18:09:54 +00001305 variants []android.Module
Paul Duffin13879572019-11-28 14:31:38 +00001306}
1307
1308func (m *sdkMember) Name() string {
1309 return m.name
1310}
1311
Paul Duffin5e71e682022-11-23 18:09:54 +00001312func (m *sdkMember) Variants() []android.Module {
Paul Duffin13879572019-11-28 14:31:38 +00001313 return m.variants
1314}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001315
Paul Duffin9c3760e2020-03-16 19:52:08 +00001316// Track usages of multilib variants.
1317type multilibUsage int
1318
1319const (
1320 multilibNone multilibUsage = 0
1321 multilib32 multilibUsage = 1
1322 multilib64 multilibUsage = 2
1323 multilibBoth = multilib32 | multilib64
1324)
1325
1326// Add the multilib that is used in the arch type.
1327func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1328 multilib := archType.Multilib
1329 switch multilib {
1330 case "":
1331 return m
1332 case "lib32":
1333 return m | multilib32
1334 case "lib64":
1335 return m | multilib64
1336 default:
1337 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1338 }
1339}
1340
1341func (m multilibUsage) String() string {
1342 switch m {
1343 case multilibNone:
1344 return ""
1345 case multilib32:
1346 return "32"
1347 case multilib64:
1348 return "64"
1349 case multilibBoth:
1350 return "both"
1351 default:
1352 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1353 m, multilibNone, multilib32, multilib64, multilibBoth))
1354 }
1355}
1356
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001357// TODO(187910671): BEGIN - Remove once modules do not have an APEX and default variant.
1358// variantCoordinate contains the coordinates used to identify a variant of an SDK member.
1359type variantCoordinate struct {
1360 // osType identifies the OS target of a variant.
1361 osType android.OsType
1362 // archId identifies the architecture and whether it is for the native bridge.
1363 archId archId
1364 // image is the image variant name.
1365 image string
1366 // linkType is the link type name.
1367 linkType string
1368}
1369
1370func getVariantCoordinate(ctx *memberContext, variant android.Module) variantCoordinate {
1371 linkType := ""
1372 if len(ctx.MemberType().SupportedLinkages()) > 0 {
1373 linkType = getLinkType(variant)
1374 }
1375 return variantCoordinate{
1376 osType: variant.Target().Os,
1377 archId: archIdFromTarget(variant.Target()),
1378 image: variant.ImageVariation().Variation,
1379 linkType: linkType,
1380 }
1381}
1382
1383// selectApexVariantsWhereAvailable filters the input list of variants by selecting the APEX
1384// specific variant for a specific variantCoordinate when there is both an APEX and default variant.
1385//
1386// There is a long-standing issue where a module that is added to an APEX has both an APEX and
1387// default/platform variant created even when the module does not require a platform variant. As a
1388// result an indirect dependency onto a module via the APEX will use the APEX variant, whereas a
1389// direct dependency onto the module will use the default/platform variant. That would result in a
1390// failure while attempting to optimize the properties for a member as it would have two variants
1391// when only one was expected.
1392//
1393// This function mitigates that problem by detecting when there are two variants that differ only
1394// by apex variant, where one is the default/platform variant and one is the APEX variant. In that
1395// case it picks the APEX variant. It picks the APEX variant because that is the behavior that would
1396// be expected
Paul Duffin5e71e682022-11-23 18:09:54 +00001397func selectApexVariantsWhereAvailable(ctx *memberContext, variants []android.Module) []android.Module {
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001398 moduleCtx := ctx.sdkMemberContext
1399
1400 // Group the variants by coordinates.
Paul Duffin5e71e682022-11-23 18:09:54 +00001401 variantsByCoord := make(map[variantCoordinate][]android.Module)
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001402 for _, variant := range variants {
1403 coord := getVariantCoordinate(ctx, variant)
1404 variantsByCoord[coord] = append(variantsByCoord[coord], variant)
1405 }
1406
Paul Duffin5e71e682022-11-23 18:09:54 +00001407 toDiscard := make(map[android.Module]struct{})
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001408 for coord, list := range variantsByCoord {
1409 count := len(list)
1410 if count == 1 {
1411 continue
1412 }
1413
Paul Duffin5e71e682022-11-23 18:09:54 +00001414 variantsByApex := make(map[string]android.Module)
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001415 conflictDetected := false
1416 for _, variant := range list {
Colin Cross313aa542023-12-13 13:47:44 -08001417 apexInfo, _ := android.OtherModuleProvider(moduleCtx, variant, android.ApexInfoProvider)
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001418 apexVariationName := apexInfo.ApexVariationName
1419 // If there are two variants for a specific APEX variation then there is conflict.
1420 if _, ok := variantsByApex[apexVariationName]; ok {
1421 conflictDetected = true
1422 break
1423 }
1424 variantsByApex[apexVariationName] = variant
1425 }
1426
1427 // If there are more than 2 apex variations or one of the apex variations is not the
1428 // default/platform variation then there is a conflict.
1429 if len(variantsByApex) != 2 {
1430 conflictDetected = true
1431 } else if _, ok := variantsByApex[""]; !ok {
1432 conflictDetected = true
1433 }
1434
1435 // If there are no conflicts then add the default/platform variation to the list to remove.
1436 if !conflictDetected {
1437 toDiscard[variantsByApex[""]] = struct{}{}
1438 continue
1439 }
1440
1441 // There are duplicate variants at this coordinate and they are not the default and APEX variant
1442 // so fail.
1443 variantDescriptions := []string{}
1444 for _, m := range list {
1445 variantDescriptions = append(variantDescriptions, fmt.Sprintf(" %s", m.String()))
1446 }
1447
1448 moduleCtx.ModuleErrorf("multiple conflicting variants detected for OsType{%s}, %s, Image{%s}, Link{%s}\n%s",
1449 coord.osType, coord.archId.String(), coord.image, coord.linkType,
1450 strings.Join(variantDescriptions, "\n"))
1451 }
1452
1453 // If there are any variants to discard then remove them from the list of variants, while
1454 // preserving the order.
1455 if len(toDiscard) > 0 {
Paul Duffin5e71e682022-11-23 18:09:54 +00001456 filtered := []android.Module{}
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001457 for _, variant := range variants {
1458 if _, ok := toDiscard[variant]; !ok {
1459 filtered = append(filtered, variant)
1460 }
1461 }
1462 variants = filtered
1463 }
1464
1465 return variants
1466}
1467
1468// TODO(187910671): END - Remove once modules do not have an APEX and default variant.
1469
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001470type baseInfo struct {
1471 Properties android.SdkMemberProperties
1472}
1473
Paul Duffinf34f6d82020-04-30 15:48:31 +01001474func (b *baseInfo) optimizableProperties() interface{} {
1475 return b.Properties
1476}
1477
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001478type osTypeSpecificInfo struct {
1479 baseInfo
1480
Paul Duffin00e46802020-03-12 20:40:35 +00001481 osType android.OsType
1482
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001483 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001484 //
1485 // Nil if there is one variant whose arch type is common
1486 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001487}
1488
Paul Duffin4b8b7932020-05-06 12:35:38 +01001489var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1490
Paul Duffinfc8dd232020-03-17 12:51:37 +00001491type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1492
Paul Duffin00e46802020-03-12 20:40:35 +00001493// Create a new osTypeSpecificInfo for the specified os type and its properties
1494// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001495func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001496 osInfo := &osTypeSpecificInfo{
1497 osType: osType,
1498 }
1499
1500 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1501 properties := variantPropertiesFactory()
1502 properties.Base().Os = osType
1503 return properties
1504 }
1505
1506 // Create a structure into which properties common across the architectures in
1507 // this os type will be stored.
1508 osInfo.Properties = osSpecificVariantPropertiesFactory()
1509
1510 // Group the variants by arch type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001511 var variantsByArchId = make(map[archId][]android.Module)
1512 var archIds []archId
Paul Duffin00e46802020-03-12 20:40:35 +00001513 for _, variant := range osTypeVariants {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001514 target := variant.Target()
1515 id := archIdFromTarget(target)
1516 if _, ok := variantsByArchId[id]; !ok {
1517 archIds = append(archIds, id)
Paul Duffin00e46802020-03-12 20:40:35 +00001518 }
1519
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001520 variantsByArchId[id] = append(variantsByArchId[id], variant)
Paul Duffin00e46802020-03-12 20:40:35 +00001521 }
1522
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001523 if commonVariants, ok := variantsByArchId[commonArchId]; ok {
Paul Duffin00e46802020-03-12 20:40:35 +00001524 if len(osTypeVariants) != 1 {
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001525 variants := []string{}
1526 for _, m := range osTypeVariants {
1527 variants = append(variants, fmt.Sprintf(" %s", m.String()))
1528 }
1529 panic(fmt.Errorf("expected to only have 1 variant of %q when arch type is common but found %d\n%s",
1530 ctx.Name(),
1531 len(osTypeVariants),
1532 strings.Join(variants, "\n")))
Paul Duffin00e46802020-03-12 20:40:35 +00001533 }
1534
1535 // A common arch type only has one variant and its properties should be treated
1536 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001537 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001538 } else {
1539 // Create an arch specific info for each supported architecture type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001540 for _, id := range archIds {
1541 archVariants := variantsByArchId[id]
1542 archInfo := newArchSpecificInfo(ctx, id, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001543
1544 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1545 }
1546 }
1547
1548 return osInfo
1549}
1550
Paul Duffin39abf8f2021-09-24 14:58:27 +01001551func (osInfo *osTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1552 if len(osInfo.archInfos) == 0 {
1553 pruner.pruneProperties(osInfo.Properties)
1554 } else {
1555 for _, archInfo := range osInfo.archInfos {
1556 archInfo.pruneUnsupportedProperties(pruner)
1557 }
1558 }
1559}
1560
Paul Duffin00e46802020-03-12 20:40:35 +00001561// Optimize the properties by extracting common properties from arch type specific
1562// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001563func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001564 // Nothing to do if there is only a single common architecture.
1565 if len(osInfo.archInfos) == 0 {
1566 return
1567 }
1568
Paul Duffin9c3760e2020-03-16 19:52:08 +00001569 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001570 for _, archInfo := range osInfo.archInfos {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001571 multilib = multilib.addArchType(archInfo.archId.archType)
Paul Duffin9c3760e2020-03-16 19:52:08 +00001572
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001573 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001574 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001575 }
1576
Paul Duffin4b8b7932020-05-06 12:35:38 +01001577 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001578
1579 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001580 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001581}
1582
1583// Add the properties for an os to a property set.
1584//
1585// Maps the properties related to the os variants through to an appropriate
1586// module structure that will produce equivalent set of variants when it is
1587// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001588func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001589
1590 var osPropertySet android.BpPropertySet
1591 var archPropertySet android.BpPropertySet
1592 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001593 if osInfo.Properties.Base().Os_count == 1 &&
1594 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1595 // There is only one OS type present in the variants and it shouldn't have a
1596 // variant-specific target. The latter is the case if it's either for device
1597 // where there is only one OS (android), or for host and the member type
1598 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001599
1600 // Create a structure that looks like:
1601 // module_type {
1602 // name: "...",
1603 // ...
1604 // <common properties>
1605 // ...
1606 // <single os type specific properties>
1607 //
1608 // arch: {
1609 // <arch specific sections>
1610 // }
1611 //
1612 osPropertySet = bpModule
1613 archPropertySet = osPropertySet.AddPropertySet("arch")
1614
1615 // Arch specific properties need to be added to an arch specific section
1616 // within arch.
1617 archOsPrefix = ""
1618 } else {
1619 // Create a structure that looks like:
1620 // module_type {
1621 // name: "...",
1622 // ...
1623 // <common properties>
1624 // ...
1625 // target: {
1626 // <arch independent os specific sections, e.g. android>
1627 // ...
1628 // <arch and os specific sections, e.g. android_x86>
1629 // }
1630 //
1631 osType := osInfo.osType
1632 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1633 archPropertySet = targetPropertySet
1634
1635 // Arch specific properties need to be added to an os and arch specific
1636 // section prefixed with <os>_.
1637 archOsPrefix = osType.Name + "_"
1638 }
1639
1640 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001641 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001642
1643 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1644 // os) specific properties.
1645 //
1646 // The archInfos list will be empty if the os contains variants for the common
1647 // architecture.
1648 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001649 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001650 }
1651}
1652
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001653func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1654 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001655 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001656}
1657
1658var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1659
Paul Duffin4b8b7932020-05-06 12:35:38 +01001660func (osInfo *osTypeSpecificInfo) String() string {
1661 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1662}
1663
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001664// archId encapsulates the information needed to identify a combination of arch type and native
1665// bridge support.
1666//
1667// Conceptually, native bridge support is a facet of an android.Target, not an android.Arch as it is
1668// essentially using one android.Arch to implement another. However, in terms of the handling of
1669// the variants native bridge is treated as part of the arch variation. See the ArchVariation method
1670// on android.Target.
1671//
1672// So, it makes sense when optimizing the variants to combine native bridge with the arch type.
1673type archId struct {
1674 // The arch type of the variant's target.
1675 archType android.ArchType
1676
1677 // True if the variants is for the native bridge, false otherwise.
1678 nativeBridge bool
1679}
1680
1681// propertyName returns the name of the property corresponding to use for this arch id.
1682func (i *archId) propertyName() string {
1683 name := i.archType.Name
1684 if i.nativeBridge {
1685 // Note: This does not result in a valid property because there is no architecture specific
1686 // native bridge property, only a generic "native_bridge" property. However, this will be used
1687 // in error messages if there is an attempt to use this in a generated bp file.
1688 name += "_native_bridge"
1689 }
1690 return name
1691}
1692
1693func (i *archId) String() string {
1694 return fmt.Sprintf("ArchType{%s}, NativeBridge{%t}", i.archType, i.nativeBridge)
1695}
1696
1697// archIdFromTarget returns an archId initialized from information in the supplied target.
1698func archIdFromTarget(target android.Target) archId {
1699 return archId{
1700 archType: target.Arch.ArchType,
1701 nativeBridge: target.NativeBridge == android.NativeBridgeEnabled,
1702 }
1703}
1704
1705// commonArchId is the archId for the common architecture.
1706var commonArchId = archId{archType: android.Common}
1707
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001708type archTypeSpecificInfo struct {
1709 baseInfo
1710
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001711 archId archId
1712 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001713
Paul Duffinb42fa672021-09-09 16:37:49 +01001714 imageVariantInfos []*imageVariantSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001715}
1716
Paul Duffin4b8b7932020-05-06 12:35:38 +01001717var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1718
Paul Duffinfc8dd232020-03-17 12:51:37 +00001719// Create a new archTypeSpecificInfo for the specified arch type and its properties
1720// structures populated with information from the variants.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001721func newArchSpecificInfo(ctx android.SdkMemberContext, archId archId, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001722
Paul Duffinfc8dd232020-03-17 12:51:37 +00001723 // Create an arch specific info into which the variant properties can be copied.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001724 archInfo := &archTypeSpecificInfo{archId: archId, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001725
1726 // Create the properties into which the arch type specific properties will be
1727 // added.
1728 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001729
Liz Kammer96320df2022-05-12 20:40:00 -04001730 // if there are multiple supported link variants, we want to nest based on linkage even if there
1731 // is only one variant, otherwise, if there is only one variant we can populate based on the arch
1732 if len(archVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001733 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001734 } else {
Paul Duffinb42fa672021-09-09 16:37:49 +01001735 // Group the variants by image type.
1736 variantsByImage := make(map[string][]android.Module)
1737 for _, variant := range archVariants {
1738 image := variant.ImageVariation().Variation
1739 variantsByImage[image] = append(variantsByImage[image], variant)
1740 }
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001741
Paul Duffinb42fa672021-09-09 16:37:49 +01001742 // Create the image variant info in a fixed order.
Cole Faust18994c72023-02-28 16:02:16 -08001743 for _, imageVariantName := range android.SortedKeys(variantsByImage) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001744 variants := variantsByImage[imageVariantName]
1745 archInfo.imageVariantInfos = append(archInfo.imageVariantInfos, newImageVariantSpecificInfo(ctx, imageVariantName, variantPropertiesFactory, variants))
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001746 }
1747 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001748
1749 return archInfo
1750}
1751
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001752// Get the link type of the variant
1753//
1754// If the variant is not differentiated by link type then it returns "",
1755// otherwise it returns one of "static" or "shared".
1756func getLinkType(variant android.Module) string {
1757 linkType := ""
1758 if linkable, ok := variant.(cc.LinkableInterface); ok {
1759 if linkable.Shared() && linkable.Static() {
1760 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1761 } else if linkable.Shared() {
1762 linkType = "shared"
1763 } else if linkable.Static() {
1764 linkType = "static"
1765 } else {
1766 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1767 }
1768 }
1769 return linkType
1770}
1771
Paul Duffin39abf8f2021-09-24 14:58:27 +01001772func (archInfo *archTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1773 if len(archInfo.imageVariantInfos) == 0 {
1774 pruner.pruneProperties(archInfo.Properties)
1775 } else {
1776 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1777 imageVariantInfo.pruneUnsupportedProperties(pruner)
1778 }
1779 }
1780}
1781
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001782// Optimize the properties by extracting common properties from link type specific
1783// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001784func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001785 if len(archInfo.imageVariantInfos) == 0 {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001786 return
1787 }
1788
Paul Duffinb42fa672021-09-09 16:37:49 +01001789 // Optimize the image variant properties first.
1790 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1791 imageVariantInfo.optimizeProperties(ctx, commonValueExtractor)
1792 }
1793
1794 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.imageVariantInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001795}
1796
Paul Duffinfc8dd232020-03-17 12:51:37 +00001797// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001798func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001799 archPropertySuffix := archInfo.archId.propertyName()
1800 propertySetName := archOsPrefix + archPropertySuffix
1801 archTypePropertySet := archPropertySet.AddPropertySet(propertySetName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001802 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1803 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1804 archTypePropertySet.AddProperty("enabled", true)
1805 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001806 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001807
Paul Duffinb42fa672021-09-09 16:37:49 +01001808 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1809 imageVariantInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001810 }
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001811
1812 // If this is for a native bridge architecture then make sure that the property set does not
1813 // contain any properties as providing native bridge specific properties is not currently
1814 // supported.
1815 if archInfo.archId.nativeBridge {
1816 propertySetContents := getPropertySetContents(archTypePropertySet)
1817 if propertySetContents != "" {
1818 ctx.SdkModuleContext().ModuleErrorf("Architecture variant %q of sdk member %q has properties distinct from other variants; this is not yet supported. The properties are:\n%s",
1819 propertySetName, ctx.name, propertySetContents)
1820 }
1821 }
1822}
1823
1824// getPropertySetContents returns the string representation of the contents of a property set, after
1825// recursively pruning any empty nested property sets.
1826func getPropertySetContents(propertySet android.BpPropertySet) string {
1827 set := propertySet.(*bpPropertySet)
1828 set.transformContents(pruneEmptySetTransformer{})
1829 if len(set.properties) != 0 {
1830 contents := &generatedContents{}
1831 contents.Indent()
1832 outputPropertySet(contents, set)
1833 setAsString := contents.content.String()
1834 return setAsString
1835 }
1836 return ""
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001837}
1838
Paul Duffin4b8b7932020-05-06 12:35:38 +01001839func (archInfo *archTypeSpecificInfo) String() string {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001840 return archInfo.archId.String()
Paul Duffin4b8b7932020-05-06 12:35:38 +01001841}
1842
Paul Duffinb42fa672021-09-09 16:37:49 +01001843type imageVariantSpecificInfo struct {
1844 baseInfo
1845
1846 imageVariant string
1847
1848 linkInfos []*linkTypeSpecificInfo
1849}
1850
1851func newImageVariantSpecificInfo(ctx android.SdkMemberContext, imageVariant string, variantPropertiesFactory variantPropertiesFactoryFunc, imageVariants []android.Module) *imageVariantSpecificInfo {
1852
1853 // Create an image variant specific info into which the variant properties can be copied.
1854 imageInfo := &imageVariantSpecificInfo{imageVariant: imageVariant}
1855
1856 // Create the properties into which the image variant specific properties will be added.
1857 imageInfo.Properties = variantPropertiesFactory()
1858
Liz Kammer96320df2022-05-12 20:40:00 -04001859 // if there are multiple supported link variants, we want to nest even if there is only one
1860 // variant, otherwise, if there is only one variant we can populate based on the image
1861 if len(imageVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffinb42fa672021-09-09 16:37:49 +01001862 imageInfo.Properties.PopulateFromVariant(ctx, imageVariants[0])
1863 } else {
1864 // There is more than one variant for this image variant which must be differentiated by link
Liz Kammer96320df2022-05-12 20:40:00 -04001865 // type. Or there are multiple supported linkages and we need to nest based on link type.
Paul Duffinb42fa672021-09-09 16:37:49 +01001866 for _, linkVariant := range imageVariants {
1867 linkType := getLinkType(linkVariant)
1868 if linkType == "" {
1869 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(imageVariants)))
1870 } else {
1871 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
1872
1873 imageInfo.linkInfos = append(imageInfo.linkInfos, linkInfo)
1874 }
1875 }
1876 }
1877
1878 return imageInfo
1879}
1880
Paul Duffin39abf8f2021-09-24 14:58:27 +01001881func (imageInfo *imageVariantSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1882 if len(imageInfo.linkInfos) == 0 {
1883 pruner.pruneProperties(imageInfo.Properties)
1884 } else {
1885 for _, linkInfo := range imageInfo.linkInfos {
1886 linkInfo.pruneUnsupportedProperties(pruner)
1887 }
1888 }
1889}
1890
Paul Duffinb42fa672021-09-09 16:37:49 +01001891// Optimize the properties by extracting common properties from link type specific
1892// properties into arch type specific properties.
1893func (imageInfo *imageVariantSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
1894 if len(imageInfo.linkInfos) == 0 {
1895 return
1896 }
1897
1898 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, imageInfo.Properties, imageInfo.linkInfos)
1899}
1900
1901// Add the properties for an arch type to a property set.
1902func (imageInfo *imageVariantSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1903 if imageInfo.imageVariant != android.CoreVariation {
1904 propertySet = propertySet.AddPropertySet(imageInfo.imageVariant)
1905 }
1906
1907 addSdkMemberPropertiesToSet(ctx, imageInfo.Properties, propertySet)
1908
Liz Kammer96320df2022-05-12 20:40:00 -04001909 usedLinkages := make(map[string]bool, len(imageInfo.linkInfos))
Paul Duffinb42fa672021-09-09 16:37:49 +01001910 for _, linkInfo := range imageInfo.linkInfos {
Liz Kammer96320df2022-05-12 20:40:00 -04001911 usedLinkages[linkInfo.linkType] = true
Paul Duffinb42fa672021-09-09 16:37:49 +01001912 linkInfo.addToPropertySet(ctx, propertySet)
1913 }
1914
Liz Kammer96320df2022-05-12 20:40:00 -04001915 // If not all supported linkages had existing variants, we need to disable the unsupported variant
1916 if len(imageInfo.linkInfos) < len(ctx.MemberType().SupportedLinkages()) {
1917 for _, l := range ctx.MemberType().SupportedLinkages() {
1918 if _, ok := usedLinkages[l]; !ok {
1919 otherLinkagePropertySet := propertySet.AddPropertySet(l)
1920 otherLinkagePropertySet.AddProperty("enabled", false)
1921 }
1922 }
1923 }
1924
Paul Duffinb42fa672021-09-09 16:37:49 +01001925 // If this is for a non-core image variant then make sure that the property set does not contain
1926 // any properties as providing non-core image variant specific properties for prebuilts is not
1927 // currently supported.
1928 if imageInfo.imageVariant != android.CoreVariation {
1929 propertySetContents := getPropertySetContents(propertySet)
1930 if propertySetContents != "" {
1931 ctx.SdkModuleContext().ModuleErrorf("Image variant %q of sdk member %q has properties distinct from other variants; this is not yet supported. The properties are:\n%s",
1932 imageInfo.imageVariant, ctx.name, propertySetContents)
1933 }
1934 }
1935}
1936
1937func (imageInfo *imageVariantSpecificInfo) String() string {
1938 return imageInfo.imageVariant
1939}
1940
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001941type linkTypeSpecificInfo struct {
1942 baseInfo
1943
1944 linkType string
1945}
1946
Paul Duffin4b8b7932020-05-06 12:35:38 +01001947var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1948
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001949// Create a new linkTypeSpecificInfo for the specified link type and its properties
1950// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001951func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001952 linkInfo := &linkTypeSpecificInfo{
1953 baseInfo: baseInfo{
1954 // Create the properties into which the link type specific properties will be
1955 // added.
1956 Properties: variantPropertiesFactory(),
1957 },
1958 linkType: linkType,
1959 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001960 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001961 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001962}
1963
Paul Duffinf68f85a2021-09-09 16:11:42 +01001964func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1965 linkPropertySet := propertySet.AddPropertySet(l.linkType)
1966 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
1967}
1968
Paul Duffin39abf8f2021-09-24 14:58:27 +01001969func (l *linkTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1970 pruner.pruneProperties(l.Properties)
1971}
1972
Paul Duffin4b8b7932020-05-06 12:35:38 +01001973func (l *linkTypeSpecificInfo) String() string {
1974 return fmt.Sprintf("LinkType{%s}", l.linkType)
1975}
1976
Paul Duffin3a4eb502020-03-19 16:11:18 +00001977type memberContext struct {
1978 sdkMemberContext android.ModuleContext
1979 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001980 memberType android.SdkMemberType
1981 name string
Paul Duffind19f8942021-07-14 12:08:37 +01001982
1983 // The set of traits required of this member.
1984 requiredTraits android.SdkMemberTraitSet
Paul Duffin3a4eb502020-03-19 16:11:18 +00001985}
1986
Cole Faust34867402023-04-28 12:32:27 -07001987func (m *memberContext) ModuleErrorf(fmt string, args ...interface{}) {
1988 m.sdkMemberContext.ModuleErrorf(fmt, args...)
1989}
1990
Paul Duffin3a4eb502020-03-19 16:11:18 +00001991func (m *memberContext) SdkModuleContext() android.ModuleContext {
1992 return m.sdkMemberContext
1993}
1994
1995func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1996 return m.builder
1997}
1998
Paul Duffina551a1c2020-03-17 21:04:24 +00001999func (m *memberContext) MemberType() android.SdkMemberType {
2000 return m.memberType
2001}
2002
2003func (m *memberContext) Name() string {
2004 return m.name
2005}
2006
Paul Duffind19f8942021-07-14 12:08:37 +01002007func (m *memberContext) RequiresTrait(trait android.SdkMemberTrait) bool {
2008 return m.requiredTraits.Contains(trait)
2009}
2010
Paul Duffin13648912022-07-15 13:12:35 +00002011func (m *memberContext) IsTargetBuildBeforeTiramisu() bool {
2012 return m.builder.targetBuildRelease.EarlierThan(buildReleaseT)
2013}
2014
2015var _ android.SdkMemberContext = (*memberContext)(nil)
2016
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01002017func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002018
2019 memberType := member.memberType
2020
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002021 // Do not add the prefer property if the member snapshot module is a source module type.
Paul Duffin4e7d1c42022-05-13 13:12:19 +00002022 moduleCtx := ctx.sdkMemberContext
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002023 if !memberType.UsesSourceModuleTypeInSnapshot() {
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002024 // Set prefer. Setting this to false is not strictly required as that is the default but it does
2025 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
2026 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
2027 // behavior is for the module.
Paul Duffin82d75ad2022-11-14 17:35:50 +00002028 bpModule.insertAfter("name", "prefer", false)
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002029 }
Paul Duffin83ad9562021-05-10 23:49:04 +01002030
Paul Duffin4e7d1c42022-05-13 13:12:19 +00002031 variants := selectApexVariantsWhereAvailable(ctx, member.variants)
2032
Paul Duffina04c1072020-03-02 10:16:35 +00002033 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00002034 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002035 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00002036 osType := variant.Target().Os
2037 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002038 }
2039
Paul Duffina04c1072020-03-02 10:16:35 +00002040 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00002041 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00002042 properties := memberType.CreateVariantPropertiesStruct()
2043 base := properties.Base()
2044 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00002045 return properties
2046 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002047
Paul Duffina04c1072020-03-02 10:16:35 +00002048 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00002049
Paul Duffina04c1072020-03-02 10:16:35 +00002050 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00002051 commonProperties := variantPropertiesFactory()
2052 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00002053
Paul Duffin39abf8f2021-09-24 14:58:27 +01002054 // Create a property pruner that will prune any properties unsupported by the target build
2055 // release.
2056 targetBuildRelease := ctx.builder.targetBuildRelease
2057 unsupportedPropertyPruner := newPropertyPrunerByBuildRelease(commonProperties, targetBuildRelease)
2058
Paul Duffinc097e362020-03-10 22:50:03 +00002059 // Create common value extractor that can be used to optimize the properties.
2060 commonValueExtractor := newCommonValueExtractor(commonProperties)
2061
Paul Duffina04c1072020-03-02 10:16:35 +00002062 // The list of property structures which are os type specific but common across
2063 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002064 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00002065
2066 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00002067 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00002068 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00002069 // Add the os specific properties to a list of os type specific yet architecture
2070 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002071 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00002072
Paul Duffin39abf8f2021-09-24 14:58:27 +01002073 osInfo.pruneUnsupportedProperties(unsupportedPropertyPruner)
2074
Paul Duffin00e46802020-03-12 20:40:35 +00002075 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002076 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00002077 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002078
Paul Duffina04c1072020-03-02 10:16:35 +00002079 // Extract properties which are common across all architectures and os types.
Paul Duffin4e7d1c42022-05-13 13:12:19 +00002080 extractCommonProperties(moduleCtx, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002081
Paul Duffina04c1072020-03-02 10:16:35 +00002082 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01002083 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002084
Paul Duffina04c1072020-03-02 10:16:35 +00002085 // Create a target property set into which target specific properties can be
2086 // added.
2087 targetPropertySet := bpModule.AddPropertySet("target")
2088
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01002089 // If the member is host OS dependent and has host_supported then disable by
2090 // default and enable each host OS variant explicitly. This avoids problems
2091 // with implicitly enabled OS variants when the snapshot is used, which might
2092 // be different from this run (e.g. different build OS).
2093 if ctx.memberType.IsHostOsDependent() {
2094 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
2095 if hostSupported {
2096 hostPropertySet := targetPropertySet.AddPropertySet("host")
2097 hostPropertySet.AddProperty("enabled", false)
2098 }
2099 }
2100
Paul Duffina04c1072020-03-02 10:16:35 +00002101 // Iterate over the os types in a fixed order.
2102 for _, osType := range s.getPossibleOsTypes() {
2103 osInfo := osTypeToInfo[osType]
2104 if osInfo == nil {
2105 continue
2106 }
2107
Paul Duffin3a4eb502020-03-19 16:11:18 +00002108 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002109 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002110}
2111
Paul Duffina04c1072020-03-02 10:16:35 +00002112// Compute the list of possible os types that this sdk could support.
2113func (s *sdk) getPossibleOsTypes() []android.OsType {
2114 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00002115 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00002116 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07002117 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00002118 osTypes = append(osTypes, osType)
2119 }
2120 }
2121 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09002122 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00002123 osTypes = append(osTypes, osType)
2124 }
2125 }
2126 }
2127 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
2128 return osTypes
2129}
2130
Paul Duffinb28369a2020-05-04 15:39:59 +01002131// Given a set of properties (struct value), return the value of the field within that
2132// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00002133type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
2134
Paul Duffinc459f892020-04-30 18:08:29 +01002135// Checks the metadata to determine whether the property should be ignored for the
2136// purposes of common value extraction or not.
2137type extractorMetadataPredicate func(metadata propertiesContainer) bool
2138
2139// Indicates whether optimizable properties are provided by a host variant or
2140// not.
2141type isHostVariant interface {
2142 isHostVariant() bool
2143}
2144
Paul Duffinb28369a2020-05-04 15:39:59 +01002145// A property that can be optimized by the commonValueExtractor.
2146type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01002147 // The name of the field for this property. It is a "."-separated path for
2148 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002149 name string
2150
Paul Duffinc459f892020-04-30 18:08:29 +01002151 // Filter that can use metadata associated with the properties being optimized
2152 // to determine whether the field should be ignored during common value
2153 // optimization.
2154 filter extractorMetadataPredicate
2155
Paul Duffinb28369a2020-05-04 15:39:59 +01002156 // Retrieves the value on which common value optimization will be performed.
2157 getter fieldAccessorFunc
2158
Paul Duffinbfdca962022-09-22 16:21:54 +01002159 // True if the field should never be cleared.
2160 //
2161 // This is set to true if and only if the field is annotated with `sdk:"keep"`.
2162 keep bool
2163
Paul Duffinb28369a2020-05-04 15:39:59 +01002164 // The empty value for the field.
2165 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01002166
2167 // True if the property can support arch variants false otherwise.
2168 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01002169}
2170
Paul Duffin4b8b7932020-05-06 12:35:38 +01002171func (p extractorProperty) String() string {
2172 return p.name
2173}
2174
Paul Duffinc097e362020-03-10 22:50:03 +00002175// Supports extracting common values from a number of instances of a properties
2176// structure into a separate common set of properties.
2177type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01002178 // The properties that the extractor can optimize.
2179 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00002180}
2181
2182// Create a new common value extractor for the structure type for the supplied
2183// properties struct.
2184//
2185// The returned extractor can be used on any properties structure of the same type
2186// as the supplied set of properties.
2187func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
2188 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
2189 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01002190 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00002191 return extractor
2192}
2193
2194// Gather the fields from the supplied structure type from which common values will
2195// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00002196//
Martin Stjernholmb0249572020-09-15 02:32:35 +01002197// This is recursive function. If it encounters a struct then it will recurse
2198// into it, passing in the accessor for the field and the struct name as prefix
2199// for the nested fields. That will then be used in the accessors for the fields
2200// in the embedded struct.
2201func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00002202 for f := 0; f < structType.NumField(); f++ {
2203 field := structType.Field(f)
2204 if field.PkgPath != "" {
2205 // Ignore unexported fields.
2206 continue
2207 }
2208
Paul Duffin02e25c82022-09-22 15:30:58 +01002209 // Ignore fields tagged with sdk:"ignore".
2210 if proptools.HasTag(field, "sdk", "ignore") {
Paul Duffinc097e362020-03-10 22:50:03 +00002211 continue
2212 }
2213
Paul Duffinc459f892020-04-30 18:08:29 +01002214 var filter extractorMetadataPredicate
2215
2216 // Add a filter
2217 if proptools.HasTag(field, "sdk", "ignored-on-host") {
2218 filter = func(metadata propertiesContainer) bool {
2219 if m, ok := metadata.(isHostVariant); ok {
2220 if m.isHostVariant() {
2221 return false
2222 }
2223 }
2224 return true
2225 }
2226 }
2227
Paul Duffinbfdca962022-09-22 16:21:54 +01002228 keep := proptools.HasTag(field, "sdk", "keep")
2229
Paul Duffinc097e362020-03-10 22:50:03 +00002230 // Save a copy of the field index for use in the function.
2231 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01002232
Martin Stjernholmb0249572020-09-15 02:32:35 +01002233 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01002234
Paul Duffinc097e362020-03-10 22:50:03 +00002235 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00002236 if containingStructAccessor != nil {
2237 // This is an embedded structure so first access the field for the embedded
2238 // structure.
2239 value = containingStructAccessor(value)
2240 }
2241
Paul Duffinc097e362020-03-10 22:50:03 +00002242 // Skip through interface and pointer values to find the structure.
2243 value = getStructValue(value)
2244
Paul Duffin4b8b7932020-05-06 12:35:38 +01002245 defer func() {
2246 if r := recover(); r != nil {
2247 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
2248 }
2249 }()
2250
Paul Duffinc097e362020-03-10 22:50:03 +00002251 // Return the field.
2252 return value.Field(fieldIndex)
2253 }
2254
Martin Stjernholmb0249572020-09-15 02:32:35 +01002255 if field.Type.Kind() == reflect.Struct {
2256 // Gather fields from the nested or embedded structure.
2257 var subNamePrefix string
2258 if field.Anonymous {
2259 subNamePrefix = namePrefix
2260 } else {
2261 subNamePrefix = name + "."
2262 }
2263 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00002264 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01002265 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01002266 name,
Paul Duffinc459f892020-04-30 18:08:29 +01002267 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01002268 fieldGetter,
Paul Duffinbfdca962022-09-22 16:21:54 +01002269 keep,
Paul Duffinb28369a2020-05-04 15:39:59 +01002270 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01002271 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01002272 }
2273 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00002274 }
Paul Duffinc097e362020-03-10 22:50:03 +00002275 }
2276}
2277
2278func getStructValue(value reflect.Value) reflect.Value {
2279foundStruct:
2280 for {
2281 kind := value.Kind()
2282 switch kind {
2283 case reflect.Interface, reflect.Ptr:
2284 value = value.Elem()
2285 case reflect.Struct:
2286 break foundStruct
2287 default:
2288 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
2289 }
2290 }
2291 return value
2292}
2293
Paul Duffinf34f6d82020-04-30 15:48:31 +01002294// A container of properties to be optimized.
2295//
2296// Allows additional information to be associated with the properties, e.g. for
2297// filtering.
2298type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002299 fmt.Stringer
2300
Paul Duffinf34f6d82020-04-30 15:48:31 +01002301 // Get the properties that need optimizing.
2302 optimizableProperties() interface{}
2303}
2304
Paul Duffin2d1bb892021-04-24 11:32:59 +01002305// A wrapper for sdk variant related properties to allow them to be optimized.
2306type sdkVariantPropertiesContainer struct {
2307 sdkVariant *sdk
2308 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01002309}
2310
Paul Duffin2d1bb892021-04-24 11:32:59 +01002311func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
2312 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01002313}
2314
Paul Duffin2d1bb892021-04-24 11:32:59 +01002315func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002316 return c.sdkVariant.String()
2317}
2318
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002319// Extract common properties from a slice of property structures of the same type.
2320//
2321// All the property structures must be of the same type.
2322// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002323// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002324//
2325// Iterates over each exported field (capitalized name) and checks to see whether they
2326// have the same value (using DeepEquals) across all the input properties. If it does not then no
2327// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01002328// and the field in each of the input properties structure is set to its default value. Nested
2329// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002330func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002331 commonPropertiesValue := reflect.ValueOf(commonProperties)
2332 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002333
Paul Duffinf34f6d82020-04-30 15:48:31 +01002334 sliceValue := reflect.ValueOf(inputPropertiesSlice)
2335
Paul Duffinb28369a2020-05-04 15:39:59 +01002336 for _, property := range e.properties {
2337 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01002338 filter := property.filter
2339 if filter == nil {
2340 filter = func(metadata propertiesContainer) bool {
2341 return true
2342 }
2343 }
Paul Duffinb28369a2020-05-04 15:39:59 +01002344
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002345 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002346 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2347 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002348 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002349
Paul Duffin864e1b42020-05-06 10:23:19 +01002350 // Assume that all the values will be the same.
2351 //
2352 // While similar to this is not quite the same as commonValue == nil. If all the values
2353 // have been filtered out then this will be false but commonValue == nil will be true.
2354 valuesDiffer := false
2355
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002356 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002357 container := sliceValue.Index(i).Interface().(propertiesContainer)
2358 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002359 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002360
Paul Duffinc459f892020-04-30 18:08:29 +01002361 if !filter(container) {
2362 expectedValue := property.emptyValue.Interface()
2363 actualValue := fieldValue.Interface()
2364 if !reflect.DeepEqual(expectedValue, actualValue) {
2365 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2366 }
2367 continue
2368 }
2369
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002370 if commonValue == nil {
2371 // Use the first value as the commonProperties value.
2372 commonValue = &fieldValue
2373 } else {
2374 // If the value does not match the current common value then there is
2375 // no value in common so break out.
2376 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2377 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002378 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002379 break
2380 }
2381 }
2382 }
2383
Paul Duffin864e1b42020-05-06 10:23:19 +01002384 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002385 // and set the input struct's field to the empty value.
2386 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002387 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002388 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffinbfdca962022-09-22 16:21:54 +01002389 if !property.keep {
2390 for i := 0; i < sliceValue.Len(); i++ {
2391 container := sliceValue.Index(i).Interface().(propertiesContainer)
2392 itemValue := reflect.ValueOf(container.optimizableProperties())
2393 fieldValue := fieldGetter(itemValue)
2394 fieldValue.Set(emptyValue)
2395 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002396 }
2397 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002398
2399 if valuesDiffer && !property.archVariant {
2400 // The values differ but the property does not support arch variants so it
2401 // is an error.
2402 var details strings.Builder
2403 for i := 0; i < sliceValue.Len(); i++ {
2404 container := sliceValue.Index(i).Interface().(propertiesContainer)
2405 itemValue := reflect.ValueOf(container.optimizableProperties())
2406 fieldValue := fieldGetter(itemValue)
2407
2408 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2409 }
2410
2411 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2412 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002413 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002414
2415 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002416}