blob: 29fb93345ff788deb6b424e6602c8401b2b0759a [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
Alyssa Ketpreechasawat59ec0fa2024-07-04 19:51:17 +0000437 // Set stripper to none to skip stripping for generated snapshots.
438 // Mainline prebuilts (cc_prebuilt_library_shared) are not strippable in older platforms.
439 // Thus, stripping should be skipped when being used as prebuilts.
440 if memberType.DisablesStrip() {
441 stripPropertySet := prebuiltModule.(*bpModule).AddPropertySet("strip")
442 stripPropertySet.AddProperty("none", true)
443 }
444
Spandan Dasa5e26d32024-03-06 14:04:36 +0000445 if member.memberType != android.LicenseModuleSdkMemberType && !builder.isInternalMember(member.name) {
446 // More exceptions
447 // 1. Skip BCP and SCCP fragments
448 // 2. Skip non-sdk contents of BCP and SCCP fragments
449 //
450 // The non-sdk contents of BCP/SSCP fragments should only be used for dexpreopt and hiddenapi,
451 // and are not available to the rest of the build.
452 if android.InList(member.memberType,
453 []android.SdkMemberType{
454 // bcp
455 java.BootclasspathFragmentSdkMemberType,
456 java.JavaBootLibsSdkMemberType,
457 // sscp
458 java.SystemServerClasspathFragmentSdkMemberType,
459 java.JavaSystemserverLibsSdkMemberType,
460 },
461 ) {
462 continue
463 }
464
465 memberNames = append(memberNames, android.PrebuiltNameFromSource(member.name))
466 }
467 }
468
469 // create an apex_contributions_defaults for this module's sdk.
470 // this module type is supported in V and above.
471 if targetApiLevel.GreaterThan(android.ApiLevelUpsideDownCake) {
472 ac := newModule("apex_contributions_defaults")
473 ac.AddProperty("name", s.Name()+".contributions")
474 ac.AddProperty("contents", memberNames)
475 bpFile.AddModule(ac)
Jiyong Park73c54ee2019-10-22 20:31:18 +0900476 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900477
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000478 // Create a transformer that will transform a module by replacing any references
Paul Duffin72910952020-01-20 18:16:30 +0000479 // to internal members with a unique module name and setting prefer: false.
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000480 snapshotTransformer := snapshotTransformation{
Paul Duffin64fb5262021-05-05 21:36:04 +0100481 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100482 }
Paul Duffin72910952020-01-20 18:16:30 +0000483
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000484 for _, module := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000485 // Prune any empty property sets.
Sam Delmerico35881362023-06-30 14:40:10 -0400486 module = transformModule(module, pruneEmptySetTransformer{})
Paul Duffina78f3a72020-02-21 16:29:35 +0000487
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000488 // Transform the module module to make it suitable for use in the snapshot.
Sam Delmerico35881362023-06-30 14:40:10 -0400489 module = transformModule(module, snapshotTransformer)
490 module = transformModule(module, emptyClasspathContentsTransformation{})
491 if module != nil {
492 bpFile.AddModule(module)
493 }
Paul Duffin43f7bf02021-05-05 22:00:51 +0100494 }
Paul Duffin26197a62021-04-24 00:34:10 +0100495
496 // generate Android.bp
Cole Fausted158f42024-03-07 16:41:27 -0800497 contents := generateBpContents(bpFile)
Paul Duffin39abf8f2021-09-24 14:58:27 +0100498 // If the snapshot is being generated for the current build release then check the syntax to make
499 // sure that it is compatible.
Paul Duffin42a49f12022-08-17 22:09:55 +0000500 if targetBuildRelease == buildReleaseCurrent {
Paul Duffin39abf8f2021-09-24 14:58:27 +0100501 syntaxCheckSnapshotBpFile(ctx, contents)
502 }
Paul Duffin26197a62021-04-24 00:34:10 +0100503
Cole Fausted158f42024-03-07 16:41:27 -0800504 android.WriteFileRuleVerbatim(ctx, bp, contents)
Paul Duffin26197a62021-04-24 00:34:10 +0100505
Paul Duffin51509a12022-04-06 12:48:09 +0000506 // Copy the build number file into the snapshot.
507 builder.CopyToSnapshot(ctx.Config().BuildNumberFile(ctx), BUILD_NUMBER_FILE)
508
Paul Duffin74f1dcd2022-07-18 13:18:23 +0000509 filesToZip := android.SortedUniquePaths(builder.filesToZip)
Paul Duffin26197a62021-04-24 00:34:10 +0100510
511 // zip them all
Paul Duffinc6ba1822022-05-06 09:38:02 +0000512 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100513 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100514 outputDesc := "Building snapshot for " + ctx.ModuleName()
515
516 // If there are no zips to merge then generate the output zip directly.
517 // Otherwise, generate an intermediate zip file into which other zips can be
518 // merged.
519 var zipFile android.OutputPath
520 var desc string
521 if len(builder.zipsToMerge) == 0 {
522 zipFile = outputZipFile
523 desc = outputDesc
524 } else {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000525 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100526 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100527 desc = "Building intermediate snapshot for " + ctx.ModuleName()
528 }
529
530 ctx.Build(pctx, android.BuildParams{
531 Description: desc,
532 Rule: zipFiles,
533 Inputs: filesToZip,
534 Output: zipFile,
535 Args: map[string]string{
536 "basedir": builder.snapshotDir.String(),
537 },
538 })
539
540 if len(builder.zipsToMerge) != 0 {
541 ctx.Build(pctx, android.BuildParams{
542 Description: outputDesc,
543 Rule: mergeZips,
544 Input: zipFile,
Paul Duffin74f1dcd2022-07-18 13:18:23 +0000545 Inputs: android.SortedUniquePaths(builder.zipsToMerge),
Paul Duffin26197a62021-04-24 00:34:10 +0100546 Output: outputZipFile,
547 })
548 }
549
Paul Duffinc6ba1822022-05-06 09:38:02 +0000550 modules := s.generateInfoData(ctx, memberVariantDeps)
551
552 // Output the modules information as pretty printed JSON.
Cole Fausted158f42024-03-07 16:41:27 -0800553 info := android.PathForModuleOut(ctx, fmt.Sprintf("%s%s.info", ctx.ModuleName(), snapshotFileSuffix))
Paul Duffinc6ba1822022-05-06 09:38:02 +0000554 output, err := json.MarshalIndent(modules, "", " ")
555 if err != nil {
556 ctx.ModuleErrorf("error generating %q: %s", info, err)
557 }
558 builder.infoContents = string(output)
Cole Fausted158f42024-03-07 16:41:27 -0800559 android.WriteFileRuleVerbatim(ctx, info, builder.infoContents)
560 installedInfo := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), info.Base(), info)
Paul Duffinc6ba1822022-05-06 09:38:02 +0000561 s.infoFile = android.OptionalPathForPath(installedInfo)
562
563 // Install the zip, making sure that the info file has been installed as well.
564 installedZip := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), outputZipFile.Base(), outputZipFile, installedInfo)
565 s.snapshotFile = android.OptionalPathForPath(installedZip)
566}
567
568type moduleInfo struct {
569 // The type of the module, e.g. java_sdk_library
570 moduleType string
571 // The name of the module.
572 name string
573 // A list of additional dependencies of the module.
574 deps []string
Paul Duffin958806b2022-05-16 13:10:47 +0000575 // Additional member specific properties.
576 // These will be added into the generated JSON alongside the above properties.
577 memberSpecific map[string]interface{}
Paul Duffinc6ba1822022-05-06 09:38:02 +0000578}
579
580func (m *moduleInfo) MarshalJSON() ([]byte, error) {
581 buffer := bytes.Buffer{}
582
583 separator := ""
584 writeObjectPair := func(key string, value interface{}) {
585 buffer.WriteString(fmt.Sprintf("%s%q: ", separator, key))
586 b, err := json.Marshal(value)
587 if err != nil {
588 panic(err)
589 }
590 buffer.Write(b)
591 separator = ","
592 }
593
594 buffer.WriteString("{")
595 writeObjectPair("@type", m.moduleType)
596 writeObjectPair("@name", m.name)
597 if m.deps != nil {
598 writeObjectPair("@deps", m.deps)
599 }
Cole Faust18994c72023-02-28 16:02:16 -0800600 for _, k := range android.SortedKeys(m.memberSpecific) {
Paul Duffin958806b2022-05-16 13:10:47 +0000601 v := m.memberSpecific[k]
Paul Duffinc6ba1822022-05-06 09:38:02 +0000602 writeObjectPair(k, v)
603 }
604 buffer.WriteString("}")
605 return buffer.Bytes(), nil
606}
607
608var _ json.Marshaler = (*moduleInfo)(nil)
609
610// generateInfoData creates a list of moduleInfo structures that will be marshalled into JSON.
611func (s *sdk) generateInfoData(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) interface{} {
612 modules := []*moduleInfo{}
613 sdkInfo := moduleInfo{
Paul Duffin958806b2022-05-16 13:10:47 +0000614 moduleType: "sdk",
615 name: ctx.ModuleName(),
616 memberSpecific: map[string]interface{}{},
Paul Duffinc6ba1822022-05-06 09:38:02 +0000617 }
618 modules = append(modules, &sdkInfo)
619
620 name2Info := map[string]*moduleInfo{}
621 getModuleInfo := func(module android.Module) *moduleInfo {
622 name := module.Name()
623 info := name2Info[name]
624 if info == nil {
625 moduleType := ctx.OtherModuleType(module)
626 // Remove any suffix added when creating modules dynamically.
627 moduleType = strings.Split(moduleType, "__")[0]
628 info = &moduleInfo{
629 moduleType: moduleType,
630 name: name,
631 }
Paul Duffin958806b2022-05-16 13:10:47 +0000632
Colin Cross313aa542023-12-13 13:47:44 -0800633 additionalSdkInfo, _ := android.OtherModuleProvider(ctx, module, android.AdditionalSdkInfoProvider)
Paul Duffin958806b2022-05-16 13:10:47 +0000634 info.memberSpecific = additionalSdkInfo.Properties
635
Paul Duffinc6ba1822022-05-06 09:38:02 +0000636 name2Info[name] = info
637 }
638 return info
639 }
640
641 for _, memberVariantDep := range memberVariantDeps {
642 propertyName := memberVariantDep.memberType.SdkPropertyName()
643 var list []string
Paul Duffin958806b2022-05-16 13:10:47 +0000644 if v, ok := sdkInfo.memberSpecific[propertyName]; ok {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000645 list = v.([]string)
646 }
647
648 memberName := memberVariantDep.variant.Name()
649 list = append(list, memberName)
Paul Duffin958806b2022-05-16 13:10:47 +0000650 sdkInfo.memberSpecific[propertyName] = android.SortedUniqueStrings(list)
Paul Duffinc6ba1822022-05-06 09:38:02 +0000651
652 if memberVariantDep.container != nil {
653 containerInfo := getModuleInfo(memberVariantDep.container)
654 containerInfo.deps = android.SortedUniqueStrings(append(containerInfo.deps, memberName))
655 }
656
657 // Make sure that the module info is created for each module.
658 getModuleInfo(memberVariantDep.variant)
659 }
660
Cole Faust18994c72023-02-28 16:02:16 -0800661 for _, memberName := range android.SortedKeys(name2Info) {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000662 info := name2Info[memberName]
663 modules = append(modules, info)
664 }
665
666 return modules
Paul Duffin26197a62021-04-24 00:34:10 +0100667}
668
Paul Duffinb97b1572021-04-29 21:50:40 +0100669// filterOutComponents removes any item from the deps list that is a component of another item in
670// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
671// then it will remove "foo.stubs" from the deps.
672func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
673 // Collate the set of components that all the modules added to the sdk provide.
674 components := map[string]*sdkMemberVariantDep{}
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000675 for i := range deps {
Paul Duffinb97b1572021-04-29 21:50:40 +0100676 dep := &deps[i]
677 for _, c := range dep.exportedComponentsInfo.Components {
678 components[c] = dep
679 }
680 }
681
682 // If no module provides components then return the input deps unfiltered.
683 if len(components) == 0 {
684 return deps
685 }
686
687 filtered := make([]sdkMemberVariantDep, 0, len(deps))
688 for _, dep := range deps {
689 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
690 if owner, ok := components[name]; ok {
691 // This is a component of another module that is a member of the sdk.
692
693 // If the component is exported but the owning module is not then the configuration is not
694 // supported.
695 if dep.export && !owner.export {
696 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
697 continue
698 }
699
700 // This module must not be added to the list of members of the sdk as that would result in a
701 // duplicate module in the sdk snapshot.
702 continue
703 }
704
705 filtered = append(filtered, dep)
706 }
707 return filtered
708}
709
Paul Duffinf88d8e02020-05-07 20:21:34 +0100710// Check the syntax of the generated Android.bp file contents and if they are
711// invalid then log an error with the contents (tagged with line numbers) and the
712// errors that were found so that it is easy to see where the problem lies.
713func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
714 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
715 if len(errs) != 0 {
716 message := &strings.Builder{}
717 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
718
719Generated Android.bp contents
720========================================================================
721`)
722 for i, line := range strings.Split(contents, "\n") {
723 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
724 }
725
726 _, _ = fmt.Fprint(message, `
727========================================================================
728
729Errors found:
730`)
731
732 for _, err := range errs {
733 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
734 }
735
736 ctx.ModuleErrorf("%s", message.String())
737 }
738}
739
Paul Duffin4b8b7932020-05-06 12:35:38 +0100740func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
741 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
742 if err != nil {
743 ctx.ModuleErrorf("error extracting common properties: %s", err)
744 }
745}
746
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000747type propertyTag struct {
748 name string
749}
750
Paul Duffin94289702021-09-09 15:38:32 +0100751var _ android.BpPropertyTag = propertyTag{}
752
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000753// BpPropertyTag instances to add to a property that contains references to other sdk members.
Paul Duffin0cb37b92020-03-04 14:52:46 +0000754//
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000755// These will ensure that the referenced modules are available, if required.
Paul Duffin13f02712020-03-06 12:30:43 +0000756var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000757var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000758
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000759type snapshotTransformation struct {
Paul Duffine6c0d842020-01-15 14:08:51 +0000760 identityTransformation
761 builder *snapshotBuilder
762}
763
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000764func (t snapshotTransformation) transformModule(module *bpModule) *bpModule {
Sam Delmerico35881362023-06-30 14:40:10 -0400765 if module != nil {
766 // If the module is an internal member then use a unique name for it.
767 name := module.Name()
768 module.setProperty("name", t.builder.snapshotSdkMemberName(name, true))
769 }
Paul Duffin72910952020-01-20 18:16:30 +0000770 return module
771}
772
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000773func (t snapshotTransformation) transformProperty(_ string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000774 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
775 required := tag == requiredSdkMemberReferencePropertyTag
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000776 return t.builder.snapshotSdkMemberNames(value.([]string), required), tag
Paul Duffin72910952020-01-20 18:16:30 +0000777 } else {
778 return value, tag
779 }
780}
781
Sam Delmerico35881362023-06-30 14:40:10 -0400782type emptyClasspathContentsTransformation struct {
783 identityTransformation
784}
785
786func (t emptyClasspathContentsTransformation) transformModule(module *bpModule) *bpModule {
787 classpathModuleTypes := []string{
788 "prebuilt_bootclasspath_fragment",
789 "prebuilt_systemserverclasspath_fragment",
790 }
791 if module != nil && android.InList(module.moduleType, classpathModuleTypes) {
792 if contents, ok := module.bpPropertySet.properties["contents"].([]string); ok {
793 if len(contents) == 0 {
794 return nil
795 }
796 }
797 }
798 return module
799}
800
Paul Duffina78f3a72020-02-21 16:29:35 +0000801type pruneEmptySetTransformer struct {
802 identityTransformation
803}
804
805var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
806
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000807func (t pruneEmptySetTransformer) transformPropertySetAfterContents(_ string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
Paul Duffina78f3a72020-02-21 16:29:35 +0000808 if len(propertySet.properties) == 0 {
809 return nil, nil
810 } else {
811 return propertySet, tag
812 }
813}
814
Cole Fausted158f42024-03-07 16:41:27 -0800815func generateBpContents(bpFile *bpFile) string {
816 contents := &generatedContents{}
Paul Duffina08e4dc2021-06-22 18:19:19 +0100817 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000818 for _, bpModule := range bpFile.order {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000819 contents.IndentedPrintf("\n")
820 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
821 outputPropertySet(contents, bpModule.bpPropertySet)
822 contents.IndentedPrintf("}\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000823 }
Cole Fausted158f42024-03-07 16:41:27 -0800824 return contents.content.String()
Paul Duffinb645ec82019-11-27 17:43:54 +0000825}
826
827func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
828 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000829
Paul Duffin0df49682021-05-07 01:10:01 +0100830 addComment := func(name string) {
831 if text, ok := set.comments[name]; ok {
832 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100833 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100834 }
835 }
836 }
837
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000838 // Output the properties first, followed by the nested sets. This ensures a
839 // consistent output irrespective of whether property sets are created before
840 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000841 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000842 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000843
Paul Duffin0df49682021-05-07 01:10:01 +0100844 // Do not write property sets in the properties phase.
845 if _, ok := value.(*bpPropertySet); ok {
846 continue
847 }
848
849 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100850 reflectValue := reflect.ValueOf(value)
851 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000852 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000853
854 for _, name := range set.order {
855 value := set.getValue(name)
856
857 // Only write property sets in the sets phase.
858 switch v := value.(type) {
859 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100860 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100861 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000862 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100863 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000864 }
865 }
866
Paul Duffinb645ec82019-11-27 17:43:54 +0000867 contents.Dedent()
868}
869
Paul Duffina08e4dc2021-06-22 18:19:19 +0100870// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
871// by the value and then followed by a , and a newline.
872func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
873 contents.IndentedPrintf("%s: ", name)
874 outputUnnamedValue(contents, value)
875 contents.UnindentedPrintf(",\n")
876}
877
878// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
879// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
880// indented and all but the last line will end with a newline.
881func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
882 valueType := value.Type()
883 switch valueType.Kind() {
884 case reflect.Bool:
885 contents.UnindentedPrintf("%t", value.Bool())
886
887 case reflect.String:
888 contents.UnindentedPrintf("%q", value)
889
Paul Duffin51227d82021-05-18 12:54:27 +0100890 case reflect.Ptr:
891 outputUnnamedValue(contents, value.Elem())
892
Paul Duffina08e4dc2021-06-22 18:19:19 +0100893 case reflect.Slice:
894 length := value.Len()
895 if length == 0 {
896 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100897 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100898 firstValue := value.Index(0)
899 if length == 1 && !multiLineValue(firstValue) {
900 contents.UnindentedPrintf("[")
901 outputUnnamedValue(contents, firstValue)
902 contents.UnindentedPrintf("]")
903 } else {
904 contents.UnindentedPrintf("[\n")
905 contents.Indent()
906 for i := 0; i < length; i++ {
907 itemValue := value.Index(i)
908 contents.IndentedPrintf("")
909 outputUnnamedValue(contents, itemValue)
910 contents.UnindentedPrintf(",\n")
911 }
912 contents.Dedent()
913 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100914 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100915 }
916
Paul Duffin51227d82021-05-18 12:54:27 +0100917 case reflect.Struct:
918 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
919 v := value.Interface()
920 if _, ok := v.(android.BpPrintable); !ok {
921 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
922 }
923 contents.UnindentedPrintf("{\n")
924 contents.Indent()
925 for f := 0; f < valueType.NumField(); f++ {
926 fieldType := valueType.Field(f)
927 if fieldType.Anonymous {
928 continue
929 }
930 fieldValue := value.Field(f)
931 fieldName := fieldType.Name
932 propertyName := proptools.PropertyNameForField(fieldName)
933 outputNamedValue(contents, propertyName, fieldValue)
934 }
935 contents.Dedent()
936 contents.IndentedPrintf("}")
937
Paul Duffina08e4dc2021-06-22 18:19:19 +0100938 default:
Cole Faust8c366312024-03-08 10:58:32 -0800939 panic(fmt.Errorf("unknown type: %T of value %#v", value, value))
Paul Duffina08e4dc2021-06-22 18:19:19 +0100940 }
941}
942
Paul Duffin51227d82021-05-18 12:54:27 +0100943// multiLineValue returns true if the supplied value may require multiple lines in the output.
944func multiLineValue(value reflect.Value) bool {
945 kind := value.Kind()
946 return kind == reflect.Slice || kind == reflect.Struct
947}
948
Paul Duffinac37c502019-11-26 18:02:20 +0000949func (s *sdk) GetAndroidBpContentsForTests() string {
Cole Fausted158f42024-03-07 16:41:27 -0800950 return generateBpContents(s.builderForTests.bpFile)
Paul Duffinac37c502019-11-26 18:02:20 +0000951}
952
Paul Duffinc6ba1822022-05-06 09:38:02 +0000953func (s *sdk) GetInfoContentsForTests() string {
954 return s.builderForTests.infoContents
955}
956
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000957type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100958 ctx android.ModuleContext
959 sdk *sdk
960
Paul Duffinb645ec82019-11-27 17:43:54 +0000961 snapshotDir android.OutputPath
962 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000963
964 // Map from destination to source of each copy - used to eliminate duplicates and
965 // detect conflicts.
966 copies map[string]string
967
Paul Duffinb645ec82019-11-27 17:43:54 +0000968 filesToZip android.Paths
969 zipsToMerge android.Paths
970
Paul Duffin7ed6ff82022-11-21 10:57:30 +0000971 // The path to an empty file.
972 emptyFile android.WritablePath
973
Paul Duffinb645ec82019-11-27 17:43:54 +0000974 prebuiltModules map[string]*bpModule
975 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000976
977 // The set of all members by name.
978 allMembersByName map[string]struct{}
979
980 // The set of exported members by name.
981 exportedMembersByName map[string]struct{}
Paul Duffin39abf8f2021-09-24 14:58:27 +0100982
Paul Duffin1938dba2022-07-26 23:53:00 +0000983 // The set of members which have been excluded from this snapshot; by name.
984 excludedMembersByName map[string]struct{}
985
Paul Duffin39abf8f2021-09-24 14:58:27 +0100986 // The target build release for which the snapshot is to be generated.
987 targetBuildRelease *buildRelease
Paul Duffinc6ba1822022-05-06 09:38:02 +0000988
Paul Duffin958806b2022-05-16 13:10:47 +0000989 // The contents of the .info file that describes the sdk contents.
Paul Duffinc6ba1822022-05-06 09:38:02 +0000990 infoContents string
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000991}
992
993func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000994 if existing, ok := s.copies[dest]; ok {
995 if existing != src.String() {
996 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
997 return
998 }
999 } else {
1000 path := s.snapshotDir.Join(s.ctx, dest)
1001 s.ctx.Build(pctx, android.BuildParams{
1002 Rule: android.Cp,
1003 Input: src,
1004 Output: path,
1005 })
1006 s.filesToZip = append(s.filesToZip, path)
1007
1008 s.copies[dest] = src.String()
1009 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001010}
1011
Paul Duffin91547182019-11-12 19:39:36 +00001012func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1013 ctx := s.ctx
1014
1015 // Repackage the zip file so that the entries are in the destDir directory.
1016 // This will allow the zip file to be merged into the snapshot.
1017 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001018
1019 ctx.Build(pctx, android.BuildParams{
1020 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1021 Rule: repackageZip,
1022 Input: zipPath,
1023 Output: tmpZipPath,
1024 Args: map[string]string{
1025 "destdir": destDir,
1026 },
1027 })
Paul Duffin91547182019-11-12 19:39:36 +00001028
1029 // Add the repackaged zip file to the files to merge.
1030 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1031}
1032
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001033func (s *snapshotBuilder) EmptyFile() android.Path {
1034 if s.emptyFile == nil {
1035 ctx := s.ctx
1036 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1037 s.ctx.Build(pctx, android.BuildParams{
1038 Rule: android.Touch,
1039 Output: s.emptyFile,
1040 })
1041 }
1042
1043 return s.emptyFile
1044}
1045
Paul Duffin9d8d6092019-12-05 18:19:29 +00001046func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1047 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001048 if s.prebuiltModules[name] != nil {
1049 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1050 }
1051
1052 m := s.bpFile.newModule(moduleType)
1053 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001054
Paul Duffinbefa4b92020-03-04 14:22:45 +00001055 variant := member.Variants()[0]
1056
Paul Duffin13f02712020-03-06 12:30:43 +00001057 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001058 // An internal member is only referenced from the sdk snapshot which is in the
1059 // same package so can be marked as private.
1060 m.AddProperty("visibility", []string{"//visibility:private"})
1061 } else {
1062 // Extract visibility information from a member variant. All variants have the same
1063 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001064 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1065
1066 // Add any additional visibility rules needed for the prebuilts to reference each other.
1067 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1068 if err != nil {
1069 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1070 }
1071
1072 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001073 if len(visibility) != 0 {
1074 m.AddProperty("visibility", visibility)
1075 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001076 }
1077
Martin Stjernholm1e041092020-11-03 00:11:09 +00001078 // Where available copy apex_available properties from the member.
1079 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1080 apexAvailable := apexAware.ApexAvailable()
1081 if len(apexAvailable) == 0 {
1082 // //apex_available:platform is the default.
1083 apexAvailable = []string{android.AvailableToPlatform}
1084 }
1085
1086 // Add in any baseline apex available settings.
1087 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1088
1089 // Remove duplicates and sort.
1090 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1091 sort.Strings(apexAvailable)
1092
1093 m.AddProperty("apex_available", apexAvailable)
1094 }
1095
Paul Duffinb0bb3762021-05-06 16:48:05 +01001096 // The licenses are the same for all variants.
1097 mctx := s.ctx
Colin Cross313aa542023-12-13 13:47:44 -08001098 licenseInfo, _ := android.OtherModuleProvider(mctx, variant, android.LicenseInfoProvider)
Paul Duffinb0bb3762021-05-06 16:48:05 +01001099 if len(licenseInfo.Licenses) > 0 {
1100 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1101 }
1102
Paul Duffin865171e2020-03-02 18:38:15 +00001103 deviceSupported := false
1104 hostSupported := false
1105
1106 for _, variant := range member.Variants() {
1107 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001108 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001109 hostSupported = true
1110 } else if osClass == android.Device {
1111 deviceSupported = true
1112 }
1113 }
1114
1115 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001116
1117 s.prebuiltModules[name] = m
1118 s.prebuiltOrder = append(s.prebuiltOrder, m)
1119 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001120}
1121
Paul Duffin865171e2020-03-02 18:38:15 +00001122func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001123 // If neither device or host is supported then this module does not support either so will not
1124 // recognize the properties.
1125 if !deviceSupported && !hostSupported {
1126 return
1127 }
1128
Paul Duffin865171e2020-03-02 18:38:15 +00001129 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001130 bpModule.AddProperty("device_supported", false)
1131 }
Paul Duffin865171e2020-03-02 18:38:15 +00001132 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001133 bpModule.AddProperty("host_supported", true)
1134 }
1135}
1136
Paul Duffin13f02712020-03-06 12:30:43 +00001137func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1138 if required {
1139 return requiredSdkMemberReferencePropertyTag
1140 } else {
1141 return optionalSdkMemberReferencePropertyTag
1142 }
1143}
1144
1145func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1146 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001147}
1148
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001149// Get a name for sdk snapshot member. If the member is private then generate a snapshot specific
1150// name. As part of the processing this checks to make sure that any required members are part of
1151// the snapshot.
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001152func (s *snapshotBuilder) snapshotSdkMemberName(name string, required bool) string {
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001153 if _, ok := s.allMembersByName[name]; !ok {
Paul Duffin13f02712020-03-06 12:30:43 +00001154 if required {
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001155 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", name)
Paul Duffin13f02712020-03-06 12:30:43 +00001156 }
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001157 return name
Paul Duffin13f02712020-03-06 12:30:43 +00001158 }
1159
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001160 if s.isInternalMember(name) {
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001161 return s.ctx.ModuleName() + "_" + name
Paul Duffin72910952020-01-20 18:16:30 +00001162 } else {
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001163 return name
Paul Duffin72910952020-01-20 18:16:30 +00001164 }
1165}
1166
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001167func (s *snapshotBuilder) snapshotSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001168 var references []string = nil
1169 for _, m := range members {
Paul Duffin1938dba2022-07-26 23:53:00 +00001170 if _, ok := s.excludedMembersByName[m]; ok {
1171 continue
1172 }
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001173 references = append(references, s.snapshotSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001174 }
1175 return references
1176}
1177
Paul Duffin13f02712020-03-06 12:30:43 +00001178func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1179 _, ok := s.exportedMembersByName[memberName]
1180 return !ok
1181}
1182
Martin Stjernholm89238f42020-07-10 00:14:03 +01001183// Add the properties from the given SdkMemberProperties to the blueprint
1184// property set. This handles common properties in SdkMemberPropertiesBase and
1185// calls the member-specific AddToPropertySet for the rest.
1186func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1187 if memberProperties.Base().Compile_multilib != "" {
1188 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1189 }
1190
1191 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1192}
1193
Paul Duffin21827262021-04-24 12:16:36 +01001194// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1195type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001196 // The sdk variant that depends (possibly indirectly) on the member variant.
1197 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001198
1199 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001200 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001201
1202 // The variant that is added to the sdk.
Paul Duffin5e71e682022-11-23 18:09:54 +00001203 variant android.Module
Paul Duffinb97b1572021-04-29 21:50:40 +01001204
Paul Duffinc6ba1822022-05-06 09:38:02 +00001205 // The optional container of this member, i.e. the module that is depended upon by the sdk
1206 // (possibly transitively) and whose dependency on this module is why it was added to the sdk.
1207 // Is nil if this a direct dependency of the sdk.
Paul Duffin5e71e682022-11-23 18:09:54 +00001208 container android.Module
Paul Duffinc6ba1822022-05-06 09:38:02 +00001209
Paul Duffinb97b1572021-04-29 21:50:40 +01001210 // True if the member should be exported, i.e. accessible, from outside the sdk.
1211 export bool
1212
1213 // The names of additional component modules provided by the variant.
1214 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1938dba2022-07-26 23:53:00 +00001215
1216 // The minimum API level on which this module is supported.
1217 minApiLevel android.ApiLevel
Paul Duffin1356d8c2020-02-25 19:26:33 +00001218}
1219
Spandan Dasb84dbb22023-03-08 22:06:35 +00001220// Host returns true if the sdk member is a host variant (e.g. host tool)
1221func (s *sdkMemberVariantDep) Host() bool {
1222 return s.variant.Target().Os.Class == android.Host
1223}
1224
Paul Duffin13879572019-11-28 14:31:38 +00001225var _ android.SdkMember = (*sdkMember)(nil)
1226
Paul Duffin21827262021-04-24 12:16:36 +01001227// sdkMember groups all the variants of a specific member module together along with the name of the
1228// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001229type sdkMember struct {
1230 memberType android.SdkMemberType
1231 name string
Paul Duffin5e71e682022-11-23 18:09:54 +00001232 variants []android.Module
Paul Duffin13879572019-11-28 14:31:38 +00001233}
1234
1235func (m *sdkMember) Name() string {
1236 return m.name
1237}
1238
Paul Duffin5e71e682022-11-23 18:09:54 +00001239func (m *sdkMember) Variants() []android.Module {
Paul Duffin13879572019-11-28 14:31:38 +00001240 return m.variants
1241}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001242
Paul Duffin9c3760e2020-03-16 19:52:08 +00001243// Track usages of multilib variants.
1244type multilibUsage int
1245
1246const (
1247 multilibNone multilibUsage = 0
1248 multilib32 multilibUsage = 1
1249 multilib64 multilibUsage = 2
1250 multilibBoth = multilib32 | multilib64
1251)
1252
1253// Add the multilib that is used in the arch type.
1254func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1255 multilib := archType.Multilib
1256 switch multilib {
1257 case "":
1258 return m
1259 case "lib32":
1260 return m | multilib32
1261 case "lib64":
1262 return m | multilib64
1263 default:
Cole Faust8c366312024-03-08 10:58:32 -08001264 panic(fmt.Errorf("unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
Paul Duffin9c3760e2020-03-16 19:52:08 +00001265 }
1266}
1267
1268func (m multilibUsage) String() string {
1269 switch m {
1270 case multilibNone:
1271 return ""
1272 case multilib32:
1273 return "32"
1274 case multilib64:
1275 return "64"
1276 case multilibBoth:
1277 return "both"
1278 default:
Cole Faust8c366312024-03-08 10:58:32 -08001279 panic(fmt.Errorf("unknown multilib value, found %b, expected one of %b, %b, %b or %b",
Paul Duffin9c3760e2020-03-16 19:52:08 +00001280 m, multilibNone, multilib32, multilib64, multilibBoth))
1281 }
1282}
1283
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001284// TODO(187910671): BEGIN - Remove once modules do not have an APEX and default variant.
1285// variantCoordinate contains the coordinates used to identify a variant of an SDK member.
1286type variantCoordinate struct {
1287 // osType identifies the OS target of a variant.
1288 osType android.OsType
1289 // archId identifies the architecture and whether it is for the native bridge.
1290 archId archId
1291 // image is the image variant name.
1292 image string
1293 // linkType is the link type name.
1294 linkType string
1295}
1296
1297func getVariantCoordinate(ctx *memberContext, variant android.Module) variantCoordinate {
1298 linkType := ""
1299 if len(ctx.MemberType().SupportedLinkages()) > 0 {
1300 linkType = getLinkType(variant)
1301 }
1302 return variantCoordinate{
1303 osType: variant.Target().Os,
1304 archId: archIdFromTarget(variant.Target()),
1305 image: variant.ImageVariation().Variation,
1306 linkType: linkType,
1307 }
1308}
1309
1310// selectApexVariantsWhereAvailable filters the input list of variants by selecting the APEX
1311// specific variant for a specific variantCoordinate when there is both an APEX and default variant.
1312//
1313// There is a long-standing issue where a module that is added to an APEX has both an APEX and
1314// default/platform variant created even when the module does not require a platform variant. As a
1315// result an indirect dependency onto a module via the APEX will use the APEX variant, whereas a
1316// direct dependency onto the module will use the default/platform variant. That would result in a
1317// failure while attempting to optimize the properties for a member as it would have two variants
1318// when only one was expected.
1319//
1320// This function mitigates that problem by detecting when there are two variants that differ only
1321// by apex variant, where one is the default/platform variant and one is the APEX variant. In that
1322// case it picks the APEX variant. It picks the APEX variant because that is the behavior that would
1323// be expected
Paul Duffin5e71e682022-11-23 18:09:54 +00001324func selectApexVariantsWhereAvailable(ctx *memberContext, variants []android.Module) []android.Module {
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001325 moduleCtx := ctx.sdkMemberContext
1326
1327 // Group the variants by coordinates.
Paul Duffin5e71e682022-11-23 18:09:54 +00001328 variantsByCoord := make(map[variantCoordinate][]android.Module)
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001329 for _, variant := range variants {
1330 coord := getVariantCoordinate(ctx, variant)
1331 variantsByCoord[coord] = append(variantsByCoord[coord], variant)
1332 }
1333
Paul Duffin5e71e682022-11-23 18:09:54 +00001334 toDiscard := make(map[android.Module]struct{})
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001335 for coord, list := range variantsByCoord {
1336 count := len(list)
1337 if count == 1 {
1338 continue
1339 }
1340
Paul Duffin5e71e682022-11-23 18:09:54 +00001341 variantsByApex := make(map[string]android.Module)
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001342 conflictDetected := false
1343 for _, variant := range list {
Colin Cross313aa542023-12-13 13:47:44 -08001344 apexInfo, _ := android.OtherModuleProvider(moduleCtx, variant, android.ApexInfoProvider)
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001345 apexVariationName := apexInfo.ApexVariationName
1346 // If there are two variants for a specific APEX variation then there is conflict.
1347 if _, ok := variantsByApex[apexVariationName]; ok {
1348 conflictDetected = true
1349 break
1350 }
1351 variantsByApex[apexVariationName] = variant
1352 }
1353
1354 // If there are more than 2 apex variations or one of the apex variations is not the
1355 // default/platform variation then there is a conflict.
1356 if len(variantsByApex) != 2 {
1357 conflictDetected = true
1358 } else if _, ok := variantsByApex[""]; !ok {
1359 conflictDetected = true
1360 }
1361
1362 // If there are no conflicts then add the default/platform variation to the list to remove.
1363 if !conflictDetected {
1364 toDiscard[variantsByApex[""]] = struct{}{}
1365 continue
1366 }
1367
1368 // There are duplicate variants at this coordinate and they are not the default and APEX variant
1369 // so fail.
1370 variantDescriptions := []string{}
1371 for _, m := range list {
1372 variantDescriptions = append(variantDescriptions, fmt.Sprintf(" %s", m.String()))
1373 }
1374
1375 moduleCtx.ModuleErrorf("multiple conflicting variants detected for OsType{%s}, %s, Image{%s}, Link{%s}\n%s",
1376 coord.osType, coord.archId.String(), coord.image, coord.linkType,
1377 strings.Join(variantDescriptions, "\n"))
1378 }
1379
1380 // If there are any variants to discard then remove them from the list of variants, while
1381 // preserving the order.
1382 if len(toDiscard) > 0 {
Paul Duffin5e71e682022-11-23 18:09:54 +00001383 filtered := []android.Module{}
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001384 for _, variant := range variants {
1385 if _, ok := toDiscard[variant]; !ok {
1386 filtered = append(filtered, variant)
1387 }
1388 }
1389 variants = filtered
1390 }
1391
1392 return variants
1393}
1394
1395// TODO(187910671): END - Remove once modules do not have an APEX and default variant.
1396
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001397type baseInfo struct {
1398 Properties android.SdkMemberProperties
1399}
1400
Paul Duffinf34f6d82020-04-30 15:48:31 +01001401func (b *baseInfo) optimizableProperties() interface{} {
1402 return b.Properties
1403}
1404
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001405type osTypeSpecificInfo struct {
1406 baseInfo
1407
Paul Duffin00e46802020-03-12 20:40:35 +00001408 osType android.OsType
1409
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001410 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001411 //
1412 // Nil if there is one variant whose arch type is common
1413 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001414}
1415
Paul Duffin4b8b7932020-05-06 12:35:38 +01001416var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1417
Paul Duffinfc8dd232020-03-17 12:51:37 +00001418type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1419
Paul Duffin00e46802020-03-12 20:40:35 +00001420// Create a new osTypeSpecificInfo for the specified os type and its properties
1421// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001422func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001423 osInfo := &osTypeSpecificInfo{
1424 osType: osType,
1425 }
1426
1427 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1428 properties := variantPropertiesFactory()
1429 properties.Base().Os = osType
1430 return properties
1431 }
1432
1433 // Create a structure into which properties common across the architectures in
1434 // this os type will be stored.
1435 osInfo.Properties = osSpecificVariantPropertiesFactory()
1436
1437 // Group the variants by arch type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001438 var variantsByArchId = make(map[archId][]android.Module)
1439 var archIds []archId
Paul Duffin00e46802020-03-12 20:40:35 +00001440 for _, variant := range osTypeVariants {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001441 target := variant.Target()
1442 id := archIdFromTarget(target)
1443 if _, ok := variantsByArchId[id]; !ok {
1444 archIds = append(archIds, id)
Paul Duffin00e46802020-03-12 20:40:35 +00001445 }
1446
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001447 variantsByArchId[id] = append(variantsByArchId[id], variant)
Paul Duffin00e46802020-03-12 20:40:35 +00001448 }
1449
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001450 if commonVariants, ok := variantsByArchId[commonArchId]; ok {
Paul Duffin00e46802020-03-12 20:40:35 +00001451 if len(osTypeVariants) != 1 {
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001452 variants := []string{}
1453 for _, m := range osTypeVariants {
1454 variants = append(variants, fmt.Sprintf(" %s", m.String()))
1455 }
1456 panic(fmt.Errorf("expected to only have 1 variant of %q when arch type is common but found %d\n%s",
1457 ctx.Name(),
1458 len(osTypeVariants),
1459 strings.Join(variants, "\n")))
Paul Duffin00e46802020-03-12 20:40:35 +00001460 }
1461
1462 // A common arch type only has one variant and its properties should be treated
1463 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001464 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001465 } else {
1466 // Create an arch specific info for each supported architecture type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001467 for _, id := range archIds {
1468 archVariants := variantsByArchId[id]
1469 archInfo := newArchSpecificInfo(ctx, id, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001470
1471 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1472 }
1473 }
1474
1475 return osInfo
1476}
1477
Paul Duffin39abf8f2021-09-24 14:58:27 +01001478func (osInfo *osTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1479 if len(osInfo.archInfos) == 0 {
1480 pruner.pruneProperties(osInfo.Properties)
1481 } else {
1482 for _, archInfo := range osInfo.archInfos {
1483 archInfo.pruneUnsupportedProperties(pruner)
1484 }
1485 }
1486}
1487
Paul Duffin00e46802020-03-12 20:40:35 +00001488// Optimize the properties by extracting common properties from arch type specific
1489// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001490func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001491 // Nothing to do if there is only a single common architecture.
1492 if len(osInfo.archInfos) == 0 {
1493 return
1494 }
1495
Paul Duffin9c3760e2020-03-16 19:52:08 +00001496 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001497 for _, archInfo := range osInfo.archInfos {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001498 multilib = multilib.addArchType(archInfo.archId.archType)
Paul Duffin9c3760e2020-03-16 19:52:08 +00001499
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001500 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001501 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001502 }
1503
Paul Duffin4b8b7932020-05-06 12:35:38 +01001504 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001505
1506 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001507 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001508}
1509
1510// Add the properties for an os to a property set.
1511//
1512// Maps the properties related to the os variants through to an appropriate
1513// module structure that will produce equivalent set of variants when it is
1514// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001515func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001516
1517 var osPropertySet android.BpPropertySet
1518 var archPropertySet android.BpPropertySet
1519 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001520 if osInfo.Properties.Base().Os_count == 1 &&
1521 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1522 // There is only one OS type present in the variants and it shouldn't have a
1523 // variant-specific target. The latter is the case if it's either for device
1524 // where there is only one OS (android), or for host and the member type
1525 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001526
1527 // Create a structure that looks like:
1528 // module_type {
1529 // name: "...",
1530 // ...
1531 // <common properties>
1532 // ...
1533 // <single os type specific properties>
1534 //
1535 // arch: {
1536 // <arch specific sections>
1537 // }
1538 //
1539 osPropertySet = bpModule
1540 archPropertySet = osPropertySet.AddPropertySet("arch")
1541
1542 // Arch specific properties need to be added to an arch specific section
1543 // within arch.
1544 archOsPrefix = ""
1545 } else {
1546 // Create a structure that looks like:
1547 // module_type {
1548 // name: "...",
1549 // ...
1550 // <common properties>
1551 // ...
1552 // target: {
1553 // <arch independent os specific sections, e.g. android>
1554 // ...
1555 // <arch and os specific sections, e.g. android_x86>
1556 // }
1557 //
1558 osType := osInfo.osType
1559 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1560 archPropertySet = targetPropertySet
1561
1562 // Arch specific properties need to be added to an os and arch specific
1563 // section prefixed with <os>_.
1564 archOsPrefix = osType.Name + "_"
1565 }
1566
1567 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001568 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001569
1570 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1571 // os) specific properties.
1572 //
1573 // The archInfos list will be empty if the os contains variants for the common
1574 // architecture.
1575 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001576 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001577 }
1578}
1579
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001580func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1581 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001582 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001583}
1584
1585var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1586
Paul Duffin4b8b7932020-05-06 12:35:38 +01001587func (osInfo *osTypeSpecificInfo) String() string {
1588 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1589}
1590
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001591// archId encapsulates the information needed to identify a combination of arch type and native
1592// bridge support.
1593//
1594// Conceptually, native bridge support is a facet of an android.Target, not an android.Arch as it is
1595// essentially using one android.Arch to implement another. However, in terms of the handling of
1596// the variants native bridge is treated as part of the arch variation. See the ArchVariation method
1597// on android.Target.
1598//
1599// So, it makes sense when optimizing the variants to combine native bridge with the arch type.
1600type archId struct {
1601 // The arch type of the variant's target.
1602 archType android.ArchType
1603
1604 // True if the variants is for the native bridge, false otherwise.
1605 nativeBridge bool
1606}
1607
1608// propertyName returns the name of the property corresponding to use for this arch id.
1609func (i *archId) propertyName() string {
1610 name := i.archType.Name
1611 if i.nativeBridge {
1612 // Note: This does not result in a valid property because there is no architecture specific
1613 // native bridge property, only a generic "native_bridge" property. However, this will be used
1614 // in error messages if there is an attempt to use this in a generated bp file.
1615 name += "_native_bridge"
1616 }
1617 return name
1618}
1619
1620func (i *archId) String() string {
1621 return fmt.Sprintf("ArchType{%s}, NativeBridge{%t}", i.archType, i.nativeBridge)
1622}
1623
1624// archIdFromTarget returns an archId initialized from information in the supplied target.
1625func archIdFromTarget(target android.Target) archId {
1626 return archId{
1627 archType: target.Arch.ArchType,
1628 nativeBridge: target.NativeBridge == android.NativeBridgeEnabled,
1629 }
1630}
1631
1632// commonArchId is the archId for the common architecture.
1633var commonArchId = archId{archType: android.Common}
1634
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001635type archTypeSpecificInfo struct {
1636 baseInfo
1637
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001638 archId archId
1639 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001640
Paul Duffinb42fa672021-09-09 16:37:49 +01001641 imageVariantInfos []*imageVariantSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001642}
1643
Paul Duffin4b8b7932020-05-06 12:35:38 +01001644var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1645
Paul Duffinfc8dd232020-03-17 12:51:37 +00001646// Create a new archTypeSpecificInfo for the specified arch type and its properties
1647// structures populated with information from the variants.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001648func newArchSpecificInfo(ctx android.SdkMemberContext, archId archId, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001649
Paul Duffinfc8dd232020-03-17 12:51:37 +00001650 // Create an arch specific info into which the variant properties can be copied.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001651 archInfo := &archTypeSpecificInfo{archId: archId, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001652
1653 // Create the properties into which the arch type specific properties will be
1654 // added.
1655 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001656
Liz Kammer96320df2022-05-12 20:40:00 -04001657 // if there are multiple supported link variants, we want to nest based on linkage even if there
1658 // is only one variant, otherwise, if there is only one variant we can populate based on the arch
1659 if len(archVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001660 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001661 } else {
Paul Duffinb42fa672021-09-09 16:37:49 +01001662 // Group the variants by image type.
1663 variantsByImage := make(map[string][]android.Module)
1664 for _, variant := range archVariants {
1665 image := variant.ImageVariation().Variation
1666 variantsByImage[image] = append(variantsByImage[image], variant)
1667 }
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001668
Paul Duffinb42fa672021-09-09 16:37:49 +01001669 // Create the image variant info in a fixed order.
Cole Faust18994c72023-02-28 16:02:16 -08001670 for _, imageVariantName := range android.SortedKeys(variantsByImage) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001671 variants := variantsByImage[imageVariantName]
1672 archInfo.imageVariantInfos = append(archInfo.imageVariantInfos, newImageVariantSpecificInfo(ctx, imageVariantName, variantPropertiesFactory, variants))
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001673 }
1674 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001675
1676 return archInfo
1677}
1678
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001679// Get the link type of the variant
1680//
1681// If the variant is not differentiated by link type then it returns "",
1682// otherwise it returns one of "static" or "shared".
1683func getLinkType(variant android.Module) string {
1684 linkType := ""
1685 if linkable, ok := variant.(cc.LinkableInterface); ok {
1686 if linkable.Shared() && linkable.Static() {
1687 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1688 } else if linkable.Shared() {
1689 linkType = "shared"
1690 } else if linkable.Static() {
1691 linkType = "static"
1692 } else {
1693 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1694 }
1695 }
1696 return linkType
1697}
1698
Paul Duffin39abf8f2021-09-24 14:58:27 +01001699func (archInfo *archTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1700 if len(archInfo.imageVariantInfos) == 0 {
1701 pruner.pruneProperties(archInfo.Properties)
1702 } else {
1703 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1704 imageVariantInfo.pruneUnsupportedProperties(pruner)
1705 }
1706 }
1707}
1708
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001709// Optimize the properties by extracting common properties from link type specific
1710// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001711func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001712 if len(archInfo.imageVariantInfos) == 0 {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001713 return
1714 }
1715
Paul Duffinb42fa672021-09-09 16:37:49 +01001716 // Optimize the image variant properties first.
1717 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1718 imageVariantInfo.optimizeProperties(ctx, commonValueExtractor)
1719 }
1720
1721 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.imageVariantInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001722}
1723
Paul Duffinfc8dd232020-03-17 12:51:37 +00001724// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001725func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001726 archPropertySuffix := archInfo.archId.propertyName()
1727 propertySetName := archOsPrefix + archPropertySuffix
1728 archTypePropertySet := archPropertySet.AddPropertySet(propertySetName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001729 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1730 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1731 archTypePropertySet.AddProperty("enabled", true)
1732 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001733 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001734
Paul Duffinb42fa672021-09-09 16:37:49 +01001735 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1736 imageVariantInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001737 }
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001738
1739 // If this is for a native bridge architecture then make sure that the property set does not
1740 // contain any properties as providing native bridge specific properties is not currently
1741 // supported.
1742 if archInfo.archId.nativeBridge {
1743 propertySetContents := getPropertySetContents(archTypePropertySet)
1744 if propertySetContents != "" {
1745 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",
1746 propertySetName, ctx.name, propertySetContents)
1747 }
1748 }
1749}
1750
1751// getPropertySetContents returns the string representation of the contents of a property set, after
1752// recursively pruning any empty nested property sets.
1753func getPropertySetContents(propertySet android.BpPropertySet) string {
1754 set := propertySet.(*bpPropertySet)
1755 set.transformContents(pruneEmptySetTransformer{})
1756 if len(set.properties) != 0 {
1757 contents := &generatedContents{}
1758 contents.Indent()
1759 outputPropertySet(contents, set)
1760 setAsString := contents.content.String()
1761 return setAsString
1762 }
1763 return ""
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001764}
1765
Paul Duffin4b8b7932020-05-06 12:35:38 +01001766func (archInfo *archTypeSpecificInfo) String() string {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001767 return archInfo.archId.String()
Paul Duffin4b8b7932020-05-06 12:35:38 +01001768}
1769
Paul Duffinb42fa672021-09-09 16:37:49 +01001770type imageVariantSpecificInfo struct {
1771 baseInfo
1772
1773 imageVariant string
1774
1775 linkInfos []*linkTypeSpecificInfo
1776}
1777
1778func newImageVariantSpecificInfo(ctx android.SdkMemberContext, imageVariant string, variantPropertiesFactory variantPropertiesFactoryFunc, imageVariants []android.Module) *imageVariantSpecificInfo {
1779
1780 // Create an image variant specific info into which the variant properties can be copied.
1781 imageInfo := &imageVariantSpecificInfo{imageVariant: imageVariant}
1782
1783 // Create the properties into which the image variant specific properties will be added.
1784 imageInfo.Properties = variantPropertiesFactory()
1785
Liz Kammer96320df2022-05-12 20:40:00 -04001786 // if there are multiple supported link variants, we want to nest even if there is only one
1787 // variant, otherwise, if there is only one variant we can populate based on the image
1788 if len(imageVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffinb42fa672021-09-09 16:37:49 +01001789 imageInfo.Properties.PopulateFromVariant(ctx, imageVariants[0])
1790 } else {
1791 // There is more than one variant for this image variant which must be differentiated by link
Liz Kammer96320df2022-05-12 20:40:00 -04001792 // type. Or there are multiple supported linkages and we need to nest based on link type.
Paul Duffinb42fa672021-09-09 16:37:49 +01001793 for _, linkVariant := range imageVariants {
1794 linkType := getLinkType(linkVariant)
1795 if linkType == "" {
1796 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(imageVariants)))
1797 } else {
1798 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
1799
1800 imageInfo.linkInfos = append(imageInfo.linkInfos, linkInfo)
1801 }
1802 }
1803 }
1804
1805 return imageInfo
1806}
1807
Paul Duffin39abf8f2021-09-24 14:58:27 +01001808func (imageInfo *imageVariantSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1809 if len(imageInfo.linkInfos) == 0 {
1810 pruner.pruneProperties(imageInfo.Properties)
1811 } else {
1812 for _, linkInfo := range imageInfo.linkInfos {
1813 linkInfo.pruneUnsupportedProperties(pruner)
1814 }
1815 }
1816}
1817
Paul Duffinb42fa672021-09-09 16:37:49 +01001818// Optimize the properties by extracting common properties from link type specific
1819// properties into arch type specific properties.
1820func (imageInfo *imageVariantSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
1821 if len(imageInfo.linkInfos) == 0 {
1822 return
1823 }
1824
1825 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, imageInfo.Properties, imageInfo.linkInfos)
1826}
1827
1828// Add the properties for an arch type to a property set.
1829func (imageInfo *imageVariantSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1830 if imageInfo.imageVariant != android.CoreVariation {
1831 propertySet = propertySet.AddPropertySet(imageInfo.imageVariant)
1832 }
1833
1834 addSdkMemberPropertiesToSet(ctx, imageInfo.Properties, propertySet)
1835
Liz Kammer96320df2022-05-12 20:40:00 -04001836 usedLinkages := make(map[string]bool, len(imageInfo.linkInfos))
Paul Duffinb42fa672021-09-09 16:37:49 +01001837 for _, linkInfo := range imageInfo.linkInfos {
Liz Kammer96320df2022-05-12 20:40:00 -04001838 usedLinkages[linkInfo.linkType] = true
Paul Duffinb42fa672021-09-09 16:37:49 +01001839 linkInfo.addToPropertySet(ctx, propertySet)
1840 }
1841
Liz Kammer96320df2022-05-12 20:40:00 -04001842 // If not all supported linkages had existing variants, we need to disable the unsupported variant
1843 if len(imageInfo.linkInfos) < len(ctx.MemberType().SupportedLinkages()) {
1844 for _, l := range ctx.MemberType().SupportedLinkages() {
1845 if _, ok := usedLinkages[l]; !ok {
1846 otherLinkagePropertySet := propertySet.AddPropertySet(l)
1847 otherLinkagePropertySet.AddProperty("enabled", false)
1848 }
1849 }
1850 }
1851
Paul Duffinb42fa672021-09-09 16:37:49 +01001852 // If this is for a non-core image variant then make sure that the property set does not contain
1853 // any properties as providing non-core image variant specific properties for prebuilts is not
1854 // currently supported.
1855 if imageInfo.imageVariant != android.CoreVariation {
1856 propertySetContents := getPropertySetContents(propertySet)
1857 if propertySetContents != "" {
1858 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",
1859 imageInfo.imageVariant, ctx.name, propertySetContents)
1860 }
1861 }
1862}
1863
1864func (imageInfo *imageVariantSpecificInfo) String() string {
1865 return imageInfo.imageVariant
1866}
1867
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001868type linkTypeSpecificInfo struct {
1869 baseInfo
1870
1871 linkType string
1872}
1873
Paul Duffin4b8b7932020-05-06 12:35:38 +01001874var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1875
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001876// Create a new linkTypeSpecificInfo for the specified link type and its properties
1877// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001878func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001879 linkInfo := &linkTypeSpecificInfo{
1880 baseInfo: baseInfo{
1881 // Create the properties into which the link type specific properties will be
1882 // added.
1883 Properties: variantPropertiesFactory(),
1884 },
1885 linkType: linkType,
1886 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001887 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001888 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001889}
1890
Paul Duffinf68f85a2021-09-09 16:11:42 +01001891func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1892 linkPropertySet := propertySet.AddPropertySet(l.linkType)
1893 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
1894}
1895
Paul Duffin39abf8f2021-09-24 14:58:27 +01001896func (l *linkTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1897 pruner.pruneProperties(l.Properties)
1898}
1899
Paul Duffin4b8b7932020-05-06 12:35:38 +01001900func (l *linkTypeSpecificInfo) String() string {
1901 return fmt.Sprintf("LinkType{%s}", l.linkType)
1902}
1903
Paul Duffin3a4eb502020-03-19 16:11:18 +00001904type memberContext struct {
1905 sdkMemberContext android.ModuleContext
1906 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001907 memberType android.SdkMemberType
1908 name string
Paul Duffind19f8942021-07-14 12:08:37 +01001909
1910 // The set of traits required of this member.
1911 requiredTraits android.SdkMemberTraitSet
Paul Duffin3a4eb502020-03-19 16:11:18 +00001912}
1913
Cole Faust34867402023-04-28 12:32:27 -07001914func (m *memberContext) ModuleErrorf(fmt string, args ...interface{}) {
1915 m.sdkMemberContext.ModuleErrorf(fmt, args...)
1916}
1917
Paul Duffin3a4eb502020-03-19 16:11:18 +00001918func (m *memberContext) SdkModuleContext() android.ModuleContext {
1919 return m.sdkMemberContext
1920}
1921
1922func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1923 return m.builder
1924}
1925
Paul Duffina551a1c2020-03-17 21:04:24 +00001926func (m *memberContext) MemberType() android.SdkMemberType {
1927 return m.memberType
1928}
1929
1930func (m *memberContext) Name() string {
1931 return m.name
1932}
1933
Paul Duffind19f8942021-07-14 12:08:37 +01001934func (m *memberContext) RequiresTrait(trait android.SdkMemberTrait) bool {
1935 return m.requiredTraits.Contains(trait)
1936}
1937
Paul Duffin13648912022-07-15 13:12:35 +00001938func (m *memberContext) IsTargetBuildBeforeTiramisu() bool {
1939 return m.builder.targetBuildRelease.EarlierThan(buildReleaseT)
1940}
1941
1942var _ android.SdkMemberContext = (*memberContext)(nil)
1943
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001944func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001945
1946 memberType := member.memberType
1947
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001948 // Do not add the prefer property if the member snapshot module is a source module type.
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001949 moduleCtx := ctx.sdkMemberContext
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001950 if !memberType.UsesSourceModuleTypeInSnapshot() {
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001951 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1952 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1953 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1954 // behavior is for the module.
Paul Duffin82d75ad2022-11-14 17:35:50 +00001955 bpModule.insertAfter("name", "prefer", false)
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001956 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001957
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001958 variants := selectApexVariantsWhereAvailable(ctx, member.variants)
1959
Paul Duffina04c1072020-03-02 10:16:35 +00001960 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001961 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001962 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001963 osType := variant.Target().Os
1964 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001965 }
1966
Paul Duffina04c1072020-03-02 10:16:35 +00001967 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001968 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001969 properties := memberType.CreateVariantPropertiesStruct()
1970 base := properties.Base()
1971 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001972 return properties
1973 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001974
Paul Duffina04c1072020-03-02 10:16:35 +00001975 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001976
Paul Duffina04c1072020-03-02 10:16:35 +00001977 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001978 commonProperties := variantPropertiesFactory()
1979 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001980
Paul Duffin39abf8f2021-09-24 14:58:27 +01001981 // Create a property pruner that will prune any properties unsupported by the target build
1982 // release.
1983 targetBuildRelease := ctx.builder.targetBuildRelease
1984 unsupportedPropertyPruner := newPropertyPrunerByBuildRelease(commonProperties, targetBuildRelease)
1985
Paul Duffinc097e362020-03-10 22:50:03 +00001986 // Create common value extractor that can be used to optimize the properties.
1987 commonValueExtractor := newCommonValueExtractor(commonProperties)
1988
Paul Duffina04c1072020-03-02 10:16:35 +00001989 // The list of property structures which are os type specific but common across
1990 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001991 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001992
1993 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001994 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001995 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001996 // Add the os specific properties to a list of os type specific yet architecture
1997 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001998 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001999
Paul Duffin39abf8f2021-09-24 14:58:27 +01002000 osInfo.pruneUnsupportedProperties(unsupportedPropertyPruner)
2001
Paul Duffin00e46802020-03-12 20:40:35 +00002002 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002003 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00002004 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002005
Paul Duffina04c1072020-03-02 10:16:35 +00002006 // Extract properties which are common across all architectures and os types.
Paul Duffin4e7d1c42022-05-13 13:12:19 +00002007 extractCommonProperties(moduleCtx, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002008
Paul Duffina04c1072020-03-02 10:16:35 +00002009 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01002010 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002011
Paul Duffina04c1072020-03-02 10:16:35 +00002012 // Create a target property set into which target specific properties can be
2013 // added.
2014 targetPropertySet := bpModule.AddPropertySet("target")
2015
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01002016 // If the member is host OS dependent and has host_supported then disable by
2017 // default and enable each host OS variant explicitly. This avoids problems
2018 // with implicitly enabled OS variants when the snapshot is used, which might
2019 // be different from this run (e.g. different build OS).
2020 if ctx.memberType.IsHostOsDependent() {
2021 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
2022 if hostSupported {
2023 hostPropertySet := targetPropertySet.AddPropertySet("host")
2024 hostPropertySet.AddProperty("enabled", false)
2025 }
2026 }
2027
Paul Duffina04c1072020-03-02 10:16:35 +00002028 // Iterate over the os types in a fixed order.
2029 for _, osType := range s.getPossibleOsTypes() {
2030 osInfo := osTypeToInfo[osType]
2031 if osInfo == nil {
2032 continue
2033 }
2034
Paul Duffin3a4eb502020-03-19 16:11:18 +00002035 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002036 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002037}
2038
Paul Duffina04c1072020-03-02 10:16:35 +00002039// Compute the list of possible os types that this sdk could support.
2040func (s *sdk) getPossibleOsTypes() []android.OsType {
2041 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00002042 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00002043 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07002044 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00002045 osTypes = append(osTypes, osType)
2046 }
2047 }
2048 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09002049 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00002050 osTypes = append(osTypes, osType)
2051 }
2052 }
2053 }
2054 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
2055 return osTypes
2056}
2057
Paul Duffinb28369a2020-05-04 15:39:59 +01002058// Given a set of properties (struct value), return the value of the field within that
2059// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00002060type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
2061
Paul Duffinc459f892020-04-30 18:08:29 +01002062// Checks the metadata to determine whether the property should be ignored for the
2063// purposes of common value extraction or not.
2064type extractorMetadataPredicate func(metadata propertiesContainer) bool
2065
2066// Indicates whether optimizable properties are provided by a host variant or
2067// not.
2068type isHostVariant interface {
2069 isHostVariant() bool
2070}
2071
Paul Duffinb28369a2020-05-04 15:39:59 +01002072// A property that can be optimized by the commonValueExtractor.
2073type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01002074 // The name of the field for this property. It is a "."-separated path for
2075 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002076 name string
2077
Paul Duffinc459f892020-04-30 18:08:29 +01002078 // Filter that can use metadata associated with the properties being optimized
2079 // to determine whether the field should be ignored during common value
2080 // optimization.
2081 filter extractorMetadataPredicate
2082
Paul Duffinb28369a2020-05-04 15:39:59 +01002083 // Retrieves the value on which common value optimization will be performed.
2084 getter fieldAccessorFunc
2085
Paul Duffinbfdca962022-09-22 16:21:54 +01002086 // True if the field should never be cleared.
2087 //
2088 // This is set to true if and only if the field is annotated with `sdk:"keep"`.
2089 keep bool
2090
Paul Duffinb28369a2020-05-04 15:39:59 +01002091 // The empty value for the field.
2092 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01002093
2094 // True if the property can support arch variants false otherwise.
2095 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01002096}
2097
Paul Duffin4b8b7932020-05-06 12:35:38 +01002098func (p extractorProperty) String() string {
2099 return p.name
2100}
2101
Paul Duffinc097e362020-03-10 22:50:03 +00002102// Supports extracting common values from a number of instances of a properties
2103// structure into a separate common set of properties.
2104type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01002105 // The properties that the extractor can optimize.
2106 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00002107}
2108
2109// Create a new common value extractor for the structure type for the supplied
2110// properties struct.
2111//
2112// The returned extractor can be used on any properties structure of the same type
2113// as the supplied set of properties.
2114func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
2115 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
2116 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01002117 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00002118 return extractor
2119}
2120
2121// Gather the fields from the supplied structure type from which common values will
2122// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00002123//
Martin Stjernholmb0249572020-09-15 02:32:35 +01002124// This is recursive function. If it encounters a struct then it will recurse
2125// into it, passing in the accessor for the field and the struct name as prefix
2126// for the nested fields. That will then be used in the accessors for the fields
2127// in the embedded struct.
2128func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00002129 for f := 0; f < structType.NumField(); f++ {
2130 field := structType.Field(f)
2131 if field.PkgPath != "" {
2132 // Ignore unexported fields.
2133 continue
2134 }
2135
Paul Duffin02e25c82022-09-22 15:30:58 +01002136 // Ignore fields tagged with sdk:"ignore".
2137 if proptools.HasTag(field, "sdk", "ignore") {
Paul Duffinc097e362020-03-10 22:50:03 +00002138 continue
2139 }
2140
Paul Duffinc459f892020-04-30 18:08:29 +01002141 var filter extractorMetadataPredicate
2142
2143 // Add a filter
2144 if proptools.HasTag(field, "sdk", "ignored-on-host") {
2145 filter = func(metadata propertiesContainer) bool {
2146 if m, ok := metadata.(isHostVariant); ok {
2147 if m.isHostVariant() {
2148 return false
2149 }
2150 }
2151 return true
2152 }
2153 }
2154
Paul Duffinbfdca962022-09-22 16:21:54 +01002155 keep := proptools.HasTag(field, "sdk", "keep")
2156
Paul Duffinc097e362020-03-10 22:50:03 +00002157 // Save a copy of the field index for use in the function.
2158 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01002159
Martin Stjernholmb0249572020-09-15 02:32:35 +01002160 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01002161
Paul Duffinc097e362020-03-10 22:50:03 +00002162 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00002163 if containingStructAccessor != nil {
2164 // This is an embedded structure so first access the field for the embedded
2165 // structure.
2166 value = containingStructAccessor(value)
2167 }
2168
Paul Duffinc097e362020-03-10 22:50:03 +00002169 // Skip through interface and pointer values to find the structure.
2170 value = getStructValue(value)
2171
Paul Duffin4b8b7932020-05-06 12:35:38 +01002172 defer func() {
2173 if r := recover(); r != nil {
2174 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
2175 }
2176 }()
2177
Paul Duffinc097e362020-03-10 22:50:03 +00002178 // Return the field.
2179 return value.Field(fieldIndex)
2180 }
2181
Martin Stjernholmb0249572020-09-15 02:32:35 +01002182 if field.Type.Kind() == reflect.Struct {
2183 // Gather fields from the nested or embedded structure.
2184 var subNamePrefix string
2185 if field.Anonymous {
2186 subNamePrefix = namePrefix
2187 } else {
2188 subNamePrefix = name + "."
2189 }
2190 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00002191 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01002192 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01002193 name,
Paul Duffinc459f892020-04-30 18:08:29 +01002194 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01002195 fieldGetter,
Paul Duffinbfdca962022-09-22 16:21:54 +01002196 keep,
Paul Duffinb28369a2020-05-04 15:39:59 +01002197 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01002198 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01002199 }
2200 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00002201 }
Paul Duffinc097e362020-03-10 22:50:03 +00002202 }
2203}
2204
2205func getStructValue(value reflect.Value) reflect.Value {
2206foundStruct:
2207 for {
2208 kind := value.Kind()
2209 switch kind {
2210 case reflect.Interface, reflect.Ptr:
2211 value = value.Elem()
2212 case reflect.Struct:
2213 break foundStruct
2214 default:
2215 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
2216 }
2217 }
2218 return value
2219}
2220
Paul Duffinf34f6d82020-04-30 15:48:31 +01002221// A container of properties to be optimized.
2222//
2223// Allows additional information to be associated with the properties, e.g. for
2224// filtering.
2225type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002226 fmt.Stringer
2227
Paul Duffinf34f6d82020-04-30 15:48:31 +01002228 // Get the properties that need optimizing.
2229 optimizableProperties() interface{}
2230}
2231
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002232// Extract common properties from a slice of property structures of the same type.
2233//
2234// All the property structures must be of the same type.
2235// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002236// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002237//
2238// Iterates over each exported field (capitalized name) and checks to see whether they
2239// have the same value (using DeepEquals) across all the input properties. If it does not then no
2240// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01002241// and the field in each of the input properties structure is set to its default value. Nested
2242// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002243func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002244 commonPropertiesValue := reflect.ValueOf(commonProperties)
2245 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002246
Paul Duffinf34f6d82020-04-30 15:48:31 +01002247 sliceValue := reflect.ValueOf(inputPropertiesSlice)
2248
Paul Duffinb28369a2020-05-04 15:39:59 +01002249 for _, property := range e.properties {
2250 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01002251 filter := property.filter
2252 if filter == nil {
2253 filter = func(metadata propertiesContainer) bool {
2254 return true
2255 }
2256 }
Paul Duffinb28369a2020-05-04 15:39:59 +01002257
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002258 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002259 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2260 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002261 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002262
Paul Duffin864e1b42020-05-06 10:23:19 +01002263 // Assume that all the values will be the same.
2264 //
2265 // While similar to this is not quite the same as commonValue == nil. If all the values
2266 // have been filtered out then this will be false but commonValue == nil will be true.
2267 valuesDiffer := false
2268
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002269 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002270 container := sliceValue.Index(i).Interface().(propertiesContainer)
2271 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002272 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002273
Paul Duffinc459f892020-04-30 18:08:29 +01002274 if !filter(container) {
2275 expectedValue := property.emptyValue.Interface()
2276 actualValue := fieldValue.Interface()
2277 if !reflect.DeepEqual(expectedValue, actualValue) {
2278 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2279 }
2280 continue
2281 }
2282
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002283 if commonValue == nil {
2284 // Use the first value as the commonProperties value.
2285 commonValue = &fieldValue
2286 } else {
2287 // If the value does not match the current common value then there is
2288 // no value in common so break out.
2289 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2290 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002291 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002292 break
2293 }
2294 }
2295 }
2296
Paul Duffin864e1b42020-05-06 10:23:19 +01002297 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002298 // and set the input struct's field to the empty value.
2299 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002300 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002301 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffinbfdca962022-09-22 16:21:54 +01002302 if !property.keep {
2303 for i := 0; i < sliceValue.Len(); i++ {
2304 container := sliceValue.Index(i).Interface().(propertiesContainer)
2305 itemValue := reflect.ValueOf(container.optimizableProperties())
2306 fieldValue := fieldGetter(itemValue)
2307 fieldValue.Set(emptyValue)
2308 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002309 }
2310 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002311
2312 if valuesDiffer && !property.archVariant {
2313 // The values differ but the property does not support arch variants so it
2314 // is an error.
2315 var details strings.Builder
2316 for i := 0; i < sliceValue.Len(); i++ {
2317 container := sliceValue.Index(i).Interface().(propertiesContainer)
2318 itemValue := reflect.ValueOf(container.optimizableProperties())
2319 fieldValue := fieldGetter(itemValue)
2320
2321 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2322 }
2323
2324 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2325 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002326 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002327
2328 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002329}