blob: bd23750219d93230c25e28faf695f7105eea21a2 [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 Duffin1a44a992022-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 Duffin42cdd622022-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{
Paul Duffin43d56de2022-07-18 13:18:23 +0000111 Command: `${config.MergeZipsCmd} -s $out $in`,
Paul Duffin375058f2019-11-29 20:17:53 +0000112 CommandDeps: []string{
113 "${config.MergeZipsCmd}",
114 },
115 })
116)
117
Paul Duffin43f7bf02021-05-05 22:00:51 +0100118const (
Paul Duffin42cdd622022-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 Duffin42cdd622022-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 Duffin42cdd622022-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 Duffina649ad52022-07-26 23:53:00 +0000186
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000187 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
188 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf7b3d0d2021-09-02 14:29:21 +0100189 if memberTag, ok := tag.(android.SdkMemberDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100190 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900191
Paul Duffin5cca7c42021-05-26 10:16:01 +0100192 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
193 if memberType == nil {
194 return false
195 }
196
Paul Duffin13879572019-11-28 14:31:38 +0000197 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000198 if !memberType.IsInstance(child) {
199 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900200 }
Paul Duffin13879572019-11-28 14:31:38 +0000201
Paul Duffin6a7e9532020-03-20 17:50:07 +0000202 // Keep track of which multilib variants are used by the sdk.
203 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
204
Paul Duffinb97b1572021-04-29 21:50:40 +0100205 var exportedComponentsInfo android.ExportedComponentsInfo
206 if ctx.OtherModuleHasProvider(child, android.ExportedComponentsInfoProvider) {
207 exportedComponentsInfo = ctx.OtherModuleProvider(child, android.ExportedComponentsInfoProvider).(android.ExportedComponentsInfo)
208 }
209
Paul Duffin1a44a992022-05-06 09:38:02 +0000210 var container android.SdkAware
211 if parent != ctx.Module() {
212 container = parent.(android.SdkAware)
213 }
214
Paul Duffina649ad52022-07-26 23:53:00 +0000215 minApiLevel := android.MinApiLevelForSdkSnapshot(ctx, child)
216
Paul Duffina7208112021-04-23 21:20:20 +0100217 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100218 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
Paul Duffin1a44a992022-05-06 09:38:02 +0000219 sdkVariant: s,
220 memberType: memberType,
221 variant: child.(android.SdkAware),
Paul Duffina649ad52022-07-26 23:53:00 +0000222 minApiLevel: minApiLevel,
Paul Duffin1a44a992022-05-06 09:38:02 +0000223 container: container,
224 export: export,
225 exportedComponentsInfo: exportedComponentsInfo,
Paul Duffinb97b1572021-04-29 21:50:40 +0100226 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000227
Paul Duffin2d3da312021-05-06 12:02:27 +0100228 // Recurse down into the member's dependencies as it may have dependencies that need to be
229 // automatically added to the sdk.
230 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900231 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000232
233 return false
Paul Duffin13879572019-11-28 14:31:38 +0000234 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000235}
236
Paul Duffincc3132e2021-04-24 01:10:30 +0100237// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
238// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000239//
Paul Duffincc3132e2021-04-24 01:10:30 +0100240// The sdkMember instances are then grouped into slices by member type. Within each such slice the
241// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000242//
Paul Duffincc3132e2021-04-24 01:10:30 +0100243// Finally, the member type slices are concatenated together to form a single slice. The order in
244// which they are concatenated is the order in which the member types were registered in the
245// android.SdkMemberTypesRegistry.
Paul Duffinb0c28d62022-07-01 15:56:06 +0000246func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, targetBuildRelease *buildRelease, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000247 byType := make(map[android.SdkMemberType][]*sdkMember)
248 byName := make(map[string]*sdkMember)
249
Paul Duffin21827262021-04-24 12:16:36 +0100250 for _, memberVariantDep := range memberVariantDeps {
251 memberType := memberVariantDep.memberType
252 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000253
254 name := ctx.OtherModuleName(variant)
255 member := byName[name]
256 if member == nil {
257 member = &sdkMember{memberType: memberType, name: name}
258 byName[name] = member
259 byType[memberType] = append(byType[memberType], member)
Liz Kammer7b710832022-05-12 20:40:00 -0400260 } else if member.memberType != memberType {
261 // validate whether this is the same member type or and overriding member type
262 if memberType.Overrides(member.memberType) {
263 member.memberType = memberType
264 } else if !member.memberType.Overrides(memberType) {
265 ctx.ModuleErrorf("Incompatible member types %q %q", member.memberType, memberType)
266 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000267 }
268
Paul Duffin1356d8c2020-02-25 19:26:33 +0000269 // Only append new variants to the list. This is needed because a member can be both
270 // exported by the sdk and also be a transitive sdk member.
271 member.variants = appendUniqueVariants(member.variants, variant)
272 }
Paul Duffin13879572019-11-28 14:31:38 +0000273 var members []*sdkMember
Paul Duffin62782de2021-07-14 12:05:16 +0100274 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffinb0c28d62022-07-01 15:56:06 +0000275 memberType := memberListProperty.memberType
276
277 if !isMemberTypeSupportedByTargetBuildRelease(memberType, targetBuildRelease) {
278 continue
279 }
280
281 membersOfType := byType[memberType]
Paul Duffin13879572019-11-28 14:31:38 +0000282 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900283 }
284
Paul Duffin6a7e9532020-03-20 17:50:07 +0000285 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900286}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900287
Paul Duffinb0c28d62022-07-01 15:56:06 +0000288// isMemberTypeSupportedByTargetBuildRelease returns true if the member type is supported by the
289// target build release.
290func isMemberTypeSupportedByTargetBuildRelease(memberType android.SdkMemberType, targetBuildRelease *buildRelease) bool {
291 supportedByTargetBuildRelease := true
292 supportedBuildReleases := memberType.SupportedBuildReleases()
293 if supportedBuildReleases == "" {
294 supportedBuildReleases = "S+"
295 }
296
297 set, err := parseBuildReleaseSet(supportedBuildReleases)
298 if err != nil {
299 panic(fmt.Errorf("member type %s has invalid supported build releases %q: %s",
300 memberType.SdkPropertyName(), supportedBuildReleases, err))
301 }
302 if !set.contains(targetBuildRelease) {
303 supportedByTargetBuildRelease = false
304 }
305 return supportedByTargetBuildRelease
306}
307
Paul Duffin72910952020-01-20 18:16:30 +0000308func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
309 for _, v := range variants {
310 if v == newVariant {
311 return variants
312 }
313 }
314 return append(variants, newVariant)
315}
316
Paul Duffin51509a12022-04-06 12:48:09 +0000317// BUILD_NUMBER_FILE is the name of the file in the snapshot zip that will contain the number of
318// the build from which the snapshot was produced.
319const BUILD_NUMBER_FILE = "snapshot-creation-build-number.txt"
320
Jiyong Park73c54ee2019-10-22 20:31:18 +0900321// SDK directory structure
322// <sdk_root>/
323// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
324// <api_ver>/ : below this directory are all auto-generated
325// Android.bp : definition of 'sdk_snapshot' module is here
326// aidl/
327// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
328// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900329// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900330// include/
331// bionic/libc/include/stdlib.h : an exported header file
332// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900333// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900334// <arch>/include/ : arch-specific exported headers
335// <arch>/include_gen/ : arch-specific generated headers
336// <arch>/lib/
337// libFoo.so : a stub library
338
Paul Duffina649ad52022-07-26 23:53:00 +0000339func (s sdk) targetBuildRelease(ctx android.ModuleContext) *buildRelease {
340 config := ctx.Config()
341 currentBuildRelease := latestBuildRelease()
342 targetBuildReleaseEnv := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE", currentBuildRelease.name)
343 targetBuildRelease, err := nameToRelease(targetBuildReleaseEnv)
344 if err != nil {
345 ctx.ModuleErrorf("invalid SOONG_SDK_SNAPSHOT_TARGET_BUILD_RELEASE: %s", err)
346 targetBuildRelease = currentBuildRelease
347 }
348
349 return targetBuildRelease
350}
351
Jiyong Park232e7852019-11-04 12:23:40 +0900352// buildSnapshot is the main function in this source file. It creates rules to copy
353// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1a44a992022-05-06 09:38:02 +0000354func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000355
Paul Duffina649ad52022-07-26 23:53:00 +0000356 targetBuildRelease := s.targetBuildRelease(ctx)
357 targetApiLevel, err := android.ApiLevelFromUser(ctx, targetBuildRelease.name)
358 if err != nil {
359 targetApiLevel = android.FutureApiLevel
360 }
361
Paul Duffinb97b1572021-04-29 21:50:40 +0100362 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100363 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100364 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000365 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100366 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100367 }
Paul Duffin865171e2020-03-02 18:38:15 +0000368
Paul Duffinb97b1572021-04-29 21:50:40 +0100369 // Filter out any sdkMemberVariantDep that is a component of another.
370 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000371
Paul Duffina649ad52022-07-26 23:53:00 +0000372 // Record the names of all the members, both explicitly specified and implicitly included. Also,
373 // record the names of any members that should be excluded from this snapshot.
Paul Duffinb97b1572021-04-29 21:50:40 +0100374 allMembersByName := make(map[string]struct{})
375 exportedMembersByName := make(map[string]struct{})
Paul Duffina649ad52022-07-26 23:53:00 +0000376 excludedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100377
Paul Duffina649ad52022-07-26 23:53:00 +0000378 addMember := func(name string, export bool, exclude bool) {
379 if exclude {
380 excludedMembersByName[name] = struct{}{}
381 return
382 }
383
Paul Duffinb97b1572021-04-29 21:50:40 +0100384 allMembersByName[name] = struct{}{}
385 if export {
386 exportedMembersByName[name] = struct{}{}
387 }
388 }
389
390 for _, memberVariantDep := range memberVariantDeps {
391 name := memberVariantDep.variant.Name()
392 export := memberVariantDep.export
393
Paul Duffina649ad52022-07-26 23:53:00 +0000394 // If the minApiLevel of the member is greater than the target API level then exclude it from
395 // this snapshot.
396 exclude := memberVariantDep.minApiLevel.GreaterThan(targetApiLevel)
397
398 addMember(name, export, exclude)
Paul Duffinb97b1572021-04-29 21:50:40 +0100399
400 // Add any components provided by the module.
401 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
Paul Duffina649ad52022-07-26 23:53:00 +0000402 addMember(component, export, exclude)
Paul Duffinb97b1572021-04-29 21:50:40 +0100403 }
404
405 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
406 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000407 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000408 }
409
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000410 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900411
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000412 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000413
414 bpFile := &bpFile{
415 modules: make(map[string]*bpModule),
416 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000417
Paul Duffin42cdd622022-05-24 20:10:05 +0000418 // Always add -current to the end
419 snapshotFileSuffix := "-current"
Paul Duffin43f7bf02021-05-05 22:00:51 +0100420
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000421 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000422 ctx: ctx,
423 sdk: s,
Paul Duffin13f02712020-03-06 12:30:43 +0000424 snapshotDir: snapshotDir.OutputPath,
425 copies: make(map[string]string),
426 filesToZip: []android.Path{bp.path},
427 bpFile: bpFile,
428 prebuiltModules: make(map[string]*bpModule),
429 allMembersByName: allMembersByName,
430 exportedMembersByName: exportedMembersByName,
Paul Duffina649ad52022-07-26 23:53:00 +0000431 excludedMembersByName: excludedMembersByName,
Paul Duffin39abf8f2021-09-24 14:58:27 +0100432 targetBuildRelease: targetBuildRelease,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900433 }
Paul Duffinac37c502019-11-26 18:02:20 +0000434 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900435
Paul Duffin62131702021-05-07 01:10:01 +0100436 // If the sdk snapshot includes any license modules then add a package module which has a
437 // default_applicable_licenses property. That will prevent the LSC license process from updating
438 // the generated Android.bp file to add a package module that includes all licenses used by all
439 // the modules in that package. That would be unnecessary as every module in the sdk should have
440 // their own licenses property specified.
441 if hasLicenses {
442 pkg := bpFile.newModule("package")
443 property := "default_applicable_licenses"
444 pkg.AddCommentForProperty(property, `
445A default list here prevents the license LSC from adding its own list which would
446be unnecessary as every module in the sdk already has its own licenses property.
447`)
448 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
449 bpFile.AddModule(pkg)
450 }
451
Paul Duffin0df49682021-05-07 01:10:01 +0100452 // Group the variants for each member module together and then group the members of each member
453 // type together.
Paul Duffinb0c28d62022-07-01 15:56:06 +0000454 members := s.groupMemberVariantsByMemberThenType(ctx, targetBuildRelease, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100455
456 // Create the prebuilt modules for each of the member modules.
Paul Duffind19f8942021-07-14 12:08:37 +0100457 traits := s.gatherTraits()
Paul Duffin13ad94f2020-02-19 16:19:27 +0000458 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000459 memberType := member.memberType
Paul Duffin2bf43892022-05-13 13:12:19 +0000460 if !memberType.ArePrebuiltsRequired() {
461 continue
462 }
Paul Duffin3a4eb502020-03-19 16:11:18 +0000463
Paul Duffind19f8942021-07-14 12:08:37 +0100464 name := member.name
Paul Duffina649ad52022-07-26 23:53:00 +0000465 if _, ok := excludedMembersByName[name]; ok {
466 continue
467 }
468
Paul Duffind19f8942021-07-14 12:08:37 +0100469 requiredTraits := traits[name]
470 if requiredTraits == nil {
471 requiredTraits = android.EmptySdkMemberTraitSet()
472 }
473
474 // Create the snapshot for the member.
475 memberCtx := &memberContext{ctx, builder, memberType, name, requiredTraits}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000476
477 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100478 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900479 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900480
Paul Duffin42cdd622022-05-24 20:10:05 +0000481 // Create a transformer that will transform a module by replacing any references
Paul Duffin72910952020-01-20 18:16:30 +0000482 // to internal members with a unique module name and setting prefer: false.
Paul Duffin42cdd622022-05-24 20:10:05 +0000483 snapshotTransformer := snapshotTransformation{
Paul Duffin64fb5262021-05-05 21:36:04 +0100484 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100485 }
Paul Duffin72910952020-01-20 18:16:30 +0000486
Paul Duffin42cdd622022-05-24 20:10:05 +0000487 for _, module := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000488 // Prune any empty property sets.
Paul Duffin42cdd622022-05-24 20:10:05 +0000489 module = module.transform(pruneEmptySetTransformer{})
Paul Duffina78f3a72020-02-21 16:29:35 +0000490
Paul Duffin42cdd622022-05-24 20:10:05 +0000491 // Transform the module module to make it suitable for use in the snapshot.
492 module.transform(snapshotTransformer)
493 bpFile.AddModule(module)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100494 }
Paul Duffin26197a62021-04-24 00:34:10 +0100495
496 // generate Android.bp
497 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
498 generateBpContents(&bp.generatedContents, bpFile)
499
500 contents := bp.content.String()
Paul Duffin39abf8f2021-09-24 14:58:27 +0100501 // If the snapshot is being generated for the current build release then check the syntax to make
502 // sure that it is compatible.
Paul Duffina649ad52022-07-26 23:53:00 +0000503 if targetBuildRelease == latestBuildRelease() {
Paul Duffin39abf8f2021-09-24 14:58:27 +0100504 syntaxCheckSnapshotBpFile(ctx, contents)
505 }
Paul Duffin26197a62021-04-24 00:34:10 +0100506
507 bp.build(pctx, ctx, nil)
508
Paul Duffin51509a12022-04-06 12:48:09 +0000509 // Copy the build number file into the snapshot.
510 builder.CopyToSnapshot(ctx.Config().BuildNumberFile(ctx), BUILD_NUMBER_FILE)
511
Paul Duffin43d56de2022-07-18 13:18:23 +0000512 filesToZip := android.SortedUniquePaths(builder.filesToZip)
Paul Duffin26197a62021-04-24 00:34:10 +0100513
514 // zip them all
Paul Duffin1a44a992022-05-06 09:38:02 +0000515 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100516 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100517 outputDesc := "Building snapshot for " + ctx.ModuleName()
518
519 // If there are no zips to merge then generate the output zip directly.
520 // Otherwise, generate an intermediate zip file into which other zips can be
521 // merged.
522 var zipFile android.OutputPath
523 var desc string
524 if len(builder.zipsToMerge) == 0 {
525 zipFile = outputZipFile
526 desc = outputDesc
527 } else {
Paul Duffin1a44a992022-05-06 09:38:02 +0000528 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotFileSuffix)
Paul Duffin43f7bf02021-05-05 22:00:51 +0100529 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100530 desc = "Building intermediate snapshot for " + ctx.ModuleName()
531 }
532
533 ctx.Build(pctx, android.BuildParams{
534 Description: desc,
535 Rule: zipFiles,
536 Inputs: filesToZip,
537 Output: zipFile,
538 Args: map[string]string{
539 "basedir": builder.snapshotDir.String(),
540 },
541 })
542
543 if len(builder.zipsToMerge) != 0 {
544 ctx.Build(pctx, android.BuildParams{
545 Description: outputDesc,
546 Rule: mergeZips,
547 Input: zipFile,
Paul Duffin43d56de2022-07-18 13:18:23 +0000548 Inputs: android.SortedUniquePaths(builder.zipsToMerge),
Paul Duffin26197a62021-04-24 00:34:10 +0100549 Output: outputZipFile,
550 })
551 }
552
Paul Duffin1a44a992022-05-06 09:38:02 +0000553 modules := s.generateInfoData(ctx, memberVariantDeps)
554
555 // Output the modules information as pretty printed JSON.
556 info := newGeneratedFile(ctx, fmt.Sprintf("%s%s.info", ctx.ModuleName(), snapshotFileSuffix))
557 output, err := json.MarshalIndent(modules, "", " ")
558 if err != nil {
559 ctx.ModuleErrorf("error generating %q: %s", info, err)
560 }
561 builder.infoContents = string(output)
562 info.generatedContents.UnindentedPrintf("%s", output)
563 info.build(pctx, ctx, nil)
564 infoPath := info.path
565 installedInfo := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), infoPath.Base(), infoPath)
566 s.infoFile = android.OptionalPathForPath(installedInfo)
567
568 // Install the zip, making sure that the info file has been installed as well.
569 installedZip := ctx.InstallFile(android.PathForMainlineSdksInstall(ctx), outputZipFile.Base(), outputZipFile, installedInfo)
570 s.snapshotFile = android.OptionalPathForPath(installedZip)
571}
572
573type moduleInfo struct {
574 // The type of the module, e.g. java_sdk_library
575 moduleType string
576 // The name of the module.
577 name string
578 // A list of additional dependencies of the module.
579 deps []string
Paul Duffindec81382022-05-16 13:10:47 +0000580 // Additional member specific properties.
581 // These will be added into the generated JSON alongside the above properties.
582 memberSpecific map[string]interface{}
Paul Duffin1a44a992022-05-06 09:38:02 +0000583}
584
585func (m *moduleInfo) MarshalJSON() ([]byte, error) {
586 buffer := bytes.Buffer{}
587
588 separator := ""
589 writeObjectPair := func(key string, value interface{}) {
590 buffer.WriteString(fmt.Sprintf("%s%q: ", separator, key))
591 b, err := json.Marshal(value)
592 if err != nil {
593 panic(err)
594 }
595 buffer.Write(b)
596 separator = ","
597 }
598
599 buffer.WriteString("{")
600 writeObjectPair("@type", m.moduleType)
601 writeObjectPair("@name", m.name)
602 if m.deps != nil {
603 writeObjectPair("@deps", m.deps)
604 }
Paul Duffindec81382022-05-16 13:10:47 +0000605 for _, k := range android.SortedStringKeys(m.memberSpecific) {
606 v := m.memberSpecific[k]
Paul Duffin1a44a992022-05-06 09:38:02 +0000607 writeObjectPair(k, v)
608 }
609 buffer.WriteString("}")
610 return buffer.Bytes(), nil
611}
612
613var _ json.Marshaler = (*moduleInfo)(nil)
614
615// generateInfoData creates a list of moduleInfo structures that will be marshalled into JSON.
616func (s *sdk) generateInfoData(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) interface{} {
617 modules := []*moduleInfo{}
618 sdkInfo := moduleInfo{
Paul Duffindec81382022-05-16 13:10:47 +0000619 moduleType: "sdk",
620 name: ctx.ModuleName(),
621 memberSpecific: map[string]interface{}{},
Paul Duffin1a44a992022-05-06 09:38:02 +0000622 }
623 modules = append(modules, &sdkInfo)
624
625 name2Info := map[string]*moduleInfo{}
626 getModuleInfo := func(module android.Module) *moduleInfo {
627 name := module.Name()
628 info := name2Info[name]
629 if info == nil {
630 moduleType := ctx.OtherModuleType(module)
631 // Remove any suffix added when creating modules dynamically.
632 moduleType = strings.Split(moduleType, "__")[0]
633 info = &moduleInfo{
634 moduleType: moduleType,
635 name: name,
636 }
Paul Duffindec81382022-05-16 13:10:47 +0000637
638 additionalSdkInfo := ctx.OtherModuleProvider(module, android.AdditionalSdkInfoProvider).(android.AdditionalSdkInfo)
639 info.memberSpecific = additionalSdkInfo.Properties
640
Paul Duffin1a44a992022-05-06 09:38:02 +0000641 name2Info[name] = info
642 }
643 return info
644 }
645
646 for _, memberVariantDep := range memberVariantDeps {
647 propertyName := memberVariantDep.memberType.SdkPropertyName()
648 var list []string
Paul Duffindec81382022-05-16 13:10:47 +0000649 if v, ok := sdkInfo.memberSpecific[propertyName]; ok {
Paul Duffin1a44a992022-05-06 09:38:02 +0000650 list = v.([]string)
651 }
652
653 memberName := memberVariantDep.variant.Name()
654 list = append(list, memberName)
Paul Duffindec81382022-05-16 13:10:47 +0000655 sdkInfo.memberSpecific[propertyName] = android.SortedUniqueStrings(list)
Paul Duffin1a44a992022-05-06 09:38:02 +0000656
657 if memberVariantDep.container != nil {
658 containerInfo := getModuleInfo(memberVariantDep.container)
659 containerInfo.deps = android.SortedUniqueStrings(append(containerInfo.deps, memberName))
660 }
661
662 // Make sure that the module info is created for each module.
663 getModuleInfo(memberVariantDep.variant)
664 }
665
666 for _, memberName := range android.SortedStringKeys(name2Info) {
667 info := name2Info[memberName]
668 modules = append(modules, info)
669 }
670
671 return modules
Paul Duffin26197a62021-04-24 00:34:10 +0100672}
673
Paul Duffinb97b1572021-04-29 21:50:40 +0100674// filterOutComponents removes any item from the deps list that is a component of another item in
675// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
676// then it will remove "foo.stubs" from the deps.
677func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
678 // Collate the set of components that all the modules added to the sdk provide.
679 components := map[string]*sdkMemberVariantDep{}
Paul Duffin42cdd622022-05-24 20:10:05 +0000680 for i := range deps {
Paul Duffinb97b1572021-04-29 21:50:40 +0100681 dep := &deps[i]
682 for _, c := range dep.exportedComponentsInfo.Components {
683 components[c] = dep
684 }
685 }
686
687 // If no module provides components then return the input deps unfiltered.
688 if len(components) == 0 {
689 return deps
690 }
691
692 filtered := make([]sdkMemberVariantDep, 0, len(deps))
693 for _, dep := range deps {
694 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
695 if owner, ok := components[name]; ok {
696 // This is a component of another module that is a member of the sdk.
697
698 // If the component is exported but the owning module is not then the configuration is not
699 // supported.
700 if dep.export && !owner.export {
701 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
702 continue
703 }
704
705 // This module must not be added to the list of members of the sdk as that would result in a
706 // duplicate module in the sdk snapshot.
707 continue
708 }
709
710 filtered = append(filtered, dep)
711 }
712 return filtered
713}
714
Paul Duffinf88d8e02020-05-07 20:21:34 +0100715// Check the syntax of the generated Android.bp file contents and if they are
716// invalid then log an error with the contents (tagged with line numbers) and the
717// errors that were found so that it is easy to see where the problem lies.
718func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
719 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
720 if len(errs) != 0 {
721 message := &strings.Builder{}
722 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
723
724Generated Android.bp contents
725========================================================================
726`)
727 for i, line := range strings.Split(contents, "\n") {
728 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
729 }
730
731 _, _ = fmt.Fprint(message, `
732========================================================================
733
734Errors found:
735`)
736
737 for _, err := range errs {
738 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
739 }
740
741 ctx.ModuleErrorf("%s", message.String())
742 }
743}
744
Paul Duffin4b8b7932020-05-06 12:35:38 +0100745func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
746 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
747 if err != nil {
748 ctx.ModuleErrorf("error extracting common properties: %s", err)
749 }
750}
751
Paul Duffinfbe470e2021-04-24 12:37:13 +0100752// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
753type snapshotModuleStaticProperties struct {
754 Compile_multilib string `android:"arch_variant"`
755}
756
Paul Duffin2d1bb892021-04-24 11:32:59 +0100757// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
758type combinedSnapshotModuleProperties struct {
759 // The sdk variant from which this information was collected.
760 sdkVariant *sdk
761
762 // Static snapshot module properties.
763 staticProperties *snapshotModuleStaticProperties
764
765 // The dynamically generated member list properties.
766 dynamicProperties interface{}
767}
768
769// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100770func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
771 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100772 var list []*combinedSnapshotModuleProperties
773 for _, sdkVariant := range sdkVariants {
774 staticProperties := &snapshotModuleStaticProperties{
775 Compile_multilib: sdkVariant.multilibUsages.String(),
776 }
Paul Duffin62782de2021-07-14 12:05:16 +0100777 dynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100778
Paul Duffincd064672021-04-24 00:47:29 +0100779 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100780 sdkVariant: sdkVariant,
781 staticProperties: staticProperties,
782 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100783 }
784 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
785
786 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100787 }
Paul Duffincd064672021-04-24 00:47:29 +0100788
789 for _, memberVariantDep := range memberVariantDeps {
790 // If the member dependency is internal then do not add the dependency to the snapshot member
791 // list properties.
792 if !memberVariantDep.export {
793 continue
794 }
795
796 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin62782de2021-07-14 12:05:16 +0100797 memberListProperty := s.memberTypeListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100798 memberName := ctx.OtherModuleName(memberVariantDep.variant)
799
Paul Duffin13082052021-05-11 00:31:38 +0100800 if memberListProperty.getter == nil {
801 continue
802 }
803
Paul Duffincd064672021-04-24 00:47:29 +0100804 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100805 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100806 if !android.InList(memberName, memberList) {
807 memberList = append(memberList, memberName)
808 }
Paul Duffin13082052021-05-11 00:31:38 +0100809 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100810 }
811
Paul Duffin2d1bb892021-04-24 11:32:59 +0100812 return list
813}
814
815func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
816
817 // Extract the dynamic properties and add them to a list of propertiesContainer.
818 propertyContainers := []propertiesContainer{}
819 for _, i := range list {
820 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
821 sdkVariant: i.sdkVariant,
822 properties: i.dynamicProperties,
823 })
824 }
825
826 // Extract the common members, removing them from the original properties.
Paul Duffin62782de2021-07-14 12:05:16 +0100827 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100828 extractor := newCommonValueExtractor(commonDynamicProperties)
829 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
830
831 // Extract the static properties and add them to a list of propertiesContainer.
832 propertyContainers = []propertiesContainer{}
833 for _, i := range list {
834 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
835 sdkVariant: i.sdkVariant,
836 properties: i.staticProperties,
837 })
838 }
839
840 commonStaticProperties := &snapshotModuleStaticProperties{}
841 extractor = newCommonValueExtractor(commonStaticProperties)
842 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
843
844 return &combinedSnapshotModuleProperties{
845 sdkVariant: nil,
846 staticProperties: commonStaticProperties,
847 dynamicProperties: commonDynamicProperties,
848 }
849}
850
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000851type propertyTag struct {
852 name string
853}
854
Paul Duffin94289702021-09-09 15:38:32 +0100855var _ android.BpPropertyTag = propertyTag{}
856
Paul Duffin42cdd622022-05-24 20:10:05 +0000857// BpPropertyTag instances to add to a property that contains references to other sdk members.
Paul Duffin0cb37b92020-03-04 14:52:46 +0000858//
Paul Duffin42cdd622022-05-24 20:10:05 +0000859// These will ensure that the referenced modules are available, if required.
Paul Duffin13f02712020-03-06 12:30:43 +0000860var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000861var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000862
Paul Duffin42cdd622022-05-24 20:10:05 +0000863type snapshotTransformation struct {
Paul Duffine6c0d842020-01-15 14:08:51 +0000864 identityTransformation
865 builder *snapshotBuilder
866}
867
Paul Duffin42cdd622022-05-24 20:10:05 +0000868func (t snapshotTransformation) transformModule(module *bpModule) *bpModule {
Paul Duffin72910952020-01-20 18:16:30 +0000869 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100870 name := module.Name()
Paul Duffin42cdd622022-05-24 20:10:05 +0000871 module.setProperty("name", t.builder.snapshotSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000872 return module
873}
874
Paul Duffin42cdd622022-05-24 20:10:05 +0000875func (t snapshotTransformation) transformProperty(_ string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000876 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
877 required := tag == requiredSdkMemberReferencePropertyTag
Paul Duffin42cdd622022-05-24 20:10:05 +0000878 return t.builder.snapshotSdkMemberNames(value.([]string), required), tag
Paul Duffin72910952020-01-20 18:16:30 +0000879 } else {
880 return value, tag
881 }
882}
883
Paul Duffina78f3a72020-02-21 16:29:35 +0000884type pruneEmptySetTransformer struct {
885 identityTransformation
886}
887
888var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
889
Paul Duffin42cdd622022-05-24 20:10:05 +0000890func (t pruneEmptySetTransformer) transformPropertySetAfterContents(_ string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
Paul Duffina78f3a72020-02-21 16:29:35 +0000891 if len(propertySet.properties) == 0 {
892 return nil, nil
893 } else {
894 return propertySet, tag
895 }
896}
897
Paul Duffinb645ec82019-11-27 17:43:54 +0000898func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100899 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000900 for _, bpModule := range bpFile.order {
Paul Duffin42cdd622022-05-24 20:10:05 +0000901 contents.IndentedPrintf("\n")
902 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
903 outputPropertySet(contents, bpModule.bpPropertySet)
904 contents.IndentedPrintf("}\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000905 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000906}
907
908func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
909 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000910
Paul Duffin0df49682021-05-07 01:10:01 +0100911 addComment := func(name string) {
912 if text, ok := set.comments[name]; ok {
913 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100914 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100915 }
916 }
917 }
918
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000919 // Output the properties first, followed by the nested sets. This ensures a
920 // consistent output irrespective of whether property sets are created before
921 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000922 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000923 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000924
Paul Duffin0df49682021-05-07 01:10:01 +0100925 // Do not write property sets in the properties phase.
926 if _, ok := value.(*bpPropertySet); ok {
927 continue
928 }
929
930 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100931 reflectValue := reflect.ValueOf(value)
932 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000933 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000934
935 for _, name := range set.order {
936 value := set.getValue(name)
937
938 // Only write property sets in the sets phase.
939 switch v := value.(type) {
940 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100941 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100942 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000943 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100944 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000945 }
946 }
947
Paul Duffinb645ec82019-11-27 17:43:54 +0000948 contents.Dedent()
949}
950
Paul Duffina08e4dc2021-06-22 18:19:19 +0100951// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
952// by the value and then followed by a , and a newline.
953func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
954 contents.IndentedPrintf("%s: ", name)
955 outputUnnamedValue(contents, value)
956 contents.UnindentedPrintf(",\n")
957}
958
959// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
960// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
961// indented and all but the last line will end with a newline.
962func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
963 valueType := value.Type()
964 switch valueType.Kind() {
965 case reflect.Bool:
966 contents.UnindentedPrintf("%t", value.Bool())
967
968 case reflect.String:
969 contents.UnindentedPrintf("%q", value)
970
Paul Duffin51227d82021-05-18 12:54:27 +0100971 case reflect.Ptr:
972 outputUnnamedValue(contents, value.Elem())
973
Paul Duffina08e4dc2021-06-22 18:19:19 +0100974 case reflect.Slice:
975 length := value.Len()
976 if length == 0 {
977 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100978 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100979 firstValue := value.Index(0)
980 if length == 1 && !multiLineValue(firstValue) {
981 contents.UnindentedPrintf("[")
982 outputUnnamedValue(contents, firstValue)
983 contents.UnindentedPrintf("]")
984 } else {
985 contents.UnindentedPrintf("[\n")
986 contents.Indent()
987 for i := 0; i < length; i++ {
988 itemValue := value.Index(i)
989 contents.IndentedPrintf("")
990 outputUnnamedValue(contents, itemValue)
991 contents.UnindentedPrintf(",\n")
992 }
993 contents.Dedent()
994 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100995 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100996 }
997
Paul Duffin51227d82021-05-18 12:54:27 +0100998 case reflect.Struct:
999 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
1000 v := value.Interface()
1001 if _, ok := v.(android.BpPrintable); !ok {
1002 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
1003 }
1004 contents.UnindentedPrintf("{\n")
1005 contents.Indent()
1006 for f := 0; f < valueType.NumField(); f++ {
1007 fieldType := valueType.Field(f)
1008 if fieldType.Anonymous {
1009 continue
1010 }
1011 fieldValue := value.Field(f)
1012 fieldName := fieldType.Name
1013 propertyName := proptools.PropertyNameForField(fieldName)
1014 outputNamedValue(contents, propertyName, fieldValue)
1015 }
1016 contents.Dedent()
1017 contents.IndentedPrintf("}")
1018
Paul Duffina08e4dc2021-06-22 18:19:19 +01001019 default:
1020 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
1021 }
1022}
1023
Paul Duffin51227d82021-05-18 12:54:27 +01001024// multiLineValue returns true if the supplied value may require multiple lines in the output.
1025func multiLineValue(value reflect.Value) bool {
1026 kind := value.Kind()
1027 return kind == reflect.Slice || kind == reflect.Struct
1028}
1029
Paul Duffinac37c502019-11-26 18:02:20 +00001030func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001031 contents := &generatedContents{}
1032 generateBpContents(contents, s.builderForTests.bpFile)
1033 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +00001034}
1035
Paul Duffin1a44a992022-05-06 09:38:02 +00001036func (s *sdk) GetInfoContentsForTests() string {
1037 return s.builderForTests.infoContents
1038}
1039
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001040type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +01001041 ctx android.ModuleContext
1042 sdk *sdk
1043
Paul Duffinb645ec82019-11-27 17:43:54 +00001044 snapshotDir android.OutputPath
1045 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +00001046
1047 // Map from destination to source of each copy - used to eliminate duplicates and
1048 // detect conflicts.
1049 copies map[string]string
1050
Paul Duffinb645ec82019-11-27 17:43:54 +00001051 filesToZip android.Paths
1052 zipsToMerge android.Paths
1053
Paul Duffin5c211452021-07-15 12:42:44 +01001054 // The path to an empty file.
1055 emptyFile android.WritablePath
1056
Paul Duffinb645ec82019-11-27 17:43:54 +00001057 prebuiltModules map[string]*bpModule
1058 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001059
1060 // The set of all members by name.
1061 allMembersByName map[string]struct{}
1062
1063 // The set of exported members by name.
1064 exportedMembersByName map[string]struct{}
Paul Duffin39abf8f2021-09-24 14:58:27 +01001065
Paul Duffina649ad52022-07-26 23:53:00 +00001066 // The set of members which have been excluded from this snapshot; by name.
1067 excludedMembersByName map[string]struct{}
1068
Paul Duffin39abf8f2021-09-24 14:58:27 +01001069 // The target build release for which the snapshot is to be generated.
1070 targetBuildRelease *buildRelease
Paul Duffin1a44a992022-05-06 09:38:02 +00001071
Paul Duffindec81382022-05-16 13:10:47 +00001072 // The contents of the .info file that describes the sdk contents.
Paul Duffin1a44a992022-05-06 09:38:02 +00001073 infoContents string
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001074}
1075
1076func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001077 if existing, ok := s.copies[dest]; ok {
1078 if existing != src.String() {
1079 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1080 return
1081 }
1082 } else {
1083 path := s.snapshotDir.Join(s.ctx, dest)
1084 s.ctx.Build(pctx, android.BuildParams{
1085 Rule: android.Cp,
1086 Input: src,
1087 Output: path,
1088 })
1089 s.filesToZip = append(s.filesToZip, path)
1090
1091 s.copies[dest] = src.String()
1092 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001093}
1094
Paul Duffin91547182019-11-12 19:39:36 +00001095func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1096 ctx := s.ctx
1097
1098 // Repackage the zip file so that the entries are in the destDir directory.
1099 // This will allow the zip file to be merged into the snapshot.
1100 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001101
1102 ctx.Build(pctx, android.BuildParams{
1103 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1104 Rule: repackageZip,
1105 Input: zipPath,
1106 Output: tmpZipPath,
1107 Args: map[string]string{
1108 "destdir": destDir,
1109 },
1110 })
Paul Duffin91547182019-11-12 19:39:36 +00001111
1112 // Add the repackaged zip file to the files to merge.
1113 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1114}
1115
Paul Duffin5c211452021-07-15 12:42:44 +01001116func (s *snapshotBuilder) EmptyFile() android.Path {
1117 if s.emptyFile == nil {
1118 ctx := s.ctx
1119 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1120 s.ctx.Build(pctx, android.BuildParams{
1121 Rule: android.Touch,
1122 Output: s.emptyFile,
1123 })
1124 }
1125
1126 return s.emptyFile
1127}
1128
Paul Duffin9d8d6092019-12-05 18:19:29 +00001129func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1130 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001131 if s.prebuiltModules[name] != nil {
1132 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1133 }
1134
1135 m := s.bpFile.newModule(moduleType)
1136 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001137
Paul Duffinbefa4b92020-03-04 14:22:45 +00001138 variant := member.Variants()[0]
1139
Paul Duffin13f02712020-03-06 12:30:43 +00001140 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001141 // An internal member is only referenced from the sdk snapshot which is in the
1142 // same package so can be marked as private.
1143 m.AddProperty("visibility", []string{"//visibility:private"})
1144 } else {
1145 // Extract visibility information from a member variant. All variants have the same
1146 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001147 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1148
1149 // Add any additional visibility rules needed for the prebuilts to reference each other.
1150 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1151 if err != nil {
1152 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1153 }
1154
1155 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001156 if len(visibility) != 0 {
1157 m.AddProperty("visibility", visibility)
1158 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001159 }
1160
Martin Stjernholm1e041092020-11-03 00:11:09 +00001161 // Where available copy apex_available properties from the member.
1162 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1163 apexAvailable := apexAware.ApexAvailable()
1164 if len(apexAvailable) == 0 {
1165 // //apex_available:platform is the default.
1166 apexAvailable = []string{android.AvailableToPlatform}
1167 }
1168
1169 // Add in any baseline apex available settings.
1170 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1171
1172 // Remove duplicates and sort.
1173 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1174 sort.Strings(apexAvailable)
1175
1176 m.AddProperty("apex_available", apexAvailable)
1177 }
1178
Paul Duffinb0bb3762021-05-06 16:48:05 +01001179 // The licenses are the same for all variants.
1180 mctx := s.ctx
1181 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1182 if len(licenseInfo.Licenses) > 0 {
1183 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1184 }
1185
Paul Duffin865171e2020-03-02 18:38:15 +00001186 deviceSupported := false
1187 hostSupported := false
1188
1189 for _, variant := range member.Variants() {
1190 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001191 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001192 hostSupported = true
1193 } else if osClass == android.Device {
1194 deviceSupported = true
1195 }
1196 }
1197
1198 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001199
1200 s.prebuiltModules[name] = m
1201 s.prebuiltOrder = append(s.prebuiltOrder, m)
1202 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001203}
1204
Paul Duffin865171e2020-03-02 18:38:15 +00001205func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001206 // If neither device or host is supported then this module does not support either so will not
1207 // recognize the properties.
1208 if !deviceSupported && !hostSupported {
1209 return
1210 }
1211
Paul Duffin865171e2020-03-02 18:38:15 +00001212 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001213 bpModule.AddProperty("device_supported", false)
1214 }
Paul Duffin865171e2020-03-02 18:38:15 +00001215 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001216 bpModule.AddProperty("host_supported", true)
1217 }
1218}
1219
Paul Duffin13f02712020-03-06 12:30:43 +00001220func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1221 if required {
1222 return requiredSdkMemberReferencePropertyTag
1223 } else {
1224 return optionalSdkMemberReferencePropertyTag
1225 }
1226}
1227
1228func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1229 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001230}
1231
Paul Duffin42cdd622022-05-24 20:10:05 +00001232// Get a name for sdk snapshot member. If the member is private then generate a snapshot specific
1233// name. As part of the processing this checks to make sure that any required members are part of
1234// the snapshot.
1235func (s *snapshotBuilder) snapshotSdkMemberName(name string, required bool) string {
1236 if _, ok := s.allMembersByName[name]; !ok {
Paul Duffin13f02712020-03-06 12:30:43 +00001237 if required {
Paul Duffin42cdd622022-05-24 20:10:05 +00001238 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", name)
Paul Duffin13f02712020-03-06 12:30:43 +00001239 }
Paul Duffin42cdd622022-05-24 20:10:05 +00001240 return name
Paul Duffin13f02712020-03-06 12:30:43 +00001241 }
1242
Paul Duffin42cdd622022-05-24 20:10:05 +00001243 if s.isInternalMember(name) {
1244 return s.ctx.ModuleName() + "_" + name
Paul Duffin72910952020-01-20 18:16:30 +00001245 } else {
Paul Duffin42cdd622022-05-24 20:10:05 +00001246 return name
Paul Duffin72910952020-01-20 18:16:30 +00001247 }
1248}
1249
Paul Duffin42cdd622022-05-24 20:10:05 +00001250func (s *snapshotBuilder) snapshotSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001251 var references []string = nil
1252 for _, m := range members {
Paul Duffina649ad52022-07-26 23:53:00 +00001253 if _, ok := s.excludedMembersByName[m]; ok {
1254 continue
1255 }
Paul Duffin42cdd622022-05-24 20:10:05 +00001256 references = append(references, s.snapshotSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001257 }
1258 return references
1259}
1260
Paul Duffin13f02712020-03-06 12:30:43 +00001261func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1262 _, ok := s.exportedMembersByName[memberName]
1263 return !ok
1264}
1265
Martin Stjernholm89238f42020-07-10 00:14:03 +01001266// Add the properties from the given SdkMemberProperties to the blueprint
1267// property set. This handles common properties in SdkMemberPropertiesBase and
1268// calls the member-specific AddToPropertySet for the rest.
1269func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1270 if memberProperties.Base().Compile_multilib != "" {
1271 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1272 }
1273
1274 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1275}
1276
Paul Duffin21827262021-04-24 12:16:36 +01001277// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1278type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001279 // The sdk variant that depends (possibly indirectly) on the member variant.
1280 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001281
1282 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001283 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001284
1285 // The variant that is added to the sdk.
1286 variant android.SdkAware
1287
Paul Duffin1a44a992022-05-06 09:38:02 +00001288 // The optional container of this member, i.e. the module that is depended upon by the sdk
1289 // (possibly transitively) and whose dependency on this module is why it was added to the sdk.
1290 // Is nil if this a direct dependency of the sdk.
1291 container android.SdkAware
1292
Paul Duffinb97b1572021-04-29 21:50:40 +01001293 // True if the member should be exported, i.e. accessible, from outside the sdk.
1294 export bool
1295
1296 // The names of additional component modules provided by the variant.
1297 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffina649ad52022-07-26 23:53:00 +00001298
1299 // The minimum API level on which this module is supported.
1300 minApiLevel android.ApiLevel
Paul Duffin1356d8c2020-02-25 19:26:33 +00001301}
1302
Paul Duffin13879572019-11-28 14:31:38 +00001303var _ android.SdkMember = (*sdkMember)(nil)
1304
Paul Duffin21827262021-04-24 12:16:36 +01001305// sdkMember groups all the variants of a specific member module together along with the name of the
1306// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001307type sdkMember struct {
1308 memberType android.SdkMemberType
1309 name string
1310 variants []android.SdkAware
1311}
1312
1313func (m *sdkMember) Name() string {
1314 return m.name
1315}
1316
1317func (m *sdkMember) Variants() []android.SdkAware {
1318 return m.variants
1319}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001320
Paul Duffin9c3760e2020-03-16 19:52:08 +00001321// Track usages of multilib variants.
1322type multilibUsage int
1323
1324const (
1325 multilibNone multilibUsage = 0
1326 multilib32 multilibUsage = 1
1327 multilib64 multilibUsage = 2
1328 multilibBoth = multilib32 | multilib64
1329)
1330
1331// Add the multilib that is used in the arch type.
1332func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1333 multilib := archType.Multilib
1334 switch multilib {
1335 case "":
1336 return m
1337 case "lib32":
1338 return m | multilib32
1339 case "lib64":
1340 return m | multilib64
1341 default:
1342 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1343 }
1344}
1345
1346func (m multilibUsage) String() string {
1347 switch m {
1348 case multilibNone:
1349 return ""
1350 case multilib32:
1351 return "32"
1352 case multilib64:
1353 return "64"
1354 case multilibBoth:
1355 return "both"
1356 default:
1357 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1358 m, multilibNone, multilib32, multilib64, multilibBoth))
1359 }
1360}
1361
Paul Duffin2bf43892022-05-13 13:12:19 +00001362// TODO(187910671): BEGIN - Remove once modules do not have an APEX and default variant.
1363// variantCoordinate contains the coordinates used to identify a variant of an SDK member.
1364type variantCoordinate struct {
1365 // osType identifies the OS target of a variant.
1366 osType android.OsType
1367 // archId identifies the architecture and whether it is for the native bridge.
1368 archId archId
1369 // image is the image variant name.
1370 image string
1371 // linkType is the link type name.
1372 linkType string
1373}
1374
1375func getVariantCoordinate(ctx *memberContext, variant android.Module) variantCoordinate {
1376 linkType := ""
1377 if len(ctx.MemberType().SupportedLinkages()) > 0 {
1378 linkType = getLinkType(variant)
1379 }
1380 return variantCoordinate{
1381 osType: variant.Target().Os,
1382 archId: archIdFromTarget(variant.Target()),
1383 image: variant.ImageVariation().Variation,
1384 linkType: linkType,
1385 }
1386}
1387
1388// selectApexVariantsWhereAvailable filters the input list of variants by selecting the APEX
1389// specific variant for a specific variantCoordinate when there is both an APEX and default variant.
1390//
1391// There is a long-standing issue where a module that is added to an APEX has both an APEX and
1392// default/platform variant created even when the module does not require a platform variant. As a
1393// result an indirect dependency onto a module via the APEX will use the APEX variant, whereas a
1394// direct dependency onto the module will use the default/platform variant. That would result in a
1395// failure while attempting to optimize the properties for a member as it would have two variants
1396// when only one was expected.
1397//
1398// This function mitigates that problem by detecting when there are two variants that differ only
1399// by apex variant, where one is the default/platform variant and one is the APEX variant. In that
1400// case it picks the APEX variant. It picks the APEX variant because that is the behavior that would
1401// be expected
1402func selectApexVariantsWhereAvailable(ctx *memberContext, variants []android.SdkAware) []android.SdkAware {
1403 moduleCtx := ctx.sdkMemberContext
1404
1405 // Group the variants by coordinates.
1406 variantsByCoord := make(map[variantCoordinate][]android.SdkAware)
1407 for _, variant := range variants {
1408 coord := getVariantCoordinate(ctx, variant)
1409 variantsByCoord[coord] = append(variantsByCoord[coord], variant)
1410 }
1411
1412 toDiscard := make(map[android.SdkAware]struct{})
1413 for coord, list := range variantsByCoord {
1414 count := len(list)
1415 if count == 1 {
1416 continue
1417 }
1418
1419 variantsByApex := make(map[string]android.SdkAware)
1420 conflictDetected := false
1421 for _, variant := range list {
1422 apexInfo := moduleCtx.OtherModuleProvider(variant, android.ApexInfoProvider).(android.ApexInfo)
1423 apexVariationName := apexInfo.ApexVariationName
1424 // If there are two variants for a specific APEX variation then there is conflict.
1425 if _, ok := variantsByApex[apexVariationName]; ok {
1426 conflictDetected = true
1427 break
1428 }
1429 variantsByApex[apexVariationName] = variant
1430 }
1431
1432 // If there are more than 2 apex variations or one of the apex variations is not the
1433 // default/platform variation then there is a conflict.
1434 if len(variantsByApex) != 2 {
1435 conflictDetected = true
1436 } else if _, ok := variantsByApex[""]; !ok {
1437 conflictDetected = true
1438 }
1439
1440 // If there are no conflicts then add the default/platform variation to the list to remove.
1441 if !conflictDetected {
1442 toDiscard[variantsByApex[""]] = struct{}{}
1443 continue
1444 }
1445
1446 // There are duplicate variants at this coordinate and they are not the default and APEX variant
1447 // so fail.
1448 variantDescriptions := []string{}
1449 for _, m := range list {
1450 variantDescriptions = append(variantDescriptions, fmt.Sprintf(" %s", m.String()))
1451 }
1452
1453 moduleCtx.ModuleErrorf("multiple conflicting variants detected for OsType{%s}, %s, Image{%s}, Link{%s}\n%s",
1454 coord.osType, coord.archId.String(), coord.image, coord.linkType,
1455 strings.Join(variantDescriptions, "\n"))
1456 }
1457
1458 // If there are any variants to discard then remove them from the list of variants, while
1459 // preserving the order.
1460 if len(toDiscard) > 0 {
1461 filtered := []android.SdkAware{}
1462 for _, variant := range variants {
1463 if _, ok := toDiscard[variant]; !ok {
1464 filtered = append(filtered, variant)
1465 }
1466 }
1467 variants = filtered
1468 }
1469
1470 return variants
1471}
1472
1473// TODO(187910671): END - Remove once modules do not have an APEX and default variant.
1474
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001475type baseInfo struct {
1476 Properties android.SdkMemberProperties
1477}
1478
Paul Duffinf34f6d82020-04-30 15:48:31 +01001479func (b *baseInfo) optimizableProperties() interface{} {
1480 return b.Properties
1481}
1482
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001483type osTypeSpecificInfo struct {
1484 baseInfo
1485
Paul Duffin00e46802020-03-12 20:40:35 +00001486 osType android.OsType
1487
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001488 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001489 //
1490 // Nil if there is one variant whose arch type is common
1491 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001492}
1493
Paul Duffin4b8b7932020-05-06 12:35:38 +01001494var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1495
Paul Duffinfc8dd232020-03-17 12:51:37 +00001496type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1497
Paul Duffin00e46802020-03-12 20:40:35 +00001498// Create a new osTypeSpecificInfo for the specified os type and its properties
1499// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001500func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001501 osInfo := &osTypeSpecificInfo{
1502 osType: osType,
1503 }
1504
1505 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1506 properties := variantPropertiesFactory()
1507 properties.Base().Os = osType
1508 return properties
1509 }
1510
1511 // Create a structure into which properties common across the architectures in
1512 // this os type will be stored.
1513 osInfo.Properties = osSpecificVariantPropertiesFactory()
1514
1515 // Group the variants by arch type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001516 var variantsByArchId = make(map[archId][]android.Module)
1517 var archIds []archId
Paul Duffin00e46802020-03-12 20:40:35 +00001518 for _, variant := range osTypeVariants {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001519 target := variant.Target()
1520 id := archIdFromTarget(target)
1521 if _, ok := variantsByArchId[id]; !ok {
1522 archIds = append(archIds, id)
Paul Duffin00e46802020-03-12 20:40:35 +00001523 }
1524
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001525 variantsByArchId[id] = append(variantsByArchId[id], variant)
Paul Duffin00e46802020-03-12 20:40:35 +00001526 }
1527
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001528 if commonVariants, ok := variantsByArchId[commonArchId]; ok {
Paul Duffin00e46802020-03-12 20:40:35 +00001529 if len(osTypeVariants) != 1 {
Paul Duffin2bf43892022-05-13 13:12:19 +00001530 variants := []string{}
1531 for _, m := range osTypeVariants {
1532 variants = append(variants, fmt.Sprintf(" %s", m.String()))
1533 }
1534 panic(fmt.Errorf("expected to only have 1 variant of %q when arch type is common but found %d\n%s",
1535 ctx.Name(),
1536 len(osTypeVariants),
1537 strings.Join(variants, "\n")))
Paul Duffin00e46802020-03-12 20:40:35 +00001538 }
1539
1540 // A common arch type only has one variant and its properties should be treated
1541 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001542 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001543 } else {
1544 // Create an arch specific info for each supported architecture type.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001545 for _, id := range archIds {
1546 archVariants := variantsByArchId[id]
1547 archInfo := newArchSpecificInfo(ctx, id, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001548
1549 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1550 }
1551 }
1552
1553 return osInfo
1554}
1555
Paul Duffin39abf8f2021-09-24 14:58:27 +01001556func (osInfo *osTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1557 if len(osInfo.archInfos) == 0 {
1558 pruner.pruneProperties(osInfo.Properties)
1559 } else {
1560 for _, archInfo := range osInfo.archInfos {
1561 archInfo.pruneUnsupportedProperties(pruner)
1562 }
1563 }
1564}
1565
Paul Duffin00e46802020-03-12 20:40:35 +00001566// Optimize the properties by extracting common properties from arch type specific
1567// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001568func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001569 // Nothing to do if there is only a single common architecture.
1570 if len(osInfo.archInfos) == 0 {
1571 return
1572 }
1573
Paul Duffin9c3760e2020-03-16 19:52:08 +00001574 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001575 for _, archInfo := range osInfo.archInfos {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001576 multilib = multilib.addArchType(archInfo.archId.archType)
Paul Duffin9c3760e2020-03-16 19:52:08 +00001577
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001578 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001579 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001580 }
1581
Paul Duffin4b8b7932020-05-06 12:35:38 +01001582 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001583
1584 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001585 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001586}
1587
1588// Add the properties for an os to a property set.
1589//
1590// Maps the properties related to the os variants through to an appropriate
1591// module structure that will produce equivalent set of variants when it is
1592// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001593func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001594
1595 var osPropertySet android.BpPropertySet
1596 var archPropertySet android.BpPropertySet
1597 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001598 if osInfo.Properties.Base().Os_count == 1 &&
1599 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1600 // There is only one OS type present in the variants and it shouldn't have a
1601 // variant-specific target. The latter is the case if it's either for device
1602 // where there is only one OS (android), or for host and the member type
1603 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001604
1605 // Create a structure that looks like:
1606 // module_type {
1607 // name: "...",
1608 // ...
1609 // <common properties>
1610 // ...
1611 // <single os type specific properties>
1612 //
1613 // arch: {
1614 // <arch specific sections>
1615 // }
1616 //
1617 osPropertySet = bpModule
1618 archPropertySet = osPropertySet.AddPropertySet("arch")
1619
1620 // Arch specific properties need to be added to an arch specific section
1621 // within arch.
1622 archOsPrefix = ""
1623 } else {
1624 // Create a structure that looks like:
1625 // module_type {
1626 // name: "...",
1627 // ...
1628 // <common properties>
1629 // ...
1630 // target: {
1631 // <arch independent os specific sections, e.g. android>
1632 // ...
1633 // <arch and os specific sections, e.g. android_x86>
1634 // }
1635 //
1636 osType := osInfo.osType
1637 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1638 archPropertySet = targetPropertySet
1639
1640 // Arch specific properties need to be added to an os and arch specific
1641 // section prefixed with <os>_.
1642 archOsPrefix = osType.Name + "_"
1643 }
1644
1645 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001646 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001647
1648 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1649 // os) specific properties.
1650 //
1651 // The archInfos list will be empty if the os contains variants for the common
1652 // architecture.
1653 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001654 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001655 }
1656}
1657
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001658func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1659 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001660 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001661}
1662
1663var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1664
Paul Duffin4b8b7932020-05-06 12:35:38 +01001665func (osInfo *osTypeSpecificInfo) String() string {
1666 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1667}
1668
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001669// archId encapsulates the information needed to identify a combination of arch type and native
1670// bridge support.
1671//
1672// Conceptually, native bridge support is a facet of an android.Target, not an android.Arch as it is
1673// essentially using one android.Arch to implement another. However, in terms of the handling of
1674// the variants native bridge is treated as part of the arch variation. See the ArchVariation method
1675// on android.Target.
1676//
1677// So, it makes sense when optimizing the variants to combine native bridge with the arch type.
1678type archId struct {
1679 // The arch type of the variant's target.
1680 archType android.ArchType
1681
1682 // True if the variants is for the native bridge, false otherwise.
1683 nativeBridge bool
1684}
1685
1686// propertyName returns the name of the property corresponding to use for this arch id.
1687func (i *archId) propertyName() string {
1688 name := i.archType.Name
1689 if i.nativeBridge {
1690 // Note: This does not result in a valid property because there is no architecture specific
1691 // native bridge property, only a generic "native_bridge" property. However, this will be used
1692 // in error messages if there is an attempt to use this in a generated bp file.
1693 name += "_native_bridge"
1694 }
1695 return name
1696}
1697
1698func (i *archId) String() string {
1699 return fmt.Sprintf("ArchType{%s}, NativeBridge{%t}", i.archType, i.nativeBridge)
1700}
1701
1702// archIdFromTarget returns an archId initialized from information in the supplied target.
1703func archIdFromTarget(target android.Target) archId {
1704 return archId{
1705 archType: target.Arch.ArchType,
1706 nativeBridge: target.NativeBridge == android.NativeBridgeEnabled,
1707 }
1708}
1709
1710// commonArchId is the archId for the common architecture.
1711var commonArchId = archId{archType: android.Common}
1712
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001713type archTypeSpecificInfo struct {
1714 baseInfo
1715
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001716 archId archId
1717 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001718
Paul Duffinb42fa672021-09-09 16:37:49 +01001719 imageVariantInfos []*imageVariantSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001720}
1721
Paul Duffin4b8b7932020-05-06 12:35:38 +01001722var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1723
Paul Duffinfc8dd232020-03-17 12:51:37 +00001724// Create a new archTypeSpecificInfo for the specified arch type and its properties
1725// structures populated with information from the variants.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001726func newArchSpecificInfo(ctx android.SdkMemberContext, archId archId, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001727
Paul Duffinfc8dd232020-03-17 12:51:37 +00001728 // Create an arch specific info into which the variant properties can be copied.
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001729 archInfo := &archTypeSpecificInfo{archId: archId, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001730
1731 // Create the properties into which the arch type specific properties will be
1732 // added.
1733 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001734
Liz Kammer7b710832022-05-12 20:40:00 -04001735 // if there are multiple supported link variants, we want to nest based on linkage even if there
1736 // is only one variant, otherwise, if there is only one variant we can populate based on the arch
1737 if len(archVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001738 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001739 } else {
Paul Duffinb42fa672021-09-09 16:37:49 +01001740 // Group the variants by image type.
1741 variantsByImage := make(map[string][]android.Module)
1742 for _, variant := range archVariants {
1743 image := variant.ImageVariation().Variation
1744 variantsByImage[image] = append(variantsByImage[image], variant)
1745 }
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001746
Paul Duffinb42fa672021-09-09 16:37:49 +01001747 // Create the image variant info in a fixed order.
1748 for _, imageVariantName := range android.SortedStringKeys(variantsByImage) {
1749 variants := variantsByImage[imageVariantName]
1750 archInfo.imageVariantInfos = append(archInfo.imageVariantInfos, newImageVariantSpecificInfo(ctx, imageVariantName, variantPropertiesFactory, variants))
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001751 }
1752 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001753
1754 return archInfo
1755}
1756
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001757// Get the link type of the variant
1758//
1759// If the variant is not differentiated by link type then it returns "",
1760// otherwise it returns one of "static" or "shared".
1761func getLinkType(variant android.Module) string {
1762 linkType := ""
1763 if linkable, ok := variant.(cc.LinkableInterface); ok {
1764 if linkable.Shared() && linkable.Static() {
1765 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1766 } else if linkable.Shared() {
1767 linkType = "shared"
1768 } else if linkable.Static() {
1769 linkType = "static"
1770 } else {
1771 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1772 }
1773 }
1774 return linkType
1775}
1776
Paul Duffin39abf8f2021-09-24 14:58:27 +01001777func (archInfo *archTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1778 if len(archInfo.imageVariantInfos) == 0 {
1779 pruner.pruneProperties(archInfo.Properties)
1780 } else {
1781 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1782 imageVariantInfo.pruneUnsupportedProperties(pruner)
1783 }
1784 }
1785}
1786
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001787// Optimize the properties by extracting common properties from link type specific
1788// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001789func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffinb42fa672021-09-09 16:37:49 +01001790 if len(archInfo.imageVariantInfos) == 0 {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001791 return
1792 }
1793
Paul Duffinb42fa672021-09-09 16:37:49 +01001794 // Optimize the image variant properties first.
1795 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1796 imageVariantInfo.optimizeProperties(ctx, commonValueExtractor)
1797 }
1798
1799 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.imageVariantInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001800}
1801
Paul Duffinfc8dd232020-03-17 12:51:37 +00001802// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001803func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001804 archPropertySuffix := archInfo.archId.propertyName()
1805 propertySetName := archOsPrefix + archPropertySuffix
1806 archTypePropertySet := archPropertySet.AddPropertySet(propertySetName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001807 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1808 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1809 archTypePropertySet.AddProperty("enabled", true)
1810 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001811 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001812
Paul Duffinb42fa672021-09-09 16:37:49 +01001813 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1814 imageVariantInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001815 }
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001816
1817 // If this is for a native bridge architecture then make sure that the property set does not
1818 // contain any properties as providing native bridge specific properties is not currently
1819 // supported.
1820 if archInfo.archId.nativeBridge {
1821 propertySetContents := getPropertySetContents(archTypePropertySet)
1822 if propertySetContents != "" {
1823 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",
1824 propertySetName, ctx.name, propertySetContents)
1825 }
1826 }
1827}
1828
1829// getPropertySetContents returns the string representation of the contents of a property set, after
1830// recursively pruning any empty nested property sets.
1831func getPropertySetContents(propertySet android.BpPropertySet) string {
1832 set := propertySet.(*bpPropertySet)
1833 set.transformContents(pruneEmptySetTransformer{})
1834 if len(set.properties) != 0 {
1835 contents := &generatedContents{}
1836 contents.Indent()
1837 outputPropertySet(contents, set)
1838 setAsString := contents.content.String()
1839 return setAsString
1840 }
1841 return ""
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001842}
1843
Paul Duffin4b8b7932020-05-06 12:35:38 +01001844func (archInfo *archTypeSpecificInfo) String() string {
Paul Duffinfefdb0b2021-09-09 18:50:49 +01001845 return archInfo.archId.String()
Paul Duffin4b8b7932020-05-06 12:35:38 +01001846}
1847
Paul Duffinb42fa672021-09-09 16:37:49 +01001848type imageVariantSpecificInfo struct {
1849 baseInfo
1850
1851 imageVariant string
1852
1853 linkInfos []*linkTypeSpecificInfo
1854}
1855
1856func newImageVariantSpecificInfo(ctx android.SdkMemberContext, imageVariant string, variantPropertiesFactory variantPropertiesFactoryFunc, imageVariants []android.Module) *imageVariantSpecificInfo {
1857
1858 // Create an image variant specific info into which the variant properties can be copied.
1859 imageInfo := &imageVariantSpecificInfo{imageVariant: imageVariant}
1860
1861 // Create the properties into which the image variant specific properties will be added.
1862 imageInfo.Properties = variantPropertiesFactory()
1863
Liz Kammer7b710832022-05-12 20:40:00 -04001864 // if there are multiple supported link variants, we want to nest even if there is only one
1865 // variant, otherwise, if there is only one variant we can populate based on the image
1866 if len(imageVariants) == 1 && len(ctx.MemberType().SupportedLinkages()) <= 1 {
Paul Duffinb42fa672021-09-09 16:37:49 +01001867 imageInfo.Properties.PopulateFromVariant(ctx, imageVariants[0])
1868 } else {
1869 // There is more than one variant for this image variant which must be differentiated by link
Liz Kammer7b710832022-05-12 20:40:00 -04001870 // type. Or there are multiple supported linkages and we need to nest based on link type.
Paul Duffinb42fa672021-09-09 16:37:49 +01001871 for _, linkVariant := range imageVariants {
1872 linkType := getLinkType(linkVariant)
1873 if linkType == "" {
1874 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(imageVariants)))
1875 } else {
1876 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
1877
1878 imageInfo.linkInfos = append(imageInfo.linkInfos, linkInfo)
1879 }
1880 }
1881 }
1882
1883 return imageInfo
1884}
1885
Paul Duffin39abf8f2021-09-24 14:58:27 +01001886func (imageInfo *imageVariantSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1887 if len(imageInfo.linkInfos) == 0 {
1888 pruner.pruneProperties(imageInfo.Properties)
1889 } else {
1890 for _, linkInfo := range imageInfo.linkInfos {
1891 linkInfo.pruneUnsupportedProperties(pruner)
1892 }
1893 }
1894}
1895
Paul Duffinb42fa672021-09-09 16:37:49 +01001896// Optimize the properties by extracting common properties from link type specific
1897// properties into arch type specific properties.
1898func (imageInfo *imageVariantSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
1899 if len(imageInfo.linkInfos) == 0 {
1900 return
1901 }
1902
1903 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, imageInfo.Properties, imageInfo.linkInfos)
1904}
1905
1906// Add the properties for an arch type to a property set.
1907func (imageInfo *imageVariantSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1908 if imageInfo.imageVariant != android.CoreVariation {
1909 propertySet = propertySet.AddPropertySet(imageInfo.imageVariant)
1910 }
1911
1912 addSdkMemberPropertiesToSet(ctx, imageInfo.Properties, propertySet)
1913
Liz Kammer7b710832022-05-12 20:40:00 -04001914 usedLinkages := make(map[string]bool, len(imageInfo.linkInfos))
Paul Duffinb42fa672021-09-09 16:37:49 +01001915 for _, linkInfo := range imageInfo.linkInfos {
Liz Kammer7b710832022-05-12 20:40:00 -04001916 usedLinkages[linkInfo.linkType] = true
Paul Duffinb42fa672021-09-09 16:37:49 +01001917 linkInfo.addToPropertySet(ctx, propertySet)
1918 }
1919
Liz Kammer7b710832022-05-12 20:40:00 -04001920 // If not all supported linkages had existing variants, we need to disable the unsupported variant
1921 if len(imageInfo.linkInfos) < len(ctx.MemberType().SupportedLinkages()) {
1922 for _, l := range ctx.MemberType().SupportedLinkages() {
1923 if _, ok := usedLinkages[l]; !ok {
1924 otherLinkagePropertySet := propertySet.AddPropertySet(l)
1925 otherLinkagePropertySet.AddProperty("enabled", false)
1926 }
1927 }
1928 }
1929
Paul Duffinb42fa672021-09-09 16:37:49 +01001930 // If this is for a non-core image variant then make sure that the property set does not contain
1931 // any properties as providing non-core image variant specific properties for prebuilts is not
1932 // currently supported.
1933 if imageInfo.imageVariant != android.CoreVariation {
1934 propertySetContents := getPropertySetContents(propertySet)
1935 if propertySetContents != "" {
1936 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",
1937 imageInfo.imageVariant, ctx.name, propertySetContents)
1938 }
1939 }
1940}
1941
1942func (imageInfo *imageVariantSpecificInfo) String() string {
1943 return imageInfo.imageVariant
1944}
1945
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001946type linkTypeSpecificInfo struct {
1947 baseInfo
1948
1949 linkType string
1950}
1951
Paul Duffin4b8b7932020-05-06 12:35:38 +01001952var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1953
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001954// Create a new linkTypeSpecificInfo for the specified link type and its properties
1955// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001956func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001957 linkInfo := &linkTypeSpecificInfo{
1958 baseInfo: baseInfo{
1959 // Create the properties into which the link type specific properties will be
1960 // added.
1961 Properties: variantPropertiesFactory(),
1962 },
1963 linkType: linkType,
1964 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001965 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001966 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001967}
1968
Paul Duffinf68f85a2021-09-09 16:11:42 +01001969func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1970 linkPropertySet := propertySet.AddPropertySet(l.linkType)
1971 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
1972}
1973
Paul Duffin39abf8f2021-09-24 14:58:27 +01001974func (l *linkTypeSpecificInfo) pruneUnsupportedProperties(pruner *propertyPruner) {
1975 pruner.pruneProperties(l.Properties)
1976}
1977
Paul Duffin4b8b7932020-05-06 12:35:38 +01001978func (l *linkTypeSpecificInfo) String() string {
1979 return fmt.Sprintf("LinkType{%s}", l.linkType)
1980}
1981
Paul Duffin3a4eb502020-03-19 16:11:18 +00001982type memberContext struct {
1983 sdkMemberContext android.ModuleContext
1984 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001985 memberType android.SdkMemberType
1986 name string
Paul Duffind19f8942021-07-14 12:08:37 +01001987
1988 // The set of traits required of this member.
1989 requiredTraits android.SdkMemberTraitSet
Paul Duffin3a4eb502020-03-19 16:11:18 +00001990}
1991
1992func (m *memberContext) SdkModuleContext() android.ModuleContext {
1993 return m.sdkMemberContext
1994}
1995
1996func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1997 return m.builder
1998}
1999
Paul Duffina551a1c2020-03-17 21:04:24 +00002000func (m *memberContext) MemberType() android.SdkMemberType {
2001 return m.memberType
2002}
2003
2004func (m *memberContext) Name() string {
2005 return m.name
2006}
2007
Paul Duffind19f8942021-07-14 12:08:37 +01002008func (m *memberContext) RequiresTrait(trait android.SdkMemberTrait) bool {
2009 return m.requiredTraits.Contains(trait)
2010}
2011
Paul Duffinbe750592022-07-15 13:12:35 +00002012func (m *memberContext) IsTargetBuildBeforeTiramisu() bool {
2013 return m.builder.targetBuildRelease.EarlierThan(buildReleaseT)
2014}
2015
2016var _ android.SdkMemberContext = (*memberContext)(nil)
2017
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01002018func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002019
2020 memberType := member.memberType
2021
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002022 // Do not add the prefer property if the member snapshot module is a source module type.
Paul Duffin2bf43892022-05-13 13:12:19 +00002023 moduleCtx := ctx.sdkMemberContext
2024 config := moduleCtx.Config()
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002025 if !memberType.UsesSourceModuleTypeInSnapshot() {
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +00002026 // Set the prefer based on the environment variable. This is a temporary work around to allow a
2027 // snapshot to be created that sets prefer: true.
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002028 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
2029 // dynamically at build time not at snapshot generation time.
Paul Duffinfb9a7f92021-07-06 17:18:42 +01002030 prefer := config.IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01002031
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002032 // Set prefer. Setting this to false is not strictly required as that is the default but it does
2033 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
2034 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
2035 // behavior is for the module.
2036 bpModule.insertAfter("name", "prefer", prefer)
Paul Duffinfb9a7f92021-07-06 17:18:42 +01002037
2038 configVar := config.Getenv("SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR")
2039 if configVar != "" {
2040 parts := strings.Split(configVar, ":")
2041 cfp := android.ConfigVarProperties{
2042 Config_namespace: proptools.StringPtr(parts[0]),
2043 Var_name: proptools.StringPtr(parts[1]),
2044 }
2045 bpModule.insertAfter("prefer", "use_source_config_var", cfp)
2046 }
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01002047 }
Paul Duffin83ad9562021-05-10 23:49:04 +01002048
Paul Duffin2bf43892022-05-13 13:12:19 +00002049 variants := selectApexVariantsWhereAvailable(ctx, member.variants)
2050
Paul Duffina04c1072020-03-02 10:16:35 +00002051 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00002052 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002053 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00002054 osType := variant.Target().Os
2055 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002056 }
2057
Paul Duffina04c1072020-03-02 10:16:35 +00002058 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00002059 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00002060 properties := memberType.CreateVariantPropertiesStruct()
2061 base := properties.Base()
2062 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00002063 return properties
2064 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002065
Paul Duffina04c1072020-03-02 10:16:35 +00002066 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00002067
Paul Duffina04c1072020-03-02 10:16:35 +00002068 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00002069 commonProperties := variantPropertiesFactory()
2070 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00002071
Paul Duffin39abf8f2021-09-24 14:58:27 +01002072 // Create a property pruner that will prune any properties unsupported by the target build
2073 // release.
2074 targetBuildRelease := ctx.builder.targetBuildRelease
2075 unsupportedPropertyPruner := newPropertyPrunerByBuildRelease(commonProperties, targetBuildRelease)
2076
Paul Duffinc097e362020-03-10 22:50:03 +00002077 // Create common value extractor that can be used to optimize the properties.
2078 commonValueExtractor := newCommonValueExtractor(commonProperties)
2079
Paul Duffina04c1072020-03-02 10:16:35 +00002080 // The list of property structures which are os type specific but common across
2081 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002082 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00002083
2084 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00002085 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00002086 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00002087 // Add the os specific properties to a list of os type specific yet architecture
2088 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002089 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00002090
Paul Duffin39abf8f2021-09-24 14:58:27 +01002091 osInfo.pruneUnsupportedProperties(unsupportedPropertyPruner)
2092
Paul Duffin00e46802020-03-12 20:40:35 +00002093 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002094 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00002095 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002096
Paul Duffina04c1072020-03-02 10:16:35 +00002097 // Extract properties which are common across all architectures and os types.
Paul Duffin2bf43892022-05-13 13:12:19 +00002098 extractCommonProperties(moduleCtx, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002099
Paul Duffina04c1072020-03-02 10:16:35 +00002100 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01002101 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002102
Paul Duffina04c1072020-03-02 10:16:35 +00002103 // Create a target property set into which target specific properties can be
2104 // added.
2105 targetPropertySet := bpModule.AddPropertySet("target")
2106
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01002107 // If the member is host OS dependent and has host_supported then disable by
2108 // default and enable each host OS variant explicitly. This avoids problems
2109 // with implicitly enabled OS variants when the snapshot is used, which might
2110 // be different from this run (e.g. different build OS).
2111 if ctx.memberType.IsHostOsDependent() {
2112 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
2113 if hostSupported {
2114 hostPropertySet := targetPropertySet.AddPropertySet("host")
2115 hostPropertySet.AddProperty("enabled", false)
2116 }
2117 }
2118
Paul Duffina04c1072020-03-02 10:16:35 +00002119 // Iterate over the os types in a fixed order.
2120 for _, osType := range s.getPossibleOsTypes() {
2121 osInfo := osTypeToInfo[osType]
2122 if osInfo == nil {
2123 continue
2124 }
2125
Paul Duffin3a4eb502020-03-19 16:11:18 +00002126 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002127 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002128}
2129
Paul Duffina04c1072020-03-02 10:16:35 +00002130// Compute the list of possible os types that this sdk could support.
2131func (s *sdk) getPossibleOsTypes() []android.OsType {
2132 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00002133 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00002134 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07002135 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00002136 osTypes = append(osTypes, osType)
2137 }
2138 }
2139 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09002140 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00002141 osTypes = append(osTypes, osType)
2142 }
2143 }
2144 }
2145 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
2146 return osTypes
2147}
2148
Paul Duffinb28369a2020-05-04 15:39:59 +01002149// Given a set of properties (struct value), return the value of the field within that
2150// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00002151type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
2152
Paul Duffinc459f892020-04-30 18:08:29 +01002153// Checks the metadata to determine whether the property should be ignored for the
2154// purposes of common value extraction or not.
2155type extractorMetadataPredicate func(metadata propertiesContainer) bool
2156
2157// Indicates whether optimizable properties are provided by a host variant or
2158// not.
2159type isHostVariant interface {
2160 isHostVariant() bool
2161}
2162
Paul Duffinb28369a2020-05-04 15:39:59 +01002163// A property that can be optimized by the commonValueExtractor.
2164type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01002165 // The name of the field for this property. It is a "."-separated path for
2166 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002167 name string
2168
Paul Duffinc459f892020-04-30 18:08:29 +01002169 // Filter that can use metadata associated with the properties being optimized
2170 // to determine whether the field should be ignored during common value
2171 // optimization.
2172 filter extractorMetadataPredicate
2173
Paul Duffinb28369a2020-05-04 15:39:59 +01002174 // Retrieves the value on which common value optimization will be performed.
2175 getter fieldAccessorFunc
2176
2177 // The empty value for the field.
2178 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01002179
2180 // True if the property can support arch variants false otherwise.
2181 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01002182}
2183
Paul Duffin4b8b7932020-05-06 12:35:38 +01002184func (p extractorProperty) String() string {
2185 return p.name
2186}
2187
Paul Duffinc097e362020-03-10 22:50:03 +00002188// Supports extracting common values from a number of instances of a properties
2189// structure into a separate common set of properties.
2190type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01002191 // The properties that the extractor can optimize.
2192 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00002193}
2194
2195// Create a new common value extractor for the structure type for the supplied
2196// properties struct.
2197//
2198// The returned extractor can be used on any properties structure of the same type
2199// as the supplied set of properties.
2200func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
2201 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
2202 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01002203 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00002204 return extractor
2205}
2206
2207// Gather the fields from the supplied structure type from which common values will
2208// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00002209//
Martin Stjernholmb0249572020-09-15 02:32:35 +01002210// This is recursive function. If it encounters a struct then it will recurse
2211// into it, passing in the accessor for the field and the struct name as prefix
2212// for the nested fields. That will then be used in the accessors for the fields
2213// in the embedded struct.
2214func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00002215 for f := 0; f < structType.NumField(); f++ {
2216 field := structType.Field(f)
2217 if field.PkgPath != "" {
2218 // Ignore unexported fields.
2219 continue
2220 }
2221
Paul Duffinb07fa512020-03-10 22:17:04 +00002222 // Ignore fields whose value should be kept.
2223 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00002224 continue
2225 }
2226
Paul Duffinc459f892020-04-30 18:08:29 +01002227 var filter extractorMetadataPredicate
2228
2229 // Add a filter
2230 if proptools.HasTag(field, "sdk", "ignored-on-host") {
2231 filter = func(metadata propertiesContainer) bool {
2232 if m, ok := metadata.(isHostVariant); ok {
2233 if m.isHostVariant() {
2234 return false
2235 }
2236 }
2237 return true
2238 }
2239 }
2240
Paul Duffinc097e362020-03-10 22:50:03 +00002241 // Save a copy of the field index for use in the function.
2242 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01002243
Martin Stjernholmb0249572020-09-15 02:32:35 +01002244 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01002245
Paul Duffinc097e362020-03-10 22:50:03 +00002246 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00002247 if containingStructAccessor != nil {
2248 // This is an embedded structure so first access the field for the embedded
2249 // structure.
2250 value = containingStructAccessor(value)
2251 }
2252
Paul Duffinc097e362020-03-10 22:50:03 +00002253 // Skip through interface and pointer values to find the structure.
2254 value = getStructValue(value)
2255
Paul Duffin4b8b7932020-05-06 12:35:38 +01002256 defer func() {
2257 if r := recover(); r != nil {
2258 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
2259 }
2260 }()
2261
Paul Duffinc097e362020-03-10 22:50:03 +00002262 // Return the field.
2263 return value.Field(fieldIndex)
2264 }
2265
Martin Stjernholmb0249572020-09-15 02:32:35 +01002266 if field.Type.Kind() == reflect.Struct {
2267 // Gather fields from the nested or embedded structure.
2268 var subNamePrefix string
2269 if field.Anonymous {
2270 subNamePrefix = namePrefix
2271 } else {
2272 subNamePrefix = name + "."
2273 }
2274 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00002275 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01002276 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01002277 name,
Paul Duffinc459f892020-04-30 18:08:29 +01002278 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01002279 fieldGetter,
2280 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01002281 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01002282 }
2283 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00002284 }
Paul Duffinc097e362020-03-10 22:50:03 +00002285 }
2286}
2287
2288func getStructValue(value reflect.Value) reflect.Value {
2289foundStruct:
2290 for {
2291 kind := value.Kind()
2292 switch kind {
2293 case reflect.Interface, reflect.Ptr:
2294 value = value.Elem()
2295 case reflect.Struct:
2296 break foundStruct
2297 default:
2298 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
2299 }
2300 }
2301 return value
2302}
2303
Paul Duffinf34f6d82020-04-30 15:48:31 +01002304// A container of properties to be optimized.
2305//
2306// Allows additional information to be associated with the properties, e.g. for
2307// filtering.
2308type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002309 fmt.Stringer
2310
Paul Duffinf34f6d82020-04-30 15:48:31 +01002311 // Get the properties that need optimizing.
2312 optimizableProperties() interface{}
2313}
2314
Paul Duffin2d1bb892021-04-24 11:32:59 +01002315// A wrapper for sdk variant related properties to allow them to be optimized.
2316type sdkVariantPropertiesContainer struct {
2317 sdkVariant *sdk
2318 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01002319}
2320
Paul Duffin2d1bb892021-04-24 11:32:59 +01002321func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
2322 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01002323}
2324
Paul Duffin2d1bb892021-04-24 11:32:59 +01002325func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01002326 return c.sdkVariant.String()
2327}
2328
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002329// Extract common properties from a slice of property structures of the same type.
2330//
2331// All the property structures must be of the same type.
2332// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01002333// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002334//
2335// Iterates over each exported field (capitalized name) and checks to see whether they
2336// have the same value (using DeepEquals) across all the input properties. If it does not then no
2337// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01002338// and the field in each of the input properties structure is set to its default value. Nested
2339// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002340func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002341 commonPropertiesValue := reflect.ValueOf(commonProperties)
2342 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002343
Paul Duffinf34f6d82020-04-30 15:48:31 +01002344 sliceValue := reflect.ValueOf(inputPropertiesSlice)
2345
Paul Duffinb28369a2020-05-04 15:39:59 +01002346 for _, property := range e.properties {
2347 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01002348 filter := property.filter
2349 if filter == nil {
2350 filter = func(metadata propertiesContainer) bool {
2351 return true
2352 }
2353 }
Paul Duffinb28369a2020-05-04 15:39:59 +01002354
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002355 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002356 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2357 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002358 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002359
Paul Duffin864e1b42020-05-06 10:23:19 +01002360 // Assume that all the values will be the same.
2361 //
2362 // While similar to this is not quite the same as commonValue == nil. If all the values
2363 // have been filtered out then this will be false but commonValue == nil will be true.
2364 valuesDiffer := false
2365
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002366 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002367 container := sliceValue.Index(i).Interface().(propertiesContainer)
2368 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002369 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002370
Paul Duffinc459f892020-04-30 18:08:29 +01002371 if !filter(container) {
2372 expectedValue := property.emptyValue.Interface()
2373 actualValue := fieldValue.Interface()
2374 if !reflect.DeepEqual(expectedValue, actualValue) {
2375 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2376 }
2377 continue
2378 }
2379
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002380 if commonValue == nil {
2381 // Use the first value as the commonProperties value.
2382 commonValue = &fieldValue
2383 } else {
2384 // If the value does not match the current common value then there is
2385 // no value in common so break out.
2386 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2387 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002388 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002389 break
2390 }
2391 }
2392 }
2393
Paul Duffin864e1b42020-05-06 10:23:19 +01002394 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002395 // and set the input struct's field to the empty value.
2396 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002397 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002398 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002399 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002400 container := sliceValue.Index(i).Interface().(propertiesContainer)
2401 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002402 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002403 fieldValue.Set(emptyValue)
2404 }
2405 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002406
2407 if valuesDiffer && !property.archVariant {
2408 // The values differ but the property does not support arch variants so it
2409 // is an error.
2410 var details strings.Builder
2411 for i := 0; i < sliceValue.Len(); i++ {
2412 container := sliceValue.Index(i).Interface().(propertiesContainer)
2413 itemValue := reflect.ValueOf(container.optimizableProperties())
2414 fieldValue := fieldGetter(itemValue)
2415
2416 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2417 }
2418
2419 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2420 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002421 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002422
2423 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002424}