blob: afecf9fe235fdafe6731be9273ab856bb9271e9a [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"
Spandan Dasa5e26d32024-03-06 14:04:36 +000027 "android/soong/java"
Colin Crosscb0ac952021-07-20 13:17:15 -070028
Paul Duffin375058f2019-11-29 20:17:53 +000029 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090030 "github.com/google/blueprint/proptools"
31
32 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090033)
34
Paul Duffin64fb5262021-05-05 21:36:04 +010035// Environment variables that affect the generated snapshot
36// ========================================================
37//
Paul Duffin39abf8f2021-09-24 14:58:27 +010038// SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE
39// This allows the target build release (i.e. the release version of the build within which
40// the snapshot will be used) of the snapshot to be specified. If unspecified then it defaults
41// to the current build release version. Otherwise, it must be the name of one of the build
42// releases defined in nameToBuildRelease, e.g. S, T, etc..
43//
44// The generated snapshot must only be used in the specified target release. If the target
45// build release is not the current build release then the generated Android.bp file not be
46// checked for compatibility.
47//
48// e.g. if setting SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE=S will cause the generated snapshot
49// to be compatible with S.
50//
Paul Duffin64fb5262021-05-05 21:36:04 +010051
Jiyong Park9b409bc2019-10-11 14:59:13 +090052var pctx = android.NewPackageContext("android/soong/sdk")
53
Paul Duffin375058f2019-11-29 20:17:53 +000054var (
55 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
56 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000057 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000058 CommandDeps: []string{
59 "${config.Zip2ZipCmd}",
60 },
61 },
62 "destdir")
63
64 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
65 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -070066 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +000067 CommandDeps: []string{
68 "${config.SoongZipCmd}",
69 },
70 Rspfile: "$out.rsp",
71 RspfileContent: "$in",
72 },
73 "basedir")
74
75 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
76 blueprint.RuleParams{
Paul Duffin74f1dcd2022-07-18 13:18:23 +000077 Command: `${config.MergeZipsCmd} -s $out $in`,
Paul Duffin375058f2019-11-29 20:17:53 +000078 CommandDeps: []string{
79 "${config.MergeZipsCmd}",
80 },
81 })
82)
83
Paul Duffin43f7bf02021-05-05 22:00:51 +010084const (
Paul Duffinb01ac4b2022-05-24 20:10:05 +000085 soongSdkSnapshotVersionCurrent = "current"
Paul Duffin43f7bf02021-05-05 22:00:51 +010086)
87
Paul Duffinb645ec82019-11-27 17:43:54 +000088type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090089 content strings.Builder
90 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090091}
92
Paul Duffinb645ec82019-11-27 17:43:54 +000093func (gc *generatedContents) Indent() {
94 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +090095}
96
Paul Duffinb645ec82019-11-27 17:43:54 +000097func (gc *generatedContents) Dedent() {
98 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +090099}
100
Paul Duffina08e4dc2021-06-22 18:19:19 +0100101// IndentedPrintf will add spaces to indent the line to the appropriate level before printing the
102// arguments.
103func (gc *generatedContents) IndentedPrintf(format string, args ...interface{}) {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000104 _, _ = fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100105}
106
107// UnindentedPrintf does not add spaces to indent the line to the appropriate level before printing
108// the arguments.
109func (gc *generatedContents) UnindentedPrintf(format string, args ...interface{}) {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000110 _, _ = fmt.Fprintf(&(gc.content), format, args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900111}
112
Paul Duffin13879572019-11-28 14:31:38 +0000113// Collect all the members.
114//
Paul Duffinb97b1572021-04-29 21:50:40 +0100115// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
116// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000117func (s *sdk) collectMembers(ctx android.ModuleContext) {
118 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000119 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
120 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf7b3d0d2021-09-02 14:29:21 +0100121 if memberTag, ok := tag.(android.SdkMemberDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100122 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900123
Paul Duffin5cca7c42021-05-26 10:16:01 +0100124 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
125 if memberType == nil {
126 return false
127 }
128
Paul Duffin13879572019-11-28 14:31:38 +0000129 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000130 if !memberType.IsInstance(child) {
131 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900132 }
Paul Duffin13879572019-11-28 14:31:38 +0000133
Paul Duffin6a7e9532020-03-20 17:50:07 +0000134 // Keep track of which multilib variants are used by the sdk.
135 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
136
Colin Cross313aa542023-12-13 13:47:44 -0800137 exportedComponentsInfo, _ := android.OtherModuleProvider(ctx, child, android.ExportedComponentsInfoProvider)
Paul Duffinb97b1572021-04-29 21:50:40 +0100138
Paul Duffin5e71e682022-11-23 18:09:54 +0000139 var container android.Module
Paul Duffinc6ba1822022-05-06 09:38:02 +0000140 if parent != ctx.Module() {
Cole Fausted158f42024-03-07 16:41:27 -0800141 container = parent
Paul Duffinc6ba1822022-05-06 09:38:02 +0000142 }
143
Paul Duffin1938dba2022-07-26 23:53:00 +0000144 minApiLevel := android.MinApiLevelForSdkSnapshot(ctx, child)
145
Paul Duffina7208112021-04-23 21:20:20 +0100146 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100147 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
Paul Duffinc6ba1822022-05-06 09:38:02 +0000148 sdkVariant: s,
149 memberType: memberType,
Cole Fausted158f42024-03-07 16:41:27 -0800150 variant: child,
Paul Duffin1938dba2022-07-26 23:53:00 +0000151 minApiLevel: minApiLevel,
Paul Duffinc6ba1822022-05-06 09:38:02 +0000152 container: container,
153 export: export,
154 exportedComponentsInfo: exportedComponentsInfo,
Paul Duffinb97b1572021-04-29 21:50:40 +0100155 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000156
Paul Duffin2d3da312021-05-06 12:02:27 +0100157 // Recurse down into the member's dependencies as it may have dependencies that need to be
158 // automatically added to the sdk.
159 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900160 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000161
162 return false
Paul Duffin13879572019-11-28 14:31:38 +0000163 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000164}
165
Spandan Dascfff9242024-03-25 20:31:32 +0000166// A denylist of modules whose host variants will be removed from the generated snapshots above the ApiLevel
167// even if they are listed in the corresponding `sdk`.
168// The key is the module name
169// The value is the _last_ dessert where the host variant of the module will be present
170// This is a workaround to ensure that these modules are generated in <=$ApiLevel, but not in in >=$ApiLevel
171var ignoreHostModuleVariantsAboveDessert = map[string]android.ApiLevel{
172 // ignore host variant of libdexfile and its transitive dependencies.
173 // The platform test that depends on them (`libunwindstack_unit_test` at the time of writing)
174 // no longer requires a prebuilt variant of libdexfile.
175 "libdexfile": android.ApiLevelUpsideDownCake,
176 "libartpalette": android.ApiLevelUpsideDownCake,
177 "libartbase": android.ApiLevelUpsideDownCake,
178}
179
Paul Duffincc3132e2021-04-24 01:10:30 +0100180// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
181// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000182//
Paul Duffincc3132e2021-04-24 01:10:30 +0100183// The sdkMember instances are then grouped into slices by member type. Within each such slice the
184// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000185//
Paul Duffincc3132e2021-04-24 01:10:30 +0100186// Finally, the member type slices are concatenated together to form a single slice. The order in
187// which they are concatenated is the order in which the member types were registered in the
188// android.SdkMemberTypesRegistry.
Paul Duffinf861df72022-07-01 15:56:06 +0000189func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, targetBuildRelease *buildRelease, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000190 byType := make(map[android.SdkMemberType][]*sdkMember)
191 byName := make(map[string]*sdkMember)
192
Paul Duffin21827262021-04-24 12:16:36 +0100193 for _, memberVariantDep := range memberVariantDeps {
194 memberType := memberVariantDep.memberType
195 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000196
197 name := ctx.OtherModuleName(variant)
Spandan Dascfff9242024-03-25 20:31:32 +0000198 targetApiLevel, err := android.ApiLevelFromUser(ctx, targetBuildRelease.name)
199 if err != nil {
200 targetApiLevel = android.FutureApiLevel
201 }
202 if lastApiLevel, exists := ignoreHostModuleVariantsAboveDessert[name]; exists && targetApiLevel.GreaterThan(lastApiLevel) && memberVariantDep.Host() {
203 // ignore host variant of this module if the targetApiLevel is V and above.
204 continue
205 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000206 member := byName[name]
207 if member == nil {
208 member = &sdkMember{memberType: memberType, name: name}
209 byName[name] = member
210 byType[memberType] = append(byType[memberType], member)
Liz Kammer96320df2022-05-12 20:40:00 -0400211 } else if member.memberType != memberType {
212 // validate whether this is the same member type or and overriding member type
213 if memberType.Overrides(member.memberType) {
214 member.memberType = memberType
215 } else if !member.memberType.Overrides(memberType) {
216 ctx.ModuleErrorf("Incompatible member types %q %q", member.memberType, memberType)
217 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000218 }
219
Paul Duffin1356d8c2020-02-25 19:26:33 +0000220 // Only append new variants to the list. This is needed because a member can be both
221 // exported by the sdk and also be a transitive sdk member.
222 member.variants = appendUniqueVariants(member.variants, variant)
223 }
Paul Duffin13879572019-11-28 14:31:38 +0000224 var members []*sdkMember
Paul Duffin62782de2021-07-14 12:05:16 +0100225 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffinf861df72022-07-01 15:56:06 +0000226 memberType := memberListProperty.memberType
227
228 if !isMemberTypeSupportedByTargetBuildRelease(memberType, targetBuildRelease) {
229 continue
230 }
231
232 membersOfType := byType[memberType]
Paul Duffin13879572019-11-28 14:31:38 +0000233 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900234 }
235
Paul Duffin6a7e9532020-03-20 17:50:07 +0000236 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900237}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900238
Paul Duffinf861df72022-07-01 15:56:06 +0000239// isMemberTypeSupportedByTargetBuildRelease returns true if the member type is supported by the
240// target build release.
241func isMemberTypeSupportedByTargetBuildRelease(memberType android.SdkMemberType, targetBuildRelease *buildRelease) bool {
242 supportedByTargetBuildRelease := true
243 supportedBuildReleases := memberType.SupportedBuildReleases()
244 if supportedBuildReleases == "" {
245 supportedBuildReleases = "S+"
246 }
247
248 set, err := parseBuildReleaseSet(supportedBuildReleases)
249 if err != nil {
250 panic(fmt.Errorf("member type %s has invalid supported build releases %q: %s",
251 memberType.SdkPropertyName(), supportedBuildReleases, err))
252 }
253 if !set.contains(targetBuildRelease) {
254 supportedByTargetBuildRelease = false
255 }
256 return supportedByTargetBuildRelease
257}
258
Paul Duffin5e71e682022-11-23 18:09:54 +0000259func appendUniqueVariants(variants []android.Module, newVariant android.Module) []android.Module {
Paul Duffin72910952020-01-20 18:16:30 +0000260 for _, v := range variants {
261 if v == newVariant {
262 return variants
263 }
264 }
265 return append(variants, newVariant)
266}
267
Paul Duffin51509a12022-04-06 12:48:09 +0000268// BUILD_NUMBER_FILE is the name of the file in the snapshot zip that will contain the number of
269// the build from which the snapshot was produced.
270const BUILD_NUMBER_FILE = "snapshot-creation-build-number.txt"
271
Jiyong Park73c54ee2019-10-22 20:31:18 +0900272// SDK directory structure
273// <sdk_root>/
274// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
275// <api_ver>/ : below this directory are all auto-generated
276// Android.bp : definition of 'sdk_snapshot' module is here
277// aidl/
278// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
279// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900280// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900281// include/
282// bionic/libc/include/stdlib.h : an exported header file
283// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900284// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900285// <arch>/include/ : arch-specific exported headers
286// <arch>/include_gen/ : arch-specific generated headers
287// <arch>/lib/
288// libFoo.so : a stub library
289
Paul Duffin1938dba2022-07-26 23:53:00 +0000290func (s sdk) targetBuildRelease(ctx android.ModuleContext) *buildRelease {
291 config := ctx.Config()
292 targetBuildReleaseEnv := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE", buildReleaseCurrent.name)
293 targetBuildRelease, err := nameToRelease(targetBuildReleaseEnv)
294 if err != nil {
295 ctx.ModuleErrorf("invalid SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE: %s", err)
296 targetBuildRelease = buildReleaseCurrent
297 }
298
299 return targetBuildRelease
300}
301
Jiyong Park232e7852019-11-04 12:23:40 +0900302// buildSnapshot is the main function in this source file. It creates rules to copy
303// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffinc6ba1822022-05-06 09:38:02 +0000304func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000305
Paul Duffin1938dba2022-07-26 23:53:00 +0000306 targetBuildRelease := s.targetBuildRelease(ctx)
307 targetApiLevel, err := android.ApiLevelFromUser(ctx, targetBuildRelease.name)
308 if err != nil {
309 targetApiLevel = android.FutureApiLevel
310 }
311
Paul Duffinb97b1572021-04-29 21:50:40 +0100312 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100313 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100314 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000315 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100316 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100317 }
Paul Duffin865171e2020-03-02 18:38:15 +0000318
Paul Duffinb97b1572021-04-29 21:50:40 +0100319 // Filter out any sdkMemberVariantDep that is a component of another.
320 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000321
Paul Duffin1938dba2022-07-26 23:53:00 +0000322 // Record the names of all the members, both explicitly specified and implicitly included. Also,
323 // record the names of any members that should be excluded from this snapshot.
Paul Duffinb97b1572021-04-29 21:50:40 +0100324 allMembersByName := make(map[string]struct{})
325 exportedMembersByName := make(map[string]struct{})
Paul Duffin1938dba2022-07-26 23:53:00 +0000326 excludedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100327
Paul Duffin1938dba2022-07-26 23:53:00 +0000328 addMember := func(name string, export bool, exclude bool) {
329 if exclude {
330 excludedMembersByName[name] = struct{}{}
331 return
332 }
333
Paul Duffinb97b1572021-04-29 21:50:40 +0100334 allMembersByName[name] = struct{}{}
335 if export {
336 exportedMembersByName[name] = struct{}{}
337 }
338 }
339
340 for _, memberVariantDep := range memberVariantDeps {
341 name := memberVariantDep.variant.Name()
342 export := memberVariantDep.export
343
Paul Duffin1938dba2022-07-26 23:53:00 +0000344 // If the minApiLevel of the member is greater than the target API level then exclude it from
345 // this snapshot.
346 exclude := memberVariantDep.minApiLevel.GreaterThan(targetApiLevel)
Spandan Dasb84dbb22023-03-08 22:06:35 +0000347 // Always include host variants (e.g. host tools) in the snapshot.
348 // Host variants should not be guarded by a min_sdk_version check. In fact, host variants
349 // do not have a `min_sdk_version`.
350 if memberVariantDep.Host() {
351 exclude = false
352 }
Paul Duffin1938dba2022-07-26 23:53:00 +0000353
354 addMember(name, export, exclude)
Paul Duffinb97b1572021-04-29 21:50:40 +0100355
356 // Add any components provided by the module.
357 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
Paul Duffin1938dba2022-07-26 23:53:00 +0000358 addMember(component, export, exclude)
Paul Duffinb97b1572021-04-29 21:50:40 +0100359 }
360
361 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
362 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000363 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000364 }
365
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000366 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900367
Cole Fausted158f42024-03-07 16:41:27 -0800368 bp := android.PathForModuleOut(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000369
370 bpFile := &bpFile{
371 modules: make(map[string]*bpModule),
372 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000373
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000374 // Always add -current to the end
375 snapshotFileSuffix := "-current"
Paul Duffin43f7bf02021-05-05 22:00:51 +0100376
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000377 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000378 ctx: ctx,
379 sdk: s,
Paul Duffin13f02712020-03-06 12:30:43 +0000380 snapshotDir: snapshotDir.OutputPath,
381 copies: make(map[string]string),
Cole Fausted158f42024-03-07 16:41:27 -0800382 filesToZip: []android.Path{bp},
Paul Duffin13f02712020-03-06 12:30:43 +0000383 bpFile: bpFile,
384 prebuiltModules: make(map[string]*bpModule),
385 allMembersByName: allMembersByName,
386 exportedMembersByName: exportedMembersByName,
Paul Duffin1938dba2022-07-26 23:53:00 +0000387 excludedMembersByName: excludedMembersByName,
Paul Duffin39abf8f2021-09-24 14:58:27 +0100388 targetBuildRelease: targetBuildRelease,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900389 }
Paul Duffinac37c502019-11-26 18:02:20 +0000390 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900391
Paul Duffin62131702021-05-07 01:10:01 +0100392 // If the sdk snapshot includes any license modules then add a package module which has a
393 // default_applicable_licenses property. That will prevent the LSC license process from updating
394 // the generated Android.bp file to add a package module that includes all licenses used by all
395 // the modules in that package. That would be unnecessary as every module in the sdk should have
396 // their own licenses property specified.
397 if hasLicenses {
398 pkg := bpFile.newModule("package")
399 property := "default_applicable_licenses"
400 pkg.AddCommentForProperty(property, `
401A default list here prevents the license LSC from adding its own list which would
402be unnecessary as every module in the sdk already has its own licenses property.
403`)
404 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
405 bpFile.AddModule(pkg)
406 }
407
Paul Duffin0df49682021-05-07 01:10:01 +0100408 // Group the variants for each member module together and then group the members of each member
409 // type together.
Paul Duffinf861df72022-07-01 15:56:06 +0000410 members := s.groupMemberVariantsByMemberThenType(ctx, targetBuildRelease, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100411
412 // Create the prebuilt modules for each of the member modules.
Paul Duffind19f8942021-07-14 12:08:37 +0100413 traits := s.gatherTraits()
Spandan Dasa5e26d32024-03-06 14:04:36 +0000414 memberNames := []string{} // soong module names of the members. contains the prebuilt_ prefix.
Paul Duffin13ad94f2020-02-19 16:19:27 +0000415 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000416 memberType := member.memberType
Paul Duffin4e7d1c42022-05-13 13:12:19 +0000417 if !memberType.ArePrebuiltsRequired() {
418 continue
419 }
Paul Duffin3a4eb502020-03-19 16:11:18 +0000420
Paul Duffind19f8942021-07-14 12:08:37 +0100421 name := member.name
Paul Duffin1938dba2022-07-26 23:53:00 +0000422 if _, ok := excludedMembersByName[name]; ok {
423 continue
424 }
425
Paul Duffind19f8942021-07-14 12:08:37 +0100426 requiredTraits := traits[name]
427 if requiredTraits == nil {
428 requiredTraits = android.EmptySdkMemberTraitSet()
429 }
430
431 // Create the snapshot for the member.
432 memberCtx := &memberContext{ctx, builder, memberType, name, requiredTraits}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000433
434 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100435 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Spandan Dasa5e26d32024-03-06 14:04:36 +0000436
437 if member.memberType != android.LicenseModuleSdkMemberType && !builder.isInternalMember(member.name) {
438 // More exceptions
439 // 1. Skip BCP and SCCP fragments
440 // 2. Skip non-sdk contents of BCP and SCCP fragments
441 //
442 // The non-sdk contents of BCP/SSCP fragments should only be used for dexpreopt and hiddenapi,
443 // and are not available to the rest of the build.
444 if android.InList(member.memberType,
445 []android.SdkMemberType{
446 // bcp
447 java.BootclasspathFragmentSdkMemberType,
448 java.JavaBootLibsSdkMemberType,
449 // sscp
450 java.SystemServerClasspathFragmentSdkMemberType,
451 java.JavaSystemserverLibsSdkMemberType,
452 },
453 ) {
454 continue
455 }
456
457 memberNames = append(memberNames, android.PrebuiltNameFromSource(member.name))
458 }
459 }
460
461 // create an apex_contributions_defaults for this module's sdk.
462 // this module type is supported in V and above.
463 if targetApiLevel.GreaterThan(android.ApiLevelUpsideDownCake) {
464 ac := newModule("apex_contributions_defaults")
465 ac.AddProperty("name", s.Name()+".contributions")
466 ac.AddProperty("contents", memberNames)
467 bpFile.AddModule(ac)
Jiyong Park73c54ee2019-10-22 20:31:18 +0900468 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900469
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000470 // Create a transformer that will transform a module by replacing any references
Paul Duffin72910952020-01-20 18:16:30 +0000471 // to internal members with a unique module name and setting prefer: false.
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000472 snapshotTransformer := snapshotTransformation{
Paul Duffin64fb5262021-05-05 21:36:04 +0100473 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100474 }
Paul Duffin72910952020-01-20 18:16:30 +0000475
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000476 for _, module := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000477 // Prune any empty property sets.
Sam Delmerico35881362023-06-30 14:40:10 -0400478 module = transformModule(module, pruneEmptySetTransformer{})
Paul Duffina78f3a72020-02-21 16:29:35 +0000479
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000480 // Transform the module module to make it suitable for use in the snapshot.
Sam Delmerico35881362023-06-30 14:40:10 -0400481 module = transformModule(module, snapshotTransformer)
482 module = transformModule(module, emptyClasspathContentsTransformation{})
483 if module != nil {
484 bpFile.AddModule(module)
485 }
Paul Duffin43f7bf02021-05-05 22:00:51 +0100486 }
Paul Duffin26197a62021-04-24 00:34:10 +0100487
488 // generate Android.bp
Cole Fausted158f42024-03-07 16:41:27 -0800489 contents := generateBpContents(bpFile)
Paul Duffin39abf8f2021-09-24 14:58:27 +0100490 // If the snapshot is being generated for the current build release then check the syntax to make
491 // sure that it is compatible.
Paul Duffin42a49f12022-08-17 22:09:55 +0000492 if targetBuildRelease == buildReleaseCurrent {
Paul Duffin39abf8f2021-09-24 14:58:27 +0100493 syntaxCheckSnapshotBpFile(ctx, contents)
494 }
Paul Duffin26197a62021-04-24 00:34:10 +0100495
Cole Fausted158f42024-03-07 16:41:27 -0800496 android.WriteFileRuleVerbatim(ctx, bp, contents)
Paul Duffin26197a62021-04-24 00:34:10 +0100497
Paul Duffin51509a12022-04-06 12:48:09 +0000498 // Copy the build number file into the snapshot.
499 builder.CopyToSnapshot(ctx.Config().BuildNumberFile(ctx), BUILD_NUMBER_FILE)
500
Paul Duffin74f1dcd2022-07-18 13:18:23 +0000501 filesToZip := android.SortedUniquePaths(builder.filesToZip)
Paul Duffin26197a62021-04-24 00:34:10 +0100502
503 // zip them all
Paul Duffinc6ba1822022-05-06 09:38:02 +0000504 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100505 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100506 outputDesc := "Building snapshot for " + ctx.ModuleName()
507
508 // If there are no zips to merge then generate the output zip directly.
509 // Otherwise, generate an intermediate zip file into which other zips can be
510 // merged.
511 var zipFile android.OutputPath
512 var desc string
513 if len(builder.zipsToMerge) == 0 {
514 zipFile = outputZipFile
515 desc = outputDesc
516 } else {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000517 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100518 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100519 desc = "Building intermediate snapshot for " + ctx.ModuleName()
520 }
521
522 ctx.Build(pctx, android.BuildParams{
523 Description: desc,
524 Rule: zipFiles,
525 Inputs: filesToZip,
526 Output: zipFile,
527 Args: map[string]string{
528 "basedir": builder.snapshotDir.String(),
529 },
530 })
531
532 if len(builder.zipsToMerge) != 0 {
533 ctx.Build(pctx, android.BuildParams{
534 Description: outputDesc,
535 Rule: mergeZips,
536 Input: zipFile,
Paul Duffin74f1dcd2022-07-18 13:18:23 +0000537 Inputs: android.SortedUniquePaths(builder.zipsToMerge),
Paul Duffin26197a62021-04-24 00:34:10 +0100538 Output: outputZipFile,
539 })
540 }
541
Paul Duffinc6ba1822022-05-06 09:38:02 +0000542 modules := s.generateInfoData(ctx, memberVariantDeps)
543
544 // Output the modules information as pretty printed JSON.
Cole Fausted158f42024-03-07 16:41:27 -0800545 info := android.PathForModuleOut(ctx, fmt.Sprintf("%s%s.info", ctx.ModuleName(), snapshotFileSuffix))
Paul Duffinc6ba1822022-05-06 09:38:02 +0000546 output, err := json.MarshalIndent(modules, "", " ")
547 if err != nil {
548 ctx.ModuleErrorf("error generating %q: %s", info, err)
549 }
550 builder.infoContents = string(output)
Cole Fausted158f42024-03-07 16:41:27 -0800551 android.WriteFileRuleVerbatim(ctx, info, builder.infoContents)
552 installedInfo := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), info.Base(), info)
Paul Duffinc6ba1822022-05-06 09:38:02 +0000553 s.infoFile = android.OptionalPathForPath(installedInfo)
554
555 // Install the zip, making sure that the info file has been installed as well.
556 installedZip := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), outputZipFile.Base(), outputZipFile, installedInfo)
557 s.snapshotFile = android.OptionalPathForPath(installedZip)
558}
559
560type moduleInfo struct {
561 // The type of the module, e.g. java_sdk_library
562 moduleType string
563 // The name of the module.
564 name string
565 // A list of additional dependencies of the module.
566 deps []string
Paul Duffin958806b2022-05-16 13:10:47 +0000567 // Additional member specific properties.
568 // These will be added into the generated JSON alongside the above properties.
569 memberSpecific map[string]interface{}
Paul Duffinc6ba1822022-05-06 09:38:02 +0000570}
571
572func (m *moduleInfo) MarshalJSON() ([]byte, error) {
573 buffer := bytes.Buffer{}
574
575 separator := ""
576 writeObjectPair := func(key string, value interface{}) {
577 buffer.WriteString(fmt.Sprintf("%s%q: ", separator, key))
578 b, err := json.Marshal(value)
579 if err != nil {
580 panic(err)
581 }
582 buffer.Write(b)
583 separator = ","
584 }
585
586 buffer.WriteString("{")
587 writeObjectPair("@type", m.moduleType)
588 writeObjectPair("@name", m.name)
589 if m.deps != nil {
590 writeObjectPair("@deps", m.deps)
591 }
Cole Faust18994c72023-02-28 16:02:16 -0800592 for _, k := range android.SortedKeys(m.memberSpecific) {
Paul Duffin958806b2022-05-16 13:10:47 +0000593 v := m.memberSpecific[k]
Paul Duffinc6ba1822022-05-06 09:38:02 +0000594 writeObjectPair(k, v)
595 }
596 buffer.WriteString("}")
597 return buffer.Bytes(), nil
598}
599
600var _ json.Marshaler = (*moduleInfo)(nil)
601
602// generateInfoData creates a list of moduleInfo structures that will be marshalled into JSON.
603func (s *sdk) generateInfoData(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) interface{} {
604 modules := []*moduleInfo{}
605 sdkInfo := moduleInfo{
Paul Duffin958806b2022-05-16 13:10:47 +0000606 moduleType: "sdk",
607 name: ctx.ModuleName(),
608 memberSpecific: map[string]interface{}{},
Paul Duffinc6ba1822022-05-06 09:38:02 +0000609 }
610 modules = append(modules, &sdkInfo)
611
612 name2Info := map[string]*moduleInfo{}
613 getModuleInfo := func(module android.Module) *moduleInfo {
614 name := module.Name()
615 info := name2Info[name]
616 if info == nil {
617 moduleType := ctx.OtherModuleType(module)
618 // Remove any suffix added when creating modules dynamically.
619 moduleType = strings.Split(moduleType, "__")[0]
620 info = &moduleInfo{
621 moduleType: moduleType,
622 name: name,
623 }
Paul Duffin958806b2022-05-16 13:10:47 +0000624
Colin Cross313aa542023-12-13 13:47:44 -0800625 additionalSdkInfo, _ := android.OtherModuleProvider(ctx, module, android.AdditionalSdkInfoProvider)
Paul Duffin958806b2022-05-16 13:10:47 +0000626 info.memberSpecific = additionalSdkInfo.Properties
627
Paul Duffinc6ba1822022-05-06 09:38:02 +0000628 name2Info[name] = info
629 }
630 return info
631 }
632
633 for _, memberVariantDep := range memberVariantDeps {
634 propertyName := memberVariantDep.memberType.SdkPropertyName()
635 var list []string
Paul Duffin958806b2022-05-16 13:10:47 +0000636 if v, ok := sdkInfo.memberSpecific[propertyName]; ok {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000637 list = v.([]string)
638 }
639
640 memberName := memberVariantDep.variant.Name()
641 list = append(list, memberName)
Paul Duffin958806b2022-05-16 13:10:47 +0000642 sdkInfo.memberSpecific[propertyName] = android.SortedUniqueStrings(list)
Paul Duffinc6ba1822022-05-06 09:38:02 +0000643
644 if memberVariantDep.container != nil {
645 containerInfo := getModuleInfo(memberVariantDep.container)
646 containerInfo.deps = android.SortedUniqueStrings(append(containerInfo.deps, memberName))
647 }
648
649 // Make sure that the module info is created for each module.
650 getModuleInfo(memberVariantDep.variant)
651 }
652
Cole Faust18994c72023-02-28 16:02:16 -0800653 for _, memberName := range android.SortedKeys(name2Info) {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000654 info := name2Info[memberName]
655 modules = append(modules, info)
656 }
657
658 return modules
Paul Duffin26197a62021-04-24 00:34:10 +0100659}
660
Paul Duffinb97b1572021-04-29 21:50:40 +0100661// filterOutComponents removes any item from the deps list that is a component of another item in
662// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
663// then it will remove "foo.stubs" from the deps.
664func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
665 // Collate the set of components that all the modules added to the sdk provide.
666 components := map[string]*sdkMemberVariantDep{}
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000667 for i := range deps {
Paul Duffinb97b1572021-04-29 21:50:40 +0100668 dep := &deps[i]
669 for _, c := range dep.exportedComponentsInfo.Components {
670 components[c] = dep
671 }
672 }
673
674 // If no module provides components then return the input deps unfiltered.
675 if len(components) == 0 {
676 return deps
677 }
678
679 filtered := make([]sdkMemberVariantDep, 0, len(deps))
680 for _, dep := range deps {
681 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
682 if owner, ok := components[name]; ok {
683 // This is a component of another module that is a member of the sdk.
684
685 // If the component is exported but the owning module is not then the configuration is not
686 // supported.
687 if dep.export && !owner.export {
688 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
689 continue
690 }
691
692 // This module must not be added to the list of members of the sdk as that would result in a
693 // duplicate module in the sdk snapshot.
694 continue
695 }
696
697 filtered = append(filtered, dep)
698 }
699 return filtered
700}
701
Paul Duffinf88d8e02020-05-07 20:21:34 +0100702// Check the syntax of the generated Android.bp file contents and if they are
703// invalid then log an error with the contents (tagged with line numbers) and the
704// errors that were found so that it is easy to see where the problem lies.
705func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
706 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
707 if len(errs) != 0 {
708 message := &strings.Builder{}
709 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
710
711Generated Android.bp contents
712========================================================================
713`)
714 for i, line := range strings.Split(contents, "\n") {
715 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
716 }
717
718 _, _ = fmt.Fprint(message, `
719========================================================================
720
721Errors found:
722`)
723
724 for _, err := range errs {
725 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
726 }
727
728 ctx.ModuleErrorf("%s", message.String())
729 }
730}
731
Paul Duffin4b8b7932020-05-06 12:35:38 +0100732func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
733 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
734 if err != nil {
735 ctx.ModuleErrorf("error extracting common properties: %s", err)
736 }
737}
738
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000739type propertyTag struct {
740 name string
741}
742
Paul Duffin94289702021-09-09 15:38:32 +0100743var _ android.BpPropertyTag = propertyTag{}
744
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000745// BpPropertyTag instances to add to a property that contains references to other sdk members.
Paul Duffin0cb37b92020-03-04 14:52:46 +0000746//
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000747// These will ensure that the referenced modules are available, if required.
Paul Duffin13f02712020-03-06 12:30:43 +0000748var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000749var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000750
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000751type snapshotTransformation struct {
Paul Duffine6c0d842020-01-15 14:08:51 +0000752 identityTransformation
753 builder *snapshotBuilder
754}
755
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000756func (t snapshotTransformation) transformModule(module *bpModule) *bpModule {
Sam Delmerico35881362023-06-30 14:40:10 -0400757 if module != nil {
758 // If the module is an internal member then use a unique name for it.
759 name := module.Name()
760 module.setProperty("name", t.builder.snapshotSdkMemberName(name, true))
761 }
Paul Duffin72910952020-01-20 18:16:30 +0000762 return module
763}
764
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000765func (t snapshotTransformation) transformProperty(_ string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000766 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
767 required := tag == requiredSdkMemberReferencePropertyTag
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000768 return t.builder.snapshotSdkMemberNames(value.([]string), required), tag
Paul Duffin72910952020-01-20 18:16:30 +0000769 } else {
770 return value, tag
771 }
772}
773
Sam Delmerico35881362023-06-30 14:40:10 -0400774type emptyClasspathContentsTransformation struct {
775 identityTransformation
776}
777
778func (t emptyClasspathContentsTransformation) transformModule(module *bpModule) *bpModule {
779 classpathModuleTypes := []string{
780 "prebuilt_bootclasspath_fragment",
781 "prebuilt_systemserverclasspath_fragment",
782 }
783 if module != nil && android.InList(module.moduleType, classpathModuleTypes) {
784 if contents, ok := module.bpPropertySet.properties["contents"].([]string); ok {
785 if len(contents) == 0 {
786 return nil
787 }
788 }
789 }
790 return module
791}
792
Paul Duffina78f3a72020-02-21 16:29:35 +0000793type pruneEmptySetTransformer struct {
794 identityTransformation
795}
796
797var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
798
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000799func (t pruneEmptySetTransformer) transformPropertySetAfterContents(_ string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
Paul Duffina78f3a72020-02-21 16:29:35 +0000800 if len(propertySet.properties) == 0 {
801 return nil, nil
802 } else {
803 return propertySet, tag
804 }
805}
806
Cole Fausted158f42024-03-07 16:41:27 -0800807func generateBpContents(bpFile *bpFile) string {
808 contents := &generatedContents{}
Paul Duffina08e4dc2021-06-22 18:19:19 +0100809 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000810 for _, bpModule := range bpFile.order {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000811 contents.IndentedPrintf("\n")
812 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
813 outputPropertySet(contents, bpModule.bpPropertySet)
814 contents.IndentedPrintf("}\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000815 }
Cole Fausted158f42024-03-07 16:41:27 -0800816 return contents.content.String()
Paul Duffinb645ec82019-11-27 17:43:54 +0000817}
818
819func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
820 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000821
Paul Duffin0df49682021-05-07 01:10:01 +0100822 addComment := func(name string) {
823 if text, ok := set.comments[name]; ok {
824 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100825 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100826 }
827 }
828 }
829
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000830 // Output the properties first, followed by the nested sets. This ensures a
831 // consistent output irrespective of whether property sets are created before
832 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000833 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000834 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000835
Paul Duffin0df49682021-05-07 01:10:01 +0100836 // Do not write property sets in the properties phase.
837 if _, ok := value.(*bpPropertySet); ok {
838 continue
839 }
840
841 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100842 reflectValue := reflect.ValueOf(value)
843 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000844 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000845
846 for _, name := range set.order {
847 value := set.getValue(name)
848
849 // Only write property sets in the sets phase.
850 switch v := value.(type) {
851 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100852 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100853 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000854 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100855 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000856 }
857 }
858
Paul Duffinb645ec82019-11-27 17:43:54 +0000859 contents.Dedent()
860}
861
Paul Duffina08e4dc2021-06-22 18:19:19 +0100862// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
863// by the value and then followed by a , and a newline.
864func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
865 contents.IndentedPrintf("%s: ", name)
866 outputUnnamedValue(contents, value)
867 contents.UnindentedPrintf(",\n")
868}
869
870// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
871// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
872// indented and all but the last line will end with a newline.
873func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
874 valueType := value.Type()
875 switch valueType.Kind() {
876 case reflect.Bool:
877 contents.UnindentedPrintf("%t", value.Bool())
878
879 case reflect.String:
880 contents.UnindentedPrintf("%q", value)
881
Paul Duffin51227d82021-05-18 12:54:27 +0100882 case reflect.Ptr:
883 outputUnnamedValue(contents, value.Elem())
884
Paul Duffina08e4dc2021-06-22 18:19:19 +0100885 case reflect.Slice:
886 length := value.Len()
887 if length == 0 {
888 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100889 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100890 firstValue := value.Index(0)
891 if length == 1 && !multiLineValue(firstValue) {
892 contents.UnindentedPrintf("[")
893 outputUnnamedValue(contents, firstValue)
894 contents.UnindentedPrintf("]")
895 } else {
896 contents.UnindentedPrintf("[\n")
897 contents.Indent()
898 for i := 0; i < length; i++ {
899 itemValue := value.Index(i)
900 contents.IndentedPrintf("")
901 outputUnnamedValue(contents, itemValue)
902 contents.UnindentedPrintf(",\n")
903 }
904 contents.Dedent()
905 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100906 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100907 }
908
Paul Duffin51227d82021-05-18 12:54:27 +0100909 case reflect.Struct:
910 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
911 v := value.Interface()
912 if _, ok := v.(android.BpPrintable); !ok {
913 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
914 }
915 contents.UnindentedPrintf("{\n")
916 contents.Indent()
917 for f := 0; f < valueType.NumField(); f++ {
918 fieldType := valueType.Field(f)
919 if fieldType.Anonymous {
920 continue
921 }
922 fieldValue := value.Field(f)
923 fieldName := fieldType.Name
924 propertyName := proptools.PropertyNameForField(fieldName)
925 outputNamedValue(contents, propertyName, fieldValue)
926 }
927 contents.Dedent()
928 contents.IndentedPrintf("}")
929
Paul Duffina08e4dc2021-06-22 18:19:19 +0100930 default:
Cole Faust8c366312024-03-08 10:58:32 -0800931 panic(fmt.Errorf("unknown type: %T of value %#v", value, value))
Paul Duffina08e4dc2021-06-22 18:19:19 +0100932 }
933}
934
Paul Duffin51227d82021-05-18 12:54:27 +0100935// multiLineValue returns true if the supplied value may require multiple lines in the output.
936func multiLineValue(value reflect.Value) bool {
937 kind := value.Kind()
938 return kind == reflect.Slice || kind == reflect.Struct
939}
940
Paul Duffinac37c502019-11-26 18:02:20 +0000941func (s *sdk) GetAndroidBpContentsForTests() string {
Cole Fausted158f42024-03-07 16:41:27 -0800942 return generateBpContents(s.builderForTests.bpFile)
Paul Duffinac37c502019-11-26 18:02:20 +0000943}
944
Paul Duffinc6ba1822022-05-06 09:38:02 +0000945func (s *sdk) GetInfoContentsForTests() string {
946 return s.builderForTests.infoContents
947}
948
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000949type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100950 ctx android.ModuleContext
951 sdk *sdk
952
Paul Duffinb645ec82019-11-27 17:43:54 +0000953 snapshotDir android.OutputPath
954 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000955
956 // Map from destination to source of each copy - used to eliminate duplicates and
957 // detect conflicts.
958 copies map[string]string
959
Paul Duffinb645ec82019-11-27 17:43:54 +0000960 filesToZip android.Paths
961 zipsToMerge android.Paths
962
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000963 // The path to an empty file.
964 emptyFile android.WritablePath
965
Paul Duffinb645ec82019-11-27 17:43:54 +0000966 prebuiltModules map[string]*bpModule
967 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000968
969 // The set of all members by name.
970 allMembersByName map[string]struct{}
971
972 // The set of exported members by name.
973 exportedMembersByName map[string]struct{}
Paul Duffin39abf8f2021-09-24 14:58:27 +0100974
Paul Duffin1938dba2022-07-26 23:53:00 +0000975 // The set of members which have been excluded from this snapshot; by name.
976 excludedMembersByName map[string]struct{}
977
Paul Duffin39abf8f2021-09-24 14:58:27 +0100978 // The target build release for which the snapshot is to be generated.
979 targetBuildRelease *buildRelease
Paul Duffinc6ba1822022-05-06 09:38:02 +0000980
Paul Duffin958806b2022-05-16 13:10:47 +0000981 // The contents of the .info file that describes the sdk contents.
Paul Duffinc6ba1822022-05-06 09:38:02 +0000982 infoContents string
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000983}
984
985func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000986 if existing, ok := s.copies[dest]; ok {
987 if existing != src.String() {
988 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
989 return
990 }
991 } else {
992 path := s.snapshotDir.Join(s.ctx, dest)
993 s.ctx.Build(pctx, android.BuildParams{
994 Rule: android.Cp,
995 Input: src,
996 Output: path,
997 })
998 s.filesToZip = append(s.filesToZip, path)
999
1000 s.copies[dest] = src.String()
1001 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001002}
1003
Paul Duffin91547182019-11-12 19:39:36 +00001004func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1005 ctx := s.ctx
1006
1007 // Repackage the zip file so that the entries are in the destDir directory.
1008 // This will allow the zip file to be merged into the snapshot.
1009 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001010
1011 ctx.Build(pctx, android.BuildParams{
1012 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1013 Rule: repackageZip,
1014 Input: zipPath,
1015 Output: tmpZipPath,
1016 Args: map[string]string{
1017 "destdir": destDir,
1018 },
1019 })
Paul Duffin91547182019-11-12 19:39:36 +00001020
1021 // Add the repackaged zip file to the files to merge.
1022 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1023}
1024
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001025func (s *snapshotBuilder) EmptyFile() android.Path {
1026 if s.emptyFile == nil {
1027 ctx := s.ctx
1028 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1029 s.ctx.Build(pctx, android.BuildParams{
1030 Rule: android.Touch,
1031 Output: s.emptyFile,
1032 })
1033 }
1034
1035 return s.emptyFile
1036}
1037
Paul Duffin9d8d6092019-12-05 18:19:29 +00001038func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1039 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001040 if s.prebuiltModules[name] != nil {
1041 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1042 }
1043
1044 m := s.bpFile.newModule(moduleType)
1045 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001046
Paul Duffinbefa4b92020-03-04 14:22:45 +00001047 variant := member.Variants()[0]
1048
Paul Duffin13f02712020-03-06 12:30:43 +00001049 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001050 // An internal member is only referenced from the sdk snapshot which is in the
1051 // same package so can be marked as private.
1052 m.AddProperty("visibility", []string{"//visibility:private"})
1053 } else {
1054 // Extract visibility information from a member variant. All variants have the same
1055 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001056 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1057
1058 // Add any additional visibility rules needed for the prebuilts to reference each other.
1059 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1060 if err != nil {
1061 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1062 }
1063
1064 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001065 if len(visibility) != 0 {
1066 m.AddProperty("visibility", visibility)
1067 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001068 }
1069
Martin Stjernholm1e041092020-11-03 00:11:09 +00001070 // Where available copy apex_available properties from the member.
1071 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1072 apexAvailable := apexAware.ApexAvailable()
1073 if len(apexAvailable) == 0 {
1074 // //apex_available:platform is the default.
1075 apexAvailable = []string{android.AvailableToPlatform}
1076 }
1077
1078 // Add in any baseline apex available settings.
1079 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1080
1081 // Remove duplicates and sort.
1082 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1083 sort.Strings(apexAvailable)
1084
1085 m.AddProperty("apex_available", apexAvailable)
1086 }
1087
Paul Duffinb0bb3762021-05-06 16:48:05 +01001088 // The licenses are the same for all variants.
1089 mctx := s.ctx
Colin Cross313aa542023-12-13 13:47:44 -08001090 licenseInfo, _ := android.OtherModuleProvider(mctx, variant, android.LicenseInfoProvider)
Paul Duffinb0bb3762021-05-06 16:48:05 +01001091 if len(licenseInfo.Licenses) > 0 {
1092 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1093 }
1094
Paul Duffin865171e2020-03-02 18:38:15 +00001095 deviceSupported := false
1096 hostSupported := false
1097
1098 for _, variant := range member.Variants() {
1099 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001100 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001101 hostSupported = true
1102 } else if osClass == android.Device {
1103 deviceSupported = true
1104 }
1105 }
1106
1107 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001108
1109 s.prebuiltModules[name] = m
1110 s.prebuiltOrder = append(s.prebuiltOrder, m)
1111 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001112}
1113
Paul Duffin865171e2020-03-02 18:38:15 +00001114func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001115 // If neither device or host is supported then this module does not support either so will not
1116 // recognize the properties.
1117 if !deviceSupported && !hostSupported {
1118 return
1119 }
1120
Paul Duffin865171e2020-03-02 18:38:15 +00001121 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001122 bpModule.AddProperty("device_supported", false)
1123 }
Paul Duffin865171e2020-03-02 18:38:15 +00001124 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001125 bpModule.AddProperty("host_supported", true)
1126 }
1127}
1128
Paul Duffin13f02712020-03-06 12:30:43 +00001129func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1130 if required {
1131 return requiredSdkMemberReferencePropertyTag
1132 } else {
1133 return optionalSdkMemberReferencePropertyTag
1134 }
1135}
1136
1137func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1138 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001139}
1140
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001141// Get a name for sdk snapshot member. If the member is private then generate a snapshot specific
1142// name. As part of the processing this checks to make sure that any required members are part of
1143// the snapshot.
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001144func (s *snapshotBuilder) snapshotSdkMemberName(name string, required bool) string {
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001145 if _, ok := s.allMembersByName[name]; !ok {
Paul Duffin13f02712020-03-06 12:30:43 +00001146 if required {
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001147 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", name)
Paul Duffin13f02712020-03-06 12:30:43 +00001148 }
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001149 return name
Paul Duffin13f02712020-03-06 12:30:43 +00001150 }
1151
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001152 if s.isInternalMember(name) {
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001153 return s.ctx.ModuleName() + "_" + name
Paul Duffin72910952020-01-20 18:16:30 +00001154 } else {
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001155 return name
Paul Duffin72910952020-01-20 18:16:30 +00001156 }
1157}
1158
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001159func (s *snapshotBuilder) snapshotSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001160 var references []string = nil
1161 for _, m := range members {
Paul Duffin1938dba2022-07-26 23:53:00 +00001162 if _, ok := s.excludedMembersByName[m]; ok {
1163 continue
1164 }
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001165 references = append(references, s.snapshotSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001166 }
1167 return references
1168}
1169
Paul Duffin13f02712020-03-06 12:30:43 +00001170func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1171 _, ok := s.exportedMembersByName[memberName]
1172 return !ok
1173}
1174
Martin Stjernholm89238f42020-07-10 00:14:03 +01001175// Add the properties from the given SdkMemberProperties to the blueprint
1176// property set. This handles common properties in SdkMemberPropertiesBase and
1177// calls the member-specific AddToPropertySet for the rest.
1178func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1179 if memberProperties.Base().Compile_multilib != "" {
1180 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1181 }
1182
1183 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1184}
1185
Paul Duffin21827262021-04-24 12:16:36 +01001186// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1187type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001188 // The sdk variant that depends (possibly indirectly) on the member variant.
1189 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001190
1191 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001192 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001193
1194 // The variant that is added to the sdk.
Paul Duffin5e71e682022-11-23 18:09:54 +00001195 variant android.Module
Paul Duffinb97b1572021-04-29 21:50:40 +01001196
Paul Duffinc6ba1822022-05-06 09:38:02 +00001197 // The optional container of this member, i.e. the module that is depended upon by the sdk
1198 // (possibly transitively) and whose dependency on this module is why it was added to the sdk.
1199 // Is nil if this a direct dependency of the sdk.
Paul Duffin5e71e682022-11-23 18:09:54 +00001200 container android.Module
Paul Duffinc6ba1822022-05-06 09:38:02 +00001201
Paul Duffinb97b1572021-04-29 21:50:40 +01001202 // True if the member should be exported, i.e. accessible, from outside the sdk.
1203 export bool
1204
1205 // The names of additional component modules provided by the variant.
1206 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1938dba2022-07-26 23:53:00 +00001207
1208 // The minimum API level on which this module is supported.
1209 minApiLevel android.ApiLevel
Paul Duffin1356d8c2020-02-25 19:26:33 +00001210}
1211
Spandan Dasb84dbb22023-03-08 22:06:35 +00001212// Host returns true if the sdk member is a host variant (e.g. host tool)
1213func (s *sdkMemberVariantDep) Host() bool {
1214 return s.variant.Target().Os.Class == android.Host
1215}
1216
Paul Duffin13879572019-11-28 14:31:38 +00001217var _ android.SdkMember = (*sdkMember)(nil)
1218
Paul Duffin21827262021-04-24 12:16:36 +01001219// sdkMember groups all the variants of a specific member module together along with the name of the
1220// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001221type sdkMember struct {
1222 memberType android.SdkMemberType
1223 name string
Paul Duffin5e71e682022-11-23 18:09:54 +00001224 variants []android.Module
Paul Duffin13879572019-11-28 14:31:38 +00001225}
1226
1227func (m *sdkMember) Name() string {
1228 return m.name
1229}
1230
Paul Duffin5e71e682022-11-23 18:09:54 +00001231func (m *sdkMember) Variants() []android.Module {
Paul Duffin13879572019-11-28 14:31:38 +00001232 return m.variants
1233}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001234
Paul Duffin9c3760e2020-03-16 19:52:08 +00001235// Track usages of multilib variants.
1236type multilibUsage int
1237
1238const (
1239 multilibNone multilibUsage = 0
1240 multilib32 multilibUsage = 1
1241 multilib64 multilibUsage = 2
1242 multilibBoth = multilib32 | multilib64
1243)
1244
1245// Add the multilib that is used in the arch type.
1246func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1247 multilib := archType.Multilib
1248 switch multilib {
1249 case "":
1250 return m
1251 case "lib32":
1252 return m | multilib32
1253 case "lib64":
1254 return m | multilib64
1255 default:
Cole Faust8c366312024-03-08 10:58:32 -08001256 panic(fmt.Errorf("unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
Paul Duffin9c3760e2020-03-16 19:52:08 +00001257 }
1258}
1259
1260func (m multilibUsage) String() string {
1261 switch m {
1262 case multilibNone:
1263 return ""
1264 case multilib32:
1265 return "32"
1266 case multilib64:
1267 return "64"
1268 case multilibBoth:
1269 return "both"
1270 default:
Cole Faust8c366312024-03-08 10:58:32 -08001271 panic(fmt.Errorf("unknown multilib value, found %b, expected one of %b, %b, %b or %b",
Paul Duffin9c3760e2020-03-16 19:52:08 +00001272 m, multilibNone, multilib32, multilib64, multilibBoth))
1273 }
1274}
1275
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001276// TODO(187910671): BEGIN - Remove once modules do not have an APEX and default variant.
1277// variantCoordinate contains the coordinates used to identify a variant of an SDK member.
1278type variantCoordinate struct {
1279 // osType identifies the OS target of a variant.
1280 osType android.OsType
1281 // archId identifies the architecture and whether it is for the native bridge.
1282 archId archId
1283 // image is the image variant name.
1284 image string
1285 // linkType is the link type name.
1286 linkType string
1287}
1288
1289func getVariantCoordinate(ctx *memberContext, variant android.Module) variantCoordinate {
1290 linkType := ""
1291 if len(ctx.MemberType().SupportedLinkages()) > 0 {
1292 linkType = getLinkType(variant)
1293 }
1294 return variantCoordinate{
1295 osType: variant.Target().Os,
1296 archId: archIdFromTarget(variant.Target()),
1297 image: variant.ImageVariation().Variation,
1298 linkType: linkType,
1299 }
1300}
1301
1302// selectApexVariantsWhereAvailable filters the input list of variants by selecting the APEX
1303// specific variant for a specific variantCoordinate when there is both an APEX and default variant.
1304//
1305// There is a long-standing issue where a module that is added to an APEX has both an APEX and
1306// default/platform variant created even when the module does not require a platform variant. As a
1307// result an indirect dependency onto a module via the APEX will use the APEX variant, whereas a
1308// direct dependency onto the module will use the default/platform variant. That would result in a
1309// failure while attempting to optimize the properties for a member as it would have two variants
1310// when only one was expected.
1311//
1312// This function mitigates that problem by detecting when there are two variants that differ only
1313// by apex variant, where one is the default/platform variant and one is the APEX variant. In that
1314// case it picks the APEX variant. It picks the APEX variant because that is the behavior that would
1315// be expected
Paul Duffin5e71e682022-11-23 18:09:54 +00001316func selectApexVariantsWhereAvailable(ctx *memberContext, variants []android.Module) []android.Module {
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001317 moduleCtx := ctx.sdkMemberContext
1318
1319 // Group the variants by coordinates.
Paul Duffin5e71e682022-11-23 18:09:54 +00001320 variantsByCoord := make(map[variantCoordinate][]android.Module)
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001321 for _, variant := range variants {
1322 coord := getVariantCoordinate(ctx, variant)
1323 variantsByCoord[coord] = append(variantsByCoord[coord], variant)
1324 }
1325
Paul Duffin5e71e682022-11-23 18:09:54 +00001326 toDiscard := make(map[android.Module]struct{})
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001327 for coord, list := range variantsByCoord {
1328 count := len(list)
1329 if count == 1 {
1330 continue
1331 }
1332
Paul Duffin5e71e682022-11-23 18:09:54 +00001333 variantsByApex := make(map[string]android.Module)
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001334 conflictDetected := false
1335 for _, variant := range list {
Colin Cross313aa542023-12-13 13:47:44 -08001336 apexInfo, _ := android.OtherModuleProvider(moduleCtx, variant, android.ApexInfoProvider)
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001337 apexVariationName := apexInfo.ApexVariationName
1338 // If there are two variants for a specific APEX variation then there is conflict.
1339 if _, ok := variantsByApex[apexVariationName]; ok {
1340 conflictDetected = true
1341 break
1342 }
1343 variantsByApex[apexVariationName] = variant
1344 }
1345
1346 // If there are more than 2 apex variations or one of the apex variations is not the
1347 // default/platform variation then there is a conflict.
1348 if len(variantsByApex) != 2 {
1349 conflictDetected = true
1350 } else if _, ok := variantsByApex[""]; !ok {
1351 conflictDetected = true
1352 }
1353
1354 // If there are no conflicts then add the default/platform variation to the list to remove.
1355 if !conflictDetected {
1356 toDiscard[variantsByApex[""]] = struct{}{}
1357 continue
1358 }
1359
1360 // There are duplicate variants at this coordinate and they are not the default and APEX variant
1361 // so fail.
1362 variantDescriptions := []string{}
1363 for _, m := range list {
1364 variantDescriptions = append(variantDescriptions, fmt.Sprintf(" %s", m.String()))
1365 }
1366
1367 moduleCtx.ModuleErrorf("multiple conflicting variants detected for OsType{%s}, %s, Image{%s}, Link{%s}\n%s",
1368 coord.osType, coord.archId.String(), coord.image, coord.linkType,
1369 strings.Join(variantDescriptions, "\n"))
1370 }
1371
1372 // If there are any variants to discard then remove them from the list of variants, while
1373 // preserving the order.
1374 if len(toDiscard) > 0 {
Paul Duffin5e71e682022-11-23 18:09:54 +00001375 filtered := []android.Module{}
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001376 for _, variant := range variants {
1377 if _, ok := toDiscard[variant]; !ok {
1378 filtered = append(filtered, variant)
1379 }
1380 }
1381 variants = filtered
1382 }
1383
1384 return variants
1385}
1386
1387// TODO(187910671): END - Remove once modules do not have an APEX and default variant.
1388
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001389type baseInfo struct {
1390 Properties android.SdkMemberProperties
1391}
1392
Paul Duffinf34f6d82020-04-30 15:48:31 +01001393func (b *baseInfo) optimizableProperties() interface{} {
1394 return b.Properties
1395}
1396
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001397type osTypeSpecificInfo struct {
1398 baseInfo
1399
Paul Duffin00e46802020-03-12 20:40:35 +00001400 osType android.OsType
1401
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001402 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001403 //
1404 // Nil if there is one variant whose arch type is common
1405 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001406}
1407
Paul Duffin4b8b7932020-05-06 12:35:38 +01001408var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1409
Paul Duffinfc8dd232020-03-17 12:51:37 +00001410type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1411
Paul Duffin00e46802020-03-12 20:40:35 +00001412// Create a new osTypeSpecificInfo for the specified os type and its properties
1413// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001414func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001415 osInfo := &osTypeSpecificInfo{
1416 osType: osType,
1417 }
1418
1419 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1420 properties := variantPropertiesFactory()
1421 properties.Base().Os = osType
1422 return properties
1423 }
1424
1425 // Create a structure into which properties common across the architectures in
1426 // this os type will be stored.
1427 osInfo.Properties = osSpecificVariantPropertiesFactory()
1428
1429 // Group the variants by arch type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001430 var variantsByArchId = make(map[archId][]android.Module)
1431 var archIds []archId
Paul Duffin00e46802020-03-12 20:40:35 +00001432 for _, variant := range osTypeVariants {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001433 target := variant.Target()
1434 id := archIdFromTarget(target)
1435 if _, ok := variantsByArchId[id]; !ok {
1436 archIds = append(archIds, id)
Paul Duffin00e46802020-03-12 20:40:35 +00001437 }
1438
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001439 variantsByArchId[id] = append(variantsByArchId[id], variant)
Paul Duffin00e46802020-03-12 20:40:35 +00001440 }
1441
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001442 if commonVariants, ok := variantsByArchId[commonArchId]; ok {
Paul Duffin00e46802020-03-12 20:40:35 +00001443 if len(osTypeVariants) != 1 {
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001444 variants := []string{}
1445 for _, m := range osTypeVariants {
1446 variants = append(variants, fmt.Sprintf(" %s", m.String()))
1447 }
1448 panic(fmt.Errorf("expected to only have 1 variant of %q when arch type is common but found %d\n%s",
1449 ctx.Name(),
1450 len(osTypeVariants),
1451 strings.Join(variants, "\n")))
Paul Duffin00e46802020-03-12 20:40:35 +00001452 }
1453
1454 // A common arch type only has one variant and its properties should be treated
1455 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001456 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001457 } else {
1458 // Create an arch specific info for each supported architecture type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001459 for _, id := range archIds {
1460 archVariants := variantsByArchId[id]
1461 archInfo := newArchSpecificInfo(ctx, id, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001462
1463 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1464 }
1465 }
1466
1467 return osInfo
1468}
1469
Paul Duffin39abf8f2021-09-24 14:58:27 +01001470func (osInfo *osTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1471 if len(osInfo.archInfos) == 0 {
1472 pruner.pruneProperties(osInfo.Properties)
1473 } else {
1474 for _, archInfo := range osInfo.archInfos {
1475 archInfo.pruneUnsupportedProperties(pruner)
1476 }
1477 }
1478}
1479
Paul Duffin00e46802020-03-12 20:40:35 +00001480// Optimize the properties by extracting common properties from arch type specific
1481// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001482func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001483 // Nothing to do if there is only a single common architecture.
1484 if len(osInfo.archInfos) == 0 {
1485 return
1486 }
1487
Paul Duffin9c3760e2020-03-16 19:52:08 +00001488 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001489 for _, archInfo := range osInfo.archInfos {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001490 multilib = multilib.addArchType(archInfo.archId.archType)
Paul Duffin9c3760e2020-03-16 19:52:08 +00001491
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001492 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001493 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001494 }
1495
Paul Duffin4b8b7932020-05-06 12:35:38 +01001496 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001497
1498 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001499 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001500}
1501
1502// Add the properties for an os to a property set.
1503//
1504// Maps the properties related to the os variants through to an appropriate
1505// module structure that will produce equivalent set of variants when it is
1506// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001507func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001508
1509 var osPropertySet android.BpPropertySet
1510 var archPropertySet android.BpPropertySet
1511 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001512 if osInfo.Properties.Base().Os_count == 1 &&
1513 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1514 // There is only one OS type present in the variants and it shouldn't have a
1515 // variant-specific target. The latter is the case if it's either for device
1516 // where there is only one OS (android), or for host and the member type
1517 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001518
1519 // Create a structure that looks like:
1520 // module_type {
1521 // name: "...",
1522 // ...
1523 // <common properties>
1524 // ...
1525 // <single os type specific properties>
1526 //
1527 // arch: {
1528 // <arch specific sections>
1529 // }
1530 //
1531 osPropertySet = bpModule
1532 archPropertySet = osPropertySet.AddPropertySet("arch")
1533
1534 // Arch specific properties need to be added to an arch specific section
1535 // within arch.
1536 archOsPrefix = ""
1537 } else {
1538 // Create a structure that looks like:
1539 // module_type {
1540 // name: "...",
1541 // ...
1542 // <common properties>
1543 // ...
1544 // target: {
1545 // <arch independent os specific sections, e.g. android>
1546 // ...
1547 // <arch and os specific sections, e.g. android_x86>
1548 // }
1549 //
1550 osType := osInfo.osType
1551 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1552 archPropertySet = targetPropertySet
1553
1554 // Arch specific properties need to be added to an os and arch specific
1555 // section prefixed with <os>_.
1556 archOsPrefix = osType.Name + "_"
1557 }
1558
1559 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001560 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001561
1562 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1563 // os) specific properties.
1564 //
1565 // The archInfos list will be empty if the os contains variants for the common
1566 // architecture.
1567 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001568 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001569 }
1570}
1571
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001572func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1573 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001574 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001575}
1576
1577var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1578
Paul Duffin4b8b7932020-05-06 12:35:38 +01001579func (osInfo *osTypeSpecificInfo) String() string {
1580 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1581}
1582
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001583// archId encapsulates the information needed to identify a combination of arch type and native
1584// bridge support.
1585//
1586// Conceptually, native bridge support is a facet of an android.Target, not an android.Arch as it is
1587// essentially using one android.Arch to implement another. However, in terms of the handling of
1588// the variants native bridge is treated as part of the arch variation. See the ArchVariation method
1589// on android.Target.
1590//
1591// So, it makes sense when optimizing the variants to combine native bridge with the arch type.
1592type archId struct {
1593 // The arch type of the variant's target.
1594 archType android.ArchType
1595
1596 // True if the variants is for the native bridge, false otherwise.
1597 nativeBridge bool
1598}
1599
1600// propertyName returns the name of the property corresponding to use for this arch id.
1601func (i *archId) propertyName() string {
1602 name := i.archType.Name
1603 if i.nativeBridge {
1604 // Note: This does not result in a valid property because there is no architecture specific
1605 // native bridge property, only a generic "native_bridge" property. However, this will be used
1606 // in error messages if there is an attempt to use this in a generated bp file.
1607 name += "_native_bridge"
1608 }
1609 return name
1610}
1611
1612func (i *archId) String() string {
1613 return fmt.Sprintf("ArchType{%s}, NativeBridge{%t}", i.archType, i.nativeBridge)
1614}
1615
1616// archIdFromTarget returns an archId initialized from information in the supplied target.
1617func archIdFromTarget(target android.Target) archId {
1618 return archId{
1619 archType: target.Arch.ArchType,
1620 nativeBridge: target.NativeBridge == android.NativeBridgeEnabled,
1621 }
1622}
1623
1624// commonArchId is the archId for the common architecture.
1625var commonArchId = archId{archType: android.Common}
1626
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001627type archTypeSpecificInfo struct {
1628 baseInfo
1629
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001630 archId archId
1631 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001632
Paul Duffinb42fa672021-09-09 16:37:49 +01001633 imageVariantInfos []*imageVariantSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001634}
1635
Paul Duffin4b8b7932020-05-06 12:35:38 +01001636var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1637
Paul Duffinfc8dd232020-03-17 12:51:37 +00001638// Create a new archTypeSpecificInfo for the specified arch type and its properties
1639// structures populated with information from the variants.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001640func newArchSpecificInfo(ctx android.SdkMemberContext, archId archId, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001641
Paul Duffinfc8dd232020-03-17 12:51:37 +00001642 // Create an arch specific info into which the variant properties can be copied.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001643 archInfo := &archTypeSpecificInfo{archId: archId, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001644
1645 // Create the properties into which the arch type specific properties will be
1646 // added.
1647 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001648
Liz Kammer96320df2022-05-12 20:40:00 -04001649 // if there are multiple supported link variants, we want to nest based on linkage even if there
1650 // is only one variant, otherwise, if there is only one variant we can populate based on the arch
1651 if len(archVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001652 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001653 } else {
Paul Duffinb42fa672021-09-09 16:37:49 +01001654 // Group the variants by image type.
1655 variantsByImage := make(map[string][]android.Module)
1656 for _, variant := range archVariants {
1657 image := variant.ImageVariation().Variation
1658 variantsByImage[image] = append(variantsByImage[image], variant)
1659 }
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001660
Paul Duffinb42fa672021-09-09 16:37:49 +01001661 // Create the image variant info in a fixed order.
Cole Faust18994c72023-02-28 16:02:16 -08001662 for _, imageVariantName := range android.SortedKeys(variantsByImage) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001663 variants := variantsByImage[imageVariantName]
1664 archInfo.imageVariantInfos = append(archInfo.imageVariantInfos, newImageVariantSpecificInfo(ctx, imageVariantName, variantPropertiesFactory, variants))
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001665 }
1666 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001667
1668 return archInfo
1669}
1670
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001671// Get the link type of the variant
1672//
1673// If the variant is not differentiated by link type then it returns "",
1674// otherwise it returns one of "static" or "shared".
1675func getLinkType(variant android.Module) string {
1676 linkType := ""
1677 if linkable, ok := variant.(cc.LinkableInterface); ok {
1678 if linkable.Shared() && linkable.Static() {
1679 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1680 } else if linkable.Shared() {
1681 linkType = "shared"
1682 } else if linkable.Static() {
1683 linkType = "static"
1684 } else {
1685 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1686 }
1687 }
1688 return linkType
1689}
1690
Paul Duffin39abf8f2021-09-24 14:58:27 +01001691func (archInfo *archTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1692 if len(archInfo.imageVariantInfos) == 0 {
1693 pruner.pruneProperties(archInfo.Properties)
1694 } else {
1695 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1696 imageVariantInfo.pruneUnsupportedProperties(pruner)
1697 }
1698 }
1699}
1700
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001701// Optimize the properties by extracting common properties from link type specific
1702// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001703func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001704 if len(archInfo.imageVariantInfos) == 0 {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001705 return
1706 }
1707
Paul Duffinb42fa672021-09-09 16:37:49 +01001708 // Optimize the image variant properties first.
1709 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1710 imageVariantInfo.optimizeProperties(ctx, commonValueExtractor)
1711 }
1712
1713 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.imageVariantInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001714}
1715
Paul Duffinfc8dd232020-03-17 12:51:37 +00001716// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001717func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001718 archPropertySuffix := archInfo.archId.propertyName()
1719 propertySetName := archOsPrefix + archPropertySuffix
1720 archTypePropertySet := archPropertySet.AddPropertySet(propertySetName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001721 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1722 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1723 archTypePropertySet.AddProperty("enabled", true)
1724 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001725 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001726
Paul Duffinb42fa672021-09-09 16:37:49 +01001727 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1728 imageVariantInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001729 }
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001730
1731 // If this is for a native bridge architecture then make sure that the property set does not
1732 // contain any properties as providing native bridge specific properties is not currently
1733 // supported.
1734 if archInfo.archId.nativeBridge {
1735 propertySetContents := getPropertySetContents(archTypePropertySet)
1736 if propertySetContents != "" {
1737 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",
1738 propertySetName, ctx.name, propertySetContents)
1739 }
1740 }
1741}
1742
1743// getPropertySetContents returns the string representation of the contents of a property set, after
1744// recursively pruning any empty nested property sets.
1745func getPropertySetContents(propertySet android.BpPropertySet) string {
1746 set := propertySet.(*bpPropertySet)
1747 set.transformContents(pruneEmptySetTransformer{})
1748 if len(set.properties) != 0 {
1749 contents := &generatedContents{}
1750 contents.Indent()
1751 outputPropertySet(contents, set)
1752 setAsString := contents.content.String()
1753 return setAsString
1754 }
1755 return ""
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001756}
1757
Paul Duffin4b8b7932020-05-06 12:35:38 +01001758func (archInfo *archTypeSpecificInfo) String() string {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001759 return archInfo.archId.String()
Paul Duffin4b8b7932020-05-06 12:35:38 +01001760}
1761
Paul Duffinb42fa672021-09-09 16:37:49 +01001762type imageVariantSpecificInfo struct {
1763 baseInfo
1764
1765 imageVariant string
1766
1767 linkInfos []*linkTypeSpecificInfo
1768}
1769
1770func newImageVariantSpecificInfo(ctx android.SdkMemberContext, imageVariant string, variantPropertiesFactory variantPropertiesFactoryFunc, imageVariants []android.Module) *imageVariantSpecificInfo {
1771
1772 // Create an image variant specific info into which the variant properties can be copied.
1773 imageInfo := &imageVariantSpecificInfo{imageVariant: imageVariant}
1774
1775 // Create the properties into which the image variant specific properties will be added.
1776 imageInfo.Properties = variantPropertiesFactory()
1777
Liz Kammer96320df2022-05-12 20:40:00 -04001778 // if there are multiple supported link variants, we want to nest even if there is only one
1779 // variant, otherwise, if there is only one variant we can populate based on the image
1780 if len(imageVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffinb42fa672021-09-09 16:37:49 +01001781 imageInfo.Properties.PopulateFromVariant(ctx, imageVariants[0])
1782 } else {
1783 // There is more than one variant for this image variant which must be differentiated by link
Liz Kammer96320df2022-05-12 20:40:00 -04001784 // type. Or there are multiple supported linkages and we need to nest based on link type.
Paul Duffinb42fa672021-09-09 16:37:49 +01001785 for _, linkVariant := range imageVariants {
1786 linkType := getLinkType(linkVariant)
1787 if linkType == "" {
1788 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(imageVariants)))
1789 } else {
1790 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
1791
1792 imageInfo.linkInfos = append(imageInfo.linkInfos, linkInfo)
1793 }
1794 }
1795 }
1796
1797 return imageInfo
1798}
1799
Paul Duffin39abf8f2021-09-24 14:58:27 +01001800func (imageInfo *imageVariantSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1801 if len(imageInfo.linkInfos) == 0 {
1802 pruner.pruneProperties(imageInfo.Properties)
1803 } else {
1804 for _, linkInfo := range imageInfo.linkInfos {
1805 linkInfo.pruneUnsupportedProperties(pruner)
1806 }
1807 }
1808}
1809
Paul Duffinb42fa672021-09-09 16:37:49 +01001810// Optimize the properties by extracting common properties from link type specific
1811// properties into arch type specific properties.
1812func (imageInfo *imageVariantSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
1813 if len(imageInfo.linkInfos) == 0 {
1814 return
1815 }
1816
1817 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, imageInfo.Properties, imageInfo.linkInfos)
1818}
1819
1820// Add the properties for an arch type to a property set.
1821func (imageInfo *imageVariantSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1822 if imageInfo.imageVariant != android.CoreVariation {
1823 propertySet = propertySet.AddPropertySet(imageInfo.imageVariant)
1824 }
1825
1826 addSdkMemberPropertiesToSet(ctx, imageInfo.Properties, propertySet)
1827
Liz Kammer96320df2022-05-12 20:40:00 -04001828 usedLinkages := make(map[string]bool, len(imageInfo.linkInfos))
Paul Duffinb42fa672021-09-09 16:37:49 +01001829 for _, linkInfo := range imageInfo.linkInfos {
Liz Kammer96320df2022-05-12 20:40:00 -04001830 usedLinkages[linkInfo.linkType] = true
Paul Duffinb42fa672021-09-09 16:37:49 +01001831 linkInfo.addToPropertySet(ctx, propertySet)
1832 }
1833
Liz Kammer96320df2022-05-12 20:40:00 -04001834 // If not all supported linkages had existing variants, we need to disable the unsupported variant
1835 if len(imageInfo.linkInfos) < len(ctx.MemberType().SupportedLinkages()) {
1836 for _, l := range ctx.MemberType().SupportedLinkages() {
1837 if _, ok := usedLinkages[l]; !ok {
1838 otherLinkagePropertySet := propertySet.AddPropertySet(l)
1839 otherLinkagePropertySet.AddProperty("enabled", false)
1840 }
1841 }
1842 }
1843
Paul Duffinb42fa672021-09-09 16:37:49 +01001844 // If this is for a non-core image variant then make sure that the property set does not contain
1845 // any properties as providing non-core image variant specific properties for prebuilts is not
1846 // currently supported.
1847 if imageInfo.imageVariant != android.CoreVariation {
1848 propertySetContents := getPropertySetContents(propertySet)
1849 if propertySetContents != "" {
1850 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",
1851 imageInfo.imageVariant, ctx.name, propertySetContents)
1852 }
1853 }
1854}
1855
1856func (imageInfo *imageVariantSpecificInfo) String() string {
1857 return imageInfo.imageVariant
1858}
1859
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001860type linkTypeSpecificInfo struct {
1861 baseInfo
1862
1863 linkType string
1864}
1865
Paul Duffin4b8b7932020-05-06 12:35:38 +01001866var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1867
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001868// Create a new linkTypeSpecificInfo for the specified link type and its properties
1869// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001870func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001871 linkInfo := &linkTypeSpecificInfo{
1872 baseInfo: baseInfo{
1873 // Create the properties into which the link type specific properties will be
1874 // added.
1875 Properties: variantPropertiesFactory(),
1876 },
1877 linkType: linkType,
1878 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001879 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001880 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001881}
1882
Paul Duffinf68f85a2021-09-09 16:11:42 +01001883func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1884 linkPropertySet := propertySet.AddPropertySet(l.linkType)
1885 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
1886}
1887
Paul Duffin39abf8f2021-09-24 14:58:27 +01001888func (l *linkTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1889 pruner.pruneProperties(l.Properties)
1890}
1891
Paul Duffin4b8b7932020-05-06 12:35:38 +01001892func (l *linkTypeSpecificInfo) String() string {
1893 return fmt.Sprintf("LinkType{%s}", l.linkType)
1894}
1895
Paul Duffin3a4eb502020-03-19 16:11:18 +00001896type memberContext struct {
1897 sdkMemberContext android.ModuleContext
1898 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001899 memberType android.SdkMemberType
1900 name string
Paul Duffind19f8942021-07-14 12:08:37 +01001901
1902 // The set of traits required of this member.
1903 requiredTraits android.SdkMemberTraitSet
Paul Duffin3a4eb502020-03-19 16:11:18 +00001904}
1905
Cole Faust34867402023-04-28 12:32:27 -07001906func (m *memberContext) ModuleErrorf(fmt string, args ...interface{}) {
1907 m.sdkMemberContext.ModuleErrorf(fmt, args...)
1908}
1909
Paul Duffin3a4eb502020-03-19 16:11:18 +00001910func (m *memberContext) SdkModuleContext() android.ModuleContext {
1911 return m.sdkMemberContext
1912}
1913
1914func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1915 return m.builder
1916}
1917
Paul Duffina551a1c2020-03-17 21:04:24 +00001918func (m *memberContext) MemberType() android.SdkMemberType {
1919 return m.memberType
1920}
1921
1922func (m *memberContext) Name() string {
1923 return m.name
1924}
1925
Paul Duffind19f8942021-07-14 12:08:37 +01001926func (m *memberContext) RequiresTrait(trait android.SdkMemberTrait) bool {
1927 return m.requiredTraits.Contains(trait)
1928}
1929
Paul Duffin13648912022-07-15 13:12:35 +00001930func (m *memberContext) IsTargetBuildBeforeTiramisu() bool {
1931 return m.builder.targetBuildRelease.EarlierThan(buildReleaseT)
1932}
1933
1934var _ android.SdkMemberContext = (*memberContext)(nil)
1935
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001936func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001937
1938 memberType := member.memberType
1939
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001940 // Do not add the prefer property if the member snapshot module is a source module type.
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001941 moduleCtx := ctx.sdkMemberContext
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001942 if !memberType.UsesSourceModuleTypeInSnapshot() {
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001943 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1944 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1945 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1946 // behavior is for the module.
Paul Duffin82d75ad2022-11-14 17:35:50 +00001947 bpModule.insertAfter("name", "prefer", false)
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001948 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001949
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001950 variants := selectApexVariantsWhereAvailable(ctx, member.variants)
1951
Paul Duffina04c1072020-03-02 10:16:35 +00001952 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001953 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001954 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001955 osType := variant.Target().Os
1956 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001957 }
1958
Paul Duffina04c1072020-03-02 10:16:35 +00001959 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001960 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001961 properties := memberType.CreateVariantPropertiesStruct()
1962 base := properties.Base()
1963 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001964 return properties
1965 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001966
Paul Duffina04c1072020-03-02 10:16:35 +00001967 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001968
Paul Duffina04c1072020-03-02 10:16:35 +00001969 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001970 commonProperties := variantPropertiesFactory()
1971 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001972
Paul Duffin39abf8f2021-09-24 14:58:27 +01001973 // Create a property pruner that will prune any properties unsupported by the target build
1974 // release.
1975 targetBuildRelease := ctx.builder.targetBuildRelease
1976 unsupportedPropertyPruner := newPropertyPrunerByBuildRelease(commonProperties, targetBuildRelease)
1977
Paul Duffinc097e362020-03-10 22:50:03 +00001978 // Create common value extractor that can be used to optimize the properties.
1979 commonValueExtractor := newCommonValueExtractor(commonProperties)
1980
Paul Duffina04c1072020-03-02 10:16:35 +00001981 // The list of property structures which are os type specific but common across
1982 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001983 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001984
1985 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001986 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001987 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001988 // Add the os specific properties to a list of os type specific yet architecture
1989 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001990 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001991
Paul Duffin39abf8f2021-09-24 14:58:27 +01001992 osInfo.pruneUnsupportedProperties(unsupportedPropertyPruner)
1993
Paul Duffin00e46802020-03-12 20:40:35 +00001994 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001995 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001996 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001997
Paul Duffina04c1072020-03-02 10:16:35 +00001998 // Extract properties which are common across all architectures and os types.
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001999 extractCommonProperties(moduleCtx, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002000
Paul Duffina04c1072020-03-02 10:16:35 +00002001 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01002002 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002003
Paul Duffina04c1072020-03-02 10:16:35 +00002004 // Create a target property set into which target specific properties can be
2005 // added.
2006 targetPropertySet := bpModule.AddPropertySet("target")
2007
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01002008 // If the member is host OS dependent and has host_supported then disable by
2009 // default and enable each host OS variant explicitly. This avoids problems
2010 // with implicitly enabled OS variants when the snapshot is used, which might
2011 // be different from this run (e.g. different build OS).
2012 if ctx.memberType.IsHostOsDependent() {
2013 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
2014 if hostSupported {
2015 hostPropertySet := targetPropertySet.AddPropertySet("host")
2016 hostPropertySet.AddProperty("enabled", false)
2017 }
2018 }
2019
Paul Duffina04c1072020-03-02 10:16:35 +00002020 // Iterate over the os types in a fixed order.
2021 for _, osType := range s.getPossibleOsTypes() {
2022 osInfo := osTypeToInfo[osType]
2023 if osInfo == nil {
2024 continue
2025 }
2026
Paul Duffin3a4eb502020-03-19 16:11:18 +00002027 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002028 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002029}
2030
Paul Duffina04c1072020-03-02 10:16:35 +00002031// Compute the list of possible os types that this sdk could support.
2032func (s *sdk) getPossibleOsTypes() []android.OsType {
2033 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00002034 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00002035 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07002036 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00002037 osTypes = append(osTypes, osType)
2038 }
2039 }
2040 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09002041 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00002042 osTypes = append(osTypes, osType)
2043 }
2044 }
2045 }
2046 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
2047 return osTypes
2048}
2049
Paul Duffinb28369a2020-05-04 15:39:59 +01002050// Given a set of properties (struct value), return the value of the field within that
2051// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00002052type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
2053
Paul Duffinc459f892020-04-30 18:08:29 +01002054// Checks the metadata to determine whether the property should be ignored for the
2055// purposes of common value extraction or not.
2056type extractorMetadataPredicate func(metadata propertiesContainer) bool
2057
2058// Indicates whether optimizable properties are provided by a host variant or
2059// not.
2060type isHostVariant interface {
2061 isHostVariant() bool
2062}
2063
Paul Duffinb28369a2020-05-04 15:39:59 +01002064// A property that can be optimized by the commonValueExtractor.
2065type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01002066 // The name of the field for this property. It is a "."-separated path for
2067 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002068 name string
2069
Paul Duffinc459f892020-04-30 18:08:29 +01002070 // Filter that can use metadata associated with the properties being optimized
2071 // to determine whether the field should be ignored during common value
2072 // optimization.
2073 filter extractorMetadataPredicate
2074
Paul Duffinb28369a2020-05-04 15:39:59 +01002075 // Retrieves the value on which common value optimization will be performed.
2076 getter fieldAccessorFunc
2077
Paul Duffinbfdca962022-09-22 16:21:54 +01002078 // True if the field should never be cleared.
2079 //
2080 // This is set to true if and only if the field is annotated with `sdk:"keep"`.
2081 keep bool
2082
Paul Duffinb28369a2020-05-04 15:39:59 +01002083 // The empty value for the field.
2084 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01002085
2086 // True if the property can support arch variants false otherwise.
2087 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01002088}
2089
Paul Duffin4b8b7932020-05-06 12:35:38 +01002090func (p extractorProperty) String() string {
2091 return p.name
2092}
2093
Paul Duffinc097e362020-03-10 22:50:03 +00002094// Supports extracting common values from a number of instances of a properties
2095// structure into a separate common set of properties.
2096type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01002097 // The properties that the extractor can optimize.
2098 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00002099}
2100
2101// Create a new common value extractor for the structure type for the supplied
2102// properties struct.
2103//
2104// The returned extractor can be used on any properties structure of the same type
2105// as the supplied set of properties.
2106func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
2107 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
2108 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01002109 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00002110 return extractor
2111}
2112
2113// Gather the fields from the supplied structure type from which common values will
2114// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00002115//
Martin Stjernholmb0249572020-09-15 02:32:35 +01002116// This is recursive function. If it encounters a struct then it will recurse
2117// into it, passing in the accessor for the field and the struct name as prefix
2118// for the nested fields. That will then be used in the accessors for the fields
2119// in the embedded struct.
2120func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00002121 for f := 0; f < structType.NumField(); f++ {
2122 field := structType.Field(f)
2123 if field.PkgPath != "" {
2124 // Ignore unexported fields.
2125 continue
2126 }
2127
Paul Duffin02e25c82022-09-22 15:30:58 +01002128 // Ignore fields tagged with sdk:"ignore".
2129 if proptools.HasTag(field, "sdk", "ignore") {
Paul Duffinc097e362020-03-10 22:50:03 +00002130 continue
2131 }
2132
Paul Duffinc459f892020-04-30 18:08:29 +01002133 var filter extractorMetadataPredicate
2134
2135 // Add a filter
2136 if proptools.HasTag(field, "sdk", "ignored-on-host") {
2137 filter = func(metadata propertiesContainer) bool {
2138 if m, ok := metadata.(isHostVariant); ok {
2139 if m.isHostVariant() {
2140 return false
2141 }
2142 }
2143 return true
2144 }
2145 }
2146
Paul Duffinbfdca962022-09-22 16:21:54 +01002147 keep := proptools.HasTag(field, "sdk", "keep")
2148
Paul Duffinc097e362020-03-10 22:50:03 +00002149 // Save a copy of the field index for use in the function.
2150 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01002151
Martin Stjernholmb0249572020-09-15 02:32:35 +01002152 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01002153
Paul Duffinc097e362020-03-10 22:50:03 +00002154 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00002155 if containingStructAccessor != nil {
2156 // This is an embedded structure so first access the field for the embedded
2157 // structure.
2158 value = containingStructAccessor(value)
2159 }
2160
Paul Duffinc097e362020-03-10 22:50:03 +00002161 // Skip through interface and pointer values to find the structure.
2162 value = getStructValue(value)
2163
Paul Duffin4b8b7932020-05-06 12:35:38 +01002164 defer func() {
2165 if r := recover(); r != nil {
2166 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
2167 }
2168 }()
2169
Paul Duffinc097e362020-03-10 22:50:03 +00002170 // Return the field.
2171 return value.Field(fieldIndex)
2172 }
2173
Martin Stjernholmb0249572020-09-15 02:32:35 +01002174 if field.Type.Kind() == reflect.Struct {
2175 // Gather fields from the nested or embedded structure.
2176 var subNamePrefix string
2177 if field.Anonymous {
2178 subNamePrefix = namePrefix
2179 } else {
2180 subNamePrefix = name + "."
2181 }
2182 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00002183 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01002184 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01002185 name,
Paul Duffinc459f892020-04-30 18:08:29 +01002186 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01002187 fieldGetter,
Paul Duffinbfdca962022-09-22 16:21:54 +01002188 keep,
Paul Duffinb28369a2020-05-04 15:39:59 +01002189 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01002190 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01002191 }
2192 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00002193 }
Paul Duffinc097e362020-03-10 22:50:03 +00002194 }
2195}
2196
2197func getStructValue(value reflect.Value) reflect.Value {
2198foundStruct:
2199 for {
2200 kind := value.Kind()
2201 switch kind {
2202 case reflect.Interface, reflect.Ptr:
2203 value = value.Elem()
2204 case reflect.Struct:
2205 break foundStruct
2206 default:
2207 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
2208 }
2209 }
2210 return value
2211}
2212
Paul Duffinf34f6d82020-04-30 15:48:31 +01002213// A container of properties to be optimized.
2214//
2215// Allows additional information to be associated with the properties, e.g. for
2216// filtering.
2217type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002218 fmt.Stringer
2219
Paul Duffinf34f6d82020-04-30 15:48:31 +01002220 // Get the properties that need optimizing.
2221 optimizableProperties() interface{}
2222}
2223
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002224// Extract common properties from a slice of property structures of the same type.
2225//
2226// All the property structures must be of the same type.
2227// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002228// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002229//
2230// Iterates over each exported field (capitalized name) and checks to see whether they
2231// have the same value (using DeepEquals) across all the input properties. If it does not then no
2232// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01002233// and the field in each of the input properties structure is set to its default value. Nested
2234// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002235func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002236 commonPropertiesValue := reflect.ValueOf(commonProperties)
2237 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002238
Paul Duffinf34f6d82020-04-30 15:48:31 +01002239 sliceValue := reflect.ValueOf(inputPropertiesSlice)
2240
Paul Duffinb28369a2020-05-04 15:39:59 +01002241 for _, property := range e.properties {
2242 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01002243 filter := property.filter
2244 if filter == nil {
2245 filter = func(metadata propertiesContainer) bool {
2246 return true
2247 }
2248 }
Paul Duffinb28369a2020-05-04 15:39:59 +01002249
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002250 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002251 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2252 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002253 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002254
Paul Duffin864e1b42020-05-06 10:23:19 +01002255 // Assume that all the values will be the same.
2256 //
2257 // While similar to this is not quite the same as commonValue == nil. If all the values
2258 // have been filtered out then this will be false but commonValue == nil will be true.
2259 valuesDiffer := false
2260
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002261 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002262 container := sliceValue.Index(i).Interface().(propertiesContainer)
2263 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002264 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002265
Paul Duffinc459f892020-04-30 18:08:29 +01002266 if !filter(container) {
2267 expectedValue := property.emptyValue.Interface()
2268 actualValue := fieldValue.Interface()
2269 if !reflect.DeepEqual(expectedValue, actualValue) {
2270 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2271 }
2272 continue
2273 }
2274
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002275 if commonValue == nil {
2276 // Use the first value as the commonProperties value.
2277 commonValue = &fieldValue
2278 } else {
2279 // If the value does not match the current common value then there is
2280 // no value in common so break out.
2281 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2282 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002283 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002284 break
2285 }
2286 }
2287 }
2288
Paul Duffin864e1b42020-05-06 10:23:19 +01002289 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002290 // and set the input struct's field to the empty value.
2291 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002292 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002293 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffinbfdca962022-09-22 16:21:54 +01002294 if !property.keep {
2295 for i := 0; i < sliceValue.Len(); i++ {
2296 container := sliceValue.Index(i).Interface().(propertiesContainer)
2297 itemValue := reflect.ValueOf(container.optimizableProperties())
2298 fieldValue := fieldGetter(itemValue)
2299 fieldValue.Set(emptyValue)
2300 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002301 }
2302 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002303
2304 if valuesDiffer && !property.archVariant {
2305 // The values differ but the property does not support arch variants so it
2306 // is an error.
2307 var details strings.Builder
2308 for i := 0; i < sliceValue.Len(); i++ {
2309 container := sliceValue.Index(i).Interface().(propertiesContainer)
2310 itemValue := reflect.ValueOf(container.optimizableProperties())
2311 fieldValue := fieldGetter(itemValue)
2312
2313 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2314 }
2315
2316 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2317 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002318 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002319
2320 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002321}