blob: 2ab45d7c15b79093fee1418b9e686a384340f750 [file] [log] [blame]
Jiyong Park9b409bc2019-10-11 14:59:13 +09001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package sdk
16
17import (
18 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000019 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000020 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090021 "strings"
22
Paul Duffin7d74e7b2020-03-06 12:30:13 +000023 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000024 "android/soong/cc"
Paul Duffin375058f2019-11-29 20:17:53 +000025 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090026 "github.com/google/blueprint/proptools"
27
28 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090029)
30
Paul Duffin64fb5262021-05-05 21:36:04 +010031// Environment variables that affect the generated snapshot
32// ========================================================
33//
34// SOONG_SDK_SNAPSHOT_PREFER
Mathew Inwoodd0b99ce2021-05-20 11:00:12 +010035// By default every unversioned module in the generated snapshot has prefer set by the
36// sdk.prebuilts_prefer property. Building it with SOONG_SDK_SNAPSHOT_PREFER=true will force
37// them to use prefer: true.
Paul Duffin64fb5262021-05-05 21:36:04 +010038//
Paul Duffin43f7bf02021-05-05 22:00:51 +010039// SOONG_SDK_SNAPSHOT_VERSION
40// This provides control over the version of the generated snapshot.
41//
42// SOONG_SDK_SNAPSHOT_VERSION=current will generate unversioned and versioned prebuilts and a
43// versioned snapshot module. This is the default behavior. The zip file containing the
44// generated snapshot will be <sdk-name>-current.zip.
45//
46// SOONG_SDK_SNAPSHOT_VERSION=unversioned will generate unversioned prebuilts only and the zip
47// file containing the generated snapshot will be <sdk-name>.zip.
48//
49// SOONG_SDK_SNAPSHOT_VERSION=<number> will generate versioned prebuilts and a versioned
50// snapshot module only. The zip file containing the generated snapshot will be
51// <sdk-name>-<number>.zip.
52//
Paul Duffin64fb5262021-05-05 21:36:04 +010053
Jiyong Park9b409bc2019-10-11 14:59:13 +090054var pctx = android.NewPackageContext("android/soong/sdk")
55
Paul Duffin375058f2019-11-29 20:17:53 +000056var (
57 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
58 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000059 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000060 CommandDeps: []string{
61 "${config.Zip2ZipCmd}",
62 },
63 },
64 "destdir")
65
66 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
67 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -070068 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +000069 CommandDeps: []string{
70 "${config.SoongZipCmd}",
71 },
72 Rspfile: "$out.rsp",
73 RspfileContent: "$in",
74 },
75 "basedir")
76
77 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
78 blueprint.RuleParams{
79 Command: `${config.MergeZipsCmd} $out $in`,
80 CommandDeps: []string{
81 "${config.MergeZipsCmd}",
82 },
83 })
84)
85
Paul Duffin43f7bf02021-05-05 22:00:51 +010086const (
87 soongSdkSnapshotVersionUnversioned = "unversioned"
88 soongSdkSnapshotVersionCurrent = "current"
89)
90
Paul Duffinb645ec82019-11-27 17:43:54 +000091type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090092 content strings.Builder
93 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090094}
95
Paul Duffinb645ec82019-11-27 17:43:54 +000096// generatedFile abstracts operations for writing contents into a file and emit a build rule
97// for the file.
98type generatedFile struct {
99 generatedContents
100 path android.OutputPath
101}
102
Jiyong Park232e7852019-11-04 12:23:40 +0900103func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +0900104 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +0000105 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +0900106 }
107}
108
Paul Duffinb645ec82019-11-27 17:43:54 +0000109func (gc *generatedContents) Indent() {
110 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +0900111}
112
Paul Duffinb645ec82019-11-27 17:43:54 +0000113func (gc *generatedContents) Dedent() {
114 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +0900115}
116
Paul Duffina08e4dc2021-06-22 18:19:19 +0100117// IndentedPrintf will add spaces to indent the line to the appropriate level before printing the
118// arguments.
119func (gc *generatedContents) IndentedPrintf(format string, args ...interface{}) {
120 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
121}
122
123// UnindentedPrintf does not add spaces to indent the line to the appropriate level before printing
124// the arguments.
125func (gc *generatedContents) UnindentedPrintf(format string, args ...interface{}) {
126 fmt.Fprintf(&(gc.content), format, args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900127}
128
129func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800130 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100131
132 content := gf.content.String()
133
134 // ninja consumes newline characters in rspfile_content. Prevent it by
135 // escaping the backslash in the newline character. The extra backslash
136 // is removed when the rspfile is written to the actual script file
137 content = strings.ReplaceAll(content, "\n", "\\n")
138
Jiyong Park9b409bc2019-10-11 14:59:13 +0900139 rb.Command().
140 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100141 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100142 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900143 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
144 rb.Command().
145 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800146 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900147}
148
Paul Duffin13879572019-11-28 14:31:38 +0000149// Collect all the members.
150//
Paul Duffinb97b1572021-04-29 21:50:40 +0100151// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
152// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000153func (s *sdk) collectMembers(ctx android.ModuleContext) {
154 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000155 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
156 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000157 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100158 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900159
Paul Duffin5cca7c42021-05-26 10:16:01 +0100160 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
161 if memberType == nil {
162 return false
163 }
164
Paul Duffin13879572019-11-28 14:31:38 +0000165 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000166 if !memberType.IsInstance(child) {
167 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900168 }
Paul Duffin13879572019-11-28 14:31:38 +0000169
Paul Duffin6a7e9532020-03-20 17:50:07 +0000170 // Keep track of which multilib variants are used by the sdk.
171 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
172
Paul Duffinb97b1572021-04-29 21:50:40 +0100173 var exportedComponentsInfo android.ExportedComponentsInfo
174 if ctx.OtherModuleHasProvider(child, android.ExportedComponentsInfoProvider) {
175 exportedComponentsInfo = ctx.OtherModuleProvider(child, android.ExportedComponentsInfoProvider).(android.ExportedComponentsInfo)
176 }
177
Paul Duffina7208112021-04-23 21:20:20 +0100178 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100179 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
180 s, memberType, child.(android.SdkAware), export, exportedComponentsInfo,
181 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000182
Paul Duffin2d3da312021-05-06 12:02:27 +0100183 // Recurse down into the member's dependencies as it may have dependencies that need to be
184 // automatically added to the sdk.
185 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900186 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000187
188 return false
Paul Duffin13879572019-11-28 14:31:38 +0000189 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000190}
191
Paul Duffincc3132e2021-04-24 01:10:30 +0100192// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
193// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000194//
Paul Duffincc3132e2021-04-24 01:10:30 +0100195// The sdkMember instances are then grouped into slices by member type. Within each such slice the
196// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000197//
Paul Duffincc3132e2021-04-24 01:10:30 +0100198// Finally, the member type slices are concatenated together to form a single slice. The order in
199// which they are concatenated is the order in which the member types were registered in the
200// android.SdkMemberTypesRegistry.
201func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000202 byType := make(map[android.SdkMemberType][]*sdkMember)
203 byName := make(map[string]*sdkMember)
204
Paul Duffin21827262021-04-24 12:16:36 +0100205 for _, memberVariantDep := range memberVariantDeps {
206 memberType := memberVariantDep.memberType
207 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000208
209 name := ctx.OtherModuleName(variant)
210 member := byName[name]
211 if member == nil {
212 member = &sdkMember{memberType: memberType, name: name}
213 byName[name] = member
214 byType[memberType] = append(byType[memberType], member)
215 }
216
Paul Duffin1356d8c2020-02-25 19:26:33 +0000217 // Only append new variants to the list. This is needed because a member can be both
218 // exported by the sdk and also be a transitive sdk member.
219 member.variants = appendUniqueVariants(member.variants, variant)
220 }
221
Paul Duffin13879572019-11-28 14:31:38 +0000222 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000223 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000224 membersOfType := byType[memberListProperty.memberType]
225 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900226 }
227
Paul Duffin6a7e9532020-03-20 17:50:07 +0000228 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900229}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900230
Paul Duffin72910952020-01-20 18:16:30 +0000231func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
232 for _, v := range variants {
233 if v == newVariant {
234 return variants
235 }
236 }
237 return append(variants, newVariant)
238}
239
Jiyong Park73c54ee2019-10-22 20:31:18 +0900240// SDK directory structure
241// <sdk_root>/
242// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
243// <api_ver>/ : below this directory are all auto-generated
244// Android.bp : definition of 'sdk_snapshot' module is here
245// aidl/
246// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
247// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900248// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900249// include/
250// bionic/libc/include/stdlib.h : an exported header file
251// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900252// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900253// <arch>/include/ : arch-specific exported headers
254// <arch>/include_gen/ : arch-specific generated headers
255// <arch>/lib/
256// libFoo.so : a stub library
257
Jiyong Park232e7852019-11-04 12:23:40 +0900258// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900259// This isn't visible to users, so could be changed in future.
260func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
261 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
262}
263
Jiyong Park232e7852019-11-04 12:23:40 +0900264// buildSnapshot is the main function in this source file. It creates rules to copy
265// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000266func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
267
Paul Duffinb97b1572021-04-29 21:50:40 +0100268 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100269 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100270 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000271 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100272 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100273 }
Paul Duffin865171e2020-03-02 18:38:15 +0000274
Paul Duffinb97b1572021-04-29 21:50:40 +0100275 // Filter out any sdkMemberVariantDep that is a component of another.
276 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000277
Paul Duffinb97b1572021-04-29 21:50:40 +0100278 // Record the names of all the members, both explicitly specified and implicitly
279 // included.
280 allMembersByName := make(map[string]struct{})
281 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100282
Paul Duffinb97b1572021-04-29 21:50:40 +0100283 addMember := func(name string, export bool) {
284 allMembersByName[name] = struct{}{}
285 if export {
286 exportedMembersByName[name] = struct{}{}
287 }
288 }
289
290 for _, memberVariantDep := range memberVariantDeps {
291 name := memberVariantDep.variant.Name()
292 export := memberVariantDep.export
293
294 addMember(name, export)
295
296 // Add any components provided by the module.
297 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
298 addMember(component, export)
299 }
300
301 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
302 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000303 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000304 }
305
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000306 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900307
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000308 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000309
310 bpFile := &bpFile{
311 modules: make(map[string]*bpModule),
312 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000313
Paul Duffin43f7bf02021-05-05 22:00:51 +0100314 config := ctx.Config()
315 version := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_VERSION", "current")
316
317 // Generate versioned modules in the snapshot unless an unversioned snapshot has been requested.
318 generateVersioned := version != soongSdkSnapshotVersionUnversioned
319
320 // Generate unversioned modules in the snapshot unless a numbered snapshot has been requested.
321 //
322 // Unversioned modules are not required in that case because the numbered version will be a
323 // finalized version of the snapshot that is intended to be kept separate from the
324 generateUnversioned := version == soongSdkSnapshotVersionUnversioned || version == soongSdkSnapshotVersionCurrent
325 snapshotZipFileSuffix := ""
326 if generateVersioned {
327 snapshotZipFileSuffix = "-" + version
328 }
329
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000330 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000331 ctx: ctx,
332 sdk: s,
Paul Duffin43f7bf02021-05-05 22:00:51 +0100333 version: version,
Paul Duffin13f02712020-03-06 12:30:43 +0000334 snapshotDir: snapshotDir.OutputPath,
335 copies: make(map[string]string),
336 filesToZip: []android.Path{bp.path},
337 bpFile: bpFile,
338 prebuiltModules: make(map[string]*bpModule),
339 allMembersByName: allMembersByName,
340 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900341 }
Paul Duffinac37c502019-11-26 18:02:20 +0000342 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900343
Paul Duffin62131702021-05-07 01:10:01 +0100344 // If the sdk snapshot includes any license modules then add a package module which has a
345 // default_applicable_licenses property. That will prevent the LSC license process from updating
346 // the generated Android.bp file to add a package module that includes all licenses used by all
347 // the modules in that package. That would be unnecessary as every module in the sdk should have
348 // their own licenses property specified.
349 if hasLicenses {
350 pkg := bpFile.newModule("package")
351 property := "default_applicable_licenses"
352 pkg.AddCommentForProperty(property, `
353A default list here prevents the license LSC from adding its own list which would
354be unnecessary as every module in the sdk already has its own licenses property.
355`)
356 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
357 bpFile.AddModule(pkg)
358 }
359
Paul Duffin0df49682021-05-07 01:10:01 +0100360 // Group the variants for each member module together and then group the members of each member
361 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100362 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100363
364 // Create the prebuilt modules for each of the member modules.
Paul Duffin13ad94f2020-02-19 16:19:27 +0000365 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000366 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000367
Paul Duffina551a1c2020-03-17 21:04:24 +0000368 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000369
370 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100371 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900372 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900373
Paul Duffine6c0d842020-01-15 14:08:51 +0000374 // Create a transformer that will transform an unversioned module into a versioned module.
375 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
376
Paul Duffin72910952020-01-20 18:16:30 +0000377 // Create a transformer that will transform an unversioned module by replacing any references
378 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100379 unversionedTransformer := unversionedTransformation{
380 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100381 }
Paul Duffin72910952020-01-20 18:16:30 +0000382
Paul Duffinb645ec82019-11-27 17:43:54 +0000383 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000384 // Prune any empty property sets.
385 unversioned = unversioned.transform(pruneEmptySetTransformer{})
386
Paul Duffin43f7bf02021-05-05 22:00:51 +0100387 if generateVersioned {
388 // Copy the unversioned module so it can be modified to make it versioned.
389 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000390
Paul Duffin43f7bf02021-05-05 22:00:51 +0100391 // Transform the unversioned module into a versioned one.
392 versioned.transform(unversionedToVersionedTransformer)
393 bpFile.AddModule(versioned)
394 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000395
Paul Duffin43f7bf02021-05-05 22:00:51 +0100396 if generateUnversioned {
397 // Transform the unversioned module to make it suitable for use in the snapshot.
398 unversioned.transform(unversionedTransformer)
399 bpFile.AddModule(unversioned)
400 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000401 }
402
Paul Duffin43f7bf02021-05-05 22:00:51 +0100403 if generateVersioned {
404 // Add the sdk/module_exports_snapshot module to the bp file.
405 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
406 }
Paul Duffin26197a62021-04-24 00:34:10 +0100407
408 // generate Android.bp
409 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
410 generateBpContents(&bp.generatedContents, bpFile)
411
412 contents := bp.content.String()
413 syntaxCheckSnapshotBpFile(ctx, contents)
414
415 bp.build(pctx, ctx, nil)
416
417 filesToZip := builder.filesToZip
418
419 // zip them all
Paul Duffin43f7bf02021-05-05 22:00:51 +0100420 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotZipFileSuffix)
421 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100422 outputDesc := "Building snapshot for " + ctx.ModuleName()
423
424 // If there are no zips to merge then generate the output zip directly.
425 // Otherwise, generate an intermediate zip file into which other zips can be
426 // merged.
427 var zipFile android.OutputPath
428 var desc string
429 if len(builder.zipsToMerge) == 0 {
430 zipFile = outputZipFile
431 desc = outputDesc
432 } else {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100433 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotZipFileSuffix)
434 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100435 desc = "Building intermediate snapshot for " + ctx.ModuleName()
436 }
437
438 ctx.Build(pctx, android.BuildParams{
439 Description: desc,
440 Rule: zipFiles,
441 Inputs: filesToZip,
442 Output: zipFile,
443 Args: map[string]string{
444 "basedir": builder.snapshotDir.String(),
445 },
446 })
447
448 if len(builder.zipsToMerge) != 0 {
449 ctx.Build(pctx, android.BuildParams{
450 Description: outputDesc,
451 Rule: mergeZips,
452 Input: zipFile,
453 Inputs: builder.zipsToMerge,
454 Output: outputZipFile,
455 })
456 }
457
458 return outputZipFile
459}
460
Paul Duffinb97b1572021-04-29 21:50:40 +0100461// filterOutComponents removes any item from the deps list that is a component of another item in
462// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
463// then it will remove "foo.stubs" from the deps.
464func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
465 // Collate the set of components that all the modules added to the sdk provide.
466 components := map[string]*sdkMemberVariantDep{}
467 for i, _ := range deps {
468 dep := &deps[i]
469 for _, c := range dep.exportedComponentsInfo.Components {
470 components[c] = dep
471 }
472 }
473
474 // If no module provides components then return the input deps unfiltered.
475 if len(components) == 0 {
476 return deps
477 }
478
479 filtered := make([]sdkMemberVariantDep, 0, len(deps))
480 for _, dep := range deps {
481 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
482 if owner, ok := components[name]; ok {
483 // This is a component of another module that is a member of the sdk.
484
485 // If the component is exported but the owning module is not then the configuration is not
486 // supported.
487 if dep.export && !owner.export {
488 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
489 continue
490 }
491
492 // This module must not be added to the list of members of the sdk as that would result in a
493 // duplicate module in the sdk snapshot.
494 continue
495 }
496
497 filtered = append(filtered, dep)
498 }
499 return filtered
500}
501
Paul Duffin26197a62021-04-24 00:34:10 +0100502// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100503func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100504 bpFile := builder.bpFile
505
Paul Duffinb645ec82019-11-27 17:43:54 +0000506 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000507 var snapshotModuleType string
508 if s.properties.Module_exports {
509 snapshotModuleType = "module_exports_snapshot"
510 } else {
511 snapshotModuleType = "sdk_snapshot"
512 }
513 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000514 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000515
516 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100517 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000518 if len(visibility) != 0 {
519 snapshotModule.AddProperty("visibility", visibility)
520 }
521
Paul Duffin865171e2020-03-02 18:38:15 +0000522 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000523
Paul Duffincd064672021-04-24 00:47:29 +0100524 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100525 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000526
Paul Duffin2d1bb892021-04-24 11:32:59 +0100527 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100528
Paul Duffin6a7e9532020-03-20 17:50:07 +0000529 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100530
Paul Duffin2d1bb892021-04-24 11:32:59 +0100531 // Create a mapping from osType to combined properties.
532 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
533 for _, combined := range combinedPropertiesList {
534 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
535 }
536
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100537 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000538 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100539 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100540 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000541
Paul Duffin2d1bb892021-04-24 11:32:59 +0100542 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000543 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000544 }
Paul Duffin865171e2020-03-02 18:38:15 +0000545
Jiyong Park8fe14e62020-10-19 22:47:34 +0900546 // If host is supported and any member is host OS dependent then disable host
547 // by default, so that we can enable each host OS variant explicitly. This
548 // avoids problems with implicitly enabled OS variants when the snapshot is
549 // used, which might be different from this run (e.g. different build OS).
550 if s.HostSupported() {
551 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100552 for _, memberVariantDep := range memberVariantDeps {
553 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
554 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900555 if !android.InList(targetString, supportedHostTargets) {
556 supportedHostTargets = append(supportedHostTargets, targetString)
557 }
558 }
559 }
560 if len(supportedHostTargets) > 0 {
561 hostPropertySet := targetPropertySet.AddPropertySet("host")
562 hostPropertySet.AddProperty("enabled", false)
563 }
564 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
565 for _, hostTarget := range supportedHostTargets {
566 propertySet := targetPropertySet.AddPropertySet(hostTarget)
567 propertySet.AddProperty("enabled", true)
568 }
569 }
570
Paul Duffin865171e2020-03-02 18:38:15 +0000571 // Prune any empty property sets.
572 snapshotModule.transform(pruneEmptySetTransformer{})
573
Paul Duffinb645ec82019-11-27 17:43:54 +0000574 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900575}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000576
Paul Duffinf88d8e02020-05-07 20:21:34 +0100577// Check the syntax of the generated Android.bp file contents and if they are
578// invalid then log an error with the contents (tagged with line numbers) and the
579// errors that were found so that it is easy to see where the problem lies.
580func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
581 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
582 if len(errs) != 0 {
583 message := &strings.Builder{}
584 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
585
586Generated Android.bp contents
587========================================================================
588`)
589 for i, line := range strings.Split(contents, "\n") {
590 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
591 }
592
593 _, _ = fmt.Fprint(message, `
594========================================================================
595
596Errors found:
597`)
598
599 for _, err := range errs {
600 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
601 }
602
603 ctx.ModuleErrorf("%s", message.String())
604 }
605}
606
Paul Duffin4b8b7932020-05-06 12:35:38 +0100607func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
608 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
609 if err != nil {
610 ctx.ModuleErrorf("error extracting common properties: %s", err)
611 }
612}
613
Paul Duffinfbe470e2021-04-24 12:37:13 +0100614// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
615type snapshotModuleStaticProperties struct {
616 Compile_multilib string `android:"arch_variant"`
617}
618
Paul Duffin2d1bb892021-04-24 11:32:59 +0100619// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
620type combinedSnapshotModuleProperties struct {
621 // The sdk variant from which this information was collected.
622 sdkVariant *sdk
623
624 // Static snapshot module properties.
625 staticProperties *snapshotModuleStaticProperties
626
627 // The dynamically generated member list properties.
628 dynamicProperties interface{}
629}
630
631// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100632func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
633 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100634 var list []*combinedSnapshotModuleProperties
635 for _, sdkVariant := range sdkVariants {
636 staticProperties := &snapshotModuleStaticProperties{
637 Compile_multilib: sdkVariant.multilibUsages.String(),
638 }
Paul Duffincd064672021-04-24 00:47:29 +0100639 dynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100640
Paul Duffincd064672021-04-24 00:47:29 +0100641 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100642 sdkVariant: sdkVariant,
643 staticProperties: staticProperties,
644 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100645 }
646 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
647
648 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100649 }
Paul Duffincd064672021-04-24 00:47:29 +0100650
651 for _, memberVariantDep := range memberVariantDeps {
652 // If the member dependency is internal then do not add the dependency to the snapshot member
653 // list properties.
654 if !memberVariantDep.export {
655 continue
656 }
657
658 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin13082052021-05-11 00:31:38 +0100659 memberListProperty := s.memberListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100660 memberName := ctx.OtherModuleName(memberVariantDep.variant)
661
Paul Duffin13082052021-05-11 00:31:38 +0100662 if memberListProperty.getter == nil {
663 continue
664 }
665
Paul Duffincd064672021-04-24 00:47:29 +0100666 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100667 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100668 if !android.InList(memberName, memberList) {
669 memberList = append(memberList, memberName)
670 }
Paul Duffin13082052021-05-11 00:31:38 +0100671 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100672 }
673
Paul Duffin2d1bb892021-04-24 11:32:59 +0100674 return list
675}
676
677func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
678
679 // Extract the dynamic properties and add them to a list of propertiesContainer.
680 propertyContainers := []propertiesContainer{}
681 for _, i := range list {
682 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
683 sdkVariant: i.sdkVariant,
684 properties: i.dynamicProperties,
685 })
686 }
687
688 // Extract the common members, removing them from the original properties.
689 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
690 extractor := newCommonValueExtractor(commonDynamicProperties)
691 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
692
693 // Extract the static properties and add them to a list of propertiesContainer.
694 propertyContainers = []propertiesContainer{}
695 for _, i := range list {
696 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
697 sdkVariant: i.sdkVariant,
698 properties: i.staticProperties,
699 })
700 }
701
702 commonStaticProperties := &snapshotModuleStaticProperties{}
703 extractor = newCommonValueExtractor(commonStaticProperties)
704 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
705
706 return &combinedSnapshotModuleProperties{
707 sdkVariant: nil,
708 staticProperties: commonStaticProperties,
709 dynamicProperties: commonDynamicProperties,
710 }
711}
712
713func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
714 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100715 multilib := staticProperties.Compile_multilib
716 if multilib != "" && multilib != "both" {
717 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
718 propertySet.AddProperty("compile_multilib", multilib)
719 }
720
Paul Duffin2d1bb892021-04-24 11:32:59 +0100721 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin865171e2020-03-02 18:38:15 +0000722 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100723 if memberListProperty.getter == nil {
724 continue
725 }
Paul Duffin865171e2020-03-02 18:38:15 +0000726 names := memberListProperty.getter(dynamicMemberTypeListProperties)
727 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000728 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000729 }
730 }
731}
732
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000733type propertyTag struct {
734 name string
735}
736
Paul Duffin0cb37b92020-03-04 14:52:46 +0000737// A BpPropertyTag to add to a property that contains references to other sdk members.
738//
739// This will cause the references to be rewritten to a versioned reference in the version
740// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000741var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000742var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000743
Paul Duffin0cb37b92020-03-04 14:52:46 +0000744// A BpPropertyTag that indicates the property should only be present in the versioned
745// module.
746//
747// This will cause the property to be removed from the unversioned instance of a
748// snapshot module.
749var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
750
Paul Duffine6c0d842020-01-15 14:08:51 +0000751type unversionedToVersionedTransformation struct {
752 identityTransformation
753 builder *snapshotBuilder
754}
755
Paul Duffine6c0d842020-01-15 14:08:51 +0000756func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
757 // Use a versioned name for the module but remember the original name for the
758 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100759 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000760 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000761 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100762 // Remove the prefer property if present as versioned modules never need marking with prefer.
763 module.removeProperty("prefer")
Paul Duffine6c0d842020-01-15 14:08:51 +0000764 return module
765}
766
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000767func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000768 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
769 required := tag == requiredSdkMemberReferencePropertyTag
770 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000771 } else {
772 return value, tag
773 }
774}
775
Paul Duffin72910952020-01-20 18:16:30 +0000776type unversionedTransformation struct {
777 identityTransformation
778 builder *snapshotBuilder
779}
780
781func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
782 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100783 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000784 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000785 return module
786}
787
788func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000789 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
790 required := tag == requiredSdkMemberReferencePropertyTag
791 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000792 } else if tag == sdkVersionedOnlyPropertyTag {
793 // The property is not allowed in the unversioned module so remove it.
794 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000795 } else {
796 return value, tag
797 }
798}
799
Paul Duffina78f3a72020-02-21 16:29:35 +0000800type pruneEmptySetTransformer struct {
801 identityTransformation
802}
803
804var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
805
806func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
807 if len(propertySet.properties) == 0 {
808 return nil, nil
809 } else {
810 return propertySet, tag
811 }
812}
813
Paul Duffinb645ec82019-11-27 17:43:54 +0000814func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000815 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
816 return true
817 })
818}
819
820func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100821 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000822 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000823 if moduleFilter(bpModule) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100824 contents.IndentedPrintf("\n")
825 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
Paul Duffind0759072021-02-17 11:23:00 +0000826 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100827 contents.IndentedPrintf("}\n")
Paul Duffind0759072021-02-17 11:23:00 +0000828 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000829 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000830}
831
832func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
833 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000834
Paul Duffin0df49682021-05-07 01:10:01 +0100835 addComment := func(name string) {
836 if text, ok := set.comments[name]; ok {
837 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100838 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100839 }
840 }
841 }
842
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000843 // Output the properties first, followed by the nested sets. This ensures a
844 // consistent output irrespective of whether property sets are created before
845 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000846 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000847 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000848
Paul Duffin0df49682021-05-07 01:10:01 +0100849 // Do not write property sets in the properties phase.
850 if _, ok := value.(*bpPropertySet); ok {
851 continue
852 }
853
854 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100855 reflectValue := reflect.ValueOf(value)
856 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000857 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000858
859 for _, name := range set.order {
860 value := set.getValue(name)
861
862 // Only write property sets in the sets phase.
863 switch v := value.(type) {
864 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100865 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100866 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000867 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100868 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000869 }
870 }
871
Paul Duffinb645ec82019-11-27 17:43:54 +0000872 contents.Dedent()
873}
874
Paul Duffina08e4dc2021-06-22 18:19:19 +0100875// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
876// by the value and then followed by a , and a newline.
877func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
878 contents.IndentedPrintf("%s: ", name)
879 outputUnnamedValue(contents, value)
880 contents.UnindentedPrintf(",\n")
881}
882
883// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
884// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
885// indented and all but the last line will end with a newline.
886func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
887 valueType := value.Type()
888 switch valueType.Kind() {
889 case reflect.Bool:
890 contents.UnindentedPrintf("%t", value.Bool())
891
892 case reflect.String:
893 contents.UnindentedPrintf("%q", value)
894
Paul Duffin51227d82021-05-18 12:54:27 +0100895 case reflect.Ptr:
896 outputUnnamedValue(contents, value.Elem())
897
Paul Duffina08e4dc2021-06-22 18:19:19 +0100898 case reflect.Slice:
899 length := value.Len()
900 if length == 0 {
901 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100902 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100903 firstValue := value.Index(0)
904 if length == 1 && !multiLineValue(firstValue) {
905 contents.UnindentedPrintf("[")
906 outputUnnamedValue(contents, firstValue)
907 contents.UnindentedPrintf("]")
908 } else {
909 contents.UnindentedPrintf("[\n")
910 contents.Indent()
911 for i := 0; i < length; i++ {
912 itemValue := value.Index(i)
913 contents.IndentedPrintf("")
914 outputUnnamedValue(contents, itemValue)
915 contents.UnindentedPrintf(",\n")
916 }
917 contents.Dedent()
918 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100919 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100920 }
921
Paul Duffin51227d82021-05-18 12:54:27 +0100922 case reflect.Struct:
923 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
924 v := value.Interface()
925 if _, ok := v.(android.BpPrintable); !ok {
926 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
927 }
928 contents.UnindentedPrintf("{\n")
929 contents.Indent()
930 for f := 0; f < valueType.NumField(); f++ {
931 fieldType := valueType.Field(f)
932 if fieldType.Anonymous {
933 continue
934 }
935 fieldValue := value.Field(f)
936 fieldName := fieldType.Name
937 propertyName := proptools.PropertyNameForField(fieldName)
938 outputNamedValue(contents, propertyName, fieldValue)
939 }
940 contents.Dedent()
941 contents.IndentedPrintf("}")
942
Paul Duffina08e4dc2021-06-22 18:19:19 +0100943 default:
944 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
945 }
946}
947
Paul Duffin51227d82021-05-18 12:54:27 +0100948// multiLineValue returns true if the supplied value may require multiple lines in the output.
949func multiLineValue(value reflect.Value) bool {
950 kind := value.Kind()
951 return kind == reflect.Slice || kind == reflect.Struct
952}
953
Paul Duffinac37c502019-11-26 18:02:20 +0000954func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000955 contents := &generatedContents{}
956 generateBpContents(contents, s.builderForTests.bpFile)
957 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000958}
959
Paul Duffind0759072021-02-17 11:23:00 +0000960func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
961 contents := &generatedContents{}
962 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100963 name := module.Name()
964 // Include modules that are either unversioned or have no name.
965 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000966 })
967 return contents.content.String()
968}
969
970func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
971 contents := &generatedContents{}
972 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100973 name := module.Name()
974 // Include modules that are either versioned or have no name.
975 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000976 })
977 return contents.content.String()
978}
979
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000980type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100981 ctx android.ModuleContext
982 sdk *sdk
983
984 // The version of the generated snapshot.
985 //
986 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
987 // this field.
988 version string
989
Paul Duffinb645ec82019-11-27 17:43:54 +0000990 snapshotDir android.OutputPath
991 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000992
993 // Map from destination to source of each copy - used to eliminate duplicates and
994 // detect conflicts.
995 copies map[string]string
996
Paul Duffinb645ec82019-11-27 17:43:54 +0000997 filesToZip android.Paths
998 zipsToMerge android.Paths
999
1000 prebuiltModules map[string]*bpModule
1001 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001002
1003 // The set of all members by name.
1004 allMembersByName map[string]struct{}
1005
1006 // The set of exported members by name.
1007 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001008}
1009
1010func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001011 if existing, ok := s.copies[dest]; ok {
1012 if existing != src.String() {
1013 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1014 return
1015 }
1016 } else {
1017 path := s.snapshotDir.Join(s.ctx, dest)
1018 s.ctx.Build(pctx, android.BuildParams{
1019 Rule: android.Cp,
1020 Input: src,
1021 Output: path,
1022 })
1023 s.filesToZip = append(s.filesToZip, path)
1024
1025 s.copies[dest] = src.String()
1026 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001027}
1028
Paul Duffin91547182019-11-12 19:39:36 +00001029func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1030 ctx := s.ctx
1031
1032 // Repackage the zip file so that the entries are in the destDir directory.
1033 // This will allow the zip file to be merged into the snapshot.
1034 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001035
1036 ctx.Build(pctx, android.BuildParams{
1037 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1038 Rule: repackageZip,
1039 Input: zipPath,
1040 Output: tmpZipPath,
1041 Args: map[string]string{
1042 "destdir": destDir,
1043 },
1044 })
Paul Duffin91547182019-11-12 19:39:36 +00001045
1046 // Add the repackaged zip file to the files to merge.
1047 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1048}
1049
Paul Duffin9d8d6092019-12-05 18:19:29 +00001050func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1051 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001052 if s.prebuiltModules[name] != nil {
1053 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1054 }
1055
1056 m := s.bpFile.newModule(moduleType)
1057 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001058
Paul Duffinbefa4b92020-03-04 14:22:45 +00001059 variant := member.Variants()[0]
1060
Paul Duffin13f02712020-03-06 12:30:43 +00001061 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001062 // An internal member is only referenced from the sdk snapshot which is in the
1063 // same package so can be marked as private.
1064 m.AddProperty("visibility", []string{"//visibility:private"})
1065 } else {
1066 // Extract visibility information from a member variant. All variants have the same
1067 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001068 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1069
1070 // Add any additional visibility rules needed for the prebuilts to reference each other.
1071 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1072 if err != nil {
1073 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1074 }
1075
1076 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001077 if len(visibility) != 0 {
1078 m.AddProperty("visibility", visibility)
1079 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001080 }
1081
Martin Stjernholm1e041092020-11-03 00:11:09 +00001082 // Where available copy apex_available properties from the member.
1083 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1084 apexAvailable := apexAware.ApexAvailable()
1085 if len(apexAvailable) == 0 {
1086 // //apex_available:platform is the default.
1087 apexAvailable = []string{android.AvailableToPlatform}
1088 }
1089
1090 // Add in any baseline apex available settings.
1091 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1092
1093 // Remove duplicates and sort.
1094 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1095 sort.Strings(apexAvailable)
1096
1097 m.AddProperty("apex_available", apexAvailable)
1098 }
1099
Paul Duffinb0bb3762021-05-06 16:48:05 +01001100 // The licenses are the same for all variants.
1101 mctx := s.ctx
1102 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1103 if len(licenseInfo.Licenses) > 0 {
1104 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1105 }
1106
Paul Duffin865171e2020-03-02 18:38:15 +00001107 deviceSupported := false
1108 hostSupported := false
1109
1110 for _, variant := range member.Variants() {
1111 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001112 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001113 hostSupported = true
1114 } else if osClass == android.Device {
1115 deviceSupported = true
1116 }
1117 }
1118
1119 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001120
Paul Duffin0cb37b92020-03-04 14:52:46 +00001121 // Disable installation in the versioned module of those modules that are ever installable.
1122 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1123 if installable.EverInstallable() {
1124 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1125 }
1126 }
1127
Paul Duffinb645ec82019-11-27 17:43:54 +00001128 s.prebuiltModules[name] = m
1129 s.prebuiltOrder = append(s.prebuiltOrder, m)
1130 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001131}
1132
Paul Duffin865171e2020-03-02 18:38:15 +00001133func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001134 // If neither device or host is supported then this module does not support either so will not
1135 // recognize the properties.
1136 if !deviceSupported && !hostSupported {
1137 return
1138 }
1139
Paul Duffin865171e2020-03-02 18:38:15 +00001140 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001141 bpModule.AddProperty("device_supported", false)
1142 }
Paul Duffin865171e2020-03-02 18:38:15 +00001143 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001144 bpModule.AddProperty("host_supported", true)
1145 }
1146}
1147
Paul Duffin13f02712020-03-06 12:30:43 +00001148func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1149 if required {
1150 return requiredSdkMemberReferencePropertyTag
1151 } else {
1152 return optionalSdkMemberReferencePropertyTag
1153 }
1154}
1155
1156func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1157 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001158}
1159
Paul Duffinb645ec82019-11-27 17:43:54 +00001160// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001161func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1162 if _, ok := s.allMembersByName[unversionedName]; !ok {
1163 if required {
1164 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1165 }
1166 return unversionedName
1167 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001168 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1169}
Paul Duffinb645ec82019-11-27 17:43:54 +00001170
Paul Duffin13f02712020-03-06 12:30:43 +00001171func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001172 var references []string = nil
1173 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001174 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001175 }
1176 return references
1177}
Paul Duffin13879572019-11-28 14:31:38 +00001178
Paul Duffin72910952020-01-20 18:16:30 +00001179// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001180func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1181 if _, ok := s.allMembersByName[unversionedName]; !ok {
1182 if required {
1183 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1184 }
1185 return unversionedName
1186 }
1187
1188 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001189 return s.ctx.ModuleName() + "_" + unversionedName
1190 } else {
1191 return unversionedName
1192 }
1193}
1194
Paul Duffin13f02712020-03-06 12:30:43 +00001195func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001196 var references []string = nil
1197 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001198 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001199 }
1200 return references
1201}
1202
Paul Duffin13f02712020-03-06 12:30:43 +00001203func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1204 _, ok := s.exportedMembersByName[memberName]
1205 return !ok
1206}
1207
Martin Stjernholm89238f42020-07-10 00:14:03 +01001208// Add the properties from the given SdkMemberProperties to the blueprint
1209// property set. This handles common properties in SdkMemberPropertiesBase and
1210// calls the member-specific AddToPropertySet for the rest.
1211func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1212 if memberProperties.Base().Compile_multilib != "" {
1213 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1214 }
1215
1216 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1217}
1218
Paul Duffin21827262021-04-24 12:16:36 +01001219// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1220type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001221 // The sdk variant that depends (possibly indirectly) on the member variant.
1222 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001223
1224 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001225 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001226
1227 // The variant that is added to the sdk.
1228 variant android.SdkAware
1229
1230 // True if the member should be exported, i.e. accessible, from outside the sdk.
1231 export bool
1232
1233 // The names of additional component modules provided by the variant.
1234 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001235}
1236
Paul Duffin13879572019-11-28 14:31:38 +00001237var _ android.SdkMember = (*sdkMember)(nil)
1238
Paul Duffin21827262021-04-24 12:16:36 +01001239// sdkMember groups all the variants of a specific member module together along with the name of the
1240// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001241type sdkMember struct {
1242 memberType android.SdkMemberType
1243 name string
1244 variants []android.SdkAware
1245}
1246
1247func (m *sdkMember) Name() string {
1248 return m.name
1249}
1250
1251func (m *sdkMember) Variants() []android.SdkAware {
1252 return m.variants
1253}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001254
Paul Duffin9c3760e2020-03-16 19:52:08 +00001255// Track usages of multilib variants.
1256type multilibUsage int
1257
1258const (
1259 multilibNone multilibUsage = 0
1260 multilib32 multilibUsage = 1
1261 multilib64 multilibUsage = 2
1262 multilibBoth = multilib32 | multilib64
1263)
1264
1265// Add the multilib that is used in the arch type.
1266func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1267 multilib := archType.Multilib
1268 switch multilib {
1269 case "":
1270 return m
1271 case "lib32":
1272 return m | multilib32
1273 case "lib64":
1274 return m | multilib64
1275 default:
1276 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1277 }
1278}
1279
1280func (m multilibUsage) String() string {
1281 switch m {
1282 case multilibNone:
1283 return ""
1284 case multilib32:
1285 return "32"
1286 case multilib64:
1287 return "64"
1288 case multilibBoth:
1289 return "both"
1290 default:
1291 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1292 m, multilibNone, multilib32, multilib64, multilibBoth))
1293 }
1294}
1295
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001296type baseInfo struct {
1297 Properties android.SdkMemberProperties
1298}
1299
Paul Duffinf34f6d82020-04-30 15:48:31 +01001300func (b *baseInfo) optimizableProperties() interface{} {
1301 return b.Properties
1302}
1303
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001304type osTypeSpecificInfo struct {
1305 baseInfo
1306
Paul Duffin00e46802020-03-12 20:40:35 +00001307 osType android.OsType
1308
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001309 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001310 //
1311 // Nil if there is one variant whose arch type is common
1312 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001313}
1314
Paul Duffin4b8b7932020-05-06 12:35:38 +01001315var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1316
Paul Duffinfc8dd232020-03-17 12:51:37 +00001317type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1318
Paul Duffin00e46802020-03-12 20:40:35 +00001319// Create a new osTypeSpecificInfo for the specified os type and its properties
1320// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001321func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001322 osInfo := &osTypeSpecificInfo{
1323 osType: osType,
1324 }
1325
1326 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1327 properties := variantPropertiesFactory()
1328 properties.Base().Os = osType
1329 return properties
1330 }
1331
1332 // Create a structure into which properties common across the architectures in
1333 // this os type will be stored.
1334 osInfo.Properties = osSpecificVariantPropertiesFactory()
1335
1336 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001337 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001338 var archTypes []android.ArchType
1339 for _, variant := range osTypeVariants {
1340 archType := variant.Target().Arch.ArchType
1341 archTypeName := archType.Name
1342 if _, ok := variantsByArchName[archTypeName]; !ok {
1343 archTypes = append(archTypes, archType)
1344 }
1345
1346 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1347 }
1348
1349 if commonVariants, ok := variantsByArchName["common"]; ok {
1350 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001351 panic(fmt.Errorf("Expected to only have 1 variant when arch type is common but found %d", len(osTypeVariants)))
Paul Duffin00e46802020-03-12 20:40:35 +00001352 }
1353
1354 // A common arch type only has one variant and its properties should be treated
1355 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001356 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001357 } else {
1358 // Create an arch specific info for each supported architecture type.
1359 for _, archType := range archTypes {
1360 archTypeName := archType.Name
1361
1362 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001363 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001364
1365 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1366 }
1367 }
1368
1369 return osInfo
1370}
1371
1372// Optimize the properties by extracting common properties from arch type specific
1373// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001374func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001375 // Nothing to do if there is only a single common architecture.
1376 if len(osInfo.archInfos) == 0 {
1377 return
1378 }
1379
Paul Duffin9c3760e2020-03-16 19:52:08 +00001380 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001381 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001382 multilib = multilib.addArchType(archInfo.archType)
1383
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001384 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001385 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001386 }
1387
Paul Duffin4b8b7932020-05-06 12:35:38 +01001388 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001389
1390 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001391 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001392}
1393
1394// Add the properties for an os to a property set.
1395//
1396// Maps the properties related to the os variants through to an appropriate
1397// module structure that will produce equivalent set of variants when it is
1398// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001399func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001400
1401 var osPropertySet android.BpPropertySet
1402 var archPropertySet android.BpPropertySet
1403 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001404 if osInfo.Properties.Base().Os_count == 1 &&
1405 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1406 // There is only one OS type present in the variants and it shouldn't have a
1407 // variant-specific target. The latter is the case if it's either for device
1408 // where there is only one OS (android), or for host and the member type
1409 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001410
1411 // Create a structure that looks like:
1412 // module_type {
1413 // name: "...",
1414 // ...
1415 // <common properties>
1416 // ...
1417 // <single os type specific properties>
1418 //
1419 // arch: {
1420 // <arch specific sections>
1421 // }
1422 //
1423 osPropertySet = bpModule
1424 archPropertySet = osPropertySet.AddPropertySet("arch")
1425
1426 // Arch specific properties need to be added to an arch specific section
1427 // within arch.
1428 archOsPrefix = ""
1429 } else {
1430 // Create a structure that looks like:
1431 // module_type {
1432 // name: "...",
1433 // ...
1434 // <common properties>
1435 // ...
1436 // target: {
1437 // <arch independent os specific sections, e.g. android>
1438 // ...
1439 // <arch and os specific sections, e.g. android_x86>
1440 // }
1441 //
1442 osType := osInfo.osType
1443 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1444 archPropertySet = targetPropertySet
1445
1446 // Arch specific properties need to be added to an os and arch specific
1447 // section prefixed with <os>_.
1448 archOsPrefix = osType.Name + "_"
1449 }
1450
1451 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001452 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001453
1454 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1455 // os) specific properties.
1456 //
1457 // The archInfos list will be empty if the os contains variants for the common
1458 // architecture.
1459 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001460 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001461 }
1462}
1463
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001464func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1465 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001466 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001467}
1468
1469var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1470
Paul Duffin4b8b7932020-05-06 12:35:38 +01001471func (osInfo *osTypeSpecificInfo) String() string {
1472 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1473}
1474
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001475type archTypeSpecificInfo struct {
1476 baseInfo
1477
1478 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001479 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001480
1481 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001482}
1483
Paul Duffin4b8b7932020-05-06 12:35:38 +01001484var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1485
Paul Duffinfc8dd232020-03-17 12:51:37 +00001486// Create a new archTypeSpecificInfo for the specified arch type and its properties
1487// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001488func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001489
Paul Duffinfc8dd232020-03-17 12:51:37 +00001490 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001491 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001492
1493 // Create the properties into which the arch type specific properties will be
1494 // added.
1495 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001496
1497 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001498 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001499 } else {
1500 // There is more than one variant for this arch type which must be differentiated
1501 // by link type.
1502 for _, linkVariant := range archVariants {
1503 linkType := getLinkType(linkVariant)
1504 if linkType == "" {
1505 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1506 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001507 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001508
1509 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1510 }
1511 }
1512 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001513
1514 return archInfo
1515}
1516
Paul Duffinf34f6d82020-04-30 15:48:31 +01001517func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1518 return archInfo.Properties
1519}
1520
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001521// Get the link type of the variant
1522//
1523// If the variant is not differentiated by link type then it returns "",
1524// otherwise it returns one of "static" or "shared".
1525func getLinkType(variant android.Module) string {
1526 linkType := ""
1527 if linkable, ok := variant.(cc.LinkableInterface); ok {
1528 if linkable.Shared() && linkable.Static() {
1529 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1530 } else if linkable.Shared() {
1531 linkType = "shared"
1532 } else if linkable.Static() {
1533 linkType = "static"
1534 } else {
1535 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1536 }
1537 }
1538 return linkType
1539}
1540
1541// Optimize the properties by extracting common properties from link type specific
1542// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001543func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001544 if len(archInfo.linkInfos) == 0 {
1545 return
1546 }
1547
Paul Duffin4b8b7932020-05-06 12:35:38 +01001548 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001549}
1550
Paul Duffinfc8dd232020-03-17 12:51:37 +00001551// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001552func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001553 archTypeName := archInfo.archType.Name
1554 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001555 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1556 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1557 archTypePropertySet.AddProperty("enabled", true)
1558 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001559 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001560
1561 for _, linkInfo := range archInfo.linkInfos {
1562 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001563 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001564 }
1565}
1566
Paul Duffin4b8b7932020-05-06 12:35:38 +01001567func (archInfo *archTypeSpecificInfo) String() string {
1568 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1569}
1570
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001571type linkTypeSpecificInfo struct {
1572 baseInfo
1573
1574 linkType string
1575}
1576
Paul Duffin4b8b7932020-05-06 12:35:38 +01001577var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1578
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001579// Create a new linkTypeSpecificInfo for the specified link type and its properties
1580// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001581func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001582 linkInfo := &linkTypeSpecificInfo{
1583 baseInfo: baseInfo{
1584 // Create the properties into which the link type specific properties will be
1585 // added.
1586 Properties: variantPropertiesFactory(),
1587 },
1588 linkType: linkType,
1589 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001590 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001591 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001592}
1593
Paul Duffin4b8b7932020-05-06 12:35:38 +01001594func (l *linkTypeSpecificInfo) String() string {
1595 return fmt.Sprintf("LinkType{%s}", l.linkType)
1596}
1597
Paul Duffin3a4eb502020-03-19 16:11:18 +00001598type memberContext struct {
1599 sdkMemberContext android.ModuleContext
1600 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001601 memberType android.SdkMemberType
1602 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001603}
1604
1605func (m *memberContext) SdkModuleContext() android.ModuleContext {
1606 return m.sdkMemberContext
1607}
1608
1609func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1610 return m.builder
1611}
1612
Paul Duffina551a1c2020-03-17 21:04:24 +00001613func (m *memberContext) MemberType() android.SdkMemberType {
1614 return m.memberType
1615}
1616
1617func (m *memberContext) Name() string {
1618 return m.name
1619}
1620
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001621func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001622
1623 memberType := member.memberType
1624
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001625 // Do not add the prefer property if the member snapshot module is a source module type.
1626 if !memberType.UsesSourceModuleTypeInSnapshot() {
Mathew Inwoodd0b99ce2021-05-20 11:00:12 +01001627 // Set the prefer based on the environment variable if present, else the sdk.prefer_prebuilts
1628 // value.
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001629 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1630 // dynamically at build time not at snapshot generation time.
Mathew Inwoodd0b99ce2021-05-20 11:00:12 +01001631 prefer := ctx.sdkMemberContext.Config().IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER") || s.PreferPrebuilts()
Paul Duffin83ad9562021-05-10 23:49:04 +01001632
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001633 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1634 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1635 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1636 // behavior is for the module.
1637 bpModule.insertAfter("name", "prefer", prefer)
1638 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001639
Paul Duffina04c1072020-03-02 10:16:35 +00001640 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001641 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001642 variants := member.Variants()
1643 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001644 osType := variant.Target().Os
1645 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001646 }
1647
Paul Duffina04c1072020-03-02 10:16:35 +00001648 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001649 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001650 properties := memberType.CreateVariantPropertiesStruct()
1651 base := properties.Base()
1652 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001653 return properties
1654 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001655
Paul Duffina04c1072020-03-02 10:16:35 +00001656 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001657
Paul Duffina04c1072020-03-02 10:16:35 +00001658 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001659 commonProperties := variantPropertiesFactory()
1660 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001661
Paul Duffinc097e362020-03-10 22:50:03 +00001662 // Create common value extractor that can be used to optimize the properties.
1663 commonValueExtractor := newCommonValueExtractor(commonProperties)
1664
Paul Duffina04c1072020-03-02 10:16:35 +00001665 // The list of property structures which are os type specific but common across
1666 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001667 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001668
1669 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001670 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001671 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001672 // Add the os specific properties to a list of os type specific yet architecture
1673 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001674 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001675
Paul Duffin00e46802020-03-12 20:40:35 +00001676 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001677 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001678 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001679
Paul Duffina04c1072020-03-02 10:16:35 +00001680 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001681 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001682
Paul Duffina04c1072020-03-02 10:16:35 +00001683 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001684 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001685
Paul Duffina04c1072020-03-02 10:16:35 +00001686 // Create a target property set into which target specific properties can be
1687 // added.
1688 targetPropertySet := bpModule.AddPropertySet("target")
1689
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001690 // If the member is host OS dependent and has host_supported then disable by
1691 // default and enable each host OS variant explicitly. This avoids problems
1692 // with implicitly enabled OS variants when the snapshot is used, which might
1693 // be different from this run (e.g. different build OS).
1694 if ctx.memberType.IsHostOsDependent() {
1695 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1696 if hostSupported {
1697 hostPropertySet := targetPropertySet.AddPropertySet("host")
1698 hostPropertySet.AddProperty("enabled", false)
1699 }
1700 }
1701
Paul Duffina04c1072020-03-02 10:16:35 +00001702 // Iterate over the os types in a fixed order.
1703 for _, osType := range s.getPossibleOsTypes() {
1704 osInfo := osTypeToInfo[osType]
1705 if osInfo == nil {
1706 continue
1707 }
1708
Paul Duffin3a4eb502020-03-19 16:11:18 +00001709 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001710 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001711}
1712
Paul Duffina04c1072020-03-02 10:16:35 +00001713// Compute the list of possible os types that this sdk could support.
1714func (s *sdk) getPossibleOsTypes() []android.OsType {
1715 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001716 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001717 if s.DeviceSupported() {
1718 if osType.Class == android.Device && osType != android.Fuchsia {
1719 osTypes = append(osTypes, osType)
1720 }
1721 }
1722 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001723 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001724 osTypes = append(osTypes, osType)
1725 }
1726 }
1727 }
1728 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1729 return osTypes
1730}
1731
Paul Duffinb28369a2020-05-04 15:39:59 +01001732// Given a set of properties (struct value), return the value of the field within that
1733// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001734type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1735
Paul Duffinc459f892020-04-30 18:08:29 +01001736// Checks the metadata to determine whether the property should be ignored for the
1737// purposes of common value extraction or not.
1738type extractorMetadataPredicate func(metadata propertiesContainer) bool
1739
1740// Indicates whether optimizable properties are provided by a host variant or
1741// not.
1742type isHostVariant interface {
1743 isHostVariant() bool
1744}
1745
Paul Duffinb28369a2020-05-04 15:39:59 +01001746// A property that can be optimized by the commonValueExtractor.
1747type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001748 // The name of the field for this property. It is a "."-separated path for
1749 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001750 name string
1751
Paul Duffinc459f892020-04-30 18:08:29 +01001752 // Filter that can use metadata associated with the properties being optimized
1753 // to determine whether the field should be ignored during common value
1754 // optimization.
1755 filter extractorMetadataPredicate
1756
Paul Duffinb28369a2020-05-04 15:39:59 +01001757 // Retrieves the value on which common value optimization will be performed.
1758 getter fieldAccessorFunc
1759
1760 // The empty value for the field.
1761 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001762
1763 // True if the property can support arch variants false otherwise.
1764 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001765}
1766
Paul Duffin4b8b7932020-05-06 12:35:38 +01001767func (p extractorProperty) String() string {
1768 return p.name
1769}
1770
Paul Duffinc097e362020-03-10 22:50:03 +00001771// Supports extracting common values from a number of instances of a properties
1772// structure into a separate common set of properties.
1773type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001774 // The properties that the extractor can optimize.
1775 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001776}
1777
1778// Create a new common value extractor for the structure type for the supplied
1779// properties struct.
1780//
1781// The returned extractor can be used on any properties structure of the same type
1782// as the supplied set of properties.
1783func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1784 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1785 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001786 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001787 return extractor
1788}
1789
1790// Gather the fields from the supplied structure type from which common values will
1791// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001792//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001793// This is recursive function. If it encounters a struct then it will recurse
1794// into it, passing in the accessor for the field and the struct name as prefix
1795// for the nested fields. That will then be used in the accessors for the fields
1796// in the embedded struct.
1797func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001798 for f := 0; f < structType.NumField(); f++ {
1799 field := structType.Field(f)
1800 if field.PkgPath != "" {
1801 // Ignore unexported fields.
1802 continue
1803 }
1804
Paul Duffinb07fa512020-03-10 22:17:04 +00001805 // Ignore fields whose value should be kept.
1806 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001807 continue
1808 }
1809
Paul Duffinc459f892020-04-30 18:08:29 +01001810 var filter extractorMetadataPredicate
1811
1812 // Add a filter
1813 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1814 filter = func(metadata propertiesContainer) bool {
1815 if m, ok := metadata.(isHostVariant); ok {
1816 if m.isHostVariant() {
1817 return false
1818 }
1819 }
1820 return true
1821 }
1822 }
1823
Paul Duffinc097e362020-03-10 22:50:03 +00001824 // Save a copy of the field index for use in the function.
1825 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001826
Martin Stjernholmb0249572020-09-15 02:32:35 +01001827 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001828
Paul Duffinc097e362020-03-10 22:50:03 +00001829 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001830 if containingStructAccessor != nil {
1831 // This is an embedded structure so first access the field for the embedded
1832 // structure.
1833 value = containingStructAccessor(value)
1834 }
1835
Paul Duffinc097e362020-03-10 22:50:03 +00001836 // Skip through interface and pointer values to find the structure.
1837 value = getStructValue(value)
1838
Paul Duffin4b8b7932020-05-06 12:35:38 +01001839 defer func() {
1840 if r := recover(); r != nil {
1841 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1842 }
1843 }()
1844
Paul Duffinc097e362020-03-10 22:50:03 +00001845 // Return the field.
1846 return value.Field(fieldIndex)
1847 }
1848
Martin Stjernholmb0249572020-09-15 02:32:35 +01001849 if field.Type.Kind() == reflect.Struct {
1850 // Gather fields from the nested or embedded structure.
1851 var subNamePrefix string
1852 if field.Anonymous {
1853 subNamePrefix = namePrefix
1854 } else {
1855 subNamePrefix = name + "."
1856 }
1857 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001858 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001859 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001860 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001861 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001862 fieldGetter,
1863 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001864 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001865 }
1866 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001867 }
Paul Duffinc097e362020-03-10 22:50:03 +00001868 }
1869}
1870
1871func getStructValue(value reflect.Value) reflect.Value {
1872foundStruct:
1873 for {
1874 kind := value.Kind()
1875 switch kind {
1876 case reflect.Interface, reflect.Ptr:
1877 value = value.Elem()
1878 case reflect.Struct:
1879 break foundStruct
1880 default:
1881 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1882 }
1883 }
1884 return value
1885}
1886
Paul Duffinf34f6d82020-04-30 15:48:31 +01001887// A container of properties to be optimized.
1888//
1889// Allows additional information to be associated with the properties, e.g. for
1890// filtering.
1891type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001892 fmt.Stringer
1893
Paul Duffinf34f6d82020-04-30 15:48:31 +01001894 // Get the properties that need optimizing.
1895 optimizableProperties() interface{}
1896}
1897
Paul Duffin2d1bb892021-04-24 11:32:59 +01001898// A wrapper for sdk variant related properties to allow them to be optimized.
1899type sdkVariantPropertiesContainer struct {
1900 sdkVariant *sdk
1901 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01001902}
1903
Paul Duffin2d1bb892021-04-24 11:32:59 +01001904func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
1905 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01001906}
1907
Paul Duffin2d1bb892021-04-24 11:32:59 +01001908func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001909 return c.sdkVariant.String()
1910}
1911
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001912// Extract common properties from a slice of property structures of the same type.
1913//
1914// All the property structures must be of the same type.
1915// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001916// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001917//
1918// Iterates over each exported field (capitalized name) and checks to see whether they
1919// have the same value (using DeepEquals) across all the input properties. If it does not then no
1920// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001921// and the field in each of the input properties structure is set to its default value. Nested
1922// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001923func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001924 commonPropertiesValue := reflect.ValueOf(commonProperties)
1925 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001926
Paul Duffinf34f6d82020-04-30 15:48:31 +01001927 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1928
Paul Duffinb28369a2020-05-04 15:39:59 +01001929 for _, property := range e.properties {
1930 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001931 filter := property.filter
1932 if filter == nil {
1933 filter = func(metadata propertiesContainer) bool {
1934 return true
1935 }
1936 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001937
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001938 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001939 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1940 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001941 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001942
Paul Duffin864e1b42020-05-06 10:23:19 +01001943 // Assume that all the values will be the same.
1944 //
1945 // While similar to this is not quite the same as commonValue == nil. If all the values
1946 // have been filtered out then this will be false but commonValue == nil will be true.
1947 valuesDiffer := false
1948
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001949 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001950 container := sliceValue.Index(i).Interface().(propertiesContainer)
1951 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001952 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001953
Paul Duffinc459f892020-04-30 18:08:29 +01001954 if !filter(container) {
1955 expectedValue := property.emptyValue.Interface()
1956 actualValue := fieldValue.Interface()
1957 if !reflect.DeepEqual(expectedValue, actualValue) {
1958 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1959 }
1960 continue
1961 }
1962
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001963 if commonValue == nil {
1964 // Use the first value as the commonProperties value.
1965 commonValue = &fieldValue
1966 } else {
1967 // If the value does not match the current common value then there is
1968 // no value in common so break out.
1969 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1970 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001971 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001972 break
1973 }
1974 }
1975 }
1976
Paul Duffin864e1b42020-05-06 10:23:19 +01001977 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001978 // and set the input struct's field to the empty value.
1979 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001980 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001981 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001982 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001983 container := sliceValue.Index(i).Interface().(propertiesContainer)
1984 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001985 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001986 fieldValue.Set(emptyValue)
1987 }
1988 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001989
1990 if valuesDiffer && !property.archVariant {
1991 // The values differ but the property does not support arch variants so it
1992 // is an error.
1993 var details strings.Builder
1994 for i := 0; i < sliceValue.Len(); i++ {
1995 container := sliceValue.Index(i).Interface().(propertiesContainer)
1996 itemValue := reflect.ValueOf(container.optimizableProperties())
1997 fieldValue := fieldGetter(itemValue)
1998
1999 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2000 }
2001
2002 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2003 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002004 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002005
2006 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002007}