blob: 7bd8bd7a30d3b021c0520961e223c7798a0f4628 [file] [log] [blame]
Jiyong Park9b409bc2019-10-11 14:59:13 +09001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package sdk
16
17import (
Paul Duffinc6ba1822022-05-06 09:38:02 +000018 "bytes"
19 "encoding/json"
Jiyong Park9b409bc2019-10-11 14:59:13 +090020 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000021 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000022 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090023 "strings"
24
Paul Duffin7d74e7b2020-03-06 12:30:13 +000025 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000026 "android/soong/cc"
Colin Crosscb0ac952021-07-20 13:17:15 -070027
Paul Duffin375058f2019-11-29 20:17:53 +000028 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090029 "github.com/google/blueprint/proptools"
30
31 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090032)
33
Paul Duffin64fb5262021-05-05 21:36:04 +010034// Environment variables that affect the generated snapshot
35// ========================================================
36//
Paul Duffin39abf8f2021-09-24 14:58:27 +010037// SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE
38// This allows the target build release (i.e. the release version of the build within which
39// the snapshot will be used) of the snapshot to be specified. If unspecified then it defaults
40// to the current build release version. Otherwise, it must be the name of one of the build
41// releases defined in nameToBuildRelease, e.g. S, T, etc..
42//
43// The generated snapshot must only be used in the specified target release. If the target
44// build release is not the current build release then the generated Android.bp file not be
45// checked for compatibility.
46//
47// e.g. if setting SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE=S will cause the generated snapshot
48// to be compatible with S.
49//
Paul Duffin64fb5262021-05-05 21:36:04 +010050
Jiyong Park9b409bc2019-10-11 14:59:13 +090051var pctx = android.NewPackageContext("android/soong/sdk")
52
Paul Duffin375058f2019-11-29 20:17:53 +000053var (
54 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
55 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000056 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000057 CommandDeps: []string{
58 "${config.Zip2ZipCmd}",
59 },
60 },
61 "destdir")
62
63 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
64 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -070065 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +000066 CommandDeps: []string{
67 "${config.SoongZipCmd}",
68 },
69 Rspfile: "$out.rsp",
70 RspfileContent: "$in",
71 },
72 "basedir")
73
74 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
75 blueprint.RuleParams{
Paul Duffin74f1dcd2022-07-18 13:18:23 +000076 Command: `${config.MergeZipsCmd} -s $out $in`,
Paul Duffin375058f2019-11-29 20:17:53 +000077 CommandDeps: []string{
78 "${config.MergeZipsCmd}",
79 },
80 })
81)
82
Paul Duffin43f7bf02021-05-05 22:00:51 +010083const (
Paul Duffinb01ac4b2022-05-24 20:10:05 +000084 soongSdkSnapshotVersionCurrent = "current"
Paul Duffin43f7bf02021-05-05 22:00:51 +010085)
86
Paul Duffinb645ec82019-11-27 17:43:54 +000087type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090088 content strings.Builder
89 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090090}
91
Paul Duffinb645ec82019-11-27 17:43:54 +000092// generatedFile abstracts operations for writing contents into a file and emit a build rule
93// for the file.
94type generatedFile struct {
95 generatedContents
96 path android.OutputPath
97}
98
Jiyong Park232e7852019-11-04 12:23:40 +090099func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +0900100 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +0000101 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +0900102 }
103}
104
Paul Duffinb645ec82019-11-27 17:43:54 +0000105func (gc *generatedContents) Indent() {
106 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +0900107}
108
Paul Duffinb645ec82019-11-27 17:43:54 +0000109func (gc *generatedContents) Dedent() {
110 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +0900111}
112
Paul Duffina08e4dc2021-06-22 18:19:19 +0100113// IndentedPrintf will add spaces to indent the line to the appropriate level before printing the
114// arguments.
115func (gc *generatedContents) IndentedPrintf(format string, args ...interface{}) {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000116 _, _ = fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100117}
118
119// UnindentedPrintf does not add spaces to indent the line to the appropriate level before printing
120// the arguments.
121func (gc *generatedContents) UnindentedPrintf(format string, args ...interface{}) {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000122 _, _ = fmt.Fprintf(&(gc.content), format, args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900123}
124
125func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800126 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100127
128 content := gf.content.String()
129
130 // ninja consumes newline characters in rspfile_content. Prevent it by
131 // escaping the backslash in the newline character. The extra backslash
132 // is removed when the rspfile is written to the actual script file
133 content = strings.ReplaceAll(content, "\n", "\\n")
134
Jiyong Park9b409bc2019-10-11 14:59:13 +0900135 rb.Command().
136 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100137 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100138 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900139 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
140 rb.Command().
141 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800142 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900143}
144
Paul Duffin13879572019-11-28 14:31:38 +0000145// Collect all the members.
146//
Paul Duffinb97b1572021-04-29 21:50:40 +0100147// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
148// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000149func (s *sdk) collectMembers(ctx android.ModuleContext) {
150 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000151 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
152 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf7b3d0d2021-09-02 14:29:21 +0100153 if memberTag, ok := tag.(android.SdkMemberDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100154 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900155
Paul Duffin5cca7c42021-05-26 10:16:01 +0100156 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
157 if memberType == nil {
158 return false
159 }
160
Paul Duffin13879572019-11-28 14:31:38 +0000161 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000162 if !memberType.IsInstance(child) {
163 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900164 }
Paul Duffin13879572019-11-28 14:31:38 +0000165
Paul Duffin6a7e9532020-03-20 17:50:07 +0000166 // Keep track of which multilib variants are used by the sdk.
167 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
168
Paul Duffinb97b1572021-04-29 21:50:40 +0100169 var exportedComponentsInfo android.ExportedComponentsInfo
170 if ctx.OtherModuleHasProvider(child, android.ExportedComponentsInfoProvider) {
171 exportedComponentsInfo = ctx.OtherModuleProvider(child, android.ExportedComponentsInfoProvider).(android.ExportedComponentsInfo)
172 }
173
Paul Duffinc6ba1822022-05-06 09:38:02 +0000174 var container android.SdkAware
175 if parent != ctx.Module() {
176 container = parent.(android.SdkAware)
177 }
178
Paul Duffin1938dba2022-07-26 23:53:00 +0000179 minApiLevel := android.MinApiLevelForSdkSnapshot(ctx, child)
180
Paul Duffina7208112021-04-23 21:20:20 +0100181 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100182 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
Paul Duffinc6ba1822022-05-06 09:38:02 +0000183 sdkVariant: s,
184 memberType: memberType,
185 variant: child.(android.SdkAware),
Paul Duffin1938dba2022-07-26 23:53:00 +0000186 minApiLevel: minApiLevel,
Paul Duffinc6ba1822022-05-06 09:38:02 +0000187 container: container,
188 export: export,
189 exportedComponentsInfo: exportedComponentsInfo,
Paul Duffinb97b1572021-04-29 21:50:40 +0100190 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000191
Paul Duffin2d3da312021-05-06 12:02:27 +0100192 // Recurse down into the member's dependencies as it may have dependencies that need to be
193 // automatically added to the sdk.
194 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900195 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000196
197 return false
Paul Duffin13879572019-11-28 14:31:38 +0000198 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000199}
200
Paul Duffincc3132e2021-04-24 01:10:30 +0100201// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
202// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000203//
Paul Duffincc3132e2021-04-24 01:10:30 +0100204// The sdkMember instances are then grouped into slices by member type. Within each such slice the
205// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000206//
Paul Duffincc3132e2021-04-24 01:10:30 +0100207// Finally, the member type slices are concatenated together to form a single slice. The order in
208// which they are concatenated is the order in which the member types were registered in the
209// android.SdkMemberTypesRegistry.
Paul Duffinf861df72022-07-01 15:56:06 +0000210func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, targetBuildRelease *buildRelease, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000211 byType := make(map[android.SdkMemberType][]*sdkMember)
212 byName := make(map[string]*sdkMember)
213
Paul Duffin21827262021-04-24 12:16:36 +0100214 for _, memberVariantDep := range memberVariantDeps {
215 memberType := memberVariantDep.memberType
216 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000217
218 name := ctx.OtherModuleName(variant)
219 member := byName[name]
220 if member == nil {
221 member = &sdkMember{memberType: memberType, name: name}
222 byName[name] = member
223 byType[memberType] = append(byType[memberType], member)
Liz Kammer96320df2022-05-12 20:40:00 -0400224 } else if member.memberType != memberType {
225 // validate whether this is the same member type or and overriding member type
226 if memberType.Overrides(member.memberType) {
227 member.memberType = memberType
228 } else if !member.memberType.Overrides(memberType) {
229 ctx.ModuleErrorf("Incompatible member types %q %q", member.memberType, memberType)
230 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000231 }
232
Paul Duffin1356d8c2020-02-25 19:26:33 +0000233 // Only append new variants to the list. This is needed because a member can be both
234 // exported by the sdk and also be a transitive sdk member.
235 member.variants = appendUniqueVariants(member.variants, variant)
236 }
Paul Duffin13879572019-11-28 14:31:38 +0000237 var members []*sdkMember
Paul Duffin62782de2021-07-14 12:05:16 +0100238 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffinf861df72022-07-01 15:56:06 +0000239 memberType := memberListProperty.memberType
240
241 if !isMemberTypeSupportedByTargetBuildRelease(memberType, targetBuildRelease) {
242 continue
243 }
244
245 membersOfType := byType[memberType]
Paul Duffin13879572019-11-28 14:31:38 +0000246 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900247 }
248
Paul Duffin6a7e9532020-03-20 17:50:07 +0000249 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900250}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900251
Paul Duffinf861df72022-07-01 15:56:06 +0000252// isMemberTypeSupportedByTargetBuildRelease returns true if the member type is supported by the
253// target build release.
254func isMemberTypeSupportedByTargetBuildRelease(memberType android.SdkMemberType, targetBuildRelease *buildRelease) bool {
255 supportedByTargetBuildRelease := true
256 supportedBuildReleases := memberType.SupportedBuildReleases()
257 if supportedBuildReleases == "" {
258 supportedBuildReleases = "S+"
259 }
260
261 set, err := parseBuildReleaseSet(supportedBuildReleases)
262 if err != nil {
263 panic(fmt.Errorf("member type %s has invalid supported build releases %q: %s",
264 memberType.SdkPropertyName(), supportedBuildReleases, err))
265 }
266 if !set.contains(targetBuildRelease) {
267 supportedByTargetBuildRelease = false
268 }
269 return supportedByTargetBuildRelease
270}
271
Paul Duffin72910952020-01-20 18:16:30 +0000272func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
273 for _, v := range variants {
274 if v == newVariant {
275 return variants
276 }
277 }
278 return append(variants, newVariant)
279}
280
Paul Duffin51509a12022-04-06 12:48:09 +0000281// BUILD_NUMBER_FILE is the name of the file in the snapshot zip that will contain the number of
282// the build from which the snapshot was produced.
283const BUILD_NUMBER_FILE = "snapshot-creation-build-number.txt"
284
Jiyong Park73c54ee2019-10-22 20:31:18 +0900285// SDK directory structure
286// <sdk_root>/
287// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
288// <api_ver>/ : below this directory are all auto-generated
289// Android.bp : definition of 'sdk_snapshot' module is here
290// aidl/
291// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
292// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900293// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900294// include/
295// bionic/libc/include/stdlib.h : an exported header file
296// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900297// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900298// <arch>/include/ : arch-specific exported headers
299// <arch>/include_gen/ : arch-specific generated headers
300// <arch>/lib/
301// libFoo.so : a stub library
302
Paul Duffin1938dba2022-07-26 23:53:00 +0000303func (s sdk) targetBuildRelease(ctx android.ModuleContext) *buildRelease {
304 config := ctx.Config()
305 targetBuildReleaseEnv := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE", buildReleaseCurrent.name)
306 targetBuildRelease, err := nameToRelease(targetBuildReleaseEnv)
307 if err != nil {
308 ctx.ModuleErrorf("invalid SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE: %s", err)
309 targetBuildRelease = buildReleaseCurrent
310 }
311
312 return targetBuildRelease
313}
314
Jiyong Park232e7852019-11-04 12:23:40 +0900315// buildSnapshot is the main function in this source file. It creates rules to copy
316// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffinc6ba1822022-05-06 09:38:02 +0000317func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000318
Paul Duffin1938dba2022-07-26 23:53:00 +0000319 targetBuildRelease := s.targetBuildRelease(ctx)
320 targetApiLevel, err := android.ApiLevelFromUser(ctx, targetBuildRelease.name)
321 if err != nil {
322 targetApiLevel = android.FutureApiLevel
323 }
324
Paul Duffinb97b1572021-04-29 21:50:40 +0100325 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100326 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100327 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000328 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100329 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100330 }
Paul Duffin865171e2020-03-02 18:38:15 +0000331
Paul Duffinb97b1572021-04-29 21:50:40 +0100332 // Filter out any sdkMemberVariantDep that is a component of another.
333 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000334
Paul Duffin1938dba2022-07-26 23:53:00 +0000335 // Record the names of all the members, both explicitly specified and implicitly included. Also,
336 // record the names of any members that should be excluded from this snapshot.
Paul Duffinb97b1572021-04-29 21:50:40 +0100337 allMembersByName := make(map[string]struct{})
338 exportedMembersByName := make(map[string]struct{})
Paul Duffin1938dba2022-07-26 23:53:00 +0000339 excludedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100340
Paul Duffin1938dba2022-07-26 23:53:00 +0000341 addMember := func(name string, export bool, exclude bool) {
342 if exclude {
343 excludedMembersByName[name] = struct{}{}
344 return
345 }
346
Paul Duffinb97b1572021-04-29 21:50:40 +0100347 allMembersByName[name] = struct{}{}
348 if export {
349 exportedMembersByName[name] = struct{}{}
350 }
351 }
352
353 for _, memberVariantDep := range memberVariantDeps {
354 name := memberVariantDep.variant.Name()
355 export := memberVariantDep.export
356
Paul Duffin1938dba2022-07-26 23:53:00 +0000357 // If the minApiLevel of the member is greater than the target API level then exclude it from
358 // this snapshot.
359 exclude := memberVariantDep.minApiLevel.GreaterThan(targetApiLevel)
360
361 addMember(name, export, exclude)
Paul Duffinb97b1572021-04-29 21:50:40 +0100362
363 // Add any components provided by the module.
364 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
Paul Duffin1938dba2022-07-26 23:53:00 +0000365 addMember(component, export, exclude)
Paul Duffinb97b1572021-04-29 21:50:40 +0100366 }
367
368 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
369 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000370 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000371 }
372
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000373 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900374
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000375 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000376
377 bpFile := &bpFile{
378 modules: make(map[string]*bpModule),
379 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000380
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000381 // Always add -current to the end
382 snapshotFileSuffix := "-current"
Paul Duffin43f7bf02021-05-05 22:00:51 +0100383
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000384 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000385 ctx: ctx,
386 sdk: s,
Paul Duffin13f02712020-03-06 12:30:43 +0000387 snapshotDir: snapshotDir.OutputPath,
388 copies: make(map[string]string),
389 filesToZip: []android.Path{bp.path},
390 bpFile: bpFile,
391 prebuiltModules: make(map[string]*bpModule),
392 allMembersByName: allMembersByName,
393 exportedMembersByName: exportedMembersByName,
Paul Duffin1938dba2022-07-26 23:53:00 +0000394 excludedMembersByName: excludedMembersByName,
Paul Duffin39abf8f2021-09-24 14:58:27 +0100395 targetBuildRelease: targetBuildRelease,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900396 }
Paul Duffinac37c502019-11-26 18:02:20 +0000397 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900398
Paul Duffin62131702021-05-07 01:10:01 +0100399 // If the sdk snapshot includes any license modules then add a package module which has a
400 // default_applicable_licenses property. That will prevent the LSC license process from updating
401 // the generated Android.bp file to add a package module that includes all licenses used by all
402 // the modules in that package. That would be unnecessary as every module in the sdk should have
403 // their own licenses property specified.
404 if hasLicenses {
405 pkg := bpFile.newModule("package")
406 property := "default_applicable_licenses"
407 pkg.AddCommentForProperty(property, `
408A default list here prevents the license LSC from adding its own list which would
409be unnecessary as every module in the sdk already has its own licenses property.
410`)
411 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
412 bpFile.AddModule(pkg)
413 }
414
Paul Duffin0df49682021-05-07 01:10:01 +0100415 // Group the variants for each member module together and then group the members of each member
416 // type together.
Paul Duffinf861df72022-07-01 15:56:06 +0000417 members := s.groupMemberVariantsByMemberThenType(ctx, targetBuildRelease, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100418
419 // Create the prebuilt modules for each of the member modules.
Paul Duffind19f8942021-07-14 12:08:37 +0100420 traits := s.gatherTraits()
Paul Duffin13ad94f2020-02-19 16:19:27 +0000421 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000422 memberType := member.memberType
Paul Duffin4e7d1c42022-05-13 13:12:19 +0000423 if !memberType.ArePrebuiltsRequired() {
424 continue
425 }
Paul Duffin3a4eb502020-03-19 16:11:18 +0000426
Paul Duffind19f8942021-07-14 12:08:37 +0100427 name := member.name
Paul Duffin1938dba2022-07-26 23:53:00 +0000428 if _, ok := excludedMembersByName[name]; ok {
429 continue
430 }
431
Paul Duffind19f8942021-07-14 12:08:37 +0100432 requiredTraits := traits[name]
433 if requiredTraits == nil {
434 requiredTraits = android.EmptySdkMemberTraitSet()
435 }
436
437 // Create the snapshot for the member.
438 memberCtx := &memberContext{ctx, builder, memberType, name, requiredTraits}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000439
440 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100441 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900442 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900443
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000444 // Create a transformer that will transform a module by replacing any references
Paul Duffin72910952020-01-20 18:16:30 +0000445 // to internal members with a unique module name and setting prefer: false.
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000446 snapshotTransformer := snapshotTransformation{
Paul Duffin64fb5262021-05-05 21:36:04 +0100447 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100448 }
Paul Duffin72910952020-01-20 18:16:30 +0000449
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000450 for _, module := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000451 // Prune any empty property sets.
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000452 module = module.transform(pruneEmptySetTransformer{})
Paul Duffina78f3a72020-02-21 16:29:35 +0000453
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000454 // Transform the module module to make it suitable for use in the snapshot.
455 module.transform(snapshotTransformer)
456 bpFile.AddModule(module)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100457 }
Paul Duffin26197a62021-04-24 00:34:10 +0100458
459 // generate Android.bp
460 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
461 generateBpContents(&bp.generatedContents, bpFile)
462
463 contents := bp.content.String()
Paul Duffin39abf8f2021-09-24 14:58:27 +0100464 // If the snapshot is being generated for the current build release then check the syntax to make
465 // sure that it is compatible.
Paul Duffin42a49f12022-08-17 22:09:55 +0000466 if targetBuildRelease == buildReleaseCurrent {
Paul Duffin39abf8f2021-09-24 14:58:27 +0100467 syntaxCheckSnapshotBpFile(ctx, contents)
468 }
Paul Duffin26197a62021-04-24 00:34:10 +0100469
470 bp.build(pctx, ctx, nil)
471
Paul Duffin51509a12022-04-06 12:48:09 +0000472 // Copy the build number file into the snapshot.
473 builder.CopyToSnapshot(ctx.Config().BuildNumberFile(ctx), BUILD_NUMBER_FILE)
474
Paul Duffin74f1dcd2022-07-18 13:18:23 +0000475 filesToZip := android.SortedUniquePaths(builder.filesToZip)
Paul Duffin26197a62021-04-24 00:34:10 +0100476
477 // zip them all
Paul Duffinc6ba1822022-05-06 09:38:02 +0000478 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100479 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100480 outputDesc := "Building snapshot for " + ctx.ModuleName()
481
482 // If there are no zips to merge then generate the output zip directly.
483 // Otherwise, generate an intermediate zip file into which other zips can be
484 // merged.
485 var zipFile android.OutputPath
486 var desc string
487 if len(builder.zipsToMerge) == 0 {
488 zipFile = outputZipFile
489 desc = outputDesc
490 } else {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000491 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100492 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100493 desc = "Building intermediate snapshot for " + ctx.ModuleName()
494 }
495
496 ctx.Build(pctx, android.BuildParams{
497 Description: desc,
498 Rule: zipFiles,
499 Inputs: filesToZip,
500 Output: zipFile,
501 Args: map[string]string{
502 "basedir": builder.snapshotDir.String(),
503 },
504 })
505
506 if len(builder.zipsToMerge) != 0 {
507 ctx.Build(pctx, android.BuildParams{
508 Description: outputDesc,
509 Rule: mergeZips,
510 Input: zipFile,
Paul Duffin74f1dcd2022-07-18 13:18:23 +0000511 Inputs: android.SortedUniquePaths(builder.zipsToMerge),
Paul Duffin26197a62021-04-24 00:34:10 +0100512 Output: outputZipFile,
513 })
514 }
515
Paul Duffinc6ba1822022-05-06 09:38:02 +0000516 modules := s.generateInfoData(ctx, memberVariantDeps)
517
518 // Output the modules information as pretty printed JSON.
519 info := newGeneratedFile(ctx, fmt.Sprintf("%s%s.info", ctx.ModuleName(), snapshotFileSuffix))
520 output, err := json.MarshalIndent(modules, "", " ")
521 if err != nil {
522 ctx.ModuleErrorf("error generating %q: %s", info, err)
523 }
524 builder.infoContents = string(output)
525 info.generatedContents.UnindentedPrintf("%s", output)
526 info.build(pctx, ctx, nil)
527 infoPath := info.path
528 installedInfo := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), infoPath.Base(), infoPath)
529 s.infoFile = android.OptionalPathForPath(installedInfo)
530
531 // Install the zip, making sure that the info file has been installed as well.
532 installedZip := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), outputZipFile.Base(), outputZipFile, installedInfo)
533 s.snapshotFile = android.OptionalPathForPath(installedZip)
534}
535
536type moduleInfo struct {
537 // The type of the module, e.g. java_sdk_library
538 moduleType string
539 // The name of the module.
540 name string
541 // A list of additional dependencies of the module.
542 deps []string
Paul Duffin958806b2022-05-16 13:10:47 +0000543 // Additional member specific properties.
544 // These will be added into the generated JSON alongside the above properties.
545 memberSpecific map[string]interface{}
Paul Duffinc6ba1822022-05-06 09:38:02 +0000546}
547
548func (m *moduleInfo) MarshalJSON() ([]byte, error) {
549 buffer := bytes.Buffer{}
550
551 separator := ""
552 writeObjectPair := func(key string, value interface{}) {
553 buffer.WriteString(fmt.Sprintf("%s%q: ", separator, key))
554 b, err := json.Marshal(value)
555 if err != nil {
556 panic(err)
557 }
558 buffer.Write(b)
559 separator = ","
560 }
561
562 buffer.WriteString("{")
563 writeObjectPair("@type", m.moduleType)
564 writeObjectPair("@name", m.name)
565 if m.deps != nil {
566 writeObjectPair("@deps", m.deps)
567 }
Paul Duffin958806b2022-05-16 13:10:47 +0000568 for _, k := range android.SortedStringKeys(m.memberSpecific) {
569 v := m.memberSpecific[k]
Paul Duffinc6ba1822022-05-06 09:38:02 +0000570 writeObjectPair(k, v)
571 }
572 buffer.WriteString("}")
573 return buffer.Bytes(), nil
574}
575
576var _ json.Marshaler = (*moduleInfo)(nil)
577
578// generateInfoData creates a list of moduleInfo structures that will be marshalled into JSON.
579func (s *sdk) generateInfoData(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) interface{} {
580 modules := []*moduleInfo{}
581 sdkInfo := moduleInfo{
Paul Duffin958806b2022-05-16 13:10:47 +0000582 moduleType: "sdk",
583 name: ctx.ModuleName(),
584 memberSpecific: map[string]interface{}{},
Paul Duffinc6ba1822022-05-06 09:38:02 +0000585 }
586 modules = append(modules, &sdkInfo)
587
588 name2Info := map[string]*moduleInfo{}
589 getModuleInfo := func(module android.Module) *moduleInfo {
590 name := module.Name()
591 info := name2Info[name]
592 if info == nil {
593 moduleType := ctx.OtherModuleType(module)
594 // Remove any suffix added when creating modules dynamically.
595 moduleType = strings.Split(moduleType, "__")[0]
596 info = &moduleInfo{
597 moduleType: moduleType,
598 name: name,
599 }
Paul Duffin958806b2022-05-16 13:10:47 +0000600
601 additionalSdkInfo := ctx.OtherModuleProvider(module, android.AdditionalSdkInfoProvider).(android.AdditionalSdkInfo)
602 info.memberSpecific = additionalSdkInfo.Properties
603
Paul Duffinc6ba1822022-05-06 09:38:02 +0000604 name2Info[name] = info
605 }
606 return info
607 }
608
609 for _, memberVariantDep := range memberVariantDeps {
610 propertyName := memberVariantDep.memberType.SdkPropertyName()
611 var list []string
Paul Duffin958806b2022-05-16 13:10:47 +0000612 if v, ok := sdkInfo.memberSpecific[propertyName]; ok {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000613 list = v.([]string)
614 }
615
616 memberName := memberVariantDep.variant.Name()
617 list = append(list, memberName)
Paul Duffin958806b2022-05-16 13:10:47 +0000618 sdkInfo.memberSpecific[propertyName] = android.SortedUniqueStrings(list)
Paul Duffinc6ba1822022-05-06 09:38:02 +0000619
620 if memberVariantDep.container != nil {
621 containerInfo := getModuleInfo(memberVariantDep.container)
622 containerInfo.deps = android.SortedUniqueStrings(append(containerInfo.deps, memberName))
623 }
624
625 // Make sure that the module info is created for each module.
626 getModuleInfo(memberVariantDep.variant)
627 }
628
629 for _, memberName := range android.SortedStringKeys(name2Info) {
630 info := name2Info[memberName]
631 modules = append(modules, info)
632 }
633
634 return modules
Paul Duffin26197a62021-04-24 00:34:10 +0100635}
636
Paul Duffinb97b1572021-04-29 21:50:40 +0100637// filterOutComponents removes any item from the deps list that is a component of another item in
638// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
639// then it will remove "foo.stubs" from the deps.
640func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
641 // Collate the set of components that all the modules added to the sdk provide.
642 components := map[string]*sdkMemberVariantDep{}
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000643 for i := range deps {
Paul Duffinb97b1572021-04-29 21:50:40 +0100644 dep := &deps[i]
645 for _, c := range dep.exportedComponentsInfo.Components {
646 components[c] = dep
647 }
648 }
649
650 // If no module provides components then return the input deps unfiltered.
651 if len(components) == 0 {
652 return deps
653 }
654
655 filtered := make([]sdkMemberVariantDep, 0, len(deps))
656 for _, dep := range deps {
657 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
658 if owner, ok := components[name]; ok {
659 // This is a component of another module that is a member of the sdk.
660
661 // If the component is exported but the owning module is not then the configuration is not
662 // supported.
663 if dep.export && !owner.export {
664 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
665 continue
666 }
667
668 // This module must not be added to the list of members of the sdk as that would result in a
669 // duplicate module in the sdk snapshot.
670 continue
671 }
672
673 filtered = append(filtered, dep)
674 }
675 return filtered
676}
677
Paul Duffinf88d8e02020-05-07 20:21:34 +0100678// Check the syntax of the generated Android.bp file contents and if they are
679// invalid then log an error with the contents (tagged with line numbers) and the
680// errors that were found so that it is easy to see where the problem lies.
681func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
682 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
683 if len(errs) != 0 {
684 message := &strings.Builder{}
685 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
686
687Generated Android.bp contents
688========================================================================
689`)
690 for i, line := range strings.Split(contents, "\n") {
691 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
692 }
693
694 _, _ = fmt.Fprint(message, `
695========================================================================
696
697Errors found:
698`)
699
700 for _, err := range errs {
701 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
702 }
703
704 ctx.ModuleErrorf("%s", message.String())
705 }
706}
707
Paul Duffin4b8b7932020-05-06 12:35:38 +0100708func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
709 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
710 if err != nil {
711 ctx.ModuleErrorf("error extracting common properties: %s", err)
712 }
713}
714
Paul Duffinfbe470e2021-04-24 12:37:13 +0100715// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
716type snapshotModuleStaticProperties struct {
717 Compile_multilib string `android:"arch_variant"`
718}
719
Paul Duffin2d1bb892021-04-24 11:32:59 +0100720// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
721type combinedSnapshotModuleProperties struct {
722 // The sdk variant from which this information was collected.
723 sdkVariant *sdk
724
725 // Static snapshot module properties.
726 staticProperties *snapshotModuleStaticProperties
727
728 // The dynamically generated member list properties.
729 dynamicProperties interface{}
730}
731
732// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100733func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
734 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100735 var list []*combinedSnapshotModuleProperties
736 for _, sdkVariant := range sdkVariants {
737 staticProperties := &snapshotModuleStaticProperties{
738 Compile_multilib: sdkVariant.multilibUsages.String(),
739 }
Paul Duffin62782de2021-07-14 12:05:16 +0100740 dynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100741
Paul Duffincd064672021-04-24 00:47:29 +0100742 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100743 sdkVariant: sdkVariant,
744 staticProperties: staticProperties,
745 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100746 }
747 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
748
749 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100750 }
Paul Duffincd064672021-04-24 00:47:29 +0100751
752 for _, memberVariantDep := range memberVariantDeps {
753 // If the member dependency is internal then do not add the dependency to the snapshot member
754 // list properties.
755 if !memberVariantDep.export {
756 continue
757 }
758
759 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin62782de2021-07-14 12:05:16 +0100760 memberListProperty := s.memberTypeListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100761 memberName := ctx.OtherModuleName(memberVariantDep.variant)
762
Paul Duffin13082052021-05-11 00:31:38 +0100763 if memberListProperty.getter == nil {
764 continue
765 }
766
Paul Duffincd064672021-04-24 00:47:29 +0100767 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100768 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100769 if !android.InList(memberName, memberList) {
770 memberList = append(memberList, memberName)
771 }
Paul Duffin13082052021-05-11 00:31:38 +0100772 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100773 }
774
Paul Duffin2d1bb892021-04-24 11:32:59 +0100775 return list
776}
777
778func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
779
780 // Extract the dynamic properties and add them to a list of propertiesContainer.
781 propertyContainers := []propertiesContainer{}
782 for _, i := range list {
783 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
784 sdkVariant: i.sdkVariant,
785 properties: i.dynamicProperties,
786 })
787 }
788
789 // Extract the common members, removing them from the original properties.
Paul Duffin62782de2021-07-14 12:05:16 +0100790 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100791 extractor := newCommonValueExtractor(commonDynamicProperties)
792 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
793
794 // Extract the static properties and add them to a list of propertiesContainer.
795 propertyContainers = []propertiesContainer{}
796 for _, i := range list {
797 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
798 sdkVariant: i.sdkVariant,
799 properties: i.staticProperties,
800 })
801 }
802
803 commonStaticProperties := &snapshotModuleStaticProperties{}
804 extractor = newCommonValueExtractor(commonStaticProperties)
805 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
806
807 return &combinedSnapshotModuleProperties{
808 sdkVariant: nil,
809 staticProperties: commonStaticProperties,
810 dynamicProperties: commonDynamicProperties,
811 }
812}
813
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000814type propertyTag struct {
815 name string
816}
817
Paul Duffin94289702021-09-09 15:38:32 +0100818var _ android.BpPropertyTag = propertyTag{}
819
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000820// BpPropertyTag instances to add to a property that contains references to other sdk members.
Paul Duffin0cb37b92020-03-04 14:52:46 +0000821//
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000822// These will ensure that the referenced modules are available, if required.
Paul Duffin13f02712020-03-06 12:30:43 +0000823var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000824var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000825
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000826type snapshotTransformation struct {
Paul Duffine6c0d842020-01-15 14:08:51 +0000827 identityTransformation
828 builder *snapshotBuilder
829}
830
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000831func (t snapshotTransformation) transformModule(module *bpModule) *bpModule {
Paul Duffin72910952020-01-20 18:16:30 +0000832 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100833 name := module.Name()
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000834 module.setProperty("name", t.builder.snapshotSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000835 return module
836}
837
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000838func (t snapshotTransformation) transformProperty(_ string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000839 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
840 required := tag == requiredSdkMemberReferencePropertyTag
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000841 return t.builder.snapshotSdkMemberNames(value.([]string), required), tag
Paul Duffin72910952020-01-20 18:16:30 +0000842 } else {
843 return value, tag
844 }
845}
846
Paul Duffina78f3a72020-02-21 16:29:35 +0000847type pruneEmptySetTransformer struct {
848 identityTransformation
849}
850
851var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
852
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000853func (t pruneEmptySetTransformer) transformPropertySetAfterContents(_ string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
Paul Duffina78f3a72020-02-21 16:29:35 +0000854 if len(propertySet.properties) == 0 {
855 return nil, nil
856 } else {
857 return propertySet, tag
858 }
859}
860
Paul Duffinb645ec82019-11-27 17:43:54 +0000861func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100862 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000863 for _, bpModule := range bpFile.order {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000864 contents.IndentedPrintf("\n")
865 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
866 outputPropertySet(contents, bpModule.bpPropertySet)
867 contents.IndentedPrintf("}\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000868 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000869}
870
871func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
872 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000873
Paul Duffin0df49682021-05-07 01:10:01 +0100874 addComment := func(name string) {
875 if text, ok := set.comments[name]; ok {
876 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100877 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100878 }
879 }
880 }
881
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000882 // Output the properties first, followed by the nested sets. This ensures a
883 // consistent output irrespective of whether property sets are created before
884 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000885 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000886 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000887
Paul Duffin0df49682021-05-07 01:10:01 +0100888 // Do not write property sets in the properties phase.
889 if _, ok := value.(*bpPropertySet); ok {
890 continue
891 }
892
893 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100894 reflectValue := reflect.ValueOf(value)
895 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000896 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000897
898 for _, name := range set.order {
899 value := set.getValue(name)
900
901 // Only write property sets in the sets phase.
902 switch v := value.(type) {
903 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100904 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100905 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000906 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100907 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000908 }
909 }
910
Paul Duffinb645ec82019-11-27 17:43:54 +0000911 contents.Dedent()
912}
913
Paul Duffina08e4dc2021-06-22 18:19:19 +0100914// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
915// by the value and then followed by a , and a newline.
916func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
917 contents.IndentedPrintf("%s: ", name)
918 outputUnnamedValue(contents, value)
919 contents.UnindentedPrintf(",\n")
920}
921
922// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
923// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
924// indented and all but the last line will end with a newline.
925func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
926 valueType := value.Type()
927 switch valueType.Kind() {
928 case reflect.Bool:
929 contents.UnindentedPrintf("%t", value.Bool())
930
931 case reflect.String:
932 contents.UnindentedPrintf("%q", value)
933
Paul Duffin51227d82021-05-18 12:54:27 +0100934 case reflect.Ptr:
935 outputUnnamedValue(contents, value.Elem())
936
Paul Duffina08e4dc2021-06-22 18:19:19 +0100937 case reflect.Slice:
938 length := value.Len()
939 if length == 0 {
940 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100941 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100942 firstValue := value.Index(0)
943 if length == 1 && !multiLineValue(firstValue) {
944 contents.UnindentedPrintf("[")
945 outputUnnamedValue(contents, firstValue)
946 contents.UnindentedPrintf("]")
947 } else {
948 contents.UnindentedPrintf("[\n")
949 contents.Indent()
950 for i := 0; i < length; i++ {
951 itemValue := value.Index(i)
952 contents.IndentedPrintf("")
953 outputUnnamedValue(contents, itemValue)
954 contents.UnindentedPrintf(",\n")
955 }
956 contents.Dedent()
957 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100958 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100959 }
960
Paul Duffin51227d82021-05-18 12:54:27 +0100961 case reflect.Struct:
962 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
963 v := value.Interface()
964 if _, ok := v.(android.BpPrintable); !ok {
965 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
966 }
967 contents.UnindentedPrintf("{\n")
968 contents.Indent()
969 for f := 0; f < valueType.NumField(); f++ {
970 fieldType := valueType.Field(f)
971 if fieldType.Anonymous {
972 continue
973 }
974 fieldValue := value.Field(f)
975 fieldName := fieldType.Name
976 propertyName := proptools.PropertyNameForField(fieldName)
977 outputNamedValue(contents, propertyName, fieldValue)
978 }
979 contents.Dedent()
980 contents.IndentedPrintf("}")
981
Paul Duffina08e4dc2021-06-22 18:19:19 +0100982 default:
983 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
984 }
985}
986
Paul Duffin51227d82021-05-18 12:54:27 +0100987// multiLineValue returns true if the supplied value may require multiple lines in the output.
988func multiLineValue(value reflect.Value) bool {
989 kind := value.Kind()
990 return kind == reflect.Slice || kind == reflect.Struct
991}
992
Paul Duffinac37c502019-11-26 18:02:20 +0000993func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000994 contents := &generatedContents{}
995 generateBpContents(contents, s.builderForTests.bpFile)
996 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000997}
998
Paul Duffinc6ba1822022-05-06 09:38:02 +0000999func (s *sdk) GetInfoContentsForTests() string {
1000 return s.builderForTests.infoContents
1001}
1002
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001003type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +01001004 ctx android.ModuleContext
1005 sdk *sdk
1006
Paul Duffinb645ec82019-11-27 17:43:54 +00001007 snapshotDir android.OutputPath
1008 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +00001009
1010 // Map from destination to source of each copy - used to eliminate duplicates and
1011 // detect conflicts.
1012 copies map[string]string
1013
Paul Duffinb645ec82019-11-27 17:43:54 +00001014 filesToZip android.Paths
1015 zipsToMerge android.Paths
1016
1017 prebuiltModules map[string]*bpModule
1018 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001019
1020 // The set of all members by name.
1021 allMembersByName map[string]struct{}
1022
1023 // The set of exported members by name.
1024 exportedMembersByName map[string]struct{}
Paul Duffin39abf8f2021-09-24 14:58:27 +01001025
Paul Duffin1938dba2022-07-26 23:53:00 +00001026 // The set of members which have been excluded from this snapshot; by name.
1027 excludedMembersByName map[string]struct{}
1028
Paul Duffin39abf8f2021-09-24 14:58:27 +01001029 // The target build release for which the snapshot is to be generated.
1030 targetBuildRelease *buildRelease
Paul Duffinc6ba1822022-05-06 09:38:02 +00001031
Paul Duffin958806b2022-05-16 13:10:47 +00001032 // The contents of the .info file that describes the sdk contents.
Paul Duffinc6ba1822022-05-06 09:38:02 +00001033 infoContents string
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001034}
1035
1036func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001037 if existing, ok := s.copies[dest]; ok {
1038 if existing != src.String() {
1039 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1040 return
1041 }
1042 } else {
1043 path := s.snapshotDir.Join(s.ctx, dest)
1044 s.ctx.Build(pctx, android.BuildParams{
1045 Rule: android.Cp,
1046 Input: src,
1047 Output: path,
1048 })
1049 s.filesToZip = append(s.filesToZip, path)
1050
1051 s.copies[dest] = src.String()
1052 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001053}
1054
Paul Duffin91547182019-11-12 19:39:36 +00001055func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1056 ctx := s.ctx
1057
1058 // Repackage the zip file so that the entries are in the destDir directory.
1059 // This will allow the zip file to be merged into the snapshot.
1060 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001061
1062 ctx.Build(pctx, android.BuildParams{
1063 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1064 Rule: repackageZip,
1065 Input: zipPath,
1066 Output: tmpZipPath,
1067 Args: map[string]string{
1068 "destdir": destDir,
1069 },
1070 })
Paul Duffin91547182019-11-12 19:39:36 +00001071
1072 // Add the repackaged zip file to the files to merge.
1073 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1074}
1075
Paul Duffin9d8d6092019-12-05 18:19:29 +00001076func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1077 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001078 if s.prebuiltModules[name] != nil {
1079 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1080 }
1081
1082 m := s.bpFile.newModule(moduleType)
1083 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001084
Paul Duffinbefa4b92020-03-04 14:22:45 +00001085 variant := member.Variants()[0]
1086
Paul Duffin13f02712020-03-06 12:30:43 +00001087 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001088 // An internal member is only referenced from the sdk snapshot which is in the
1089 // same package so can be marked as private.
1090 m.AddProperty("visibility", []string{"//visibility:private"})
1091 } else {
1092 // Extract visibility information from a member variant. All variants have the same
1093 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001094 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1095
1096 // Add any additional visibility rules needed for the prebuilts to reference each other.
1097 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1098 if err != nil {
1099 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1100 }
1101
1102 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001103 if len(visibility) != 0 {
1104 m.AddProperty("visibility", visibility)
1105 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001106 }
1107
Martin Stjernholm1e041092020-11-03 00:11:09 +00001108 // Where available copy apex_available properties from the member.
1109 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1110 apexAvailable := apexAware.ApexAvailable()
1111 if len(apexAvailable) == 0 {
1112 // //apex_available:platform is the default.
1113 apexAvailable = []string{android.AvailableToPlatform}
1114 }
1115
1116 // Add in any baseline apex available settings.
1117 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1118
1119 // Remove duplicates and sort.
1120 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1121 sort.Strings(apexAvailable)
1122
1123 m.AddProperty("apex_available", apexAvailable)
1124 }
1125
Paul Duffinb0bb3762021-05-06 16:48:05 +01001126 // The licenses are the same for all variants.
1127 mctx := s.ctx
1128 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1129 if len(licenseInfo.Licenses) > 0 {
1130 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1131 }
1132
Paul Duffin865171e2020-03-02 18:38:15 +00001133 deviceSupported := false
1134 hostSupported := false
1135
1136 for _, variant := range member.Variants() {
1137 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001138 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001139 hostSupported = true
1140 } else if osClass == android.Device {
1141 deviceSupported = true
1142 }
1143 }
1144
1145 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001146
1147 s.prebuiltModules[name] = m
1148 s.prebuiltOrder = append(s.prebuiltOrder, m)
1149 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001150}
1151
Paul Duffinc61783b2022-10-20 17:21:40 +01001152func (s *snapshotBuilder) AddInternalModule(properties android.SdkMemberProperties, moduleType string, nameSuffix string) android.BpModule {
1153 name := properties.Name() + "-" + nameSuffix
1154
1155 if s.prebuiltModules[name] != nil {
1156 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1157 }
1158
1159 m := s.bpFile.newModule(moduleType)
1160 m.AddProperty("name", name)
1161 m.AddProperty("visibility", []string{"//visibility:private"})
1162
1163 s.prebuiltModules[name] = m
1164 s.prebuiltOrder = append(s.prebuiltOrder, m)
1165
1166 s.allMembersByName[name] = struct{}{}
1167 return m
1168}
1169
Paul Duffin865171e2020-03-02 18:38:15 +00001170func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001171 // If neither device or host is supported then this module does not support either so will not
1172 // recognize the properties.
1173 if !deviceSupported && !hostSupported {
1174 return
1175 }
1176
Paul Duffin865171e2020-03-02 18:38:15 +00001177 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001178 bpModule.AddProperty("device_supported", false)
1179 }
Paul Duffin865171e2020-03-02 18:38:15 +00001180 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001181 bpModule.AddProperty("host_supported", true)
1182 }
1183}
1184
Paul Duffin13f02712020-03-06 12:30:43 +00001185func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1186 if required {
1187 return requiredSdkMemberReferencePropertyTag
1188 } else {
1189 return optionalSdkMemberReferencePropertyTag
1190 }
1191}
1192
1193func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1194 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001195}
1196
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001197// Get a name for sdk snapshot member. If the member is private then generate a snapshot specific
1198// name. As part of the processing this checks to make sure that any required members are part of
1199// the snapshot.
Paul Duffinc61783b2022-10-20 17:21:40 +01001200func (s *snapshotBuilder) snapshotSdkMemberName(reference string, required bool) string {
1201 prefix := ""
1202 name := strings.TrimPrefix(reference, ":")
1203 if name != reference {
1204 prefix = ":"
1205 }
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001206 if _, ok := s.allMembersByName[name]; !ok {
Paul Duffin13f02712020-03-06 12:30:43 +00001207 if required {
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001208 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", name)
Paul Duffin13f02712020-03-06 12:30:43 +00001209 }
Paul Duffinc61783b2022-10-20 17:21:40 +01001210 return reference
Paul Duffin13f02712020-03-06 12:30:43 +00001211 }
1212
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001213 if s.isInternalMember(name) {
Paul Duffinc61783b2022-10-20 17:21:40 +01001214 return prefix + s.ctx.ModuleName() + "_" + name
Paul Duffin72910952020-01-20 18:16:30 +00001215 } else {
Paul Duffinc61783b2022-10-20 17:21:40 +01001216 return reference
Paul Duffin72910952020-01-20 18:16:30 +00001217 }
1218}
1219
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001220func (s *snapshotBuilder) snapshotSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001221 var references []string = nil
1222 for _, m := range members {
Paul Duffin1938dba2022-07-26 23:53:00 +00001223 if _, ok := s.excludedMembersByName[m]; ok {
1224 continue
1225 }
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001226 references = append(references, s.snapshotSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001227 }
1228 return references
1229}
1230
Paul Duffin13f02712020-03-06 12:30:43 +00001231func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1232 _, ok := s.exportedMembersByName[memberName]
1233 return !ok
1234}
1235
Martin Stjernholm89238f42020-07-10 00:14:03 +01001236// Add the properties from the given SdkMemberProperties to the blueprint
1237// property set. This handles common properties in SdkMemberPropertiesBase and
1238// calls the member-specific AddToPropertySet for the rest.
1239func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1240 if memberProperties.Base().Compile_multilib != "" {
1241 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1242 }
1243
1244 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1245}
1246
Paul Duffin21827262021-04-24 12:16:36 +01001247// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1248type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001249 // The sdk variant that depends (possibly indirectly) on the member variant.
1250 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001251
1252 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001253 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001254
1255 // The variant that is added to the sdk.
1256 variant android.SdkAware
1257
Paul Duffinc6ba1822022-05-06 09:38:02 +00001258 // The optional container of this member, i.e. the module that is depended upon by the sdk
1259 // (possibly transitively) and whose dependency on this module is why it was added to the sdk.
1260 // Is nil if this a direct dependency of the sdk.
1261 container android.SdkAware
1262
Paul Duffinb97b1572021-04-29 21:50:40 +01001263 // True if the member should be exported, i.e. accessible, from outside the sdk.
1264 export bool
1265
1266 // The names of additional component modules provided by the variant.
1267 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1938dba2022-07-26 23:53:00 +00001268
1269 // The minimum API level on which this module is supported.
1270 minApiLevel android.ApiLevel
Paul Duffin1356d8c2020-02-25 19:26:33 +00001271}
1272
Paul Duffin13879572019-11-28 14:31:38 +00001273var _ android.SdkMember = (*sdkMember)(nil)
1274
Paul Duffin21827262021-04-24 12:16:36 +01001275// sdkMember groups all the variants of a specific member module together along with the name of the
1276// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001277type sdkMember struct {
1278 memberType android.SdkMemberType
1279 name string
1280 variants []android.SdkAware
1281}
1282
1283func (m *sdkMember) Name() string {
1284 return m.name
1285}
1286
1287func (m *sdkMember) Variants() []android.SdkAware {
1288 return m.variants
1289}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001290
Paul Duffin9c3760e2020-03-16 19:52:08 +00001291// Track usages of multilib variants.
1292type multilibUsage int
1293
1294const (
1295 multilibNone multilibUsage = 0
1296 multilib32 multilibUsage = 1
1297 multilib64 multilibUsage = 2
1298 multilibBoth = multilib32 | multilib64
1299)
1300
1301// Add the multilib that is used in the arch type.
1302func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1303 multilib := archType.Multilib
1304 switch multilib {
1305 case "":
1306 return m
1307 case "lib32":
1308 return m | multilib32
1309 case "lib64":
1310 return m | multilib64
1311 default:
1312 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1313 }
1314}
1315
1316func (m multilibUsage) String() string {
1317 switch m {
1318 case multilibNone:
1319 return ""
1320 case multilib32:
1321 return "32"
1322 case multilib64:
1323 return "64"
1324 case multilibBoth:
1325 return "both"
1326 default:
1327 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1328 m, multilibNone, multilib32, multilib64, multilibBoth))
1329 }
1330}
1331
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001332// TODO(187910671): BEGIN - Remove once modules do not have an APEX and default variant.
1333// variantCoordinate contains the coordinates used to identify a variant of an SDK member.
1334type variantCoordinate struct {
1335 // osType identifies the OS target of a variant.
1336 osType android.OsType
1337 // archId identifies the architecture and whether it is for the native bridge.
1338 archId archId
1339 // image is the image variant name.
1340 image string
1341 // linkType is the link type name.
1342 linkType string
1343}
1344
1345func getVariantCoordinate(ctx *memberContext, variant android.Module) variantCoordinate {
1346 linkType := ""
1347 if len(ctx.MemberType().SupportedLinkages()) > 0 {
1348 linkType = getLinkType(variant)
1349 }
1350 return variantCoordinate{
1351 osType: variant.Target().Os,
1352 archId: archIdFromTarget(variant.Target()),
1353 image: variant.ImageVariation().Variation,
1354 linkType: linkType,
1355 }
1356}
1357
1358// selectApexVariantsWhereAvailable filters the input list of variants by selecting the APEX
1359// specific variant for a specific variantCoordinate when there is both an APEX and default variant.
1360//
1361// There is a long-standing issue where a module that is added to an APEX has both an APEX and
1362// default/platform variant created even when the module does not require a platform variant. As a
1363// result an indirect dependency onto a module via the APEX will use the APEX variant, whereas a
1364// direct dependency onto the module will use the default/platform variant. That would result in a
1365// failure while attempting to optimize the properties for a member as it would have two variants
1366// when only one was expected.
1367//
1368// This function mitigates that problem by detecting when there are two variants that differ only
1369// by apex variant, where one is the default/platform variant and one is the APEX variant. In that
1370// case it picks the APEX variant. It picks the APEX variant because that is the behavior that would
1371// be expected
1372func selectApexVariantsWhereAvailable(ctx *memberContext, variants []android.SdkAware) []android.SdkAware {
1373 moduleCtx := ctx.sdkMemberContext
1374
1375 // Group the variants by coordinates.
1376 variantsByCoord := make(map[variantCoordinate][]android.SdkAware)
1377 for _, variant := range variants {
1378 coord := getVariantCoordinate(ctx, variant)
1379 variantsByCoord[coord] = append(variantsByCoord[coord], variant)
1380 }
1381
1382 toDiscard := make(map[android.SdkAware]struct{})
1383 for coord, list := range variantsByCoord {
1384 count := len(list)
1385 if count == 1 {
1386 continue
1387 }
1388
1389 variantsByApex := make(map[string]android.SdkAware)
1390 conflictDetected := false
1391 for _, variant := range list {
1392 apexInfo := moduleCtx.OtherModuleProvider(variant, android.ApexInfoProvider).(android.ApexInfo)
1393 apexVariationName := apexInfo.ApexVariationName
1394 // If there are two variants for a specific APEX variation then there is conflict.
1395 if _, ok := variantsByApex[apexVariationName]; ok {
1396 conflictDetected = true
1397 break
1398 }
1399 variantsByApex[apexVariationName] = variant
1400 }
1401
1402 // If there are more than 2 apex variations or one of the apex variations is not the
1403 // default/platform variation then there is a conflict.
1404 if len(variantsByApex) != 2 {
1405 conflictDetected = true
1406 } else if _, ok := variantsByApex[""]; !ok {
1407 conflictDetected = true
1408 }
1409
1410 // If there are no conflicts then add the default/platform variation to the list to remove.
1411 if !conflictDetected {
1412 toDiscard[variantsByApex[""]] = struct{}{}
1413 continue
1414 }
1415
1416 // There are duplicate variants at this coordinate and they are not the default and APEX variant
1417 // so fail.
1418 variantDescriptions := []string{}
1419 for _, m := range list {
1420 variantDescriptions = append(variantDescriptions, fmt.Sprintf(" %s", m.String()))
1421 }
1422
1423 moduleCtx.ModuleErrorf("multiple conflicting variants detected for OsType{%s}, %s, Image{%s}, Link{%s}\n%s",
1424 coord.osType, coord.archId.String(), coord.image, coord.linkType,
1425 strings.Join(variantDescriptions, "\n"))
1426 }
1427
1428 // If there are any variants to discard then remove them from the list of variants, while
1429 // preserving the order.
1430 if len(toDiscard) > 0 {
1431 filtered := []android.SdkAware{}
1432 for _, variant := range variants {
1433 if _, ok := toDiscard[variant]; !ok {
1434 filtered = append(filtered, variant)
1435 }
1436 }
1437 variants = filtered
1438 }
1439
1440 return variants
1441}
1442
1443// TODO(187910671): END - Remove once modules do not have an APEX and default variant.
1444
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001445type baseInfo struct {
1446 Properties android.SdkMemberProperties
1447}
1448
Paul Duffinf34f6d82020-04-30 15:48:31 +01001449func (b *baseInfo) optimizableProperties() interface{} {
1450 return b.Properties
1451}
1452
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001453type osTypeSpecificInfo struct {
1454 baseInfo
1455
Paul Duffin00e46802020-03-12 20:40:35 +00001456 osType android.OsType
1457
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001458 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001459 //
1460 // Nil if there is one variant whose arch type is common
1461 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001462}
1463
Paul Duffin4b8b7932020-05-06 12:35:38 +01001464var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1465
Paul Duffinfc8dd232020-03-17 12:51:37 +00001466type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1467
Paul Duffin00e46802020-03-12 20:40:35 +00001468// Create a new osTypeSpecificInfo for the specified os type and its properties
1469// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001470func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001471 osInfo := &osTypeSpecificInfo{
1472 osType: osType,
1473 }
1474
1475 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1476 properties := variantPropertiesFactory()
1477 properties.Base().Os = osType
1478 return properties
1479 }
1480
1481 // Create a structure into which properties common across the architectures in
1482 // this os type will be stored.
1483 osInfo.Properties = osSpecificVariantPropertiesFactory()
1484
1485 // Group the variants by arch type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001486 var variantsByArchId = make(map[archId][]android.Module)
1487 var archIds []archId
Paul Duffin00e46802020-03-12 20:40:35 +00001488 for _, variant := range osTypeVariants {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001489 target := variant.Target()
1490 id := archIdFromTarget(target)
1491 if _, ok := variantsByArchId[id]; !ok {
1492 archIds = append(archIds, id)
Paul Duffin00e46802020-03-12 20:40:35 +00001493 }
1494
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001495 variantsByArchId[id] = append(variantsByArchId[id], variant)
Paul Duffin00e46802020-03-12 20:40:35 +00001496 }
1497
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001498 if commonVariants, ok := variantsByArchId[commonArchId]; ok {
Paul Duffin00e46802020-03-12 20:40:35 +00001499 if len(osTypeVariants) != 1 {
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001500 variants := []string{}
1501 for _, m := range osTypeVariants {
1502 variants = append(variants, fmt.Sprintf(" %s", m.String()))
1503 }
1504 panic(fmt.Errorf("expected to only have 1 variant of %q when arch type is common but found %d\n%s",
1505 ctx.Name(),
1506 len(osTypeVariants),
1507 strings.Join(variants, "\n")))
Paul Duffin00e46802020-03-12 20:40:35 +00001508 }
1509
1510 // A common arch type only has one variant and its properties should be treated
1511 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001512 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001513 } else {
1514 // Create an arch specific info for each supported architecture type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001515 for _, id := range archIds {
1516 archVariants := variantsByArchId[id]
1517 archInfo := newArchSpecificInfo(ctx, id, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001518
1519 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1520 }
1521 }
1522
1523 return osInfo
1524}
1525
Paul Duffin39abf8f2021-09-24 14:58:27 +01001526func (osInfo *osTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1527 if len(osInfo.archInfos) == 0 {
1528 pruner.pruneProperties(osInfo.Properties)
1529 } else {
1530 for _, archInfo := range osInfo.archInfos {
1531 archInfo.pruneUnsupportedProperties(pruner)
1532 }
1533 }
1534}
1535
Paul Duffin00e46802020-03-12 20:40:35 +00001536// Optimize the properties by extracting common properties from arch type specific
1537// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001538func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001539 // Nothing to do if there is only a single common architecture.
1540 if len(osInfo.archInfos) == 0 {
1541 return
1542 }
1543
Paul Duffin9c3760e2020-03-16 19:52:08 +00001544 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001545 for _, archInfo := range osInfo.archInfos {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001546 multilib = multilib.addArchType(archInfo.archId.archType)
Paul Duffin9c3760e2020-03-16 19:52:08 +00001547
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001548 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001549 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001550 }
1551
Paul Duffin4b8b7932020-05-06 12:35:38 +01001552 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001553
1554 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001555 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001556}
1557
1558// Add the properties for an os to a property set.
1559//
1560// Maps the properties related to the os variants through to an appropriate
1561// module structure that will produce equivalent set of variants when it is
1562// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001563func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001564
1565 var osPropertySet android.BpPropertySet
1566 var archPropertySet android.BpPropertySet
1567 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001568 if osInfo.Properties.Base().Os_count == 1 &&
1569 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1570 // There is only one OS type present in the variants and it shouldn't have a
1571 // variant-specific target. The latter is the case if it's either for device
1572 // where there is only one OS (android), or for host and the member type
1573 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001574
1575 // Create a structure that looks like:
1576 // module_type {
1577 // name: "...",
1578 // ...
1579 // <common properties>
1580 // ...
1581 // <single os type specific properties>
1582 //
1583 // arch: {
1584 // <arch specific sections>
1585 // }
1586 //
1587 osPropertySet = bpModule
1588 archPropertySet = osPropertySet.AddPropertySet("arch")
1589
1590 // Arch specific properties need to be added to an arch specific section
1591 // within arch.
1592 archOsPrefix = ""
1593 } else {
1594 // Create a structure that looks like:
1595 // module_type {
1596 // name: "...",
1597 // ...
1598 // <common properties>
1599 // ...
1600 // target: {
1601 // <arch independent os specific sections, e.g. android>
1602 // ...
1603 // <arch and os specific sections, e.g. android_x86>
1604 // }
1605 //
1606 osType := osInfo.osType
1607 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1608 archPropertySet = targetPropertySet
1609
1610 // Arch specific properties need to be added to an os and arch specific
1611 // section prefixed with <os>_.
1612 archOsPrefix = osType.Name + "_"
1613 }
1614
1615 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001616 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001617
1618 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1619 // os) specific properties.
1620 //
1621 // The archInfos list will be empty if the os contains variants for the common
1622 // architecture.
1623 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001624 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001625 }
1626}
1627
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001628func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1629 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001630 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001631}
1632
1633var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1634
Paul Duffin4b8b7932020-05-06 12:35:38 +01001635func (osInfo *osTypeSpecificInfo) String() string {
1636 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1637}
1638
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001639// archId encapsulates the information needed to identify a combination of arch type and native
1640// bridge support.
1641//
1642// Conceptually, native bridge support is a facet of an android.Target, not an android.Arch as it is
1643// essentially using one android.Arch to implement another. However, in terms of the handling of
1644// the variants native bridge is treated as part of the arch variation. See the ArchVariation method
1645// on android.Target.
1646//
1647// So, it makes sense when optimizing the variants to combine native bridge with the arch type.
1648type archId struct {
1649 // The arch type of the variant's target.
1650 archType android.ArchType
1651
1652 // True if the variants is for the native bridge, false otherwise.
1653 nativeBridge bool
1654}
1655
1656// propertyName returns the name of the property corresponding to use for this arch id.
1657func (i *archId) propertyName() string {
1658 name := i.archType.Name
1659 if i.nativeBridge {
1660 // Note: This does not result in a valid property because there is no architecture specific
1661 // native bridge property, only a generic "native_bridge" property. However, this will be used
1662 // in error messages if there is an attempt to use this in a generated bp file.
1663 name += "_native_bridge"
1664 }
1665 return name
1666}
1667
1668func (i *archId) String() string {
1669 return fmt.Sprintf("ArchType{%s}, NativeBridge{%t}", i.archType, i.nativeBridge)
1670}
1671
1672// archIdFromTarget returns an archId initialized from information in the supplied target.
1673func archIdFromTarget(target android.Target) archId {
1674 return archId{
1675 archType: target.Arch.ArchType,
1676 nativeBridge: target.NativeBridge == android.NativeBridgeEnabled,
1677 }
1678}
1679
1680// commonArchId is the archId for the common architecture.
1681var commonArchId = archId{archType: android.Common}
1682
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001683type archTypeSpecificInfo struct {
1684 baseInfo
1685
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001686 archId archId
1687 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001688
Paul Duffinb42fa672021-09-09 16:37:49 +01001689 imageVariantInfos []*imageVariantSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001690}
1691
Paul Duffin4b8b7932020-05-06 12:35:38 +01001692var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1693
Paul Duffinfc8dd232020-03-17 12:51:37 +00001694// Create a new archTypeSpecificInfo for the specified arch type and its properties
1695// structures populated with information from the variants.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001696func newArchSpecificInfo(ctx android.SdkMemberContext, archId archId, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001697
Paul Duffinfc8dd232020-03-17 12:51:37 +00001698 // Create an arch specific info into which the variant properties can be copied.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001699 archInfo := &archTypeSpecificInfo{archId: archId, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001700
1701 // Create the properties into which the arch type specific properties will be
1702 // added.
1703 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001704
Liz Kammer96320df2022-05-12 20:40:00 -04001705 // if there are multiple supported link variants, we want to nest based on linkage even if there
1706 // is only one variant, otherwise, if there is only one variant we can populate based on the arch
1707 if len(archVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001708 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001709 } else {
Paul Duffinb42fa672021-09-09 16:37:49 +01001710 // Group the variants by image type.
1711 variantsByImage := make(map[string][]android.Module)
1712 for _, variant := range archVariants {
1713 image := variant.ImageVariation().Variation
1714 variantsByImage[image] = append(variantsByImage[image], variant)
1715 }
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001716
Paul Duffinb42fa672021-09-09 16:37:49 +01001717 // Create the image variant info in a fixed order.
1718 for _, imageVariantName := range android.SortedStringKeys(variantsByImage) {
1719 variants := variantsByImage[imageVariantName]
1720 archInfo.imageVariantInfos = append(archInfo.imageVariantInfos, newImageVariantSpecificInfo(ctx, imageVariantName, variantPropertiesFactory, variants))
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001721 }
1722 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001723
1724 return archInfo
1725}
1726
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001727// Get the link type of the variant
1728//
1729// If the variant is not differentiated by link type then it returns "",
1730// otherwise it returns one of "static" or "shared".
1731func getLinkType(variant android.Module) string {
1732 linkType := ""
1733 if linkable, ok := variant.(cc.LinkableInterface); ok {
1734 if linkable.Shared() && linkable.Static() {
1735 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1736 } else if linkable.Shared() {
1737 linkType = "shared"
1738 } else if linkable.Static() {
1739 linkType = "static"
1740 } else {
1741 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1742 }
1743 }
1744 return linkType
1745}
1746
Paul Duffin39abf8f2021-09-24 14:58:27 +01001747func (archInfo *archTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1748 if len(archInfo.imageVariantInfos) == 0 {
1749 pruner.pruneProperties(archInfo.Properties)
1750 } else {
1751 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1752 imageVariantInfo.pruneUnsupportedProperties(pruner)
1753 }
1754 }
1755}
1756
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001757// Optimize the properties by extracting common properties from link type specific
1758// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001759func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001760 if len(archInfo.imageVariantInfos) == 0 {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001761 return
1762 }
1763
Paul Duffinb42fa672021-09-09 16:37:49 +01001764 // Optimize the image variant properties first.
1765 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1766 imageVariantInfo.optimizeProperties(ctx, commonValueExtractor)
1767 }
1768
1769 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.imageVariantInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001770}
1771
Paul Duffinfc8dd232020-03-17 12:51:37 +00001772// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001773func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001774 archPropertySuffix := archInfo.archId.propertyName()
1775 propertySetName := archOsPrefix + archPropertySuffix
1776 archTypePropertySet := archPropertySet.AddPropertySet(propertySetName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001777 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1778 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1779 archTypePropertySet.AddProperty("enabled", true)
1780 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001781 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001782
Paul Duffinb42fa672021-09-09 16:37:49 +01001783 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1784 imageVariantInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001785 }
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001786
1787 // If this is for a native bridge architecture then make sure that the property set does not
1788 // contain any properties as providing native bridge specific properties is not currently
1789 // supported.
1790 if archInfo.archId.nativeBridge {
1791 propertySetContents := getPropertySetContents(archTypePropertySet)
1792 if propertySetContents != "" {
1793 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",
1794 propertySetName, ctx.name, propertySetContents)
1795 }
1796 }
1797}
1798
1799// getPropertySetContents returns the string representation of the contents of a property set, after
1800// recursively pruning any empty nested property sets.
1801func getPropertySetContents(propertySet android.BpPropertySet) string {
1802 set := propertySet.(*bpPropertySet)
1803 set.transformContents(pruneEmptySetTransformer{})
1804 if len(set.properties) != 0 {
1805 contents := &generatedContents{}
1806 contents.Indent()
1807 outputPropertySet(contents, set)
1808 setAsString := contents.content.String()
1809 return setAsString
1810 }
1811 return ""
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001812}
1813
Paul Duffin4b8b7932020-05-06 12:35:38 +01001814func (archInfo *archTypeSpecificInfo) String() string {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001815 return archInfo.archId.String()
Paul Duffin4b8b7932020-05-06 12:35:38 +01001816}
1817
Paul Duffinb42fa672021-09-09 16:37:49 +01001818type imageVariantSpecificInfo struct {
1819 baseInfo
1820
1821 imageVariant string
1822
1823 linkInfos []*linkTypeSpecificInfo
1824}
1825
1826func newImageVariantSpecificInfo(ctx android.SdkMemberContext, imageVariant string, variantPropertiesFactory variantPropertiesFactoryFunc, imageVariants []android.Module) *imageVariantSpecificInfo {
1827
1828 // Create an image variant specific info into which the variant properties can be copied.
1829 imageInfo := &imageVariantSpecificInfo{imageVariant: imageVariant}
1830
1831 // Create the properties into which the image variant specific properties will be added.
1832 imageInfo.Properties = variantPropertiesFactory()
1833
Liz Kammer96320df2022-05-12 20:40:00 -04001834 // if there are multiple supported link variants, we want to nest even if there is only one
1835 // variant, otherwise, if there is only one variant we can populate based on the image
1836 if len(imageVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffinb42fa672021-09-09 16:37:49 +01001837 imageInfo.Properties.PopulateFromVariant(ctx, imageVariants[0])
1838 } else {
1839 // There is more than one variant for this image variant which must be differentiated by link
Liz Kammer96320df2022-05-12 20:40:00 -04001840 // type. Or there are multiple supported linkages and we need to nest based on link type.
Paul Duffinb42fa672021-09-09 16:37:49 +01001841 for _, linkVariant := range imageVariants {
1842 linkType := getLinkType(linkVariant)
1843 if linkType == "" {
1844 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(imageVariants)))
1845 } else {
1846 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
1847
1848 imageInfo.linkInfos = append(imageInfo.linkInfos, linkInfo)
1849 }
1850 }
1851 }
1852
1853 return imageInfo
1854}
1855
Paul Duffin39abf8f2021-09-24 14:58:27 +01001856func (imageInfo *imageVariantSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1857 if len(imageInfo.linkInfos) == 0 {
1858 pruner.pruneProperties(imageInfo.Properties)
1859 } else {
1860 for _, linkInfo := range imageInfo.linkInfos {
1861 linkInfo.pruneUnsupportedProperties(pruner)
1862 }
1863 }
1864}
1865
Paul Duffinb42fa672021-09-09 16:37:49 +01001866// Optimize the properties by extracting common properties from link type specific
1867// properties into arch type specific properties.
1868func (imageInfo *imageVariantSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
1869 if len(imageInfo.linkInfos) == 0 {
1870 return
1871 }
1872
1873 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, imageInfo.Properties, imageInfo.linkInfos)
1874}
1875
1876// Add the properties for an arch type to a property set.
1877func (imageInfo *imageVariantSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1878 if imageInfo.imageVariant != android.CoreVariation {
1879 propertySet = propertySet.AddPropertySet(imageInfo.imageVariant)
1880 }
1881
1882 addSdkMemberPropertiesToSet(ctx, imageInfo.Properties, propertySet)
1883
Liz Kammer96320df2022-05-12 20:40:00 -04001884 usedLinkages := make(map[string]bool, len(imageInfo.linkInfos))
Paul Duffinb42fa672021-09-09 16:37:49 +01001885 for _, linkInfo := range imageInfo.linkInfos {
Liz Kammer96320df2022-05-12 20:40:00 -04001886 usedLinkages[linkInfo.linkType] = true
Paul Duffinb42fa672021-09-09 16:37:49 +01001887 linkInfo.addToPropertySet(ctx, propertySet)
1888 }
1889
Liz Kammer96320df2022-05-12 20:40:00 -04001890 // If not all supported linkages had existing variants, we need to disable the unsupported variant
1891 if len(imageInfo.linkInfos) < len(ctx.MemberType().SupportedLinkages()) {
1892 for _, l := range ctx.MemberType().SupportedLinkages() {
1893 if _, ok := usedLinkages[l]; !ok {
1894 otherLinkagePropertySet := propertySet.AddPropertySet(l)
1895 otherLinkagePropertySet.AddProperty("enabled", false)
1896 }
1897 }
1898 }
1899
Paul Duffinb42fa672021-09-09 16:37:49 +01001900 // If this is for a non-core image variant then make sure that the property set does not contain
1901 // any properties as providing non-core image variant specific properties for prebuilts is not
1902 // currently supported.
1903 if imageInfo.imageVariant != android.CoreVariation {
1904 propertySetContents := getPropertySetContents(propertySet)
1905 if propertySetContents != "" {
1906 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",
1907 imageInfo.imageVariant, ctx.name, propertySetContents)
1908 }
1909 }
1910}
1911
1912func (imageInfo *imageVariantSpecificInfo) String() string {
1913 return imageInfo.imageVariant
1914}
1915
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001916type linkTypeSpecificInfo struct {
1917 baseInfo
1918
1919 linkType string
1920}
1921
Paul Duffin4b8b7932020-05-06 12:35:38 +01001922var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1923
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001924// Create a new linkTypeSpecificInfo for the specified link type and its properties
1925// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001926func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001927 linkInfo := &linkTypeSpecificInfo{
1928 baseInfo: baseInfo{
1929 // Create the properties into which the link type specific properties will be
1930 // added.
1931 Properties: variantPropertiesFactory(),
1932 },
1933 linkType: linkType,
1934 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001935 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001936 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001937}
1938
Paul Duffinf68f85a2021-09-09 16:11:42 +01001939func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1940 linkPropertySet := propertySet.AddPropertySet(l.linkType)
1941 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
1942}
1943
Paul Duffin39abf8f2021-09-24 14:58:27 +01001944func (l *linkTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1945 pruner.pruneProperties(l.Properties)
1946}
1947
Paul Duffin4b8b7932020-05-06 12:35:38 +01001948func (l *linkTypeSpecificInfo) String() string {
1949 return fmt.Sprintf("LinkType{%s}", l.linkType)
1950}
1951
Paul Duffin3a4eb502020-03-19 16:11:18 +00001952type memberContext struct {
1953 sdkMemberContext android.ModuleContext
1954 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001955 memberType android.SdkMemberType
1956 name string
Paul Duffind19f8942021-07-14 12:08:37 +01001957
1958 // The set of traits required of this member.
1959 requiredTraits android.SdkMemberTraitSet
Paul Duffin3a4eb502020-03-19 16:11:18 +00001960}
1961
1962func (m *memberContext) SdkModuleContext() android.ModuleContext {
1963 return m.sdkMemberContext
1964}
1965
1966func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1967 return m.builder
1968}
1969
Paul Duffina551a1c2020-03-17 21:04:24 +00001970func (m *memberContext) MemberType() android.SdkMemberType {
1971 return m.memberType
1972}
1973
1974func (m *memberContext) Name() string {
1975 return m.name
1976}
1977
Paul Duffind19f8942021-07-14 12:08:37 +01001978func (m *memberContext) RequiresTrait(trait android.SdkMemberTrait) bool {
1979 return m.requiredTraits.Contains(trait)
1980}
1981
Paul Duffin13648912022-07-15 13:12:35 +00001982func (m *memberContext) IsTargetBuildBeforeTiramisu() bool {
1983 return m.builder.targetBuildRelease.EarlierThan(buildReleaseT)
1984}
1985
1986var _ android.SdkMemberContext = (*memberContext)(nil)
1987
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001988func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001989
1990 memberType := member.memberType
1991
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001992 // Do not add the prefer property if the member snapshot module is a source module type.
Paul Duffin4e7d1c42022-05-13 13:12:19 +00001993 moduleCtx := ctx.sdkMemberContext
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001994 if !memberType.UsesSourceModuleTypeInSnapshot() {
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001995 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1996 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1997 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1998 // behavior is for the module.
Paul Duffin82d75ad2022-11-14 17:35:50 +00001999 bpModule.insertAfter("name", "prefer", false)
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002000 }
Paul Duffin83ad9562021-05-10 23:49:04 +01002001
Paul Duffin4e7d1c42022-05-13 13:12:19 +00002002 variants := selectApexVariantsWhereAvailable(ctx, member.variants)
2003
Paul Duffina04c1072020-03-02 10:16:35 +00002004 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00002005 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002006 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00002007 osType := variant.Target().Os
2008 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002009 }
2010
Paul Duffina04c1072020-03-02 10:16:35 +00002011 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00002012 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00002013 properties := memberType.CreateVariantPropertiesStruct()
2014 base := properties.Base()
Paul Duffinc61783b2022-10-20 17:21:40 +01002015 base.MemberName = member.Name()
Paul Duffina04c1072020-03-02 10:16:35 +00002016 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00002017 return properties
2018 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002019
Paul Duffina04c1072020-03-02 10:16:35 +00002020 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00002021
Paul Duffina04c1072020-03-02 10:16:35 +00002022 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00002023 commonProperties := variantPropertiesFactory()
2024 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00002025
Paul Duffin39abf8f2021-09-24 14:58:27 +01002026 // Create a property pruner that will prune any properties unsupported by the target build
2027 // release.
2028 targetBuildRelease := ctx.builder.targetBuildRelease
2029 unsupportedPropertyPruner := newPropertyPrunerByBuildRelease(commonProperties, targetBuildRelease)
2030
Paul Duffinc097e362020-03-10 22:50:03 +00002031 // Create common value extractor that can be used to optimize the properties.
2032 commonValueExtractor := newCommonValueExtractor(commonProperties)
2033
Paul Duffina04c1072020-03-02 10:16:35 +00002034 // The list of property structures which are os type specific but common across
2035 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002036 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00002037
2038 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00002039 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00002040 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00002041 // Add the os specific properties to a list of os type specific yet architecture
2042 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002043 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00002044
Paul Duffin39abf8f2021-09-24 14:58:27 +01002045 osInfo.pruneUnsupportedProperties(unsupportedPropertyPruner)
2046
Paul Duffin00e46802020-03-12 20:40:35 +00002047 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002048 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00002049 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002050
Paul Duffina04c1072020-03-02 10:16:35 +00002051 // Extract properties which are common across all architectures and os types.
Paul Duffin4e7d1c42022-05-13 13:12:19 +00002052 extractCommonProperties(moduleCtx, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002053
Paul Duffina04c1072020-03-02 10:16:35 +00002054 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01002055 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002056
Paul Duffina04c1072020-03-02 10:16:35 +00002057 // Create a target property set into which target specific properties can be
2058 // added.
2059 targetPropertySet := bpModule.AddPropertySet("target")
2060
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01002061 // If the member is host OS dependent and has host_supported then disable by
2062 // default and enable each host OS variant explicitly. This avoids problems
2063 // with implicitly enabled OS variants when the snapshot is used, which might
2064 // be different from this run (e.g. different build OS).
2065 if ctx.memberType.IsHostOsDependent() {
2066 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
2067 if hostSupported {
2068 hostPropertySet := targetPropertySet.AddPropertySet("host")
2069 hostPropertySet.AddProperty("enabled", false)
2070 }
2071 }
2072
Paul Duffina04c1072020-03-02 10:16:35 +00002073 // Iterate over the os types in a fixed order.
2074 for _, osType := range s.getPossibleOsTypes() {
2075 osInfo := osTypeToInfo[osType]
2076 if osInfo == nil {
2077 continue
2078 }
2079
Paul Duffin3a4eb502020-03-19 16:11:18 +00002080 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002081 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002082}
2083
Paul Duffina04c1072020-03-02 10:16:35 +00002084// Compute the list of possible os types that this sdk could support.
2085func (s *sdk) getPossibleOsTypes() []android.OsType {
2086 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00002087 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00002088 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07002089 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00002090 osTypes = append(osTypes, osType)
2091 }
2092 }
2093 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09002094 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00002095 osTypes = append(osTypes, osType)
2096 }
2097 }
2098 }
2099 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
2100 return osTypes
2101}
2102
Paul Duffinb28369a2020-05-04 15:39:59 +01002103// Given a set of properties (struct value), return the value of the field within that
2104// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00002105type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
2106
Paul Duffinc459f892020-04-30 18:08:29 +01002107// Checks the metadata to determine whether the property should be ignored for the
2108// purposes of common value extraction or not.
2109type extractorMetadataPredicate func(metadata propertiesContainer) bool
2110
2111// Indicates whether optimizable properties are provided by a host variant or
2112// not.
2113type isHostVariant interface {
2114 isHostVariant() bool
2115}
2116
Paul Duffinb28369a2020-05-04 15:39:59 +01002117// A property that can be optimized by the commonValueExtractor.
2118type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01002119 // The name of the field for this property. It is a "."-separated path for
2120 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002121 name string
2122
Paul Duffinc459f892020-04-30 18:08:29 +01002123 // Filter that can use metadata associated with the properties being optimized
2124 // to determine whether the field should be ignored during common value
2125 // optimization.
2126 filter extractorMetadataPredicate
2127
Paul Duffinb28369a2020-05-04 15:39:59 +01002128 // Retrieves the value on which common value optimization will be performed.
2129 getter fieldAccessorFunc
2130
Paul Duffinbfdca962022-09-22 16:21:54 +01002131 // True if the field should never be cleared.
2132 //
2133 // This is set to true if and only if the field is annotated with `sdk:"keep"`.
2134 keep bool
2135
Paul Duffinb28369a2020-05-04 15:39:59 +01002136 // The empty value for the field.
2137 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01002138
2139 // True if the property can support arch variants false otherwise.
2140 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01002141}
2142
Paul Duffin4b8b7932020-05-06 12:35:38 +01002143func (p extractorProperty) String() string {
2144 return p.name
2145}
2146
Paul Duffinc097e362020-03-10 22:50:03 +00002147// Supports extracting common values from a number of instances of a properties
2148// structure into a separate common set of properties.
2149type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01002150 // The properties that the extractor can optimize.
2151 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00002152}
2153
2154// Create a new common value extractor for the structure type for the supplied
2155// properties struct.
2156//
2157// The returned extractor can be used on any properties structure of the same type
2158// as the supplied set of properties.
2159func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
2160 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
2161 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01002162 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00002163 return extractor
2164}
2165
2166// Gather the fields from the supplied structure type from which common values will
2167// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00002168//
Martin Stjernholmb0249572020-09-15 02:32:35 +01002169// This is recursive function. If it encounters a struct then it will recurse
2170// into it, passing in the accessor for the field and the struct name as prefix
2171// for the nested fields. That will then be used in the accessors for the fields
2172// in the embedded struct.
2173func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00002174 for f := 0; f < structType.NumField(); f++ {
2175 field := structType.Field(f)
2176 if field.PkgPath != "" {
2177 // Ignore unexported fields.
2178 continue
2179 }
2180
Paul Duffin02e25c82022-09-22 15:30:58 +01002181 // Ignore fields tagged with sdk:"ignore".
2182 if proptools.HasTag(field, "sdk", "ignore") {
Paul Duffinc097e362020-03-10 22:50:03 +00002183 continue
2184 }
2185
Paul Duffinc459f892020-04-30 18:08:29 +01002186 var filter extractorMetadataPredicate
2187
2188 // Add a filter
2189 if proptools.HasTag(field, "sdk", "ignored-on-host") {
2190 filter = func(metadata propertiesContainer) bool {
2191 if m, ok := metadata.(isHostVariant); ok {
2192 if m.isHostVariant() {
2193 return false
2194 }
2195 }
2196 return true
2197 }
2198 }
2199
Paul Duffinbfdca962022-09-22 16:21:54 +01002200 keep := proptools.HasTag(field, "sdk", "keep")
2201
Paul Duffinc097e362020-03-10 22:50:03 +00002202 // Save a copy of the field index for use in the function.
2203 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01002204
Martin Stjernholmb0249572020-09-15 02:32:35 +01002205 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01002206
Paul Duffinc097e362020-03-10 22:50:03 +00002207 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00002208 if containingStructAccessor != nil {
2209 // This is an embedded structure so first access the field for the embedded
2210 // structure.
2211 value = containingStructAccessor(value)
2212 }
2213
Paul Duffinc097e362020-03-10 22:50:03 +00002214 // Skip through interface and pointer values to find the structure.
2215 value = getStructValue(value)
2216
Paul Duffin4b8b7932020-05-06 12:35:38 +01002217 defer func() {
2218 if r := recover(); r != nil {
2219 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
2220 }
2221 }()
2222
Paul Duffinc097e362020-03-10 22:50:03 +00002223 // Return the field.
2224 return value.Field(fieldIndex)
2225 }
2226
Martin Stjernholmb0249572020-09-15 02:32:35 +01002227 if field.Type.Kind() == reflect.Struct {
2228 // Gather fields from the nested or embedded structure.
2229 var subNamePrefix string
2230 if field.Anonymous {
2231 subNamePrefix = namePrefix
2232 } else {
2233 subNamePrefix = name + "."
2234 }
2235 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00002236 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01002237 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01002238 name,
Paul Duffinc459f892020-04-30 18:08:29 +01002239 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01002240 fieldGetter,
Paul Duffinbfdca962022-09-22 16:21:54 +01002241 keep,
Paul Duffinb28369a2020-05-04 15:39:59 +01002242 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01002243 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01002244 }
2245 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00002246 }
Paul Duffinc097e362020-03-10 22:50:03 +00002247 }
2248}
2249
2250func getStructValue(value reflect.Value) reflect.Value {
2251foundStruct:
2252 for {
2253 kind := value.Kind()
2254 switch kind {
2255 case reflect.Interface, reflect.Ptr:
2256 value = value.Elem()
2257 case reflect.Struct:
2258 break foundStruct
2259 default:
2260 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
2261 }
2262 }
2263 return value
2264}
2265
Paul Duffinf34f6d82020-04-30 15:48:31 +01002266// A container of properties to be optimized.
2267//
2268// Allows additional information to be associated with the properties, e.g. for
2269// filtering.
2270type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002271 fmt.Stringer
2272
Paul Duffinf34f6d82020-04-30 15:48:31 +01002273 // Get the properties that need optimizing.
2274 optimizableProperties() interface{}
2275}
2276
Paul Duffin2d1bb892021-04-24 11:32:59 +01002277// A wrapper for sdk variant related properties to allow them to be optimized.
2278type sdkVariantPropertiesContainer struct {
2279 sdkVariant *sdk
2280 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01002281}
2282
Paul Duffin2d1bb892021-04-24 11:32:59 +01002283func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
2284 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01002285}
2286
Paul Duffin2d1bb892021-04-24 11:32:59 +01002287func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002288 return c.sdkVariant.String()
2289}
2290
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002291// Extract common properties from a slice of property structures of the same type.
2292//
2293// All the property structures must be of the same type.
2294// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002295// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002296//
2297// Iterates over each exported field (capitalized name) and checks to see whether they
2298// have the same value (using DeepEquals) across all the input properties. If it does not then no
2299// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01002300// and the field in each of the input properties structure is set to its default value. Nested
2301// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002302func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002303 commonPropertiesValue := reflect.ValueOf(commonProperties)
2304 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002305
Paul Duffinf34f6d82020-04-30 15:48:31 +01002306 sliceValue := reflect.ValueOf(inputPropertiesSlice)
2307
Paul Duffinb28369a2020-05-04 15:39:59 +01002308 for _, property := range e.properties {
2309 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01002310 filter := property.filter
2311 if filter == nil {
2312 filter = func(metadata propertiesContainer) bool {
2313 return true
2314 }
2315 }
Paul Duffinb28369a2020-05-04 15:39:59 +01002316
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002317 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002318 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2319 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002320 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002321
Paul Duffin864e1b42020-05-06 10:23:19 +01002322 // Assume that all the values will be the same.
2323 //
2324 // While similar to this is not quite the same as commonValue == nil. If all the values
2325 // have been filtered out then this will be false but commonValue == nil will be true.
2326 valuesDiffer := false
2327
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002328 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002329 container := sliceValue.Index(i).Interface().(propertiesContainer)
2330 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002331 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002332
Paul Duffinc459f892020-04-30 18:08:29 +01002333 if !filter(container) {
2334 expectedValue := property.emptyValue.Interface()
2335 actualValue := fieldValue.Interface()
2336 if !reflect.DeepEqual(expectedValue, actualValue) {
2337 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2338 }
2339 continue
2340 }
2341
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002342 if commonValue == nil {
2343 // Use the first value as the commonProperties value.
2344 commonValue = &fieldValue
2345 } else {
2346 // If the value does not match the current common value then there is
2347 // no value in common so break out.
2348 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2349 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002350 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002351 break
2352 }
2353 }
2354 }
2355
Paul Duffin864e1b42020-05-06 10:23:19 +01002356 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002357 // and set the input struct's field to the empty value.
2358 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002359 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002360 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffinbfdca962022-09-22 16:21:54 +01002361 if !property.keep {
2362 for i := 0; i < sliceValue.Len(); i++ {
2363 container := sliceValue.Index(i).Interface().(propertiesContainer)
2364 itemValue := reflect.ValueOf(container.optimizableProperties())
2365 fieldValue := fieldGetter(itemValue)
2366 fieldValue.Set(emptyValue)
2367 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002368 }
2369 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002370
2371 if valuesDiffer && !property.archVariant {
2372 // The values differ but the property does not support arch variants so it
2373 // is an error.
2374 var details strings.Builder
2375 for i := 0; i < sliceValue.Len(); i++ {
2376 container := sliceValue.Index(i).Interface().(propertiesContainer)
2377 itemValue := reflect.ValueOf(container.optimizableProperties())
2378 fieldValue := fieldGetter(itemValue)
2379
2380 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2381 }
2382
2383 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2384 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002385 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002386
2387 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002388}