blob: cc06c3b1c139a6c0809578bb2ea92b94e7bc93cf [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 Duffin3e7d3ca2021-09-09 16:37:49 +010025
Paul Duffin375058f2019-11-29 20:17:53 +000026 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090027 "github.com/google/blueprint/proptools"
28
29 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090030)
31
Paul Duffin64fb5262021-05-05 21:36:04 +010032// Environment variables that affect the generated snapshot
33// ========================================================
34//
35// SOONG_SDK_SNAPSHOT_PREFER
36// By default every unversioned module in the generated snapshot has prefer: false. Building it
37// with SOONG_SDK_SNAPSHOT_PREFER=true will force them to use prefer: true.
38//
Paul Duffin973bedb2021-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 Duffin973bedb2021-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 Duffinb645ec82019-11-27 17:43:54 +0000117func (gc *generatedContents) Printfln(format string, args ...interface{}) {
Paul Duffin11108272020-05-11 22:59:25 +0100118 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format+"\n", args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900119}
120
121func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800122 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100123
124 content := gf.content.String()
125
126 // ninja consumes newline characters in rspfile_content. Prevent it by
127 // escaping the backslash in the newline character. The extra backslash
128 // is removed when the rspfile is written to the actual script file
129 content = strings.ReplaceAll(content, "\n", "\\n")
130
Jiyong Park9b409bc2019-10-11 14:59:13 +0900131 rb.Command().
132 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100133 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100134 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900135 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
136 rb.Command().
137 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800138 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900139}
140
Paul Duffin13879572019-11-28 14:31:38 +0000141// Collect all the members.
142//
Paul Duffina1aa7382021-04-29 21:50:40 +0100143// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
144// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000145func (s *sdk) collectMembers(ctx android.ModuleContext) {
146 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000147 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
148 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000149 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100150 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900151
Paul Duffinb3821fe2021-05-26 10:16:01 +0100152 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
153 if memberType == nil {
154 return false
155 }
156
Paul Duffin13879572019-11-28 14:31:38 +0000157 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000158 if !memberType.IsInstance(child) {
159 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900160 }
Paul Duffin13879572019-11-28 14:31:38 +0000161
Paul Duffin6a7e9532020-03-20 17:50:07 +0000162 // Keep track of which multilib variants are used by the sdk.
163 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
164
Paul Duffina1aa7382021-04-29 21:50:40 +0100165 var exportedComponentsInfo android.ExportedComponentsInfo
166 if ctx.OtherModuleHasProvider(child, android.ExportedComponentsInfoProvider) {
167 exportedComponentsInfo = ctx.OtherModuleProvider(child, android.ExportedComponentsInfoProvider).(android.ExportedComponentsInfo)
168 }
169
Paul Duffina7208112021-04-23 21:20:20 +0100170 export := memberTag.ExportMember()
Paul Duffina1aa7382021-04-29 21:50:40 +0100171 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
172 s, memberType, child.(android.SdkAware), export, exportedComponentsInfo,
173 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000174
Paul Duffin2d3da312021-05-06 12:02:27 +0100175 // Recurse down into the member's dependencies as it may have dependencies that need to be
176 // automatically added to the sdk.
177 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900178 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000179
180 return false
Paul Duffin13879572019-11-28 14:31:38 +0000181 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000182}
183
Paul Duffincc3132e2021-04-24 01:10:30 +0100184// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
185// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000186//
Paul Duffincc3132e2021-04-24 01:10:30 +0100187// The sdkMember instances are then grouped into slices by member type. Within each such slice the
188// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000189//
Paul Duffincc3132e2021-04-24 01:10:30 +0100190// Finally, the member type slices are concatenated together to form a single slice. The order in
191// which they are concatenated is the order in which the member types were registered in the
192// android.SdkMemberTypesRegistry.
193func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000194 byType := make(map[android.SdkMemberType][]*sdkMember)
195 byName := make(map[string]*sdkMember)
196
Paul Duffin21827262021-04-24 12:16:36 +0100197 for _, memberVariantDep := range memberVariantDeps {
198 memberType := memberVariantDep.memberType
199 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000200
201 name := ctx.OtherModuleName(variant)
202 member := byName[name]
203 if member == nil {
204 member = &sdkMember{memberType: memberType, name: name}
205 byName[name] = member
206 byType[memberType] = append(byType[memberType], member)
207 }
208
Paul Duffin1356d8c2020-02-25 19:26:33 +0000209 // Only append new variants to the list. This is needed because a member can be both
210 // exported by the sdk and also be a transitive sdk member.
211 member.variants = appendUniqueVariants(member.variants, variant)
212 }
213
Paul Duffin13879572019-11-28 14:31:38 +0000214 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000215 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000216 membersOfType := byType[memberListProperty.memberType]
217 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900218 }
219
Paul Duffin6a7e9532020-03-20 17:50:07 +0000220 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900221}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900222
Paul Duffin72910952020-01-20 18:16:30 +0000223func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
224 for _, v := range variants {
225 if v == newVariant {
226 return variants
227 }
228 }
229 return append(variants, newVariant)
230}
231
Jiyong Park73c54ee2019-10-22 20:31:18 +0900232// SDK directory structure
233// <sdk_root>/
234// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
235// <api_ver>/ : below this directory are all auto-generated
236// Android.bp : definition of 'sdk_snapshot' module is here
237// aidl/
238// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
239// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900240// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900241// include/
242// bionic/libc/include/stdlib.h : an exported header file
243// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900244// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900245// <arch>/include/ : arch-specific exported headers
246// <arch>/include_gen/ : arch-specific generated headers
247// <arch>/lib/
248// libFoo.so : a stub library
249
Jiyong Park232e7852019-11-04 12:23:40 +0900250// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900251// This isn't visible to users, so could be changed in future.
252func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
253 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
254}
255
Jiyong Park232e7852019-11-04 12:23:40 +0900256// buildSnapshot is the main function in this source file. It creates rules to copy
257// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000258func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
259
Paul Duffina1aa7382021-04-29 21:50:40 +0100260 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100261 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100262 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000263 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100264 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffina1aa7382021-04-29 21:50:40 +0100265 }
Paul Duffin865171e2020-03-02 18:38:15 +0000266
Paul Duffina1aa7382021-04-29 21:50:40 +0100267 // Filter out any sdkMemberVariantDep that is a component of another.
268 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000269
Paul Duffina1aa7382021-04-29 21:50:40 +0100270 // Record the names of all the members, both explicitly specified and implicitly
271 // included.
272 allMembersByName := make(map[string]struct{})
273 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100274
Paul Duffina1aa7382021-04-29 21:50:40 +0100275 addMember := func(name string, export bool) {
276 allMembersByName[name] = struct{}{}
277 if export {
278 exportedMembersByName[name] = struct{}{}
279 }
280 }
281
282 for _, memberVariantDep := range memberVariantDeps {
283 name := memberVariantDep.variant.Name()
284 export := memberVariantDep.export
285
286 addMember(name, export)
287
288 // Add any components provided by the module.
289 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
290 addMember(component, export)
291 }
292
293 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
294 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000295 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000296 }
297
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000298 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900299
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000300 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000301
302 bpFile := &bpFile{
303 modules: make(map[string]*bpModule),
304 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000305
Paul Duffin973bedb2021-05-05 22:00:51 +0100306 config := ctx.Config()
307 version := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_VERSION", "current")
308
309 // Generate versioned modules in the snapshot unless an unversioned snapshot has been requested.
310 generateVersioned := version != soongSdkSnapshotVersionUnversioned
311
312 // Generate unversioned modules in the snapshot unless a numbered snapshot has been requested.
313 //
314 // Unversioned modules are not required in that case because the numbered version will be a
315 // finalized version of the snapshot that is intended to be kept separate from the
316 generateUnversioned := version == soongSdkSnapshotVersionUnversioned || version == soongSdkSnapshotVersionCurrent
317 snapshotZipFileSuffix := ""
318 if generateVersioned {
319 snapshotZipFileSuffix = "-" + version
320 }
321
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000322 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000323 ctx: ctx,
324 sdk: s,
Paul Duffin973bedb2021-05-05 22:00:51 +0100325 version: version,
Paul Duffin13f02712020-03-06 12:30:43 +0000326 snapshotDir: snapshotDir.OutputPath,
327 copies: make(map[string]string),
328 filesToZip: []android.Path{bp.path},
329 bpFile: bpFile,
330 prebuiltModules: make(map[string]*bpModule),
331 allMembersByName: allMembersByName,
332 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900333 }
Paul Duffinac37c502019-11-26 18:02:20 +0000334 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900335
Paul Duffin62131702021-05-07 01:10:01 +0100336 // If the sdk snapshot includes any license modules then add a package module which has a
337 // default_applicable_licenses property. That will prevent the LSC license process from updating
338 // the generated Android.bp file to add a package module that includes all licenses used by all
339 // the modules in that package. That would be unnecessary as every module in the sdk should have
340 // their own licenses property specified.
341 if hasLicenses {
342 pkg := bpFile.newModule("package")
343 property := "default_applicable_licenses"
344 pkg.AddCommentForProperty(property, `
345A default list here prevents the license LSC from adding its own list which would
346be unnecessary as every module in the sdk already has its own licenses property.
347`)
348 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
349 bpFile.AddModule(pkg)
350 }
351
Paul Duffin0df49682021-05-07 01:10:01 +0100352 // Group the variants for each member module together and then group the members of each member
353 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100354 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100355
356 // Create the prebuilt modules for each of the member modules.
Paul Duffin13ad94f2020-02-19 16:19:27 +0000357 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000358 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000359
Paul Duffina551a1c2020-03-17 21:04:24 +0000360 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000361
362 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100363 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900364 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900365
Paul Duffine6c0d842020-01-15 14:08:51 +0000366 // Create a transformer that will transform an unversioned module into a versioned module.
367 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
368
Paul Duffin72910952020-01-20 18:16:30 +0000369 // Create a transformer that will transform an unversioned module by replacing any references
370 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100371 unversionedTransformer := unversionedTransformation{
372 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100373 }
Paul Duffin72910952020-01-20 18:16:30 +0000374
Paul Duffinb645ec82019-11-27 17:43:54 +0000375 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000376 // Prune any empty property sets.
377 unversioned = unversioned.transform(pruneEmptySetTransformer{})
378
Paul Duffin973bedb2021-05-05 22:00:51 +0100379 if generateVersioned {
380 // Copy the unversioned module so it can be modified to make it versioned.
381 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000382
Paul Duffin973bedb2021-05-05 22:00:51 +0100383 // Transform the unversioned module into a versioned one.
384 versioned.transform(unversionedToVersionedTransformer)
385 bpFile.AddModule(versioned)
386 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000387
Paul Duffin973bedb2021-05-05 22:00:51 +0100388 if generateUnversioned {
389 // Transform the unversioned module to make it suitable for use in the snapshot.
390 unversioned.transform(unversionedTransformer)
391 bpFile.AddModule(unversioned)
392 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000393 }
394
Paul Duffin973bedb2021-05-05 22:00:51 +0100395 if generateVersioned {
396 // Add the sdk/module_exports_snapshot module to the bp file.
397 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
398 }
Paul Duffin26197a62021-04-24 00:34:10 +0100399
400 // generate Android.bp
401 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
402 generateBpContents(&bp.generatedContents, bpFile)
403
404 contents := bp.content.String()
405 syntaxCheckSnapshotBpFile(ctx, contents)
406
407 bp.build(pctx, ctx, nil)
408
409 filesToZip := builder.filesToZip
410
411 // zip them all
Paul Duffin973bedb2021-05-05 22:00:51 +0100412 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotZipFileSuffix)
413 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100414 outputDesc := "Building snapshot for " + ctx.ModuleName()
415
416 // If there are no zips to merge then generate the output zip directly.
417 // Otherwise, generate an intermediate zip file into which other zips can be
418 // merged.
419 var zipFile android.OutputPath
420 var desc string
421 if len(builder.zipsToMerge) == 0 {
422 zipFile = outputZipFile
423 desc = outputDesc
424 } else {
Paul Duffin973bedb2021-05-05 22:00:51 +0100425 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotZipFileSuffix)
426 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100427 desc = "Building intermediate snapshot for " + ctx.ModuleName()
428 }
429
430 ctx.Build(pctx, android.BuildParams{
431 Description: desc,
432 Rule: zipFiles,
433 Inputs: filesToZip,
434 Output: zipFile,
435 Args: map[string]string{
436 "basedir": builder.snapshotDir.String(),
437 },
438 })
439
440 if len(builder.zipsToMerge) != 0 {
441 ctx.Build(pctx, android.BuildParams{
442 Description: outputDesc,
443 Rule: mergeZips,
444 Input: zipFile,
445 Inputs: builder.zipsToMerge,
446 Output: outputZipFile,
447 })
448 }
449
450 return outputZipFile
451}
452
Paul Duffina1aa7382021-04-29 21:50:40 +0100453// filterOutComponents removes any item from the deps list that is a component of another item in
454// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
455// then it will remove "foo.stubs" from the deps.
456func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
457 // Collate the set of components that all the modules added to the sdk provide.
458 components := map[string]*sdkMemberVariantDep{}
459 for i, _ := range deps {
460 dep := &deps[i]
461 for _, c := range dep.exportedComponentsInfo.Components {
462 components[c] = dep
463 }
464 }
465
466 // If no module provides components then return the input deps unfiltered.
467 if len(components) == 0 {
468 return deps
469 }
470
471 filtered := make([]sdkMemberVariantDep, 0, len(deps))
472 for _, dep := range deps {
473 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
474 if owner, ok := components[name]; ok {
475 // This is a component of another module that is a member of the sdk.
476
477 // If the component is exported but the owning module is not then the configuration is not
478 // supported.
479 if dep.export && !owner.export {
480 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
481 continue
482 }
483
484 // This module must not be added to the list of members of the sdk as that would result in a
485 // duplicate module in the sdk snapshot.
486 continue
487 }
488
489 filtered = append(filtered, dep)
490 }
491 return filtered
492}
493
Paul Duffin26197a62021-04-24 00:34:10 +0100494// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100495func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100496 bpFile := builder.bpFile
497
Paul Duffinb645ec82019-11-27 17:43:54 +0000498 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000499 var snapshotModuleType string
500 if s.properties.Module_exports {
501 snapshotModuleType = "module_exports_snapshot"
502 } else {
503 snapshotModuleType = "sdk_snapshot"
504 }
505 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000506 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000507
508 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100509 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000510 if len(visibility) != 0 {
511 snapshotModule.AddProperty("visibility", visibility)
512 }
513
Paul Duffin865171e2020-03-02 18:38:15 +0000514 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000515
Paul Duffincd064672021-04-24 00:47:29 +0100516 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100517 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000518
Paul Duffin2d1bb892021-04-24 11:32:59 +0100519 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100520
Paul Duffin6a7e9532020-03-20 17:50:07 +0000521 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100522
Paul Duffin2d1bb892021-04-24 11:32:59 +0100523 // Create a mapping from osType to combined properties.
524 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
525 for _, combined := range combinedPropertiesList {
526 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
527 }
528
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100529 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000530 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100531 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100532 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000533
Paul Duffin2d1bb892021-04-24 11:32:59 +0100534 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000535 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000536 }
Paul Duffin865171e2020-03-02 18:38:15 +0000537
Jiyong Park8fe14e62020-10-19 22:47:34 +0900538 // If host is supported and any member is host OS dependent then disable host
539 // by default, so that we can enable each host OS variant explicitly. This
540 // avoids problems with implicitly enabled OS variants when the snapshot is
541 // used, which might be different from this run (e.g. different build OS).
542 if s.HostSupported() {
543 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100544 for _, memberVariantDep := range memberVariantDeps {
545 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
546 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900547 if !android.InList(targetString, supportedHostTargets) {
548 supportedHostTargets = append(supportedHostTargets, targetString)
549 }
550 }
551 }
552 if len(supportedHostTargets) > 0 {
553 hostPropertySet := targetPropertySet.AddPropertySet("host")
554 hostPropertySet.AddProperty("enabled", false)
555 }
556 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
557 for _, hostTarget := range supportedHostTargets {
558 propertySet := targetPropertySet.AddPropertySet(hostTarget)
559 propertySet.AddProperty("enabled", true)
560 }
561 }
562
Paul Duffin865171e2020-03-02 18:38:15 +0000563 // Prune any empty property sets.
564 snapshotModule.transform(pruneEmptySetTransformer{})
565
Paul Duffinb645ec82019-11-27 17:43:54 +0000566 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900567}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000568
Paul Duffinf88d8e02020-05-07 20:21:34 +0100569// Check the syntax of the generated Android.bp file contents and if they are
570// invalid then log an error with the contents (tagged with line numbers) and the
571// errors that were found so that it is easy to see where the problem lies.
572func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
573 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
574 if len(errs) != 0 {
575 message := &strings.Builder{}
576 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
577
578Generated Android.bp contents
579========================================================================
580`)
581 for i, line := range strings.Split(contents, "\n") {
582 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
583 }
584
585 _, _ = fmt.Fprint(message, `
586========================================================================
587
588Errors found:
589`)
590
591 for _, err := range errs {
592 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
593 }
594
595 ctx.ModuleErrorf("%s", message.String())
596 }
597}
598
Paul Duffin4b8b7932020-05-06 12:35:38 +0100599func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
600 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
601 if err != nil {
602 ctx.ModuleErrorf("error extracting common properties: %s", err)
603 }
604}
605
Paul Duffinfbe470e2021-04-24 12:37:13 +0100606// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
607type snapshotModuleStaticProperties struct {
608 Compile_multilib string `android:"arch_variant"`
609}
610
Paul Duffin2d1bb892021-04-24 11:32:59 +0100611// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
612type combinedSnapshotModuleProperties struct {
613 // The sdk variant from which this information was collected.
614 sdkVariant *sdk
615
616 // Static snapshot module properties.
617 staticProperties *snapshotModuleStaticProperties
618
619 // The dynamically generated member list properties.
620 dynamicProperties interface{}
621}
622
623// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100624func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
625 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100626 var list []*combinedSnapshotModuleProperties
627 for _, sdkVariant := range sdkVariants {
628 staticProperties := &snapshotModuleStaticProperties{
629 Compile_multilib: sdkVariant.multilibUsages.String(),
630 }
Paul Duffincd064672021-04-24 00:47:29 +0100631 dynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100632
Paul Duffincd064672021-04-24 00:47:29 +0100633 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100634 sdkVariant: sdkVariant,
635 staticProperties: staticProperties,
636 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100637 }
638 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
639
640 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100641 }
Paul Duffincd064672021-04-24 00:47:29 +0100642
643 for _, memberVariantDep := range memberVariantDeps {
644 // If the member dependency is internal then do not add the dependency to the snapshot member
645 // list properties.
646 if !memberVariantDep.export {
647 continue
648 }
649
650 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin13082052021-05-11 00:31:38 +0100651 memberListProperty := s.memberListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100652 memberName := ctx.OtherModuleName(memberVariantDep.variant)
653
Paul Duffin13082052021-05-11 00:31:38 +0100654 if memberListProperty.getter == nil {
655 continue
656 }
657
Paul Duffincd064672021-04-24 00:47:29 +0100658 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100659 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100660 if !android.InList(memberName, memberList) {
661 memberList = append(memberList, memberName)
662 }
Paul Duffin13082052021-05-11 00:31:38 +0100663 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100664 }
665
Paul Duffin2d1bb892021-04-24 11:32:59 +0100666 return list
667}
668
669func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
670
671 // Extract the dynamic properties and add them to a list of propertiesContainer.
672 propertyContainers := []propertiesContainer{}
673 for _, i := range list {
674 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
675 sdkVariant: i.sdkVariant,
676 properties: i.dynamicProperties,
677 })
678 }
679
680 // Extract the common members, removing them from the original properties.
681 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
682 extractor := newCommonValueExtractor(commonDynamicProperties)
683 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
684
685 // Extract the static properties and add them to a list of propertiesContainer.
686 propertyContainers = []propertiesContainer{}
687 for _, i := range list {
688 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
689 sdkVariant: i.sdkVariant,
690 properties: i.staticProperties,
691 })
692 }
693
694 commonStaticProperties := &snapshotModuleStaticProperties{}
695 extractor = newCommonValueExtractor(commonStaticProperties)
696 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
697
698 return &combinedSnapshotModuleProperties{
699 sdkVariant: nil,
700 staticProperties: commonStaticProperties,
701 dynamicProperties: commonDynamicProperties,
702 }
703}
704
705func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
706 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100707 multilib := staticProperties.Compile_multilib
708 if multilib != "" && multilib != "both" {
709 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
710 propertySet.AddProperty("compile_multilib", multilib)
711 }
712
Paul Duffin2d1bb892021-04-24 11:32:59 +0100713 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin865171e2020-03-02 18:38:15 +0000714 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100715 if memberListProperty.getter == nil {
716 continue
717 }
Paul Duffin865171e2020-03-02 18:38:15 +0000718 names := memberListProperty.getter(dynamicMemberTypeListProperties)
719 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000720 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000721 }
722 }
723}
724
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000725type propertyTag struct {
726 name string
727}
728
Paul Duffin0cb37b92020-03-04 14:52:46 +0000729// A BpPropertyTag to add to a property that contains references to other sdk members.
730//
731// This will cause the references to be rewritten to a versioned reference in the version
732// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000733var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000734var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000735
Paul Duffin0cb37b92020-03-04 14:52:46 +0000736// A BpPropertyTag that indicates the property should only be present in the versioned
737// module.
738//
739// This will cause the property to be removed from the unversioned instance of a
740// snapshot module.
741var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
742
Paul Duffine6c0d842020-01-15 14:08:51 +0000743type unversionedToVersionedTransformation struct {
744 identityTransformation
745 builder *snapshotBuilder
746}
747
Paul Duffine6c0d842020-01-15 14:08:51 +0000748func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
749 // Use a versioned name for the module but remember the original name for the
750 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100751 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000752 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000753 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100754 // Remove the prefer property if present as versioned modules never need marking with prefer.
755 module.removeProperty("prefer")
Paul Duffine6c0d842020-01-15 14:08:51 +0000756 return module
757}
758
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000759func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000760 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
761 required := tag == requiredSdkMemberReferencePropertyTag
762 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000763 } else {
764 return value, tag
765 }
766}
767
Paul Duffin72910952020-01-20 18:16:30 +0000768type unversionedTransformation struct {
769 identityTransformation
770 builder *snapshotBuilder
771}
772
773func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
774 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100775 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000776 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000777 return module
778}
779
780func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000781 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
782 required := tag == requiredSdkMemberReferencePropertyTag
783 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000784 } else if tag == sdkVersionedOnlyPropertyTag {
785 // The property is not allowed in the unversioned module so remove it.
786 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000787 } else {
788 return value, tag
789 }
790}
791
Paul Duffina78f3a72020-02-21 16:29:35 +0000792type pruneEmptySetTransformer struct {
793 identityTransformation
794}
795
796var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
797
798func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
799 if len(propertySet.properties) == 0 {
800 return nil, nil
801 } else {
802 return propertySet, tag
803 }
804}
805
Paul Duffinb645ec82019-11-27 17:43:54 +0000806func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000807 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
808 return true
809 })
810}
811
812func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffinb645ec82019-11-27 17:43:54 +0000813 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
814 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000815 if moduleFilter(bpModule) {
816 contents.Printfln("")
817 contents.Printfln("%s {", bpModule.moduleType)
818 outputPropertySet(contents, bpModule.bpPropertySet)
819 contents.Printfln("}")
820 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000821 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000822}
823
824func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
825 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000826
Paul Duffin0df49682021-05-07 01:10:01 +0100827 addComment := func(name string) {
828 if text, ok := set.comments[name]; ok {
829 for _, line := range strings.Split(text, "\n") {
830 contents.Printfln("// %s", line)
831 }
832 }
833 }
834
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000835 // Output the properties first, followed by the nested sets. This ensures a
836 // consistent output irrespective of whether property sets are created before
837 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000838 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000839 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000840
Paul Duffin0df49682021-05-07 01:10:01 +0100841 // Do not write property sets in the properties phase.
842 if _, ok := value.(*bpPropertySet); ok {
843 continue
844 }
845
846 addComment(name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000847 switch v := value.(type) {
848 case []string:
849 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000850 if length > 1 {
851 contents.Printfln("%s: [", name)
852 contents.Indent()
853 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000854 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000855 }
856 contents.Dedent()
857 contents.Printfln("],")
858 } else if length == 0 {
859 contents.Printfln("%s: [],", name)
860 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000861 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000862 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000863
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000864 case bool:
865 contents.Printfln("%s: %t,", name, v)
866
Paul Duffinb645ec82019-11-27 17:43:54 +0000867 default:
868 contents.Printfln("%s: %q,", name, value)
869 }
870 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000871
872 for _, name := range set.order {
873 value := set.getValue(name)
874
875 // Only write property sets in the sets phase.
876 switch v := value.(type) {
877 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100878 addComment(name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000879 contents.Printfln("%s: {", name)
880 outputPropertySet(contents, v)
881 contents.Printfln("},")
882 }
883 }
884
Paul Duffinb645ec82019-11-27 17:43:54 +0000885 contents.Dedent()
886}
887
Paul Duffinac37c502019-11-26 18:02:20 +0000888func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000889 contents := &generatedContents{}
890 generateBpContents(contents, s.builderForTests.bpFile)
891 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000892}
893
Paul Duffind0759072021-02-17 11:23:00 +0000894func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
895 contents := &generatedContents{}
896 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100897 name := module.Name()
898 // Include modules that are either unversioned or have no name.
899 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000900 })
901 return contents.content.String()
902}
903
904func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
905 contents := &generatedContents{}
906 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100907 name := module.Name()
908 // Include modules that are either versioned or have no name.
909 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000910 })
911 return contents.content.String()
912}
913
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000914type snapshotBuilder struct {
Paul Duffin973bedb2021-05-05 22:00:51 +0100915 ctx android.ModuleContext
916 sdk *sdk
917
918 // The version of the generated snapshot.
919 //
920 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
921 // this field.
922 version string
923
Paul Duffinb645ec82019-11-27 17:43:54 +0000924 snapshotDir android.OutputPath
925 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000926
927 // Map from destination to source of each copy - used to eliminate duplicates and
928 // detect conflicts.
929 copies map[string]string
930
Paul Duffinb645ec82019-11-27 17:43:54 +0000931 filesToZip android.Paths
932 zipsToMerge android.Paths
933
934 prebuiltModules map[string]*bpModule
935 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000936
937 // The set of all members by name.
938 allMembersByName map[string]struct{}
939
940 // The set of exported members by name.
941 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000942}
943
944func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000945 if existing, ok := s.copies[dest]; ok {
946 if existing != src.String() {
947 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
948 return
949 }
950 } else {
951 path := s.snapshotDir.Join(s.ctx, dest)
952 s.ctx.Build(pctx, android.BuildParams{
953 Rule: android.Cp,
954 Input: src,
955 Output: path,
956 })
957 s.filesToZip = append(s.filesToZip, path)
958
959 s.copies[dest] = src.String()
960 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000961}
962
Paul Duffin91547182019-11-12 19:39:36 +0000963func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
964 ctx := s.ctx
965
966 // Repackage the zip file so that the entries are in the destDir directory.
967 // This will allow the zip file to be merged into the snapshot.
968 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000969
970 ctx.Build(pctx, android.BuildParams{
971 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
972 Rule: repackageZip,
973 Input: zipPath,
974 Output: tmpZipPath,
975 Args: map[string]string{
976 "destdir": destDir,
977 },
978 })
Paul Duffin91547182019-11-12 19:39:36 +0000979
980 // Add the repackaged zip file to the files to merge.
981 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
982}
983
Paul Duffin9d8d6092019-12-05 18:19:29 +0000984func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
985 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000986 if s.prebuiltModules[name] != nil {
987 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
988 }
989
990 m := s.bpFile.newModule(moduleType)
991 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000992
Paul Duffinbefa4b92020-03-04 14:22:45 +0000993 variant := member.Variants()[0]
994
Paul Duffin13f02712020-03-06 12:30:43 +0000995 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000996 // An internal member is only referenced from the sdk snapshot which is in the
997 // same package so can be marked as private.
998 m.AddProperty("visibility", []string{"//visibility:private"})
999 } else {
1000 // Extract visibility information from a member variant. All variants have the same
1001 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001002 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1003
1004 // Add any additional visibility rules needed for the prebuilts to reference each other.
1005 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1006 if err != nil {
1007 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1008 }
1009
1010 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001011 if len(visibility) != 0 {
1012 m.AddProperty("visibility", visibility)
1013 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001014 }
1015
Martin Stjernholm1e041092020-11-03 00:11:09 +00001016 // Where available copy apex_available properties from the member.
1017 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1018 apexAvailable := apexAware.ApexAvailable()
1019 if len(apexAvailable) == 0 {
1020 // //apex_available:platform is the default.
1021 apexAvailable = []string{android.AvailableToPlatform}
1022 }
1023
1024 // Add in any baseline apex available settings.
1025 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1026
1027 // Remove duplicates and sort.
1028 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1029 sort.Strings(apexAvailable)
1030
1031 m.AddProperty("apex_available", apexAvailable)
1032 }
1033
Paul Duffinb0bb3762021-05-06 16:48:05 +01001034 // The licenses are the same for all variants.
1035 mctx := s.ctx
1036 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1037 if len(licenseInfo.Licenses) > 0 {
1038 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1039 }
1040
Paul Duffin865171e2020-03-02 18:38:15 +00001041 deviceSupported := false
1042 hostSupported := false
1043
1044 for _, variant := range member.Variants() {
1045 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001046 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001047 hostSupported = true
1048 } else if osClass == android.Device {
1049 deviceSupported = true
1050 }
1051 }
1052
1053 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001054
Paul Duffin0cb37b92020-03-04 14:52:46 +00001055 // Disable installation in the versioned module of those modules that are ever installable.
1056 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1057 if installable.EverInstallable() {
1058 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1059 }
1060 }
1061
Paul Duffinb645ec82019-11-27 17:43:54 +00001062 s.prebuiltModules[name] = m
1063 s.prebuiltOrder = append(s.prebuiltOrder, m)
1064 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001065}
1066
Paul Duffin865171e2020-03-02 18:38:15 +00001067func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001068 // If neither device or host is supported then this module does not support either so will not
1069 // recognize the properties.
1070 if !deviceSupported && !hostSupported {
1071 return
1072 }
1073
Paul Duffin865171e2020-03-02 18:38:15 +00001074 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001075 bpModule.AddProperty("device_supported", false)
1076 }
Paul Duffin865171e2020-03-02 18:38:15 +00001077 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001078 bpModule.AddProperty("host_supported", true)
1079 }
1080}
1081
Paul Duffin13f02712020-03-06 12:30:43 +00001082func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1083 if required {
1084 return requiredSdkMemberReferencePropertyTag
1085 } else {
1086 return optionalSdkMemberReferencePropertyTag
1087 }
1088}
1089
1090func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1091 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001092}
1093
Paul Duffinb645ec82019-11-27 17:43:54 +00001094// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001095func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1096 if _, ok := s.allMembersByName[unversionedName]; !ok {
1097 if required {
1098 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1099 }
1100 return unversionedName
1101 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001102 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1103}
Paul Duffinb645ec82019-11-27 17:43:54 +00001104
Paul Duffin13f02712020-03-06 12:30:43 +00001105func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001106 var references []string = nil
1107 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001108 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001109 }
1110 return references
1111}
Paul Duffin13879572019-11-28 14:31:38 +00001112
Paul Duffin72910952020-01-20 18:16:30 +00001113// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001114func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1115 if _, ok := s.allMembersByName[unversionedName]; !ok {
1116 if required {
1117 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1118 }
1119 return unversionedName
1120 }
1121
1122 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001123 return s.ctx.ModuleName() + "_" + unversionedName
1124 } else {
1125 return unversionedName
1126 }
1127}
1128
Paul Duffin13f02712020-03-06 12:30:43 +00001129func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001130 var references []string = nil
1131 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001132 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001133 }
1134 return references
1135}
1136
Paul Duffin13f02712020-03-06 12:30:43 +00001137func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1138 _, ok := s.exportedMembersByName[memberName]
1139 return !ok
1140}
1141
Martin Stjernholm89238f42020-07-10 00:14:03 +01001142// Add the properties from the given SdkMemberProperties to the blueprint
1143// property set. This handles common properties in SdkMemberPropertiesBase and
1144// calls the member-specific AddToPropertySet for the rest.
1145func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1146 if memberProperties.Base().Compile_multilib != "" {
1147 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1148 }
1149
1150 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1151}
1152
Paul Duffin21827262021-04-24 12:16:36 +01001153// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1154type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001155 // The sdk variant that depends (possibly indirectly) on the member variant.
1156 sdkVariant *sdk
Paul Duffina1aa7382021-04-29 21:50:40 +01001157
1158 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001159 memberType android.SdkMemberType
Paul Duffina1aa7382021-04-29 21:50:40 +01001160
1161 // The variant that is added to the sdk.
1162 variant android.SdkAware
1163
1164 // True if the member should be exported, i.e. accessible, from outside the sdk.
1165 export bool
1166
1167 // The names of additional component modules provided by the variant.
1168 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001169}
1170
Paul Duffin13879572019-11-28 14:31:38 +00001171var _ android.SdkMember = (*sdkMember)(nil)
1172
Paul Duffin21827262021-04-24 12:16:36 +01001173// sdkMember groups all the variants of a specific member module together along with the name of the
1174// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001175type sdkMember struct {
1176 memberType android.SdkMemberType
1177 name string
1178 variants []android.SdkAware
1179}
1180
1181func (m *sdkMember) Name() string {
1182 return m.name
1183}
1184
1185func (m *sdkMember) Variants() []android.SdkAware {
1186 return m.variants
1187}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001188
Paul Duffin9c3760e2020-03-16 19:52:08 +00001189// Track usages of multilib variants.
1190type multilibUsage int
1191
1192const (
1193 multilibNone multilibUsage = 0
1194 multilib32 multilibUsage = 1
1195 multilib64 multilibUsage = 2
1196 multilibBoth = multilib32 | multilib64
1197)
1198
1199// Add the multilib that is used in the arch type.
1200func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1201 multilib := archType.Multilib
1202 switch multilib {
1203 case "":
1204 return m
1205 case "lib32":
1206 return m | multilib32
1207 case "lib64":
1208 return m | multilib64
1209 default:
1210 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1211 }
1212}
1213
1214func (m multilibUsage) String() string {
1215 switch m {
1216 case multilibNone:
1217 return ""
1218 case multilib32:
1219 return "32"
1220 case multilib64:
1221 return "64"
1222 case multilibBoth:
1223 return "both"
1224 default:
1225 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1226 m, multilibNone, multilib32, multilib64, multilibBoth))
1227 }
1228}
1229
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001230type baseInfo struct {
1231 Properties android.SdkMemberProperties
1232}
1233
Paul Duffinf34f6d82020-04-30 15:48:31 +01001234func (b *baseInfo) optimizableProperties() interface{} {
1235 return b.Properties
1236}
1237
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001238type osTypeSpecificInfo struct {
1239 baseInfo
1240
Paul Duffin00e46802020-03-12 20:40:35 +00001241 osType android.OsType
1242
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001243 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001244 //
1245 // Nil if there is one variant whose arch type is common
1246 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001247}
1248
Paul Duffin4b8b7932020-05-06 12:35:38 +01001249var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1250
Paul Duffinfc8dd232020-03-17 12:51:37 +00001251type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1252
Paul Duffin00e46802020-03-12 20:40:35 +00001253// Create a new osTypeSpecificInfo for the specified os type and its properties
1254// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001255func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001256 osInfo := &osTypeSpecificInfo{
1257 osType: osType,
1258 }
1259
1260 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1261 properties := variantPropertiesFactory()
1262 properties.Base().Os = osType
1263 return properties
1264 }
1265
1266 // Create a structure into which properties common across the architectures in
1267 // this os type will be stored.
1268 osInfo.Properties = osSpecificVariantPropertiesFactory()
1269
1270 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001271 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001272 var archTypes []android.ArchType
1273 for _, variant := range osTypeVariants {
1274 archType := variant.Target().Arch.ArchType
1275 archTypeName := archType.Name
1276 if _, ok := variantsByArchName[archTypeName]; !ok {
1277 archTypes = append(archTypes, archType)
1278 }
1279
1280 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1281 }
1282
1283 if commonVariants, ok := variantsByArchName["common"]; ok {
1284 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001285 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 +00001286 }
1287
1288 // A common arch type only has one variant and its properties should be treated
1289 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001290 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001291 } else {
1292 // Create an arch specific info for each supported architecture type.
1293 for _, archType := range archTypes {
1294 archTypeName := archType.Name
1295
1296 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001297 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001298
1299 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1300 }
1301 }
1302
1303 return osInfo
1304}
1305
1306// Optimize the properties by extracting common properties from arch type specific
1307// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001308func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001309 // Nothing to do if there is only a single common architecture.
1310 if len(osInfo.archInfos) == 0 {
1311 return
1312 }
1313
Paul Duffin9c3760e2020-03-16 19:52:08 +00001314 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001315 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001316 multilib = multilib.addArchType(archInfo.archType)
1317
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001318 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001319 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001320 }
1321
Paul Duffin4b8b7932020-05-06 12:35:38 +01001322 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001323
1324 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001325 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001326}
1327
1328// Add the properties for an os to a property set.
1329//
1330// Maps the properties related to the os variants through to an appropriate
1331// module structure that will produce equivalent set of variants when it is
1332// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001333func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001334
1335 var osPropertySet android.BpPropertySet
1336 var archPropertySet android.BpPropertySet
1337 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001338 if osInfo.Properties.Base().Os_count == 1 &&
1339 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1340 // There is only one OS type present in the variants and it shouldn't have a
1341 // variant-specific target. The latter is the case if it's either for device
1342 // where there is only one OS (android), or for host and the member type
1343 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001344
1345 // Create a structure that looks like:
1346 // module_type {
1347 // name: "...",
1348 // ...
1349 // <common properties>
1350 // ...
1351 // <single os type specific properties>
1352 //
1353 // arch: {
1354 // <arch specific sections>
1355 // }
1356 //
1357 osPropertySet = bpModule
1358 archPropertySet = osPropertySet.AddPropertySet("arch")
1359
1360 // Arch specific properties need to be added to an arch specific section
1361 // within arch.
1362 archOsPrefix = ""
1363 } else {
1364 // Create a structure that looks like:
1365 // module_type {
1366 // name: "...",
1367 // ...
1368 // <common properties>
1369 // ...
1370 // target: {
1371 // <arch independent os specific sections, e.g. android>
1372 // ...
1373 // <arch and os specific sections, e.g. android_x86>
1374 // }
1375 //
1376 osType := osInfo.osType
1377 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1378 archPropertySet = targetPropertySet
1379
1380 // Arch specific properties need to be added to an os and arch specific
1381 // section prefixed with <os>_.
1382 archOsPrefix = osType.Name + "_"
1383 }
1384
1385 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001386 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001387
1388 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1389 // os) specific properties.
1390 //
1391 // The archInfos list will be empty if the os contains variants for the common
1392 // architecture.
1393 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001394 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001395 }
1396}
1397
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001398func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1399 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001400 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001401}
1402
1403var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1404
Paul Duffin4b8b7932020-05-06 12:35:38 +01001405func (osInfo *osTypeSpecificInfo) String() string {
1406 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1407}
1408
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001409type archTypeSpecificInfo struct {
1410 baseInfo
1411
1412 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001413 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001414
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001415 imageVariantInfos []*imageVariantSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001416}
1417
Paul Duffin4b8b7932020-05-06 12:35:38 +01001418var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1419
Paul Duffinfc8dd232020-03-17 12:51:37 +00001420// Create a new archTypeSpecificInfo for the specified arch type and its properties
1421// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001422func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001423
Paul Duffinfc8dd232020-03-17 12:51:37 +00001424 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001425 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001426
1427 // Create the properties into which the arch type specific properties will be
1428 // added.
1429 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001430
1431 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001432 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001433 } else {
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001434 // Group the variants by image type.
1435 variantsByImage := make(map[string][]android.Module)
1436 for _, variant := range archVariants {
1437 image := variant.ImageVariation().Variation
1438 variantsByImage[image] = append(variantsByImage[image], variant)
1439 }
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001440
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001441 // Create the image variant info in a fixed order.
1442 for _, imageVariantName := range android.SortedStringKeys(variantsByImage) {
1443 variants := variantsByImage[imageVariantName]
1444 archInfo.imageVariantInfos = append(archInfo.imageVariantInfos, newImageVariantSpecificInfo(ctx, imageVariantName, variantPropertiesFactory, variants))
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001445 }
1446 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001447
1448 return archInfo
1449}
1450
Paul Duffinf34f6d82020-04-30 15:48:31 +01001451func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1452 return archInfo.Properties
1453}
1454
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001455// Get the link type of the variant
1456//
1457// If the variant is not differentiated by link type then it returns "",
1458// otherwise it returns one of "static" or "shared".
1459func getLinkType(variant android.Module) string {
1460 linkType := ""
1461 if linkable, ok := variant.(cc.LinkableInterface); ok {
1462 if linkable.Shared() && linkable.Static() {
1463 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1464 } else if linkable.Shared() {
1465 linkType = "shared"
1466 } else if linkable.Static() {
1467 linkType = "static"
1468 } else {
1469 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1470 }
1471 }
1472 return linkType
1473}
1474
1475// Optimize the properties by extracting common properties from link type specific
1476// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001477func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001478 if len(archInfo.imageVariantInfos) == 0 {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001479 return
1480 }
1481
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001482 // Optimize the image variant properties first.
1483 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1484 imageVariantInfo.optimizeProperties(ctx, commonValueExtractor)
1485 }
1486
1487 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.imageVariantInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001488}
1489
Paul Duffinfc8dd232020-03-17 12:51:37 +00001490// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001491func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001492 archTypeName := archInfo.archType.Name
1493 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001494 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1495 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1496 archTypePropertySet.AddProperty("enabled", true)
1497 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001498 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001499
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001500 for _, imageVariantInfo := range archInfo.imageVariantInfos {
1501 imageVariantInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001502 }
1503}
1504
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001505// getPropertySetContents returns the string representation of the contents of a property set, after
1506// recursively pruning any empty nested property sets.
1507func getPropertySetContents(propertySet android.BpPropertySet) string {
1508 set := propertySet.(*bpPropertySet)
1509 set.transformContents(pruneEmptySetTransformer{})
1510 if len(set.properties) != 0 {
1511 contents := &generatedContents{}
1512 contents.Indent()
1513 outputPropertySet(contents, set)
1514 setAsString := contents.content.String()
1515 return setAsString
1516 }
1517 return ""
1518}
1519
Paul Duffin4b8b7932020-05-06 12:35:38 +01001520func (archInfo *archTypeSpecificInfo) String() string {
1521 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1522}
1523
Paul Duffin3e7d3ca2021-09-09 16:37:49 +01001524type imageVariantSpecificInfo struct {
1525 baseInfo
1526
1527 imageVariant string
1528
1529 linkInfos []*linkTypeSpecificInfo
1530}
1531
1532func newImageVariantSpecificInfo(ctx android.SdkMemberContext, imageVariant string, variantPropertiesFactory variantPropertiesFactoryFunc, imageVariants []android.Module) *imageVariantSpecificInfo {
1533
1534 // Create an image variant specific info into which the variant properties can be copied.
1535 imageInfo := &imageVariantSpecificInfo{imageVariant: imageVariant}
1536
1537 // Create the properties into which the image variant specific properties will be added.
1538 imageInfo.Properties = variantPropertiesFactory()
1539
1540 if len(imageVariants) == 1 {
1541 imageInfo.Properties.PopulateFromVariant(ctx, imageVariants[0])
1542 } else {
1543 // There is more than one variant for this image variant which must be differentiated by link
1544 // type.
1545 for _, linkVariant := range imageVariants {
1546 linkType := getLinkType(linkVariant)
1547 if linkType == "" {
1548 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(imageVariants)))
1549 } else {
1550 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
1551
1552 imageInfo.linkInfos = append(imageInfo.linkInfos, linkInfo)
1553 }
1554 }
1555 }
1556
1557 return imageInfo
1558}
1559
1560// Optimize the properties by extracting common properties from link type specific
1561// properties into arch type specific properties.
1562func (imageInfo *imageVariantSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
1563 if len(imageInfo.linkInfos) == 0 {
1564 return
1565 }
1566
1567 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, imageInfo.Properties, imageInfo.linkInfos)
1568}
1569
1570// Add the properties for an arch type to a property set.
1571func (imageInfo *imageVariantSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1572 if imageInfo.imageVariant != android.CoreVariation {
1573 propertySet = propertySet.AddPropertySet(imageInfo.imageVariant)
1574 }
1575
1576 addSdkMemberPropertiesToSet(ctx, imageInfo.Properties, propertySet)
1577
1578 for _, linkInfo := range imageInfo.linkInfos {
1579 linkInfo.addToPropertySet(ctx, propertySet)
1580 }
1581
1582 // If this is for a non-core image variant then make sure that the property set does not contain
1583 // any properties as providing non-core image variant specific properties for prebuilts is not
1584 // currently supported.
1585 if imageInfo.imageVariant != android.CoreVariation {
1586 propertySetContents := getPropertySetContents(propertySet)
1587 if propertySetContents != "" {
1588 ctx.SdkModuleContext().ModuleErrorf("Image variant %q of sdk member %q has properties distinct from other variants; this is not yet supported. The properties are:\n%s",
1589 imageInfo.imageVariant, ctx.name, propertySetContents)
1590 }
1591 }
1592}
1593
1594func (imageInfo *imageVariantSpecificInfo) String() string {
1595 return imageInfo.imageVariant
1596}
1597
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001598type linkTypeSpecificInfo struct {
1599 baseInfo
1600
1601 linkType string
1602}
1603
Paul Duffin4b8b7932020-05-06 12:35:38 +01001604var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1605
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001606// Create a new linkTypeSpecificInfo for the specified link type and its properties
1607// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001608func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001609 linkInfo := &linkTypeSpecificInfo{
1610 baseInfo: baseInfo{
1611 // Create the properties into which the link type specific properties will be
1612 // added.
1613 Properties: variantPropertiesFactory(),
1614 },
1615 linkType: linkType,
1616 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001617 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001618 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001619}
1620
Paul Duffinc5662552021-09-09 16:11:42 +01001621func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1622 linkPropertySet := propertySet.AddPropertySet(l.linkType)
1623 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
1624}
1625
Paul Duffin4b8b7932020-05-06 12:35:38 +01001626func (l *linkTypeSpecificInfo) String() string {
1627 return fmt.Sprintf("LinkType{%s}", l.linkType)
1628}
1629
Paul Duffin3a4eb502020-03-19 16:11:18 +00001630type memberContext struct {
1631 sdkMemberContext android.ModuleContext
1632 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001633 memberType android.SdkMemberType
1634 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001635}
1636
1637func (m *memberContext) SdkModuleContext() android.ModuleContext {
1638 return m.sdkMemberContext
1639}
1640
1641func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1642 return m.builder
1643}
1644
Paul Duffina551a1c2020-03-17 21:04:24 +00001645func (m *memberContext) MemberType() android.SdkMemberType {
1646 return m.memberType
1647}
1648
1649func (m *memberContext) Name() string {
1650 return m.name
1651}
1652
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001653func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001654
1655 memberType := member.memberType
1656
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001657 // Do not add the prefer property if the member snapshot module is a source module type.
1658 if !memberType.UsesSourceModuleTypeInSnapshot() {
1659 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1660 // snapshot to be created that sets prefer: true.
1661 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1662 // dynamically at build time not at snapshot generation time.
1663 prefer := ctx.sdkMemberContext.Config().IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001664
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001665 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1666 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1667 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1668 // behavior is for the module.
1669 bpModule.insertAfter("name", "prefer", prefer)
1670 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001671
Paul Duffina04c1072020-03-02 10:16:35 +00001672 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001673 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001674 variants := member.Variants()
1675 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001676 osType := variant.Target().Os
1677 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001678 }
1679
Paul Duffina04c1072020-03-02 10:16:35 +00001680 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001681 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001682 properties := memberType.CreateVariantPropertiesStruct()
1683 base := properties.Base()
1684 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001685 return properties
1686 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001687
Paul Duffina04c1072020-03-02 10:16:35 +00001688 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001689
Paul Duffina04c1072020-03-02 10:16:35 +00001690 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001691 commonProperties := variantPropertiesFactory()
1692 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001693
Paul Duffinc097e362020-03-10 22:50:03 +00001694 // Create common value extractor that can be used to optimize the properties.
1695 commonValueExtractor := newCommonValueExtractor(commonProperties)
1696
Paul Duffina04c1072020-03-02 10:16:35 +00001697 // The list of property structures which are os type specific but common across
1698 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001699 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001700
1701 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001702 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001703 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001704 // Add the os specific properties to a list of os type specific yet architecture
1705 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001706 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001707
Paul Duffin00e46802020-03-12 20:40:35 +00001708 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001709 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001710 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001711
Paul Duffina04c1072020-03-02 10:16:35 +00001712 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001713 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001714
Paul Duffina04c1072020-03-02 10:16:35 +00001715 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001716 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001717
Paul Duffina04c1072020-03-02 10:16:35 +00001718 // Create a target property set into which target specific properties can be
1719 // added.
1720 targetPropertySet := bpModule.AddPropertySet("target")
1721
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001722 // If the member is host OS dependent and has host_supported then disable by
1723 // default and enable each host OS variant explicitly. This avoids problems
1724 // with implicitly enabled OS variants when the snapshot is used, which might
1725 // be different from this run (e.g. different build OS).
1726 if ctx.memberType.IsHostOsDependent() {
1727 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1728 if hostSupported {
1729 hostPropertySet := targetPropertySet.AddPropertySet("host")
1730 hostPropertySet.AddProperty("enabled", false)
1731 }
1732 }
1733
Paul Duffina04c1072020-03-02 10:16:35 +00001734 // Iterate over the os types in a fixed order.
1735 for _, osType := range s.getPossibleOsTypes() {
1736 osInfo := osTypeToInfo[osType]
1737 if osInfo == nil {
1738 continue
1739 }
1740
Paul Duffin3a4eb502020-03-19 16:11:18 +00001741 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001742 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001743}
1744
Paul Duffina04c1072020-03-02 10:16:35 +00001745// Compute the list of possible os types that this sdk could support.
1746func (s *sdk) getPossibleOsTypes() []android.OsType {
1747 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001748 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001749 if s.DeviceSupported() {
1750 if osType.Class == android.Device && osType != android.Fuchsia {
1751 osTypes = append(osTypes, osType)
1752 }
1753 }
1754 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001755 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001756 osTypes = append(osTypes, osType)
1757 }
1758 }
1759 }
1760 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1761 return osTypes
1762}
1763
Paul Duffinb28369a2020-05-04 15:39:59 +01001764// Given a set of properties (struct value), return the value of the field within that
1765// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001766type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1767
Paul Duffinc459f892020-04-30 18:08:29 +01001768// Checks the metadata to determine whether the property should be ignored for the
1769// purposes of common value extraction or not.
1770type extractorMetadataPredicate func(metadata propertiesContainer) bool
1771
1772// Indicates whether optimizable properties are provided by a host variant or
1773// not.
1774type isHostVariant interface {
1775 isHostVariant() bool
1776}
1777
Paul Duffinb28369a2020-05-04 15:39:59 +01001778// A property that can be optimized by the commonValueExtractor.
1779type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001780 // The name of the field for this property. It is a "."-separated path for
1781 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001782 name string
1783
Paul Duffinc459f892020-04-30 18:08:29 +01001784 // Filter that can use metadata associated with the properties being optimized
1785 // to determine whether the field should be ignored during common value
1786 // optimization.
1787 filter extractorMetadataPredicate
1788
Paul Duffinb28369a2020-05-04 15:39:59 +01001789 // Retrieves the value on which common value optimization will be performed.
1790 getter fieldAccessorFunc
1791
1792 // The empty value for the field.
1793 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001794
1795 // True if the property can support arch variants false otherwise.
1796 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001797}
1798
Paul Duffin4b8b7932020-05-06 12:35:38 +01001799func (p extractorProperty) String() string {
1800 return p.name
1801}
1802
Paul Duffinc097e362020-03-10 22:50:03 +00001803// Supports extracting common values from a number of instances of a properties
1804// structure into a separate common set of properties.
1805type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001806 // The properties that the extractor can optimize.
1807 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001808}
1809
1810// Create a new common value extractor for the structure type for the supplied
1811// properties struct.
1812//
1813// The returned extractor can be used on any properties structure of the same type
1814// as the supplied set of properties.
1815func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1816 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1817 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001818 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001819 return extractor
1820}
1821
1822// Gather the fields from the supplied structure type from which common values will
1823// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001824//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001825// This is recursive function. If it encounters a struct then it will recurse
1826// into it, passing in the accessor for the field and the struct name as prefix
1827// for the nested fields. That will then be used in the accessors for the fields
1828// in the embedded struct.
1829func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001830 for f := 0; f < structType.NumField(); f++ {
1831 field := structType.Field(f)
1832 if field.PkgPath != "" {
1833 // Ignore unexported fields.
1834 continue
1835 }
1836
Paul Duffinb07fa512020-03-10 22:17:04 +00001837 // Ignore fields whose value should be kept.
1838 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001839 continue
1840 }
1841
Paul Duffinc459f892020-04-30 18:08:29 +01001842 var filter extractorMetadataPredicate
1843
1844 // Add a filter
1845 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1846 filter = func(metadata propertiesContainer) bool {
1847 if m, ok := metadata.(isHostVariant); ok {
1848 if m.isHostVariant() {
1849 return false
1850 }
1851 }
1852 return true
1853 }
1854 }
1855
Paul Duffinc097e362020-03-10 22:50:03 +00001856 // Save a copy of the field index for use in the function.
1857 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001858
Martin Stjernholmb0249572020-09-15 02:32:35 +01001859 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001860
Paul Duffinc097e362020-03-10 22:50:03 +00001861 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001862 if containingStructAccessor != nil {
1863 // This is an embedded structure so first access the field for the embedded
1864 // structure.
1865 value = containingStructAccessor(value)
1866 }
1867
Paul Duffinc097e362020-03-10 22:50:03 +00001868 // Skip through interface and pointer values to find the structure.
1869 value = getStructValue(value)
1870
Paul Duffin4b8b7932020-05-06 12:35:38 +01001871 defer func() {
1872 if r := recover(); r != nil {
1873 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1874 }
1875 }()
1876
Paul Duffinc097e362020-03-10 22:50:03 +00001877 // Return the field.
1878 return value.Field(fieldIndex)
1879 }
1880
Martin Stjernholmb0249572020-09-15 02:32:35 +01001881 if field.Type.Kind() == reflect.Struct {
1882 // Gather fields from the nested or embedded structure.
1883 var subNamePrefix string
1884 if field.Anonymous {
1885 subNamePrefix = namePrefix
1886 } else {
1887 subNamePrefix = name + "."
1888 }
1889 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001890 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001891 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001892 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001893 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001894 fieldGetter,
1895 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001896 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001897 }
1898 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001899 }
Paul Duffinc097e362020-03-10 22:50:03 +00001900 }
1901}
1902
1903func getStructValue(value reflect.Value) reflect.Value {
1904foundStruct:
1905 for {
1906 kind := value.Kind()
1907 switch kind {
1908 case reflect.Interface, reflect.Ptr:
1909 value = value.Elem()
1910 case reflect.Struct:
1911 break foundStruct
1912 default:
1913 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1914 }
1915 }
1916 return value
1917}
1918
Paul Duffinf34f6d82020-04-30 15:48:31 +01001919// A container of properties to be optimized.
1920//
1921// Allows additional information to be associated with the properties, e.g. for
1922// filtering.
1923type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001924 fmt.Stringer
1925
Paul Duffinf34f6d82020-04-30 15:48:31 +01001926 // Get the properties that need optimizing.
1927 optimizableProperties() interface{}
1928}
1929
Paul Duffin2d1bb892021-04-24 11:32:59 +01001930// A wrapper for sdk variant related properties to allow them to be optimized.
1931type sdkVariantPropertiesContainer struct {
1932 sdkVariant *sdk
1933 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01001934}
1935
Paul Duffin2d1bb892021-04-24 11:32:59 +01001936func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
1937 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01001938}
1939
Paul Duffin2d1bb892021-04-24 11:32:59 +01001940func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001941 return c.sdkVariant.String()
1942}
1943
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001944// Extract common properties from a slice of property structures of the same type.
1945//
1946// All the property structures must be of the same type.
1947// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001948// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001949//
1950// Iterates over each exported field (capitalized name) and checks to see whether they
1951// have the same value (using DeepEquals) across all the input properties. If it does not then no
1952// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001953// and the field in each of the input properties structure is set to its default value. Nested
1954// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001955func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001956 commonPropertiesValue := reflect.ValueOf(commonProperties)
1957 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001958
Paul Duffinf34f6d82020-04-30 15:48:31 +01001959 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1960
Paul Duffinb28369a2020-05-04 15:39:59 +01001961 for _, property := range e.properties {
1962 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001963 filter := property.filter
1964 if filter == nil {
1965 filter = func(metadata propertiesContainer) bool {
1966 return true
1967 }
1968 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001969
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001970 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001971 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1972 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001973 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001974
Paul Duffin864e1b42020-05-06 10:23:19 +01001975 // Assume that all the values will be the same.
1976 //
1977 // While similar to this is not quite the same as commonValue == nil. If all the values
1978 // have been filtered out then this will be false but commonValue == nil will be true.
1979 valuesDiffer := false
1980
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001981 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001982 container := sliceValue.Index(i).Interface().(propertiesContainer)
1983 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001984 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001985
Paul Duffinc459f892020-04-30 18:08:29 +01001986 if !filter(container) {
1987 expectedValue := property.emptyValue.Interface()
1988 actualValue := fieldValue.Interface()
1989 if !reflect.DeepEqual(expectedValue, actualValue) {
1990 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1991 }
1992 continue
1993 }
1994
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001995 if commonValue == nil {
1996 // Use the first value as the commonProperties value.
1997 commonValue = &fieldValue
1998 } else {
1999 // If the value does not match the current common value then there is
2000 // no value in common so break out.
2001 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2002 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002003 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002004 break
2005 }
2006 }
2007 }
2008
Paul Duffin864e1b42020-05-06 10:23:19 +01002009 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002010 // and set the input struct's field to the empty value.
2011 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002012 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002013 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002014 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002015 container := sliceValue.Index(i).Interface().(propertiesContainer)
2016 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002017 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002018 fieldValue.Set(emptyValue)
2019 }
2020 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002021
2022 if valuesDiffer && !property.archVariant {
2023 // The values differ but the property does not support arch variants so it
2024 // is an error.
2025 var details strings.Builder
2026 for i := 0; i < sliceValue.Len(); i++ {
2027 container := sliceValue.Index(i).Interface().(propertiesContainer)
2028 itemValue := reflect.ValueOf(container.optimizableProperties())
2029 fieldValue := fieldGetter(itemValue)
2030
2031 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2032 }
2033
2034 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2035 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002036 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002037
2038 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002039}