blob: 8e4f9d4e2efe7b5e7dfe4ad6c1f045bcd574256c [file] [log] [blame]
Jiyong Park9b409bc2019-10-11 14:59:13 +09001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package sdk
16
17import (
Paul Duffinc6ba1822022-05-06 09:38:02 +000018 "bytes"
19 "encoding/json"
Jiyong Park9b409bc2019-10-11 14:59:13 +090020 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000021 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000022 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090023 "strings"
24
Paul Duffin7d74e7b2020-03-06 12:30:13 +000025 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000026 "android/soong/cc"
Colin Crosscb0ac952021-07-20 13:17:15 -070027
Paul Duffin375058f2019-11-29 20:17:53 +000028 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090029 "github.com/google/blueprint/proptools"
30
31 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090032)
33
Paul Duffin64fb5262021-05-05 21:36:04 +010034// Environment variables that affect the generated snapshot
35// ========================================================
36//
37// SOONG_SDK_SNAPSHOT_PREFER
Paul Duffinb01ac4b2022-05-24 20:10:05 +000038// By default every module in the generated snapshot has prefer: false. Building it
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +000039// with SOONG_SDK_SNAPSHOT_PREFER=true will force them to use prefer: true.
Paul Duffin64fb5262021-05-05 21:36:04 +010040//
Paul Duffinfb9a7f92021-07-06 17:18:42 +010041// SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR
42// If set this specifies the Soong config var that can be used to control whether the prebuilt
43// modules from the generated snapshot or the original source modules. Values must be a colon
44// separated pair of strings, the first of which is the Soong config namespace, and the second
45// is the name of the variable within that namespace.
46//
47// The config namespace and var name are used to set the `use_source_config_var` property. That
48// in turn will cause the generated prebuilts to use the soong config variable to select whether
49// source or the prebuilt is used.
50// e.g. If an sdk snapshot is built using:
51// m SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR=acme:build_from_source sdkextensions-sdk
52// Then the resulting snapshot will include:
53// use_source_config_var: {
54// config_namespace: "acme",
55// var_name: "build_from_source",
56// }
57//
58// Assuming that the config variable is defined in .mk using something like:
59// $(call add_soong_config_namespace,acme)
60// $(call add_soong_config_var_value,acme,build_from_source,true)
61//
62// Then when the snapshot is unpacked in the repository it will have the following behavior:
63// m droid - will use the sdkextensions-sdk prebuilts if present. Otherwise, it will use the
64// sources.
65// m SOONG_CONFIG_acme_build_from_source=true droid - will use the sdkextensions-sdk
66// sources, if present. Otherwise, it will use the prebuilts.
67//
68// This is a temporary mechanism to control the prefer flags and will be removed once a more
69// maintainable solution has been implemented.
70// TODO(b/174997203): Remove when no longer necessary.
71//
Paul Duffin39abf8f2021-09-24 14:58:27 +010072// SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE
73// This allows the target build release (i.e. the release version of the build within which
74// the snapshot will be used) of the snapshot to be specified. If unspecified then it defaults
75// to the current build release version. Otherwise, it must be the name of one of the build
76// releases defined in nameToBuildRelease, e.g. S, T, etc..
77//
78// The generated snapshot must only be used in the specified target release. If the target
79// build release is not the current build release then the generated Android.bp file not be
80// checked for compatibility.
81//
82// e.g. if setting SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE=S will cause the generated snapshot
83// to be compatible with S.
84//
Paul Duffin64fb5262021-05-05 21:36:04 +010085
Jiyong Park9b409bc2019-10-11 14:59:13 +090086var pctx = android.NewPackageContext("android/soong/sdk")
87
Paul Duffin375058f2019-11-29 20:17:53 +000088var (
89 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
90 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000091 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000092 CommandDeps: []string{
93 "${config.Zip2ZipCmd}",
94 },
95 },
96 "destdir")
97
98 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
99 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -0700100 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +0000101 CommandDeps: []string{
102 "${config.SoongZipCmd}",
103 },
104 Rspfile: "$out.rsp",
105 RspfileContent: "$in",
106 },
107 "basedir")
108
109 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
110 blueprint.RuleParams{
111 Command: `${config.MergeZipsCmd} $out $in`,
112 CommandDeps: []string{
113 "${config.MergeZipsCmd}",
114 },
115 })
116)
117
Paul Duffin43f7bf02021-05-05 22:00:51 +0100118const (
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000119 soongSdkSnapshotVersionCurrent = "current"
Paul Duffin43f7bf02021-05-05 22:00:51 +0100120)
121
Paul Duffinb645ec82019-11-27 17:43:54 +0000122type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +0900123 content strings.Builder
124 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +0900125}
126
Paul Duffinb645ec82019-11-27 17:43:54 +0000127// generatedFile abstracts operations for writing contents into a file and emit a build rule
128// for the file.
129type generatedFile struct {
130 generatedContents
131 path android.OutputPath
132}
133
Jiyong Park232e7852019-11-04 12:23:40 +0900134func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +0900135 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +0000136 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +0900137 }
138}
139
Paul Duffinb645ec82019-11-27 17:43:54 +0000140func (gc *generatedContents) Indent() {
141 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +0900142}
143
Paul Duffinb645ec82019-11-27 17:43:54 +0000144func (gc *generatedContents) Dedent() {
145 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +0900146}
147
Paul Duffina08e4dc2021-06-22 18:19:19 +0100148// IndentedPrintf will add spaces to indent the line to the appropriate level before printing the
149// arguments.
150func (gc *generatedContents) IndentedPrintf(format string, args ...interface{}) {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000151 _, _ = fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100152}
153
154// UnindentedPrintf does not add spaces to indent the line to the appropriate level before printing
155// the arguments.
156func (gc *generatedContents) UnindentedPrintf(format string, args ...interface{}) {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000157 _, _ = fmt.Fprintf(&(gc.content), format, args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900158}
159
160func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800161 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100162
163 content := gf.content.String()
164
165 // ninja consumes newline characters in rspfile_content. Prevent it by
166 // escaping the backslash in the newline character. The extra backslash
167 // is removed when the rspfile is written to the actual script file
168 content = strings.ReplaceAll(content, "\n", "\\n")
169
Jiyong Park9b409bc2019-10-11 14:59:13 +0900170 rb.Command().
171 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100172 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100173 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900174 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
175 rb.Command().
176 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800177 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900178}
179
Paul Duffin13879572019-11-28 14:31:38 +0000180// Collect all the members.
181//
Paul Duffinb97b1572021-04-29 21:50:40 +0100182// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
183// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000184func (s *sdk) collectMembers(ctx android.ModuleContext) {
185 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000186 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
187 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf7b3d0d2021-09-02 14:29:21 +0100188 if memberTag, ok := tag.(android.SdkMemberDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100189 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900190
Paul Duffin5cca7c42021-05-26 10:16:01 +0100191 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
192 if memberType == nil {
193 return false
194 }
195
Paul Duffin13879572019-11-28 14:31:38 +0000196 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000197 if !memberType.IsInstance(child) {
198 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900199 }
Paul Duffin13879572019-11-28 14:31:38 +0000200
Paul Duffin6a7e9532020-03-20 17:50:07 +0000201 // Keep track of which multilib variants are used by the sdk.
202 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
203
Paul Duffinb97b1572021-04-29 21:50:40 +0100204 var exportedComponentsInfo android.ExportedComponentsInfo
205 if ctx.OtherModuleHasProvider(child, android.ExportedComponentsInfoProvider) {
206 exportedComponentsInfo = ctx.OtherModuleProvider(child, android.ExportedComponentsInfoProvider).(android.ExportedComponentsInfo)
207 }
208
Paul Duffinc6ba1822022-05-06 09:38:02 +0000209 var container android.SdkAware
210 if parent != ctx.Module() {
211 container = parent.(android.SdkAware)
212 }
213
Paul Duffina7208112021-04-23 21:20:20 +0100214 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100215 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
Paul Duffinc6ba1822022-05-06 09:38:02 +0000216 sdkVariant: s,
217 memberType: memberType,
218 variant: child.(android.SdkAware),
219 container: container,
220 export: export,
221 exportedComponentsInfo: exportedComponentsInfo,
Paul Duffinb97b1572021-04-29 21:50:40 +0100222 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000223
Paul Duffin2d3da312021-05-06 12:02:27 +0100224 // Recurse down into the member's dependencies as it may have dependencies that need to be
225 // automatically added to the sdk.
226 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900227 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000228
229 return false
Paul Duffin13879572019-11-28 14:31:38 +0000230 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000231}
232
Paul Duffincc3132e2021-04-24 01:10:30 +0100233// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
234// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000235//
Paul Duffincc3132e2021-04-24 01:10:30 +0100236// The sdkMember instances are then grouped into slices by member type. Within each such slice the
237// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000238//
Paul Duffincc3132e2021-04-24 01:10:30 +0100239// Finally, the member type slices are concatenated together to form a single slice. The order in
240// which they are concatenated is the order in which the member types were registered in the
241// android.SdkMemberTypesRegistry.
Paul Duffinf861df72022-07-01 15:56:06 +0000242func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, targetBuildRelease *buildRelease, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000243 byType := make(map[android.SdkMemberType][]*sdkMember)
244 byName := make(map[string]*sdkMember)
245
Paul Duffin21827262021-04-24 12:16:36 +0100246 for _, memberVariantDep := range memberVariantDeps {
247 memberType := memberVariantDep.memberType
248 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000249
250 name := ctx.OtherModuleName(variant)
251 member := byName[name]
252 if member == nil {
253 member = &sdkMember{memberType: memberType, name: name}
254 byName[name] = member
255 byType[memberType] = append(byType[memberType], member)
Liz Kammer96320df2022-05-12 20:40:00 -0400256 } else if member.memberType != memberType {
257 // validate whether this is the same member type or and overriding member type
258 if memberType.Overrides(member.memberType) {
259 member.memberType = memberType
260 } else if !member.memberType.Overrides(memberType) {
261 ctx.ModuleErrorf("Incompatible member types %q %q", member.memberType, memberType)
262 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000263 }
264
Paul Duffin1356d8c2020-02-25 19:26:33 +0000265 // Only append new variants to the list. This is needed because a member can be both
266 // exported by the sdk and also be a transitive sdk member.
267 member.variants = appendUniqueVariants(member.variants, variant)
268 }
Paul Duffin13879572019-11-28 14:31:38 +0000269 var members []*sdkMember
Paul Duffin62782de2021-07-14 12:05:16 +0100270 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffinf861df72022-07-01 15:56:06 +0000271 memberType := memberListProperty.memberType
272
273 if !isMemberTypeSupportedByTargetBuildRelease(memberType, targetBuildRelease) {
274 continue
275 }
276
277 membersOfType := byType[memberType]
Paul Duffin13879572019-11-28 14:31:38 +0000278 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900279 }
280
Paul Duffin6a7e9532020-03-20 17:50:07 +0000281 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900282}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900283
Paul Duffinf861df72022-07-01 15:56:06 +0000284// isMemberTypeSupportedByTargetBuildRelease returns true if the member type is supported by the
285// target build release.
286func isMemberTypeSupportedByTargetBuildRelease(memberType android.SdkMemberType, targetBuildRelease *buildRelease) bool {
287 supportedByTargetBuildRelease := true
288 supportedBuildReleases := memberType.SupportedBuildReleases()
289 if supportedBuildReleases == "" {
290 supportedBuildReleases = "S+"
291 }
292
293 set, err := parseBuildReleaseSet(supportedBuildReleases)
294 if err != nil {
295 panic(fmt.Errorf("member type %s has invalid supported build releases %q: %s",
296 memberType.SdkPropertyName(), supportedBuildReleases, err))
297 }
298 if !set.contains(targetBuildRelease) {
299 supportedByTargetBuildRelease = false
300 }
301 return supportedByTargetBuildRelease
302}
303
Paul Duffin72910952020-01-20 18:16:30 +0000304func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
305 for _, v := range variants {
306 if v == newVariant {
307 return variants
308 }
309 }
310 return append(variants, newVariant)
311}
312
Paul Duffin51509a12022-04-06 12:48:09 +0000313// BUILD_NUMBER_FILE is the name of the file in the snapshot zip that will contain the number of
314// the build from which the snapshot was produced.
315const BUILD_NUMBER_FILE = "snapshot-creation-build-number.txt"
316
Jiyong Park73c54ee2019-10-22 20:31:18 +0900317// SDK directory structure
318// <sdk_root>/
319// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
320// <api_ver>/ : below this directory are all auto-generated
321// Android.bp : definition of 'sdk_snapshot' module is here
322// aidl/
323// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
324// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900325// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900326// include/
327// bionic/libc/include/stdlib.h : an exported header file
328// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900329// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900330// <arch>/include/ : arch-specific exported headers
331// <arch>/include_gen/ : arch-specific generated headers
332// <arch>/lib/
333// libFoo.so : a stub library
334
Jiyong Park232e7852019-11-04 12:23:40 +0900335// buildSnapshot is the main function in this source file. It creates rules to copy
336// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffinc6ba1822022-05-06 09:38:02 +0000337func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000338
Paul Duffinb97b1572021-04-29 21:50:40 +0100339 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100340 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100341 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000342 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100343 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100344 }
Paul Duffin865171e2020-03-02 18:38:15 +0000345
Paul Duffinb97b1572021-04-29 21:50:40 +0100346 // Filter out any sdkMemberVariantDep that is a component of another.
347 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000348
Paul Duffinb97b1572021-04-29 21:50:40 +0100349 // Record the names of all the members, both explicitly specified and implicitly
350 // included.
351 allMembersByName := make(map[string]struct{})
352 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100353
Paul Duffinb97b1572021-04-29 21:50:40 +0100354 addMember := func(name string, export bool) {
355 allMembersByName[name] = struct{}{}
356 if export {
357 exportedMembersByName[name] = struct{}{}
358 }
359 }
360
361 for _, memberVariantDep := range memberVariantDeps {
362 name := memberVariantDep.variant.Name()
363 export := memberVariantDep.export
364
365 addMember(name, export)
366
367 // Add any components provided by the module.
368 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
369 addMember(component, export)
370 }
371
372 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
373 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000374 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000375 }
376
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000377 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900378
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000379 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000380
381 bpFile := &bpFile{
382 modules: make(map[string]*bpModule),
383 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000384
Paul Duffin43f7bf02021-05-05 22:00:51 +0100385 config := ctx.Config()
Paul Duffin43f7bf02021-05-05 22:00:51 +0100386
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000387 // Always add -current to the end
388 snapshotFileSuffix := "-current"
Paul Duffin43f7bf02021-05-05 22:00:51 +0100389
Paul Duffin39abf8f2021-09-24 14:58:27 +0100390 currentBuildRelease := latestBuildRelease()
391 targetBuildReleaseEnv := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE", currentBuildRelease.name)
392 targetBuildRelease, err := nameToRelease(targetBuildReleaseEnv)
393 if err != nil {
394 ctx.ModuleErrorf("invalid SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE: %s", err)
395 targetBuildRelease = currentBuildRelease
396 }
397
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000398 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000399 ctx: ctx,
400 sdk: s,
Paul Duffin13f02712020-03-06 12:30:43 +0000401 snapshotDir: snapshotDir.OutputPath,
402 copies: make(map[string]string),
403 filesToZip: []android.Path{bp.path},
404 bpFile: bpFile,
405 prebuiltModules: make(map[string]*bpModule),
406 allMembersByName: allMembersByName,
407 exportedMembersByName: exportedMembersByName,
Paul Duffin39abf8f2021-09-24 14:58:27 +0100408 targetBuildRelease: targetBuildRelease,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900409 }
Paul Duffinac37c502019-11-26 18:02:20 +0000410 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900411
Paul Duffin62131702021-05-07 01:10:01 +0100412 // If the sdk snapshot includes any license modules then add a package module which has a
413 // default_applicable_licenses property. That will prevent the LSC license process from updating
414 // the generated Android.bp file to add a package module that includes all licenses used by all
415 // the modules in that package. That would be unnecessary as every module in the sdk should have
416 // their own licenses property specified.
417 if hasLicenses {
418 pkg := bpFile.newModule("package")
419 property := "default_applicable_licenses"
420 pkg.AddCommentForProperty(property, `
421A default list here prevents the license LSC from adding its own list which would
422be unnecessary as every module in the sdk already has its own licenses property.
423`)
424 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
425 bpFile.AddModule(pkg)
426 }
427
Paul Duffin0df49682021-05-07 01:10:01 +0100428 // Group the variants for each member module together and then group the members of each member
429 // type together.
Paul Duffinf861df72022-07-01 15:56:06 +0000430 members := s.groupMemberVariantsByMemberThenType(ctx, targetBuildRelease, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100431
432 // Create the prebuilt modules for each of the member modules.
Paul Duffind19f8942021-07-14 12:08:37 +0100433 traits := s.gatherTraits()
Paul Duffin13ad94f2020-02-19 16:19:27 +0000434 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000435 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000436
Paul Duffind19f8942021-07-14 12:08:37 +0100437 name := member.name
438 requiredTraits := traits[name]
439 if requiredTraits == nil {
440 requiredTraits = android.EmptySdkMemberTraitSet()
441 }
442
443 // Create the snapshot for the member.
444 memberCtx := &memberContext{ctx, builder, memberType, name, requiredTraits}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000445
446 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100447 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900448 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900449
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000450 // Create a transformer that will transform a module by replacing any references
Paul Duffin72910952020-01-20 18:16:30 +0000451 // to internal members with a unique module name and setting prefer: false.
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000452 snapshotTransformer := snapshotTransformation{
Paul Duffin64fb5262021-05-05 21:36:04 +0100453 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100454 }
Paul Duffin72910952020-01-20 18:16:30 +0000455
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000456 for _, module := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000457 // Prune any empty property sets.
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000458 module = module.transform(pruneEmptySetTransformer{})
Paul Duffina78f3a72020-02-21 16:29:35 +0000459
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000460 // Transform the module module to make it suitable for use in the snapshot.
461 module.transform(snapshotTransformer)
462 bpFile.AddModule(module)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100463 }
Paul Duffin26197a62021-04-24 00:34:10 +0100464
465 // generate Android.bp
466 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
467 generateBpContents(&bp.generatedContents, bpFile)
468
469 contents := bp.content.String()
Paul Duffin39abf8f2021-09-24 14:58:27 +0100470 // If the snapshot is being generated for the current build release then check the syntax to make
471 // sure that it is compatible.
472 if targetBuildRelease == currentBuildRelease {
473 syntaxCheckSnapshotBpFile(ctx, contents)
474 }
Paul Duffin26197a62021-04-24 00:34:10 +0100475
476 bp.build(pctx, ctx, nil)
477
Paul Duffin51509a12022-04-06 12:48:09 +0000478 // Copy the build number file into the snapshot.
479 builder.CopyToSnapshot(ctx.Config().BuildNumberFile(ctx), BUILD_NUMBER_FILE)
480
Paul Duffin26197a62021-04-24 00:34:10 +0100481 filesToZip := builder.filesToZip
482
483 // zip them all
Paul Duffinc6ba1822022-05-06 09:38:02 +0000484 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100485 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100486 outputDesc := "Building snapshot for " + ctx.ModuleName()
487
488 // If there are no zips to merge then generate the output zip directly.
489 // Otherwise, generate an intermediate zip file into which other zips can be
490 // merged.
491 var zipFile android.OutputPath
492 var desc string
493 if len(builder.zipsToMerge) == 0 {
494 zipFile = outputZipFile
495 desc = outputDesc
496 } else {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000497 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100498 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100499 desc = "Building intermediate snapshot for " + ctx.ModuleName()
500 }
501
502 ctx.Build(pctx, android.BuildParams{
503 Description: desc,
504 Rule: zipFiles,
505 Inputs: filesToZip,
506 Output: zipFile,
507 Args: map[string]string{
508 "basedir": builder.snapshotDir.String(),
509 },
510 })
511
512 if len(builder.zipsToMerge) != 0 {
513 ctx.Build(pctx, android.BuildParams{
514 Description: outputDesc,
515 Rule: mergeZips,
516 Input: zipFile,
517 Inputs: builder.zipsToMerge,
518 Output: outputZipFile,
519 })
520 }
521
Paul Duffinc6ba1822022-05-06 09:38:02 +0000522 modules := s.generateInfoData(ctx, memberVariantDeps)
523
524 // Output the modules information as pretty printed JSON.
525 info := newGeneratedFile(ctx, fmt.Sprintf("%s%s.info", ctx.ModuleName(), snapshotFileSuffix))
526 output, err := json.MarshalIndent(modules, "", " ")
527 if err != nil {
528 ctx.ModuleErrorf("error generating %q: %s", info, err)
529 }
530 builder.infoContents = string(output)
531 info.generatedContents.UnindentedPrintf("%s", output)
532 info.build(pctx, ctx, nil)
533 infoPath := info.path
534 installedInfo := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), infoPath.Base(), infoPath)
535 s.infoFile = android.OptionalPathForPath(installedInfo)
536
537 // Install the zip, making sure that the info file has been installed as well.
538 installedZip := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), outputZipFile.Base(), outputZipFile, installedInfo)
539 s.snapshotFile = android.OptionalPathForPath(installedZip)
540}
541
542type moduleInfo struct {
543 // The type of the module, e.g. java_sdk_library
544 moduleType string
545 // The name of the module.
546 name string
547 // A list of additional dependencies of the module.
548 deps []string
Paul Duffin958806b2022-05-16 13:10:47 +0000549 // Additional member specific properties.
550 // These will be added into the generated JSON alongside the above properties.
551 memberSpecific map[string]interface{}
Paul Duffinc6ba1822022-05-06 09:38:02 +0000552}
553
554func (m *moduleInfo) MarshalJSON() ([]byte, error) {
555 buffer := bytes.Buffer{}
556
557 separator := ""
558 writeObjectPair := func(key string, value interface{}) {
559 buffer.WriteString(fmt.Sprintf("%s%q: ", separator, key))
560 b, err := json.Marshal(value)
561 if err != nil {
562 panic(err)
563 }
564 buffer.Write(b)
565 separator = ","
566 }
567
568 buffer.WriteString("{")
569 writeObjectPair("@type", m.moduleType)
570 writeObjectPair("@name", m.name)
571 if m.deps != nil {
572 writeObjectPair("@deps", m.deps)
573 }
Paul Duffin958806b2022-05-16 13:10:47 +0000574 for _, k := range android.SortedStringKeys(m.memberSpecific) {
575 v := m.memberSpecific[k]
Paul Duffinc6ba1822022-05-06 09:38:02 +0000576 writeObjectPair(k, v)
577 }
578 buffer.WriteString("}")
579 return buffer.Bytes(), nil
580}
581
582var _ json.Marshaler = (*moduleInfo)(nil)
583
584// generateInfoData creates a list of moduleInfo structures that will be marshalled into JSON.
585func (s *sdk) generateInfoData(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) interface{} {
586 modules := []*moduleInfo{}
587 sdkInfo := moduleInfo{
Paul Duffin958806b2022-05-16 13:10:47 +0000588 moduleType: "sdk",
589 name: ctx.ModuleName(),
590 memberSpecific: map[string]interface{}{},
Paul Duffinc6ba1822022-05-06 09:38:02 +0000591 }
592 modules = append(modules, &sdkInfo)
593
594 name2Info := map[string]*moduleInfo{}
595 getModuleInfo := func(module android.Module) *moduleInfo {
596 name := module.Name()
597 info := name2Info[name]
598 if info == nil {
599 moduleType := ctx.OtherModuleType(module)
600 // Remove any suffix added when creating modules dynamically.
601 moduleType = strings.Split(moduleType, "__")[0]
602 info = &moduleInfo{
603 moduleType: moduleType,
604 name: name,
605 }
Paul Duffin958806b2022-05-16 13:10:47 +0000606
607 additionalSdkInfo := ctx.OtherModuleProvider(module, android.AdditionalSdkInfoProvider).(android.AdditionalSdkInfo)
608 info.memberSpecific = additionalSdkInfo.Properties
609
Paul Duffinc6ba1822022-05-06 09:38:02 +0000610 name2Info[name] = info
611 }
612 return info
613 }
614
615 for _, memberVariantDep := range memberVariantDeps {
616 propertyName := memberVariantDep.memberType.SdkPropertyName()
617 var list []string
Paul Duffin958806b2022-05-16 13:10:47 +0000618 if v, ok := sdkInfo.memberSpecific[propertyName]; ok {
Paul Duffinc6ba1822022-05-06 09:38:02 +0000619 list = v.([]string)
620 }
621
622 memberName := memberVariantDep.variant.Name()
623 list = append(list, memberName)
Paul Duffin958806b2022-05-16 13:10:47 +0000624 sdkInfo.memberSpecific[propertyName] = android.SortedUniqueStrings(list)
Paul Duffinc6ba1822022-05-06 09:38:02 +0000625
626 if memberVariantDep.container != nil {
627 containerInfo := getModuleInfo(memberVariantDep.container)
628 containerInfo.deps = android.SortedUniqueStrings(append(containerInfo.deps, memberName))
629 }
630
631 // Make sure that the module info is created for each module.
632 getModuleInfo(memberVariantDep.variant)
633 }
634
635 for _, memberName := range android.SortedStringKeys(name2Info) {
636 info := name2Info[memberName]
637 modules = append(modules, info)
638 }
639
640 return modules
Paul Duffin26197a62021-04-24 00:34:10 +0100641}
642
Paul Duffinb97b1572021-04-29 21:50:40 +0100643// filterOutComponents removes any item from the deps list that is a component of another item in
644// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
645// then it will remove "foo.stubs" from the deps.
646func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
647 // Collate the set of components that all the modules added to the sdk provide.
648 components := map[string]*sdkMemberVariantDep{}
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000649 for i := range deps {
Paul Duffinb97b1572021-04-29 21:50:40 +0100650 dep := &deps[i]
651 for _, c := range dep.exportedComponentsInfo.Components {
652 components[c] = dep
653 }
654 }
655
656 // If no module provides components then return the input deps unfiltered.
657 if len(components) == 0 {
658 return deps
659 }
660
661 filtered := make([]sdkMemberVariantDep, 0, len(deps))
662 for _, dep := range deps {
663 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
664 if owner, ok := components[name]; ok {
665 // This is a component of another module that is a member of the sdk.
666
667 // If the component is exported but the owning module is not then the configuration is not
668 // supported.
669 if dep.export && !owner.export {
670 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
671 continue
672 }
673
674 // This module must not be added to the list of members of the sdk as that would result in a
675 // duplicate module in the sdk snapshot.
676 continue
677 }
678
679 filtered = append(filtered, dep)
680 }
681 return filtered
682}
683
Paul Duffinf88d8e02020-05-07 20:21:34 +0100684// Check the syntax of the generated Android.bp file contents and if they are
685// invalid then log an error with the contents (tagged with line numbers) and the
686// errors that were found so that it is easy to see where the problem lies.
687func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
688 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
689 if len(errs) != 0 {
690 message := &strings.Builder{}
691 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
692
693Generated Android.bp contents
694========================================================================
695`)
696 for i, line := range strings.Split(contents, "\n") {
697 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
698 }
699
700 _, _ = fmt.Fprint(message, `
701========================================================================
702
703Errors found:
704`)
705
706 for _, err := range errs {
707 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
708 }
709
710 ctx.ModuleErrorf("%s", message.String())
711 }
712}
713
Paul Duffin4b8b7932020-05-06 12:35:38 +0100714func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
715 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
716 if err != nil {
717 ctx.ModuleErrorf("error extracting common properties: %s", err)
718 }
719}
720
Paul Duffinfbe470e2021-04-24 12:37:13 +0100721// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
722type snapshotModuleStaticProperties struct {
723 Compile_multilib string `android:"arch_variant"`
724}
725
Paul Duffin2d1bb892021-04-24 11:32:59 +0100726// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
727type combinedSnapshotModuleProperties struct {
728 // The sdk variant from which this information was collected.
729 sdkVariant *sdk
730
731 // Static snapshot module properties.
732 staticProperties *snapshotModuleStaticProperties
733
734 // The dynamically generated member list properties.
735 dynamicProperties interface{}
736}
737
738// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100739func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
740 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100741 var list []*combinedSnapshotModuleProperties
742 for _, sdkVariant := range sdkVariants {
743 staticProperties := &snapshotModuleStaticProperties{
744 Compile_multilib: sdkVariant.multilibUsages.String(),
745 }
Paul Duffin62782de2021-07-14 12:05:16 +0100746 dynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100747
Paul Duffincd064672021-04-24 00:47:29 +0100748 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100749 sdkVariant: sdkVariant,
750 staticProperties: staticProperties,
751 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100752 }
753 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
754
755 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100756 }
Paul Duffincd064672021-04-24 00:47:29 +0100757
758 for _, memberVariantDep := range memberVariantDeps {
759 // If the member dependency is internal then do not add the dependency to the snapshot member
760 // list properties.
761 if !memberVariantDep.export {
762 continue
763 }
764
765 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin62782de2021-07-14 12:05:16 +0100766 memberListProperty := s.memberTypeListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100767 memberName := ctx.OtherModuleName(memberVariantDep.variant)
768
Paul Duffin13082052021-05-11 00:31:38 +0100769 if memberListProperty.getter == nil {
770 continue
771 }
772
Paul Duffincd064672021-04-24 00:47:29 +0100773 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100774 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100775 if !android.InList(memberName, memberList) {
776 memberList = append(memberList, memberName)
777 }
Paul Duffin13082052021-05-11 00:31:38 +0100778 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100779 }
780
Paul Duffin2d1bb892021-04-24 11:32:59 +0100781 return list
782}
783
784func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
785
786 // Extract the dynamic properties and add them to a list of propertiesContainer.
787 propertyContainers := []propertiesContainer{}
788 for _, i := range list {
789 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
790 sdkVariant: i.sdkVariant,
791 properties: i.dynamicProperties,
792 })
793 }
794
795 // Extract the common members, removing them from the original properties.
Paul Duffin62782de2021-07-14 12:05:16 +0100796 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100797 extractor := newCommonValueExtractor(commonDynamicProperties)
798 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
799
800 // Extract the static properties and add them to a list of propertiesContainer.
801 propertyContainers = []propertiesContainer{}
802 for _, i := range list {
803 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
804 sdkVariant: i.sdkVariant,
805 properties: i.staticProperties,
806 })
807 }
808
809 commonStaticProperties := &snapshotModuleStaticProperties{}
810 extractor = newCommonValueExtractor(commonStaticProperties)
811 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
812
813 return &combinedSnapshotModuleProperties{
814 sdkVariant: nil,
815 staticProperties: commonStaticProperties,
816 dynamicProperties: commonDynamicProperties,
817 }
818}
819
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000820type propertyTag struct {
821 name string
822}
823
Paul Duffin94289702021-09-09 15:38:32 +0100824var _ android.BpPropertyTag = propertyTag{}
825
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000826// BpPropertyTag instances to add to a property that contains references to other sdk members.
Paul Duffin0cb37b92020-03-04 14:52:46 +0000827//
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000828// These will ensure that the referenced modules are available, if required.
Paul Duffin13f02712020-03-06 12:30:43 +0000829var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000830var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000831
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000832type snapshotTransformation struct {
Paul Duffine6c0d842020-01-15 14:08:51 +0000833 identityTransformation
834 builder *snapshotBuilder
835}
836
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000837func (t snapshotTransformation) transformModule(module *bpModule) *bpModule {
Paul Duffin72910952020-01-20 18:16:30 +0000838 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100839 name := module.Name()
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000840 module.setProperty("name", t.builder.snapshotSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000841 return module
842}
843
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000844func (t snapshotTransformation) transformProperty(_ string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000845 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
846 required := tag == requiredSdkMemberReferencePropertyTag
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000847 return t.builder.snapshotSdkMemberNames(value.([]string), required), tag
Paul Duffin72910952020-01-20 18:16:30 +0000848 } else {
849 return value, tag
850 }
851}
852
Paul Duffina78f3a72020-02-21 16:29:35 +0000853type pruneEmptySetTransformer struct {
854 identityTransformation
855}
856
857var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
858
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000859func (t pruneEmptySetTransformer) transformPropertySetAfterContents(_ string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
Paul Duffina78f3a72020-02-21 16:29:35 +0000860 if len(propertySet.properties) == 0 {
861 return nil, nil
862 } else {
863 return propertySet, tag
864 }
865}
866
Paul Duffinb645ec82019-11-27 17:43:54 +0000867func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100868 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000869 for _, bpModule := range bpFile.order {
Paul Duffinb01ac4b2022-05-24 20:10:05 +0000870 contents.IndentedPrintf("\n")
871 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
872 outputPropertySet(contents, bpModule.bpPropertySet)
873 contents.IndentedPrintf("}\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000874 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000875}
876
877func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
878 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000879
Paul Duffin0df49682021-05-07 01:10:01 +0100880 addComment := func(name string) {
881 if text, ok := set.comments[name]; ok {
882 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100883 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100884 }
885 }
886 }
887
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000888 // Output the properties first, followed by the nested sets. This ensures a
889 // consistent output irrespective of whether property sets are created before
890 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000891 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000892 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000893
Paul Duffin0df49682021-05-07 01:10:01 +0100894 // Do not write property sets in the properties phase.
895 if _, ok := value.(*bpPropertySet); ok {
896 continue
897 }
898
899 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100900 reflectValue := reflect.ValueOf(value)
901 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000902 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000903
904 for _, name := range set.order {
905 value := set.getValue(name)
906
907 // Only write property sets in the sets phase.
908 switch v := value.(type) {
909 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100910 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100911 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000912 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100913 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000914 }
915 }
916
Paul Duffinb645ec82019-11-27 17:43:54 +0000917 contents.Dedent()
918}
919
Paul Duffina08e4dc2021-06-22 18:19:19 +0100920// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
921// by the value and then followed by a , and a newline.
922func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
923 contents.IndentedPrintf("%s: ", name)
924 outputUnnamedValue(contents, value)
925 contents.UnindentedPrintf(",\n")
926}
927
928// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
929// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
930// indented and all but the last line will end with a newline.
931func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
932 valueType := value.Type()
933 switch valueType.Kind() {
934 case reflect.Bool:
935 contents.UnindentedPrintf("%t", value.Bool())
936
937 case reflect.String:
938 contents.UnindentedPrintf("%q", value)
939
Paul Duffin51227d82021-05-18 12:54:27 +0100940 case reflect.Ptr:
941 outputUnnamedValue(contents, value.Elem())
942
Paul Duffina08e4dc2021-06-22 18:19:19 +0100943 case reflect.Slice:
944 length := value.Len()
945 if length == 0 {
946 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100947 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100948 firstValue := value.Index(0)
949 if length == 1 && !multiLineValue(firstValue) {
950 contents.UnindentedPrintf("[")
951 outputUnnamedValue(contents, firstValue)
952 contents.UnindentedPrintf("]")
953 } else {
954 contents.UnindentedPrintf("[\n")
955 contents.Indent()
956 for i := 0; i < length; i++ {
957 itemValue := value.Index(i)
958 contents.IndentedPrintf("")
959 outputUnnamedValue(contents, itemValue)
960 contents.UnindentedPrintf(",\n")
961 }
962 contents.Dedent()
963 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100964 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100965 }
966
Paul Duffin51227d82021-05-18 12:54:27 +0100967 case reflect.Struct:
968 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
969 v := value.Interface()
970 if _, ok := v.(android.BpPrintable); !ok {
971 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
972 }
973 contents.UnindentedPrintf("{\n")
974 contents.Indent()
975 for f := 0; f < valueType.NumField(); f++ {
976 fieldType := valueType.Field(f)
977 if fieldType.Anonymous {
978 continue
979 }
980 fieldValue := value.Field(f)
981 fieldName := fieldType.Name
982 propertyName := proptools.PropertyNameForField(fieldName)
983 outputNamedValue(contents, propertyName, fieldValue)
984 }
985 contents.Dedent()
986 contents.IndentedPrintf("}")
987
Paul Duffina08e4dc2021-06-22 18:19:19 +0100988 default:
989 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
990 }
991}
992
Paul Duffin51227d82021-05-18 12:54:27 +0100993// multiLineValue returns true if the supplied value may require multiple lines in the output.
994func multiLineValue(value reflect.Value) bool {
995 kind := value.Kind()
996 return kind == reflect.Slice || kind == reflect.Struct
997}
998
Paul Duffinac37c502019-11-26 18:02:20 +0000999func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001000 contents := &generatedContents{}
1001 generateBpContents(contents, s.builderForTests.bpFile)
1002 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +00001003}
1004
Paul Duffinc6ba1822022-05-06 09:38:02 +00001005func (s *sdk) GetInfoContentsForTests() string {
1006 return s.builderForTests.infoContents
1007}
1008
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001009type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +01001010 ctx android.ModuleContext
1011 sdk *sdk
1012
Paul Duffinb645ec82019-11-27 17:43:54 +00001013 snapshotDir android.OutputPath
1014 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +00001015
1016 // Map from destination to source of each copy - used to eliminate duplicates and
1017 // detect conflicts.
1018 copies map[string]string
1019
Paul Duffinb645ec82019-11-27 17:43:54 +00001020 filesToZip android.Paths
1021 zipsToMerge android.Paths
1022
Paul Duffin5c211452021-07-15 12:42:44 +01001023 // The path to an empty file.
1024 emptyFile android.WritablePath
1025
Paul Duffinb645ec82019-11-27 17:43:54 +00001026 prebuiltModules map[string]*bpModule
1027 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001028
1029 // The set of all members by name.
1030 allMembersByName map[string]struct{}
1031
1032 // The set of exported members by name.
1033 exportedMembersByName map[string]struct{}
Paul Duffin39abf8f2021-09-24 14:58:27 +01001034
1035 // The target build release for which the snapshot is to be generated.
1036 targetBuildRelease *buildRelease
Paul Duffinc6ba1822022-05-06 09:38:02 +00001037
Paul Duffin958806b2022-05-16 13:10:47 +00001038 // The contents of the .info file that describes the sdk contents.
Paul Duffinc6ba1822022-05-06 09:38:02 +00001039 infoContents string
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001040}
1041
1042func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001043 if existing, ok := s.copies[dest]; ok {
1044 if existing != src.String() {
1045 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1046 return
1047 }
1048 } else {
1049 path := s.snapshotDir.Join(s.ctx, dest)
1050 s.ctx.Build(pctx, android.BuildParams{
1051 Rule: android.Cp,
1052 Input: src,
1053 Output: path,
1054 })
1055 s.filesToZip = append(s.filesToZip, path)
1056
1057 s.copies[dest] = src.String()
1058 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001059}
1060
Paul Duffin91547182019-11-12 19:39:36 +00001061func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1062 ctx := s.ctx
1063
1064 // Repackage the zip file so that the entries are in the destDir directory.
1065 // This will allow the zip file to be merged into the snapshot.
1066 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001067
1068 ctx.Build(pctx, android.BuildParams{
1069 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1070 Rule: repackageZip,
1071 Input: zipPath,
1072 Output: tmpZipPath,
1073 Args: map[string]string{
1074 "destdir": destDir,
1075 },
1076 })
Paul Duffin91547182019-11-12 19:39:36 +00001077
1078 // Add the repackaged zip file to the files to merge.
1079 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1080}
1081
Paul Duffin5c211452021-07-15 12:42:44 +01001082func (s *snapshotBuilder) EmptyFile() android.Path {
1083 if s.emptyFile == nil {
1084 ctx := s.ctx
1085 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1086 s.ctx.Build(pctx, android.BuildParams{
1087 Rule: android.Touch,
1088 Output: s.emptyFile,
1089 })
1090 }
1091
1092 return s.emptyFile
1093}
1094
Paul Duffin9d8d6092019-12-05 18:19:29 +00001095func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1096 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001097 if s.prebuiltModules[name] != nil {
1098 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1099 }
1100
1101 m := s.bpFile.newModule(moduleType)
1102 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001103
Paul Duffinbefa4b92020-03-04 14:22:45 +00001104 variant := member.Variants()[0]
1105
Paul Duffin13f02712020-03-06 12:30:43 +00001106 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001107 // An internal member is only referenced from the sdk snapshot which is in the
1108 // same package so can be marked as private.
1109 m.AddProperty("visibility", []string{"//visibility:private"})
1110 } else {
1111 // Extract visibility information from a member variant. All variants have the same
1112 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001113 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1114
1115 // Add any additional visibility rules needed for the prebuilts to reference each other.
1116 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1117 if err != nil {
1118 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1119 }
1120
1121 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001122 if len(visibility) != 0 {
1123 m.AddProperty("visibility", visibility)
1124 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001125 }
1126
Martin Stjernholm1e041092020-11-03 00:11:09 +00001127 // Where available copy apex_available properties from the member.
1128 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1129 apexAvailable := apexAware.ApexAvailable()
1130 if len(apexAvailable) == 0 {
1131 // //apex_available:platform is the default.
1132 apexAvailable = []string{android.AvailableToPlatform}
1133 }
1134
1135 // Add in any baseline apex available settings.
1136 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1137
1138 // Remove duplicates and sort.
1139 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1140 sort.Strings(apexAvailable)
1141
1142 m.AddProperty("apex_available", apexAvailable)
1143 }
1144
Paul Duffinb0bb3762021-05-06 16:48:05 +01001145 // The licenses are the same for all variants.
1146 mctx := s.ctx
1147 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1148 if len(licenseInfo.Licenses) > 0 {
1149 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1150 }
1151
Paul Duffin865171e2020-03-02 18:38:15 +00001152 deviceSupported := false
1153 hostSupported := false
1154
1155 for _, variant := range member.Variants() {
1156 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001157 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001158 hostSupported = true
1159 } else if osClass == android.Device {
1160 deviceSupported = true
1161 }
1162 }
1163
1164 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001165
1166 s.prebuiltModules[name] = m
1167 s.prebuiltOrder = append(s.prebuiltOrder, m)
1168 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001169}
1170
Paul Duffin865171e2020-03-02 18:38:15 +00001171func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001172 // If neither device or host is supported then this module does not support either so will not
1173 // recognize the properties.
1174 if !deviceSupported && !hostSupported {
1175 return
1176 }
1177
Paul Duffin865171e2020-03-02 18:38:15 +00001178 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001179 bpModule.AddProperty("device_supported", false)
1180 }
Paul Duffin865171e2020-03-02 18:38:15 +00001181 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001182 bpModule.AddProperty("host_supported", true)
1183 }
1184}
1185
Paul Duffin13f02712020-03-06 12:30:43 +00001186func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1187 if required {
1188 return requiredSdkMemberReferencePropertyTag
1189 } else {
1190 return optionalSdkMemberReferencePropertyTag
1191 }
1192}
1193
1194func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1195 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001196}
1197
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001198// Get a name for sdk snapshot member. If the member is private then generate a snapshot specific
1199// name. As part of the processing this checks to make sure that any required members are part of
1200// the snapshot.
1201func (s *snapshotBuilder) snapshotSdkMemberName(name string, required bool) string {
1202 if _, ok := s.allMembersByName[name]; !ok {
Paul Duffin13f02712020-03-06 12:30:43 +00001203 if required {
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001204 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", name)
Paul Duffin13f02712020-03-06 12:30:43 +00001205 }
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001206 return name
Paul Duffin13f02712020-03-06 12:30:43 +00001207 }
1208
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001209 if s.isInternalMember(name) {
1210 return s.ctx.ModuleName() + "_" + name
Paul Duffin72910952020-01-20 18:16:30 +00001211 } else {
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001212 return name
Paul Duffin72910952020-01-20 18:16:30 +00001213 }
1214}
1215
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001216func (s *snapshotBuilder) snapshotSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001217 var references []string = nil
1218 for _, m := range members {
Paul Duffinb01ac4b2022-05-24 20:10:05 +00001219 references = append(references, s.snapshotSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001220 }
1221 return references
1222}
1223
Paul Duffin13f02712020-03-06 12:30:43 +00001224func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1225 _, ok := s.exportedMembersByName[memberName]
1226 return !ok
1227}
1228
Martin Stjernholm89238f42020-07-10 00:14:03 +01001229// Add the properties from the given SdkMemberProperties to the blueprint
1230// property set. This handles common properties in SdkMemberPropertiesBase and
1231// calls the member-specific AddToPropertySet for the rest.
1232func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1233 if memberProperties.Base().Compile_multilib != "" {
1234 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1235 }
1236
1237 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1238}
1239
Paul Duffin21827262021-04-24 12:16:36 +01001240// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1241type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001242 // The sdk variant that depends (possibly indirectly) on the member variant.
1243 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001244
1245 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001246 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001247
1248 // The variant that is added to the sdk.
1249 variant android.SdkAware
1250
Paul Duffinc6ba1822022-05-06 09:38:02 +00001251 // The optional container of this member, i.e. the module that is depended upon by the sdk
1252 // (possibly transitively) and whose dependency on this module is why it was added to the sdk.
1253 // Is nil if this a direct dependency of the sdk.
1254 container android.SdkAware
1255
Paul Duffinb97b1572021-04-29 21:50:40 +01001256 // True if the member should be exported, i.e. accessible, from outside the sdk.
1257 export bool
1258
1259 // The names of additional component modules provided by the variant.
1260 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001261}
1262
Paul Duffin13879572019-11-28 14:31:38 +00001263var _ android.SdkMember = (*sdkMember)(nil)
1264
Paul Duffin21827262021-04-24 12:16:36 +01001265// sdkMember groups all the variants of a specific member module together along with the name of the
1266// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001267type sdkMember struct {
1268 memberType android.SdkMemberType
1269 name string
1270 variants []android.SdkAware
1271}
1272
1273func (m *sdkMember) Name() string {
1274 return m.name
1275}
1276
1277func (m *sdkMember) Variants() []android.SdkAware {
1278 return m.variants
1279}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001280
Paul Duffin9c3760e2020-03-16 19:52:08 +00001281// Track usages of multilib variants.
1282type multilibUsage int
1283
1284const (
1285 multilibNone multilibUsage = 0
1286 multilib32 multilibUsage = 1
1287 multilib64 multilibUsage = 2
1288 multilibBoth = multilib32 | multilib64
1289)
1290
1291// Add the multilib that is used in the arch type.
1292func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1293 multilib := archType.Multilib
1294 switch multilib {
1295 case "":
1296 return m
1297 case "lib32":
1298 return m | multilib32
1299 case "lib64":
1300 return m | multilib64
1301 default:
1302 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1303 }
1304}
1305
1306func (m multilibUsage) String() string {
1307 switch m {
1308 case multilibNone:
1309 return ""
1310 case multilib32:
1311 return "32"
1312 case multilib64:
1313 return "64"
1314 case multilibBoth:
1315 return "both"
1316 default:
1317 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1318 m, multilibNone, multilib32, multilib64, multilibBoth))
1319 }
1320}
1321
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001322type baseInfo struct {
1323 Properties android.SdkMemberProperties
1324}
1325
Paul Duffinf34f6d82020-04-30 15:48:31 +01001326func (b *baseInfo) optimizableProperties() interface{} {
1327 return b.Properties
1328}
1329
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001330type osTypeSpecificInfo struct {
1331 baseInfo
1332
Paul Duffin00e46802020-03-12 20:40:35 +00001333 osType android.OsType
1334
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001335 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001336 //
1337 // Nil if there is one variant whose arch type is common
1338 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001339}
1340
Paul Duffin4b8b7932020-05-06 12:35:38 +01001341var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1342
Paul Duffinfc8dd232020-03-17 12:51:37 +00001343type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1344
Paul Duffin00e46802020-03-12 20:40:35 +00001345// Create a new osTypeSpecificInfo for the specified os type and its properties
1346// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001347func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001348 osInfo := &osTypeSpecificInfo{
1349 osType: osType,
1350 }
1351
1352 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1353 properties := variantPropertiesFactory()
1354 properties.Base().Os = osType
1355 return properties
1356 }
1357
1358 // Create a structure into which properties common across the architectures in
1359 // this os type will be stored.
1360 osInfo.Properties = osSpecificVariantPropertiesFactory()
1361
1362 // Group the variants by arch type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001363 var variantsByArchId = make(map[archId][]android.Module)
1364 var archIds []archId
Paul Duffin00e46802020-03-12 20:40:35 +00001365 for _, variant := range osTypeVariants {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001366 target := variant.Target()
1367 id := archIdFromTarget(target)
1368 if _, ok := variantsByArchId[id]; !ok {
1369 archIds = append(archIds, id)
Paul Duffin00e46802020-03-12 20:40:35 +00001370 }
1371
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001372 variantsByArchId[id] = append(variantsByArchId[id], variant)
Paul Duffin00e46802020-03-12 20:40:35 +00001373 }
1374
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001375 if commonVariants, ok := variantsByArchId[commonArchId]; ok {
Paul Duffin00e46802020-03-12 20:40:35 +00001376 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001377 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 +00001378 }
1379
1380 // A common arch type only has one variant and its properties should be treated
1381 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001382 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001383 } else {
1384 // Create an arch specific info for each supported architecture type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001385 for _, id := range archIds {
1386 archVariants := variantsByArchId[id]
1387 archInfo := newArchSpecificInfo(ctx, id, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001388
1389 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1390 }
1391 }
1392
1393 return osInfo
1394}
1395
Paul Duffin39abf8f2021-09-24 14:58:27 +01001396func (osInfo *osTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1397 if len(osInfo.archInfos) == 0 {
1398 pruner.pruneProperties(osInfo.Properties)
1399 } else {
1400 for _, archInfo := range osInfo.archInfos {
1401 archInfo.pruneUnsupportedProperties(pruner)
1402 }
1403 }
1404}
1405
Paul Duffin00e46802020-03-12 20:40:35 +00001406// Optimize the properties by extracting common properties from arch type specific
1407// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001408func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001409 // Nothing to do if there is only a single common architecture.
1410 if len(osInfo.archInfos) == 0 {
1411 return
1412 }
1413
Paul Duffin9c3760e2020-03-16 19:52:08 +00001414 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001415 for _, archInfo := range osInfo.archInfos {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001416 multilib = multilib.addArchType(archInfo.archId.archType)
Paul Duffin9c3760e2020-03-16 19:52:08 +00001417
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001418 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001419 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001420 }
1421
Paul Duffin4b8b7932020-05-06 12:35:38 +01001422 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001423
1424 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001425 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001426}
1427
1428// Add the properties for an os to a property set.
1429//
1430// Maps the properties related to the os variants through to an appropriate
1431// module structure that will produce equivalent set of variants when it is
1432// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001433func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001434
1435 var osPropertySet android.BpPropertySet
1436 var archPropertySet android.BpPropertySet
1437 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001438 if osInfo.Properties.Base().Os_count == 1 &&
1439 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1440 // There is only one OS type present in the variants and it shouldn't have a
1441 // variant-specific target. The latter is the case if it's either for device
1442 // where there is only one OS (android), or for host and the member type
1443 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001444
1445 // Create a structure that looks like:
1446 // module_type {
1447 // name: "...",
1448 // ...
1449 // <common properties>
1450 // ...
1451 // <single os type specific properties>
1452 //
1453 // arch: {
1454 // <arch specific sections>
1455 // }
1456 //
1457 osPropertySet = bpModule
1458 archPropertySet = osPropertySet.AddPropertySet("arch")
1459
1460 // Arch specific properties need to be added to an arch specific section
1461 // within arch.
1462 archOsPrefix = ""
1463 } else {
1464 // Create a structure that looks like:
1465 // module_type {
1466 // name: "...",
1467 // ...
1468 // <common properties>
1469 // ...
1470 // target: {
1471 // <arch independent os specific sections, e.g. android>
1472 // ...
1473 // <arch and os specific sections, e.g. android_x86>
1474 // }
1475 //
1476 osType := osInfo.osType
1477 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1478 archPropertySet = targetPropertySet
1479
1480 // Arch specific properties need to be added to an os and arch specific
1481 // section prefixed with <os>_.
1482 archOsPrefix = osType.Name + "_"
1483 }
1484
1485 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001486 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001487
1488 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1489 // os) specific properties.
1490 //
1491 // The archInfos list will be empty if the os contains variants for the common
1492 // architecture.
1493 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001494 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001495 }
1496}
1497
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001498func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1499 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001500 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001501}
1502
1503var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1504
Paul Duffin4b8b7932020-05-06 12:35:38 +01001505func (osInfo *osTypeSpecificInfo) String() string {
1506 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1507}
1508
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001509// archId encapsulates the information needed to identify a combination of arch type and native
1510// bridge support.
1511//
1512// Conceptually, native bridge support is a facet of an android.Target, not an android.Arch as it is
1513// essentially using one android.Arch to implement another. However, in terms of the handling of
1514// the variants native bridge is treated as part of the arch variation. See the ArchVariation method
1515// on android.Target.
1516//
1517// So, it makes sense when optimizing the variants to combine native bridge with the arch type.
1518type archId struct {
1519 // The arch type of the variant's target.
1520 archType android.ArchType
1521
1522 // True if the variants is for the native bridge, false otherwise.
1523 nativeBridge bool
1524}
1525
1526// propertyName returns the name of the property corresponding to use for this arch id.
1527func (i *archId) propertyName() string {
1528 name := i.archType.Name
1529 if i.nativeBridge {
1530 // Note: This does not result in a valid property because there is no architecture specific
1531 // native bridge property, only a generic "native_bridge" property. However, this will be used
1532 // in error messages if there is an attempt to use this in a generated bp file.
1533 name += "_native_bridge"
1534 }
1535 return name
1536}
1537
1538func (i *archId) String() string {
1539 return fmt.Sprintf("ArchType{%s}, NativeBridge{%t}", i.archType, i.nativeBridge)
1540}
1541
1542// archIdFromTarget returns an archId initialized from information in the supplied target.
1543func archIdFromTarget(target android.Target) archId {
1544 return archId{
1545 archType: target.Arch.ArchType,
1546 nativeBridge: target.NativeBridge == android.NativeBridgeEnabled,
1547 }
1548}
1549
1550// commonArchId is the archId for the common architecture.
1551var commonArchId = archId{archType: android.Common}
1552
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001553type archTypeSpecificInfo struct {
1554 baseInfo
1555
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001556 archId archId
1557 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001558
Paul Duffinb42fa672021-09-09 16:37:49 +01001559 imageVariantInfos []*imageVariantSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001560}
1561
Paul Duffin4b8b7932020-05-06 12:35:38 +01001562var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1563
Paul Duffinfc8dd232020-03-17 12:51:37 +00001564// Create a new archTypeSpecificInfo for the specified arch type and its properties
1565// structures populated with information from the variants.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001566func newArchSpecificInfo(ctx android.SdkMemberContext, archId archId, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001567
Paul Duffinfc8dd232020-03-17 12:51:37 +00001568 // Create an arch specific info into which the variant properties can be copied.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001569 archInfo := &archTypeSpecificInfo{archId: archId, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001570
1571 // Create the properties into which the arch type specific properties will be
1572 // added.
1573 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001574
Liz Kammer96320df2022-05-12 20:40:00 -04001575 // if there are multiple supported link variants, we want to nest based on linkage even if there
1576 // is only one variant, otherwise, if there is only one variant we can populate based on the arch
1577 if len(archVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001578 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001579 } else {
Paul Duffinb42fa672021-09-09 16:37:49 +01001580 // Group the variants by image type.
1581 variantsByImage := make(map[string][]android.Module)
1582 for _, variant := range archVariants {
1583 image := variant.ImageVariation().Variation
1584 variantsByImage[image] = append(variantsByImage[image], variant)
1585 }
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001586
Paul Duffinb42fa672021-09-09 16:37:49 +01001587 // Create the image variant info in a fixed order.
1588 for _, imageVariantName := range android.SortedStringKeys(variantsByImage) {
1589 variants := variantsByImage[imageVariantName]
1590 archInfo.imageVariantInfos = append(archInfo.imageVariantInfos, newImageVariantSpecificInfo(ctx, imageVariantName, variantPropertiesFactory, variants))
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001591 }
1592 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001593
1594 return archInfo
1595}
1596
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001597// Get the link type of the variant
1598//
1599// If the variant is not differentiated by link type then it returns "",
1600// otherwise it returns one of "static" or "shared".
1601func getLinkType(variant android.Module) string {
1602 linkType := ""
1603 if linkable, ok := variant.(cc.LinkableInterface); ok {
1604 if linkable.Shared() && linkable.Static() {
1605 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1606 } else if linkable.Shared() {
1607 linkType = "shared"
1608 } else if linkable.Static() {
1609 linkType = "static"
1610 } else {
1611 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1612 }
1613 }
1614 return linkType
1615}
1616
Paul Duffin39abf8f2021-09-24 14:58:27 +01001617func (archInfo *archTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1618 if len(archInfo.imageVariantInfos) == 0 {
1619 pruner.pruneProperties(archInfo.Properties)
1620 } else {
1621 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1622 imageVariantInfo.pruneUnsupportedProperties(pruner)
1623 }
1624 }
1625}
1626
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001627// Optimize the properties by extracting common properties from link type specific
1628// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001629func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001630 if len(archInfo.imageVariantInfos) == 0 {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001631 return
1632 }
1633
Paul Duffinb42fa672021-09-09 16:37:49 +01001634 // Optimize the image variant properties first.
1635 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1636 imageVariantInfo.optimizeProperties(ctx, commonValueExtractor)
1637 }
1638
1639 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.imageVariantInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001640}
1641
Paul Duffinfc8dd232020-03-17 12:51:37 +00001642// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001643func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001644 archPropertySuffix := archInfo.archId.propertyName()
1645 propertySetName := archOsPrefix + archPropertySuffix
1646 archTypePropertySet := archPropertySet.AddPropertySet(propertySetName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001647 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1648 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1649 archTypePropertySet.AddProperty("enabled", true)
1650 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001651 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001652
Paul Duffinb42fa672021-09-09 16:37:49 +01001653 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1654 imageVariantInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001655 }
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001656
1657 // If this is for a native bridge architecture then make sure that the property set does not
1658 // contain any properties as providing native bridge specific properties is not currently
1659 // supported.
1660 if archInfo.archId.nativeBridge {
1661 propertySetContents := getPropertySetContents(archTypePropertySet)
1662 if propertySetContents != "" {
1663 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",
1664 propertySetName, ctx.name, propertySetContents)
1665 }
1666 }
1667}
1668
1669// getPropertySetContents returns the string representation of the contents of a property set, after
1670// recursively pruning any empty nested property sets.
1671func getPropertySetContents(propertySet android.BpPropertySet) string {
1672 set := propertySet.(*bpPropertySet)
1673 set.transformContents(pruneEmptySetTransformer{})
1674 if len(set.properties) != 0 {
1675 contents := &generatedContents{}
1676 contents.Indent()
1677 outputPropertySet(contents, set)
1678 setAsString := contents.content.String()
1679 return setAsString
1680 }
1681 return ""
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001682}
1683
Paul Duffin4b8b7932020-05-06 12:35:38 +01001684func (archInfo *archTypeSpecificInfo) String() string {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001685 return archInfo.archId.String()
Paul Duffin4b8b7932020-05-06 12:35:38 +01001686}
1687
Paul Duffinb42fa672021-09-09 16:37:49 +01001688type imageVariantSpecificInfo struct {
1689 baseInfo
1690
1691 imageVariant string
1692
1693 linkInfos []*linkTypeSpecificInfo
1694}
1695
1696func newImageVariantSpecificInfo(ctx android.SdkMemberContext, imageVariant string, variantPropertiesFactory variantPropertiesFactoryFunc, imageVariants []android.Module) *imageVariantSpecificInfo {
1697
1698 // Create an image variant specific info into which the variant properties can be copied.
1699 imageInfo := &imageVariantSpecificInfo{imageVariant: imageVariant}
1700
1701 // Create the properties into which the image variant specific properties will be added.
1702 imageInfo.Properties = variantPropertiesFactory()
1703
Liz Kammer96320df2022-05-12 20:40:00 -04001704 // if there are multiple supported link variants, we want to nest even if there is only one
1705 // variant, otherwise, if there is only one variant we can populate based on the image
1706 if len(imageVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffinb42fa672021-09-09 16:37:49 +01001707 imageInfo.Properties.PopulateFromVariant(ctx, imageVariants[0])
1708 } else {
1709 // There is more than one variant for this image variant which must be differentiated by link
Liz Kammer96320df2022-05-12 20:40:00 -04001710 // type. Or there are multiple supported linkages and we need to nest based on link type.
Paul Duffinb42fa672021-09-09 16:37:49 +01001711 for _, linkVariant := range imageVariants {
1712 linkType := getLinkType(linkVariant)
1713 if linkType == "" {
1714 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(imageVariants)))
1715 } else {
1716 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
1717
1718 imageInfo.linkInfos = append(imageInfo.linkInfos, linkInfo)
1719 }
1720 }
1721 }
1722
1723 return imageInfo
1724}
1725
Paul Duffin39abf8f2021-09-24 14:58:27 +01001726func (imageInfo *imageVariantSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1727 if len(imageInfo.linkInfos) == 0 {
1728 pruner.pruneProperties(imageInfo.Properties)
1729 } else {
1730 for _, linkInfo := range imageInfo.linkInfos {
1731 linkInfo.pruneUnsupportedProperties(pruner)
1732 }
1733 }
1734}
1735
Paul Duffinb42fa672021-09-09 16:37:49 +01001736// Optimize the properties by extracting common properties from link type specific
1737// properties into arch type specific properties.
1738func (imageInfo *imageVariantSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
1739 if len(imageInfo.linkInfos) == 0 {
1740 return
1741 }
1742
1743 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, imageInfo.Properties, imageInfo.linkInfos)
1744}
1745
1746// Add the properties for an arch type to a property set.
1747func (imageInfo *imageVariantSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1748 if imageInfo.imageVariant != android.CoreVariation {
1749 propertySet = propertySet.AddPropertySet(imageInfo.imageVariant)
1750 }
1751
1752 addSdkMemberPropertiesToSet(ctx, imageInfo.Properties, propertySet)
1753
Liz Kammer96320df2022-05-12 20:40:00 -04001754 usedLinkages := make(map[string]bool, len(imageInfo.linkInfos))
Paul Duffinb42fa672021-09-09 16:37:49 +01001755 for _, linkInfo := range imageInfo.linkInfos {
Liz Kammer96320df2022-05-12 20:40:00 -04001756 usedLinkages[linkInfo.linkType] = true
Paul Duffinb42fa672021-09-09 16:37:49 +01001757 linkInfo.addToPropertySet(ctx, propertySet)
1758 }
1759
Liz Kammer96320df2022-05-12 20:40:00 -04001760 // If not all supported linkages had existing variants, we need to disable the unsupported variant
1761 if len(imageInfo.linkInfos) < len(ctx.MemberType().SupportedLinkages()) {
1762 for _, l := range ctx.MemberType().SupportedLinkages() {
1763 if _, ok := usedLinkages[l]; !ok {
1764 otherLinkagePropertySet := propertySet.AddPropertySet(l)
1765 otherLinkagePropertySet.AddProperty("enabled", false)
1766 }
1767 }
1768 }
1769
Paul Duffinb42fa672021-09-09 16:37:49 +01001770 // If this is for a non-core image variant then make sure that the property set does not contain
1771 // any properties as providing non-core image variant specific properties for prebuilts is not
1772 // currently supported.
1773 if imageInfo.imageVariant != android.CoreVariation {
1774 propertySetContents := getPropertySetContents(propertySet)
1775 if propertySetContents != "" {
1776 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",
1777 imageInfo.imageVariant, ctx.name, propertySetContents)
1778 }
1779 }
1780}
1781
1782func (imageInfo *imageVariantSpecificInfo) String() string {
1783 return imageInfo.imageVariant
1784}
1785
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001786type linkTypeSpecificInfo struct {
1787 baseInfo
1788
1789 linkType string
1790}
1791
Paul Duffin4b8b7932020-05-06 12:35:38 +01001792var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1793
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001794// Create a new linkTypeSpecificInfo for the specified link type and its properties
1795// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001796func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001797 linkInfo := &linkTypeSpecificInfo{
1798 baseInfo: baseInfo{
1799 // Create the properties into which the link type specific properties will be
1800 // added.
1801 Properties: variantPropertiesFactory(),
1802 },
1803 linkType: linkType,
1804 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001805 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001806 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001807}
1808
Paul Duffinf68f85a2021-09-09 16:11:42 +01001809func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1810 linkPropertySet := propertySet.AddPropertySet(l.linkType)
1811 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
1812}
1813
Paul Duffin39abf8f2021-09-24 14:58:27 +01001814func (l *linkTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1815 pruner.pruneProperties(l.Properties)
1816}
1817
Paul Duffin4b8b7932020-05-06 12:35:38 +01001818func (l *linkTypeSpecificInfo) String() string {
1819 return fmt.Sprintf("LinkType{%s}", l.linkType)
1820}
1821
Paul Duffin3a4eb502020-03-19 16:11:18 +00001822type memberContext struct {
1823 sdkMemberContext android.ModuleContext
1824 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001825 memberType android.SdkMemberType
1826 name string
Paul Duffind19f8942021-07-14 12:08:37 +01001827
1828 // The set of traits required of this member.
1829 requiredTraits android.SdkMemberTraitSet
Paul Duffin3a4eb502020-03-19 16:11:18 +00001830}
1831
1832func (m *memberContext) SdkModuleContext() android.ModuleContext {
1833 return m.sdkMemberContext
1834}
1835
1836func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1837 return m.builder
1838}
1839
Paul Duffina551a1c2020-03-17 21:04:24 +00001840func (m *memberContext) MemberType() android.SdkMemberType {
1841 return m.memberType
1842}
1843
1844func (m *memberContext) Name() string {
1845 return m.name
1846}
1847
Paul Duffind19f8942021-07-14 12:08:37 +01001848func (m *memberContext) RequiresTrait(trait android.SdkMemberTrait) bool {
1849 return m.requiredTraits.Contains(trait)
1850}
1851
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001852func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001853
1854 memberType := member.memberType
1855
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001856 // Do not add the prefer property if the member snapshot module is a source module type.
Paul Duffin39abf8f2021-09-24 14:58:27 +01001857 config := ctx.sdkMemberContext.Config()
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001858 if !memberType.UsesSourceModuleTypeInSnapshot() {
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +00001859 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1860 // snapshot to be created that sets prefer: true.
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001861 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1862 // dynamically at build time not at snapshot generation time.
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001863 prefer := config.IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001864
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001865 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1866 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1867 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1868 // behavior is for the module.
1869 bpModule.insertAfter("name", "prefer", prefer)
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001870
1871 configVar := config.Getenv("SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR")
1872 if configVar != "" {
1873 parts := strings.Split(configVar, ":")
1874 cfp := android.ConfigVarProperties{
1875 Config_namespace: proptools.StringPtr(parts[0]),
1876 Var_name: proptools.StringPtr(parts[1]),
1877 }
1878 bpModule.insertAfter("prefer", "use_source_config_var", cfp)
1879 }
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001880 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001881
Paul Duffina04c1072020-03-02 10:16:35 +00001882 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001883 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001884 variants := member.Variants()
1885 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001886 osType := variant.Target().Os
1887 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001888 }
1889
Paul Duffina04c1072020-03-02 10:16:35 +00001890 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001891 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001892 properties := memberType.CreateVariantPropertiesStruct()
1893 base := properties.Base()
1894 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001895 return properties
1896 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001897
Paul Duffina04c1072020-03-02 10:16:35 +00001898 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001899
Paul Duffina04c1072020-03-02 10:16:35 +00001900 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001901 commonProperties := variantPropertiesFactory()
1902 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001903
Paul Duffin39abf8f2021-09-24 14:58:27 +01001904 // Create a property pruner that will prune any properties unsupported by the target build
1905 // release.
1906 targetBuildRelease := ctx.builder.targetBuildRelease
1907 unsupportedPropertyPruner := newPropertyPrunerByBuildRelease(commonProperties, targetBuildRelease)
1908
Paul Duffinc097e362020-03-10 22:50:03 +00001909 // Create common value extractor that can be used to optimize the properties.
1910 commonValueExtractor := newCommonValueExtractor(commonProperties)
1911
Paul Duffina04c1072020-03-02 10:16:35 +00001912 // The list of property structures which are os type specific but common across
1913 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001914 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001915
1916 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001917 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001918 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001919 // Add the os specific properties to a list of os type specific yet architecture
1920 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001921 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001922
Paul Duffin39abf8f2021-09-24 14:58:27 +01001923 osInfo.pruneUnsupportedProperties(unsupportedPropertyPruner)
1924
Paul Duffin00e46802020-03-12 20:40:35 +00001925 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001926 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001927 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001928
Paul Duffina04c1072020-03-02 10:16:35 +00001929 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001930 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001931
Paul Duffina04c1072020-03-02 10:16:35 +00001932 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001933 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001934
Paul Duffina04c1072020-03-02 10:16:35 +00001935 // Create a target property set into which target specific properties can be
1936 // added.
1937 targetPropertySet := bpModule.AddPropertySet("target")
1938
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001939 // If the member is host OS dependent and has host_supported then disable by
1940 // default and enable each host OS variant explicitly. This avoids problems
1941 // with implicitly enabled OS variants when the snapshot is used, which might
1942 // be different from this run (e.g. different build OS).
1943 if ctx.memberType.IsHostOsDependent() {
1944 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1945 if hostSupported {
1946 hostPropertySet := targetPropertySet.AddPropertySet("host")
1947 hostPropertySet.AddProperty("enabled", false)
1948 }
1949 }
1950
Paul Duffina04c1072020-03-02 10:16:35 +00001951 // Iterate over the os types in a fixed order.
1952 for _, osType := range s.getPossibleOsTypes() {
1953 osInfo := osTypeToInfo[osType]
1954 if osInfo == nil {
1955 continue
1956 }
1957
Paul Duffin3a4eb502020-03-19 16:11:18 +00001958 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001959 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001960}
1961
Paul Duffina04c1072020-03-02 10:16:35 +00001962// Compute the list of possible os types that this sdk could support.
1963func (s *sdk) getPossibleOsTypes() []android.OsType {
1964 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001965 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001966 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07001967 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00001968 osTypes = append(osTypes, osType)
1969 }
1970 }
1971 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001972 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001973 osTypes = append(osTypes, osType)
1974 }
1975 }
1976 }
1977 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1978 return osTypes
1979}
1980
Paul Duffinb28369a2020-05-04 15:39:59 +01001981// Given a set of properties (struct value), return the value of the field within that
1982// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001983type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1984
Paul Duffinc459f892020-04-30 18:08:29 +01001985// Checks the metadata to determine whether the property should be ignored for the
1986// purposes of common value extraction or not.
1987type extractorMetadataPredicate func(metadata propertiesContainer) bool
1988
1989// Indicates whether optimizable properties are provided by a host variant or
1990// not.
1991type isHostVariant interface {
1992 isHostVariant() bool
1993}
1994
Paul Duffinb28369a2020-05-04 15:39:59 +01001995// A property that can be optimized by the commonValueExtractor.
1996type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001997 // The name of the field for this property. It is a "."-separated path for
1998 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001999 name string
2000
Paul Duffinc459f892020-04-30 18:08:29 +01002001 // Filter that can use metadata associated with the properties being optimized
2002 // to determine whether the field should be ignored during common value
2003 // optimization.
2004 filter extractorMetadataPredicate
2005
Paul Duffinb28369a2020-05-04 15:39:59 +01002006 // Retrieves the value on which common value optimization will be performed.
2007 getter fieldAccessorFunc
2008
2009 // The empty value for the field.
2010 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01002011
2012 // True if the property can support arch variants false otherwise.
2013 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01002014}
2015
Paul Duffin4b8b7932020-05-06 12:35:38 +01002016func (p extractorProperty) String() string {
2017 return p.name
2018}
2019
Paul Duffinc097e362020-03-10 22:50:03 +00002020// Supports extracting common values from a number of instances of a properties
2021// structure into a separate common set of properties.
2022type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01002023 // The properties that the extractor can optimize.
2024 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00002025}
2026
2027// Create a new common value extractor for the structure type for the supplied
2028// properties struct.
2029//
2030// The returned extractor can be used on any properties structure of the same type
2031// as the supplied set of properties.
2032func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
2033 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
2034 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01002035 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00002036 return extractor
2037}
2038
2039// Gather the fields from the supplied structure type from which common values will
2040// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00002041//
Martin Stjernholmb0249572020-09-15 02:32:35 +01002042// This is recursive function. If it encounters a struct then it will recurse
2043// into it, passing in the accessor for the field and the struct name as prefix
2044// for the nested fields. That will then be used in the accessors for the fields
2045// in the embedded struct.
2046func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00002047 for f := 0; f < structType.NumField(); f++ {
2048 field := structType.Field(f)
2049 if field.PkgPath != "" {
2050 // Ignore unexported fields.
2051 continue
2052 }
2053
Paul Duffinb07fa512020-03-10 22:17:04 +00002054 // Ignore fields whose value should be kept.
2055 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00002056 continue
2057 }
2058
Paul Duffinc459f892020-04-30 18:08:29 +01002059 var filter extractorMetadataPredicate
2060
2061 // Add a filter
2062 if proptools.HasTag(field, "sdk", "ignored-on-host") {
2063 filter = func(metadata propertiesContainer) bool {
2064 if m, ok := metadata.(isHostVariant); ok {
2065 if m.isHostVariant() {
2066 return false
2067 }
2068 }
2069 return true
2070 }
2071 }
2072
Paul Duffinc097e362020-03-10 22:50:03 +00002073 // Save a copy of the field index for use in the function.
2074 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01002075
Martin Stjernholmb0249572020-09-15 02:32:35 +01002076 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01002077
Paul Duffinc097e362020-03-10 22:50:03 +00002078 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00002079 if containingStructAccessor != nil {
2080 // This is an embedded structure so first access the field for the embedded
2081 // structure.
2082 value = containingStructAccessor(value)
2083 }
2084
Paul Duffinc097e362020-03-10 22:50:03 +00002085 // Skip through interface and pointer values to find the structure.
2086 value = getStructValue(value)
2087
Paul Duffin4b8b7932020-05-06 12:35:38 +01002088 defer func() {
2089 if r := recover(); r != nil {
2090 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
2091 }
2092 }()
2093
Paul Duffinc097e362020-03-10 22:50:03 +00002094 // Return the field.
2095 return value.Field(fieldIndex)
2096 }
2097
Martin Stjernholmb0249572020-09-15 02:32:35 +01002098 if field.Type.Kind() == reflect.Struct {
2099 // Gather fields from the nested or embedded structure.
2100 var subNamePrefix string
2101 if field.Anonymous {
2102 subNamePrefix = namePrefix
2103 } else {
2104 subNamePrefix = name + "."
2105 }
2106 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00002107 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01002108 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01002109 name,
Paul Duffinc459f892020-04-30 18:08:29 +01002110 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01002111 fieldGetter,
2112 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01002113 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01002114 }
2115 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00002116 }
Paul Duffinc097e362020-03-10 22:50:03 +00002117 }
2118}
2119
2120func getStructValue(value reflect.Value) reflect.Value {
2121foundStruct:
2122 for {
2123 kind := value.Kind()
2124 switch kind {
2125 case reflect.Interface, reflect.Ptr:
2126 value = value.Elem()
2127 case reflect.Struct:
2128 break foundStruct
2129 default:
2130 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
2131 }
2132 }
2133 return value
2134}
2135
Paul Duffinf34f6d82020-04-30 15:48:31 +01002136// A container of properties to be optimized.
2137//
2138// Allows additional information to be associated with the properties, e.g. for
2139// filtering.
2140type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002141 fmt.Stringer
2142
Paul Duffinf34f6d82020-04-30 15:48:31 +01002143 // Get the properties that need optimizing.
2144 optimizableProperties() interface{}
2145}
2146
Paul Duffin2d1bb892021-04-24 11:32:59 +01002147// A wrapper for sdk variant related properties to allow them to be optimized.
2148type sdkVariantPropertiesContainer struct {
2149 sdkVariant *sdk
2150 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01002151}
2152
Paul Duffin2d1bb892021-04-24 11:32:59 +01002153func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
2154 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01002155}
2156
Paul Duffin2d1bb892021-04-24 11:32:59 +01002157func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002158 return c.sdkVariant.String()
2159}
2160
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002161// Extract common properties from a slice of property structures of the same type.
2162//
2163// All the property structures must be of the same type.
2164// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002165// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002166//
2167// Iterates over each exported field (capitalized name) and checks to see whether they
2168// have the same value (using DeepEquals) across all the input properties. If it does not then no
2169// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01002170// and the field in each of the input properties structure is set to its default value. Nested
2171// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002172func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002173 commonPropertiesValue := reflect.ValueOf(commonProperties)
2174 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002175
Paul Duffinf34f6d82020-04-30 15:48:31 +01002176 sliceValue := reflect.ValueOf(inputPropertiesSlice)
2177
Paul Duffinb28369a2020-05-04 15:39:59 +01002178 for _, property := range e.properties {
2179 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01002180 filter := property.filter
2181 if filter == nil {
2182 filter = func(metadata propertiesContainer) bool {
2183 return true
2184 }
2185 }
Paul Duffinb28369a2020-05-04 15:39:59 +01002186
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002187 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002188 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2189 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002190 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002191
Paul Duffin864e1b42020-05-06 10:23:19 +01002192 // Assume that all the values will be the same.
2193 //
2194 // While similar to this is not quite the same as commonValue == nil. If all the values
2195 // have been filtered out then this will be false but commonValue == nil will be true.
2196 valuesDiffer := false
2197
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002198 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002199 container := sliceValue.Index(i).Interface().(propertiesContainer)
2200 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002201 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002202
Paul Duffinc459f892020-04-30 18:08:29 +01002203 if !filter(container) {
2204 expectedValue := property.emptyValue.Interface()
2205 actualValue := fieldValue.Interface()
2206 if !reflect.DeepEqual(expectedValue, actualValue) {
2207 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2208 }
2209 continue
2210 }
2211
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002212 if commonValue == nil {
2213 // Use the first value as the commonProperties value.
2214 commonValue = &fieldValue
2215 } else {
2216 // If the value does not match the current common value then there is
2217 // no value in common so break out.
2218 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2219 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002220 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002221 break
2222 }
2223 }
2224 }
2225
Paul Duffin864e1b42020-05-06 10:23:19 +01002226 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002227 // and set the input struct's field to the empty value.
2228 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002229 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002230 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002231 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002232 container := sliceValue.Index(i).Interface().(propertiesContainer)
2233 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002234 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002235 fieldValue.Set(emptyValue)
2236 }
2237 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002238
2239 if valuesDiffer && !property.archVariant {
2240 // The values differ but the property does not support arch variants so it
2241 // is an error.
2242 var details strings.Builder
2243 for i := 0; i < sliceValue.Len(); i++ {
2244 container := sliceValue.Index(i).Interface().(propertiesContainer)
2245 itemValue := reflect.ValueOf(container.optimizableProperties())
2246 fieldValue := fieldGetter(itemValue)
2247
2248 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2249 }
2250
2251 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2252 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002253 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002254
2255 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002256}