blob: 664ab4696be2336186b617b82658ac33fe62e27c [file] [log] [blame]
Jiyong Park9b409bc2019-10-11 14:59:13 +09001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package sdk
16
17import (
Paul Duffinc6ba1822022-05-06 09:38:02 +000018 "bytes"
19 "encoding/json"
Jiyong Park9b409bc2019-10-11 14:59:13 +090020 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000021 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000022 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090023 "strings"
24
Paul Duffin7d74e7b2020-03-06 12:30:13 +000025 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000026 "android/soong/cc"
Colin Crosscb0ac952021-07-20 13:17:15 -070027
Paul Duffin375058f2019-11-29 20:17:53 +000028 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090029 "github.com/google/blueprint/proptools"
30
31 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090032)
33
Paul Duffin64fb5262021-05-05 21:36:04 +010034// Environment variables that affect the generated snapshot
35// ========================================================
36//
Paul Duffin39abf8f2021-09-24 14:58:27 +010037// SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE
38// This allows the target build release (i.e. the release version of the build within which
39// the snapshot will be used) of the snapshot to be specified. If unspecified then it defaults
40// to the current build release version. Otherwise, it must be the name of one of the build
41// releases defined in nameToBuildRelease, e.g. S, T, etc..
42//
43// The generated snapshot must only be used in the specified target release. If the target
44// build release is not the current build release then the generated Android.bp file not be
45// checked for compatibility.
46//
47// e.g. if setting SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE=S will cause the generated snapshot
48// to be compatible with S.
49//
Paul Duffin64fb5262021-05-05 21:36:04 +010050
Jiyong Park9b409bc2019-10-11 14:59:13 +090051var pctx = android.NewPackageContext("android/soong/sdk")
52
Paul Duffin375058f2019-11-29 20:17:53 +000053var (
54 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
55 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000056 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000057 CommandDeps: []string{
58 "${config.Zip2ZipCmd}",
59 },
60 },
61 "destdir")
62
63 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
64 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -070065 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +000066 CommandDeps: []string{
67 "${config.SoongZipCmd}",
68 },
69 Rspfile: "$out.rsp",
70 RspfileContent: "$in",
71 },
72 "basedir")
73
74 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
75 blueprint.RuleParams{
Paul Duffin74f1dcd2022-07-18 13:18:23 +000076 Command: `${config.MergeZipsCmd} -s $out $in`,
Paul Duffin375058f2019-11-29 20:17:53 +000077 CommandDeps: []string{
78 "${config.MergeZipsCmd}",
79 },
80 })
81)
82
Paul Duffin43f7bf02021-05-05 22:00:51 +010083const (
Paul Duffinb01ac4b2022-05-24 20:10:05 +000084 soongSdkSnapshotVersionCurrent = "current"
Paul Duffin43f7bf02021-05-05 22:00:51 +010085)
86
Paul Duffinb645ec82019-11-27 17:43:54 +000087type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090088 content strings.Builder
89 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090090}
91
Paul Duffinb645ec82019-11-27 17:43:54 +000092func (gc *generatedContents) Indent() {
93 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +090094}
95
Paul Duffinb645ec82019-11-27 17:43:54 +000096func (gc *generatedContents) Dedent() {
97 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +090098}
99
Paul Duffina08e4dc2021-06-22 18:19:19 +0100100// IndentedPrintf will add spaces to indent the line to the appropriate level before printing the
101// arguments.
102func (gc *generatedContents) IndentedPrintf(format string, args ...interface{}) {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000103 _, _ = fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100104}
105
106// UnindentedPrintf does not add spaces to indent the line to the appropriate level before printing
107// the arguments.
108func (gc *generatedContents) UnindentedPrintf(format string, args ...interface{}) {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000109 _, _ = fmt.Fprintf(&(gc.content), format, args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900110}
111
Paul Duffin13879572019-11-28 14:31:38 +0000112// Collect all the members.
113//
Paul Duffinb97b1572021-04-29 21:50:40 +0100114// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
115// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000116func (s *sdk) collectMembers(ctx android.ModuleContext) {
117 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000118 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
119 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf7b3d0d2021-09-02 14:29:21 +0100120 if memberTag, ok := tag.(android.SdkMemberDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100121 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900122
Paul Duffin5cca7c42021-05-26 10:16:01 +0100123 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
124 if memberType == nil {
125 return false
126 }
127
Paul Duffin13879572019-11-28 14:31:38 +0000128 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000129 if !memberType.IsInstance(child) {
130 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900131 }
Paul Duffin13879572019-11-28 14:31:38 +0000132
Paul Duffin6a7e9532020-03-20 17:50:07 +0000133 // Keep track of which multilib variants are used by the sdk.
134 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
135
Colin Cross313aa542023-12-13 13:47:44 -0800136 exportedComponentsInfo, _ := android.OtherModuleProvider(ctx, child, android.ExportedComponentsInfoProvider)
Paul Duffinb97b1572021-04-29 21:50:40 +0100137
Paul Duffin5e71e682022-11-23 18:09:54 +0000138 var container android.Module
Paul Duffinc6ba1822022-05-06 09:38:02 +0000139 if parent != ctx.Module() {
Cole Fausted158f42024-03-07 16:41:27 -0800140 container = parent
Paul Duffinc6ba1822022-05-06 09:38:02 +0000141 }
142
Paul Duffin1938dba2022-07-26 23:53:00 +0000143 minApiLevel := android.MinApiLevelForSdkSnapshot(ctx, child)
144
Paul Duffina7208112021-04-23 21:20:20 +0100145 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100146 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
Paul Duffinc6ba1822022-05-06 09:38:02 +0000147 sdkVariant: s,
148 memberType: memberType,
Cole Fausted158f42024-03-07 16:41:27 -0800149 variant: child,
Paul Duffin1938dba2022-07-26 23:53:00 +0000150 minApiLevel: minApiLevel,
Paul Duffinc6ba1822022-05-06 09:38:02 +0000151 container: container,
152 export: export,
153 exportedComponentsInfo: exportedComponentsInfo,
Paul Duffinb97b1572021-04-29 21:50:40 +0100154 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000155
Paul Duffin2d3da312021-05-06 12:02:27 +0100156 // Recurse down into the member's dependencies as it may have dependencies that need to be
157 // automatically added to the sdk.
158 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900159 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000160
161 return false
Paul Duffin13879572019-11-28 14:31:38 +0000162 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000163}
164
Paul Duffincc3132e2021-04-24 01:10:30 +0100165// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
166// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000167//
Paul Duffincc3132e2021-04-24 01:10:30 +0100168// The sdkMember instances are then grouped into slices by member type. Within each such slice the
169// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000170//
Paul Duffincc3132e2021-04-24 01:10:30 +0100171// Finally, the member type slices are concatenated together to form a single slice. The order in
172// which they are concatenated is the order in which the member types were registered in the
173// android.SdkMemberTypesRegistry.
Paul Duffinf861df72022-07-01 15:56:06 +0000174func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, targetBuildRelease *buildRelease, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000175 byType := make(map[android.SdkMemberType][]*sdkMember)
176 byName := make(map[string]*sdkMember)
177
Paul Duffin21827262021-04-24 12:16:36 +0100178 for _, memberVariantDep := range memberVariantDeps {
179 memberType := memberVariantDep.memberType
180 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000181
182 name := ctx.OtherModuleName(variant)
183 member := byName[name]
184 if member == nil {
185 member = &sdkMember{memberType: memberType, name: name}
186 byName[name] = member
187 byType[memberType] = append(byType[memberType], member)
Liz Kammer96320df2022-05-12 20:40:00 -0400188 } else if member.memberType != memberType {
189 // validate whether this is the same member type or and overriding member type
190 if memberType.Overrides(member.memberType) {
191 member.memberType = memberType
192 } else if !member.memberType.Overrides(memberType) {
193 ctx.ModuleErrorf("Incompatible member types %q %q", member.memberType, memberType)
194 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000195 }
196
Paul Duffin1356d8c2020-02-25 19:26:33 +0000197 // Only append new variants to the list. This is needed because a member can be both
198 // exported by the sdk and also be a transitive sdk member.
199 member.variants = appendUniqueVariants(member.variants, variant)
200 }
Paul Duffin13879572019-11-28 14:31:38 +0000201 var members []*sdkMember
Paul Duffin62782de2021-07-14 12:05:16 +0100202 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffinf861df72022-07-01 15:56:06 +0000203 memberType := memberListProperty.memberType
204
205 if !isMemberTypeSupportedByTargetBuildRelease(memberType, targetBuildRelease) {
206 continue
207 }
208
209 membersOfType := byType[memberType]
Paul Duffin13879572019-11-28 14:31:38 +0000210 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900211 }
212
Paul Duffin6a7e9532020-03-20 17:50:07 +0000213 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900214}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900215
Paul Duffinf861df72022-07-01 15:56:06 +0000216// isMemberTypeSupportedByTargetBuildRelease returns true if the member type is supported by the
217// target build release.
218func isMemberTypeSupportedByTargetBuildRelease(memberType android.SdkMemberType, targetBuildRelease *buildRelease) bool {
219 supportedByTargetBuildRelease := true
220 supportedBuildReleases := memberType.SupportedBuildReleases()
221 if supportedBuildReleases == "" {
222 supportedBuildReleases = "S+"
223 }
224
225 set, err := parseBuildReleaseSet(supportedBuildReleases)
226 if err != nil {
227 panic(fmt.Errorf("member type %s has invalid supported build releases %q: %s",
228 memberType.SdkPropertyName(), supportedBuildReleases, err))
229 }
230 if !set.contains(targetBuildRelease) {
231 supportedByTargetBuildRelease = false
232 }
233 return supportedByTargetBuildRelease
234}
235
Paul Duffin5e71e682022-11-23 18:09:54 +0000236func appendUniqueVariants(variants []android.Module, newVariant android.Module) []android.Module {
Paul Duffin72910952020-01-20 18:16:30 +0000237 for _, v := range variants {
238 if v == newVariant {
239 return variants
240 }
241 }
242 return append(variants, newVariant)
243}
244
Paul Duffin51509a12022-04-06 12:48:09 +0000245// BUILD_NUMBER_FILE is the name of the file in the snapshot zip that will contain the number of
246// the build from which the snapshot was produced.
247const BUILD_NUMBER_FILE = "snapshot-creation-build-number.txt"
248
Jiyong Park73c54ee2019-10-22 20:31:18 +0900249// SDK directory structure
250// <sdk_root>/
251// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
252// <api_ver>/ : below this directory are all auto-generated
253// Android.bp : definition of 'sdk_snapshot' module is here
254// aidl/
255// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
256// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900257// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900258// include/
259// bionic/libc/include/stdlib.h : an exported header file
260// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900261// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900262// <arch>/include/ : arch-specific exported headers
263// <arch>/include_gen/ : arch-specific generated headers
264// <arch>/lib/
265// libFoo.so : a stub library
266
Paul Duffin1938dba2022-07-26 23:53:00 +0000267func (s sdk) targetBuildRelease(ctx android.ModuleContext) *buildRelease {
268 config := ctx.Config()
269 targetBuildReleaseEnv := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE", buildReleaseCurrent.name)
270 targetBuildRelease, err := nameToRelease(targetBuildReleaseEnv)
271 if err != nil {
272 ctx.ModuleErrorf("invalid SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE: %s", err)
273 targetBuildRelease = buildReleaseCurrent
274 }
275
276 return targetBuildRelease
277}
278
Jiyong Park232e7852019-11-04 12:23:40 +0900279// buildSnapshot is the main function in this source file. It creates rules to copy
280// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffinc6ba1822022-05-06 09:38:02 +0000281func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000282
Paul Duffin1938dba2022-07-26 23:53:00 +0000283 targetBuildRelease := s.targetBuildRelease(ctx)
284 targetApiLevel, err := android.ApiLevelFromUser(ctx, targetBuildRelease.name)
285 if err != nil {
286 targetApiLevel = android.FutureApiLevel
287 }
288
Paul Duffinb97b1572021-04-29 21:50:40 +0100289 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100290 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100291 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000292 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100293 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100294 }
Paul Duffin865171e2020-03-02 18:38:15 +0000295
Paul Duffinb97b1572021-04-29 21:50:40 +0100296 // Filter out any sdkMemberVariantDep that is a component of another.
297 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000298
Paul Duffin1938dba2022-07-26 23:53:00 +0000299 // Record the names of all the members, both explicitly specified and implicitly included. Also,
300 // record the names of any members that should be excluded from this snapshot.
Paul Duffinb97b1572021-04-29 21:50:40 +0100301 allMembersByName := make(map[string]struct{})
302 exportedMembersByName := make(map[string]struct{})
Paul Duffin1938dba2022-07-26 23:53:00 +0000303 excludedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100304
Paul Duffin1938dba2022-07-26 23:53:00 +0000305 addMember := func(name string, export bool, exclude bool) {
306 if exclude {
307 excludedMembersByName[name] = struct{}{}
308 return
309 }
310
Paul Duffinb97b1572021-04-29 21:50:40 +0100311 allMembersByName[name] = struct{}{}
312 if export {
313 exportedMembersByName[name] = struct{}{}
314 }
315 }
316
317 for _, memberVariantDep := range memberVariantDeps {
318 name := memberVariantDep.variant.Name()
319 export := memberVariantDep.export
320
Paul Duffin1938dba2022-07-26 23:53:00 +0000321 // If the minApiLevel of the member is greater than the target API level then exclude it from
322 // this snapshot.
323 exclude := memberVariantDep.minApiLevel.GreaterThan(targetApiLevel)
Spandan Dasb84dbb22023-03-08 22:06:35 +0000324 // Always include host variants (e.g. host tools) in the snapshot.
325 // Host variants should not be guarded by a min_sdk_version check. In fact, host variants
326 // do not have a `min_sdk_version`.
327 if memberVariantDep.Host() {
328 exclude = false
329 }
Paul Duffin1938dba2022-07-26 23:53:00 +0000330
331 addMember(name, export, exclude)
Paul Duffinb97b1572021-04-29 21:50:40 +0100332
333 // Add any components provided by the module.
334 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
Paul Duffin1938dba2022-07-26 23:53:00 +0000335 addMember(component, export, exclude)
Paul Duffinb97b1572021-04-29 21:50:40 +0100336 }
337
338 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
339 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000340 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000341 }
342
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000343 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900344
Cole Fausted158f42024-03-07 16:41:27 -0800345 bp := android.PathForModuleOut(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000346
347 bpFile := &bpFile{
348 modules: make(map[string]*bpModule),
349 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000350
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000351 // Always add -current to the end
352 snapshotFileSuffix := "-current"
Paul Duffin43f7bf02021-05-05 22:00:51 +0100353
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000354 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000355 ctx: ctx,
356 sdk: s,
Paul Duffin13f02712020-03-06 12:30:43 +0000357 snapshotDir: snapshotDir.OutputPath,
358 copies: make(map[string]string),
Cole Fausted158f42024-03-07 16:41:27 -0800359 filesToZip: []android.Path{bp},
Paul Duffin13f02712020-03-06 12:30:43 +0000360 bpFile: bpFile,
361 prebuiltModules: make(map[string]*bpModule),
362 allMembersByName: allMembersByName,
363 exportedMembersByName: exportedMembersByName,
Paul Duffin1938dba2022-07-26 23:53:00 +0000364 excludedMembersByName: excludedMembersByName,
Paul Duffin39abf8f2021-09-24 14:58:27 +0100365 targetBuildRelease: targetBuildRelease,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900366 }
Paul Duffinac37c502019-11-26 18:02:20 +0000367 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900368
Paul Duffin62131702021-05-07 01:10:01 +0100369 // If the sdk snapshot includes any license modules then add a package module which has a
370 // default_applicable_licenses property. That will prevent the LSC license process from updating
371 // the generated Android.bp file to add a package module that includes all licenses used by all
372 // the modules in that package. That would be unnecessary as every module in the sdk should have
373 // their own licenses property specified.
374 if hasLicenses {
375 pkg := bpFile.newModule("package")
376 property := "default_applicable_licenses"
377 pkg.AddCommentForProperty(property, `
378A default list here prevents the license LSC from adding its own list which would
379be unnecessary as every module in the sdk already has its own licenses property.
380`)
381 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
382 bpFile.AddModule(pkg)
383 }
384
Paul Duffin0df49682021-05-07 01:10:01 +0100385 // Group the variants for each member module together and then group the members of each member
386 // type together.
Paul Duffinf861df72022-07-01 15:56:06 +0000387 members := s.groupMemberVariantsByMemberThenType(ctx, targetBuildRelease, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100388
389 // Create the prebuilt modules for each of the member modules.
Paul Duffind19f8942021-07-14 12:08:37 +0100390 traits := s.gatherTraits()
Paul Duffin13ad94f2020-02-19 16:19:27 +0000391 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000392 memberType := member.memberType
Paul Duffin4e7d1c42022-05-13 13:12:19 +0000393 if !memberType.ArePrebuiltsRequired() {
394 continue
395 }
Paul Duffin3a4eb502020-03-19 16:11:18 +0000396
Paul Duffind19f8942021-07-14 12:08:37 +0100397 name := member.name
Paul Duffin1938dba2022-07-26 23:53:00 +0000398 if _, ok := excludedMembersByName[name]; ok {
399 continue
400 }
401
Paul Duffind19f8942021-07-14 12:08:37 +0100402 requiredTraits := traits[name]
403 if requiredTraits == nil {
404 requiredTraits = android.EmptySdkMemberTraitSet()
405 }
406
407 // Create the snapshot for the member.
408 memberCtx := &memberContext{ctx, builder, memberType, name, requiredTraits}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000409
410 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100411 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900412 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900413
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000414 // Create a transformer that will transform a module by replacing any references
Paul Duffin72910952020-01-20 18:16:30 +0000415 // to internal members with a unique module name and setting prefer: false.
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000416 snapshotTransformer := snapshotTransformation{
Paul Duffin64fb5262021-05-05 21:36:04 +0100417 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100418 }
Paul Duffin72910952020-01-20 18:16:30 +0000419
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000420 for _, module := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000421 // Prune any empty property sets.
Sam Delmerico35881362023-06-30 14:40:10 -0400422 module = transformModule(module, pruneEmptySetTransformer{})
Paul Duffina78f3a72020-02-21 16:29:35 +0000423
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000424 // Transform the module module to make it suitable for use in the snapshot.
Sam Delmerico35881362023-06-30 14:40:10 -0400425 module = transformModule(module, snapshotTransformer)
426 module = transformModule(module, emptyClasspathContentsTransformation{})
427 if module != nil {
428 bpFile.AddModule(module)
429 }
Paul Duffin43f7bf02021-05-05 22:00:51 +0100430 }
Paul Duffin26197a62021-04-24 00:34:10 +0100431
432 // generate Android.bp
Cole Fausted158f42024-03-07 16:41:27 -0800433 contents := generateBpContents(bpFile)
Paul Duffin39abf8f2021-09-24 14:58:27 +0100434 // If the snapshot is being generated for the current build release then check the syntax to make
435 // sure that it is compatible.
Paul Duffin42a49f12022-08-17 22:09:55 +0000436 if targetBuildRelease == buildReleaseCurrent {
Paul Duffin39abf8f2021-09-24 14:58:27 +0100437 syntaxCheckSnapshotBpFile(ctx, contents)
438 }
Paul Duffin26197a62021-04-24 00:34:10 +0100439
Cole Fausted158f42024-03-07 16:41:27 -0800440 android.WriteFileRuleVerbatim(ctx, bp, contents)
Paul Duffin26197a62021-04-24 00:34:10 +0100441
Paul Duffin51509a12022-04-06 12:48:09 +0000442 // Copy the build number file into the snapshot.
443 builder.CopyToSnapshot(ctx.Config().BuildNumberFile(ctx), BUILD_NUMBER_FILE)
444
Paul Duffin74f1dcd2022-07-18 13:18:23 +0000445 filesToZip := android.SortedUniquePaths(builder.filesToZip)
Paul Duffin26197a62021-04-24 00:34:10 +0100446
447 // zip them all
Paul Duffinc6ba1822022-05-06 09:38:02 +0000448 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100449 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100450 outputDesc := "Building snapshot for " + ctx.ModuleName()
451
452 // If there are no zips to merge then generate the output zip directly.
453 // Otherwise, generate an intermediate zip file into which other zips can be
454 // merged.
455 var zipFile android.OutputPath
456 var desc string
457 if len(builder.zipsToMerge) == 0 {
458 zipFile = outputZipFile
459 desc = outputDesc
460 } else {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000461 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100462 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100463 desc = "Building intermediate snapshot for " + ctx.ModuleName()
464 }
465
466 ctx.Build(pctx, android.BuildParams{
467 Description: desc,
468 Rule: zipFiles,
469 Inputs: filesToZip,
470 Output: zipFile,
471 Args: map[string]string{
472 "basedir": builder.snapshotDir.String(),
473 },
474 })
475
476 if len(builder.zipsToMerge) != 0 {
477 ctx.Build(pctx, android.BuildParams{
478 Description: outputDesc,
479 Rule: mergeZips,
480 Input: zipFile,
Paul Duffin74f1dcd2022-07-18 13:18:23 +0000481 Inputs: android.SortedUniquePaths(builder.zipsToMerge),
Paul Duffin26197a62021-04-24 00:34:10 +0100482 Output: outputZipFile,
483 })
484 }
485
Paul Duffinc6ba1822022-05-06 09:38:02 +0000486 modules := s.generateInfoData(ctx, memberVariantDeps)
487
488 // Output the modules information as pretty printed JSON.
Cole Fausted158f42024-03-07 16:41:27 -0800489 info := android.PathForModuleOut(ctx, fmt.Sprintf("%s%s.info", ctx.ModuleName(), snapshotFileSuffix))
Paul Duffinc6ba1822022-05-06 09:38:02 +0000490 output, err := json.MarshalIndent(modules, "", " ")
491 if err != nil {
492 ctx.ModuleErrorf("error generating %q: %s", info, err)
493 }
494 builder.infoContents = string(output)
Cole Fausted158f42024-03-07 16:41:27 -0800495 android.WriteFileRuleVerbatim(ctx, info, builder.infoContents)
496 installedInfo := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), info.Base(), info)
Paul Duffinc6ba1822022-05-06 09:38:02 +0000497 s.infoFile = android.OptionalPathForPath(installedInfo)
498
499 // Install the zip, making sure that the info file has been installed as well.
500 installedZip := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), outputZipFile.Base(), outputZipFile, installedInfo)
501 s.snapshotFile = android.OptionalPathForPath(installedZip)
502}
503
504type moduleInfo struct {
505 // The type of the module, e.g. java_sdk_library
506 moduleType string
507 // The name of the module.
508 name string
509 // A list of additional dependencies of the module.
510 deps []string
Paul Duffin958806b2022-05-16 13:10:47 +0000511 // Additional member specific properties.
512 // These will be added into the generated JSON alongside the above properties.
513 memberSpecific map[string]interface{}
Paul Duffinc6ba1822022-05-06 09:38:02 +0000514}
515
516func (m *moduleInfo) MarshalJSON() ([]byte, error) {
517 buffer := bytes.Buffer{}
518
519 separator := ""
520 writeObjectPair := func(key string, value interface{}) {
521 buffer.WriteString(fmt.Sprintf("%s%q: ", separator, key))
522 b, err := json.Marshal(value)
523 if err != nil {
524 panic(err)
525 }
526 buffer.Write(b)
527 separator = ","
528 }
529
530 buffer.WriteString("{")
531 writeObjectPair("@type", m.moduleType)
532 writeObjectPair("@name", m.name)
533 if m.deps != nil {
534 writeObjectPair("@deps", m.deps)
535 }
Cole Faust18994c72023-02-28 16:02:16 -0800536 for _, k := range android.SortedKeys(m.memberSpecific) {
Paul Duffin958806b2022-05-16 13:10:47 +0000537 v := m.memberSpecific[k]
Paul Duffinc6ba1822022-05-06 09:38:02 +0000538 writeObjectPair(k, v)
539 }
540 buffer.WriteString("}")
541 return buffer.Bytes(), nil
542}
543
544var _ json.Marshaler = (*moduleInfo)(nil)
545
546// generateInfoData creates a list of moduleInfo structures that will be marshalled into JSON.
547func (s *sdk) generateInfoData(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) interface{} {
548 modules := []*moduleInfo{}
549 sdkInfo := moduleInfo{
Paul Duffin958806b2022-05-16 13:10:47 +0000550 moduleType: "sdk",
551 name: ctx.ModuleName(),
552 memberSpecific: map[string]interface{}{},
Paul Duffinc6ba1822022-05-06 09:38:02 +0000553 }
554 modules = append(modules, &sdkInfo)
555
556 name2Info := map[string]*moduleInfo{}
557 getModuleInfo := func(module android.Module) *moduleInfo {
558 name := module.Name()
559 info := name2Info[name]
560 if info == nil {
561 moduleType := ctx.OtherModuleType(module)
562 // Remove any suffix added when creating modules dynamically.
563 moduleType = strings.Split(moduleType, "__")[0]
564 info = &moduleInfo{
565 moduleType: moduleType,
566 name: name,
567 }
Paul Duffin958806b2022-05-16 13:10:47 +0000568
Colin Cross313aa542023-12-13 13:47:44 -0800569 additionalSdkInfo, _ := android.OtherModuleProvider(ctx, module, android.AdditionalSdkInfoProvider)
Paul Duffin958806b2022-05-16 13:10:47 +0000570 info.memberSpecific = additionalSdkInfo.Properties
571
Paul Duffinc6ba1822022-05-06 09:38:02 +0000572 name2Info[name] = info
573 }
574 return info
575 }
576
577 for _, memberVariantDep := range memberVariantDeps {
578 propertyName := memberVariantDep.memberType.SdkPropertyName()
579 var list []string
Paul Duffin958806b2022-05-16 13:10:47 +0000580 if v, ok := sdkInfo.memberSpecific[propertyName]; ok {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000581 list = v.([]string)
582 }
583
584 memberName := memberVariantDep.variant.Name()
585 list = append(list, memberName)
Paul Duffin958806b2022-05-16 13:10:47 +0000586 sdkInfo.memberSpecific[propertyName] = android.SortedUniqueStrings(list)
Paul Duffinc6ba1822022-05-06 09:38:02 +0000587
588 if memberVariantDep.container != nil {
589 containerInfo := getModuleInfo(memberVariantDep.container)
590 containerInfo.deps = android.SortedUniqueStrings(append(containerInfo.deps, memberName))
591 }
592
593 // Make sure that the module info is created for each module.
594 getModuleInfo(memberVariantDep.variant)
595 }
596
Cole Faust18994c72023-02-28 16:02:16 -0800597 for _, memberName := range android.SortedKeys(name2Info) {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000598 info := name2Info[memberName]
599 modules = append(modules, info)
600 }
601
602 return modules
Paul Duffin26197a62021-04-24 00:34:10 +0100603}
604
Paul Duffinb97b1572021-04-29 21:50:40 +0100605// filterOutComponents removes any item from the deps list that is a component of another item in
606// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
607// then it will remove "foo.stubs" from the deps.
608func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
609 // Collate the set of components that all the modules added to the sdk provide.
610 components := map[string]*sdkMemberVariantDep{}
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000611 for i := range deps {
Paul Duffinb97b1572021-04-29 21:50:40 +0100612 dep := &deps[i]
613 for _, c := range dep.exportedComponentsInfo.Components {
614 components[c] = dep
615 }
616 }
617
618 // If no module provides components then return the input deps unfiltered.
619 if len(components) == 0 {
620 return deps
621 }
622
623 filtered := make([]sdkMemberVariantDep, 0, len(deps))
624 for _, dep := range deps {
625 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
626 if owner, ok := components[name]; ok {
627 // This is a component of another module that is a member of the sdk.
628
629 // If the component is exported but the owning module is not then the configuration is not
630 // supported.
631 if dep.export && !owner.export {
632 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
633 continue
634 }
635
636 // This module must not be added to the list of members of the sdk as that would result in a
637 // duplicate module in the sdk snapshot.
638 continue
639 }
640
641 filtered = append(filtered, dep)
642 }
643 return filtered
644}
645
Paul Duffinf88d8e02020-05-07 20:21:34 +0100646// Check the syntax of the generated Android.bp file contents and if they are
647// invalid then log an error with the contents (tagged with line numbers) and the
648// errors that were found so that it is easy to see where the problem lies.
649func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
650 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
651 if len(errs) != 0 {
652 message := &strings.Builder{}
653 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
654
655Generated Android.bp contents
656========================================================================
657`)
658 for i, line := range strings.Split(contents, "\n") {
659 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
660 }
661
662 _, _ = fmt.Fprint(message, `
663========================================================================
664
665Errors found:
666`)
667
668 for _, err := range errs {
669 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
670 }
671
672 ctx.ModuleErrorf("%s", message.String())
673 }
674}
675
Paul Duffin4b8b7932020-05-06 12:35:38 +0100676func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
677 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
678 if err != nil {
679 ctx.ModuleErrorf("error extracting common properties: %s", err)
680 }
681}
682
Paul Duffinfbe470e2021-04-24 12:37:13 +0100683// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
684type snapshotModuleStaticProperties struct {
685 Compile_multilib string `android:"arch_variant"`
686}
687
Paul Duffin2d1bb892021-04-24 11:32:59 +0100688// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
689type combinedSnapshotModuleProperties struct {
690 // The sdk variant from which this information was collected.
691 sdkVariant *sdk
692
693 // Static snapshot module properties.
694 staticProperties *snapshotModuleStaticProperties
695
696 // The dynamically generated member list properties.
697 dynamicProperties interface{}
698}
699
700// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100701func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
702 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100703 var list []*combinedSnapshotModuleProperties
704 for _, sdkVariant := range sdkVariants {
705 staticProperties := &snapshotModuleStaticProperties{
706 Compile_multilib: sdkVariant.multilibUsages.String(),
707 }
Paul Duffin62782de2021-07-14 12:05:16 +0100708 dynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100709
Paul Duffincd064672021-04-24 00:47:29 +0100710 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100711 sdkVariant: sdkVariant,
712 staticProperties: staticProperties,
713 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100714 }
715 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
716
717 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100718 }
Paul Duffincd064672021-04-24 00:47:29 +0100719
720 for _, memberVariantDep := range memberVariantDeps {
721 // If the member dependency is internal then do not add the dependency to the snapshot member
722 // list properties.
723 if !memberVariantDep.export {
724 continue
725 }
726
727 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin62782de2021-07-14 12:05:16 +0100728 memberListProperty := s.memberTypeListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100729 memberName := ctx.OtherModuleName(memberVariantDep.variant)
730
Paul Duffin13082052021-05-11 00:31:38 +0100731 if memberListProperty.getter == nil {
732 continue
733 }
734
Paul Duffincd064672021-04-24 00:47:29 +0100735 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100736 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100737 if !android.InList(memberName, memberList) {
738 memberList = append(memberList, memberName)
739 }
Paul Duffin13082052021-05-11 00:31:38 +0100740 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100741 }
742
Paul Duffin2d1bb892021-04-24 11:32:59 +0100743 return list
744}
745
746func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
747
748 // Extract the dynamic properties and add them to a list of propertiesContainer.
749 propertyContainers := []propertiesContainer{}
750 for _, i := range list {
751 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
752 sdkVariant: i.sdkVariant,
753 properties: i.dynamicProperties,
754 })
755 }
756
757 // Extract the common members, removing them from the original properties.
Paul Duffin62782de2021-07-14 12:05:16 +0100758 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100759 extractor := newCommonValueExtractor(commonDynamicProperties)
760 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
761
762 // Extract the static properties and add them to a list of propertiesContainer.
763 propertyContainers = []propertiesContainer{}
764 for _, i := range list {
765 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
766 sdkVariant: i.sdkVariant,
767 properties: i.staticProperties,
768 })
769 }
770
771 commonStaticProperties := &snapshotModuleStaticProperties{}
772 extractor = newCommonValueExtractor(commonStaticProperties)
773 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
774
775 return &combinedSnapshotModuleProperties{
776 sdkVariant: nil,
777 staticProperties: commonStaticProperties,
778 dynamicProperties: commonDynamicProperties,
779 }
780}
781
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000782type propertyTag struct {
783 name string
784}
785
Paul Duffin94289702021-09-09 15:38:32 +0100786var _ android.BpPropertyTag = propertyTag{}
787
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000788// BpPropertyTag instances to add to a property that contains references to other sdk members.
Paul Duffin0cb37b92020-03-04 14:52:46 +0000789//
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000790// These will ensure that the referenced modules are available, if required.
Paul Duffin13f02712020-03-06 12:30:43 +0000791var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000792var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000793
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000794type snapshotTransformation struct {
Paul Duffine6c0d842020-01-15 14:08:51 +0000795 identityTransformation
796 builder *snapshotBuilder
797}
798
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000799func (t snapshotTransformation) transformModule(module *bpModule) *bpModule {
Sam Delmerico35881362023-06-30 14:40:10 -0400800 if module != nil {
801 // If the module is an internal member then use a unique name for it.
802 name := module.Name()
803 module.setProperty("name", t.builder.snapshotSdkMemberName(name, true))
804 }
Paul Duffin72910952020-01-20 18:16:30 +0000805 return module
806}
807
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000808func (t snapshotTransformation) transformProperty(_ string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000809 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
810 required := tag == requiredSdkMemberReferencePropertyTag
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000811 return t.builder.snapshotSdkMemberNames(value.([]string), required), tag
Paul Duffin72910952020-01-20 18:16:30 +0000812 } else {
813 return value, tag
814 }
815}
816
Sam Delmerico35881362023-06-30 14:40:10 -0400817type emptyClasspathContentsTransformation struct {
818 identityTransformation
819}
820
821func (t emptyClasspathContentsTransformation) transformModule(module *bpModule) *bpModule {
822 classpathModuleTypes := []string{
823 "prebuilt_bootclasspath_fragment",
824 "prebuilt_systemserverclasspath_fragment",
825 }
826 if module != nil && android.InList(module.moduleType, classpathModuleTypes) {
827 if contents, ok := module.bpPropertySet.properties["contents"].([]string); ok {
828 if len(contents) == 0 {
829 return nil
830 }
831 }
832 }
833 return module
834}
835
Paul Duffina78f3a72020-02-21 16:29:35 +0000836type pruneEmptySetTransformer struct {
837 identityTransformation
838}
839
840var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
841
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000842func (t pruneEmptySetTransformer) transformPropertySetAfterContents(_ string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
Paul Duffina78f3a72020-02-21 16:29:35 +0000843 if len(propertySet.properties) == 0 {
844 return nil, nil
845 } else {
846 return propertySet, tag
847 }
848}
849
Cole Fausted158f42024-03-07 16:41:27 -0800850func generateBpContents(bpFile *bpFile) string {
851 contents := &generatedContents{}
Paul Duffina08e4dc2021-06-22 18:19:19 +0100852 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000853 for _, bpModule := range bpFile.order {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000854 contents.IndentedPrintf("\n")
855 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
856 outputPropertySet(contents, bpModule.bpPropertySet)
857 contents.IndentedPrintf("}\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000858 }
Cole Fausted158f42024-03-07 16:41:27 -0800859 return contents.content.String()
Paul Duffinb645ec82019-11-27 17:43:54 +0000860}
861
862func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
863 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000864
Paul Duffin0df49682021-05-07 01:10:01 +0100865 addComment := func(name string) {
866 if text, ok := set.comments[name]; ok {
867 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100868 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100869 }
870 }
871 }
872
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000873 // Output the properties first, followed by the nested sets. This ensures a
874 // consistent output irrespective of whether property sets are created before
875 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000876 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000877 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000878
Paul Duffin0df49682021-05-07 01:10:01 +0100879 // Do not write property sets in the properties phase.
880 if _, ok := value.(*bpPropertySet); ok {
881 continue
882 }
883
884 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100885 reflectValue := reflect.ValueOf(value)
886 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000887 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000888
889 for _, name := range set.order {
890 value := set.getValue(name)
891
892 // Only write property sets in the sets phase.
893 switch v := value.(type) {
894 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100895 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100896 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000897 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100898 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000899 }
900 }
901
Paul Duffinb645ec82019-11-27 17:43:54 +0000902 contents.Dedent()
903}
904
Paul Duffina08e4dc2021-06-22 18:19:19 +0100905// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
906// by the value and then followed by a , and a newline.
907func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
908 contents.IndentedPrintf("%s: ", name)
909 outputUnnamedValue(contents, value)
910 contents.UnindentedPrintf(",\n")
911}
912
913// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
914// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
915// indented and all but the last line will end with a newline.
916func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
917 valueType := value.Type()
918 switch valueType.Kind() {
919 case reflect.Bool:
920 contents.UnindentedPrintf("%t", value.Bool())
921
922 case reflect.String:
923 contents.UnindentedPrintf("%q", value)
924
Paul Duffin51227d82021-05-18 12:54:27 +0100925 case reflect.Ptr:
926 outputUnnamedValue(contents, value.Elem())
927
Paul Duffina08e4dc2021-06-22 18:19:19 +0100928 case reflect.Slice:
929 length := value.Len()
930 if length == 0 {
931 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100932 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100933 firstValue := value.Index(0)
934 if length == 1 && !multiLineValue(firstValue) {
935 contents.UnindentedPrintf("[")
936 outputUnnamedValue(contents, firstValue)
937 contents.UnindentedPrintf("]")
938 } else {
939 contents.UnindentedPrintf("[\n")
940 contents.Indent()
941 for i := 0; i < length; i++ {
942 itemValue := value.Index(i)
943 contents.IndentedPrintf("")
944 outputUnnamedValue(contents, itemValue)
945 contents.UnindentedPrintf(",\n")
946 }
947 contents.Dedent()
948 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100949 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100950 }
951
Paul Duffin51227d82021-05-18 12:54:27 +0100952 case reflect.Struct:
953 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
954 v := value.Interface()
955 if _, ok := v.(android.BpPrintable); !ok {
956 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
957 }
958 contents.UnindentedPrintf("{\n")
959 contents.Indent()
960 for f := 0; f < valueType.NumField(); f++ {
961 fieldType := valueType.Field(f)
962 if fieldType.Anonymous {
963 continue
964 }
965 fieldValue := value.Field(f)
966 fieldName := fieldType.Name
967 propertyName := proptools.PropertyNameForField(fieldName)
968 outputNamedValue(contents, propertyName, fieldValue)
969 }
970 contents.Dedent()
971 contents.IndentedPrintf("}")
972
Paul Duffina08e4dc2021-06-22 18:19:19 +0100973 default:
974 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
975 }
976}
977
Paul Duffin51227d82021-05-18 12:54:27 +0100978// multiLineValue returns true if the supplied value may require multiple lines in the output.
979func multiLineValue(value reflect.Value) bool {
980 kind := value.Kind()
981 return kind == reflect.Slice || kind == reflect.Struct
982}
983
Paul Duffinac37c502019-11-26 18:02:20 +0000984func (s *sdk) GetAndroidBpContentsForTests() string {
Cole Fausted158f42024-03-07 16:41:27 -0800985 return generateBpContents(s.builderForTests.bpFile)
Paul Duffinac37c502019-11-26 18:02:20 +0000986}
987
Paul Duffinc6ba1822022-05-06 09:38:02 +0000988func (s *sdk) GetInfoContentsForTests() string {
989 return s.builderForTests.infoContents
990}
991
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000992type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100993 ctx android.ModuleContext
994 sdk *sdk
995
Paul Duffinb645ec82019-11-27 17:43:54 +0000996 snapshotDir android.OutputPath
997 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000998
999 // Map from destination to source of each copy - used to eliminate duplicates and
1000 // detect conflicts.
1001 copies map[string]string
1002
Paul Duffinb645ec82019-11-27 17:43:54 +00001003 filesToZip android.Paths
1004 zipsToMerge android.Paths
1005
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001006 // The path to an empty file.
1007 emptyFile android.WritablePath
1008
Paul Duffinb645ec82019-11-27 17:43:54 +00001009 prebuiltModules map[string]*bpModule
1010 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001011
1012 // The set of all members by name.
1013 allMembersByName map[string]struct{}
1014
1015 // The set of exported members by name.
1016 exportedMembersByName map[string]struct{}
Paul Duffin39abf8f2021-09-24 14:58:27 +01001017
Paul Duffin1938dba2022-07-26 23:53:00 +00001018 // The set of members which have been excluded from this snapshot; by name.
1019 excludedMembersByName map[string]struct{}
1020
Paul Duffin39abf8f2021-09-24 14:58:27 +01001021 // The target build release for which the snapshot is to be generated.
1022 targetBuildRelease *buildRelease
Paul Duffinc6ba1822022-05-06 09:38:02 +00001023
Paul Duffin958806b2022-05-16 13:10:47 +00001024 // The contents of the .info file that describes the sdk contents.
Paul Duffinc6ba1822022-05-06 09:38:02 +00001025 infoContents string
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001026}
1027
1028func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001029 if existing, ok := s.copies[dest]; ok {
1030 if existing != src.String() {
1031 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1032 return
1033 }
1034 } else {
1035 path := s.snapshotDir.Join(s.ctx, dest)
1036 s.ctx.Build(pctx, android.BuildParams{
1037 Rule: android.Cp,
1038 Input: src,
1039 Output: path,
1040 })
1041 s.filesToZip = append(s.filesToZip, path)
1042
1043 s.copies[dest] = src.String()
1044 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001045}
1046
Paul Duffin91547182019-11-12 19:39:36 +00001047func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1048 ctx := s.ctx
1049
1050 // Repackage the zip file so that the entries are in the destDir directory.
1051 // This will allow the zip file to be merged into the snapshot.
1052 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001053
1054 ctx.Build(pctx, android.BuildParams{
1055 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1056 Rule: repackageZip,
1057 Input: zipPath,
1058 Output: tmpZipPath,
1059 Args: map[string]string{
1060 "destdir": destDir,
1061 },
1062 })
Paul Duffin91547182019-11-12 19:39:36 +00001063
1064 // Add the repackaged zip file to the files to merge.
1065 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1066}
1067
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001068func (s *snapshotBuilder) EmptyFile() android.Path {
1069 if s.emptyFile == nil {
1070 ctx := s.ctx
1071 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1072 s.ctx.Build(pctx, android.BuildParams{
1073 Rule: android.Touch,
1074 Output: s.emptyFile,
1075 })
1076 }
1077
1078 return s.emptyFile
1079}
1080
Paul Duffin9d8d6092019-12-05 18:19:29 +00001081func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1082 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001083 if s.prebuiltModules[name] != nil {
1084 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1085 }
1086
1087 m := s.bpFile.newModule(moduleType)
1088 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001089
Paul Duffinbefa4b92020-03-04 14:22:45 +00001090 variant := member.Variants()[0]
1091
Paul Duffin13f02712020-03-06 12:30:43 +00001092 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001093 // An internal member is only referenced from the sdk snapshot which is in the
1094 // same package so can be marked as private.
1095 m.AddProperty("visibility", []string{"//visibility:private"})
1096 } else {
1097 // Extract visibility information from a member variant. All variants have the same
1098 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001099 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1100
1101 // Add any additional visibility rules needed for the prebuilts to reference each other.
1102 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1103 if err != nil {
1104 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1105 }
1106
1107 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001108 if len(visibility) != 0 {
1109 m.AddProperty("visibility", visibility)
1110 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001111 }
1112
Martin Stjernholm1e041092020-11-03 00:11:09 +00001113 // Where available copy apex_available properties from the member.
1114 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1115 apexAvailable := apexAware.ApexAvailable()
1116 if len(apexAvailable) == 0 {
1117 // //apex_available:platform is the default.
1118 apexAvailable = []string{android.AvailableToPlatform}
1119 }
1120
1121 // Add in any baseline apex available settings.
1122 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1123
1124 // Remove duplicates and sort.
1125 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1126 sort.Strings(apexAvailable)
1127
1128 m.AddProperty("apex_available", apexAvailable)
1129 }
1130
Paul Duffinb0bb3762021-05-06 16:48:05 +01001131 // The licenses are the same for all variants.
1132 mctx := s.ctx
Colin Cross313aa542023-12-13 13:47:44 -08001133 licenseInfo, _ := android.OtherModuleProvider(mctx, variant, android.LicenseInfoProvider)
Paul Duffinb0bb3762021-05-06 16:48:05 +01001134 if len(licenseInfo.Licenses) > 0 {
1135 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1136 }
1137
Paul Duffin865171e2020-03-02 18:38:15 +00001138 deviceSupported := false
1139 hostSupported := false
1140
1141 for _, variant := range member.Variants() {
1142 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001143 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001144 hostSupported = true
1145 } else if osClass == android.Device {
1146 deviceSupported = true
1147 }
1148 }
1149
1150 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001151
1152 s.prebuiltModules[name] = m
1153 s.prebuiltOrder = append(s.prebuiltOrder, m)
1154 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001155}
1156
Paul Duffin865171e2020-03-02 18:38:15 +00001157func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001158 // If neither device or host is supported then this module does not support either so will not
1159 // recognize the properties.
1160 if !deviceSupported && !hostSupported {
1161 return
1162 }
1163
Paul Duffin865171e2020-03-02 18:38:15 +00001164 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001165 bpModule.AddProperty("device_supported", false)
1166 }
Paul Duffin865171e2020-03-02 18:38:15 +00001167 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001168 bpModule.AddProperty("host_supported", true)
1169 }
1170}
1171
Paul Duffin13f02712020-03-06 12:30:43 +00001172func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1173 if required {
1174 return requiredSdkMemberReferencePropertyTag
1175 } else {
1176 return optionalSdkMemberReferencePropertyTag
1177 }
1178}
1179
1180func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1181 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001182}
1183
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001184// Get a name for sdk snapshot member. If the member is private then generate a snapshot specific
1185// name. As part of the processing this checks to make sure that any required members are part of
1186// the snapshot.
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001187func (s *snapshotBuilder) snapshotSdkMemberName(name string, required bool) string {
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001188 if _, ok := s.allMembersByName[name]; !ok {
Paul Duffin13f02712020-03-06 12:30:43 +00001189 if required {
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001190 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", name)
Paul Duffin13f02712020-03-06 12:30:43 +00001191 }
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001192 return name
Paul Duffin13f02712020-03-06 12:30:43 +00001193 }
1194
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001195 if s.isInternalMember(name) {
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001196 return s.ctx.ModuleName() + "_" + name
Paul Duffin72910952020-01-20 18:16:30 +00001197 } else {
Paul Duffin7ed6ff82022-11-21 10:57:30 +00001198 return name
Paul Duffin72910952020-01-20 18:16:30 +00001199 }
1200}
1201
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001202func (s *snapshotBuilder) snapshotSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001203 var references []string = nil
1204 for _, m := range members {
Paul Duffin1938dba2022-07-26 23:53:00 +00001205 if _, ok := s.excludedMembersByName[m]; ok {
1206 continue
1207 }
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001208 references = append(references, s.snapshotSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001209 }
1210 return references
1211}
1212
Paul Duffin13f02712020-03-06 12:30:43 +00001213func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1214 _, ok := s.exportedMembersByName[memberName]
1215 return !ok
1216}
1217
Martin Stjernholm89238f42020-07-10 00:14:03 +01001218// Add the properties from the given SdkMemberProperties to the blueprint
1219// property set. This handles common properties in SdkMemberPropertiesBase and
1220// calls the member-specific AddToPropertySet for the rest.
1221func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1222 if memberProperties.Base().Compile_multilib != "" {
1223 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1224 }
1225
1226 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1227}
1228
Paul Duffin21827262021-04-24 12:16:36 +01001229// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1230type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001231 // The sdk variant that depends (possibly indirectly) on the member variant.
1232 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001233
1234 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001235 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001236
1237 // The variant that is added to the sdk.
Paul Duffin5e71e682022-11-23 18:09:54 +00001238 variant android.Module
Paul Duffinb97b1572021-04-29 21:50:40 +01001239
Paul Duffinc6ba1822022-05-06 09:38:02 +00001240 // The optional container of this member, i.e. the module that is depended upon by the sdk
1241 // (possibly transitively) and whose dependency on this module is why it was added to the sdk.
1242 // Is nil if this a direct dependency of the sdk.
Paul Duffin5e71e682022-11-23 18:09:54 +00001243 container android.Module
Paul Duffinc6ba1822022-05-06 09:38:02 +00001244
Paul Duffinb97b1572021-04-29 21:50:40 +01001245 // True if the member should be exported, i.e. accessible, from outside the sdk.
1246 export bool
1247
1248 // The names of additional component modules provided by the variant.
1249 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1938dba2022-07-26 23:53:00 +00001250
1251 // The minimum API level on which this module is supported.
1252 minApiLevel android.ApiLevel
Paul Duffin1356d8c2020-02-25 19:26:33 +00001253}
1254
Spandan Dasb84dbb22023-03-08 22:06:35 +00001255// Host returns true if the sdk member is a host variant (e.g. host tool)
1256func (s *sdkMemberVariantDep) Host() bool {
1257 return s.variant.Target().Os.Class == android.Host
1258}
1259
Paul Duffin13879572019-11-28 14:31:38 +00001260var _ android.SdkMember = (*sdkMember)(nil)
1261
Paul Duffin21827262021-04-24 12:16:36 +01001262// sdkMember groups all the variants of a specific member module together along with the name of the
1263// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001264type sdkMember struct {
1265 memberType android.SdkMemberType
1266 name string
Paul Duffin5e71e682022-11-23 18:09:54 +00001267 variants []android.Module
Paul Duffin13879572019-11-28 14:31:38 +00001268}
1269
1270func (m *sdkMember) Name() string {
1271 return m.name
1272}
1273
Paul Duffin5e71e682022-11-23 18:09:54 +00001274func (m *sdkMember) Variants() []android.Module {
Paul Duffin13879572019-11-28 14:31:38 +00001275 return m.variants
1276}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001277
Paul Duffin9c3760e2020-03-16 19:52:08 +00001278// Track usages of multilib variants.
1279type multilibUsage int
1280
1281const (
1282 multilibNone multilibUsage = 0
1283 multilib32 multilibUsage = 1
1284 multilib64 multilibUsage = 2
1285 multilibBoth = multilib32 | multilib64
1286)
1287
1288// Add the multilib that is used in the arch type.
1289func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1290 multilib := archType.Multilib
1291 switch multilib {
1292 case "":
1293 return m
1294 case "lib32":
1295 return m | multilib32
1296 case "lib64":
1297 return m | multilib64
1298 default:
1299 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1300 }
1301}
1302
1303func (m multilibUsage) String() string {
1304 switch m {
1305 case multilibNone:
1306 return ""
1307 case multilib32:
1308 return "32"
1309 case multilib64:
1310 return "64"
1311 case multilibBoth:
1312 return "both"
1313 default:
1314 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1315 m, multilibNone, multilib32, multilib64, multilibBoth))
1316 }
1317}
1318
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001319// TODO(187910671): BEGIN - Remove once modules do not have an APEX and default variant.
1320// variantCoordinate contains the coordinates used to identify a variant of an SDK member.
1321type variantCoordinate struct {
1322 // osType identifies the OS target of a variant.
1323 osType android.OsType
1324 // archId identifies the architecture and whether it is for the native bridge.
1325 archId archId
1326 // image is the image variant name.
1327 image string
1328 // linkType is the link type name.
1329 linkType string
1330}
1331
1332func getVariantCoordinate(ctx *memberContext, variant android.Module) variantCoordinate {
1333 linkType := ""
1334 if len(ctx.MemberType().SupportedLinkages()) > 0 {
1335 linkType = getLinkType(variant)
1336 }
1337 return variantCoordinate{
1338 osType: variant.Target().Os,
1339 archId: archIdFromTarget(variant.Target()),
1340 image: variant.ImageVariation().Variation,
1341 linkType: linkType,
1342 }
1343}
1344
1345// selectApexVariantsWhereAvailable filters the input list of variants by selecting the APEX
1346// specific variant for a specific variantCoordinate when there is both an APEX and default variant.
1347//
1348// There is a long-standing issue where a module that is added to an APEX has both an APEX and
1349// default/platform variant created even when the module does not require a platform variant. As a
1350// result an indirect dependency onto a module via the APEX will use the APEX variant, whereas a
1351// direct dependency onto the module will use the default/platform variant. That would result in a
1352// failure while attempting to optimize the properties for a member as it would have two variants
1353// when only one was expected.
1354//
1355// This function mitigates that problem by detecting when there are two variants that differ only
1356// by apex variant, where one is the default/platform variant and one is the APEX variant. In that
1357// case it picks the APEX variant. It picks the APEX variant because that is the behavior that would
1358// be expected
Paul Duffin5e71e682022-11-23 18:09:54 +00001359func selectApexVariantsWhereAvailable(ctx *memberContext, variants []android.Module) []android.Module {
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001360 moduleCtx := ctx.sdkMemberContext
1361
1362 // Group the variants by coordinates.
Paul Duffin5e71e682022-11-23 18:09:54 +00001363 variantsByCoord := make(map[variantCoordinate][]android.Module)
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001364 for _, variant := range variants {
1365 coord := getVariantCoordinate(ctx, variant)
1366 variantsByCoord[coord] = append(variantsByCoord[coord], variant)
1367 }
1368
Paul Duffin5e71e682022-11-23 18:09:54 +00001369 toDiscard := make(map[android.Module]struct{})
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001370 for coord, list := range variantsByCoord {
1371 count := len(list)
1372 if count == 1 {
1373 continue
1374 }
1375
Paul Duffin5e71e682022-11-23 18:09:54 +00001376 variantsByApex := make(map[string]android.Module)
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001377 conflictDetected := false
1378 for _, variant := range list {
Colin Cross313aa542023-12-13 13:47:44 -08001379 apexInfo, _ := android.OtherModuleProvider(moduleCtx, variant, android.ApexInfoProvider)
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001380 apexVariationName := apexInfo.ApexVariationName
1381 // If there are two variants for a specific APEX variation then there is conflict.
1382 if _, ok := variantsByApex[apexVariationName]; ok {
1383 conflictDetected = true
1384 break
1385 }
1386 variantsByApex[apexVariationName] = variant
1387 }
1388
1389 // If there are more than 2 apex variations or one of the apex variations is not the
1390 // default/platform variation then there is a conflict.
1391 if len(variantsByApex) != 2 {
1392 conflictDetected = true
1393 } else if _, ok := variantsByApex[""]; !ok {
1394 conflictDetected = true
1395 }
1396
1397 // If there are no conflicts then add the default/platform variation to the list to remove.
1398 if !conflictDetected {
1399 toDiscard[variantsByApex[""]] = struct{}{}
1400 continue
1401 }
1402
1403 // There are duplicate variants at this coordinate and they are not the default and APEX variant
1404 // so fail.
1405 variantDescriptions := []string{}
1406 for _, m := range list {
1407 variantDescriptions = append(variantDescriptions, fmt.Sprintf(" %s", m.String()))
1408 }
1409
1410 moduleCtx.ModuleErrorf("multiple conflicting variants detected for OsType{%s}, %s, Image{%s}, Link{%s}\n%s",
1411 coord.osType, coord.archId.String(), coord.image, coord.linkType,
1412 strings.Join(variantDescriptions, "\n"))
1413 }
1414
1415 // If there are any variants to discard then remove them from the list of variants, while
1416 // preserving the order.
1417 if len(toDiscard) > 0 {
Paul Duffin5e71e682022-11-23 18:09:54 +00001418 filtered := []android.Module{}
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001419 for _, variant := range variants {
1420 if _, ok := toDiscard[variant]; !ok {
1421 filtered = append(filtered, variant)
1422 }
1423 }
1424 variants = filtered
1425 }
1426
1427 return variants
1428}
1429
1430// TODO(187910671): END - Remove once modules do not have an APEX and default variant.
1431
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001432type baseInfo struct {
1433 Properties android.SdkMemberProperties
1434}
1435
Paul Duffinf34f6d82020-04-30 15:48:31 +01001436func (b *baseInfo) optimizableProperties() interface{} {
1437 return b.Properties
1438}
1439
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001440type osTypeSpecificInfo struct {
1441 baseInfo
1442
Paul Duffin00e46802020-03-12 20:40:35 +00001443 osType android.OsType
1444
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001445 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001446 //
1447 // Nil if there is one variant whose arch type is common
1448 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001449}
1450
Paul Duffin4b8b7932020-05-06 12:35:38 +01001451var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1452
Paul Duffinfc8dd232020-03-17 12:51:37 +00001453type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1454
Paul Duffin00e46802020-03-12 20:40:35 +00001455// Create a new osTypeSpecificInfo for the specified os type and its properties
1456// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001457func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001458 osInfo := &osTypeSpecificInfo{
1459 osType: osType,
1460 }
1461
1462 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1463 properties := variantPropertiesFactory()
1464 properties.Base().Os = osType
1465 return properties
1466 }
1467
1468 // Create a structure into which properties common across the architectures in
1469 // this os type will be stored.
1470 osInfo.Properties = osSpecificVariantPropertiesFactory()
1471
1472 // Group the variants by arch type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001473 var variantsByArchId = make(map[archId][]android.Module)
1474 var archIds []archId
Paul Duffin00e46802020-03-12 20:40:35 +00001475 for _, variant := range osTypeVariants {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001476 target := variant.Target()
1477 id := archIdFromTarget(target)
1478 if _, ok := variantsByArchId[id]; !ok {
1479 archIds = append(archIds, id)
Paul Duffin00e46802020-03-12 20:40:35 +00001480 }
1481
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001482 variantsByArchId[id] = append(variantsByArchId[id], variant)
Paul Duffin00e46802020-03-12 20:40:35 +00001483 }
1484
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001485 if commonVariants, ok := variantsByArchId[commonArchId]; ok {
Paul Duffin00e46802020-03-12 20:40:35 +00001486 if len(osTypeVariants) != 1 {
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001487 variants := []string{}
1488 for _, m := range osTypeVariants {
1489 variants = append(variants, fmt.Sprintf(" %s", m.String()))
1490 }
1491 panic(fmt.Errorf("expected to only have 1 variant of %q when arch type is common but found %d\n%s",
1492 ctx.Name(),
1493 len(osTypeVariants),
1494 strings.Join(variants, "\n")))
Paul Duffin00e46802020-03-12 20:40:35 +00001495 }
1496
1497 // A common arch type only has one variant and its properties should be treated
1498 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001499 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001500 } else {
1501 // Create an arch specific info for each supported architecture type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001502 for _, id := range archIds {
1503 archVariants := variantsByArchId[id]
1504 archInfo := newArchSpecificInfo(ctx, id, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001505
1506 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1507 }
1508 }
1509
1510 return osInfo
1511}
1512
Paul Duffin39abf8f2021-09-24 14:58:27 +01001513func (osInfo *osTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1514 if len(osInfo.archInfos) == 0 {
1515 pruner.pruneProperties(osInfo.Properties)
1516 } else {
1517 for _, archInfo := range osInfo.archInfos {
1518 archInfo.pruneUnsupportedProperties(pruner)
1519 }
1520 }
1521}
1522
Paul Duffin00e46802020-03-12 20:40:35 +00001523// Optimize the properties by extracting common properties from arch type specific
1524// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001525func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001526 // Nothing to do if there is only a single common architecture.
1527 if len(osInfo.archInfos) == 0 {
1528 return
1529 }
1530
Paul Duffin9c3760e2020-03-16 19:52:08 +00001531 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001532 for _, archInfo := range osInfo.archInfos {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001533 multilib = multilib.addArchType(archInfo.archId.archType)
Paul Duffin9c3760e2020-03-16 19:52:08 +00001534
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001535 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001536 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001537 }
1538
Paul Duffin4b8b7932020-05-06 12:35:38 +01001539 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001540
1541 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001542 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001543}
1544
1545// Add the properties for an os to a property set.
1546//
1547// Maps the properties related to the os variants through to an appropriate
1548// module structure that will produce equivalent set of variants when it is
1549// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001550func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001551
1552 var osPropertySet android.BpPropertySet
1553 var archPropertySet android.BpPropertySet
1554 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001555 if osInfo.Properties.Base().Os_count == 1 &&
1556 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1557 // There is only one OS type present in the variants and it shouldn't have a
1558 // variant-specific target. The latter is the case if it's either for device
1559 // where there is only one OS (android), or for host and the member type
1560 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001561
1562 // Create a structure that looks like:
1563 // module_type {
1564 // name: "...",
1565 // ...
1566 // <common properties>
1567 // ...
1568 // <single os type specific properties>
1569 //
1570 // arch: {
1571 // <arch specific sections>
1572 // }
1573 //
1574 osPropertySet = bpModule
1575 archPropertySet = osPropertySet.AddPropertySet("arch")
1576
1577 // Arch specific properties need to be added to an arch specific section
1578 // within arch.
1579 archOsPrefix = ""
1580 } else {
1581 // Create a structure that looks like:
1582 // module_type {
1583 // name: "...",
1584 // ...
1585 // <common properties>
1586 // ...
1587 // target: {
1588 // <arch independent os specific sections, e.g. android>
1589 // ...
1590 // <arch and os specific sections, e.g. android_x86>
1591 // }
1592 //
1593 osType := osInfo.osType
1594 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1595 archPropertySet = targetPropertySet
1596
1597 // Arch specific properties need to be added to an os and arch specific
1598 // section prefixed with <os>_.
1599 archOsPrefix = osType.Name + "_"
1600 }
1601
1602 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001603 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001604
1605 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1606 // os) specific properties.
1607 //
1608 // The archInfos list will be empty if the os contains variants for the common
1609 // architecture.
1610 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001611 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001612 }
1613}
1614
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001615func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1616 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001617 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001618}
1619
1620var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1621
Paul Duffin4b8b7932020-05-06 12:35:38 +01001622func (osInfo *osTypeSpecificInfo) String() string {
1623 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1624}
1625
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001626// archId encapsulates the information needed to identify a combination of arch type and native
1627// bridge support.
1628//
1629// Conceptually, native bridge support is a facet of an android.Target, not an android.Arch as it is
1630// essentially using one android.Arch to implement another. However, in terms of the handling of
1631// the variants native bridge is treated as part of the arch variation. See the ArchVariation method
1632// on android.Target.
1633//
1634// So, it makes sense when optimizing the variants to combine native bridge with the arch type.
1635type archId struct {
1636 // The arch type of the variant's target.
1637 archType android.ArchType
1638
1639 // True if the variants is for the native bridge, false otherwise.
1640 nativeBridge bool
1641}
1642
1643// propertyName returns the name of the property corresponding to use for this arch id.
1644func (i *archId) propertyName() string {
1645 name := i.archType.Name
1646 if i.nativeBridge {
1647 // Note: This does not result in a valid property because there is no architecture specific
1648 // native bridge property, only a generic "native_bridge" property. However, this will be used
1649 // in error messages if there is an attempt to use this in a generated bp file.
1650 name += "_native_bridge"
1651 }
1652 return name
1653}
1654
1655func (i *archId) String() string {
1656 return fmt.Sprintf("ArchType{%s}, NativeBridge{%t}", i.archType, i.nativeBridge)
1657}
1658
1659// archIdFromTarget returns an archId initialized from information in the supplied target.
1660func archIdFromTarget(target android.Target) archId {
1661 return archId{
1662 archType: target.Arch.ArchType,
1663 nativeBridge: target.NativeBridge == android.NativeBridgeEnabled,
1664 }
1665}
1666
1667// commonArchId is the archId for the common architecture.
1668var commonArchId = archId{archType: android.Common}
1669
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001670type archTypeSpecificInfo struct {
1671 baseInfo
1672
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001673 archId archId
1674 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001675
Paul Duffinb42fa672021-09-09 16:37:49 +01001676 imageVariantInfos []*imageVariantSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001677}
1678
Paul Duffin4b8b7932020-05-06 12:35:38 +01001679var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1680
Paul Duffinfc8dd232020-03-17 12:51:37 +00001681// Create a new archTypeSpecificInfo for the specified arch type and its properties
1682// structures populated with information from the variants.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001683func newArchSpecificInfo(ctx android.SdkMemberContext, archId archId, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001684
Paul Duffinfc8dd232020-03-17 12:51:37 +00001685 // Create an arch specific info into which the variant properties can be copied.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001686 archInfo := &archTypeSpecificInfo{archId: archId, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001687
1688 // Create the properties into which the arch type specific properties will be
1689 // added.
1690 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001691
Liz Kammer96320df2022-05-12 20:40:00 -04001692 // if there are multiple supported link variants, we want to nest based on linkage even if there
1693 // is only one variant, otherwise, if there is only one variant we can populate based on the arch
1694 if len(archVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001695 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001696 } else {
Paul Duffinb42fa672021-09-09 16:37:49 +01001697 // Group the variants by image type.
1698 variantsByImage := make(map[string][]android.Module)
1699 for _, variant := range archVariants {
1700 image := variant.ImageVariation().Variation
1701 variantsByImage[image] = append(variantsByImage[image], variant)
1702 }
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001703
Paul Duffinb42fa672021-09-09 16:37:49 +01001704 // Create the image variant info in a fixed order.
Cole Faust18994c72023-02-28 16:02:16 -08001705 for _, imageVariantName := range android.SortedKeys(variantsByImage) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001706 variants := variantsByImage[imageVariantName]
1707 archInfo.imageVariantInfos = append(archInfo.imageVariantInfos, newImageVariantSpecificInfo(ctx, imageVariantName, variantPropertiesFactory, variants))
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001708 }
1709 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001710
1711 return archInfo
1712}
1713
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001714// Get the link type of the variant
1715//
1716// If the variant is not differentiated by link type then it returns "",
1717// otherwise it returns one of "static" or "shared".
1718func getLinkType(variant android.Module) string {
1719 linkType := ""
1720 if linkable, ok := variant.(cc.LinkableInterface); ok {
1721 if linkable.Shared() && linkable.Static() {
1722 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1723 } else if linkable.Shared() {
1724 linkType = "shared"
1725 } else if linkable.Static() {
1726 linkType = "static"
1727 } else {
1728 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1729 }
1730 }
1731 return linkType
1732}
1733
Paul Duffin39abf8f2021-09-24 14:58:27 +01001734func (archInfo *archTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1735 if len(archInfo.imageVariantInfos) == 0 {
1736 pruner.pruneProperties(archInfo.Properties)
1737 } else {
1738 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1739 imageVariantInfo.pruneUnsupportedProperties(pruner)
1740 }
1741 }
1742}
1743
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001744// Optimize the properties by extracting common properties from link type specific
1745// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001746func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001747 if len(archInfo.imageVariantInfos) == 0 {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001748 return
1749 }
1750
Paul Duffinb42fa672021-09-09 16:37:49 +01001751 // Optimize the image variant properties first.
1752 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1753 imageVariantInfo.optimizeProperties(ctx, commonValueExtractor)
1754 }
1755
1756 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.imageVariantInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001757}
1758
Paul Duffinfc8dd232020-03-17 12:51:37 +00001759// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001760func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001761 archPropertySuffix := archInfo.archId.propertyName()
1762 propertySetName := archOsPrefix + archPropertySuffix
1763 archTypePropertySet := archPropertySet.AddPropertySet(propertySetName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001764 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1765 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1766 archTypePropertySet.AddProperty("enabled", true)
1767 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001768 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001769
Paul Duffinb42fa672021-09-09 16:37:49 +01001770 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1771 imageVariantInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001772 }
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001773
1774 // If this is for a native bridge architecture then make sure that the property set does not
1775 // contain any properties as providing native bridge specific properties is not currently
1776 // supported.
1777 if archInfo.archId.nativeBridge {
1778 propertySetContents := getPropertySetContents(archTypePropertySet)
1779 if propertySetContents != "" {
1780 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",
1781 propertySetName, ctx.name, propertySetContents)
1782 }
1783 }
1784}
1785
1786// getPropertySetContents returns the string representation of the contents of a property set, after
1787// recursively pruning any empty nested property sets.
1788func getPropertySetContents(propertySet android.BpPropertySet) string {
1789 set := propertySet.(*bpPropertySet)
1790 set.transformContents(pruneEmptySetTransformer{})
1791 if len(set.properties) != 0 {
1792 contents := &generatedContents{}
1793 contents.Indent()
1794 outputPropertySet(contents, set)
1795 setAsString := contents.content.String()
1796 return setAsString
1797 }
1798 return ""
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001799}
1800
Paul Duffin4b8b7932020-05-06 12:35:38 +01001801func (archInfo *archTypeSpecificInfo) String() string {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001802 return archInfo.archId.String()
Paul Duffin4b8b7932020-05-06 12:35:38 +01001803}
1804
Paul Duffinb42fa672021-09-09 16:37:49 +01001805type imageVariantSpecificInfo struct {
1806 baseInfo
1807
1808 imageVariant string
1809
1810 linkInfos []*linkTypeSpecificInfo
1811}
1812
1813func newImageVariantSpecificInfo(ctx android.SdkMemberContext, imageVariant string, variantPropertiesFactory variantPropertiesFactoryFunc, imageVariants []android.Module) *imageVariantSpecificInfo {
1814
1815 // Create an image variant specific info into which the variant properties can be copied.
1816 imageInfo := &imageVariantSpecificInfo{imageVariant: imageVariant}
1817
1818 // Create the properties into which the image variant specific properties will be added.
1819 imageInfo.Properties = variantPropertiesFactory()
1820
Liz Kammer96320df2022-05-12 20:40:00 -04001821 // if there are multiple supported link variants, we want to nest even if there is only one
1822 // variant, otherwise, if there is only one variant we can populate based on the image
1823 if len(imageVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffinb42fa672021-09-09 16:37:49 +01001824 imageInfo.Properties.PopulateFromVariant(ctx, imageVariants[0])
1825 } else {
1826 // There is more than one variant for this image variant which must be differentiated by link
Liz Kammer96320df2022-05-12 20:40:00 -04001827 // type. Or there are multiple supported linkages and we need to nest based on link type.
Paul Duffinb42fa672021-09-09 16:37:49 +01001828 for _, linkVariant := range imageVariants {
1829 linkType := getLinkType(linkVariant)
1830 if linkType == "" {
1831 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(imageVariants)))
1832 } else {
1833 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
1834
1835 imageInfo.linkInfos = append(imageInfo.linkInfos, linkInfo)
1836 }
1837 }
1838 }
1839
1840 return imageInfo
1841}
1842
Paul Duffin39abf8f2021-09-24 14:58:27 +01001843func (imageInfo *imageVariantSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1844 if len(imageInfo.linkInfos) == 0 {
1845 pruner.pruneProperties(imageInfo.Properties)
1846 } else {
1847 for _, linkInfo := range imageInfo.linkInfos {
1848 linkInfo.pruneUnsupportedProperties(pruner)
1849 }
1850 }
1851}
1852
Paul Duffinb42fa672021-09-09 16:37:49 +01001853// Optimize the properties by extracting common properties from link type specific
1854// properties into arch type specific properties.
1855func (imageInfo *imageVariantSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
1856 if len(imageInfo.linkInfos) == 0 {
1857 return
1858 }
1859
1860 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, imageInfo.Properties, imageInfo.linkInfos)
1861}
1862
1863// Add the properties for an arch type to a property set.
1864func (imageInfo *imageVariantSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1865 if imageInfo.imageVariant != android.CoreVariation {
1866 propertySet = propertySet.AddPropertySet(imageInfo.imageVariant)
1867 }
1868
1869 addSdkMemberPropertiesToSet(ctx, imageInfo.Properties, propertySet)
1870
Liz Kammer96320df2022-05-12 20:40:00 -04001871 usedLinkages := make(map[string]bool, len(imageInfo.linkInfos))
Paul Duffinb42fa672021-09-09 16:37:49 +01001872 for _, linkInfo := range imageInfo.linkInfos {
Liz Kammer96320df2022-05-12 20:40:00 -04001873 usedLinkages[linkInfo.linkType] = true
Paul Duffinb42fa672021-09-09 16:37:49 +01001874 linkInfo.addToPropertySet(ctx, propertySet)
1875 }
1876
Liz Kammer96320df2022-05-12 20:40:00 -04001877 // If not all supported linkages had existing variants, we need to disable the unsupported variant
1878 if len(imageInfo.linkInfos) < len(ctx.MemberType().SupportedLinkages()) {
1879 for _, l := range ctx.MemberType().SupportedLinkages() {
1880 if _, ok := usedLinkages[l]; !ok {
1881 otherLinkagePropertySet := propertySet.AddPropertySet(l)
1882 otherLinkagePropertySet.AddProperty("enabled", false)
1883 }
1884 }
1885 }
1886
Paul Duffinb42fa672021-09-09 16:37:49 +01001887 // If this is for a non-core image variant then make sure that the property set does not contain
1888 // any properties as providing non-core image variant specific properties for prebuilts is not
1889 // currently supported.
1890 if imageInfo.imageVariant != android.CoreVariation {
1891 propertySetContents := getPropertySetContents(propertySet)
1892 if propertySetContents != "" {
1893 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",
1894 imageInfo.imageVariant, ctx.name, propertySetContents)
1895 }
1896 }
1897}
1898
1899func (imageInfo *imageVariantSpecificInfo) String() string {
1900 return imageInfo.imageVariant
1901}
1902
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001903type linkTypeSpecificInfo struct {
1904 baseInfo
1905
1906 linkType string
1907}
1908
Paul Duffin4b8b7932020-05-06 12:35:38 +01001909var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1910
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001911// Create a new linkTypeSpecificInfo for the specified link type and its properties
1912// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001913func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001914 linkInfo := &linkTypeSpecificInfo{
1915 baseInfo: baseInfo{
1916 // Create the properties into which the link type specific properties will be
1917 // added.
1918 Properties: variantPropertiesFactory(),
1919 },
1920 linkType: linkType,
1921 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001922 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001923 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001924}
1925
Paul Duffinf68f85a2021-09-09 16:11:42 +01001926func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1927 linkPropertySet := propertySet.AddPropertySet(l.linkType)
1928 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
1929}
1930
Paul Duffin39abf8f2021-09-24 14:58:27 +01001931func (l *linkTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1932 pruner.pruneProperties(l.Properties)
1933}
1934
Paul Duffin4b8b7932020-05-06 12:35:38 +01001935func (l *linkTypeSpecificInfo) String() string {
1936 return fmt.Sprintf("LinkType{%s}", l.linkType)
1937}
1938
Paul Duffin3a4eb502020-03-19 16:11:18 +00001939type memberContext struct {
1940 sdkMemberContext android.ModuleContext
1941 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001942 memberType android.SdkMemberType
1943 name string
Paul Duffind19f8942021-07-14 12:08:37 +01001944
1945 // The set of traits required of this member.
1946 requiredTraits android.SdkMemberTraitSet
Paul Duffin3a4eb502020-03-19 16:11:18 +00001947}
1948
Cole Faust34867402023-04-28 12:32:27 -07001949func (m *memberContext) ModuleErrorf(fmt string, args ...interface{}) {
1950 m.sdkMemberContext.ModuleErrorf(fmt, args...)
1951}
1952
Paul Duffin3a4eb502020-03-19 16:11:18 +00001953func (m *memberContext) SdkModuleContext() android.ModuleContext {
1954 return m.sdkMemberContext
1955}
1956
1957func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1958 return m.builder
1959}
1960
Paul Duffina551a1c2020-03-17 21:04:24 +00001961func (m *memberContext) MemberType() android.SdkMemberType {
1962 return m.memberType
1963}
1964
1965func (m *memberContext) Name() string {
1966 return m.name
1967}
1968
Paul Duffind19f8942021-07-14 12:08:37 +01001969func (m *memberContext) RequiresTrait(trait android.SdkMemberTrait) bool {
1970 return m.requiredTraits.Contains(trait)
1971}
1972
Paul Duffin13648912022-07-15 13:12:35 +00001973func (m *memberContext) IsTargetBuildBeforeTiramisu() bool {
1974 return m.builder.targetBuildRelease.EarlierThan(buildReleaseT)
1975}
1976
1977var _ android.SdkMemberContext = (*memberContext)(nil)
1978
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001979func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001980
1981 memberType := member.memberType
1982
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001983 // Do not add the prefer property if the member snapshot module is a source module type.
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001984 moduleCtx := ctx.sdkMemberContext
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001985 if !memberType.UsesSourceModuleTypeInSnapshot() {
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001986 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1987 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1988 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1989 // behavior is for the module.
Paul Duffin82d75ad2022-11-14 17:35:50 +00001990 bpModule.insertAfter("name", "prefer", false)
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001991 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001992
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001993 variants := selectApexVariantsWhereAvailable(ctx, member.variants)
1994
Paul Duffina04c1072020-03-02 10:16:35 +00001995 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001996 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001997 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001998 osType := variant.Target().Os
1999 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002000 }
2001
Paul Duffina04c1072020-03-02 10:16:35 +00002002 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00002003 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00002004 properties := memberType.CreateVariantPropertiesStruct()
2005 base := properties.Base()
2006 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00002007 return properties
2008 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002009
Paul Duffina04c1072020-03-02 10:16:35 +00002010 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00002011
Paul Duffina04c1072020-03-02 10:16:35 +00002012 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00002013 commonProperties := variantPropertiesFactory()
2014 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00002015
Paul Duffin39abf8f2021-09-24 14:58:27 +01002016 // Create a property pruner that will prune any properties unsupported by the target build
2017 // release.
2018 targetBuildRelease := ctx.builder.targetBuildRelease
2019 unsupportedPropertyPruner := newPropertyPrunerByBuildRelease(commonProperties, targetBuildRelease)
2020
Paul Duffinc097e362020-03-10 22:50:03 +00002021 // Create common value extractor that can be used to optimize the properties.
2022 commonValueExtractor := newCommonValueExtractor(commonProperties)
2023
Paul Duffina04c1072020-03-02 10:16:35 +00002024 // The list of property structures which are os type specific but common across
2025 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002026 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00002027
2028 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00002029 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00002030 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00002031 // Add the os specific properties to a list of os type specific yet architecture
2032 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002033 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00002034
Paul Duffin39abf8f2021-09-24 14:58:27 +01002035 osInfo.pruneUnsupportedProperties(unsupportedPropertyPruner)
2036
Paul Duffin00e46802020-03-12 20:40:35 +00002037 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002038 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00002039 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002040
Paul Duffina04c1072020-03-02 10:16:35 +00002041 // Extract properties which are common across all architectures and os types.
Paul Duffin4e7d1c42022-05-13 13:12:19 +00002042 extractCommonProperties(moduleCtx, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002043
Paul Duffina04c1072020-03-02 10:16:35 +00002044 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01002045 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002046
Paul Duffina04c1072020-03-02 10:16:35 +00002047 // Create a target property set into which target specific properties can be
2048 // added.
2049 targetPropertySet := bpModule.AddPropertySet("target")
2050
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01002051 // If the member is host OS dependent and has host_supported then disable by
2052 // default and enable each host OS variant explicitly. This avoids problems
2053 // with implicitly enabled OS variants when the snapshot is used, which might
2054 // be different from this run (e.g. different build OS).
2055 if ctx.memberType.IsHostOsDependent() {
2056 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
2057 if hostSupported {
2058 hostPropertySet := targetPropertySet.AddPropertySet("host")
2059 hostPropertySet.AddProperty("enabled", false)
2060 }
2061 }
2062
Paul Duffina04c1072020-03-02 10:16:35 +00002063 // Iterate over the os types in a fixed order.
2064 for _, osType := range s.getPossibleOsTypes() {
2065 osInfo := osTypeToInfo[osType]
2066 if osInfo == nil {
2067 continue
2068 }
2069
Paul Duffin3a4eb502020-03-19 16:11:18 +00002070 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002071 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002072}
2073
Paul Duffina04c1072020-03-02 10:16:35 +00002074// Compute the list of possible os types that this sdk could support.
2075func (s *sdk) getPossibleOsTypes() []android.OsType {
2076 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00002077 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00002078 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07002079 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00002080 osTypes = append(osTypes, osType)
2081 }
2082 }
2083 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09002084 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00002085 osTypes = append(osTypes, osType)
2086 }
2087 }
2088 }
2089 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
2090 return osTypes
2091}
2092
Paul Duffinb28369a2020-05-04 15:39:59 +01002093// Given a set of properties (struct value), return the value of the field within that
2094// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00002095type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
2096
Paul Duffinc459f892020-04-30 18:08:29 +01002097// Checks the metadata to determine whether the property should be ignored for the
2098// purposes of common value extraction or not.
2099type extractorMetadataPredicate func(metadata propertiesContainer) bool
2100
2101// Indicates whether optimizable properties are provided by a host variant or
2102// not.
2103type isHostVariant interface {
2104 isHostVariant() bool
2105}
2106
Paul Duffinb28369a2020-05-04 15:39:59 +01002107// A property that can be optimized by the commonValueExtractor.
2108type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01002109 // The name of the field for this property. It is a "."-separated path for
2110 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002111 name string
2112
Paul Duffinc459f892020-04-30 18:08:29 +01002113 // Filter that can use metadata associated with the properties being optimized
2114 // to determine whether the field should be ignored during common value
2115 // optimization.
2116 filter extractorMetadataPredicate
2117
Paul Duffinb28369a2020-05-04 15:39:59 +01002118 // Retrieves the value on which common value optimization will be performed.
2119 getter fieldAccessorFunc
2120
Paul Duffinbfdca962022-09-22 16:21:54 +01002121 // True if the field should never be cleared.
2122 //
2123 // This is set to true if and only if the field is annotated with `sdk:"keep"`.
2124 keep bool
2125
Paul Duffinb28369a2020-05-04 15:39:59 +01002126 // The empty value for the field.
2127 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01002128
2129 // True if the property can support arch variants false otherwise.
2130 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01002131}
2132
Paul Duffin4b8b7932020-05-06 12:35:38 +01002133func (p extractorProperty) String() string {
2134 return p.name
2135}
2136
Paul Duffinc097e362020-03-10 22:50:03 +00002137// Supports extracting common values from a number of instances of a properties
2138// structure into a separate common set of properties.
2139type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01002140 // The properties that the extractor can optimize.
2141 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00002142}
2143
2144// Create a new common value extractor for the structure type for the supplied
2145// properties struct.
2146//
2147// The returned extractor can be used on any properties structure of the same type
2148// as the supplied set of properties.
2149func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
2150 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
2151 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01002152 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00002153 return extractor
2154}
2155
2156// Gather the fields from the supplied structure type from which common values will
2157// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00002158//
Martin Stjernholmb0249572020-09-15 02:32:35 +01002159// This is recursive function. If it encounters a struct then it will recurse
2160// into it, passing in the accessor for the field and the struct name as prefix
2161// for the nested fields. That will then be used in the accessors for the fields
2162// in the embedded struct.
2163func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00002164 for f := 0; f < structType.NumField(); f++ {
2165 field := structType.Field(f)
2166 if field.PkgPath != "" {
2167 // Ignore unexported fields.
2168 continue
2169 }
2170
Paul Duffin02e25c82022-09-22 15:30:58 +01002171 // Ignore fields tagged with sdk:"ignore".
2172 if proptools.HasTag(field, "sdk", "ignore") {
Paul Duffinc097e362020-03-10 22:50:03 +00002173 continue
2174 }
2175
Paul Duffinc459f892020-04-30 18:08:29 +01002176 var filter extractorMetadataPredicate
2177
2178 // Add a filter
2179 if proptools.HasTag(field, "sdk", "ignored-on-host") {
2180 filter = func(metadata propertiesContainer) bool {
2181 if m, ok := metadata.(isHostVariant); ok {
2182 if m.isHostVariant() {
2183 return false
2184 }
2185 }
2186 return true
2187 }
2188 }
2189
Paul Duffinbfdca962022-09-22 16:21:54 +01002190 keep := proptools.HasTag(field, "sdk", "keep")
2191
Paul Duffinc097e362020-03-10 22:50:03 +00002192 // Save a copy of the field index for use in the function.
2193 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01002194
Martin Stjernholmb0249572020-09-15 02:32:35 +01002195 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01002196
Paul Duffinc097e362020-03-10 22:50:03 +00002197 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00002198 if containingStructAccessor != nil {
2199 // This is an embedded structure so first access the field for the embedded
2200 // structure.
2201 value = containingStructAccessor(value)
2202 }
2203
Paul Duffinc097e362020-03-10 22:50:03 +00002204 // Skip through interface and pointer values to find the structure.
2205 value = getStructValue(value)
2206
Paul Duffin4b8b7932020-05-06 12:35:38 +01002207 defer func() {
2208 if r := recover(); r != nil {
2209 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
2210 }
2211 }()
2212
Paul Duffinc097e362020-03-10 22:50:03 +00002213 // Return the field.
2214 return value.Field(fieldIndex)
2215 }
2216
Martin Stjernholmb0249572020-09-15 02:32:35 +01002217 if field.Type.Kind() == reflect.Struct {
2218 // Gather fields from the nested or embedded structure.
2219 var subNamePrefix string
2220 if field.Anonymous {
2221 subNamePrefix = namePrefix
2222 } else {
2223 subNamePrefix = name + "."
2224 }
2225 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00002226 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01002227 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01002228 name,
Paul Duffinc459f892020-04-30 18:08:29 +01002229 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01002230 fieldGetter,
Paul Duffinbfdca962022-09-22 16:21:54 +01002231 keep,
Paul Duffinb28369a2020-05-04 15:39:59 +01002232 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01002233 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01002234 }
2235 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00002236 }
Paul Duffinc097e362020-03-10 22:50:03 +00002237 }
2238}
2239
2240func getStructValue(value reflect.Value) reflect.Value {
2241foundStruct:
2242 for {
2243 kind := value.Kind()
2244 switch kind {
2245 case reflect.Interface, reflect.Ptr:
2246 value = value.Elem()
2247 case reflect.Struct:
2248 break foundStruct
2249 default:
2250 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
2251 }
2252 }
2253 return value
2254}
2255
Paul Duffinf34f6d82020-04-30 15:48:31 +01002256// A container of properties to be optimized.
2257//
2258// Allows additional information to be associated with the properties, e.g. for
2259// filtering.
2260type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002261 fmt.Stringer
2262
Paul Duffinf34f6d82020-04-30 15:48:31 +01002263 // Get the properties that need optimizing.
2264 optimizableProperties() interface{}
2265}
2266
Paul Duffin2d1bb892021-04-24 11:32:59 +01002267// A wrapper for sdk variant related properties to allow them to be optimized.
2268type sdkVariantPropertiesContainer struct {
2269 sdkVariant *sdk
2270 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01002271}
2272
Paul Duffin2d1bb892021-04-24 11:32:59 +01002273func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
2274 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01002275}
2276
Paul Duffin2d1bb892021-04-24 11:32:59 +01002277func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002278 return c.sdkVariant.String()
2279}
2280
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002281// Extract common properties from a slice of property structures of the same type.
2282//
2283// All the property structures must be of the same type.
2284// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002285// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002286//
2287// Iterates over each exported field (capitalized name) and checks to see whether they
2288// have the same value (using DeepEquals) across all the input properties. If it does not then no
2289// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01002290// and the field in each of the input properties structure is set to its default value. Nested
2291// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002292func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002293 commonPropertiesValue := reflect.ValueOf(commonProperties)
2294 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002295
Paul Duffinf34f6d82020-04-30 15:48:31 +01002296 sliceValue := reflect.ValueOf(inputPropertiesSlice)
2297
Paul Duffinb28369a2020-05-04 15:39:59 +01002298 for _, property := range e.properties {
2299 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01002300 filter := property.filter
2301 if filter == nil {
2302 filter = func(metadata propertiesContainer) bool {
2303 return true
2304 }
2305 }
Paul Duffinb28369a2020-05-04 15:39:59 +01002306
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002307 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002308 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2309 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002310 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002311
Paul Duffin864e1b42020-05-06 10:23:19 +01002312 // Assume that all the values will be the same.
2313 //
2314 // While similar to this is not quite the same as commonValue == nil. If all the values
2315 // have been filtered out then this will be false but commonValue == nil will be true.
2316 valuesDiffer := false
2317
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002318 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002319 container := sliceValue.Index(i).Interface().(propertiesContainer)
2320 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002321 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002322
Paul Duffinc459f892020-04-30 18:08:29 +01002323 if !filter(container) {
2324 expectedValue := property.emptyValue.Interface()
2325 actualValue := fieldValue.Interface()
2326 if !reflect.DeepEqual(expectedValue, actualValue) {
2327 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2328 }
2329 continue
2330 }
2331
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002332 if commonValue == nil {
2333 // Use the first value as the commonProperties value.
2334 commonValue = &fieldValue
2335 } else {
2336 // If the value does not match the current common value then there is
2337 // no value in common so break out.
2338 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2339 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002340 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002341 break
2342 }
2343 }
2344 }
2345
Paul Duffin864e1b42020-05-06 10:23:19 +01002346 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002347 // and set the input struct's field to the empty value.
2348 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002349 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002350 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffinbfdca962022-09-22 16:21:54 +01002351 if !property.keep {
2352 for i := 0; i < sliceValue.Len(); i++ {
2353 container := sliceValue.Index(i).Interface().(propertiesContainer)
2354 itemValue := reflect.ValueOf(container.optimizableProperties())
2355 fieldValue := fieldGetter(itemValue)
2356 fieldValue.Set(emptyValue)
2357 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002358 }
2359 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002360
2361 if valuesDiffer && !property.archVariant {
2362 // The values differ but the property does not support arch variants so it
2363 // is an error.
2364 var details strings.Builder
2365 for i := 0; i < sliceValue.Len(); i++ {
2366 container := sliceValue.Index(i).Interface().(propertiesContainer)
2367 itemValue := reflect.ValueOf(container.optimizableProperties())
2368 fieldValue := fieldGetter(itemValue)
2369
2370 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2371 }
2372
2373 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2374 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002375 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002376
2377 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002378}