blob: 389e845e75b9d17c19f6903e4964ec4e38e8d320 [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 (
18 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000019 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000020 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090021 "strings"
22
Paul Duffin7d74e7b2020-03-06 12:30:13 +000023 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000024 "android/soong/cc"
Colin Crosscb0ac952021-07-20 13:17:15 -070025
Paul Duffin375058f2019-11-29 20:17:53 +000026 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090027 "github.com/google/blueprint/proptools"
28
29 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090030)
31
Paul Duffin64fb5262021-05-05 21:36:04 +010032// Environment variables that affect the generated snapshot
33// ========================================================
34//
35// SOONG_SDK_SNAPSHOT_PREFER
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +000036// By default every unversioned module in the generated snapshot has prefer: false. Building it
37// with SOONG_SDK_SNAPSHOT_PREFER=true will force them to use prefer: true.
Paul Duffin64fb5262021-05-05 21:36:04 +010038//
Paul Duffinfb9a7f92021-07-06 17:18:42 +010039// SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR
40// If set this specifies the Soong config var that can be used to control whether the prebuilt
41// modules from the generated snapshot or the original source modules. Values must be a colon
42// separated pair of strings, the first of which is the Soong config namespace, and the second
43// is the name of the variable within that namespace.
44//
45// The config namespace and var name are used to set the `use_source_config_var` property. That
46// in turn will cause the generated prebuilts to use the soong config variable to select whether
47// source or the prebuilt is used.
48// e.g. If an sdk snapshot is built using:
49// m SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR=acme:build_from_source sdkextensions-sdk
50// Then the resulting snapshot will include:
51// use_source_config_var: {
52// config_namespace: "acme",
53// var_name: "build_from_source",
54// }
55//
56// Assuming that the config variable is defined in .mk using something like:
57// $(call add_soong_config_namespace,acme)
58// $(call add_soong_config_var_value,acme,build_from_source,true)
59//
60// Then when the snapshot is unpacked in the repository it will have the following behavior:
61// m droid - will use the sdkextensions-sdk prebuilts if present. Otherwise, it will use the
62// sources.
63// m SOONG_CONFIG_acme_build_from_source=true droid - will use the sdkextensions-sdk
64// sources, if present. Otherwise, it will use the prebuilts.
65//
66// This is a temporary mechanism to control the prefer flags and will be removed once a more
67// maintainable solution has been implemented.
68// TODO(b/174997203): Remove when no longer necessary.
69//
Paul Duffin43f7bf02021-05-05 22:00:51 +010070// SOONG_SDK_SNAPSHOT_VERSION
71// This provides control over the version of the generated snapshot.
72//
73// SOONG_SDK_SNAPSHOT_VERSION=current will generate unversioned and versioned prebuilts and a
74// versioned snapshot module. This is the default behavior. The zip file containing the
75// generated snapshot will be <sdk-name>-current.zip.
76//
77// SOONG_SDK_SNAPSHOT_VERSION=unversioned will generate unversioned prebuilts only and the zip
78// file containing the generated snapshot will be <sdk-name>.zip.
79//
80// SOONG_SDK_SNAPSHOT_VERSION=<number> will generate versioned prebuilts and a versioned
81// snapshot module only. The zip file containing the generated snapshot will be
82// <sdk-name>-<number>.zip.
83//
Paul Duffin39abf8f2021-09-24 14:58:27 +010084// SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE
85// This allows the target build release (i.e. the release version of the build within which
86// the snapshot will be used) of the snapshot to be specified. If unspecified then it defaults
87// to the current build release version. Otherwise, it must be the name of one of the build
88// releases defined in nameToBuildRelease, e.g. S, T, etc..
89//
90// The generated snapshot must only be used in the specified target release. If the target
91// build release is not the current build release then the generated Android.bp file not be
92// checked for compatibility.
93//
94// e.g. if setting SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE=S will cause the generated snapshot
95// to be compatible with S.
96//
Paul Duffin64fb5262021-05-05 21:36:04 +010097
Jiyong Park9b409bc2019-10-11 14:59:13 +090098var pctx = android.NewPackageContext("android/soong/sdk")
99
Paul Duffin375058f2019-11-29 20:17:53 +0000100var (
101 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
102 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +0000103 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +0000104 CommandDeps: []string{
105 "${config.Zip2ZipCmd}",
106 },
107 },
108 "destdir")
109
110 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
111 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -0700112 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +0000113 CommandDeps: []string{
114 "${config.SoongZipCmd}",
115 },
116 Rspfile: "$out.rsp",
117 RspfileContent: "$in",
118 },
119 "basedir")
120
121 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
122 blueprint.RuleParams{
123 Command: `${config.MergeZipsCmd} $out $in`,
124 CommandDeps: []string{
125 "${config.MergeZipsCmd}",
126 },
127 })
128)
129
Paul Duffin43f7bf02021-05-05 22:00:51 +0100130const (
131 soongSdkSnapshotVersionUnversioned = "unversioned"
132 soongSdkSnapshotVersionCurrent = "current"
133)
134
Paul Duffinb645ec82019-11-27 17:43:54 +0000135type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +0900136 content strings.Builder
137 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +0900138}
139
Paul Duffinb645ec82019-11-27 17:43:54 +0000140// generatedFile abstracts operations for writing contents into a file and emit a build rule
141// for the file.
142type generatedFile struct {
143 generatedContents
144 path android.OutputPath
145}
146
Jiyong Park232e7852019-11-04 12:23:40 +0900147func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +0900148 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +0000149 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +0900150 }
151}
152
Paul Duffinb645ec82019-11-27 17:43:54 +0000153func (gc *generatedContents) Indent() {
154 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +0900155}
156
Paul Duffinb645ec82019-11-27 17:43:54 +0000157func (gc *generatedContents) Dedent() {
158 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +0900159}
160
Paul Duffina08e4dc2021-06-22 18:19:19 +0100161// IndentedPrintf will add spaces to indent the line to the appropriate level before printing the
162// arguments.
163func (gc *generatedContents) IndentedPrintf(format string, args ...interface{}) {
164 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
165}
166
167// UnindentedPrintf does not add spaces to indent the line to the appropriate level before printing
168// the arguments.
169func (gc *generatedContents) UnindentedPrintf(format string, args ...interface{}) {
170 fmt.Fprintf(&(gc.content), format, args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900171}
172
173func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800174 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100175
176 content := gf.content.String()
177
178 // ninja consumes newline characters in rspfile_content. Prevent it by
179 // escaping the backslash in the newline character. The extra backslash
180 // is removed when the rspfile is written to the actual script file
181 content = strings.ReplaceAll(content, "\n", "\\n")
182
Jiyong Park9b409bc2019-10-11 14:59:13 +0900183 rb.Command().
184 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100185 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100186 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900187 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
188 rb.Command().
189 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800190 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900191}
192
Paul Duffin13879572019-11-28 14:31:38 +0000193// Collect all the members.
194//
Paul Duffinb97b1572021-04-29 21:50:40 +0100195// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
196// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000197func (s *sdk) collectMembers(ctx android.ModuleContext) {
198 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000199 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
200 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf7b3d0d2021-09-02 14:29:21 +0100201 if memberTag, ok := tag.(android.SdkMemberDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100202 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900203
Paul Duffin5cca7c42021-05-26 10:16:01 +0100204 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
205 if memberType == nil {
206 return false
207 }
208
Paul Duffin13879572019-11-28 14:31:38 +0000209 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000210 if !memberType.IsInstance(child) {
211 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900212 }
Paul Duffin13879572019-11-28 14:31:38 +0000213
Paul Duffin6a7e9532020-03-20 17:50:07 +0000214 // Keep track of which multilib variants are used by the sdk.
215 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
216
Paul Duffinb97b1572021-04-29 21:50:40 +0100217 var exportedComponentsInfo android.ExportedComponentsInfo
218 if ctx.OtherModuleHasProvider(child, android.ExportedComponentsInfoProvider) {
219 exportedComponentsInfo = ctx.OtherModuleProvider(child, android.ExportedComponentsInfoProvider).(android.ExportedComponentsInfo)
220 }
221
Paul Duffina7208112021-04-23 21:20:20 +0100222 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100223 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
224 s, memberType, child.(android.SdkAware), export, exportedComponentsInfo,
225 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000226
Paul Duffin2d3da312021-05-06 12:02:27 +0100227 // Recurse down into the member's dependencies as it may have dependencies that need to be
228 // automatically added to the sdk.
229 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900230 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000231
232 return false
Paul Duffin13879572019-11-28 14:31:38 +0000233 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000234}
235
Paul Duffincc3132e2021-04-24 01:10:30 +0100236// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
237// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000238//
Paul Duffincc3132e2021-04-24 01:10:30 +0100239// The sdkMember instances are then grouped into slices by member type. Within each such slice the
240// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000241//
Paul Duffincc3132e2021-04-24 01:10:30 +0100242// Finally, the member type slices are concatenated together to form a single slice. The order in
243// which they are concatenated is the order in which the member types were registered in the
244// android.SdkMemberTypesRegistry.
245func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000246 byType := make(map[android.SdkMemberType][]*sdkMember)
247 byName := make(map[string]*sdkMember)
248
Paul Duffin21827262021-04-24 12:16:36 +0100249 for _, memberVariantDep := range memberVariantDeps {
250 memberType := memberVariantDep.memberType
251 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000252
253 name := ctx.OtherModuleName(variant)
254 member := byName[name]
255 if member == nil {
256 member = &sdkMember{memberType: memberType, name: name}
257 byName[name] = member
258 byType[memberType] = append(byType[memberType], member)
259 }
260
Paul Duffin1356d8c2020-02-25 19:26:33 +0000261 // Only append new variants to the list. This is needed because a member can be both
262 // exported by the sdk and also be a transitive sdk member.
263 member.variants = appendUniqueVariants(member.variants, variant)
264 }
265
Paul Duffin13879572019-11-28 14:31:38 +0000266 var members []*sdkMember
Paul Duffin62782de2021-07-14 12:05:16 +0100267 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000268 membersOfType := byType[memberListProperty.memberType]
269 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900270 }
271
Paul Duffin6a7e9532020-03-20 17:50:07 +0000272 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900273}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900274
Paul Duffin72910952020-01-20 18:16:30 +0000275func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
276 for _, v := range variants {
277 if v == newVariant {
278 return variants
279 }
280 }
281 return append(variants, newVariant)
282}
283
Jiyong Park73c54ee2019-10-22 20:31:18 +0900284// SDK directory structure
285// <sdk_root>/
286// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
287// <api_ver>/ : below this directory are all auto-generated
288// Android.bp : definition of 'sdk_snapshot' module is here
289// aidl/
290// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
291// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900292// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900293// include/
294// bionic/libc/include/stdlib.h : an exported header file
295// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900296// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900297// <arch>/include/ : arch-specific exported headers
298// <arch>/include_gen/ : arch-specific generated headers
299// <arch>/lib/
300// libFoo.so : a stub library
301
Jiyong Park232e7852019-11-04 12:23:40 +0900302// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900303// This isn't visible to users, so could be changed in future.
304func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
305 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
306}
307
Jiyong Park232e7852019-11-04 12:23:40 +0900308// buildSnapshot is the main function in this source file. It creates rules to copy
309// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000310func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
311
Paul Duffinb97b1572021-04-29 21:50:40 +0100312 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100313 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100314 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000315 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100316 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100317 }
Paul Duffin865171e2020-03-02 18:38:15 +0000318
Paul Duffinb97b1572021-04-29 21:50:40 +0100319 // Filter out any sdkMemberVariantDep that is a component of another.
320 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000321
Paul Duffinb97b1572021-04-29 21:50:40 +0100322 // Record the names of all the members, both explicitly specified and implicitly
323 // included.
324 allMembersByName := make(map[string]struct{})
325 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100326
Paul Duffinb97b1572021-04-29 21:50:40 +0100327 addMember := func(name string, export bool) {
328 allMembersByName[name] = struct{}{}
329 if export {
330 exportedMembersByName[name] = struct{}{}
331 }
332 }
333
334 for _, memberVariantDep := range memberVariantDeps {
335 name := memberVariantDep.variant.Name()
336 export := memberVariantDep.export
337
338 addMember(name, export)
339
340 // Add any components provided by the module.
341 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
342 addMember(component, export)
343 }
344
345 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
346 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000347 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000348 }
349
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000350 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900351
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000352 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000353
354 bpFile := &bpFile{
355 modules: make(map[string]*bpModule),
356 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000357
Paul Duffin43f7bf02021-05-05 22:00:51 +0100358 config := ctx.Config()
359 version := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_VERSION", "current")
360
361 // Generate versioned modules in the snapshot unless an unversioned snapshot has been requested.
362 generateVersioned := version != soongSdkSnapshotVersionUnversioned
363
364 // Generate unversioned modules in the snapshot unless a numbered snapshot has been requested.
365 //
366 // Unversioned modules are not required in that case because the numbered version will be a
367 // finalized version of the snapshot that is intended to be kept separate from the
368 generateUnversioned := version == soongSdkSnapshotVersionUnversioned || version == soongSdkSnapshotVersionCurrent
369 snapshotZipFileSuffix := ""
370 if generateVersioned {
371 snapshotZipFileSuffix = "-" + version
372 }
373
Paul Duffin39abf8f2021-09-24 14:58:27 +0100374 currentBuildRelease := latestBuildRelease()
375 targetBuildReleaseEnv := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE", currentBuildRelease.name)
376 targetBuildRelease, err := nameToRelease(targetBuildReleaseEnv)
377 if err != nil {
378 ctx.ModuleErrorf("invalid SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE: %s", err)
379 targetBuildRelease = currentBuildRelease
380 }
381
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000382 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000383 ctx: ctx,
384 sdk: s,
Paul Duffin43f7bf02021-05-05 22:00:51 +0100385 version: version,
Paul Duffin13f02712020-03-06 12:30:43 +0000386 snapshotDir: snapshotDir.OutputPath,
387 copies: make(map[string]string),
388 filesToZip: []android.Path{bp.path},
389 bpFile: bpFile,
390 prebuiltModules: make(map[string]*bpModule),
391 allMembersByName: allMembersByName,
392 exportedMembersByName: exportedMembersByName,
Paul Duffin39abf8f2021-09-24 14:58:27 +0100393 targetBuildRelease: targetBuildRelease,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900394 }
Paul Duffinac37c502019-11-26 18:02:20 +0000395 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900396
Paul Duffin62131702021-05-07 01:10:01 +0100397 // If the sdk snapshot includes any license modules then add a package module which has a
398 // default_applicable_licenses property. That will prevent the LSC license process from updating
399 // the generated Android.bp file to add a package module that includes all licenses used by all
400 // the modules in that package. That would be unnecessary as every module in the sdk should have
401 // their own licenses property specified.
402 if hasLicenses {
403 pkg := bpFile.newModule("package")
404 property := "default_applicable_licenses"
405 pkg.AddCommentForProperty(property, `
406A default list here prevents the license LSC from adding its own list which would
407be unnecessary as every module in the sdk already has its own licenses property.
408`)
409 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
410 bpFile.AddModule(pkg)
411 }
412
Paul Duffin0df49682021-05-07 01:10:01 +0100413 // Group the variants for each member module together and then group the members of each member
414 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100415 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100416
417 // Create the prebuilt modules for each of the member modules.
Paul Duffind19f8942021-07-14 12:08:37 +0100418 traits := s.gatherTraits()
Paul Duffin13ad94f2020-02-19 16:19:27 +0000419 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000420 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000421
Paul Duffind19f8942021-07-14 12:08:37 +0100422 name := member.name
423 requiredTraits := traits[name]
424 if requiredTraits == nil {
425 requiredTraits = android.EmptySdkMemberTraitSet()
426 }
427
428 // Create the snapshot for the member.
429 memberCtx := &memberContext{ctx, builder, memberType, name, requiredTraits}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000430
431 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100432 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900433 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900434
Paul Duffine6c0d842020-01-15 14:08:51 +0000435 // Create a transformer that will transform an unversioned module into a versioned module.
436 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
437
Paul Duffin72910952020-01-20 18:16:30 +0000438 // Create a transformer that will transform an unversioned module by replacing any references
439 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100440 unversionedTransformer := unversionedTransformation{
441 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100442 }
Paul Duffin72910952020-01-20 18:16:30 +0000443
Paul Duffinb645ec82019-11-27 17:43:54 +0000444 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000445 // Prune any empty property sets.
446 unversioned = unversioned.transform(pruneEmptySetTransformer{})
447
Paul Duffin43f7bf02021-05-05 22:00:51 +0100448 if generateVersioned {
449 // Copy the unversioned module so it can be modified to make it versioned.
450 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000451
Paul Duffin43f7bf02021-05-05 22:00:51 +0100452 // Transform the unversioned module into a versioned one.
453 versioned.transform(unversionedToVersionedTransformer)
454 bpFile.AddModule(versioned)
455 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000456
Paul Duffin43f7bf02021-05-05 22:00:51 +0100457 if generateUnversioned {
458 // Transform the unversioned module to make it suitable for use in the snapshot.
459 unversioned.transform(unversionedTransformer)
460 bpFile.AddModule(unversioned)
461 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000462 }
463
Paul Duffin43f7bf02021-05-05 22:00:51 +0100464 if generateVersioned {
465 // Add the sdk/module_exports_snapshot module to the bp file.
466 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
467 }
Paul Duffin26197a62021-04-24 00:34:10 +0100468
469 // generate Android.bp
470 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
471 generateBpContents(&bp.generatedContents, bpFile)
472
473 contents := bp.content.String()
Paul Duffin39abf8f2021-09-24 14:58:27 +0100474 // If the snapshot is being generated for the current build release then check the syntax to make
475 // sure that it is compatible.
476 if targetBuildRelease == currentBuildRelease {
477 syntaxCheckSnapshotBpFile(ctx, contents)
478 }
Paul Duffin26197a62021-04-24 00:34:10 +0100479
480 bp.build(pctx, ctx, nil)
481
482 filesToZip := builder.filesToZip
483
484 // zip them all
Paul Duffin43f7bf02021-05-05 22:00:51 +0100485 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotZipFileSuffix)
486 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100487 outputDesc := "Building snapshot for " + ctx.ModuleName()
488
489 // If there are no zips to merge then generate the output zip directly.
490 // Otherwise, generate an intermediate zip file into which other zips can be
491 // merged.
492 var zipFile android.OutputPath
493 var desc string
494 if len(builder.zipsToMerge) == 0 {
495 zipFile = outputZipFile
496 desc = outputDesc
497 } else {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100498 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotZipFileSuffix)
499 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100500 desc = "Building intermediate snapshot for " + ctx.ModuleName()
501 }
502
503 ctx.Build(pctx, android.BuildParams{
504 Description: desc,
505 Rule: zipFiles,
506 Inputs: filesToZip,
507 Output: zipFile,
508 Args: map[string]string{
509 "basedir": builder.snapshotDir.String(),
510 },
511 })
512
513 if len(builder.zipsToMerge) != 0 {
514 ctx.Build(pctx, android.BuildParams{
515 Description: outputDesc,
516 Rule: mergeZips,
517 Input: zipFile,
518 Inputs: builder.zipsToMerge,
519 Output: outputZipFile,
520 })
521 }
522
523 return outputZipFile
524}
525
Paul Duffinb97b1572021-04-29 21:50:40 +0100526// filterOutComponents removes any item from the deps list that is a component of another item in
527// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
528// then it will remove "foo.stubs" from the deps.
529func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
530 // Collate the set of components that all the modules added to the sdk provide.
531 components := map[string]*sdkMemberVariantDep{}
532 for i, _ := range deps {
533 dep := &deps[i]
534 for _, c := range dep.exportedComponentsInfo.Components {
535 components[c] = dep
536 }
537 }
538
539 // If no module provides components then return the input deps unfiltered.
540 if len(components) == 0 {
541 return deps
542 }
543
544 filtered := make([]sdkMemberVariantDep, 0, len(deps))
545 for _, dep := range deps {
546 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
547 if owner, ok := components[name]; ok {
548 // This is a component of another module that is a member of the sdk.
549
550 // If the component is exported but the owning module is not then the configuration is not
551 // supported.
552 if dep.export && !owner.export {
553 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
554 continue
555 }
556
557 // This module must not be added to the list of members of the sdk as that would result in a
558 // duplicate module in the sdk snapshot.
559 continue
560 }
561
562 filtered = append(filtered, dep)
563 }
564 return filtered
565}
566
Paul Duffin26197a62021-04-24 00:34:10 +0100567// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100568func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100569 bpFile := builder.bpFile
570
Paul Duffinb645ec82019-11-27 17:43:54 +0000571 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000572 var snapshotModuleType string
573 if s.properties.Module_exports {
574 snapshotModuleType = "module_exports_snapshot"
575 } else {
576 snapshotModuleType = "sdk_snapshot"
577 }
578 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000579 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000580
581 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100582 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000583 if len(visibility) != 0 {
584 snapshotModule.AddProperty("visibility", visibility)
585 }
586
Paul Duffin865171e2020-03-02 18:38:15 +0000587 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000588
Paul Duffincd064672021-04-24 00:47:29 +0100589 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100590 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000591
Paul Duffin2d1bb892021-04-24 11:32:59 +0100592 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100593
Paul Duffin6a7e9532020-03-20 17:50:07 +0000594 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100595
Paul Duffin2d1bb892021-04-24 11:32:59 +0100596 // Create a mapping from osType to combined properties.
597 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
598 for _, combined := range combinedPropertiesList {
599 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
600 }
601
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100602 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000603 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100604 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100605 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000606
Paul Duffin2d1bb892021-04-24 11:32:59 +0100607 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000608 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000609 }
Paul Duffin865171e2020-03-02 18:38:15 +0000610
Jiyong Park8fe14e62020-10-19 22:47:34 +0900611 // If host is supported and any member is host OS dependent then disable host
612 // by default, so that we can enable each host OS variant explicitly. This
613 // avoids problems with implicitly enabled OS variants when the snapshot is
614 // used, which might be different from this run (e.g. different build OS).
615 if s.HostSupported() {
616 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100617 for _, memberVariantDep := range memberVariantDeps {
618 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
619 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900620 if !android.InList(targetString, supportedHostTargets) {
621 supportedHostTargets = append(supportedHostTargets, targetString)
622 }
623 }
624 }
625 if len(supportedHostTargets) > 0 {
626 hostPropertySet := targetPropertySet.AddPropertySet("host")
627 hostPropertySet.AddProperty("enabled", false)
628 }
629 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
630 for _, hostTarget := range supportedHostTargets {
631 propertySet := targetPropertySet.AddPropertySet(hostTarget)
632 propertySet.AddProperty("enabled", true)
633 }
634 }
635
Paul Duffin865171e2020-03-02 18:38:15 +0000636 // Prune any empty property sets.
637 snapshotModule.transform(pruneEmptySetTransformer{})
638
Paul Duffinb645ec82019-11-27 17:43:54 +0000639 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900640}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000641
Paul Duffinf88d8e02020-05-07 20:21:34 +0100642// Check the syntax of the generated Android.bp file contents and if they are
643// invalid then log an error with the contents (tagged with line numbers) and the
644// errors that were found so that it is easy to see where the problem lies.
645func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
646 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
647 if len(errs) != 0 {
648 message := &strings.Builder{}
649 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
650
651Generated Android.bp contents
652========================================================================
653`)
654 for i, line := range strings.Split(contents, "\n") {
655 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
656 }
657
658 _, _ = fmt.Fprint(message, `
659========================================================================
660
661Errors found:
662`)
663
664 for _, err := range errs {
665 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
666 }
667
668 ctx.ModuleErrorf("%s", message.String())
669 }
670}
671
Paul Duffin4b8b7932020-05-06 12:35:38 +0100672func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
673 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
674 if err != nil {
675 ctx.ModuleErrorf("error extracting common properties: %s", err)
676 }
677}
678
Paul Duffinfbe470e2021-04-24 12:37:13 +0100679// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
680type snapshotModuleStaticProperties struct {
681 Compile_multilib string `android:"arch_variant"`
682}
683
Paul Duffin2d1bb892021-04-24 11:32:59 +0100684// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
685type combinedSnapshotModuleProperties struct {
686 // The sdk variant from which this information was collected.
687 sdkVariant *sdk
688
689 // Static snapshot module properties.
690 staticProperties *snapshotModuleStaticProperties
691
692 // The dynamically generated member list properties.
693 dynamicProperties interface{}
694}
695
696// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100697func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
698 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100699 var list []*combinedSnapshotModuleProperties
700 for _, sdkVariant := range sdkVariants {
701 staticProperties := &snapshotModuleStaticProperties{
702 Compile_multilib: sdkVariant.multilibUsages.String(),
703 }
Paul Duffin62782de2021-07-14 12:05:16 +0100704 dynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100705
Paul Duffincd064672021-04-24 00:47:29 +0100706 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100707 sdkVariant: sdkVariant,
708 staticProperties: staticProperties,
709 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100710 }
711 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
712
713 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100714 }
Paul Duffincd064672021-04-24 00:47:29 +0100715
716 for _, memberVariantDep := range memberVariantDeps {
717 // If the member dependency is internal then do not add the dependency to the snapshot member
718 // list properties.
719 if !memberVariantDep.export {
720 continue
721 }
722
723 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin62782de2021-07-14 12:05:16 +0100724 memberListProperty := s.memberTypeListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100725 memberName := ctx.OtherModuleName(memberVariantDep.variant)
726
Paul Duffin13082052021-05-11 00:31:38 +0100727 if memberListProperty.getter == nil {
728 continue
729 }
730
Paul Duffincd064672021-04-24 00:47:29 +0100731 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100732 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100733 if !android.InList(memberName, memberList) {
734 memberList = append(memberList, memberName)
735 }
Paul Duffin13082052021-05-11 00:31:38 +0100736 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100737 }
738
Paul Duffin2d1bb892021-04-24 11:32:59 +0100739 return list
740}
741
742func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
743
744 // Extract the dynamic properties and add them to a list of propertiesContainer.
745 propertyContainers := []propertiesContainer{}
746 for _, i := range list {
747 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
748 sdkVariant: i.sdkVariant,
749 properties: i.dynamicProperties,
750 })
751 }
752
753 // Extract the common members, removing them from the original properties.
Paul Duffin62782de2021-07-14 12:05:16 +0100754 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100755 extractor := newCommonValueExtractor(commonDynamicProperties)
756 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
757
758 // Extract the static properties and add them to a list of propertiesContainer.
759 propertyContainers = []propertiesContainer{}
760 for _, i := range list {
761 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
762 sdkVariant: i.sdkVariant,
763 properties: i.staticProperties,
764 })
765 }
766
767 commonStaticProperties := &snapshotModuleStaticProperties{}
768 extractor = newCommonValueExtractor(commonStaticProperties)
769 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
770
771 return &combinedSnapshotModuleProperties{
772 sdkVariant: nil,
773 staticProperties: commonStaticProperties,
774 dynamicProperties: commonDynamicProperties,
775 }
776}
777
778func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
779 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100780 multilib := staticProperties.Compile_multilib
781 if multilib != "" && multilib != "both" {
782 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
783 propertySet.AddProperty("compile_multilib", multilib)
784 }
785
Paul Duffin2d1bb892021-04-24 11:32:59 +0100786 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin62782de2021-07-14 12:05:16 +0100787 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100788 if memberListProperty.getter == nil {
789 continue
790 }
Paul Duffin865171e2020-03-02 18:38:15 +0000791 names := memberListProperty.getter(dynamicMemberTypeListProperties)
792 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000793 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000794 }
795 }
796}
797
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000798type propertyTag struct {
799 name string
800}
801
Paul Duffin94289702021-09-09 15:38:32 +0100802var _ android.BpPropertyTag = propertyTag{}
803
Paul Duffin0cb37b92020-03-04 14:52:46 +0000804// A BpPropertyTag to add to a property that contains references to other sdk members.
805//
806// This will cause the references to be rewritten to a versioned reference in the version
807// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000808var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000809var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000810
Paul Duffin0cb37b92020-03-04 14:52:46 +0000811// A BpPropertyTag that indicates the property should only be present in the versioned
812// module.
813//
814// This will cause the property to be removed from the unversioned instance of a
815// snapshot module.
816var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
817
Paul Duffine6c0d842020-01-15 14:08:51 +0000818type unversionedToVersionedTransformation struct {
819 identityTransformation
820 builder *snapshotBuilder
821}
822
Paul Duffine6c0d842020-01-15 14:08:51 +0000823func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
824 // Use a versioned name for the module but remember the original name for the
825 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100826 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000827 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000828 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100829 // Remove the prefer property if present as versioned modules never need marking with prefer.
830 module.removeProperty("prefer")
Paul Duffinfb9a7f92021-07-06 17:18:42 +0100831 // Ditto for use_source_config_var
832 module.removeProperty("use_source_config_var")
Paul Duffine6c0d842020-01-15 14:08:51 +0000833 return module
834}
835
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000836func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000837 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
838 required := tag == requiredSdkMemberReferencePropertyTag
839 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000840 } else {
841 return value, tag
842 }
843}
844
Paul Duffin72910952020-01-20 18:16:30 +0000845type unversionedTransformation struct {
846 identityTransformation
847 builder *snapshotBuilder
848}
849
850func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
851 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100852 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000853 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000854 return module
855}
856
857func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000858 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
859 required := tag == requiredSdkMemberReferencePropertyTag
860 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000861 } else if tag == sdkVersionedOnlyPropertyTag {
862 // The property is not allowed in the unversioned module so remove it.
863 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000864 } else {
865 return value, tag
866 }
867}
868
Paul Duffina78f3a72020-02-21 16:29:35 +0000869type pruneEmptySetTransformer struct {
870 identityTransformation
871}
872
873var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
874
875func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
876 if len(propertySet.properties) == 0 {
877 return nil, nil
878 } else {
879 return propertySet, tag
880 }
881}
882
Paul Duffinb645ec82019-11-27 17:43:54 +0000883func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000884 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
885 return true
886 })
887}
888
889func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100890 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000891 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000892 if moduleFilter(bpModule) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100893 contents.IndentedPrintf("\n")
894 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
Paul Duffind0759072021-02-17 11:23:00 +0000895 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100896 contents.IndentedPrintf("}\n")
Paul Duffind0759072021-02-17 11:23:00 +0000897 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000898 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000899}
900
901func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
902 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000903
Paul Duffin0df49682021-05-07 01:10:01 +0100904 addComment := func(name string) {
905 if text, ok := set.comments[name]; ok {
906 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100907 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100908 }
909 }
910 }
911
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000912 // Output the properties first, followed by the nested sets. This ensures a
913 // consistent output irrespective of whether property sets are created before
914 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000915 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000916 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000917
Paul Duffin0df49682021-05-07 01:10:01 +0100918 // Do not write property sets in the properties phase.
919 if _, ok := value.(*bpPropertySet); ok {
920 continue
921 }
922
923 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100924 reflectValue := reflect.ValueOf(value)
925 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000926 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000927
928 for _, name := range set.order {
929 value := set.getValue(name)
930
931 // Only write property sets in the sets phase.
932 switch v := value.(type) {
933 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100934 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100935 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000936 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100937 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000938 }
939 }
940
Paul Duffinb645ec82019-11-27 17:43:54 +0000941 contents.Dedent()
942}
943
Paul Duffina08e4dc2021-06-22 18:19:19 +0100944// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
945// by the value and then followed by a , and a newline.
946func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
947 contents.IndentedPrintf("%s: ", name)
948 outputUnnamedValue(contents, value)
949 contents.UnindentedPrintf(",\n")
950}
951
952// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
953// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
954// indented and all but the last line will end with a newline.
955func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
956 valueType := value.Type()
957 switch valueType.Kind() {
958 case reflect.Bool:
959 contents.UnindentedPrintf("%t", value.Bool())
960
961 case reflect.String:
962 contents.UnindentedPrintf("%q", value)
963
Paul Duffin51227d82021-05-18 12:54:27 +0100964 case reflect.Ptr:
965 outputUnnamedValue(contents, value.Elem())
966
Paul Duffina08e4dc2021-06-22 18:19:19 +0100967 case reflect.Slice:
968 length := value.Len()
969 if length == 0 {
970 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100971 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100972 firstValue := value.Index(0)
973 if length == 1 && !multiLineValue(firstValue) {
974 contents.UnindentedPrintf("[")
975 outputUnnamedValue(contents, firstValue)
976 contents.UnindentedPrintf("]")
977 } else {
978 contents.UnindentedPrintf("[\n")
979 contents.Indent()
980 for i := 0; i < length; i++ {
981 itemValue := value.Index(i)
982 contents.IndentedPrintf("")
983 outputUnnamedValue(contents, itemValue)
984 contents.UnindentedPrintf(",\n")
985 }
986 contents.Dedent()
987 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100988 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100989 }
990
Paul Duffin51227d82021-05-18 12:54:27 +0100991 case reflect.Struct:
992 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
993 v := value.Interface()
994 if _, ok := v.(android.BpPrintable); !ok {
995 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
996 }
997 contents.UnindentedPrintf("{\n")
998 contents.Indent()
999 for f := 0; f < valueType.NumField(); f++ {
1000 fieldType := valueType.Field(f)
1001 if fieldType.Anonymous {
1002 continue
1003 }
1004 fieldValue := value.Field(f)
1005 fieldName := fieldType.Name
1006 propertyName := proptools.PropertyNameForField(fieldName)
1007 outputNamedValue(contents, propertyName, fieldValue)
1008 }
1009 contents.Dedent()
1010 contents.IndentedPrintf("}")
1011
Paul Duffina08e4dc2021-06-22 18:19:19 +01001012 default:
1013 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
1014 }
1015}
1016
Paul Duffin51227d82021-05-18 12:54:27 +01001017// multiLineValue returns true if the supplied value may require multiple lines in the output.
1018func multiLineValue(value reflect.Value) bool {
1019 kind := value.Kind()
1020 return kind == reflect.Slice || kind == reflect.Struct
1021}
1022
Paul Duffinac37c502019-11-26 18:02:20 +00001023func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001024 contents := &generatedContents{}
1025 generateBpContents(contents, s.builderForTests.bpFile)
1026 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +00001027}
1028
Paul Duffind0759072021-02-17 11:23:00 +00001029func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
1030 contents := &generatedContents{}
1031 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001032 name := module.Name()
1033 // Include modules that are either unversioned or have no name.
1034 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001035 })
1036 return contents.content.String()
1037}
1038
1039func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
1040 contents := &generatedContents{}
1041 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001042 name := module.Name()
1043 // Include modules that are either versioned or have no name.
1044 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001045 })
1046 return contents.content.String()
1047}
1048
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001049type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +01001050 ctx android.ModuleContext
1051 sdk *sdk
1052
1053 // The version of the generated snapshot.
1054 //
1055 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
1056 // this field.
1057 version string
1058
Paul Duffinb645ec82019-11-27 17:43:54 +00001059 snapshotDir android.OutputPath
1060 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +00001061
1062 // Map from destination to source of each copy - used to eliminate duplicates and
1063 // detect conflicts.
1064 copies map[string]string
1065
Paul Duffinb645ec82019-11-27 17:43:54 +00001066 filesToZip android.Paths
1067 zipsToMerge android.Paths
1068
Paul Duffin5c211452021-07-15 12:42:44 +01001069 // The path to an empty file.
1070 emptyFile android.WritablePath
1071
Paul Duffinb645ec82019-11-27 17:43:54 +00001072 prebuiltModules map[string]*bpModule
1073 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001074
1075 // The set of all members by name.
1076 allMembersByName map[string]struct{}
1077
1078 // The set of exported members by name.
1079 exportedMembersByName map[string]struct{}
Paul Duffin39abf8f2021-09-24 14:58:27 +01001080
1081 // The target build release for which the snapshot is to be generated.
1082 targetBuildRelease *buildRelease
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001083}
1084
1085func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001086 if existing, ok := s.copies[dest]; ok {
1087 if existing != src.String() {
1088 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1089 return
1090 }
1091 } else {
1092 path := s.snapshotDir.Join(s.ctx, dest)
1093 s.ctx.Build(pctx, android.BuildParams{
1094 Rule: android.Cp,
1095 Input: src,
1096 Output: path,
1097 })
1098 s.filesToZip = append(s.filesToZip, path)
1099
1100 s.copies[dest] = src.String()
1101 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001102}
1103
Paul Duffin91547182019-11-12 19:39:36 +00001104func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1105 ctx := s.ctx
1106
1107 // Repackage the zip file so that the entries are in the destDir directory.
1108 // This will allow the zip file to be merged into the snapshot.
1109 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001110
1111 ctx.Build(pctx, android.BuildParams{
1112 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1113 Rule: repackageZip,
1114 Input: zipPath,
1115 Output: tmpZipPath,
1116 Args: map[string]string{
1117 "destdir": destDir,
1118 },
1119 })
Paul Duffin91547182019-11-12 19:39:36 +00001120
1121 // Add the repackaged zip file to the files to merge.
1122 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1123}
1124
Paul Duffin5c211452021-07-15 12:42:44 +01001125func (s *snapshotBuilder) EmptyFile() android.Path {
1126 if s.emptyFile == nil {
1127 ctx := s.ctx
1128 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1129 s.ctx.Build(pctx, android.BuildParams{
1130 Rule: android.Touch,
1131 Output: s.emptyFile,
1132 })
1133 }
1134
1135 return s.emptyFile
1136}
1137
Paul Duffin9d8d6092019-12-05 18:19:29 +00001138func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1139 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001140 if s.prebuiltModules[name] != nil {
1141 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1142 }
1143
1144 m := s.bpFile.newModule(moduleType)
1145 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001146
Paul Duffinbefa4b92020-03-04 14:22:45 +00001147 variant := member.Variants()[0]
1148
Paul Duffin13f02712020-03-06 12:30:43 +00001149 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001150 // An internal member is only referenced from the sdk snapshot which is in the
1151 // same package so can be marked as private.
1152 m.AddProperty("visibility", []string{"//visibility:private"})
1153 } else {
1154 // Extract visibility information from a member variant. All variants have the same
1155 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001156 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1157
1158 // Add any additional visibility rules needed for the prebuilts to reference each other.
1159 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1160 if err != nil {
1161 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1162 }
1163
1164 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001165 if len(visibility) != 0 {
1166 m.AddProperty("visibility", visibility)
1167 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001168 }
1169
Martin Stjernholm1e041092020-11-03 00:11:09 +00001170 // Where available copy apex_available properties from the member.
1171 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1172 apexAvailable := apexAware.ApexAvailable()
1173 if len(apexAvailable) == 0 {
1174 // //apex_available:platform is the default.
1175 apexAvailable = []string{android.AvailableToPlatform}
1176 }
1177
1178 // Add in any baseline apex available settings.
1179 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1180
1181 // Remove duplicates and sort.
1182 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1183 sort.Strings(apexAvailable)
1184
1185 m.AddProperty("apex_available", apexAvailable)
1186 }
1187
Paul Duffinb0bb3762021-05-06 16:48:05 +01001188 // The licenses are the same for all variants.
1189 mctx := s.ctx
1190 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1191 if len(licenseInfo.Licenses) > 0 {
1192 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1193 }
1194
Paul Duffin865171e2020-03-02 18:38:15 +00001195 deviceSupported := false
1196 hostSupported := false
1197
1198 for _, variant := range member.Variants() {
1199 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001200 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001201 hostSupported = true
1202 } else if osClass == android.Device {
1203 deviceSupported = true
1204 }
1205 }
1206
1207 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001208
Paul Duffin0cb37b92020-03-04 14:52:46 +00001209 // Disable installation in the versioned module of those modules that are ever installable.
1210 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1211 if installable.EverInstallable() {
1212 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1213 }
1214 }
1215
Paul Duffinb645ec82019-11-27 17:43:54 +00001216 s.prebuiltModules[name] = m
1217 s.prebuiltOrder = append(s.prebuiltOrder, m)
1218 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001219}
1220
Paul Duffin865171e2020-03-02 18:38:15 +00001221func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001222 // If neither device or host is supported then this module does not support either so will not
1223 // recognize the properties.
1224 if !deviceSupported && !hostSupported {
1225 return
1226 }
1227
Paul Duffin865171e2020-03-02 18:38:15 +00001228 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001229 bpModule.AddProperty("device_supported", false)
1230 }
Paul Duffin865171e2020-03-02 18:38:15 +00001231 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001232 bpModule.AddProperty("host_supported", true)
1233 }
1234}
1235
Paul Duffin13f02712020-03-06 12:30:43 +00001236func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1237 if required {
1238 return requiredSdkMemberReferencePropertyTag
1239 } else {
1240 return optionalSdkMemberReferencePropertyTag
1241 }
1242}
1243
1244func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1245 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001246}
1247
Paul Duffinb645ec82019-11-27 17:43:54 +00001248// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001249func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1250 if _, ok := s.allMembersByName[unversionedName]; !ok {
1251 if required {
1252 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1253 }
1254 return unversionedName
1255 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001256 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1257}
Paul Duffinb645ec82019-11-27 17:43:54 +00001258
Paul Duffin13f02712020-03-06 12:30:43 +00001259func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001260 var references []string = nil
1261 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001262 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001263 }
1264 return references
1265}
Paul Duffin13879572019-11-28 14:31:38 +00001266
Paul Duffin72910952020-01-20 18:16:30 +00001267// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001268func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1269 if _, ok := s.allMembersByName[unversionedName]; !ok {
1270 if required {
1271 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1272 }
1273 return unversionedName
1274 }
1275
1276 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001277 return s.ctx.ModuleName() + "_" + unversionedName
1278 } else {
1279 return unversionedName
1280 }
1281}
1282
Paul Duffin13f02712020-03-06 12:30:43 +00001283func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001284 var references []string = nil
1285 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001286 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001287 }
1288 return references
1289}
1290
Paul Duffin13f02712020-03-06 12:30:43 +00001291func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1292 _, ok := s.exportedMembersByName[memberName]
1293 return !ok
1294}
1295
Martin Stjernholm89238f42020-07-10 00:14:03 +01001296// Add the properties from the given SdkMemberProperties to the blueprint
1297// property set. This handles common properties in SdkMemberPropertiesBase and
1298// calls the member-specific AddToPropertySet for the rest.
1299func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1300 if memberProperties.Base().Compile_multilib != "" {
1301 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1302 }
1303
1304 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1305}
1306
Paul Duffin21827262021-04-24 12:16:36 +01001307// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1308type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001309 // The sdk variant that depends (possibly indirectly) on the member variant.
1310 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001311
1312 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001313 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001314
1315 // The variant that is added to the sdk.
1316 variant android.SdkAware
1317
1318 // True if the member should be exported, i.e. accessible, from outside the sdk.
1319 export bool
1320
1321 // The names of additional component modules provided by the variant.
1322 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001323}
1324
Paul Duffin13879572019-11-28 14:31:38 +00001325var _ android.SdkMember = (*sdkMember)(nil)
1326
Paul Duffin21827262021-04-24 12:16:36 +01001327// sdkMember groups all the variants of a specific member module together along with the name of the
1328// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001329type sdkMember struct {
1330 memberType android.SdkMemberType
1331 name string
1332 variants []android.SdkAware
1333}
1334
1335func (m *sdkMember) Name() string {
1336 return m.name
1337}
1338
1339func (m *sdkMember) Variants() []android.SdkAware {
1340 return m.variants
1341}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001342
Paul Duffin9c3760e2020-03-16 19:52:08 +00001343// Track usages of multilib variants.
1344type multilibUsage int
1345
1346const (
1347 multilibNone multilibUsage = 0
1348 multilib32 multilibUsage = 1
1349 multilib64 multilibUsage = 2
1350 multilibBoth = multilib32 | multilib64
1351)
1352
1353// Add the multilib that is used in the arch type.
1354func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1355 multilib := archType.Multilib
1356 switch multilib {
1357 case "":
1358 return m
1359 case "lib32":
1360 return m | multilib32
1361 case "lib64":
1362 return m | multilib64
1363 default:
1364 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1365 }
1366}
1367
1368func (m multilibUsage) String() string {
1369 switch m {
1370 case multilibNone:
1371 return ""
1372 case multilib32:
1373 return "32"
1374 case multilib64:
1375 return "64"
1376 case multilibBoth:
1377 return "both"
1378 default:
1379 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1380 m, multilibNone, multilib32, multilib64, multilibBoth))
1381 }
1382}
1383
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001384type baseInfo struct {
1385 Properties android.SdkMemberProperties
1386}
1387
Paul Duffinf34f6d82020-04-30 15:48:31 +01001388func (b *baseInfo) optimizableProperties() interface{} {
1389 return b.Properties
1390}
1391
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001392type osTypeSpecificInfo struct {
1393 baseInfo
1394
Paul Duffin00e46802020-03-12 20:40:35 +00001395 osType android.OsType
1396
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001397 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001398 //
1399 // Nil if there is one variant whose arch type is common
1400 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001401}
1402
Paul Duffin4b8b7932020-05-06 12:35:38 +01001403var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1404
Paul Duffinfc8dd232020-03-17 12:51:37 +00001405type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1406
Paul Duffin00e46802020-03-12 20:40:35 +00001407// Create a new osTypeSpecificInfo for the specified os type and its properties
1408// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001409func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001410 osInfo := &osTypeSpecificInfo{
1411 osType: osType,
1412 }
1413
1414 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1415 properties := variantPropertiesFactory()
1416 properties.Base().Os = osType
1417 return properties
1418 }
1419
1420 // Create a structure into which properties common across the architectures in
1421 // this os type will be stored.
1422 osInfo.Properties = osSpecificVariantPropertiesFactory()
1423
1424 // Group the variants by arch type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001425 var variantsByArchId = make(map[archId][]android.Module)
1426 var archIds []archId
Paul Duffin00e46802020-03-12 20:40:35 +00001427 for _, variant := range osTypeVariants {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001428 target := variant.Target()
1429 id := archIdFromTarget(target)
1430 if _, ok := variantsByArchId[id]; !ok {
1431 archIds = append(archIds, id)
Paul Duffin00e46802020-03-12 20:40:35 +00001432 }
1433
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001434 variantsByArchId[id] = append(variantsByArchId[id], variant)
Paul Duffin00e46802020-03-12 20:40:35 +00001435 }
1436
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001437 if commonVariants, ok := variantsByArchId[commonArchId]; ok {
Paul Duffin00e46802020-03-12 20:40:35 +00001438 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001439 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 +00001440 }
1441
1442 // A common arch type only has one variant and its properties should be treated
1443 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001444 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001445 } else {
1446 // Create an arch specific info for each supported architecture type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001447 for _, id := range archIds {
1448 archVariants := variantsByArchId[id]
1449 archInfo := newArchSpecificInfo(ctx, id, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001450
1451 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1452 }
1453 }
1454
1455 return osInfo
1456}
1457
Paul Duffin39abf8f2021-09-24 14:58:27 +01001458func (osInfo *osTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1459 if len(osInfo.archInfos) == 0 {
1460 pruner.pruneProperties(osInfo.Properties)
1461 } else {
1462 for _, archInfo := range osInfo.archInfos {
1463 archInfo.pruneUnsupportedProperties(pruner)
1464 }
1465 }
1466}
1467
Paul Duffin00e46802020-03-12 20:40:35 +00001468// Optimize the properties by extracting common properties from arch type specific
1469// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001470func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001471 // Nothing to do if there is only a single common architecture.
1472 if len(osInfo.archInfos) == 0 {
1473 return
1474 }
1475
Paul Duffin9c3760e2020-03-16 19:52:08 +00001476 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001477 for _, archInfo := range osInfo.archInfos {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001478 multilib = multilib.addArchType(archInfo.archId.archType)
Paul Duffin9c3760e2020-03-16 19:52:08 +00001479
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001480 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001481 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001482 }
1483
Paul Duffin4b8b7932020-05-06 12:35:38 +01001484 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001485
1486 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001487 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001488}
1489
1490// Add the properties for an os to a property set.
1491//
1492// Maps the properties related to the os variants through to an appropriate
1493// module structure that will produce equivalent set of variants when it is
1494// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001495func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001496
1497 var osPropertySet android.BpPropertySet
1498 var archPropertySet android.BpPropertySet
1499 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001500 if osInfo.Properties.Base().Os_count == 1 &&
1501 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1502 // There is only one OS type present in the variants and it shouldn't have a
1503 // variant-specific target. The latter is the case if it's either for device
1504 // where there is only one OS (android), or for host and the member type
1505 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001506
1507 // Create a structure that looks like:
1508 // module_type {
1509 // name: "...",
1510 // ...
1511 // <common properties>
1512 // ...
1513 // <single os type specific properties>
1514 //
1515 // arch: {
1516 // <arch specific sections>
1517 // }
1518 //
1519 osPropertySet = bpModule
1520 archPropertySet = osPropertySet.AddPropertySet("arch")
1521
1522 // Arch specific properties need to be added to an arch specific section
1523 // within arch.
1524 archOsPrefix = ""
1525 } else {
1526 // Create a structure that looks like:
1527 // module_type {
1528 // name: "...",
1529 // ...
1530 // <common properties>
1531 // ...
1532 // target: {
1533 // <arch independent os specific sections, e.g. android>
1534 // ...
1535 // <arch and os specific sections, e.g. android_x86>
1536 // }
1537 //
1538 osType := osInfo.osType
1539 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1540 archPropertySet = targetPropertySet
1541
1542 // Arch specific properties need to be added to an os and arch specific
1543 // section prefixed with <os>_.
1544 archOsPrefix = osType.Name + "_"
1545 }
1546
1547 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001548 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001549
1550 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1551 // os) specific properties.
1552 //
1553 // The archInfos list will be empty if the os contains variants for the common
1554 // architecture.
1555 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001556 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001557 }
1558}
1559
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001560func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1561 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001562 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001563}
1564
1565var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1566
Paul Duffin4b8b7932020-05-06 12:35:38 +01001567func (osInfo *osTypeSpecificInfo) String() string {
1568 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1569}
1570
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001571// archId encapsulates the information needed to identify a combination of arch type and native
1572// bridge support.
1573//
1574// Conceptually, native bridge support is a facet of an android.Target, not an android.Arch as it is
1575// essentially using one android.Arch to implement another. However, in terms of the handling of
1576// the variants native bridge is treated as part of the arch variation. See the ArchVariation method
1577// on android.Target.
1578//
1579// So, it makes sense when optimizing the variants to combine native bridge with the arch type.
1580type archId struct {
1581 // The arch type of the variant's target.
1582 archType android.ArchType
1583
1584 // True if the variants is for the native bridge, false otherwise.
1585 nativeBridge bool
1586}
1587
1588// propertyName returns the name of the property corresponding to use for this arch id.
1589func (i *archId) propertyName() string {
1590 name := i.archType.Name
1591 if i.nativeBridge {
1592 // Note: This does not result in a valid property because there is no architecture specific
1593 // native bridge property, only a generic "native_bridge" property. However, this will be used
1594 // in error messages if there is an attempt to use this in a generated bp file.
1595 name += "_native_bridge"
1596 }
1597 return name
1598}
1599
1600func (i *archId) String() string {
1601 return fmt.Sprintf("ArchType{%s}, NativeBridge{%t}", i.archType, i.nativeBridge)
1602}
1603
1604// archIdFromTarget returns an archId initialized from information in the supplied target.
1605func archIdFromTarget(target android.Target) archId {
1606 return archId{
1607 archType: target.Arch.ArchType,
1608 nativeBridge: target.NativeBridge == android.NativeBridgeEnabled,
1609 }
1610}
1611
1612// commonArchId is the archId for the common architecture.
1613var commonArchId = archId{archType: android.Common}
1614
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001615type archTypeSpecificInfo struct {
1616 baseInfo
1617
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001618 archId archId
1619 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001620
Paul Duffinb42fa672021-09-09 16:37:49 +01001621 imageVariantInfos []*imageVariantSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001622}
1623
Paul Duffin4b8b7932020-05-06 12:35:38 +01001624var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1625
Paul Duffinfc8dd232020-03-17 12:51:37 +00001626// Create a new archTypeSpecificInfo for the specified arch type and its properties
1627// structures populated with information from the variants.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001628func newArchSpecificInfo(ctx android.SdkMemberContext, archId archId, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001629
Paul Duffinfc8dd232020-03-17 12:51:37 +00001630 // Create an arch specific info into which the variant properties can be copied.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001631 archInfo := &archTypeSpecificInfo{archId: archId, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001632
1633 // Create the properties into which the arch type specific properties will be
1634 // added.
1635 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001636
1637 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001638 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001639 } else {
Paul Duffinb42fa672021-09-09 16:37:49 +01001640 // Group the variants by image type.
1641 variantsByImage := make(map[string][]android.Module)
1642 for _, variant := range archVariants {
1643 image := variant.ImageVariation().Variation
1644 variantsByImage[image] = append(variantsByImage[image], variant)
1645 }
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001646
Paul Duffinb42fa672021-09-09 16:37:49 +01001647 // Create the image variant info in a fixed order.
1648 for _, imageVariantName := range android.SortedStringKeys(variantsByImage) {
1649 variants := variantsByImage[imageVariantName]
1650 archInfo.imageVariantInfos = append(archInfo.imageVariantInfos, newImageVariantSpecificInfo(ctx, imageVariantName, variantPropertiesFactory, variants))
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001651 }
1652 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001653
1654 return archInfo
1655}
1656
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001657// Get the link type of the variant
1658//
1659// If the variant is not differentiated by link type then it returns "",
1660// otherwise it returns one of "static" or "shared".
1661func getLinkType(variant android.Module) string {
1662 linkType := ""
1663 if linkable, ok := variant.(cc.LinkableInterface); ok {
1664 if linkable.Shared() && linkable.Static() {
1665 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1666 } else if linkable.Shared() {
1667 linkType = "shared"
1668 } else if linkable.Static() {
1669 linkType = "static"
1670 } else {
1671 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1672 }
1673 }
1674 return linkType
1675}
1676
Paul Duffin39abf8f2021-09-24 14:58:27 +01001677func (archInfo *archTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1678 if len(archInfo.imageVariantInfos) == 0 {
1679 pruner.pruneProperties(archInfo.Properties)
1680 } else {
1681 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1682 imageVariantInfo.pruneUnsupportedProperties(pruner)
1683 }
1684 }
1685}
1686
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001687// Optimize the properties by extracting common properties from link type specific
1688// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001689func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001690 if len(archInfo.imageVariantInfos) == 0 {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001691 return
1692 }
1693
Paul Duffinb42fa672021-09-09 16:37:49 +01001694 // Optimize the image variant properties first.
1695 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1696 imageVariantInfo.optimizeProperties(ctx, commonValueExtractor)
1697 }
1698
1699 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.imageVariantInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001700}
1701
Paul Duffinfc8dd232020-03-17 12:51:37 +00001702// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001703func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001704 archPropertySuffix := archInfo.archId.propertyName()
1705 propertySetName := archOsPrefix + archPropertySuffix
1706 archTypePropertySet := archPropertySet.AddPropertySet(propertySetName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001707 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1708 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1709 archTypePropertySet.AddProperty("enabled", true)
1710 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001711 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001712
Paul Duffinb42fa672021-09-09 16:37:49 +01001713 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1714 imageVariantInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001715 }
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001716
1717 // If this is for a native bridge architecture then make sure that the property set does not
1718 // contain any properties as providing native bridge specific properties is not currently
1719 // supported.
1720 if archInfo.archId.nativeBridge {
1721 propertySetContents := getPropertySetContents(archTypePropertySet)
1722 if propertySetContents != "" {
1723 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",
1724 propertySetName, ctx.name, propertySetContents)
1725 }
1726 }
1727}
1728
1729// getPropertySetContents returns the string representation of the contents of a property set, after
1730// recursively pruning any empty nested property sets.
1731func getPropertySetContents(propertySet android.BpPropertySet) string {
1732 set := propertySet.(*bpPropertySet)
1733 set.transformContents(pruneEmptySetTransformer{})
1734 if len(set.properties) != 0 {
1735 contents := &generatedContents{}
1736 contents.Indent()
1737 outputPropertySet(contents, set)
1738 setAsString := contents.content.String()
1739 return setAsString
1740 }
1741 return ""
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001742}
1743
Paul Duffin4b8b7932020-05-06 12:35:38 +01001744func (archInfo *archTypeSpecificInfo) String() string {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001745 return archInfo.archId.String()
Paul Duffin4b8b7932020-05-06 12:35:38 +01001746}
1747
Paul Duffinb42fa672021-09-09 16:37:49 +01001748type imageVariantSpecificInfo struct {
1749 baseInfo
1750
1751 imageVariant string
1752
1753 linkInfos []*linkTypeSpecificInfo
1754}
1755
1756func newImageVariantSpecificInfo(ctx android.SdkMemberContext, imageVariant string, variantPropertiesFactory variantPropertiesFactoryFunc, imageVariants []android.Module) *imageVariantSpecificInfo {
1757
1758 // Create an image variant specific info into which the variant properties can be copied.
1759 imageInfo := &imageVariantSpecificInfo{imageVariant: imageVariant}
1760
1761 // Create the properties into which the image variant specific properties will be added.
1762 imageInfo.Properties = variantPropertiesFactory()
1763
1764 if len(imageVariants) == 1 {
1765 imageInfo.Properties.PopulateFromVariant(ctx, imageVariants[0])
1766 } else {
1767 // There is more than one variant for this image variant which must be differentiated by link
1768 // type.
1769 for _, linkVariant := range imageVariants {
1770 linkType := getLinkType(linkVariant)
1771 if linkType == "" {
1772 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(imageVariants)))
1773 } else {
1774 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
1775
1776 imageInfo.linkInfos = append(imageInfo.linkInfos, linkInfo)
1777 }
1778 }
1779 }
1780
1781 return imageInfo
1782}
1783
Paul Duffin39abf8f2021-09-24 14:58:27 +01001784func (imageInfo *imageVariantSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1785 if len(imageInfo.linkInfos) == 0 {
1786 pruner.pruneProperties(imageInfo.Properties)
1787 } else {
1788 for _, linkInfo := range imageInfo.linkInfos {
1789 linkInfo.pruneUnsupportedProperties(pruner)
1790 }
1791 }
1792}
1793
Paul Duffinb42fa672021-09-09 16:37:49 +01001794// Optimize the properties by extracting common properties from link type specific
1795// properties into arch type specific properties.
1796func (imageInfo *imageVariantSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
1797 if len(imageInfo.linkInfos) == 0 {
1798 return
1799 }
1800
1801 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, imageInfo.Properties, imageInfo.linkInfos)
1802}
1803
1804// Add the properties for an arch type to a property set.
1805func (imageInfo *imageVariantSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1806 if imageInfo.imageVariant != android.CoreVariation {
1807 propertySet = propertySet.AddPropertySet(imageInfo.imageVariant)
1808 }
1809
1810 addSdkMemberPropertiesToSet(ctx, imageInfo.Properties, propertySet)
1811
1812 for _, linkInfo := range imageInfo.linkInfos {
1813 linkInfo.addToPropertySet(ctx, propertySet)
1814 }
1815
1816 // If this is for a non-core image variant then make sure that the property set does not contain
1817 // any properties as providing non-core image variant specific properties for prebuilts is not
1818 // currently supported.
1819 if imageInfo.imageVariant != android.CoreVariation {
1820 propertySetContents := getPropertySetContents(propertySet)
1821 if propertySetContents != "" {
1822 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",
1823 imageInfo.imageVariant, ctx.name, propertySetContents)
1824 }
1825 }
1826}
1827
1828func (imageInfo *imageVariantSpecificInfo) String() string {
1829 return imageInfo.imageVariant
1830}
1831
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001832type linkTypeSpecificInfo struct {
1833 baseInfo
1834
1835 linkType string
1836}
1837
Paul Duffin4b8b7932020-05-06 12:35:38 +01001838var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1839
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001840// Create a new linkTypeSpecificInfo for the specified link type and its properties
1841// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001842func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001843 linkInfo := &linkTypeSpecificInfo{
1844 baseInfo: baseInfo{
1845 // Create the properties into which the link type specific properties will be
1846 // added.
1847 Properties: variantPropertiesFactory(),
1848 },
1849 linkType: linkType,
1850 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001851 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001852 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001853}
1854
Paul Duffinf68f85a2021-09-09 16:11:42 +01001855func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1856 linkPropertySet := propertySet.AddPropertySet(l.linkType)
1857 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
1858}
1859
Paul Duffin39abf8f2021-09-24 14:58:27 +01001860func (l *linkTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1861 pruner.pruneProperties(l.Properties)
1862}
1863
Paul Duffin4b8b7932020-05-06 12:35:38 +01001864func (l *linkTypeSpecificInfo) String() string {
1865 return fmt.Sprintf("LinkType{%s}", l.linkType)
1866}
1867
Paul Duffin3a4eb502020-03-19 16:11:18 +00001868type memberContext struct {
1869 sdkMemberContext android.ModuleContext
1870 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001871 memberType android.SdkMemberType
1872 name string
Paul Duffind19f8942021-07-14 12:08:37 +01001873
1874 // The set of traits required of this member.
1875 requiredTraits android.SdkMemberTraitSet
Paul Duffin3a4eb502020-03-19 16:11:18 +00001876}
1877
1878func (m *memberContext) SdkModuleContext() android.ModuleContext {
1879 return m.sdkMemberContext
1880}
1881
1882func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1883 return m.builder
1884}
1885
Paul Duffina551a1c2020-03-17 21:04:24 +00001886func (m *memberContext) MemberType() android.SdkMemberType {
1887 return m.memberType
1888}
1889
1890func (m *memberContext) Name() string {
1891 return m.name
1892}
1893
Paul Duffind19f8942021-07-14 12:08:37 +01001894func (m *memberContext) RequiresTrait(trait android.SdkMemberTrait) bool {
1895 return m.requiredTraits.Contains(trait)
1896}
1897
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001898func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001899
1900 memberType := member.memberType
1901
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001902 // Do not add the prefer property if the member snapshot module is a source module type.
Paul Duffin39abf8f2021-09-24 14:58:27 +01001903 config := ctx.sdkMemberContext.Config()
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001904 if !memberType.UsesSourceModuleTypeInSnapshot() {
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +00001905 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1906 // snapshot to be created that sets prefer: true.
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001907 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1908 // dynamically at build time not at snapshot generation time.
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001909 prefer := config.IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001910
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001911 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1912 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1913 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1914 // behavior is for the module.
1915 bpModule.insertAfter("name", "prefer", prefer)
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001916
1917 configVar := config.Getenv("SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR")
1918 if configVar != "" {
1919 parts := strings.Split(configVar, ":")
1920 cfp := android.ConfigVarProperties{
1921 Config_namespace: proptools.StringPtr(parts[0]),
1922 Var_name: proptools.StringPtr(parts[1]),
1923 }
1924 bpModule.insertAfter("prefer", "use_source_config_var", cfp)
1925 }
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001926 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001927
Paul Duffina04c1072020-03-02 10:16:35 +00001928 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001929 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001930 variants := member.Variants()
1931 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001932 osType := variant.Target().Os
1933 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001934 }
1935
Paul Duffina04c1072020-03-02 10:16:35 +00001936 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001937 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001938 properties := memberType.CreateVariantPropertiesStruct()
1939 base := properties.Base()
1940 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001941 return properties
1942 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001943
Paul Duffina04c1072020-03-02 10:16:35 +00001944 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001945
Paul Duffina04c1072020-03-02 10:16:35 +00001946 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001947 commonProperties := variantPropertiesFactory()
1948 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001949
Paul Duffin39abf8f2021-09-24 14:58:27 +01001950 // Create a property pruner that will prune any properties unsupported by the target build
1951 // release.
1952 targetBuildRelease := ctx.builder.targetBuildRelease
1953 unsupportedPropertyPruner := newPropertyPrunerByBuildRelease(commonProperties, targetBuildRelease)
1954
Paul Duffinc097e362020-03-10 22:50:03 +00001955 // Create common value extractor that can be used to optimize the properties.
1956 commonValueExtractor := newCommonValueExtractor(commonProperties)
1957
Paul Duffina04c1072020-03-02 10:16:35 +00001958 // The list of property structures which are os type specific but common across
1959 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001960 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001961
1962 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001963 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001964 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001965 // Add the os specific properties to a list of os type specific yet architecture
1966 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001967 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001968
Paul Duffin39abf8f2021-09-24 14:58:27 +01001969 osInfo.pruneUnsupportedProperties(unsupportedPropertyPruner)
1970
Paul Duffin00e46802020-03-12 20:40:35 +00001971 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001972 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001973 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001974
Paul Duffina04c1072020-03-02 10:16:35 +00001975 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001976 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001977
Paul Duffina04c1072020-03-02 10:16:35 +00001978 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001979 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001980
Paul Duffina04c1072020-03-02 10:16:35 +00001981 // Create a target property set into which target specific properties can be
1982 // added.
1983 targetPropertySet := bpModule.AddPropertySet("target")
1984
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001985 // If the member is host OS dependent and has host_supported then disable by
1986 // default and enable each host OS variant explicitly. This avoids problems
1987 // with implicitly enabled OS variants when the snapshot is used, which might
1988 // be different from this run (e.g. different build OS).
1989 if ctx.memberType.IsHostOsDependent() {
1990 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1991 if hostSupported {
1992 hostPropertySet := targetPropertySet.AddPropertySet("host")
1993 hostPropertySet.AddProperty("enabled", false)
1994 }
1995 }
1996
Paul Duffina04c1072020-03-02 10:16:35 +00001997 // Iterate over the os types in a fixed order.
1998 for _, osType := range s.getPossibleOsTypes() {
1999 osInfo := osTypeToInfo[osType]
2000 if osInfo == nil {
2001 continue
2002 }
2003
Paul Duffin3a4eb502020-03-19 16:11:18 +00002004 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002005 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002006}
2007
Paul Duffina04c1072020-03-02 10:16:35 +00002008// Compute the list of possible os types that this sdk could support.
2009func (s *sdk) getPossibleOsTypes() []android.OsType {
2010 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00002011 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00002012 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07002013 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00002014 osTypes = append(osTypes, osType)
2015 }
2016 }
2017 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09002018 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00002019 osTypes = append(osTypes, osType)
2020 }
2021 }
2022 }
2023 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
2024 return osTypes
2025}
2026
Paul Duffinb28369a2020-05-04 15:39:59 +01002027// Given a set of properties (struct value), return the value of the field within that
2028// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00002029type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
2030
Paul Duffinc459f892020-04-30 18:08:29 +01002031// Checks the metadata to determine whether the property should be ignored for the
2032// purposes of common value extraction or not.
2033type extractorMetadataPredicate func(metadata propertiesContainer) bool
2034
2035// Indicates whether optimizable properties are provided by a host variant or
2036// not.
2037type isHostVariant interface {
2038 isHostVariant() bool
2039}
2040
Paul Duffinb28369a2020-05-04 15:39:59 +01002041// A property that can be optimized by the commonValueExtractor.
2042type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01002043 // The name of the field for this property. It is a "."-separated path for
2044 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002045 name string
2046
Paul Duffinc459f892020-04-30 18:08:29 +01002047 // Filter that can use metadata associated with the properties being optimized
2048 // to determine whether the field should be ignored during common value
2049 // optimization.
2050 filter extractorMetadataPredicate
2051
Paul Duffinb28369a2020-05-04 15:39:59 +01002052 // Retrieves the value on which common value optimization will be performed.
2053 getter fieldAccessorFunc
2054
2055 // The empty value for the field.
2056 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01002057
2058 // True if the property can support arch variants false otherwise.
2059 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01002060}
2061
Paul Duffin4b8b7932020-05-06 12:35:38 +01002062func (p extractorProperty) String() string {
2063 return p.name
2064}
2065
Paul Duffinc097e362020-03-10 22:50:03 +00002066// Supports extracting common values from a number of instances of a properties
2067// structure into a separate common set of properties.
2068type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01002069 // The properties that the extractor can optimize.
2070 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00002071}
2072
2073// Create a new common value extractor for the structure type for the supplied
2074// properties struct.
2075//
2076// The returned extractor can be used on any properties structure of the same type
2077// as the supplied set of properties.
2078func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
2079 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
2080 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01002081 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00002082 return extractor
2083}
2084
2085// Gather the fields from the supplied structure type from which common values will
2086// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00002087//
Martin Stjernholmb0249572020-09-15 02:32:35 +01002088// This is recursive function. If it encounters a struct then it will recurse
2089// into it, passing in the accessor for the field and the struct name as prefix
2090// for the nested fields. That will then be used in the accessors for the fields
2091// in the embedded struct.
2092func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00002093 for f := 0; f < structType.NumField(); f++ {
2094 field := structType.Field(f)
2095 if field.PkgPath != "" {
2096 // Ignore unexported fields.
2097 continue
2098 }
2099
Paul Duffinb07fa512020-03-10 22:17:04 +00002100 // Ignore fields whose value should be kept.
2101 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00002102 continue
2103 }
2104
Paul Duffinc459f892020-04-30 18:08:29 +01002105 var filter extractorMetadataPredicate
2106
2107 // Add a filter
2108 if proptools.HasTag(field, "sdk", "ignored-on-host") {
2109 filter = func(metadata propertiesContainer) bool {
2110 if m, ok := metadata.(isHostVariant); ok {
2111 if m.isHostVariant() {
2112 return false
2113 }
2114 }
2115 return true
2116 }
2117 }
2118
Paul Duffinc097e362020-03-10 22:50:03 +00002119 // Save a copy of the field index for use in the function.
2120 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01002121
Martin Stjernholmb0249572020-09-15 02:32:35 +01002122 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01002123
Paul Duffinc097e362020-03-10 22:50:03 +00002124 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00002125 if containingStructAccessor != nil {
2126 // This is an embedded structure so first access the field for the embedded
2127 // structure.
2128 value = containingStructAccessor(value)
2129 }
2130
Paul Duffinc097e362020-03-10 22:50:03 +00002131 // Skip through interface and pointer values to find the structure.
2132 value = getStructValue(value)
2133
Paul Duffin4b8b7932020-05-06 12:35:38 +01002134 defer func() {
2135 if r := recover(); r != nil {
2136 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
2137 }
2138 }()
2139
Paul Duffinc097e362020-03-10 22:50:03 +00002140 // Return the field.
2141 return value.Field(fieldIndex)
2142 }
2143
Martin Stjernholmb0249572020-09-15 02:32:35 +01002144 if field.Type.Kind() == reflect.Struct {
2145 // Gather fields from the nested or embedded structure.
2146 var subNamePrefix string
2147 if field.Anonymous {
2148 subNamePrefix = namePrefix
2149 } else {
2150 subNamePrefix = name + "."
2151 }
2152 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00002153 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01002154 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01002155 name,
Paul Duffinc459f892020-04-30 18:08:29 +01002156 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01002157 fieldGetter,
2158 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01002159 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01002160 }
2161 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00002162 }
Paul Duffinc097e362020-03-10 22:50:03 +00002163 }
2164}
2165
2166func getStructValue(value reflect.Value) reflect.Value {
2167foundStruct:
2168 for {
2169 kind := value.Kind()
2170 switch kind {
2171 case reflect.Interface, reflect.Ptr:
2172 value = value.Elem()
2173 case reflect.Struct:
2174 break foundStruct
2175 default:
2176 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
2177 }
2178 }
2179 return value
2180}
2181
Paul Duffinf34f6d82020-04-30 15:48:31 +01002182// A container of properties to be optimized.
2183//
2184// Allows additional information to be associated with the properties, e.g. for
2185// filtering.
2186type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002187 fmt.Stringer
2188
Paul Duffinf34f6d82020-04-30 15:48:31 +01002189 // Get the properties that need optimizing.
2190 optimizableProperties() interface{}
2191}
2192
Paul Duffin2d1bb892021-04-24 11:32:59 +01002193// A wrapper for sdk variant related properties to allow them to be optimized.
2194type sdkVariantPropertiesContainer struct {
2195 sdkVariant *sdk
2196 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01002197}
2198
Paul Duffin2d1bb892021-04-24 11:32:59 +01002199func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
2200 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01002201}
2202
Paul Duffin2d1bb892021-04-24 11:32:59 +01002203func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002204 return c.sdkVariant.String()
2205}
2206
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002207// Extract common properties from a slice of property structures of the same type.
2208//
2209// All the property structures must be of the same type.
2210// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002211// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002212//
2213// Iterates over each exported field (capitalized name) and checks to see whether they
2214// have the same value (using DeepEquals) across all the input properties. If it does not then no
2215// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01002216// and the field in each of the input properties structure is set to its default value. Nested
2217// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002218func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002219 commonPropertiesValue := reflect.ValueOf(commonProperties)
2220 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002221
Paul Duffinf34f6d82020-04-30 15:48:31 +01002222 sliceValue := reflect.ValueOf(inputPropertiesSlice)
2223
Paul Duffinb28369a2020-05-04 15:39:59 +01002224 for _, property := range e.properties {
2225 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01002226 filter := property.filter
2227 if filter == nil {
2228 filter = func(metadata propertiesContainer) bool {
2229 return true
2230 }
2231 }
Paul Duffinb28369a2020-05-04 15:39:59 +01002232
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002233 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002234 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2235 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002236 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002237
Paul Duffin864e1b42020-05-06 10:23:19 +01002238 // Assume that all the values will be the same.
2239 //
2240 // While similar to this is not quite the same as commonValue == nil. If all the values
2241 // have been filtered out then this will be false but commonValue == nil will be true.
2242 valuesDiffer := false
2243
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002244 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002245 container := sliceValue.Index(i).Interface().(propertiesContainer)
2246 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002247 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002248
Paul Duffinc459f892020-04-30 18:08:29 +01002249 if !filter(container) {
2250 expectedValue := property.emptyValue.Interface()
2251 actualValue := fieldValue.Interface()
2252 if !reflect.DeepEqual(expectedValue, actualValue) {
2253 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2254 }
2255 continue
2256 }
2257
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002258 if commonValue == nil {
2259 // Use the first value as the commonProperties value.
2260 commonValue = &fieldValue
2261 } else {
2262 // If the value does not match the current common value then there is
2263 // no value in common so break out.
2264 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2265 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002266 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002267 break
2268 }
2269 }
2270 }
2271
Paul Duffin864e1b42020-05-06 10:23:19 +01002272 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002273 // and set the input struct's field to the empty value.
2274 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002275 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002276 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002277 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002278 container := sliceValue.Index(i).Interface().(propertiesContainer)
2279 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002280 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002281 fieldValue.Set(emptyValue)
2282 }
2283 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002284
2285 if valuesDiffer && !property.archVariant {
2286 // The values differ but the property does not support arch variants so it
2287 // is an error.
2288 var details strings.Builder
2289 for i := 0; i < sliceValue.Len(); i++ {
2290 container := sliceValue.Index(i).Interface().(propertiesContainer)
2291 itemValue := reflect.ValueOf(container.optimizableProperties())
2292 fieldValue := fieldGetter(itemValue)
2293
2294 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2295 }
2296
2297 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2298 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002299 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002300
2301 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002302}