blob: 71bd042a6045a3ffdda2f2bc1dc34ea6f93166fa [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//
37// SOONG_SDK_SNAPSHOT_PREFER
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +000038// By default every unversioned module in the generated snapshot has prefer: false. Building it
39// with SOONG_SDK_SNAPSHOT_PREFER=true will force them to use prefer: true.
Paul Duffin64fb5262021-05-05 21:36:04 +010040//
Paul Duffinfb9a7f92021-07-06 17:18:42 +010041// SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR
42// If set this specifies the Soong config var that can be used to control whether the prebuilt
43// modules from the generated snapshot or the original source modules. Values must be a colon
44// separated pair of strings, the first of which is the Soong config namespace, and the second
45// is the name of the variable within that namespace.
46//
47// The config namespace and var name are used to set the `use_source_config_var` property. That
48// in turn will cause the generated prebuilts to use the soong config variable to select whether
49// source or the prebuilt is used.
50// e.g. If an sdk snapshot is built using:
51// m SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR=acme:build_from_source sdkextensions-sdk
52// Then the resulting snapshot will include:
53// use_source_config_var: {
54// config_namespace: "acme",
55// var_name: "build_from_source",
56// }
57//
58// Assuming that the config variable is defined in .mk using something like:
59// $(call add_soong_config_namespace,acme)
60// $(call add_soong_config_var_value,acme,build_from_source,true)
61//
62// Then when the snapshot is unpacked in the repository it will have the following behavior:
63// m droid - will use the sdkextensions-sdk prebuilts if present. Otherwise, it will use the
64// sources.
65// m SOONG_CONFIG_acme_build_from_source=true droid - will use the sdkextensions-sdk
66// sources, if present. Otherwise, it will use the prebuilts.
67//
68// This is a temporary mechanism to control the prefer flags and will be removed once a more
69// maintainable solution has been implemented.
70// TODO(b/174997203): Remove when no longer necessary.
71//
Paul Duffin43f7bf02021-05-05 22:00:51 +010072// SOONG_SDK_SNAPSHOT_VERSION
73// This provides control over the version of the generated snapshot.
74//
75// SOONG_SDK_SNAPSHOT_VERSION=current will generate unversioned and versioned prebuilts and a
76// versioned snapshot module. This is the default behavior. The zip file containing the
77// generated snapshot will be <sdk-name>-current.zip.
78//
79// SOONG_SDK_SNAPSHOT_VERSION=unversioned will generate unversioned prebuilts only and the zip
80// file containing the generated snapshot will be <sdk-name>.zip.
81//
82// SOONG_SDK_SNAPSHOT_VERSION=<number> will generate versioned prebuilts and a versioned
83// snapshot module only. The zip file containing the generated snapshot will be
84// <sdk-name>-<number>.zip.
85//
Paul Duffin39abf8f2021-09-24 14:58:27 +010086// SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE
87// This allows the target build release (i.e. the release version of the build within which
88// the snapshot will be used) of the snapshot to be specified. If unspecified then it defaults
89// to the current build release version. Otherwise, it must be the name of one of the build
90// releases defined in nameToBuildRelease, e.g. S, T, etc..
91//
92// The generated snapshot must only be used in the specified target release. If the target
93// build release is not the current build release then the generated Android.bp file not be
94// checked for compatibility.
95//
96// e.g. if setting SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE=S will cause the generated snapshot
97// to be compatible with S.
98//
Paul Duffin64fb5262021-05-05 21:36:04 +010099
Jiyong Park9b409bc2019-10-11 14:59:13 +0900100var pctx = android.NewPackageContext("android/soong/sdk")
101
Paul Duffin375058f2019-11-29 20:17:53 +0000102var (
103 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
104 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +0000105 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +0000106 CommandDeps: []string{
107 "${config.Zip2ZipCmd}",
108 },
109 },
110 "destdir")
111
112 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
113 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -0700114 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +0000115 CommandDeps: []string{
116 "${config.SoongZipCmd}",
117 },
118 Rspfile: "$out.rsp",
119 RspfileContent: "$in",
120 },
121 "basedir")
122
123 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
124 blueprint.RuleParams{
125 Command: `${config.MergeZipsCmd} $out $in`,
126 CommandDeps: []string{
127 "${config.MergeZipsCmd}",
128 },
129 })
130)
131
Paul Duffin43f7bf02021-05-05 22:00:51 +0100132const (
133 soongSdkSnapshotVersionUnversioned = "unversioned"
134 soongSdkSnapshotVersionCurrent = "current"
135)
136
Paul Duffinb645ec82019-11-27 17:43:54 +0000137type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +0900138 content strings.Builder
139 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +0900140}
141
Paul Duffinb645ec82019-11-27 17:43:54 +0000142// generatedFile abstracts operations for writing contents into a file and emit a build rule
143// for the file.
144type generatedFile struct {
145 generatedContents
146 path android.OutputPath
147}
148
Jiyong Park232e7852019-11-04 12:23:40 +0900149func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +0900150 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +0000151 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +0900152 }
153}
154
Paul Duffinb645ec82019-11-27 17:43:54 +0000155func (gc *generatedContents) Indent() {
156 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +0900157}
158
Paul Duffinb645ec82019-11-27 17:43:54 +0000159func (gc *generatedContents) Dedent() {
160 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +0900161}
162
Paul Duffina08e4dc2021-06-22 18:19:19 +0100163// IndentedPrintf will add spaces to indent the line to the appropriate level before printing the
164// arguments.
165func (gc *generatedContents) IndentedPrintf(format string, args ...interface{}) {
166 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
167}
168
169// UnindentedPrintf does not add spaces to indent the line to the appropriate level before printing
170// the arguments.
171func (gc *generatedContents) UnindentedPrintf(format string, args ...interface{}) {
172 fmt.Fprintf(&(gc.content), format, args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900173}
174
175func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800176 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100177
178 content := gf.content.String()
179
180 // ninja consumes newline characters in rspfile_content. Prevent it by
181 // escaping the backslash in the newline character. The extra backslash
182 // is removed when the rspfile is written to the actual script file
183 content = strings.ReplaceAll(content, "\n", "\\n")
184
Jiyong Park9b409bc2019-10-11 14:59:13 +0900185 rb.Command().
186 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100187 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100188 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900189 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
190 rb.Command().
191 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800192 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900193}
194
Paul Duffin13879572019-11-28 14:31:38 +0000195// Collect all the members.
196//
Paul Duffinb97b1572021-04-29 21:50:40 +0100197// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
198// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000199func (s *sdk) collectMembers(ctx android.ModuleContext) {
200 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000201 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
202 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf7b3d0d2021-09-02 14:29:21 +0100203 if memberTag, ok := tag.(android.SdkMemberDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100204 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900205
Paul Duffin5cca7c42021-05-26 10:16:01 +0100206 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
207 if memberType == nil {
208 return false
209 }
210
Paul Duffin13879572019-11-28 14:31:38 +0000211 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000212 if !memberType.IsInstance(child) {
213 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900214 }
Paul Duffin13879572019-11-28 14:31:38 +0000215
Paul Duffin6a7e9532020-03-20 17:50:07 +0000216 // Keep track of which multilib variants are used by the sdk.
217 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
218
Paul Duffinb97b1572021-04-29 21:50:40 +0100219 var exportedComponentsInfo android.ExportedComponentsInfo
220 if ctx.OtherModuleHasProvider(child, android.ExportedComponentsInfoProvider) {
221 exportedComponentsInfo = ctx.OtherModuleProvider(child, android.ExportedComponentsInfoProvider).(android.ExportedComponentsInfo)
222 }
223
Paul Duffinc6ba1822022-05-06 09:38:02 +0000224 var container android.SdkAware
225 if parent != ctx.Module() {
226 container = parent.(android.SdkAware)
227 }
228
Paul Duffina7208112021-04-23 21:20:20 +0100229 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100230 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
Paul Duffinc6ba1822022-05-06 09:38:02 +0000231 sdkVariant: s,
232 memberType: memberType,
233 variant: child.(android.SdkAware),
234 container: container,
235 export: export,
236 exportedComponentsInfo: exportedComponentsInfo,
Paul Duffinb97b1572021-04-29 21:50:40 +0100237 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000238
Paul Duffin2d3da312021-05-06 12:02:27 +0100239 // Recurse down into the member's dependencies as it may have dependencies that need to be
240 // automatically added to the sdk.
241 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900242 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000243
244 return false
Paul Duffin13879572019-11-28 14:31:38 +0000245 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000246}
247
Paul Duffincc3132e2021-04-24 01:10:30 +0100248// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
249// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000250//
Paul Duffincc3132e2021-04-24 01:10:30 +0100251// The sdkMember instances are then grouped into slices by member type. Within each such slice the
252// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000253//
Paul Duffincc3132e2021-04-24 01:10:30 +0100254// Finally, the member type slices are concatenated together to form a single slice. The order in
255// which they are concatenated is the order in which the member types were registered in the
256// android.SdkMemberTypesRegistry.
257func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000258 byType := make(map[android.SdkMemberType][]*sdkMember)
259 byName := make(map[string]*sdkMember)
260
Paul Duffin21827262021-04-24 12:16:36 +0100261 for _, memberVariantDep := range memberVariantDeps {
262 memberType := memberVariantDep.memberType
263 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000264
265 name := ctx.OtherModuleName(variant)
266 member := byName[name]
267 if member == nil {
268 member = &sdkMember{memberType: memberType, name: name}
269 byName[name] = member
270 byType[memberType] = append(byType[memberType], member)
271 }
272
Paul Duffin1356d8c2020-02-25 19:26:33 +0000273 // Only append new variants to the list. This is needed because a member can be both
274 // exported by the sdk and also be a transitive sdk member.
275 member.variants = appendUniqueVariants(member.variants, variant)
276 }
277
Paul Duffin13879572019-11-28 14:31:38 +0000278 var members []*sdkMember
Paul Duffin62782de2021-07-14 12:05:16 +0100279 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000280 membersOfType := byType[memberListProperty.memberType]
281 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900282 }
283
Paul Duffin6a7e9532020-03-20 17:50:07 +0000284 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900285}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900286
Paul Duffin72910952020-01-20 18:16:30 +0000287func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
288 for _, v := range variants {
289 if v == newVariant {
290 return variants
291 }
292 }
293 return append(variants, newVariant)
294}
295
Paul Duffin51509a12022-04-06 12:48:09 +0000296// BUILD_NUMBER_FILE is the name of the file in the snapshot zip that will contain the number of
297// the build from which the snapshot was produced.
298const BUILD_NUMBER_FILE = "snapshot-creation-build-number.txt"
299
Jiyong Park73c54ee2019-10-22 20:31:18 +0900300// SDK directory structure
301// <sdk_root>/
302// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
303// <api_ver>/ : below this directory are all auto-generated
304// Android.bp : definition of 'sdk_snapshot' module is here
305// aidl/
306// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
307// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900308// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900309// include/
310// bionic/libc/include/stdlib.h : an exported header file
311// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900312// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900313// <arch>/include/ : arch-specific exported headers
314// <arch>/include_gen/ : arch-specific generated headers
315// <arch>/lib/
316// libFoo.so : a stub library
317
Jiyong Park232e7852019-11-04 12:23:40 +0900318// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900319// This isn't visible to users, so could be changed in future.
320func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
321 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
322}
323
Jiyong Park232e7852019-11-04 12:23:40 +0900324// buildSnapshot is the main function in this source file. It creates rules to copy
325// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffinc6ba1822022-05-06 09:38:02 +0000326func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000327
Paul Duffinb97b1572021-04-29 21:50:40 +0100328 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100329 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100330 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000331 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100332 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100333 }
Paul Duffin865171e2020-03-02 18:38:15 +0000334
Paul Duffinb97b1572021-04-29 21:50:40 +0100335 // Filter out any sdkMemberVariantDep that is a component of another.
336 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000337
Paul Duffinb97b1572021-04-29 21:50:40 +0100338 // Record the names of all the members, both explicitly specified and implicitly
339 // included.
340 allMembersByName := make(map[string]struct{})
341 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100342
Paul Duffinb97b1572021-04-29 21:50:40 +0100343 addMember := func(name string, export bool) {
344 allMembersByName[name] = struct{}{}
345 if export {
346 exportedMembersByName[name] = struct{}{}
347 }
348 }
349
350 for _, memberVariantDep := range memberVariantDeps {
351 name := memberVariantDep.variant.Name()
352 export := memberVariantDep.export
353
354 addMember(name, export)
355
356 // Add any components provided by the module.
357 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
358 addMember(component, export)
359 }
360
361 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
362 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000363 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000364 }
365
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000366 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900367
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000368 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000369
370 bpFile := &bpFile{
371 modules: make(map[string]*bpModule),
372 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000373
Paul Duffin43f7bf02021-05-05 22:00:51 +0100374 config := ctx.Config()
375 version := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_VERSION", "current")
376
377 // Generate versioned modules in the snapshot unless an unversioned snapshot has been requested.
378 generateVersioned := version != soongSdkSnapshotVersionUnversioned
379
380 // Generate unversioned modules in the snapshot unless a numbered snapshot has been requested.
381 //
382 // Unversioned modules are not required in that case because the numbered version will be a
383 // finalized version of the snapshot that is intended to be kept separate from the
384 generateUnversioned := version == soongSdkSnapshotVersionUnversioned || version == soongSdkSnapshotVersionCurrent
Paul Duffinc6ba1822022-05-06 09:38:02 +0000385 snapshotFileSuffix := ""
Paul Duffin43f7bf02021-05-05 22:00:51 +0100386 if generateVersioned {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000387 snapshotFileSuffix = "-" + version
Paul Duffin43f7bf02021-05-05 22:00:51 +0100388 }
389
Paul Duffin39abf8f2021-09-24 14:58:27 +0100390 currentBuildRelease := latestBuildRelease()
391 targetBuildReleaseEnv := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE", currentBuildRelease.name)
392 targetBuildRelease, err := nameToRelease(targetBuildReleaseEnv)
393 if err != nil {
394 ctx.ModuleErrorf("invalid SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE: %s", err)
395 targetBuildRelease = currentBuildRelease
396 }
397
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000398 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000399 ctx: ctx,
400 sdk: s,
Paul Duffin43f7bf02021-05-05 22:00:51 +0100401 version: version,
Paul Duffin13f02712020-03-06 12:30:43 +0000402 snapshotDir: snapshotDir.OutputPath,
403 copies: make(map[string]string),
404 filesToZip: []android.Path{bp.path},
405 bpFile: bpFile,
406 prebuiltModules: make(map[string]*bpModule),
407 allMembersByName: allMembersByName,
408 exportedMembersByName: exportedMembersByName,
Paul Duffin39abf8f2021-09-24 14:58:27 +0100409 targetBuildRelease: targetBuildRelease,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900410 }
Paul Duffinac37c502019-11-26 18:02:20 +0000411 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900412
Paul Duffin62131702021-05-07 01:10:01 +0100413 // If the sdk snapshot includes any license modules then add a package module which has a
414 // default_applicable_licenses property. That will prevent the LSC license process from updating
415 // the generated Android.bp file to add a package module that includes all licenses used by all
416 // the modules in that package. That would be unnecessary as every module in the sdk should have
417 // their own licenses property specified.
418 if hasLicenses {
419 pkg := bpFile.newModule("package")
420 property := "default_applicable_licenses"
421 pkg.AddCommentForProperty(property, `
422A default list here prevents the license LSC from adding its own list which would
423be unnecessary as every module in the sdk already has its own licenses property.
424`)
425 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
426 bpFile.AddModule(pkg)
427 }
428
Paul Duffin0df49682021-05-07 01:10:01 +0100429 // Group the variants for each member module together and then group the members of each member
430 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100431 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100432
433 // Create the prebuilt modules for each of the member modules.
Paul Duffind19f8942021-07-14 12:08:37 +0100434 traits := s.gatherTraits()
Paul Duffin13ad94f2020-02-19 16:19:27 +0000435 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000436 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000437
Paul Duffind19f8942021-07-14 12:08:37 +0100438 name := member.name
439 requiredTraits := traits[name]
440 if requiredTraits == nil {
441 requiredTraits = android.EmptySdkMemberTraitSet()
442 }
443
444 // Create the snapshot for the member.
445 memberCtx := &memberContext{ctx, builder, memberType, name, requiredTraits}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000446
447 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100448 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900449 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900450
Paul Duffine6c0d842020-01-15 14:08:51 +0000451 // Create a transformer that will transform an unversioned module into a versioned module.
452 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
453
Paul Duffin72910952020-01-20 18:16:30 +0000454 // Create a transformer that will transform an unversioned module by replacing any references
455 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100456 unversionedTransformer := unversionedTransformation{
457 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100458 }
Paul Duffin72910952020-01-20 18:16:30 +0000459
Paul Duffinb645ec82019-11-27 17:43:54 +0000460 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000461 // Prune any empty property sets.
462 unversioned = unversioned.transform(pruneEmptySetTransformer{})
463
Paul Duffin43f7bf02021-05-05 22:00:51 +0100464 if generateVersioned {
465 // Copy the unversioned module so it can be modified to make it versioned.
466 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000467
Paul Duffin43f7bf02021-05-05 22:00:51 +0100468 // Transform the unversioned module into a versioned one.
469 versioned.transform(unversionedToVersionedTransformer)
470 bpFile.AddModule(versioned)
471 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000472
Paul Duffin43f7bf02021-05-05 22:00:51 +0100473 if generateUnversioned {
474 // Transform the unversioned module to make it suitable for use in the snapshot.
475 unversioned.transform(unversionedTransformer)
476 bpFile.AddModule(unversioned)
477 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000478 }
479
Paul Duffin43f7bf02021-05-05 22:00:51 +0100480 if generateVersioned {
481 // Add the sdk/module_exports_snapshot module to the bp file.
482 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
483 }
Paul Duffin26197a62021-04-24 00:34:10 +0100484
485 // generate Android.bp
486 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
487 generateBpContents(&bp.generatedContents, bpFile)
488
489 contents := bp.content.String()
Paul Duffin39abf8f2021-09-24 14:58:27 +0100490 // If the snapshot is being generated for the current build release then check the syntax to make
491 // sure that it is compatible.
492 if targetBuildRelease == currentBuildRelease {
493 syntaxCheckSnapshotBpFile(ctx, contents)
494 }
Paul Duffin26197a62021-04-24 00:34:10 +0100495
496 bp.build(pctx, ctx, nil)
497
Paul Duffin51509a12022-04-06 12:48:09 +0000498 // Copy the build number file into the snapshot.
499 builder.CopyToSnapshot(ctx.Config().BuildNumberFile(ctx), BUILD_NUMBER_FILE)
500
Paul Duffin26197a62021-04-24 00:34:10 +0100501 filesToZip := builder.filesToZip
502
503 // zip them all
Paul Duffinc6ba1822022-05-06 09:38:02 +0000504 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100505 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100506 outputDesc := "Building snapshot for " + ctx.ModuleName()
507
508 // If there are no zips to merge then generate the output zip directly.
509 // Otherwise, generate an intermediate zip file into which other zips can be
510 // merged.
511 var zipFile android.OutputPath
512 var desc string
513 if len(builder.zipsToMerge) == 0 {
514 zipFile = outputZipFile
515 desc = outputDesc
516 } else {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000517 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100518 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100519 desc = "Building intermediate snapshot for " + ctx.ModuleName()
520 }
521
522 ctx.Build(pctx, android.BuildParams{
523 Description: desc,
524 Rule: zipFiles,
525 Inputs: filesToZip,
526 Output: zipFile,
527 Args: map[string]string{
528 "basedir": builder.snapshotDir.String(),
529 },
530 })
531
532 if len(builder.zipsToMerge) != 0 {
533 ctx.Build(pctx, android.BuildParams{
534 Description: outputDesc,
535 Rule: mergeZips,
536 Input: zipFile,
537 Inputs: builder.zipsToMerge,
538 Output: outputZipFile,
539 })
540 }
541
Paul Duffinc6ba1822022-05-06 09:38:02 +0000542 modules := s.generateInfoData(ctx, memberVariantDeps)
543
544 // Output the modules information as pretty printed JSON.
545 info := newGeneratedFile(ctx, fmt.Sprintf("%s%s.info", ctx.ModuleName(), snapshotFileSuffix))
546 output, err := json.MarshalIndent(modules, "", " ")
547 if err != nil {
548 ctx.ModuleErrorf("error generating %q: %s", info, err)
549 }
550 builder.infoContents = string(output)
551 info.generatedContents.UnindentedPrintf("%s", output)
552 info.build(pctx, ctx, nil)
553 infoPath := info.path
554 installedInfo := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), infoPath.Base(), infoPath)
555 s.infoFile = android.OptionalPathForPath(installedInfo)
556
557 // Install the zip, making sure that the info file has been installed as well.
558 installedZip := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), outputZipFile.Base(), outputZipFile, installedInfo)
559 s.snapshotFile = android.OptionalPathForPath(installedZip)
560}
561
562type moduleInfo struct {
563 // The type of the module, e.g. java_sdk_library
564 moduleType string
565 // The name of the module.
566 name string
567 // A list of additional dependencies of the module.
568 deps []string
569 // Additional dynamic properties.
570 dynamic map[string]interface{}
571}
572
573func (m *moduleInfo) MarshalJSON() ([]byte, error) {
574 buffer := bytes.Buffer{}
575
576 separator := ""
577 writeObjectPair := func(key string, value interface{}) {
578 buffer.WriteString(fmt.Sprintf("%s%q: ", separator, key))
579 b, err := json.Marshal(value)
580 if err != nil {
581 panic(err)
582 }
583 buffer.Write(b)
584 separator = ","
585 }
586
587 buffer.WriteString("{")
588 writeObjectPair("@type", m.moduleType)
589 writeObjectPair("@name", m.name)
590 if m.deps != nil {
591 writeObjectPair("@deps", m.deps)
592 }
593 for _, k := range android.SortedStringKeys(m.dynamic) {
594 v := m.dynamic[k]
595 writeObjectPair(k, v)
596 }
597 buffer.WriteString("}")
598 return buffer.Bytes(), nil
599}
600
601var _ json.Marshaler = (*moduleInfo)(nil)
602
603// generateInfoData creates a list of moduleInfo structures that will be marshalled into JSON.
604func (s *sdk) generateInfoData(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) interface{} {
605 modules := []*moduleInfo{}
606 sdkInfo := moduleInfo{
607 moduleType: "sdk",
608 name: ctx.ModuleName(),
609 dynamic: map[string]interface{}{},
610 }
611 modules = append(modules, &sdkInfo)
612
613 name2Info := map[string]*moduleInfo{}
614 getModuleInfo := func(module android.Module) *moduleInfo {
615 name := module.Name()
616 info := name2Info[name]
617 if info == nil {
618 moduleType := ctx.OtherModuleType(module)
619 // Remove any suffix added when creating modules dynamically.
620 moduleType = strings.Split(moduleType, "__")[0]
621 info = &moduleInfo{
622 moduleType: moduleType,
623 name: name,
624 }
625 name2Info[name] = info
626 }
627 return info
628 }
629
630 for _, memberVariantDep := range memberVariantDeps {
631 propertyName := memberVariantDep.memberType.SdkPropertyName()
632 var list []string
633 if v, ok := sdkInfo.dynamic[propertyName]; ok {
634 list = v.([]string)
635 }
636
637 memberName := memberVariantDep.variant.Name()
638 list = append(list, memberName)
639 sdkInfo.dynamic[propertyName] = android.SortedUniqueStrings(list)
640
641 if memberVariantDep.container != nil {
642 containerInfo := getModuleInfo(memberVariantDep.container)
643 containerInfo.deps = android.SortedUniqueStrings(append(containerInfo.deps, memberName))
644 }
645
646 // Make sure that the module info is created for each module.
647 getModuleInfo(memberVariantDep.variant)
648 }
649
650 for _, memberName := range android.SortedStringKeys(name2Info) {
651 info := name2Info[memberName]
652 modules = append(modules, info)
653 }
654
655 return modules
Paul Duffin26197a62021-04-24 00:34:10 +0100656}
657
Paul Duffinb97b1572021-04-29 21:50:40 +0100658// filterOutComponents removes any item from the deps list that is a component of another item in
659// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
660// then it will remove "foo.stubs" from the deps.
661func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
662 // Collate the set of components that all the modules added to the sdk provide.
663 components := map[string]*sdkMemberVariantDep{}
664 for i, _ := range deps {
665 dep := &deps[i]
666 for _, c := range dep.exportedComponentsInfo.Components {
667 components[c] = dep
668 }
669 }
670
671 // If no module provides components then return the input deps unfiltered.
672 if len(components) == 0 {
673 return deps
674 }
675
676 filtered := make([]sdkMemberVariantDep, 0, len(deps))
677 for _, dep := range deps {
678 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
679 if owner, ok := components[name]; ok {
680 // This is a component of another module that is a member of the sdk.
681
682 // If the component is exported but the owning module is not then the configuration is not
683 // supported.
684 if dep.export && !owner.export {
685 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
686 continue
687 }
688
689 // This module must not be added to the list of members of the sdk as that would result in a
690 // duplicate module in the sdk snapshot.
691 continue
692 }
693
694 filtered = append(filtered, dep)
695 }
696 return filtered
697}
698
Paul Duffin26197a62021-04-24 00:34:10 +0100699// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100700func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100701 bpFile := builder.bpFile
702
Paul Duffinb645ec82019-11-27 17:43:54 +0000703 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000704 var snapshotModuleType string
705 if s.properties.Module_exports {
706 snapshotModuleType = "module_exports_snapshot"
707 } else {
708 snapshotModuleType = "sdk_snapshot"
709 }
710 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000711 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000712
713 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100714 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000715 if len(visibility) != 0 {
716 snapshotModule.AddProperty("visibility", visibility)
717 }
718
Paul Duffin865171e2020-03-02 18:38:15 +0000719 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000720
Paul Duffincd064672021-04-24 00:47:29 +0100721 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100722 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000723
Paul Duffin2d1bb892021-04-24 11:32:59 +0100724 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100725
Paul Duffin6a7e9532020-03-20 17:50:07 +0000726 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100727
Paul Duffin2d1bb892021-04-24 11:32:59 +0100728 // Create a mapping from osType to combined properties.
729 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
730 for _, combined := range combinedPropertiesList {
731 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
732 }
733
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100734 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000735 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100736 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100737 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000738
Paul Duffin2d1bb892021-04-24 11:32:59 +0100739 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000740 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000741 }
Paul Duffin865171e2020-03-02 18:38:15 +0000742
Jiyong Park8fe14e62020-10-19 22:47:34 +0900743 // If host is supported and any member is host OS dependent then disable host
744 // by default, so that we can enable each host OS variant explicitly. This
745 // avoids problems with implicitly enabled OS variants when the snapshot is
746 // used, which might be different from this run (e.g. different build OS).
747 if s.HostSupported() {
748 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100749 for _, memberVariantDep := range memberVariantDeps {
750 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
751 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900752 if !android.InList(targetString, supportedHostTargets) {
753 supportedHostTargets = append(supportedHostTargets, targetString)
754 }
755 }
756 }
757 if len(supportedHostTargets) > 0 {
758 hostPropertySet := targetPropertySet.AddPropertySet("host")
759 hostPropertySet.AddProperty("enabled", false)
760 }
761 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
762 for _, hostTarget := range supportedHostTargets {
763 propertySet := targetPropertySet.AddPropertySet(hostTarget)
764 propertySet.AddProperty("enabled", true)
765 }
766 }
767
Paul Duffin865171e2020-03-02 18:38:15 +0000768 // Prune any empty property sets.
769 snapshotModule.transform(pruneEmptySetTransformer{})
770
Paul Duffinb645ec82019-11-27 17:43:54 +0000771 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900772}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000773
Paul Duffinf88d8e02020-05-07 20:21:34 +0100774// Check the syntax of the generated Android.bp file contents and if they are
775// invalid then log an error with the contents (tagged with line numbers) and the
776// errors that were found so that it is easy to see where the problem lies.
777func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
778 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
779 if len(errs) != 0 {
780 message := &strings.Builder{}
781 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
782
783Generated Android.bp contents
784========================================================================
785`)
786 for i, line := range strings.Split(contents, "\n") {
787 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
788 }
789
790 _, _ = fmt.Fprint(message, `
791========================================================================
792
793Errors found:
794`)
795
796 for _, err := range errs {
797 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
798 }
799
800 ctx.ModuleErrorf("%s", message.String())
801 }
802}
803
Paul Duffin4b8b7932020-05-06 12:35:38 +0100804func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
805 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
806 if err != nil {
807 ctx.ModuleErrorf("error extracting common properties: %s", err)
808 }
809}
810
Paul Duffinfbe470e2021-04-24 12:37:13 +0100811// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
812type snapshotModuleStaticProperties struct {
813 Compile_multilib string `android:"arch_variant"`
814}
815
Paul Duffin2d1bb892021-04-24 11:32:59 +0100816// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
817type combinedSnapshotModuleProperties struct {
818 // The sdk variant from which this information was collected.
819 sdkVariant *sdk
820
821 // Static snapshot module properties.
822 staticProperties *snapshotModuleStaticProperties
823
824 // The dynamically generated member list properties.
825 dynamicProperties interface{}
826}
827
828// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100829func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
830 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100831 var list []*combinedSnapshotModuleProperties
832 for _, sdkVariant := range sdkVariants {
833 staticProperties := &snapshotModuleStaticProperties{
834 Compile_multilib: sdkVariant.multilibUsages.String(),
835 }
Paul Duffin62782de2021-07-14 12:05:16 +0100836 dynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100837
Paul Duffincd064672021-04-24 00:47:29 +0100838 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100839 sdkVariant: sdkVariant,
840 staticProperties: staticProperties,
841 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100842 }
843 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
844
845 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100846 }
Paul Duffincd064672021-04-24 00:47:29 +0100847
848 for _, memberVariantDep := range memberVariantDeps {
849 // If the member dependency is internal then do not add the dependency to the snapshot member
850 // list properties.
851 if !memberVariantDep.export {
852 continue
853 }
854
855 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin62782de2021-07-14 12:05:16 +0100856 memberListProperty := s.memberTypeListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100857 memberName := ctx.OtherModuleName(memberVariantDep.variant)
858
Paul Duffin13082052021-05-11 00:31:38 +0100859 if memberListProperty.getter == nil {
860 continue
861 }
862
Paul Duffincd064672021-04-24 00:47:29 +0100863 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100864 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100865 if !android.InList(memberName, memberList) {
866 memberList = append(memberList, memberName)
867 }
Paul Duffin13082052021-05-11 00:31:38 +0100868 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100869 }
870
Paul Duffin2d1bb892021-04-24 11:32:59 +0100871 return list
872}
873
874func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
875
876 // Extract the dynamic properties and add them to a list of propertiesContainer.
877 propertyContainers := []propertiesContainer{}
878 for _, i := range list {
879 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
880 sdkVariant: i.sdkVariant,
881 properties: i.dynamicProperties,
882 })
883 }
884
885 // Extract the common members, removing them from the original properties.
Paul Duffin62782de2021-07-14 12:05:16 +0100886 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100887 extractor := newCommonValueExtractor(commonDynamicProperties)
888 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
889
890 // Extract the static properties and add them to a list of propertiesContainer.
891 propertyContainers = []propertiesContainer{}
892 for _, i := range list {
893 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
894 sdkVariant: i.sdkVariant,
895 properties: i.staticProperties,
896 })
897 }
898
899 commonStaticProperties := &snapshotModuleStaticProperties{}
900 extractor = newCommonValueExtractor(commonStaticProperties)
901 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
902
903 return &combinedSnapshotModuleProperties{
904 sdkVariant: nil,
905 staticProperties: commonStaticProperties,
906 dynamicProperties: commonDynamicProperties,
907 }
908}
909
910func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
911 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100912 multilib := staticProperties.Compile_multilib
913 if multilib != "" && multilib != "both" {
914 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
915 propertySet.AddProperty("compile_multilib", multilib)
916 }
917
Paul Duffin2d1bb892021-04-24 11:32:59 +0100918 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin62782de2021-07-14 12:05:16 +0100919 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100920 if memberListProperty.getter == nil {
921 continue
922 }
Paul Duffin865171e2020-03-02 18:38:15 +0000923 names := memberListProperty.getter(dynamicMemberTypeListProperties)
924 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000925 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000926 }
927 }
928}
929
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000930type propertyTag struct {
931 name string
932}
933
Paul Duffin94289702021-09-09 15:38:32 +0100934var _ android.BpPropertyTag = propertyTag{}
935
Paul Duffin0cb37b92020-03-04 14:52:46 +0000936// A BpPropertyTag to add to a property that contains references to other sdk members.
937//
938// This will cause the references to be rewritten to a versioned reference in the version
939// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000940var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000941var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000942
Paul Duffin0cb37b92020-03-04 14:52:46 +0000943// A BpPropertyTag that indicates the property should only be present in the versioned
944// module.
945//
946// This will cause the property to be removed from the unversioned instance of a
947// snapshot module.
948var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
949
Paul Duffine6c0d842020-01-15 14:08:51 +0000950type unversionedToVersionedTransformation struct {
951 identityTransformation
952 builder *snapshotBuilder
953}
954
Paul Duffine6c0d842020-01-15 14:08:51 +0000955func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
956 // Use a versioned name for the module but remember the original name for the
957 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100958 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000959 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000960 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100961 // Remove the prefer property if present as versioned modules never need marking with prefer.
962 module.removeProperty("prefer")
Paul Duffinfb9a7f92021-07-06 17:18:42 +0100963 // Ditto for use_source_config_var
964 module.removeProperty("use_source_config_var")
Paul Duffine6c0d842020-01-15 14:08:51 +0000965 return module
966}
967
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000968func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000969 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
970 required := tag == requiredSdkMemberReferencePropertyTag
971 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000972 } else {
973 return value, tag
974 }
975}
976
Paul Duffin72910952020-01-20 18:16:30 +0000977type unversionedTransformation struct {
978 identityTransformation
979 builder *snapshotBuilder
980}
981
982func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
983 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100984 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000985 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000986 return module
987}
988
989func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000990 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
991 required := tag == requiredSdkMemberReferencePropertyTag
992 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000993 } else if tag == sdkVersionedOnlyPropertyTag {
994 // The property is not allowed in the unversioned module so remove it.
995 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000996 } else {
997 return value, tag
998 }
999}
1000
Paul Duffina78f3a72020-02-21 16:29:35 +00001001type pruneEmptySetTransformer struct {
1002 identityTransformation
1003}
1004
1005var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
1006
1007func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
1008 if len(propertySet.properties) == 0 {
1009 return nil, nil
1010 } else {
1011 return propertySet, tag
1012 }
1013}
1014
Paul Duffinb645ec82019-11-27 17:43:54 +00001015func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +00001016 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
1017 return true
1018 })
1019}
1020
1021func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffina08e4dc2021-06-22 18:19:19 +01001022 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +00001023 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +00001024 if moduleFilter(bpModule) {
Paul Duffina08e4dc2021-06-22 18:19:19 +01001025 contents.IndentedPrintf("\n")
1026 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
Paul Duffind0759072021-02-17 11:23:00 +00001027 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffina08e4dc2021-06-22 18:19:19 +01001028 contents.IndentedPrintf("}\n")
Paul Duffind0759072021-02-17 11:23:00 +00001029 }
Paul Duffinb645ec82019-11-27 17:43:54 +00001030 }
Paul Duffinb645ec82019-11-27 17:43:54 +00001031}
1032
1033func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
1034 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +00001035
Paul Duffin0df49682021-05-07 01:10:01 +01001036 addComment := func(name string) {
1037 if text, ok := set.comments[name]; ok {
1038 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +01001039 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +01001040 }
1041 }
1042 }
1043
Paul Duffin07ef3cb2020-03-11 18:17:42 +00001044 // Output the properties first, followed by the nested sets. This ensures a
1045 // consistent output irrespective of whether property sets are created before
1046 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +00001047 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +00001048 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +00001049
Paul Duffin0df49682021-05-07 01:10:01 +01001050 // Do not write property sets in the properties phase.
1051 if _, ok := value.(*bpPropertySet); ok {
1052 continue
1053 }
1054
1055 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +01001056 reflectValue := reflect.ValueOf(value)
1057 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +00001058 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +00001059
1060 for _, name := range set.order {
1061 value := set.getValue(name)
1062
1063 // Only write property sets in the sets phase.
1064 switch v := value.(type) {
1065 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +01001066 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +01001067 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +00001068 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +01001069 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +00001070 }
1071 }
1072
Paul Duffinb645ec82019-11-27 17:43:54 +00001073 contents.Dedent()
1074}
1075
Paul Duffina08e4dc2021-06-22 18:19:19 +01001076// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
1077// by the value and then followed by a , and a newline.
1078func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
1079 contents.IndentedPrintf("%s: ", name)
1080 outputUnnamedValue(contents, value)
1081 contents.UnindentedPrintf(",\n")
1082}
1083
1084// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
1085// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
1086// indented and all but the last line will end with a newline.
1087func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
1088 valueType := value.Type()
1089 switch valueType.Kind() {
1090 case reflect.Bool:
1091 contents.UnindentedPrintf("%t", value.Bool())
1092
1093 case reflect.String:
1094 contents.UnindentedPrintf("%q", value)
1095
Paul Duffin51227d82021-05-18 12:54:27 +01001096 case reflect.Ptr:
1097 outputUnnamedValue(contents, value.Elem())
1098
Paul Duffina08e4dc2021-06-22 18:19:19 +01001099 case reflect.Slice:
1100 length := value.Len()
1101 if length == 0 {
1102 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +01001103 } else {
Paul Duffin51227d82021-05-18 12:54:27 +01001104 firstValue := value.Index(0)
1105 if length == 1 && !multiLineValue(firstValue) {
1106 contents.UnindentedPrintf("[")
1107 outputUnnamedValue(contents, firstValue)
1108 contents.UnindentedPrintf("]")
1109 } else {
1110 contents.UnindentedPrintf("[\n")
1111 contents.Indent()
1112 for i := 0; i < length; i++ {
1113 itemValue := value.Index(i)
1114 contents.IndentedPrintf("")
1115 outputUnnamedValue(contents, itemValue)
1116 contents.UnindentedPrintf(",\n")
1117 }
1118 contents.Dedent()
1119 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +01001120 }
Paul Duffina08e4dc2021-06-22 18:19:19 +01001121 }
1122
Paul Duffin51227d82021-05-18 12:54:27 +01001123 case reflect.Struct:
1124 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
1125 v := value.Interface()
1126 if _, ok := v.(android.BpPrintable); !ok {
1127 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
1128 }
1129 contents.UnindentedPrintf("{\n")
1130 contents.Indent()
1131 for f := 0; f < valueType.NumField(); f++ {
1132 fieldType := valueType.Field(f)
1133 if fieldType.Anonymous {
1134 continue
1135 }
1136 fieldValue := value.Field(f)
1137 fieldName := fieldType.Name
1138 propertyName := proptools.PropertyNameForField(fieldName)
1139 outputNamedValue(contents, propertyName, fieldValue)
1140 }
1141 contents.Dedent()
1142 contents.IndentedPrintf("}")
1143
Paul Duffina08e4dc2021-06-22 18:19:19 +01001144 default:
1145 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
1146 }
1147}
1148
Paul Duffin51227d82021-05-18 12:54:27 +01001149// multiLineValue returns true if the supplied value may require multiple lines in the output.
1150func multiLineValue(value reflect.Value) bool {
1151 kind := value.Kind()
1152 return kind == reflect.Slice || kind == reflect.Struct
1153}
1154
Paul Duffinac37c502019-11-26 18:02:20 +00001155func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001156 contents := &generatedContents{}
1157 generateBpContents(contents, s.builderForTests.bpFile)
1158 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +00001159}
1160
Paul Duffinc6ba1822022-05-06 09:38:02 +00001161func (s *sdk) GetInfoContentsForTests() string {
1162 return s.builderForTests.infoContents
1163}
1164
Paul Duffind0759072021-02-17 11:23:00 +00001165func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
1166 contents := &generatedContents{}
1167 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001168 name := module.Name()
1169 // Include modules that are either unversioned or have no name.
1170 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001171 })
1172 return contents.content.String()
1173}
1174
1175func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
1176 contents := &generatedContents{}
1177 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001178 name := module.Name()
1179 // Include modules that are either versioned or have no name.
1180 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001181 })
1182 return contents.content.String()
1183}
1184
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001185type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +01001186 ctx android.ModuleContext
1187 sdk *sdk
1188
1189 // The version of the generated snapshot.
1190 //
1191 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
1192 // this field.
1193 version string
1194
Paul Duffinb645ec82019-11-27 17:43:54 +00001195 snapshotDir android.OutputPath
1196 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +00001197
1198 // Map from destination to source of each copy - used to eliminate duplicates and
1199 // detect conflicts.
1200 copies map[string]string
1201
Paul Duffinb645ec82019-11-27 17:43:54 +00001202 filesToZip android.Paths
1203 zipsToMerge android.Paths
1204
Paul Duffin5c211452021-07-15 12:42:44 +01001205 // The path to an empty file.
1206 emptyFile android.WritablePath
1207
Paul Duffinb645ec82019-11-27 17:43:54 +00001208 prebuiltModules map[string]*bpModule
1209 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001210
1211 // The set of all members by name.
1212 allMembersByName map[string]struct{}
1213
1214 // The set of exported members by name.
1215 exportedMembersByName map[string]struct{}
Paul Duffin39abf8f2021-09-24 14:58:27 +01001216
1217 // The target build release for which the snapshot is to be generated.
1218 targetBuildRelease *buildRelease
Paul Duffinc6ba1822022-05-06 09:38:02 +00001219
1220 infoContents string
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001221}
1222
1223func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001224 if existing, ok := s.copies[dest]; ok {
1225 if existing != src.String() {
1226 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1227 return
1228 }
1229 } else {
1230 path := s.snapshotDir.Join(s.ctx, dest)
1231 s.ctx.Build(pctx, android.BuildParams{
1232 Rule: android.Cp,
1233 Input: src,
1234 Output: path,
1235 })
1236 s.filesToZip = append(s.filesToZip, path)
1237
1238 s.copies[dest] = src.String()
1239 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001240}
1241
Paul Duffin91547182019-11-12 19:39:36 +00001242func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1243 ctx := s.ctx
1244
1245 // Repackage the zip file so that the entries are in the destDir directory.
1246 // This will allow the zip file to be merged into the snapshot.
1247 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001248
1249 ctx.Build(pctx, android.BuildParams{
1250 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1251 Rule: repackageZip,
1252 Input: zipPath,
1253 Output: tmpZipPath,
1254 Args: map[string]string{
1255 "destdir": destDir,
1256 },
1257 })
Paul Duffin91547182019-11-12 19:39:36 +00001258
1259 // Add the repackaged zip file to the files to merge.
1260 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1261}
1262
Paul Duffin5c211452021-07-15 12:42:44 +01001263func (s *snapshotBuilder) EmptyFile() android.Path {
1264 if s.emptyFile == nil {
1265 ctx := s.ctx
1266 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1267 s.ctx.Build(pctx, android.BuildParams{
1268 Rule: android.Touch,
1269 Output: s.emptyFile,
1270 })
1271 }
1272
1273 return s.emptyFile
1274}
1275
Paul Duffin9d8d6092019-12-05 18:19:29 +00001276func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1277 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001278 if s.prebuiltModules[name] != nil {
1279 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1280 }
1281
1282 m := s.bpFile.newModule(moduleType)
1283 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001284
Paul Duffinbefa4b92020-03-04 14:22:45 +00001285 variant := member.Variants()[0]
1286
Paul Duffin13f02712020-03-06 12:30:43 +00001287 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001288 // An internal member is only referenced from the sdk snapshot which is in the
1289 // same package so can be marked as private.
1290 m.AddProperty("visibility", []string{"//visibility:private"})
1291 } else {
1292 // Extract visibility information from a member variant. All variants have the same
1293 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001294 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1295
1296 // Add any additional visibility rules needed for the prebuilts to reference each other.
1297 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1298 if err != nil {
1299 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1300 }
1301
1302 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001303 if len(visibility) != 0 {
1304 m.AddProperty("visibility", visibility)
1305 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001306 }
1307
Martin Stjernholm1e041092020-11-03 00:11:09 +00001308 // Where available copy apex_available properties from the member.
1309 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1310 apexAvailable := apexAware.ApexAvailable()
1311 if len(apexAvailable) == 0 {
1312 // //apex_available:platform is the default.
1313 apexAvailable = []string{android.AvailableToPlatform}
1314 }
1315
1316 // Add in any baseline apex available settings.
1317 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1318
1319 // Remove duplicates and sort.
1320 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1321 sort.Strings(apexAvailable)
1322
1323 m.AddProperty("apex_available", apexAvailable)
1324 }
1325
Paul Duffinb0bb3762021-05-06 16:48:05 +01001326 // The licenses are the same for all variants.
1327 mctx := s.ctx
1328 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1329 if len(licenseInfo.Licenses) > 0 {
1330 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1331 }
1332
Paul Duffin865171e2020-03-02 18:38:15 +00001333 deviceSupported := false
1334 hostSupported := false
1335
1336 for _, variant := range member.Variants() {
1337 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001338 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001339 hostSupported = true
1340 } else if osClass == android.Device {
1341 deviceSupported = true
1342 }
1343 }
1344
1345 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001346
Paul Duffin0cb37b92020-03-04 14:52:46 +00001347 // Disable installation in the versioned module of those modules that are ever installable.
1348 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1349 if installable.EverInstallable() {
1350 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1351 }
1352 }
1353
Paul Duffinb645ec82019-11-27 17:43:54 +00001354 s.prebuiltModules[name] = m
1355 s.prebuiltOrder = append(s.prebuiltOrder, m)
1356 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001357}
1358
Paul Duffin865171e2020-03-02 18:38:15 +00001359func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001360 // If neither device or host is supported then this module does not support either so will not
1361 // recognize the properties.
1362 if !deviceSupported && !hostSupported {
1363 return
1364 }
1365
Paul Duffin865171e2020-03-02 18:38:15 +00001366 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001367 bpModule.AddProperty("device_supported", false)
1368 }
Paul Duffin865171e2020-03-02 18:38:15 +00001369 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001370 bpModule.AddProperty("host_supported", true)
1371 }
1372}
1373
Paul Duffin13f02712020-03-06 12:30:43 +00001374func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1375 if required {
1376 return requiredSdkMemberReferencePropertyTag
1377 } else {
1378 return optionalSdkMemberReferencePropertyTag
1379 }
1380}
1381
1382func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1383 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001384}
1385
Paul Duffinb645ec82019-11-27 17:43:54 +00001386// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001387func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1388 if _, ok := s.allMembersByName[unversionedName]; !ok {
1389 if required {
1390 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1391 }
1392 return unversionedName
1393 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001394 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1395}
Paul Duffinb645ec82019-11-27 17:43:54 +00001396
Paul Duffin13f02712020-03-06 12:30:43 +00001397func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001398 var references []string = nil
1399 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001400 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001401 }
1402 return references
1403}
Paul Duffin13879572019-11-28 14:31:38 +00001404
Paul Duffin72910952020-01-20 18:16:30 +00001405// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001406func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1407 if _, ok := s.allMembersByName[unversionedName]; !ok {
1408 if required {
1409 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1410 }
1411 return unversionedName
1412 }
1413
1414 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001415 return s.ctx.ModuleName() + "_" + unversionedName
1416 } else {
1417 return unversionedName
1418 }
1419}
1420
Paul Duffin13f02712020-03-06 12:30:43 +00001421func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001422 var references []string = nil
1423 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001424 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001425 }
1426 return references
1427}
1428
Paul Duffin13f02712020-03-06 12:30:43 +00001429func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1430 _, ok := s.exportedMembersByName[memberName]
1431 return !ok
1432}
1433
Martin Stjernholm89238f42020-07-10 00:14:03 +01001434// Add the properties from the given SdkMemberProperties to the blueprint
1435// property set. This handles common properties in SdkMemberPropertiesBase and
1436// calls the member-specific AddToPropertySet for the rest.
1437func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1438 if memberProperties.Base().Compile_multilib != "" {
1439 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1440 }
1441
1442 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1443}
1444
Paul Duffin21827262021-04-24 12:16:36 +01001445// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1446type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001447 // The sdk variant that depends (possibly indirectly) on the member variant.
1448 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001449
1450 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001451 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001452
1453 // The variant that is added to the sdk.
1454 variant android.SdkAware
1455
Paul Duffinc6ba1822022-05-06 09:38:02 +00001456 // The optional container of this member, i.e. the module that is depended upon by the sdk
1457 // (possibly transitively) and whose dependency on this module is why it was added to the sdk.
1458 // Is nil if this a direct dependency of the sdk.
1459 container android.SdkAware
1460
Paul Duffinb97b1572021-04-29 21:50:40 +01001461 // True if the member should be exported, i.e. accessible, from outside the sdk.
1462 export bool
1463
1464 // The names of additional component modules provided by the variant.
1465 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001466}
1467
Paul Duffin13879572019-11-28 14:31:38 +00001468var _ android.SdkMember = (*sdkMember)(nil)
1469
Paul Duffin21827262021-04-24 12:16:36 +01001470// sdkMember groups all the variants of a specific member module together along with the name of the
1471// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001472type sdkMember struct {
1473 memberType android.SdkMemberType
1474 name string
1475 variants []android.SdkAware
1476}
1477
1478func (m *sdkMember) Name() string {
1479 return m.name
1480}
1481
1482func (m *sdkMember) Variants() []android.SdkAware {
1483 return m.variants
1484}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001485
Paul Duffin9c3760e2020-03-16 19:52:08 +00001486// Track usages of multilib variants.
1487type multilibUsage int
1488
1489const (
1490 multilibNone multilibUsage = 0
1491 multilib32 multilibUsage = 1
1492 multilib64 multilibUsage = 2
1493 multilibBoth = multilib32 | multilib64
1494)
1495
1496// Add the multilib that is used in the arch type.
1497func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1498 multilib := archType.Multilib
1499 switch multilib {
1500 case "":
1501 return m
1502 case "lib32":
1503 return m | multilib32
1504 case "lib64":
1505 return m | multilib64
1506 default:
1507 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1508 }
1509}
1510
1511func (m multilibUsage) String() string {
1512 switch m {
1513 case multilibNone:
1514 return ""
1515 case multilib32:
1516 return "32"
1517 case multilib64:
1518 return "64"
1519 case multilibBoth:
1520 return "both"
1521 default:
1522 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1523 m, multilibNone, multilib32, multilib64, multilibBoth))
1524 }
1525}
1526
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001527type baseInfo struct {
1528 Properties android.SdkMemberProperties
1529}
1530
Paul Duffinf34f6d82020-04-30 15:48:31 +01001531func (b *baseInfo) optimizableProperties() interface{} {
1532 return b.Properties
1533}
1534
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001535type osTypeSpecificInfo struct {
1536 baseInfo
1537
Paul Duffin00e46802020-03-12 20:40:35 +00001538 osType android.OsType
1539
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001540 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001541 //
1542 // Nil if there is one variant whose arch type is common
1543 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001544}
1545
Paul Duffin4b8b7932020-05-06 12:35:38 +01001546var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1547
Paul Duffinfc8dd232020-03-17 12:51:37 +00001548type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1549
Paul Duffin00e46802020-03-12 20:40:35 +00001550// Create a new osTypeSpecificInfo for the specified os type and its properties
1551// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001552func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001553 osInfo := &osTypeSpecificInfo{
1554 osType: osType,
1555 }
1556
1557 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1558 properties := variantPropertiesFactory()
1559 properties.Base().Os = osType
1560 return properties
1561 }
1562
1563 // Create a structure into which properties common across the architectures in
1564 // this os type will be stored.
1565 osInfo.Properties = osSpecificVariantPropertiesFactory()
1566
1567 // Group the variants by arch type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001568 var variantsByArchId = make(map[archId][]android.Module)
1569 var archIds []archId
Paul Duffin00e46802020-03-12 20:40:35 +00001570 for _, variant := range osTypeVariants {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001571 target := variant.Target()
1572 id := archIdFromTarget(target)
1573 if _, ok := variantsByArchId[id]; !ok {
1574 archIds = append(archIds, id)
Paul Duffin00e46802020-03-12 20:40:35 +00001575 }
1576
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001577 variantsByArchId[id] = append(variantsByArchId[id], variant)
Paul Duffin00e46802020-03-12 20:40:35 +00001578 }
1579
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001580 if commonVariants, ok := variantsByArchId[commonArchId]; ok {
Paul Duffin00e46802020-03-12 20:40:35 +00001581 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001582 panic(fmt.Errorf("Expected to only have 1 variant when arch type is common but found %d", len(osTypeVariants)))
Paul Duffin00e46802020-03-12 20:40:35 +00001583 }
1584
1585 // A common arch type only has one variant and its properties should be treated
1586 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001587 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001588 } else {
1589 // Create an arch specific info for each supported architecture type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001590 for _, id := range archIds {
1591 archVariants := variantsByArchId[id]
1592 archInfo := newArchSpecificInfo(ctx, id, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001593
1594 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1595 }
1596 }
1597
1598 return osInfo
1599}
1600
Paul Duffin39abf8f2021-09-24 14:58:27 +01001601func (osInfo *osTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1602 if len(osInfo.archInfos) == 0 {
1603 pruner.pruneProperties(osInfo.Properties)
1604 } else {
1605 for _, archInfo := range osInfo.archInfos {
1606 archInfo.pruneUnsupportedProperties(pruner)
1607 }
1608 }
1609}
1610
Paul Duffin00e46802020-03-12 20:40:35 +00001611// Optimize the properties by extracting common properties from arch type specific
1612// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001613func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001614 // Nothing to do if there is only a single common architecture.
1615 if len(osInfo.archInfos) == 0 {
1616 return
1617 }
1618
Paul Duffin9c3760e2020-03-16 19:52:08 +00001619 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001620 for _, archInfo := range osInfo.archInfos {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001621 multilib = multilib.addArchType(archInfo.archId.archType)
Paul Duffin9c3760e2020-03-16 19:52:08 +00001622
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001623 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001624 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001625 }
1626
Paul Duffin4b8b7932020-05-06 12:35:38 +01001627 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001628
1629 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001630 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001631}
1632
1633// Add the properties for an os to a property set.
1634//
1635// Maps the properties related to the os variants through to an appropriate
1636// module structure that will produce equivalent set of variants when it is
1637// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001638func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001639
1640 var osPropertySet android.BpPropertySet
1641 var archPropertySet android.BpPropertySet
1642 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001643 if osInfo.Properties.Base().Os_count == 1 &&
1644 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1645 // There is only one OS type present in the variants and it shouldn't have a
1646 // variant-specific target. The latter is the case if it's either for device
1647 // where there is only one OS (android), or for host and the member type
1648 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001649
1650 // Create a structure that looks like:
1651 // module_type {
1652 // name: "...",
1653 // ...
1654 // <common properties>
1655 // ...
1656 // <single os type specific properties>
1657 //
1658 // arch: {
1659 // <arch specific sections>
1660 // }
1661 //
1662 osPropertySet = bpModule
1663 archPropertySet = osPropertySet.AddPropertySet("arch")
1664
1665 // Arch specific properties need to be added to an arch specific section
1666 // within arch.
1667 archOsPrefix = ""
1668 } else {
1669 // Create a structure that looks like:
1670 // module_type {
1671 // name: "...",
1672 // ...
1673 // <common properties>
1674 // ...
1675 // target: {
1676 // <arch independent os specific sections, e.g. android>
1677 // ...
1678 // <arch and os specific sections, e.g. android_x86>
1679 // }
1680 //
1681 osType := osInfo.osType
1682 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1683 archPropertySet = targetPropertySet
1684
1685 // Arch specific properties need to be added to an os and arch specific
1686 // section prefixed with <os>_.
1687 archOsPrefix = osType.Name + "_"
1688 }
1689
1690 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001691 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001692
1693 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1694 // os) specific properties.
1695 //
1696 // The archInfos list will be empty if the os contains variants for the common
1697 // architecture.
1698 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001699 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001700 }
1701}
1702
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001703func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1704 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001705 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001706}
1707
1708var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1709
Paul Duffin4b8b7932020-05-06 12:35:38 +01001710func (osInfo *osTypeSpecificInfo) String() string {
1711 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1712}
1713
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001714// archId encapsulates the information needed to identify a combination of arch type and native
1715// bridge support.
1716//
1717// Conceptually, native bridge support is a facet of an android.Target, not an android.Arch as it is
1718// essentially using one android.Arch to implement another. However, in terms of the handling of
1719// the variants native bridge is treated as part of the arch variation. See the ArchVariation method
1720// on android.Target.
1721//
1722// So, it makes sense when optimizing the variants to combine native bridge with the arch type.
1723type archId struct {
1724 // The arch type of the variant's target.
1725 archType android.ArchType
1726
1727 // True if the variants is for the native bridge, false otherwise.
1728 nativeBridge bool
1729}
1730
1731// propertyName returns the name of the property corresponding to use for this arch id.
1732func (i *archId) propertyName() string {
1733 name := i.archType.Name
1734 if i.nativeBridge {
1735 // Note: This does not result in a valid property because there is no architecture specific
1736 // native bridge property, only a generic "native_bridge" property. However, this will be used
1737 // in error messages if there is an attempt to use this in a generated bp file.
1738 name += "_native_bridge"
1739 }
1740 return name
1741}
1742
1743func (i *archId) String() string {
1744 return fmt.Sprintf("ArchType{%s}, NativeBridge{%t}", i.archType, i.nativeBridge)
1745}
1746
1747// archIdFromTarget returns an archId initialized from information in the supplied target.
1748func archIdFromTarget(target android.Target) archId {
1749 return archId{
1750 archType: target.Arch.ArchType,
1751 nativeBridge: target.NativeBridge == android.NativeBridgeEnabled,
1752 }
1753}
1754
1755// commonArchId is the archId for the common architecture.
1756var commonArchId = archId{archType: android.Common}
1757
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001758type archTypeSpecificInfo struct {
1759 baseInfo
1760
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001761 archId archId
1762 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001763
Paul Duffinb42fa672021-09-09 16:37:49 +01001764 imageVariantInfos []*imageVariantSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001765}
1766
Paul Duffin4b8b7932020-05-06 12:35:38 +01001767var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1768
Paul Duffinfc8dd232020-03-17 12:51:37 +00001769// Create a new archTypeSpecificInfo for the specified arch type and its properties
1770// structures populated with information from the variants.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001771func newArchSpecificInfo(ctx android.SdkMemberContext, archId archId, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001772
Paul Duffinfc8dd232020-03-17 12:51:37 +00001773 // Create an arch specific info into which the variant properties can be copied.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001774 archInfo := &archTypeSpecificInfo{archId: archId, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001775
1776 // Create the properties into which the arch type specific properties will be
1777 // added.
1778 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001779
1780 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001781 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001782 } else {
Paul Duffinb42fa672021-09-09 16:37:49 +01001783 // Group the variants by image type.
1784 variantsByImage := make(map[string][]android.Module)
1785 for _, variant := range archVariants {
1786 image := variant.ImageVariation().Variation
1787 variantsByImage[image] = append(variantsByImage[image], variant)
1788 }
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001789
Paul Duffinb42fa672021-09-09 16:37:49 +01001790 // Create the image variant info in a fixed order.
1791 for _, imageVariantName := range android.SortedStringKeys(variantsByImage) {
1792 variants := variantsByImage[imageVariantName]
1793 archInfo.imageVariantInfos = append(archInfo.imageVariantInfos, newImageVariantSpecificInfo(ctx, imageVariantName, variantPropertiesFactory, variants))
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001794 }
1795 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001796
1797 return archInfo
1798}
1799
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001800// Get the link type of the variant
1801//
1802// If the variant is not differentiated by link type then it returns "",
1803// otherwise it returns one of "static" or "shared".
1804func getLinkType(variant android.Module) string {
1805 linkType := ""
1806 if linkable, ok := variant.(cc.LinkableInterface); ok {
1807 if linkable.Shared() && linkable.Static() {
1808 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1809 } else if linkable.Shared() {
1810 linkType = "shared"
1811 } else if linkable.Static() {
1812 linkType = "static"
1813 } else {
1814 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1815 }
1816 }
1817 return linkType
1818}
1819
Paul Duffin39abf8f2021-09-24 14:58:27 +01001820func (archInfo *archTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1821 if len(archInfo.imageVariantInfos) == 0 {
1822 pruner.pruneProperties(archInfo.Properties)
1823 } else {
1824 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1825 imageVariantInfo.pruneUnsupportedProperties(pruner)
1826 }
1827 }
1828}
1829
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001830// Optimize the properties by extracting common properties from link type specific
1831// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001832func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001833 if len(archInfo.imageVariantInfos) == 0 {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001834 return
1835 }
1836
Paul Duffinb42fa672021-09-09 16:37:49 +01001837 // Optimize the image variant properties first.
1838 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1839 imageVariantInfo.optimizeProperties(ctx, commonValueExtractor)
1840 }
1841
1842 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.imageVariantInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001843}
1844
Paul Duffinfc8dd232020-03-17 12:51:37 +00001845// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001846func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001847 archPropertySuffix := archInfo.archId.propertyName()
1848 propertySetName := archOsPrefix + archPropertySuffix
1849 archTypePropertySet := archPropertySet.AddPropertySet(propertySetName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001850 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1851 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1852 archTypePropertySet.AddProperty("enabled", true)
1853 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001854 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001855
Paul Duffinb42fa672021-09-09 16:37:49 +01001856 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1857 imageVariantInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001858 }
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001859
1860 // If this is for a native bridge architecture then make sure that the property set does not
1861 // contain any properties as providing native bridge specific properties is not currently
1862 // supported.
1863 if archInfo.archId.nativeBridge {
1864 propertySetContents := getPropertySetContents(archTypePropertySet)
1865 if propertySetContents != "" {
1866 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",
1867 propertySetName, ctx.name, propertySetContents)
1868 }
1869 }
1870}
1871
1872// getPropertySetContents returns the string representation of the contents of a property set, after
1873// recursively pruning any empty nested property sets.
1874func getPropertySetContents(propertySet android.BpPropertySet) string {
1875 set := propertySet.(*bpPropertySet)
1876 set.transformContents(pruneEmptySetTransformer{})
1877 if len(set.properties) != 0 {
1878 contents := &generatedContents{}
1879 contents.Indent()
1880 outputPropertySet(contents, set)
1881 setAsString := contents.content.String()
1882 return setAsString
1883 }
1884 return ""
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001885}
1886
Paul Duffin4b8b7932020-05-06 12:35:38 +01001887func (archInfo *archTypeSpecificInfo) String() string {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001888 return archInfo.archId.String()
Paul Duffin4b8b7932020-05-06 12:35:38 +01001889}
1890
Paul Duffinb42fa672021-09-09 16:37:49 +01001891type imageVariantSpecificInfo struct {
1892 baseInfo
1893
1894 imageVariant string
1895
1896 linkInfos []*linkTypeSpecificInfo
1897}
1898
1899func newImageVariantSpecificInfo(ctx android.SdkMemberContext, imageVariant string, variantPropertiesFactory variantPropertiesFactoryFunc, imageVariants []android.Module) *imageVariantSpecificInfo {
1900
1901 // Create an image variant specific info into which the variant properties can be copied.
1902 imageInfo := &imageVariantSpecificInfo{imageVariant: imageVariant}
1903
1904 // Create the properties into which the image variant specific properties will be added.
1905 imageInfo.Properties = variantPropertiesFactory()
1906
1907 if len(imageVariants) == 1 {
1908 imageInfo.Properties.PopulateFromVariant(ctx, imageVariants[0])
1909 } else {
1910 // There is more than one variant for this image variant which must be differentiated by link
1911 // type.
1912 for _, linkVariant := range imageVariants {
1913 linkType := getLinkType(linkVariant)
1914 if linkType == "" {
1915 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(imageVariants)))
1916 } else {
1917 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
1918
1919 imageInfo.linkInfos = append(imageInfo.linkInfos, linkInfo)
1920 }
1921 }
1922 }
1923
1924 return imageInfo
1925}
1926
Paul Duffin39abf8f2021-09-24 14:58:27 +01001927func (imageInfo *imageVariantSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1928 if len(imageInfo.linkInfos) == 0 {
1929 pruner.pruneProperties(imageInfo.Properties)
1930 } else {
1931 for _, linkInfo := range imageInfo.linkInfos {
1932 linkInfo.pruneUnsupportedProperties(pruner)
1933 }
1934 }
1935}
1936
Paul Duffinb42fa672021-09-09 16:37:49 +01001937// Optimize the properties by extracting common properties from link type specific
1938// properties into arch type specific properties.
1939func (imageInfo *imageVariantSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
1940 if len(imageInfo.linkInfos) == 0 {
1941 return
1942 }
1943
1944 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, imageInfo.Properties, imageInfo.linkInfos)
1945}
1946
1947// Add the properties for an arch type to a property set.
1948func (imageInfo *imageVariantSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1949 if imageInfo.imageVariant != android.CoreVariation {
1950 propertySet = propertySet.AddPropertySet(imageInfo.imageVariant)
1951 }
1952
1953 addSdkMemberPropertiesToSet(ctx, imageInfo.Properties, propertySet)
1954
1955 for _, linkInfo := range imageInfo.linkInfos {
1956 linkInfo.addToPropertySet(ctx, propertySet)
1957 }
1958
1959 // If this is for a non-core image variant then make sure that the property set does not contain
1960 // any properties as providing non-core image variant specific properties for prebuilts is not
1961 // currently supported.
1962 if imageInfo.imageVariant != android.CoreVariation {
1963 propertySetContents := getPropertySetContents(propertySet)
1964 if propertySetContents != "" {
1965 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",
1966 imageInfo.imageVariant, ctx.name, propertySetContents)
1967 }
1968 }
1969}
1970
1971func (imageInfo *imageVariantSpecificInfo) String() string {
1972 return imageInfo.imageVariant
1973}
1974
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001975type linkTypeSpecificInfo struct {
1976 baseInfo
1977
1978 linkType string
1979}
1980
Paul Duffin4b8b7932020-05-06 12:35:38 +01001981var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1982
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001983// Create a new linkTypeSpecificInfo for the specified link type and its properties
1984// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001985func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001986 linkInfo := &linkTypeSpecificInfo{
1987 baseInfo: baseInfo{
1988 // Create the properties into which the link type specific properties will be
1989 // added.
1990 Properties: variantPropertiesFactory(),
1991 },
1992 linkType: linkType,
1993 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001994 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001995 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001996}
1997
Paul Duffinf68f85a2021-09-09 16:11:42 +01001998func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1999 linkPropertySet := propertySet.AddPropertySet(l.linkType)
2000 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
2001}
2002
Paul Duffin39abf8f2021-09-24 14:58:27 +01002003func (l *linkTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
2004 pruner.pruneProperties(l.Properties)
2005}
2006
Paul Duffin4b8b7932020-05-06 12:35:38 +01002007func (l *linkTypeSpecificInfo) String() string {
2008 return fmt.Sprintf("LinkType{%s}", l.linkType)
2009}
2010
Paul Duffin3a4eb502020-03-19 16:11:18 +00002011type memberContext struct {
2012 sdkMemberContext android.ModuleContext
2013 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00002014 memberType android.SdkMemberType
2015 name string
Paul Duffind19f8942021-07-14 12:08:37 +01002016
2017 // The set of traits required of this member.
2018 requiredTraits android.SdkMemberTraitSet
Paul Duffin3a4eb502020-03-19 16:11:18 +00002019}
2020
2021func (m *memberContext) SdkModuleContext() android.ModuleContext {
2022 return m.sdkMemberContext
2023}
2024
2025func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
2026 return m.builder
2027}
2028
Paul Duffina551a1c2020-03-17 21:04:24 +00002029func (m *memberContext) MemberType() android.SdkMemberType {
2030 return m.memberType
2031}
2032
2033func (m *memberContext) Name() string {
2034 return m.name
2035}
2036
Paul Duffind19f8942021-07-14 12:08:37 +01002037func (m *memberContext) RequiresTrait(trait android.SdkMemberTrait) bool {
2038 return m.requiredTraits.Contains(trait)
2039}
2040
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01002041func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002042
2043 memberType := member.memberType
2044
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002045 // Do not add the prefer property if the member snapshot module is a source module type.
Paul Duffin39abf8f2021-09-24 14:58:27 +01002046 config := ctx.sdkMemberContext.Config()
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002047 if !memberType.UsesSourceModuleTypeInSnapshot() {
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +00002048 // Set the prefer based on the environment variable. This is a temporary work around to allow a
2049 // snapshot to be created that sets prefer: true.
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002050 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
2051 // dynamically at build time not at snapshot generation time.
Paul Duffinfb9a7f92021-07-06 17:18:42 +01002052 prefer := config.IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01002053
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002054 // Set prefer. Setting this to false is not strictly required as that is the default but it does
2055 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
2056 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
2057 // behavior is for the module.
2058 bpModule.insertAfter("name", "prefer", prefer)
Paul Duffinfb9a7f92021-07-06 17:18:42 +01002059
2060 configVar := config.Getenv("SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR")
2061 if configVar != "" {
2062 parts := strings.Split(configVar, ":")
2063 cfp := android.ConfigVarProperties{
2064 Config_namespace: proptools.StringPtr(parts[0]),
2065 Var_name: proptools.StringPtr(parts[1]),
2066 }
2067 bpModule.insertAfter("prefer", "use_source_config_var", cfp)
2068 }
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002069 }
Paul Duffin83ad9562021-05-10 23:49:04 +01002070
Paul Duffina04c1072020-03-02 10:16:35 +00002071 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00002072 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002073 variants := member.Variants()
2074 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00002075 osType := variant.Target().Os
2076 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002077 }
2078
Paul Duffina04c1072020-03-02 10:16:35 +00002079 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00002080 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00002081 properties := memberType.CreateVariantPropertiesStruct()
2082 base := properties.Base()
2083 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00002084 return properties
2085 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002086
Paul Duffina04c1072020-03-02 10:16:35 +00002087 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00002088
Paul Duffina04c1072020-03-02 10:16:35 +00002089 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00002090 commonProperties := variantPropertiesFactory()
2091 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00002092
Paul Duffin39abf8f2021-09-24 14:58:27 +01002093 // Create a property pruner that will prune any properties unsupported by the target build
2094 // release.
2095 targetBuildRelease := ctx.builder.targetBuildRelease
2096 unsupportedPropertyPruner := newPropertyPrunerByBuildRelease(commonProperties, targetBuildRelease)
2097
Paul Duffinc097e362020-03-10 22:50:03 +00002098 // Create common value extractor that can be used to optimize the properties.
2099 commonValueExtractor := newCommonValueExtractor(commonProperties)
2100
Paul Duffina04c1072020-03-02 10:16:35 +00002101 // The list of property structures which are os type specific but common across
2102 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002103 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00002104
2105 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00002106 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00002107 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00002108 // Add the os specific properties to a list of os type specific yet architecture
2109 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002110 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00002111
Paul Duffin39abf8f2021-09-24 14:58:27 +01002112 osInfo.pruneUnsupportedProperties(unsupportedPropertyPruner)
2113
Paul Duffin00e46802020-03-12 20:40:35 +00002114 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002115 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00002116 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002117
Paul Duffina04c1072020-03-02 10:16:35 +00002118 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002119 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002120
Paul Duffina04c1072020-03-02 10:16:35 +00002121 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01002122 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002123
Paul Duffina04c1072020-03-02 10:16:35 +00002124 // Create a target property set into which target specific properties can be
2125 // added.
2126 targetPropertySet := bpModule.AddPropertySet("target")
2127
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01002128 // If the member is host OS dependent and has host_supported then disable by
2129 // default and enable each host OS variant explicitly. This avoids problems
2130 // with implicitly enabled OS variants when the snapshot is used, which might
2131 // be different from this run (e.g. different build OS).
2132 if ctx.memberType.IsHostOsDependent() {
2133 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
2134 if hostSupported {
2135 hostPropertySet := targetPropertySet.AddPropertySet("host")
2136 hostPropertySet.AddProperty("enabled", false)
2137 }
2138 }
2139
Paul Duffina04c1072020-03-02 10:16:35 +00002140 // Iterate over the os types in a fixed order.
2141 for _, osType := range s.getPossibleOsTypes() {
2142 osInfo := osTypeToInfo[osType]
2143 if osInfo == nil {
2144 continue
2145 }
2146
Paul Duffin3a4eb502020-03-19 16:11:18 +00002147 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002148 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002149}
2150
Paul Duffina04c1072020-03-02 10:16:35 +00002151// Compute the list of possible os types that this sdk could support.
2152func (s *sdk) getPossibleOsTypes() []android.OsType {
2153 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00002154 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00002155 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07002156 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00002157 osTypes = append(osTypes, osType)
2158 }
2159 }
2160 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09002161 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00002162 osTypes = append(osTypes, osType)
2163 }
2164 }
2165 }
2166 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
2167 return osTypes
2168}
2169
Paul Duffinb28369a2020-05-04 15:39:59 +01002170// Given a set of properties (struct value), return the value of the field within that
2171// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00002172type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
2173
Paul Duffinc459f892020-04-30 18:08:29 +01002174// Checks the metadata to determine whether the property should be ignored for the
2175// purposes of common value extraction or not.
2176type extractorMetadataPredicate func(metadata propertiesContainer) bool
2177
2178// Indicates whether optimizable properties are provided by a host variant or
2179// not.
2180type isHostVariant interface {
2181 isHostVariant() bool
2182}
2183
Paul Duffinb28369a2020-05-04 15:39:59 +01002184// A property that can be optimized by the commonValueExtractor.
2185type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01002186 // The name of the field for this property. It is a "."-separated path for
2187 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002188 name string
2189
Paul Duffinc459f892020-04-30 18:08:29 +01002190 // Filter that can use metadata associated with the properties being optimized
2191 // to determine whether the field should be ignored during common value
2192 // optimization.
2193 filter extractorMetadataPredicate
2194
Paul Duffinb28369a2020-05-04 15:39:59 +01002195 // Retrieves the value on which common value optimization will be performed.
2196 getter fieldAccessorFunc
2197
2198 // The empty value for the field.
2199 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01002200
2201 // True if the property can support arch variants false otherwise.
2202 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01002203}
2204
Paul Duffin4b8b7932020-05-06 12:35:38 +01002205func (p extractorProperty) String() string {
2206 return p.name
2207}
2208
Paul Duffinc097e362020-03-10 22:50:03 +00002209// Supports extracting common values from a number of instances of a properties
2210// structure into a separate common set of properties.
2211type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01002212 // The properties that the extractor can optimize.
2213 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00002214}
2215
2216// Create a new common value extractor for the structure type for the supplied
2217// properties struct.
2218//
2219// The returned extractor can be used on any properties structure of the same type
2220// as the supplied set of properties.
2221func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
2222 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
2223 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01002224 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00002225 return extractor
2226}
2227
2228// Gather the fields from the supplied structure type from which common values will
2229// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00002230//
Martin Stjernholmb0249572020-09-15 02:32:35 +01002231// This is recursive function. If it encounters a struct then it will recurse
2232// into it, passing in the accessor for the field and the struct name as prefix
2233// for the nested fields. That will then be used in the accessors for the fields
2234// in the embedded struct.
2235func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00002236 for f := 0; f < structType.NumField(); f++ {
2237 field := structType.Field(f)
2238 if field.PkgPath != "" {
2239 // Ignore unexported fields.
2240 continue
2241 }
2242
Paul Duffinb07fa512020-03-10 22:17:04 +00002243 // Ignore fields whose value should be kept.
2244 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00002245 continue
2246 }
2247
Paul Duffinc459f892020-04-30 18:08:29 +01002248 var filter extractorMetadataPredicate
2249
2250 // Add a filter
2251 if proptools.HasTag(field, "sdk", "ignored-on-host") {
2252 filter = func(metadata propertiesContainer) bool {
2253 if m, ok := metadata.(isHostVariant); ok {
2254 if m.isHostVariant() {
2255 return false
2256 }
2257 }
2258 return true
2259 }
2260 }
2261
Paul Duffinc097e362020-03-10 22:50:03 +00002262 // Save a copy of the field index for use in the function.
2263 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01002264
Martin Stjernholmb0249572020-09-15 02:32:35 +01002265 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01002266
Paul Duffinc097e362020-03-10 22:50:03 +00002267 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00002268 if containingStructAccessor != nil {
2269 // This is an embedded structure so first access the field for the embedded
2270 // structure.
2271 value = containingStructAccessor(value)
2272 }
2273
Paul Duffinc097e362020-03-10 22:50:03 +00002274 // Skip through interface and pointer values to find the structure.
2275 value = getStructValue(value)
2276
Paul Duffin4b8b7932020-05-06 12:35:38 +01002277 defer func() {
2278 if r := recover(); r != nil {
2279 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
2280 }
2281 }()
2282
Paul Duffinc097e362020-03-10 22:50:03 +00002283 // Return the field.
2284 return value.Field(fieldIndex)
2285 }
2286
Martin Stjernholmb0249572020-09-15 02:32:35 +01002287 if field.Type.Kind() == reflect.Struct {
2288 // Gather fields from the nested or embedded structure.
2289 var subNamePrefix string
2290 if field.Anonymous {
2291 subNamePrefix = namePrefix
2292 } else {
2293 subNamePrefix = name + "."
2294 }
2295 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00002296 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01002297 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01002298 name,
Paul Duffinc459f892020-04-30 18:08:29 +01002299 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01002300 fieldGetter,
2301 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01002302 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01002303 }
2304 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00002305 }
Paul Duffinc097e362020-03-10 22:50:03 +00002306 }
2307}
2308
2309func getStructValue(value reflect.Value) reflect.Value {
2310foundStruct:
2311 for {
2312 kind := value.Kind()
2313 switch kind {
2314 case reflect.Interface, reflect.Ptr:
2315 value = value.Elem()
2316 case reflect.Struct:
2317 break foundStruct
2318 default:
2319 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
2320 }
2321 }
2322 return value
2323}
2324
Paul Duffinf34f6d82020-04-30 15:48:31 +01002325// A container of properties to be optimized.
2326//
2327// Allows additional information to be associated with the properties, e.g. for
2328// filtering.
2329type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002330 fmt.Stringer
2331
Paul Duffinf34f6d82020-04-30 15:48:31 +01002332 // Get the properties that need optimizing.
2333 optimizableProperties() interface{}
2334}
2335
Paul Duffin2d1bb892021-04-24 11:32:59 +01002336// A wrapper for sdk variant related properties to allow them to be optimized.
2337type sdkVariantPropertiesContainer struct {
2338 sdkVariant *sdk
2339 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01002340}
2341
Paul Duffin2d1bb892021-04-24 11:32:59 +01002342func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
2343 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01002344}
2345
Paul Duffin2d1bb892021-04-24 11:32:59 +01002346func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002347 return c.sdkVariant.String()
2348}
2349
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002350// Extract common properties from a slice of property structures of the same type.
2351//
2352// All the property structures must be of the same type.
2353// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002354// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002355//
2356// Iterates over each exported field (capitalized name) and checks to see whether they
2357// have the same value (using DeepEquals) across all the input properties. If it does not then no
2358// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01002359// and the field in each of the input properties structure is set to its default value. Nested
2360// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002361func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002362 commonPropertiesValue := reflect.ValueOf(commonProperties)
2363 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002364
Paul Duffinf34f6d82020-04-30 15:48:31 +01002365 sliceValue := reflect.ValueOf(inputPropertiesSlice)
2366
Paul Duffinb28369a2020-05-04 15:39:59 +01002367 for _, property := range e.properties {
2368 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01002369 filter := property.filter
2370 if filter == nil {
2371 filter = func(metadata propertiesContainer) bool {
2372 return true
2373 }
2374 }
Paul Duffinb28369a2020-05-04 15:39:59 +01002375
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002376 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002377 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2378 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002379 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002380
Paul Duffin864e1b42020-05-06 10:23:19 +01002381 // Assume that all the values will be the same.
2382 //
2383 // While similar to this is not quite the same as commonValue == nil. If all the values
2384 // have been filtered out then this will be false but commonValue == nil will be true.
2385 valuesDiffer := false
2386
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002387 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002388 container := sliceValue.Index(i).Interface().(propertiesContainer)
2389 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002390 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002391
Paul Duffinc459f892020-04-30 18:08:29 +01002392 if !filter(container) {
2393 expectedValue := property.emptyValue.Interface()
2394 actualValue := fieldValue.Interface()
2395 if !reflect.DeepEqual(expectedValue, actualValue) {
2396 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2397 }
2398 continue
2399 }
2400
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002401 if commonValue == nil {
2402 // Use the first value as the commonProperties value.
2403 commonValue = &fieldValue
2404 } else {
2405 // If the value does not match the current common value then there is
2406 // no value in common so break out.
2407 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2408 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002409 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002410 break
2411 }
2412 }
2413 }
2414
Paul Duffin864e1b42020-05-06 10:23:19 +01002415 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002416 // and set the input struct's field to the empty value.
2417 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002418 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002419 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002420 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002421 container := sliceValue.Index(i).Interface().(propertiesContainer)
2422 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002423 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002424 fieldValue.Set(emptyValue)
2425 }
2426 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002427
2428 if valuesDiffer && !property.archVariant {
2429 // The values differ but the property does not support arch variants so it
2430 // is an error.
2431 var details strings.Builder
2432 for i := 0; i < sliceValue.Len(); i++ {
2433 container := sliceValue.Index(i).Interface().(propertiesContainer)
2434 itemValue := reflect.ValueOf(container.optimizableProperties())
2435 fieldValue := fieldGetter(itemValue)
2436
2437 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2438 }
2439
2440 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2441 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002442 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002443
2444 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002445}