blob: 3f613399afd04d25f584f768b2c4e1d987308795 [file] [log] [blame]
Jiyong Park9b409bc2019-10-11 14:59:13 +09001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package sdk
16
17import (
18 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000019 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000020 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090021 "strings"
22
Paul Duffin7d74e7b2020-03-06 12:30:13 +000023 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000024 "android/soong/cc"
Paul Duffin375058f2019-11-29 20:17:53 +000025 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090026 "github.com/google/blueprint/proptools"
27
28 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090029)
30
Paul Duffin64fb5262021-05-05 21:36:04 +010031// Environment variables that affect the generated snapshot
32// ========================================================
33//
34// SOONG_SDK_SNAPSHOT_PREFER
35// By default every unversioned module in the generated snapshot has prefer: false. Building it
36// with SOONG_SDK_SNAPSHOT_PREFER=true will force them to use prefer: true.
37//
Paul Duffin43f7bf02021-05-05 22:00:51 +010038// SOONG_SDK_SNAPSHOT_VERSION
39// This provides control over the version of the generated snapshot.
40//
41// SOONG_SDK_SNAPSHOT_VERSION=current will generate unversioned and versioned prebuilts and a
42// versioned snapshot module. This is the default behavior. The zip file containing the
43// generated snapshot will be <sdk-name>-current.zip.
44//
45// SOONG_SDK_SNAPSHOT_VERSION=unversioned will generate unversioned prebuilts only and the zip
46// file containing the generated snapshot will be <sdk-name>.zip.
47//
48// SOONG_SDK_SNAPSHOT_VERSION=<number> will generate versioned prebuilts and a versioned
49// snapshot module only. The zip file containing the generated snapshot will be
50// <sdk-name>-<number>.zip.
51//
Paul Duffin64fb5262021-05-05 21:36:04 +010052
Jiyong Park9b409bc2019-10-11 14:59:13 +090053var pctx = android.NewPackageContext("android/soong/sdk")
54
Paul Duffin375058f2019-11-29 20:17:53 +000055var (
56 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
57 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000058 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000059 CommandDeps: []string{
60 "${config.Zip2ZipCmd}",
61 },
62 },
63 "destdir")
64
65 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
66 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -070067 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +000068 CommandDeps: []string{
69 "${config.SoongZipCmd}",
70 },
71 Rspfile: "$out.rsp",
72 RspfileContent: "$in",
73 },
74 "basedir")
75
76 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
77 blueprint.RuleParams{
78 Command: `${config.MergeZipsCmd} $out $in`,
79 CommandDeps: []string{
80 "${config.MergeZipsCmd}",
81 },
82 })
83)
84
Paul Duffin43f7bf02021-05-05 22:00:51 +010085const (
86 soongSdkSnapshotVersionUnversioned = "unversioned"
87 soongSdkSnapshotVersionCurrent = "current"
88)
89
Paul Duffinb645ec82019-11-27 17:43:54 +000090type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090091 content strings.Builder
92 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090093}
94
Paul Duffinb645ec82019-11-27 17:43:54 +000095// generatedFile abstracts operations for writing contents into a file and emit a build rule
96// for the file.
97type generatedFile struct {
98 generatedContents
99 path android.OutputPath
100}
101
Jiyong Park232e7852019-11-04 12:23:40 +0900102func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +0900103 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +0000104 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +0900105 }
106}
107
Paul Duffinb645ec82019-11-27 17:43:54 +0000108func (gc *generatedContents) Indent() {
109 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +0900110}
111
Paul Duffinb645ec82019-11-27 17:43:54 +0000112func (gc *generatedContents) Dedent() {
113 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +0900114}
115
Paul Duffina08e4dc2021-06-22 18:19:19 +0100116// IndentedPrintf will add spaces to indent the line to the appropriate level before printing the
117// arguments.
118func (gc *generatedContents) IndentedPrintf(format string, args ...interface{}) {
119 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
120}
121
122// UnindentedPrintf does not add spaces to indent the line to the appropriate level before printing
123// the arguments.
124func (gc *generatedContents) UnindentedPrintf(format string, args ...interface{}) {
125 fmt.Fprintf(&(gc.content), format, args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900126}
127
128func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800129 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100130
131 content := gf.content.String()
132
133 // ninja consumes newline characters in rspfile_content. Prevent it by
134 // escaping the backslash in the newline character. The extra backslash
135 // is removed when the rspfile is written to the actual script file
136 content = strings.ReplaceAll(content, "\n", "\\n")
137
Jiyong Park9b409bc2019-10-11 14:59:13 +0900138 rb.Command().
139 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100140 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100141 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900142 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
143 rb.Command().
144 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800145 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900146}
147
Paul Duffin13879572019-11-28 14:31:38 +0000148// Collect all the members.
149//
Paul Duffinb97b1572021-04-29 21:50:40 +0100150// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
151// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000152func (s *sdk) collectMembers(ctx android.ModuleContext) {
153 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000154 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
155 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000156 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100157 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900158
Paul Duffin13879572019-11-28 14:31:38 +0000159 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000160 if !memberType.IsInstance(child) {
161 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900162 }
Paul Duffin13879572019-11-28 14:31:38 +0000163
Paul Duffin6a7e9532020-03-20 17:50:07 +0000164 // Keep track of which multilib variants are used by the sdk.
165 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
166
Paul Duffinb97b1572021-04-29 21:50:40 +0100167 var exportedComponentsInfo android.ExportedComponentsInfo
168 if ctx.OtherModuleHasProvider(child, android.ExportedComponentsInfoProvider) {
169 exportedComponentsInfo = ctx.OtherModuleProvider(child, android.ExportedComponentsInfoProvider).(android.ExportedComponentsInfo)
170 }
171
Paul Duffina7208112021-04-23 21:20:20 +0100172 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100173 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
174 s, memberType, child.(android.SdkAware), export, exportedComponentsInfo,
175 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000176
Paul Duffin2d3da312021-05-06 12:02:27 +0100177 // Recurse down into the member's dependencies as it may have dependencies that need to be
178 // automatically added to the sdk.
179 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900180 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000181
182 return false
Paul Duffin13879572019-11-28 14:31:38 +0000183 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000184}
185
Paul Duffincc3132e2021-04-24 01:10:30 +0100186// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
187// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000188//
Paul Duffincc3132e2021-04-24 01:10:30 +0100189// The sdkMember instances are then grouped into slices by member type. Within each such slice the
190// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000191//
Paul Duffincc3132e2021-04-24 01:10:30 +0100192// Finally, the member type slices are concatenated together to form a single slice. The order in
193// which they are concatenated is the order in which the member types were registered in the
194// android.SdkMemberTypesRegistry.
195func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000196 byType := make(map[android.SdkMemberType][]*sdkMember)
197 byName := make(map[string]*sdkMember)
198
Paul Duffin21827262021-04-24 12:16:36 +0100199 for _, memberVariantDep := range memberVariantDeps {
200 memberType := memberVariantDep.memberType
201 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000202
203 name := ctx.OtherModuleName(variant)
204 member := byName[name]
205 if member == nil {
206 member = &sdkMember{memberType: memberType, name: name}
207 byName[name] = member
208 byType[memberType] = append(byType[memberType], member)
209 }
210
Paul Duffin1356d8c2020-02-25 19:26:33 +0000211 // Only append new variants to the list. This is needed because a member can be both
212 // exported by the sdk and also be a transitive sdk member.
213 member.variants = appendUniqueVariants(member.variants, variant)
214 }
215
Paul Duffin13879572019-11-28 14:31:38 +0000216 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000217 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000218 membersOfType := byType[memberListProperty.memberType]
219 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900220 }
221
Paul Duffin6a7e9532020-03-20 17:50:07 +0000222 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900223}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900224
Paul Duffin72910952020-01-20 18:16:30 +0000225func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
226 for _, v := range variants {
227 if v == newVariant {
228 return variants
229 }
230 }
231 return append(variants, newVariant)
232}
233
Jiyong Park73c54ee2019-10-22 20:31:18 +0900234// SDK directory structure
235// <sdk_root>/
236// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
237// <api_ver>/ : below this directory are all auto-generated
238// Android.bp : definition of 'sdk_snapshot' module is here
239// aidl/
240// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
241// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900242// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900243// include/
244// bionic/libc/include/stdlib.h : an exported header file
245// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900246// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900247// <arch>/include/ : arch-specific exported headers
248// <arch>/include_gen/ : arch-specific generated headers
249// <arch>/lib/
250// libFoo.so : a stub library
251
Jiyong Park232e7852019-11-04 12:23:40 +0900252// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900253// This isn't visible to users, so could be changed in future.
254func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
255 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
256}
257
Jiyong Park232e7852019-11-04 12:23:40 +0900258// buildSnapshot is the main function in this source file. It creates rules to copy
259// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000260func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
261
Paul Duffinb97b1572021-04-29 21:50:40 +0100262 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100263 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100264 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000265 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100266 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100267 }
Paul Duffin865171e2020-03-02 18:38:15 +0000268
Paul Duffinb97b1572021-04-29 21:50:40 +0100269 // Filter out any sdkMemberVariantDep that is a component of another.
270 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000271
Paul Duffinb97b1572021-04-29 21:50:40 +0100272 // Record the names of all the members, both explicitly specified and implicitly
273 // included.
274 allMembersByName := make(map[string]struct{})
275 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100276
Paul Duffinb97b1572021-04-29 21:50:40 +0100277 addMember := func(name string, export bool) {
278 allMembersByName[name] = struct{}{}
279 if export {
280 exportedMembersByName[name] = struct{}{}
281 }
282 }
283
284 for _, memberVariantDep := range memberVariantDeps {
285 name := memberVariantDep.variant.Name()
286 export := memberVariantDep.export
287
288 addMember(name, export)
289
290 // Add any components provided by the module.
291 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
292 addMember(component, export)
293 }
294
295 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
296 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000297 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000298 }
299
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000300 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900301
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000302 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000303
304 bpFile := &bpFile{
305 modules: make(map[string]*bpModule),
306 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000307
Paul Duffin43f7bf02021-05-05 22:00:51 +0100308 config := ctx.Config()
309 version := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_VERSION", "current")
310
311 // Generate versioned modules in the snapshot unless an unversioned snapshot has been requested.
312 generateVersioned := version != soongSdkSnapshotVersionUnversioned
313
314 // Generate unversioned modules in the snapshot unless a numbered snapshot has been requested.
315 //
316 // Unversioned modules are not required in that case because the numbered version will be a
317 // finalized version of the snapshot that is intended to be kept separate from the
318 generateUnversioned := version == soongSdkSnapshotVersionUnversioned || version == soongSdkSnapshotVersionCurrent
319 snapshotZipFileSuffix := ""
320 if generateVersioned {
321 snapshotZipFileSuffix = "-" + version
322 }
323
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000324 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000325 ctx: ctx,
326 sdk: s,
Paul Duffin43f7bf02021-05-05 22:00:51 +0100327 version: version,
Paul Duffin13f02712020-03-06 12:30:43 +0000328 snapshotDir: snapshotDir.OutputPath,
329 copies: make(map[string]string),
330 filesToZip: []android.Path{bp.path},
331 bpFile: bpFile,
332 prebuiltModules: make(map[string]*bpModule),
333 allMembersByName: allMembersByName,
334 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900335 }
Paul Duffinac37c502019-11-26 18:02:20 +0000336 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900337
Paul Duffin62131702021-05-07 01:10:01 +0100338 // If the sdk snapshot includes any license modules then add a package module which has a
339 // default_applicable_licenses property. That will prevent the LSC license process from updating
340 // the generated Android.bp file to add a package module that includes all licenses used by all
341 // the modules in that package. That would be unnecessary as every module in the sdk should have
342 // their own licenses property specified.
343 if hasLicenses {
344 pkg := bpFile.newModule("package")
345 property := "default_applicable_licenses"
346 pkg.AddCommentForProperty(property, `
347A default list here prevents the license LSC from adding its own list which would
348be unnecessary as every module in the sdk already has its own licenses property.
349`)
350 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
351 bpFile.AddModule(pkg)
352 }
353
Paul Duffin0df49682021-05-07 01:10:01 +0100354 // Group the variants for each member module together and then group the members of each member
355 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100356 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100357
358 // Create the prebuilt modules for each of the member modules.
Paul Duffin13ad94f2020-02-19 16:19:27 +0000359 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000360 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000361
Paul Duffina551a1c2020-03-17 21:04:24 +0000362 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000363
364 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100365 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900366 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900367
Paul Duffine6c0d842020-01-15 14:08:51 +0000368 // Create a transformer that will transform an unversioned module into a versioned module.
369 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
370
Paul Duffin72910952020-01-20 18:16:30 +0000371 // Create a transformer that will transform an unversioned module by replacing any references
372 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100373 unversionedTransformer := unversionedTransformation{
374 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100375 }
Paul Duffin72910952020-01-20 18:16:30 +0000376
Paul Duffinb645ec82019-11-27 17:43:54 +0000377 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000378 // Prune any empty property sets.
379 unversioned = unversioned.transform(pruneEmptySetTransformer{})
380
Paul Duffin43f7bf02021-05-05 22:00:51 +0100381 if generateVersioned {
382 // Copy the unversioned module so it can be modified to make it versioned.
383 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000384
Paul Duffin43f7bf02021-05-05 22:00:51 +0100385 // Transform the unversioned module into a versioned one.
386 versioned.transform(unversionedToVersionedTransformer)
387 bpFile.AddModule(versioned)
388 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000389
Paul Duffin43f7bf02021-05-05 22:00:51 +0100390 if generateUnversioned {
391 // Transform the unversioned module to make it suitable for use in the snapshot.
392 unversioned.transform(unversionedTransformer)
393 bpFile.AddModule(unversioned)
394 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000395 }
396
Paul Duffin43f7bf02021-05-05 22:00:51 +0100397 if generateVersioned {
398 // Add the sdk/module_exports_snapshot module to the bp file.
399 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
400 }
Paul Duffin26197a62021-04-24 00:34:10 +0100401
402 // generate Android.bp
403 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
404 generateBpContents(&bp.generatedContents, bpFile)
405
406 contents := bp.content.String()
407 syntaxCheckSnapshotBpFile(ctx, contents)
408
409 bp.build(pctx, ctx, nil)
410
411 filesToZip := builder.filesToZip
412
413 // zip them all
Paul Duffin43f7bf02021-05-05 22:00:51 +0100414 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotZipFileSuffix)
415 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100416 outputDesc := "Building snapshot for " + ctx.ModuleName()
417
418 // If there are no zips to merge then generate the output zip directly.
419 // Otherwise, generate an intermediate zip file into which other zips can be
420 // merged.
421 var zipFile android.OutputPath
422 var desc string
423 if len(builder.zipsToMerge) == 0 {
424 zipFile = outputZipFile
425 desc = outputDesc
426 } else {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100427 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotZipFileSuffix)
428 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100429 desc = "Building intermediate snapshot for " + ctx.ModuleName()
430 }
431
432 ctx.Build(pctx, android.BuildParams{
433 Description: desc,
434 Rule: zipFiles,
435 Inputs: filesToZip,
436 Output: zipFile,
437 Args: map[string]string{
438 "basedir": builder.snapshotDir.String(),
439 },
440 })
441
442 if len(builder.zipsToMerge) != 0 {
443 ctx.Build(pctx, android.BuildParams{
444 Description: outputDesc,
445 Rule: mergeZips,
446 Input: zipFile,
447 Inputs: builder.zipsToMerge,
448 Output: outputZipFile,
449 })
450 }
451
452 return outputZipFile
453}
454
Paul Duffinb97b1572021-04-29 21:50:40 +0100455// filterOutComponents removes any item from the deps list that is a component of another item in
456// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
457// then it will remove "foo.stubs" from the deps.
458func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
459 // Collate the set of components that all the modules added to the sdk provide.
460 components := map[string]*sdkMemberVariantDep{}
461 for i, _ := range deps {
462 dep := &deps[i]
463 for _, c := range dep.exportedComponentsInfo.Components {
464 components[c] = dep
465 }
466 }
467
468 // If no module provides components then return the input deps unfiltered.
469 if len(components) == 0 {
470 return deps
471 }
472
473 filtered := make([]sdkMemberVariantDep, 0, len(deps))
474 for _, dep := range deps {
475 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
476 if owner, ok := components[name]; ok {
477 // This is a component of another module that is a member of the sdk.
478
479 // If the component is exported but the owning module is not then the configuration is not
480 // supported.
481 if dep.export && !owner.export {
482 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
483 continue
484 }
485
486 // This module must not be added to the list of members of the sdk as that would result in a
487 // duplicate module in the sdk snapshot.
488 continue
489 }
490
491 filtered = append(filtered, dep)
492 }
493 return filtered
494}
495
Paul Duffin26197a62021-04-24 00:34:10 +0100496// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100497func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100498 bpFile := builder.bpFile
499
Paul Duffinb645ec82019-11-27 17:43:54 +0000500 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000501 var snapshotModuleType string
502 if s.properties.Module_exports {
503 snapshotModuleType = "module_exports_snapshot"
504 } else {
505 snapshotModuleType = "sdk_snapshot"
506 }
507 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000508 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000509
510 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100511 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000512 if len(visibility) != 0 {
513 snapshotModule.AddProperty("visibility", visibility)
514 }
515
Paul Duffin865171e2020-03-02 18:38:15 +0000516 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000517
Paul Duffincd064672021-04-24 00:47:29 +0100518 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100519 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000520
Paul Duffin2d1bb892021-04-24 11:32:59 +0100521 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100522
Paul Duffin6a7e9532020-03-20 17:50:07 +0000523 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100524
Paul Duffin2d1bb892021-04-24 11:32:59 +0100525 // Create a mapping from osType to combined properties.
526 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
527 for _, combined := range combinedPropertiesList {
528 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
529 }
530
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100531 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000532 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100533 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100534 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000535
Paul Duffin2d1bb892021-04-24 11:32:59 +0100536 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000537 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000538 }
Paul Duffin865171e2020-03-02 18:38:15 +0000539
Jiyong Park8fe14e62020-10-19 22:47:34 +0900540 // If host is supported and any member is host OS dependent then disable host
541 // by default, so that we can enable each host OS variant explicitly. This
542 // avoids problems with implicitly enabled OS variants when the snapshot is
543 // used, which might be different from this run (e.g. different build OS).
544 if s.HostSupported() {
545 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100546 for _, memberVariantDep := range memberVariantDeps {
547 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
548 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900549 if !android.InList(targetString, supportedHostTargets) {
550 supportedHostTargets = append(supportedHostTargets, targetString)
551 }
552 }
553 }
554 if len(supportedHostTargets) > 0 {
555 hostPropertySet := targetPropertySet.AddPropertySet("host")
556 hostPropertySet.AddProperty("enabled", false)
557 }
558 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
559 for _, hostTarget := range supportedHostTargets {
560 propertySet := targetPropertySet.AddPropertySet(hostTarget)
561 propertySet.AddProperty("enabled", true)
562 }
563 }
564
Paul Duffin865171e2020-03-02 18:38:15 +0000565 // Prune any empty property sets.
566 snapshotModule.transform(pruneEmptySetTransformer{})
567
Paul Duffinb645ec82019-11-27 17:43:54 +0000568 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900569}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000570
Paul Duffinf88d8e02020-05-07 20:21:34 +0100571// Check the syntax of the generated Android.bp file contents and if they are
572// invalid then log an error with the contents (tagged with line numbers) and the
573// errors that were found so that it is easy to see where the problem lies.
574func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
575 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
576 if len(errs) != 0 {
577 message := &strings.Builder{}
578 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
579
580Generated Android.bp contents
581========================================================================
582`)
583 for i, line := range strings.Split(contents, "\n") {
584 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
585 }
586
587 _, _ = fmt.Fprint(message, `
588========================================================================
589
590Errors found:
591`)
592
593 for _, err := range errs {
594 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
595 }
596
597 ctx.ModuleErrorf("%s", message.String())
598 }
599}
600
Paul Duffin4b8b7932020-05-06 12:35:38 +0100601func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
602 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
603 if err != nil {
604 ctx.ModuleErrorf("error extracting common properties: %s", err)
605 }
606}
607
Paul Duffinfbe470e2021-04-24 12:37:13 +0100608// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
609type snapshotModuleStaticProperties struct {
610 Compile_multilib string `android:"arch_variant"`
611}
612
Paul Duffin2d1bb892021-04-24 11:32:59 +0100613// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
614type combinedSnapshotModuleProperties struct {
615 // The sdk variant from which this information was collected.
616 sdkVariant *sdk
617
618 // Static snapshot module properties.
619 staticProperties *snapshotModuleStaticProperties
620
621 // The dynamically generated member list properties.
622 dynamicProperties interface{}
623}
624
625// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100626func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
627 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100628 var list []*combinedSnapshotModuleProperties
629 for _, sdkVariant := range sdkVariants {
630 staticProperties := &snapshotModuleStaticProperties{
631 Compile_multilib: sdkVariant.multilibUsages.String(),
632 }
Paul Duffincd064672021-04-24 00:47:29 +0100633 dynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100634
Paul Duffincd064672021-04-24 00:47:29 +0100635 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100636 sdkVariant: sdkVariant,
637 staticProperties: staticProperties,
638 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100639 }
640 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
641
642 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100643 }
Paul Duffincd064672021-04-24 00:47:29 +0100644
645 for _, memberVariantDep := range memberVariantDeps {
646 // If the member dependency is internal then do not add the dependency to the snapshot member
647 // list properties.
648 if !memberVariantDep.export {
649 continue
650 }
651
652 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin13082052021-05-11 00:31:38 +0100653 memberListProperty := s.memberListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100654 memberName := ctx.OtherModuleName(memberVariantDep.variant)
655
Paul Duffin13082052021-05-11 00:31:38 +0100656 if memberListProperty.getter == nil {
657 continue
658 }
659
Paul Duffincd064672021-04-24 00:47:29 +0100660 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100661 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100662 if !android.InList(memberName, memberList) {
663 memberList = append(memberList, memberName)
664 }
Paul Duffin13082052021-05-11 00:31:38 +0100665 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100666 }
667
Paul Duffin2d1bb892021-04-24 11:32:59 +0100668 return list
669}
670
671func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
672
673 // Extract the dynamic properties and add them to a list of propertiesContainer.
674 propertyContainers := []propertiesContainer{}
675 for _, i := range list {
676 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
677 sdkVariant: i.sdkVariant,
678 properties: i.dynamicProperties,
679 })
680 }
681
682 // Extract the common members, removing them from the original properties.
683 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
684 extractor := newCommonValueExtractor(commonDynamicProperties)
685 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
686
687 // Extract the static properties and add them to a list of propertiesContainer.
688 propertyContainers = []propertiesContainer{}
689 for _, i := range list {
690 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
691 sdkVariant: i.sdkVariant,
692 properties: i.staticProperties,
693 })
694 }
695
696 commonStaticProperties := &snapshotModuleStaticProperties{}
697 extractor = newCommonValueExtractor(commonStaticProperties)
698 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
699
700 return &combinedSnapshotModuleProperties{
701 sdkVariant: nil,
702 staticProperties: commonStaticProperties,
703 dynamicProperties: commonDynamicProperties,
704 }
705}
706
707func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
708 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100709 multilib := staticProperties.Compile_multilib
710 if multilib != "" && multilib != "both" {
711 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
712 propertySet.AddProperty("compile_multilib", multilib)
713 }
714
Paul Duffin2d1bb892021-04-24 11:32:59 +0100715 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin865171e2020-03-02 18:38:15 +0000716 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100717 if memberListProperty.getter == nil {
718 continue
719 }
Paul Duffin865171e2020-03-02 18:38:15 +0000720 names := memberListProperty.getter(dynamicMemberTypeListProperties)
721 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000722 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000723 }
724 }
725}
726
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000727type propertyTag struct {
728 name string
729}
730
Paul Duffin0cb37b92020-03-04 14:52:46 +0000731// A BpPropertyTag to add to a property that contains references to other sdk members.
732//
733// This will cause the references to be rewritten to a versioned reference in the version
734// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000735var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000736var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000737
Paul Duffin0cb37b92020-03-04 14:52:46 +0000738// A BpPropertyTag that indicates the property should only be present in the versioned
739// module.
740//
741// This will cause the property to be removed from the unversioned instance of a
742// snapshot module.
743var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
744
Paul Duffine6c0d842020-01-15 14:08:51 +0000745type unversionedToVersionedTransformation struct {
746 identityTransformation
747 builder *snapshotBuilder
748}
749
Paul Duffine6c0d842020-01-15 14:08:51 +0000750func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
751 // Use a versioned name for the module but remember the original name for the
752 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100753 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000754 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000755 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100756 // Remove the prefer property if present as versioned modules never need marking with prefer.
757 module.removeProperty("prefer")
Paul Duffine6c0d842020-01-15 14:08:51 +0000758 return module
759}
760
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000761func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000762 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
763 required := tag == requiredSdkMemberReferencePropertyTag
764 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000765 } else {
766 return value, tag
767 }
768}
769
Paul Duffin72910952020-01-20 18:16:30 +0000770type unversionedTransformation struct {
771 identityTransformation
772 builder *snapshotBuilder
773}
774
775func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
776 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100777 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000778 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000779 return module
780}
781
782func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000783 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
784 required := tag == requiredSdkMemberReferencePropertyTag
785 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000786 } else if tag == sdkVersionedOnlyPropertyTag {
787 // The property is not allowed in the unversioned module so remove it.
788 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000789 } else {
790 return value, tag
791 }
792}
793
Paul Duffina78f3a72020-02-21 16:29:35 +0000794type pruneEmptySetTransformer struct {
795 identityTransformation
796}
797
798var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
799
800func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
801 if len(propertySet.properties) == 0 {
802 return nil, nil
803 } else {
804 return propertySet, tag
805 }
806}
807
Paul Duffinb645ec82019-11-27 17:43:54 +0000808func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000809 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
810 return true
811 })
812}
813
814func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100815 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000816 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000817 if moduleFilter(bpModule) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100818 contents.IndentedPrintf("\n")
819 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
Paul Duffind0759072021-02-17 11:23:00 +0000820 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100821 contents.IndentedPrintf("}\n")
Paul Duffind0759072021-02-17 11:23:00 +0000822 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000823 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000824}
825
826func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
827 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000828
Paul Duffin0df49682021-05-07 01:10:01 +0100829 addComment := func(name string) {
830 if text, ok := set.comments[name]; ok {
831 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100832 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100833 }
834 }
835 }
836
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000837 // Output the properties first, followed by the nested sets. This ensures a
838 // consistent output irrespective of whether property sets are created before
839 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000840 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000841 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000842
Paul Duffin0df49682021-05-07 01:10:01 +0100843 // Do not write property sets in the properties phase.
844 if _, ok := value.(*bpPropertySet); ok {
845 continue
846 }
847
848 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100849 reflectValue := reflect.ValueOf(value)
850 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000851 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000852
853 for _, name := range set.order {
854 value := set.getValue(name)
855
856 // Only write property sets in the sets phase.
857 switch v := value.(type) {
858 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100859 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100860 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000861 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100862 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000863 }
864 }
865
Paul Duffinb645ec82019-11-27 17:43:54 +0000866 contents.Dedent()
867}
868
Paul Duffina08e4dc2021-06-22 18:19:19 +0100869// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
870// by the value and then followed by a , and a newline.
871func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
872 contents.IndentedPrintf("%s: ", name)
873 outputUnnamedValue(contents, value)
874 contents.UnindentedPrintf(",\n")
875}
876
877// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
878// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
879// indented and all but the last line will end with a newline.
880func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
881 valueType := value.Type()
882 switch valueType.Kind() {
883 case reflect.Bool:
884 contents.UnindentedPrintf("%t", value.Bool())
885
886 case reflect.String:
887 contents.UnindentedPrintf("%q", value)
888
Paul Duffin51227d82021-05-18 12:54:27 +0100889 case reflect.Ptr:
890 outputUnnamedValue(contents, value.Elem())
891
Paul Duffina08e4dc2021-06-22 18:19:19 +0100892 case reflect.Slice:
893 length := value.Len()
894 if length == 0 {
895 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100896 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100897 firstValue := value.Index(0)
898 if length == 1 && !multiLineValue(firstValue) {
899 contents.UnindentedPrintf("[")
900 outputUnnamedValue(contents, firstValue)
901 contents.UnindentedPrintf("]")
902 } else {
903 contents.UnindentedPrintf("[\n")
904 contents.Indent()
905 for i := 0; i < length; i++ {
906 itemValue := value.Index(i)
907 contents.IndentedPrintf("")
908 outputUnnamedValue(contents, itemValue)
909 contents.UnindentedPrintf(",\n")
910 }
911 contents.Dedent()
912 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100913 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100914 }
915
Paul Duffin51227d82021-05-18 12:54:27 +0100916 case reflect.Struct:
917 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
918 v := value.Interface()
919 if _, ok := v.(android.BpPrintable); !ok {
920 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
921 }
922 contents.UnindentedPrintf("{\n")
923 contents.Indent()
924 for f := 0; f < valueType.NumField(); f++ {
925 fieldType := valueType.Field(f)
926 if fieldType.Anonymous {
927 continue
928 }
929 fieldValue := value.Field(f)
930 fieldName := fieldType.Name
931 propertyName := proptools.PropertyNameForField(fieldName)
932 outputNamedValue(contents, propertyName, fieldValue)
933 }
934 contents.Dedent()
935 contents.IndentedPrintf("}")
936
Paul Duffina08e4dc2021-06-22 18:19:19 +0100937 default:
938 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
939 }
940}
941
Paul Duffin51227d82021-05-18 12:54:27 +0100942// multiLineValue returns true if the supplied value may require multiple lines in the output.
943func multiLineValue(value reflect.Value) bool {
944 kind := value.Kind()
945 return kind == reflect.Slice || kind == reflect.Struct
946}
947
Paul Duffinac37c502019-11-26 18:02:20 +0000948func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000949 contents := &generatedContents{}
950 generateBpContents(contents, s.builderForTests.bpFile)
951 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000952}
953
Paul Duffind0759072021-02-17 11:23:00 +0000954func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
955 contents := &generatedContents{}
956 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100957 name := module.Name()
958 // Include modules that are either unversioned or have no name.
959 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000960 })
961 return contents.content.String()
962}
963
964func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
965 contents := &generatedContents{}
966 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100967 name := module.Name()
968 // Include modules that are either versioned or have no name.
969 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000970 })
971 return contents.content.String()
972}
973
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000974type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100975 ctx android.ModuleContext
976 sdk *sdk
977
978 // The version of the generated snapshot.
979 //
980 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
981 // this field.
982 version string
983
Paul Duffinb645ec82019-11-27 17:43:54 +0000984 snapshotDir android.OutputPath
985 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000986
987 // Map from destination to source of each copy - used to eliminate duplicates and
988 // detect conflicts.
989 copies map[string]string
990
Paul Duffinb645ec82019-11-27 17:43:54 +0000991 filesToZip android.Paths
992 zipsToMerge android.Paths
993
994 prebuiltModules map[string]*bpModule
995 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000996
997 // The set of all members by name.
998 allMembersByName map[string]struct{}
999
1000 // The set of exported members by name.
1001 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001002}
1003
1004func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001005 if existing, ok := s.copies[dest]; ok {
1006 if existing != src.String() {
1007 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1008 return
1009 }
1010 } else {
1011 path := s.snapshotDir.Join(s.ctx, dest)
1012 s.ctx.Build(pctx, android.BuildParams{
1013 Rule: android.Cp,
1014 Input: src,
1015 Output: path,
1016 })
1017 s.filesToZip = append(s.filesToZip, path)
1018
1019 s.copies[dest] = src.String()
1020 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001021}
1022
Paul Duffin91547182019-11-12 19:39:36 +00001023func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1024 ctx := s.ctx
1025
1026 // Repackage the zip file so that the entries are in the destDir directory.
1027 // This will allow the zip file to be merged into the snapshot.
1028 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001029
1030 ctx.Build(pctx, android.BuildParams{
1031 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1032 Rule: repackageZip,
1033 Input: zipPath,
1034 Output: tmpZipPath,
1035 Args: map[string]string{
1036 "destdir": destDir,
1037 },
1038 })
Paul Duffin91547182019-11-12 19:39:36 +00001039
1040 // Add the repackaged zip file to the files to merge.
1041 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1042}
1043
Paul Duffin9d8d6092019-12-05 18:19:29 +00001044func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1045 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001046 if s.prebuiltModules[name] != nil {
1047 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1048 }
1049
1050 m := s.bpFile.newModule(moduleType)
1051 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001052
Paul Duffinbefa4b92020-03-04 14:22:45 +00001053 variant := member.Variants()[0]
1054
Paul Duffin13f02712020-03-06 12:30:43 +00001055 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001056 // An internal member is only referenced from the sdk snapshot which is in the
1057 // same package so can be marked as private.
1058 m.AddProperty("visibility", []string{"//visibility:private"})
1059 } else {
1060 // Extract visibility information from a member variant. All variants have the same
1061 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001062 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1063
1064 // Add any additional visibility rules needed for the prebuilts to reference each other.
1065 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1066 if err != nil {
1067 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1068 }
1069
1070 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001071 if len(visibility) != 0 {
1072 m.AddProperty("visibility", visibility)
1073 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001074 }
1075
Martin Stjernholm1e041092020-11-03 00:11:09 +00001076 // Where available copy apex_available properties from the member.
1077 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1078 apexAvailable := apexAware.ApexAvailable()
1079 if len(apexAvailable) == 0 {
1080 // //apex_available:platform is the default.
1081 apexAvailable = []string{android.AvailableToPlatform}
1082 }
1083
1084 // Add in any baseline apex available settings.
1085 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1086
1087 // Remove duplicates and sort.
1088 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1089 sort.Strings(apexAvailable)
1090
1091 m.AddProperty("apex_available", apexAvailable)
1092 }
1093
Paul Duffinb0bb3762021-05-06 16:48:05 +01001094 // The licenses are the same for all variants.
1095 mctx := s.ctx
1096 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1097 if len(licenseInfo.Licenses) > 0 {
1098 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1099 }
1100
Paul Duffin865171e2020-03-02 18:38:15 +00001101 deviceSupported := false
1102 hostSupported := false
1103
1104 for _, variant := range member.Variants() {
1105 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001106 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001107 hostSupported = true
1108 } else if osClass == android.Device {
1109 deviceSupported = true
1110 }
1111 }
1112
1113 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001114
Paul Duffin0cb37b92020-03-04 14:52:46 +00001115 // Disable installation in the versioned module of those modules that are ever installable.
1116 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1117 if installable.EverInstallable() {
1118 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1119 }
1120 }
1121
Paul Duffinb645ec82019-11-27 17:43:54 +00001122 s.prebuiltModules[name] = m
1123 s.prebuiltOrder = append(s.prebuiltOrder, m)
1124 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001125}
1126
Paul Duffin865171e2020-03-02 18:38:15 +00001127func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001128 // If neither device or host is supported then this module does not support either so will not
1129 // recognize the properties.
1130 if !deviceSupported && !hostSupported {
1131 return
1132 }
1133
Paul Duffin865171e2020-03-02 18:38:15 +00001134 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001135 bpModule.AddProperty("device_supported", false)
1136 }
Paul Duffin865171e2020-03-02 18:38:15 +00001137 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001138 bpModule.AddProperty("host_supported", true)
1139 }
1140}
1141
Paul Duffin13f02712020-03-06 12:30:43 +00001142func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1143 if required {
1144 return requiredSdkMemberReferencePropertyTag
1145 } else {
1146 return optionalSdkMemberReferencePropertyTag
1147 }
1148}
1149
1150func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1151 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001152}
1153
Paul Duffinb645ec82019-11-27 17:43:54 +00001154// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001155func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1156 if _, ok := s.allMembersByName[unversionedName]; !ok {
1157 if required {
1158 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1159 }
1160 return unversionedName
1161 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001162 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1163}
Paul Duffinb645ec82019-11-27 17:43:54 +00001164
Paul Duffin13f02712020-03-06 12:30:43 +00001165func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001166 var references []string = nil
1167 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001168 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001169 }
1170 return references
1171}
Paul Duffin13879572019-11-28 14:31:38 +00001172
Paul Duffin72910952020-01-20 18:16:30 +00001173// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001174func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1175 if _, ok := s.allMembersByName[unversionedName]; !ok {
1176 if required {
1177 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1178 }
1179 return unversionedName
1180 }
1181
1182 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001183 return s.ctx.ModuleName() + "_" + unversionedName
1184 } else {
1185 return unversionedName
1186 }
1187}
1188
Paul Duffin13f02712020-03-06 12:30:43 +00001189func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001190 var references []string = nil
1191 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001192 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001193 }
1194 return references
1195}
1196
Paul Duffin13f02712020-03-06 12:30:43 +00001197func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1198 _, ok := s.exportedMembersByName[memberName]
1199 return !ok
1200}
1201
Martin Stjernholm89238f42020-07-10 00:14:03 +01001202// Add the properties from the given SdkMemberProperties to the blueprint
1203// property set. This handles common properties in SdkMemberPropertiesBase and
1204// calls the member-specific AddToPropertySet for the rest.
1205func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1206 if memberProperties.Base().Compile_multilib != "" {
1207 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1208 }
1209
1210 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1211}
1212
Paul Duffin21827262021-04-24 12:16:36 +01001213// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1214type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001215 // The sdk variant that depends (possibly indirectly) on the member variant.
1216 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001217
1218 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001219 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001220
1221 // The variant that is added to the sdk.
1222 variant android.SdkAware
1223
1224 // True if the member should be exported, i.e. accessible, from outside the sdk.
1225 export bool
1226
1227 // The names of additional component modules provided by the variant.
1228 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001229}
1230
Paul Duffin13879572019-11-28 14:31:38 +00001231var _ android.SdkMember = (*sdkMember)(nil)
1232
Paul Duffin21827262021-04-24 12:16:36 +01001233// sdkMember groups all the variants of a specific member module together along with the name of the
1234// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001235type sdkMember struct {
1236 memberType android.SdkMemberType
1237 name string
1238 variants []android.SdkAware
1239}
1240
1241func (m *sdkMember) Name() string {
1242 return m.name
1243}
1244
1245func (m *sdkMember) Variants() []android.SdkAware {
1246 return m.variants
1247}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001248
Paul Duffin9c3760e2020-03-16 19:52:08 +00001249// Track usages of multilib variants.
1250type multilibUsage int
1251
1252const (
1253 multilibNone multilibUsage = 0
1254 multilib32 multilibUsage = 1
1255 multilib64 multilibUsage = 2
1256 multilibBoth = multilib32 | multilib64
1257)
1258
1259// Add the multilib that is used in the arch type.
1260func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1261 multilib := archType.Multilib
1262 switch multilib {
1263 case "":
1264 return m
1265 case "lib32":
1266 return m | multilib32
1267 case "lib64":
1268 return m | multilib64
1269 default:
1270 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1271 }
1272}
1273
1274func (m multilibUsage) String() string {
1275 switch m {
1276 case multilibNone:
1277 return ""
1278 case multilib32:
1279 return "32"
1280 case multilib64:
1281 return "64"
1282 case multilibBoth:
1283 return "both"
1284 default:
1285 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1286 m, multilibNone, multilib32, multilib64, multilibBoth))
1287 }
1288}
1289
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001290type baseInfo struct {
1291 Properties android.SdkMemberProperties
1292}
1293
Paul Duffinf34f6d82020-04-30 15:48:31 +01001294func (b *baseInfo) optimizableProperties() interface{} {
1295 return b.Properties
1296}
1297
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001298type osTypeSpecificInfo struct {
1299 baseInfo
1300
Paul Duffin00e46802020-03-12 20:40:35 +00001301 osType android.OsType
1302
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001303 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001304 //
1305 // Nil if there is one variant whose arch type is common
1306 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001307}
1308
Paul Duffin4b8b7932020-05-06 12:35:38 +01001309var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1310
Paul Duffinfc8dd232020-03-17 12:51:37 +00001311type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1312
Paul Duffin00e46802020-03-12 20:40:35 +00001313// Create a new osTypeSpecificInfo for the specified os type and its properties
1314// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001315func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001316 osInfo := &osTypeSpecificInfo{
1317 osType: osType,
1318 }
1319
1320 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1321 properties := variantPropertiesFactory()
1322 properties.Base().Os = osType
1323 return properties
1324 }
1325
1326 // Create a structure into which properties common across the architectures in
1327 // this os type will be stored.
1328 osInfo.Properties = osSpecificVariantPropertiesFactory()
1329
1330 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001331 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001332 var archTypes []android.ArchType
1333 for _, variant := range osTypeVariants {
1334 archType := variant.Target().Arch.ArchType
1335 archTypeName := archType.Name
1336 if _, ok := variantsByArchName[archTypeName]; !ok {
1337 archTypes = append(archTypes, archType)
1338 }
1339
1340 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1341 }
1342
1343 if commonVariants, ok := variantsByArchName["common"]; ok {
1344 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001345 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 +00001346 }
1347
1348 // A common arch type only has one variant and its properties should be treated
1349 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001350 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001351 } else {
1352 // Create an arch specific info for each supported architecture type.
1353 for _, archType := range archTypes {
1354 archTypeName := archType.Name
1355
1356 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001357 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001358
1359 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1360 }
1361 }
1362
1363 return osInfo
1364}
1365
1366// Optimize the properties by extracting common properties from arch type specific
1367// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001368func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001369 // Nothing to do if there is only a single common architecture.
1370 if len(osInfo.archInfos) == 0 {
1371 return
1372 }
1373
Paul Duffin9c3760e2020-03-16 19:52:08 +00001374 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001375 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001376 multilib = multilib.addArchType(archInfo.archType)
1377
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001378 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001379 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001380 }
1381
Paul Duffin4b8b7932020-05-06 12:35:38 +01001382 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001383
1384 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001385 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001386}
1387
1388// Add the properties for an os to a property set.
1389//
1390// Maps the properties related to the os variants through to an appropriate
1391// module structure that will produce equivalent set of variants when it is
1392// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001393func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001394
1395 var osPropertySet android.BpPropertySet
1396 var archPropertySet android.BpPropertySet
1397 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001398 if osInfo.Properties.Base().Os_count == 1 &&
1399 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1400 // There is only one OS type present in the variants and it shouldn't have a
1401 // variant-specific target. The latter is the case if it's either for device
1402 // where there is only one OS (android), or for host and the member type
1403 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001404
1405 // Create a structure that looks like:
1406 // module_type {
1407 // name: "...",
1408 // ...
1409 // <common properties>
1410 // ...
1411 // <single os type specific properties>
1412 //
1413 // arch: {
1414 // <arch specific sections>
1415 // }
1416 //
1417 osPropertySet = bpModule
1418 archPropertySet = osPropertySet.AddPropertySet("arch")
1419
1420 // Arch specific properties need to be added to an arch specific section
1421 // within arch.
1422 archOsPrefix = ""
1423 } else {
1424 // Create a structure that looks like:
1425 // module_type {
1426 // name: "...",
1427 // ...
1428 // <common properties>
1429 // ...
1430 // target: {
1431 // <arch independent os specific sections, e.g. android>
1432 // ...
1433 // <arch and os specific sections, e.g. android_x86>
1434 // }
1435 //
1436 osType := osInfo.osType
1437 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1438 archPropertySet = targetPropertySet
1439
1440 // Arch specific properties need to be added to an os and arch specific
1441 // section prefixed with <os>_.
1442 archOsPrefix = osType.Name + "_"
1443 }
1444
1445 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001446 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001447
1448 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1449 // os) specific properties.
1450 //
1451 // The archInfos list will be empty if the os contains variants for the common
1452 // architecture.
1453 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001454 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001455 }
1456}
1457
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001458func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1459 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001460 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001461}
1462
1463var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1464
Paul Duffin4b8b7932020-05-06 12:35:38 +01001465func (osInfo *osTypeSpecificInfo) String() string {
1466 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1467}
1468
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001469type archTypeSpecificInfo struct {
1470 baseInfo
1471
1472 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001473 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001474
1475 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001476}
1477
Paul Duffin4b8b7932020-05-06 12:35:38 +01001478var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1479
Paul Duffinfc8dd232020-03-17 12:51:37 +00001480// Create a new archTypeSpecificInfo for the specified arch type and its properties
1481// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001482func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001483
Paul Duffinfc8dd232020-03-17 12:51:37 +00001484 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001485 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001486
1487 // Create the properties into which the arch type specific properties will be
1488 // added.
1489 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001490
1491 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001492 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001493 } else {
1494 // There is more than one variant for this arch type which must be differentiated
1495 // by link type.
1496 for _, linkVariant := range archVariants {
1497 linkType := getLinkType(linkVariant)
1498 if linkType == "" {
1499 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1500 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001501 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001502
1503 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1504 }
1505 }
1506 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001507
1508 return archInfo
1509}
1510
Paul Duffinf34f6d82020-04-30 15:48:31 +01001511func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1512 return archInfo.Properties
1513}
1514
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001515// Get the link type of the variant
1516//
1517// If the variant is not differentiated by link type then it returns "",
1518// otherwise it returns one of "static" or "shared".
1519func getLinkType(variant android.Module) string {
1520 linkType := ""
1521 if linkable, ok := variant.(cc.LinkableInterface); ok {
1522 if linkable.Shared() && linkable.Static() {
1523 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1524 } else if linkable.Shared() {
1525 linkType = "shared"
1526 } else if linkable.Static() {
1527 linkType = "static"
1528 } else {
1529 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1530 }
1531 }
1532 return linkType
1533}
1534
1535// Optimize the properties by extracting common properties from link type specific
1536// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001537func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001538 if len(archInfo.linkInfos) == 0 {
1539 return
1540 }
1541
Paul Duffin4b8b7932020-05-06 12:35:38 +01001542 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001543}
1544
Paul Duffinfc8dd232020-03-17 12:51:37 +00001545// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001546func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001547 archTypeName := archInfo.archType.Name
1548 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001549 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1550 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1551 archTypePropertySet.AddProperty("enabled", true)
1552 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001553 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001554
1555 for _, linkInfo := range archInfo.linkInfos {
1556 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001557 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001558 }
1559}
1560
Paul Duffin4b8b7932020-05-06 12:35:38 +01001561func (archInfo *archTypeSpecificInfo) String() string {
1562 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1563}
1564
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001565type linkTypeSpecificInfo struct {
1566 baseInfo
1567
1568 linkType string
1569}
1570
Paul Duffin4b8b7932020-05-06 12:35:38 +01001571var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1572
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001573// Create a new linkTypeSpecificInfo for the specified link type and its properties
1574// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001575func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001576 linkInfo := &linkTypeSpecificInfo{
1577 baseInfo: baseInfo{
1578 // Create the properties into which the link type specific properties will be
1579 // added.
1580 Properties: variantPropertiesFactory(),
1581 },
1582 linkType: linkType,
1583 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001584 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001585 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001586}
1587
Paul Duffin4b8b7932020-05-06 12:35:38 +01001588func (l *linkTypeSpecificInfo) String() string {
1589 return fmt.Sprintf("LinkType{%s}", l.linkType)
1590}
1591
Paul Duffin3a4eb502020-03-19 16:11:18 +00001592type memberContext struct {
1593 sdkMemberContext android.ModuleContext
1594 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001595 memberType android.SdkMemberType
1596 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001597}
1598
1599func (m *memberContext) SdkModuleContext() android.ModuleContext {
1600 return m.sdkMemberContext
1601}
1602
1603func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1604 return m.builder
1605}
1606
Paul Duffina551a1c2020-03-17 21:04:24 +00001607func (m *memberContext) MemberType() android.SdkMemberType {
1608 return m.memberType
1609}
1610
1611func (m *memberContext) Name() string {
1612 return m.name
1613}
1614
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001615func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001616
1617 memberType := member.memberType
1618
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001619 // Do not add the prefer property if the member snapshot module is a source module type.
1620 if !memberType.UsesSourceModuleTypeInSnapshot() {
1621 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1622 // snapshot to be created that sets prefer: true.
1623 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1624 // dynamically at build time not at snapshot generation time.
1625 prefer := ctx.sdkMemberContext.Config().IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001626
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001627 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1628 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1629 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1630 // behavior is for the module.
1631 bpModule.insertAfter("name", "prefer", prefer)
1632 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001633
Paul Duffina04c1072020-03-02 10:16:35 +00001634 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001635 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001636 variants := member.Variants()
1637 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001638 osType := variant.Target().Os
1639 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001640 }
1641
Paul Duffina04c1072020-03-02 10:16:35 +00001642 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001643 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001644 properties := memberType.CreateVariantPropertiesStruct()
1645 base := properties.Base()
1646 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001647 return properties
1648 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001649
Paul Duffina04c1072020-03-02 10:16:35 +00001650 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001651
Paul Duffina04c1072020-03-02 10:16:35 +00001652 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001653 commonProperties := variantPropertiesFactory()
1654 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001655
Paul Duffinc097e362020-03-10 22:50:03 +00001656 // Create common value extractor that can be used to optimize the properties.
1657 commonValueExtractor := newCommonValueExtractor(commonProperties)
1658
Paul Duffina04c1072020-03-02 10:16:35 +00001659 // The list of property structures which are os type specific but common across
1660 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001661 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001662
1663 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001664 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001665 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001666 // Add the os specific properties to a list of os type specific yet architecture
1667 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001668 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001669
Paul Duffin00e46802020-03-12 20:40:35 +00001670 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001671 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001672 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001673
Paul Duffina04c1072020-03-02 10:16:35 +00001674 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001675 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001676
Paul Duffina04c1072020-03-02 10:16:35 +00001677 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001678 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001679
Paul Duffina04c1072020-03-02 10:16:35 +00001680 // Create a target property set into which target specific properties can be
1681 // added.
1682 targetPropertySet := bpModule.AddPropertySet("target")
1683
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001684 // If the member is host OS dependent and has host_supported then disable by
1685 // default and enable each host OS variant explicitly. This avoids problems
1686 // with implicitly enabled OS variants when the snapshot is used, which might
1687 // be different from this run (e.g. different build OS).
1688 if ctx.memberType.IsHostOsDependent() {
1689 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1690 if hostSupported {
1691 hostPropertySet := targetPropertySet.AddPropertySet("host")
1692 hostPropertySet.AddProperty("enabled", false)
1693 }
1694 }
1695
Paul Duffina04c1072020-03-02 10:16:35 +00001696 // Iterate over the os types in a fixed order.
1697 for _, osType := range s.getPossibleOsTypes() {
1698 osInfo := osTypeToInfo[osType]
1699 if osInfo == nil {
1700 continue
1701 }
1702
Paul Duffin3a4eb502020-03-19 16:11:18 +00001703 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001704 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001705}
1706
Paul Duffina04c1072020-03-02 10:16:35 +00001707// Compute the list of possible os types that this sdk could support.
1708func (s *sdk) getPossibleOsTypes() []android.OsType {
1709 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001710 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001711 if s.DeviceSupported() {
1712 if osType.Class == android.Device && osType != android.Fuchsia {
1713 osTypes = append(osTypes, osType)
1714 }
1715 }
1716 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001717 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001718 osTypes = append(osTypes, osType)
1719 }
1720 }
1721 }
1722 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1723 return osTypes
1724}
1725
Paul Duffinb28369a2020-05-04 15:39:59 +01001726// Given a set of properties (struct value), return the value of the field within that
1727// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001728type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1729
Paul Duffinc459f892020-04-30 18:08:29 +01001730// Checks the metadata to determine whether the property should be ignored for the
1731// purposes of common value extraction or not.
1732type extractorMetadataPredicate func(metadata propertiesContainer) bool
1733
1734// Indicates whether optimizable properties are provided by a host variant or
1735// not.
1736type isHostVariant interface {
1737 isHostVariant() bool
1738}
1739
Paul Duffinb28369a2020-05-04 15:39:59 +01001740// A property that can be optimized by the commonValueExtractor.
1741type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001742 // The name of the field for this property. It is a "."-separated path for
1743 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001744 name string
1745
Paul Duffinc459f892020-04-30 18:08:29 +01001746 // Filter that can use metadata associated with the properties being optimized
1747 // to determine whether the field should be ignored during common value
1748 // optimization.
1749 filter extractorMetadataPredicate
1750
Paul Duffinb28369a2020-05-04 15:39:59 +01001751 // Retrieves the value on which common value optimization will be performed.
1752 getter fieldAccessorFunc
1753
1754 // The empty value for the field.
1755 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001756
1757 // True if the property can support arch variants false otherwise.
1758 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001759}
1760
Paul Duffin4b8b7932020-05-06 12:35:38 +01001761func (p extractorProperty) String() string {
1762 return p.name
1763}
1764
Paul Duffinc097e362020-03-10 22:50:03 +00001765// Supports extracting common values from a number of instances of a properties
1766// structure into a separate common set of properties.
1767type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001768 // The properties that the extractor can optimize.
1769 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001770}
1771
1772// Create a new common value extractor for the structure type for the supplied
1773// properties struct.
1774//
1775// The returned extractor can be used on any properties structure of the same type
1776// as the supplied set of properties.
1777func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1778 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1779 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001780 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001781 return extractor
1782}
1783
1784// Gather the fields from the supplied structure type from which common values will
1785// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001786//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001787// This is recursive function. If it encounters a struct then it will recurse
1788// into it, passing in the accessor for the field and the struct name as prefix
1789// for the nested fields. That will then be used in the accessors for the fields
1790// in the embedded struct.
1791func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001792 for f := 0; f < structType.NumField(); f++ {
1793 field := structType.Field(f)
1794 if field.PkgPath != "" {
1795 // Ignore unexported fields.
1796 continue
1797 }
1798
Paul Duffinb07fa512020-03-10 22:17:04 +00001799 // Ignore fields whose value should be kept.
1800 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001801 continue
1802 }
1803
Paul Duffinc459f892020-04-30 18:08:29 +01001804 var filter extractorMetadataPredicate
1805
1806 // Add a filter
1807 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1808 filter = func(metadata propertiesContainer) bool {
1809 if m, ok := metadata.(isHostVariant); ok {
1810 if m.isHostVariant() {
1811 return false
1812 }
1813 }
1814 return true
1815 }
1816 }
1817
Paul Duffinc097e362020-03-10 22:50:03 +00001818 // Save a copy of the field index for use in the function.
1819 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001820
Martin Stjernholmb0249572020-09-15 02:32:35 +01001821 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001822
Paul Duffinc097e362020-03-10 22:50:03 +00001823 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001824 if containingStructAccessor != nil {
1825 // This is an embedded structure so first access the field for the embedded
1826 // structure.
1827 value = containingStructAccessor(value)
1828 }
1829
Paul Duffinc097e362020-03-10 22:50:03 +00001830 // Skip through interface and pointer values to find the structure.
1831 value = getStructValue(value)
1832
Paul Duffin4b8b7932020-05-06 12:35:38 +01001833 defer func() {
1834 if r := recover(); r != nil {
1835 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1836 }
1837 }()
1838
Paul Duffinc097e362020-03-10 22:50:03 +00001839 // Return the field.
1840 return value.Field(fieldIndex)
1841 }
1842
Martin Stjernholmb0249572020-09-15 02:32:35 +01001843 if field.Type.Kind() == reflect.Struct {
1844 // Gather fields from the nested or embedded structure.
1845 var subNamePrefix string
1846 if field.Anonymous {
1847 subNamePrefix = namePrefix
1848 } else {
1849 subNamePrefix = name + "."
1850 }
1851 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001852 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001853 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001854 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001855 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001856 fieldGetter,
1857 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001858 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001859 }
1860 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001861 }
Paul Duffinc097e362020-03-10 22:50:03 +00001862 }
1863}
1864
1865func getStructValue(value reflect.Value) reflect.Value {
1866foundStruct:
1867 for {
1868 kind := value.Kind()
1869 switch kind {
1870 case reflect.Interface, reflect.Ptr:
1871 value = value.Elem()
1872 case reflect.Struct:
1873 break foundStruct
1874 default:
1875 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1876 }
1877 }
1878 return value
1879}
1880
Paul Duffinf34f6d82020-04-30 15:48:31 +01001881// A container of properties to be optimized.
1882//
1883// Allows additional information to be associated with the properties, e.g. for
1884// filtering.
1885type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001886 fmt.Stringer
1887
Paul Duffinf34f6d82020-04-30 15:48:31 +01001888 // Get the properties that need optimizing.
1889 optimizableProperties() interface{}
1890}
1891
Paul Duffin2d1bb892021-04-24 11:32:59 +01001892// A wrapper for sdk variant related properties to allow them to be optimized.
1893type sdkVariantPropertiesContainer struct {
1894 sdkVariant *sdk
1895 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01001896}
1897
Paul Duffin2d1bb892021-04-24 11:32:59 +01001898func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
1899 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01001900}
1901
Paul Duffin2d1bb892021-04-24 11:32:59 +01001902func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001903 return c.sdkVariant.String()
1904}
1905
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001906// Extract common properties from a slice of property structures of the same type.
1907//
1908// All the property structures must be of the same type.
1909// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001910// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001911//
1912// Iterates over each exported field (capitalized name) and checks to see whether they
1913// have the same value (using DeepEquals) across all the input properties. If it does not then no
1914// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001915// and the field in each of the input properties structure is set to its default value. Nested
1916// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001917func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001918 commonPropertiesValue := reflect.ValueOf(commonProperties)
1919 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001920
Paul Duffinf34f6d82020-04-30 15:48:31 +01001921 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1922
Paul Duffinb28369a2020-05-04 15:39:59 +01001923 for _, property := range e.properties {
1924 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001925 filter := property.filter
1926 if filter == nil {
1927 filter = func(metadata propertiesContainer) bool {
1928 return true
1929 }
1930 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001931
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001932 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001933 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1934 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001935 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001936
Paul Duffin864e1b42020-05-06 10:23:19 +01001937 // Assume that all the values will be the same.
1938 //
1939 // While similar to this is not quite the same as commonValue == nil. If all the values
1940 // have been filtered out then this will be false but commonValue == nil will be true.
1941 valuesDiffer := false
1942
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001943 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001944 container := sliceValue.Index(i).Interface().(propertiesContainer)
1945 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001946 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001947
Paul Duffinc459f892020-04-30 18:08:29 +01001948 if !filter(container) {
1949 expectedValue := property.emptyValue.Interface()
1950 actualValue := fieldValue.Interface()
1951 if !reflect.DeepEqual(expectedValue, actualValue) {
1952 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1953 }
1954 continue
1955 }
1956
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001957 if commonValue == nil {
1958 // Use the first value as the commonProperties value.
1959 commonValue = &fieldValue
1960 } else {
1961 // If the value does not match the current common value then there is
1962 // no value in common so break out.
1963 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1964 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001965 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001966 break
1967 }
1968 }
1969 }
1970
Paul Duffin864e1b42020-05-06 10:23:19 +01001971 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001972 // and set the input struct's field to the empty value.
1973 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001974 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001975 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001976 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001977 container := sliceValue.Index(i).Interface().(propertiesContainer)
1978 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001979 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001980 fieldValue.Set(emptyValue)
1981 }
1982 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001983
1984 if valuesDiffer && !property.archVariant {
1985 // The values differ but the property does not support arch variants so it
1986 // is an error.
1987 var details strings.Builder
1988 for i := 0; i < sliceValue.Len(); i++ {
1989 container := sliceValue.Index(i).Interface().(propertiesContainer)
1990 itemValue := reflect.ValueOf(container.optimizableProperties())
1991 fieldValue := fieldGetter(itemValue)
1992
1993 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1994 }
1995
1996 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1997 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001998 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01001999
2000 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002001}