blob: 3ec1bfaf440def5745880a13035208b707149e33 [file] [log] [blame]
Jiyong Park9b409bc2019-10-11 14:59:13 +09001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package sdk
16
17import (
18 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000019 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000020 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090021 "strings"
22
Paul Duffin7d74e7b2020-03-06 12:30:13 +000023 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000024 "android/soong/cc"
Paul Duffin375058f2019-11-29 20:17:53 +000025 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090026 "github.com/google/blueprint/proptools"
27
28 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090029)
30
Paul Duffin64fb5262021-05-05 21:36:04 +010031// Environment variables that affect the generated snapshot
32// ========================================================
33//
34// SOONG_SDK_SNAPSHOT_PREFER
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +000035// 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.
Paul Duffin64fb5262021-05-05 21:36:04 +010037//
Paul Duffinfb9a7f92021-07-06 17:18:42 +010038// SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR
39// If set this specifies the Soong config var that can be used to control whether the prebuilt
40// modules from the generated snapshot or the original source modules. Values must be a colon
41// separated pair of strings, the first of which is the Soong config namespace, and the second
42// is the name of the variable within that namespace.
43//
44// The config namespace and var name are used to set the `use_source_config_var` property. That
45// in turn will cause the generated prebuilts to use the soong config variable to select whether
46// source or the prebuilt is used.
47// e.g. If an sdk snapshot is built using:
48// m SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR=acme:build_from_source sdkextensions-sdk
49// Then the resulting snapshot will include:
50// use_source_config_var: {
51// config_namespace: "acme",
52// var_name: "build_from_source",
53// }
54//
55// Assuming that the config variable is defined in .mk using something like:
56// $(call add_soong_config_namespace,acme)
57// $(call add_soong_config_var_value,acme,build_from_source,true)
58//
59// Then when the snapshot is unpacked in the repository it will have the following behavior:
60// m droid - will use the sdkextensions-sdk prebuilts if present. Otherwise, it will use the
61// sources.
62// m SOONG_CONFIG_acme_build_from_source=true droid - will use the sdkextensions-sdk
63// sources, if present. Otherwise, it will use the prebuilts.
64//
65// This is a temporary mechanism to control the prefer flags and will be removed once a more
66// maintainable solution has been implemented.
67// TODO(b/174997203): Remove when no longer necessary.
68//
Paul Duffin43f7bf02021-05-05 22:00:51 +010069// SOONG_SDK_SNAPSHOT_VERSION
70// This provides control over the version of the generated snapshot.
71//
72// SOONG_SDK_SNAPSHOT_VERSION=current will generate unversioned and versioned prebuilts and a
73// versioned snapshot module. This is the default behavior. The zip file containing the
74// generated snapshot will be <sdk-name>-current.zip.
75//
76// SOONG_SDK_SNAPSHOT_VERSION=unversioned will generate unversioned prebuilts only and the zip
77// file containing the generated snapshot will be <sdk-name>.zip.
78//
79// SOONG_SDK_SNAPSHOT_VERSION=<number> will generate versioned prebuilts and a versioned
80// snapshot module only. The zip file containing the generated snapshot will be
81// <sdk-name>-<number>.zip.
82//
Paul Duffin64fb5262021-05-05 21:36:04 +010083
Jiyong Park9b409bc2019-10-11 14:59:13 +090084var pctx = android.NewPackageContext("android/soong/sdk")
85
Paul Duffin375058f2019-11-29 20:17:53 +000086var (
87 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
88 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000089 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000090 CommandDeps: []string{
91 "${config.Zip2ZipCmd}",
92 },
93 },
94 "destdir")
95
96 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
97 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -070098 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +000099 CommandDeps: []string{
100 "${config.SoongZipCmd}",
101 },
102 Rspfile: "$out.rsp",
103 RspfileContent: "$in",
104 },
105 "basedir")
106
107 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
108 blueprint.RuleParams{
109 Command: `${config.MergeZipsCmd} $out $in`,
110 CommandDeps: []string{
111 "${config.MergeZipsCmd}",
112 },
113 })
114)
115
Paul Duffin43f7bf02021-05-05 22:00:51 +0100116const (
117 soongSdkSnapshotVersionUnversioned = "unversioned"
118 soongSdkSnapshotVersionCurrent = "current"
119)
120
Paul Duffinb645ec82019-11-27 17:43:54 +0000121type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +0900122 content strings.Builder
123 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +0900124}
125
Paul Duffinb645ec82019-11-27 17:43:54 +0000126// generatedFile abstracts operations for writing contents into a file and emit a build rule
127// for the file.
128type generatedFile struct {
129 generatedContents
130 path android.OutputPath
131}
132
Jiyong Park232e7852019-11-04 12:23:40 +0900133func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +0900134 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +0000135 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +0900136 }
137}
138
Paul Duffinb645ec82019-11-27 17:43:54 +0000139func (gc *generatedContents) Indent() {
140 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +0900141}
142
Paul Duffinb645ec82019-11-27 17:43:54 +0000143func (gc *generatedContents) Dedent() {
144 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +0900145}
146
Paul Duffina08e4dc2021-06-22 18:19:19 +0100147// IndentedPrintf will add spaces to indent the line to the appropriate level before printing the
148// arguments.
149func (gc *generatedContents) IndentedPrintf(format string, args ...interface{}) {
150 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
151}
152
153// UnindentedPrintf does not add spaces to indent the line to the appropriate level before printing
154// the arguments.
155func (gc *generatedContents) UnindentedPrintf(format string, args ...interface{}) {
156 fmt.Fprintf(&(gc.content), format, args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900157}
158
159func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800160 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100161
162 content := gf.content.String()
163
164 // ninja consumes newline characters in rspfile_content. Prevent it by
165 // escaping the backslash in the newline character. The extra backslash
166 // is removed when the rspfile is written to the actual script file
167 content = strings.ReplaceAll(content, "\n", "\\n")
168
Jiyong Park9b409bc2019-10-11 14:59:13 +0900169 rb.Command().
170 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100171 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100172 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900173 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
174 rb.Command().
175 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800176 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900177}
178
Paul Duffin13879572019-11-28 14:31:38 +0000179// Collect all the members.
180//
Paul Duffinb97b1572021-04-29 21:50:40 +0100181// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
182// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000183func (s *sdk) collectMembers(ctx android.ModuleContext) {
184 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000185 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
186 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000187 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100188 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900189
Paul Duffin5cca7c42021-05-26 10:16:01 +0100190 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
191 if memberType == nil {
192 return false
193 }
194
Paul Duffin13879572019-11-28 14:31:38 +0000195 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000196 if !memberType.IsInstance(child) {
197 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900198 }
Paul Duffin13879572019-11-28 14:31:38 +0000199
Paul Duffin6a7e9532020-03-20 17:50:07 +0000200 // Keep track of which multilib variants are used by the sdk.
201 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
202
Paul Duffinb97b1572021-04-29 21:50:40 +0100203 var exportedComponentsInfo android.ExportedComponentsInfo
204 if ctx.OtherModuleHasProvider(child, android.ExportedComponentsInfoProvider) {
205 exportedComponentsInfo = ctx.OtherModuleProvider(child, android.ExportedComponentsInfoProvider).(android.ExportedComponentsInfo)
206 }
207
Paul Duffina7208112021-04-23 21:20:20 +0100208 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100209 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
210 s, memberType, child.(android.SdkAware), export, exportedComponentsInfo,
211 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000212
Paul Duffin2d3da312021-05-06 12:02:27 +0100213 // Recurse down into the member's dependencies as it may have dependencies that need to be
214 // automatically added to the sdk.
215 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900216 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000217
218 return false
Paul Duffin13879572019-11-28 14:31:38 +0000219 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000220}
221
Paul Duffincc3132e2021-04-24 01:10:30 +0100222// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
223// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000224//
Paul Duffincc3132e2021-04-24 01:10:30 +0100225// The sdkMember instances are then grouped into slices by member type. Within each such slice the
226// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000227//
Paul Duffincc3132e2021-04-24 01:10:30 +0100228// Finally, the member type slices are concatenated together to form a single slice. The order in
229// which they are concatenated is the order in which the member types were registered in the
230// android.SdkMemberTypesRegistry.
231func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000232 byType := make(map[android.SdkMemberType][]*sdkMember)
233 byName := make(map[string]*sdkMember)
234
Paul Duffin21827262021-04-24 12:16:36 +0100235 for _, memberVariantDep := range memberVariantDeps {
236 memberType := memberVariantDep.memberType
237 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000238
239 name := ctx.OtherModuleName(variant)
240 member := byName[name]
241 if member == nil {
242 member = &sdkMember{memberType: memberType, name: name}
243 byName[name] = member
244 byType[memberType] = append(byType[memberType], member)
245 }
246
Paul Duffin1356d8c2020-02-25 19:26:33 +0000247 // Only append new variants to the list. This is needed because a member can be both
248 // exported by the sdk and also be a transitive sdk member.
249 member.variants = appendUniqueVariants(member.variants, variant)
250 }
251
Paul Duffin13879572019-11-28 14:31:38 +0000252 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000253 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000254 membersOfType := byType[memberListProperty.memberType]
255 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900256 }
257
Paul Duffin6a7e9532020-03-20 17:50:07 +0000258 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900259}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900260
Paul Duffin72910952020-01-20 18:16:30 +0000261func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
262 for _, v := range variants {
263 if v == newVariant {
264 return variants
265 }
266 }
267 return append(variants, newVariant)
268}
269
Jiyong Park73c54ee2019-10-22 20:31:18 +0900270// SDK directory structure
271// <sdk_root>/
272// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
273// <api_ver>/ : below this directory are all auto-generated
274// Android.bp : definition of 'sdk_snapshot' module is here
275// aidl/
276// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
277// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900278// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900279// include/
280// bionic/libc/include/stdlib.h : an exported header file
281// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900282// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900283// <arch>/include/ : arch-specific exported headers
284// <arch>/include_gen/ : arch-specific generated headers
285// <arch>/lib/
286// libFoo.so : a stub library
287
Jiyong Park232e7852019-11-04 12:23:40 +0900288// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900289// This isn't visible to users, so could be changed in future.
290func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
291 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
292}
293
Jiyong Park232e7852019-11-04 12:23:40 +0900294// buildSnapshot is the main function in this source file. It creates rules to copy
295// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000296func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
297
Paul Duffinb97b1572021-04-29 21:50:40 +0100298 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100299 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100300 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000301 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100302 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100303 }
Paul Duffin865171e2020-03-02 18:38:15 +0000304
Paul Duffinb97b1572021-04-29 21:50:40 +0100305 // Filter out any sdkMemberVariantDep that is a component of another.
306 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000307
Paul Duffinb97b1572021-04-29 21:50:40 +0100308 // Record the names of all the members, both explicitly specified and implicitly
309 // included.
310 allMembersByName := make(map[string]struct{})
311 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100312
Paul Duffinb97b1572021-04-29 21:50:40 +0100313 addMember := func(name string, export bool) {
314 allMembersByName[name] = struct{}{}
315 if export {
316 exportedMembersByName[name] = struct{}{}
317 }
318 }
319
320 for _, memberVariantDep := range memberVariantDeps {
321 name := memberVariantDep.variant.Name()
322 export := memberVariantDep.export
323
324 addMember(name, export)
325
326 // Add any components provided by the module.
327 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
328 addMember(component, export)
329 }
330
331 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
332 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000333 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000334 }
335
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000336 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900337
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000338 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000339
340 bpFile := &bpFile{
341 modules: make(map[string]*bpModule),
342 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000343
Paul Duffin43f7bf02021-05-05 22:00:51 +0100344 config := ctx.Config()
345 version := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_VERSION", "current")
346
347 // Generate versioned modules in the snapshot unless an unversioned snapshot has been requested.
348 generateVersioned := version != soongSdkSnapshotVersionUnversioned
349
350 // Generate unversioned modules in the snapshot unless a numbered snapshot has been requested.
351 //
352 // Unversioned modules are not required in that case because the numbered version will be a
353 // finalized version of the snapshot that is intended to be kept separate from the
354 generateUnversioned := version == soongSdkSnapshotVersionUnversioned || version == soongSdkSnapshotVersionCurrent
355 snapshotZipFileSuffix := ""
356 if generateVersioned {
357 snapshotZipFileSuffix = "-" + version
358 }
359
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000360 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000361 ctx: ctx,
362 sdk: s,
Paul Duffin43f7bf02021-05-05 22:00:51 +0100363 version: version,
Paul Duffin13f02712020-03-06 12:30:43 +0000364 snapshotDir: snapshotDir.OutputPath,
365 copies: make(map[string]string),
366 filesToZip: []android.Path{bp.path},
367 bpFile: bpFile,
368 prebuiltModules: make(map[string]*bpModule),
369 allMembersByName: allMembersByName,
370 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900371 }
Paul Duffinac37c502019-11-26 18:02:20 +0000372 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900373
Paul Duffin62131702021-05-07 01:10:01 +0100374 // If the sdk snapshot includes any license modules then add a package module which has a
375 // default_applicable_licenses property. That will prevent the LSC license process from updating
376 // the generated Android.bp file to add a package module that includes all licenses used by all
377 // the modules in that package. That would be unnecessary as every module in the sdk should have
378 // their own licenses property specified.
379 if hasLicenses {
380 pkg := bpFile.newModule("package")
381 property := "default_applicable_licenses"
382 pkg.AddCommentForProperty(property, `
383A default list here prevents the license LSC from adding its own list which would
384be unnecessary as every module in the sdk already has its own licenses property.
385`)
386 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
387 bpFile.AddModule(pkg)
388 }
389
Paul Duffin0df49682021-05-07 01:10:01 +0100390 // Group the variants for each member module together and then group the members of each member
391 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100392 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100393
394 // Create the prebuilt modules for each of the member modules.
Paul Duffin13ad94f2020-02-19 16:19:27 +0000395 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000396 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000397
Paul Duffina551a1c2020-03-17 21:04:24 +0000398 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000399
400 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100401 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900402 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900403
Paul Duffine6c0d842020-01-15 14:08:51 +0000404 // Create a transformer that will transform an unversioned module into a versioned module.
405 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
406
Paul Duffin72910952020-01-20 18:16:30 +0000407 // Create a transformer that will transform an unversioned module by replacing any references
408 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100409 unversionedTransformer := unversionedTransformation{
410 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100411 }
Paul Duffin72910952020-01-20 18:16:30 +0000412
Paul Duffinb645ec82019-11-27 17:43:54 +0000413 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000414 // Prune any empty property sets.
415 unversioned = unversioned.transform(pruneEmptySetTransformer{})
416
Paul Duffin43f7bf02021-05-05 22:00:51 +0100417 if generateVersioned {
418 // Copy the unversioned module so it can be modified to make it versioned.
419 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000420
Paul Duffin43f7bf02021-05-05 22:00:51 +0100421 // Transform the unversioned module into a versioned one.
422 versioned.transform(unversionedToVersionedTransformer)
423 bpFile.AddModule(versioned)
424 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000425
Paul Duffin43f7bf02021-05-05 22:00:51 +0100426 if generateUnversioned {
427 // Transform the unversioned module to make it suitable for use in the snapshot.
428 unversioned.transform(unversionedTransformer)
429 bpFile.AddModule(unversioned)
430 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000431 }
432
Paul Duffin43f7bf02021-05-05 22:00:51 +0100433 if generateVersioned {
434 // Add the sdk/module_exports_snapshot module to the bp file.
435 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
436 }
Paul Duffin26197a62021-04-24 00:34:10 +0100437
438 // generate Android.bp
439 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
440 generateBpContents(&bp.generatedContents, bpFile)
441
442 contents := bp.content.String()
443 syntaxCheckSnapshotBpFile(ctx, contents)
444
445 bp.build(pctx, ctx, nil)
446
447 filesToZip := builder.filesToZip
448
449 // zip them all
Paul Duffin43f7bf02021-05-05 22:00:51 +0100450 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotZipFileSuffix)
451 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100452 outputDesc := "Building snapshot for " + ctx.ModuleName()
453
454 // If there are no zips to merge then generate the output zip directly.
455 // Otherwise, generate an intermediate zip file into which other zips can be
456 // merged.
457 var zipFile android.OutputPath
458 var desc string
459 if len(builder.zipsToMerge) == 0 {
460 zipFile = outputZipFile
461 desc = outputDesc
462 } else {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100463 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotZipFileSuffix)
464 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100465 desc = "Building intermediate snapshot for " + ctx.ModuleName()
466 }
467
468 ctx.Build(pctx, android.BuildParams{
469 Description: desc,
470 Rule: zipFiles,
471 Inputs: filesToZip,
472 Output: zipFile,
473 Args: map[string]string{
474 "basedir": builder.snapshotDir.String(),
475 },
476 })
477
478 if len(builder.zipsToMerge) != 0 {
479 ctx.Build(pctx, android.BuildParams{
480 Description: outputDesc,
481 Rule: mergeZips,
482 Input: zipFile,
483 Inputs: builder.zipsToMerge,
484 Output: outputZipFile,
485 })
486 }
487
488 return outputZipFile
489}
490
Paul Duffinb97b1572021-04-29 21:50:40 +0100491// filterOutComponents removes any item from the deps list that is a component of another item in
492// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
493// then it will remove "foo.stubs" from the deps.
494func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
495 // Collate the set of components that all the modules added to the sdk provide.
496 components := map[string]*sdkMemberVariantDep{}
497 for i, _ := range deps {
498 dep := &deps[i]
499 for _, c := range dep.exportedComponentsInfo.Components {
500 components[c] = dep
501 }
502 }
503
504 // If no module provides components then return the input deps unfiltered.
505 if len(components) == 0 {
506 return deps
507 }
508
509 filtered := make([]sdkMemberVariantDep, 0, len(deps))
510 for _, dep := range deps {
511 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
512 if owner, ok := components[name]; ok {
513 // This is a component of another module that is a member of the sdk.
514
515 // If the component is exported but the owning module is not then the configuration is not
516 // supported.
517 if dep.export && !owner.export {
518 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
519 continue
520 }
521
522 // This module must not be added to the list of members of the sdk as that would result in a
523 // duplicate module in the sdk snapshot.
524 continue
525 }
526
527 filtered = append(filtered, dep)
528 }
529 return filtered
530}
531
Paul Duffin26197a62021-04-24 00:34:10 +0100532// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100533func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100534 bpFile := builder.bpFile
535
Paul Duffinb645ec82019-11-27 17:43:54 +0000536 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000537 var snapshotModuleType string
538 if s.properties.Module_exports {
539 snapshotModuleType = "module_exports_snapshot"
540 } else {
541 snapshotModuleType = "sdk_snapshot"
542 }
543 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000544 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000545
546 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100547 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000548 if len(visibility) != 0 {
549 snapshotModule.AddProperty("visibility", visibility)
550 }
551
Paul Duffin865171e2020-03-02 18:38:15 +0000552 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000553
Paul Duffincd064672021-04-24 00:47:29 +0100554 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100555 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000556
Paul Duffin2d1bb892021-04-24 11:32:59 +0100557 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100558
Paul Duffin6a7e9532020-03-20 17:50:07 +0000559 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100560
Paul Duffin2d1bb892021-04-24 11:32:59 +0100561 // Create a mapping from osType to combined properties.
562 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
563 for _, combined := range combinedPropertiesList {
564 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
565 }
566
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100567 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000568 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100569 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100570 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000571
Paul Duffin2d1bb892021-04-24 11:32:59 +0100572 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000573 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000574 }
Paul Duffin865171e2020-03-02 18:38:15 +0000575
Jiyong Park8fe14e62020-10-19 22:47:34 +0900576 // If host is supported and any member is host OS dependent then disable host
577 // by default, so that we can enable each host OS variant explicitly. This
578 // avoids problems with implicitly enabled OS variants when the snapshot is
579 // used, which might be different from this run (e.g. different build OS).
580 if s.HostSupported() {
581 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100582 for _, memberVariantDep := range memberVariantDeps {
583 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
584 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900585 if !android.InList(targetString, supportedHostTargets) {
586 supportedHostTargets = append(supportedHostTargets, targetString)
587 }
588 }
589 }
590 if len(supportedHostTargets) > 0 {
591 hostPropertySet := targetPropertySet.AddPropertySet("host")
592 hostPropertySet.AddProperty("enabled", false)
593 }
594 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
595 for _, hostTarget := range supportedHostTargets {
596 propertySet := targetPropertySet.AddPropertySet(hostTarget)
597 propertySet.AddProperty("enabled", true)
598 }
599 }
600
Paul Duffin865171e2020-03-02 18:38:15 +0000601 // Prune any empty property sets.
602 snapshotModule.transform(pruneEmptySetTransformer{})
603
Paul Duffinb645ec82019-11-27 17:43:54 +0000604 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900605}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000606
Paul Duffinf88d8e02020-05-07 20:21:34 +0100607// Check the syntax of the generated Android.bp file contents and if they are
608// invalid then log an error with the contents (tagged with line numbers) and the
609// errors that were found so that it is easy to see where the problem lies.
610func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
611 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
612 if len(errs) != 0 {
613 message := &strings.Builder{}
614 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
615
616Generated Android.bp contents
617========================================================================
618`)
619 for i, line := range strings.Split(contents, "\n") {
620 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
621 }
622
623 _, _ = fmt.Fprint(message, `
624========================================================================
625
626Errors found:
627`)
628
629 for _, err := range errs {
630 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
631 }
632
633 ctx.ModuleErrorf("%s", message.String())
634 }
635}
636
Paul Duffin4b8b7932020-05-06 12:35:38 +0100637func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
638 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
639 if err != nil {
640 ctx.ModuleErrorf("error extracting common properties: %s", err)
641 }
642}
643
Paul Duffinfbe470e2021-04-24 12:37:13 +0100644// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
645type snapshotModuleStaticProperties struct {
646 Compile_multilib string `android:"arch_variant"`
647}
648
Paul Duffin2d1bb892021-04-24 11:32:59 +0100649// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
650type combinedSnapshotModuleProperties struct {
651 // The sdk variant from which this information was collected.
652 sdkVariant *sdk
653
654 // Static snapshot module properties.
655 staticProperties *snapshotModuleStaticProperties
656
657 // The dynamically generated member list properties.
658 dynamicProperties interface{}
659}
660
661// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100662func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
663 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100664 var list []*combinedSnapshotModuleProperties
665 for _, sdkVariant := range sdkVariants {
666 staticProperties := &snapshotModuleStaticProperties{
667 Compile_multilib: sdkVariant.multilibUsages.String(),
668 }
Paul Duffincd064672021-04-24 00:47:29 +0100669 dynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100670
Paul Duffincd064672021-04-24 00:47:29 +0100671 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100672 sdkVariant: sdkVariant,
673 staticProperties: staticProperties,
674 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100675 }
676 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
677
678 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100679 }
Paul Duffincd064672021-04-24 00:47:29 +0100680
681 for _, memberVariantDep := range memberVariantDeps {
682 // If the member dependency is internal then do not add the dependency to the snapshot member
683 // list properties.
684 if !memberVariantDep.export {
685 continue
686 }
687
688 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin13082052021-05-11 00:31:38 +0100689 memberListProperty := s.memberListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100690 memberName := ctx.OtherModuleName(memberVariantDep.variant)
691
Paul Duffin13082052021-05-11 00:31:38 +0100692 if memberListProperty.getter == nil {
693 continue
694 }
695
Paul Duffincd064672021-04-24 00:47:29 +0100696 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100697 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100698 if !android.InList(memberName, memberList) {
699 memberList = append(memberList, memberName)
700 }
Paul Duffin13082052021-05-11 00:31:38 +0100701 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100702 }
703
Paul Duffin2d1bb892021-04-24 11:32:59 +0100704 return list
705}
706
707func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
708
709 // Extract the dynamic properties and add them to a list of propertiesContainer.
710 propertyContainers := []propertiesContainer{}
711 for _, i := range list {
712 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
713 sdkVariant: i.sdkVariant,
714 properties: i.dynamicProperties,
715 })
716 }
717
718 // Extract the common members, removing them from the original properties.
719 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
720 extractor := newCommonValueExtractor(commonDynamicProperties)
721 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
722
723 // Extract the static properties and add them to a list of propertiesContainer.
724 propertyContainers = []propertiesContainer{}
725 for _, i := range list {
726 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
727 sdkVariant: i.sdkVariant,
728 properties: i.staticProperties,
729 })
730 }
731
732 commonStaticProperties := &snapshotModuleStaticProperties{}
733 extractor = newCommonValueExtractor(commonStaticProperties)
734 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
735
736 return &combinedSnapshotModuleProperties{
737 sdkVariant: nil,
738 staticProperties: commonStaticProperties,
739 dynamicProperties: commonDynamicProperties,
740 }
741}
742
743func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
744 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100745 multilib := staticProperties.Compile_multilib
746 if multilib != "" && multilib != "both" {
747 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
748 propertySet.AddProperty("compile_multilib", multilib)
749 }
750
Paul Duffin2d1bb892021-04-24 11:32:59 +0100751 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin865171e2020-03-02 18:38:15 +0000752 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100753 if memberListProperty.getter == nil {
754 continue
755 }
Paul Duffin865171e2020-03-02 18:38:15 +0000756 names := memberListProperty.getter(dynamicMemberTypeListProperties)
757 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000758 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000759 }
760 }
761}
762
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000763type propertyTag struct {
764 name string
765}
766
Paul Duffin0cb37b92020-03-04 14:52:46 +0000767// A BpPropertyTag to add to a property that contains references to other sdk members.
768//
769// This will cause the references to be rewritten to a versioned reference in the version
770// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000771var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000772var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000773
Paul Duffin0cb37b92020-03-04 14:52:46 +0000774// A BpPropertyTag that indicates the property should only be present in the versioned
775// module.
776//
777// This will cause the property to be removed from the unversioned instance of a
778// snapshot module.
779var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
780
Paul Duffine6c0d842020-01-15 14:08:51 +0000781type unversionedToVersionedTransformation struct {
782 identityTransformation
783 builder *snapshotBuilder
784}
785
Paul Duffine6c0d842020-01-15 14:08:51 +0000786func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
787 // Use a versioned name for the module but remember the original name for the
788 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100789 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000790 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000791 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100792 // Remove the prefer property if present as versioned modules never need marking with prefer.
793 module.removeProperty("prefer")
Paul Duffinfb9a7f92021-07-06 17:18:42 +0100794 // Ditto for use_source_config_var
795 module.removeProperty("use_source_config_var")
Paul Duffine6c0d842020-01-15 14:08:51 +0000796 return module
797}
798
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000799func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000800 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
801 required := tag == requiredSdkMemberReferencePropertyTag
802 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000803 } else {
804 return value, tag
805 }
806}
807
Paul Duffin72910952020-01-20 18:16:30 +0000808type unversionedTransformation struct {
809 identityTransformation
810 builder *snapshotBuilder
811}
812
813func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
814 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100815 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000816 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000817 return module
818}
819
820func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000821 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
822 required := tag == requiredSdkMemberReferencePropertyTag
823 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000824 } else if tag == sdkVersionedOnlyPropertyTag {
825 // The property is not allowed in the unversioned module so remove it.
826 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000827 } else {
828 return value, tag
829 }
830}
831
Paul Duffina78f3a72020-02-21 16:29:35 +0000832type pruneEmptySetTransformer struct {
833 identityTransformation
834}
835
836var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
837
838func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
839 if len(propertySet.properties) == 0 {
840 return nil, nil
841 } else {
842 return propertySet, tag
843 }
844}
845
Paul Duffinb645ec82019-11-27 17:43:54 +0000846func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000847 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
848 return true
849 })
850}
851
852func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100853 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000854 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000855 if moduleFilter(bpModule) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100856 contents.IndentedPrintf("\n")
857 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
Paul Duffind0759072021-02-17 11:23:00 +0000858 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100859 contents.IndentedPrintf("}\n")
Paul Duffind0759072021-02-17 11:23:00 +0000860 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000861 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000862}
863
864func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
865 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000866
Paul Duffin0df49682021-05-07 01:10:01 +0100867 addComment := func(name string) {
868 if text, ok := set.comments[name]; ok {
869 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100870 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100871 }
872 }
873 }
874
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000875 // Output the properties first, followed by the nested sets. This ensures a
876 // consistent output irrespective of whether property sets are created before
877 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000878 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000879 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000880
Paul Duffin0df49682021-05-07 01:10:01 +0100881 // Do not write property sets in the properties phase.
882 if _, ok := value.(*bpPropertySet); ok {
883 continue
884 }
885
886 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100887 reflectValue := reflect.ValueOf(value)
888 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000889 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000890
891 for _, name := range set.order {
892 value := set.getValue(name)
893
894 // Only write property sets in the sets phase.
895 switch v := value.(type) {
896 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100897 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100898 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000899 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100900 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000901 }
902 }
903
Paul Duffinb645ec82019-11-27 17:43:54 +0000904 contents.Dedent()
905}
906
Paul Duffina08e4dc2021-06-22 18:19:19 +0100907// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
908// by the value and then followed by a , and a newline.
909func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
910 contents.IndentedPrintf("%s: ", name)
911 outputUnnamedValue(contents, value)
912 contents.UnindentedPrintf(",\n")
913}
914
915// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
916// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
917// indented and all but the last line will end with a newline.
918func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
919 valueType := value.Type()
920 switch valueType.Kind() {
921 case reflect.Bool:
922 contents.UnindentedPrintf("%t", value.Bool())
923
924 case reflect.String:
925 contents.UnindentedPrintf("%q", value)
926
Paul Duffin51227d82021-05-18 12:54:27 +0100927 case reflect.Ptr:
928 outputUnnamedValue(contents, value.Elem())
929
Paul Duffina08e4dc2021-06-22 18:19:19 +0100930 case reflect.Slice:
931 length := value.Len()
932 if length == 0 {
933 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100934 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100935 firstValue := value.Index(0)
936 if length == 1 && !multiLineValue(firstValue) {
937 contents.UnindentedPrintf("[")
938 outputUnnamedValue(contents, firstValue)
939 contents.UnindentedPrintf("]")
940 } else {
941 contents.UnindentedPrintf("[\n")
942 contents.Indent()
943 for i := 0; i < length; i++ {
944 itemValue := value.Index(i)
945 contents.IndentedPrintf("")
946 outputUnnamedValue(contents, itemValue)
947 contents.UnindentedPrintf(",\n")
948 }
949 contents.Dedent()
950 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100951 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100952 }
953
Paul Duffin51227d82021-05-18 12:54:27 +0100954 case reflect.Struct:
955 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
956 v := value.Interface()
957 if _, ok := v.(android.BpPrintable); !ok {
958 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
959 }
960 contents.UnindentedPrintf("{\n")
961 contents.Indent()
962 for f := 0; f < valueType.NumField(); f++ {
963 fieldType := valueType.Field(f)
964 if fieldType.Anonymous {
965 continue
966 }
967 fieldValue := value.Field(f)
968 fieldName := fieldType.Name
969 propertyName := proptools.PropertyNameForField(fieldName)
970 outputNamedValue(contents, propertyName, fieldValue)
971 }
972 contents.Dedent()
973 contents.IndentedPrintf("}")
974
Paul Duffina08e4dc2021-06-22 18:19:19 +0100975 default:
976 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
977 }
978}
979
Paul Duffin51227d82021-05-18 12:54:27 +0100980// multiLineValue returns true if the supplied value may require multiple lines in the output.
981func multiLineValue(value reflect.Value) bool {
982 kind := value.Kind()
983 return kind == reflect.Slice || kind == reflect.Struct
984}
985
Paul Duffinac37c502019-11-26 18:02:20 +0000986func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000987 contents := &generatedContents{}
988 generateBpContents(contents, s.builderForTests.bpFile)
989 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000990}
991
Paul Duffind0759072021-02-17 11:23:00 +0000992func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
993 contents := &generatedContents{}
994 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100995 name := module.Name()
996 // Include modules that are either unversioned or have no name.
997 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000998 })
999 return contents.content.String()
1000}
1001
1002func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
1003 contents := &generatedContents{}
1004 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001005 name := module.Name()
1006 // Include modules that are either versioned or have no name.
1007 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001008 })
1009 return contents.content.String()
1010}
1011
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001012type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +01001013 ctx android.ModuleContext
1014 sdk *sdk
1015
1016 // The version of the generated snapshot.
1017 //
1018 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
1019 // this field.
1020 version string
1021
Paul Duffinb645ec82019-11-27 17:43:54 +00001022 snapshotDir android.OutputPath
1023 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +00001024
1025 // Map from destination to source of each copy - used to eliminate duplicates and
1026 // detect conflicts.
1027 copies map[string]string
1028
Paul Duffinb645ec82019-11-27 17:43:54 +00001029 filesToZip android.Paths
1030 zipsToMerge android.Paths
1031
Paul Duffin5c211452021-07-15 12:42:44 +01001032 // The path to an empty file.
1033 emptyFile android.WritablePath
1034
Paul Duffinb645ec82019-11-27 17:43:54 +00001035 prebuiltModules map[string]*bpModule
1036 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001037
1038 // The set of all members by name.
1039 allMembersByName map[string]struct{}
1040
1041 // The set of exported members by name.
1042 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001043}
1044
1045func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001046 if existing, ok := s.copies[dest]; ok {
1047 if existing != src.String() {
1048 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1049 return
1050 }
1051 } else {
1052 path := s.snapshotDir.Join(s.ctx, dest)
1053 s.ctx.Build(pctx, android.BuildParams{
1054 Rule: android.Cp,
1055 Input: src,
1056 Output: path,
1057 })
1058 s.filesToZip = append(s.filesToZip, path)
1059
1060 s.copies[dest] = src.String()
1061 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001062}
1063
Paul Duffin91547182019-11-12 19:39:36 +00001064func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1065 ctx := s.ctx
1066
1067 // Repackage the zip file so that the entries are in the destDir directory.
1068 // This will allow the zip file to be merged into the snapshot.
1069 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001070
1071 ctx.Build(pctx, android.BuildParams{
1072 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1073 Rule: repackageZip,
1074 Input: zipPath,
1075 Output: tmpZipPath,
1076 Args: map[string]string{
1077 "destdir": destDir,
1078 },
1079 })
Paul Duffin91547182019-11-12 19:39:36 +00001080
1081 // Add the repackaged zip file to the files to merge.
1082 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1083}
1084
Paul Duffin5c211452021-07-15 12:42:44 +01001085func (s *snapshotBuilder) EmptyFile() android.Path {
1086 if s.emptyFile == nil {
1087 ctx := s.ctx
1088 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1089 s.ctx.Build(pctx, android.BuildParams{
1090 Rule: android.Touch,
1091 Output: s.emptyFile,
1092 })
1093 }
1094
1095 return s.emptyFile
1096}
1097
Paul Duffin9d8d6092019-12-05 18:19:29 +00001098func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1099 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001100 if s.prebuiltModules[name] != nil {
1101 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1102 }
1103
1104 m := s.bpFile.newModule(moduleType)
1105 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001106
Paul Duffinbefa4b92020-03-04 14:22:45 +00001107 variant := member.Variants()[0]
1108
Paul Duffin13f02712020-03-06 12:30:43 +00001109 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001110 // An internal member is only referenced from the sdk snapshot which is in the
1111 // same package so can be marked as private.
1112 m.AddProperty("visibility", []string{"//visibility:private"})
1113 } else {
1114 // Extract visibility information from a member variant. All variants have the same
1115 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001116 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1117
1118 // Add any additional visibility rules needed for the prebuilts to reference each other.
1119 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1120 if err != nil {
1121 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1122 }
1123
1124 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001125 if len(visibility) != 0 {
1126 m.AddProperty("visibility", visibility)
1127 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001128 }
1129
Martin Stjernholm1e041092020-11-03 00:11:09 +00001130 // Where available copy apex_available properties from the member.
1131 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1132 apexAvailable := apexAware.ApexAvailable()
1133 if len(apexAvailable) == 0 {
1134 // //apex_available:platform is the default.
1135 apexAvailable = []string{android.AvailableToPlatform}
1136 }
1137
1138 // Add in any baseline apex available settings.
1139 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1140
1141 // Remove duplicates and sort.
1142 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1143 sort.Strings(apexAvailable)
1144
1145 m.AddProperty("apex_available", apexAvailable)
1146 }
1147
Paul Duffinb0bb3762021-05-06 16:48:05 +01001148 // The licenses are the same for all variants.
1149 mctx := s.ctx
1150 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1151 if len(licenseInfo.Licenses) > 0 {
1152 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1153 }
1154
Paul Duffin865171e2020-03-02 18:38:15 +00001155 deviceSupported := false
1156 hostSupported := false
1157
1158 for _, variant := range member.Variants() {
1159 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001160 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001161 hostSupported = true
1162 } else if osClass == android.Device {
1163 deviceSupported = true
1164 }
1165 }
1166
1167 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001168
Paul Duffin0cb37b92020-03-04 14:52:46 +00001169 // Disable installation in the versioned module of those modules that are ever installable.
1170 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1171 if installable.EverInstallable() {
1172 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1173 }
1174 }
1175
Paul Duffinb645ec82019-11-27 17:43:54 +00001176 s.prebuiltModules[name] = m
1177 s.prebuiltOrder = append(s.prebuiltOrder, m)
1178 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001179}
1180
Paul Duffin865171e2020-03-02 18:38:15 +00001181func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001182 // If neither device or host is supported then this module does not support either so will not
1183 // recognize the properties.
1184 if !deviceSupported && !hostSupported {
1185 return
1186 }
1187
Paul Duffin865171e2020-03-02 18:38:15 +00001188 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001189 bpModule.AddProperty("device_supported", false)
1190 }
Paul Duffin865171e2020-03-02 18:38:15 +00001191 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001192 bpModule.AddProperty("host_supported", true)
1193 }
1194}
1195
Paul Duffin13f02712020-03-06 12:30:43 +00001196func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1197 if required {
1198 return requiredSdkMemberReferencePropertyTag
1199 } else {
1200 return optionalSdkMemberReferencePropertyTag
1201 }
1202}
1203
1204func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1205 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001206}
1207
Paul Duffinb645ec82019-11-27 17:43:54 +00001208// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001209func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1210 if _, ok := s.allMembersByName[unversionedName]; !ok {
1211 if required {
1212 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1213 }
1214 return unversionedName
1215 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001216 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1217}
Paul Duffinb645ec82019-11-27 17:43:54 +00001218
Paul Duffin13f02712020-03-06 12:30:43 +00001219func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001220 var references []string = nil
1221 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001222 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001223 }
1224 return references
1225}
Paul Duffin13879572019-11-28 14:31:38 +00001226
Paul Duffin72910952020-01-20 18:16:30 +00001227// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001228func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1229 if _, ok := s.allMembersByName[unversionedName]; !ok {
1230 if required {
1231 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1232 }
1233 return unversionedName
1234 }
1235
1236 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001237 return s.ctx.ModuleName() + "_" + unversionedName
1238 } else {
1239 return unversionedName
1240 }
1241}
1242
Paul Duffin13f02712020-03-06 12:30:43 +00001243func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001244 var references []string = nil
1245 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001246 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001247 }
1248 return references
1249}
1250
Paul Duffin13f02712020-03-06 12:30:43 +00001251func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1252 _, ok := s.exportedMembersByName[memberName]
1253 return !ok
1254}
1255
Martin Stjernholm89238f42020-07-10 00:14:03 +01001256// Add the properties from the given SdkMemberProperties to the blueprint
1257// property set. This handles common properties in SdkMemberPropertiesBase and
1258// calls the member-specific AddToPropertySet for the rest.
1259func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1260 if memberProperties.Base().Compile_multilib != "" {
1261 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1262 }
1263
1264 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1265}
1266
Paul Duffin21827262021-04-24 12:16:36 +01001267// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1268type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001269 // The sdk variant that depends (possibly indirectly) on the member variant.
1270 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001271
1272 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001273 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001274
1275 // The variant that is added to the sdk.
1276 variant android.SdkAware
1277
1278 // True if the member should be exported, i.e. accessible, from outside the sdk.
1279 export bool
1280
1281 // The names of additional component modules provided by the variant.
1282 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001283}
1284
Paul Duffin13879572019-11-28 14:31:38 +00001285var _ android.SdkMember = (*sdkMember)(nil)
1286
Paul Duffin21827262021-04-24 12:16:36 +01001287// sdkMember groups all the variants of a specific member module together along with the name of the
1288// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001289type sdkMember struct {
1290 memberType android.SdkMemberType
1291 name string
1292 variants []android.SdkAware
1293}
1294
1295func (m *sdkMember) Name() string {
1296 return m.name
1297}
1298
1299func (m *sdkMember) Variants() []android.SdkAware {
1300 return m.variants
1301}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001302
Paul Duffin9c3760e2020-03-16 19:52:08 +00001303// Track usages of multilib variants.
1304type multilibUsage int
1305
1306const (
1307 multilibNone multilibUsage = 0
1308 multilib32 multilibUsage = 1
1309 multilib64 multilibUsage = 2
1310 multilibBoth = multilib32 | multilib64
1311)
1312
1313// Add the multilib that is used in the arch type.
1314func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1315 multilib := archType.Multilib
1316 switch multilib {
1317 case "":
1318 return m
1319 case "lib32":
1320 return m | multilib32
1321 case "lib64":
1322 return m | multilib64
1323 default:
1324 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1325 }
1326}
1327
1328func (m multilibUsage) String() string {
1329 switch m {
1330 case multilibNone:
1331 return ""
1332 case multilib32:
1333 return "32"
1334 case multilib64:
1335 return "64"
1336 case multilibBoth:
1337 return "both"
1338 default:
1339 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1340 m, multilibNone, multilib32, multilib64, multilibBoth))
1341 }
1342}
1343
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001344type baseInfo struct {
1345 Properties android.SdkMemberProperties
1346}
1347
Paul Duffinf34f6d82020-04-30 15:48:31 +01001348func (b *baseInfo) optimizableProperties() interface{} {
1349 return b.Properties
1350}
1351
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001352type osTypeSpecificInfo struct {
1353 baseInfo
1354
Paul Duffin00e46802020-03-12 20:40:35 +00001355 osType android.OsType
1356
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001357 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001358 //
1359 // Nil if there is one variant whose arch type is common
1360 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001361}
1362
Paul Duffin4b8b7932020-05-06 12:35:38 +01001363var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1364
Paul Duffinfc8dd232020-03-17 12:51:37 +00001365type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1366
Paul Duffin00e46802020-03-12 20:40:35 +00001367// Create a new osTypeSpecificInfo for the specified os type and its properties
1368// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001369func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001370 osInfo := &osTypeSpecificInfo{
1371 osType: osType,
1372 }
1373
1374 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1375 properties := variantPropertiesFactory()
1376 properties.Base().Os = osType
1377 return properties
1378 }
1379
1380 // Create a structure into which properties common across the architectures in
1381 // this os type will be stored.
1382 osInfo.Properties = osSpecificVariantPropertiesFactory()
1383
1384 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001385 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001386 var archTypes []android.ArchType
1387 for _, variant := range osTypeVariants {
1388 archType := variant.Target().Arch.ArchType
1389 archTypeName := archType.Name
1390 if _, ok := variantsByArchName[archTypeName]; !ok {
1391 archTypes = append(archTypes, archType)
1392 }
1393
1394 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1395 }
1396
1397 if commonVariants, ok := variantsByArchName["common"]; ok {
1398 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001399 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 +00001400 }
1401
1402 // A common arch type only has one variant and its properties should be treated
1403 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001404 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001405 } else {
1406 // Create an arch specific info for each supported architecture type.
1407 for _, archType := range archTypes {
1408 archTypeName := archType.Name
1409
1410 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001411 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001412
1413 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1414 }
1415 }
1416
1417 return osInfo
1418}
1419
1420// Optimize the properties by extracting common properties from arch type specific
1421// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001422func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001423 // Nothing to do if there is only a single common architecture.
1424 if len(osInfo.archInfos) == 0 {
1425 return
1426 }
1427
Paul Duffin9c3760e2020-03-16 19:52:08 +00001428 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001429 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001430 multilib = multilib.addArchType(archInfo.archType)
1431
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001432 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001433 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001434 }
1435
Paul Duffin4b8b7932020-05-06 12:35:38 +01001436 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001437
1438 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001439 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001440}
1441
1442// Add the properties for an os to a property set.
1443//
1444// Maps the properties related to the os variants through to an appropriate
1445// module structure that will produce equivalent set of variants when it is
1446// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001447func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001448
1449 var osPropertySet android.BpPropertySet
1450 var archPropertySet android.BpPropertySet
1451 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001452 if osInfo.Properties.Base().Os_count == 1 &&
1453 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1454 // There is only one OS type present in the variants and it shouldn't have a
1455 // variant-specific target. The latter is the case if it's either for device
1456 // where there is only one OS (android), or for host and the member type
1457 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001458
1459 // Create a structure that looks like:
1460 // module_type {
1461 // name: "...",
1462 // ...
1463 // <common properties>
1464 // ...
1465 // <single os type specific properties>
1466 //
1467 // arch: {
1468 // <arch specific sections>
1469 // }
1470 //
1471 osPropertySet = bpModule
1472 archPropertySet = osPropertySet.AddPropertySet("arch")
1473
1474 // Arch specific properties need to be added to an arch specific section
1475 // within arch.
1476 archOsPrefix = ""
1477 } else {
1478 // Create a structure that looks like:
1479 // module_type {
1480 // name: "...",
1481 // ...
1482 // <common properties>
1483 // ...
1484 // target: {
1485 // <arch independent os specific sections, e.g. android>
1486 // ...
1487 // <arch and os specific sections, e.g. android_x86>
1488 // }
1489 //
1490 osType := osInfo.osType
1491 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1492 archPropertySet = targetPropertySet
1493
1494 // Arch specific properties need to be added to an os and arch specific
1495 // section prefixed with <os>_.
1496 archOsPrefix = osType.Name + "_"
1497 }
1498
1499 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001500 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001501
1502 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1503 // os) specific properties.
1504 //
1505 // The archInfos list will be empty if the os contains variants for the common
1506 // architecture.
1507 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001508 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001509 }
1510}
1511
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001512func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1513 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001514 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001515}
1516
1517var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1518
Paul Duffin4b8b7932020-05-06 12:35:38 +01001519func (osInfo *osTypeSpecificInfo) String() string {
1520 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1521}
1522
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001523type archTypeSpecificInfo struct {
1524 baseInfo
1525
1526 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001527 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001528
1529 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001530}
1531
Paul Duffin4b8b7932020-05-06 12:35:38 +01001532var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1533
Paul Duffinfc8dd232020-03-17 12:51:37 +00001534// Create a new archTypeSpecificInfo for the specified arch type and its properties
1535// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001536func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001537
Paul Duffinfc8dd232020-03-17 12:51:37 +00001538 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001539 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001540
1541 // Create the properties into which the arch type specific properties will be
1542 // added.
1543 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001544
1545 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001546 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001547 } else {
1548 // There is more than one variant for this arch type which must be differentiated
1549 // by link type.
1550 for _, linkVariant := range archVariants {
1551 linkType := getLinkType(linkVariant)
1552 if linkType == "" {
1553 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1554 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001555 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001556
1557 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1558 }
1559 }
1560 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001561
1562 return archInfo
1563}
1564
Paul Duffinf34f6d82020-04-30 15:48:31 +01001565func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1566 return archInfo.Properties
1567}
1568
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001569// Get the link type of the variant
1570//
1571// If the variant is not differentiated by link type then it returns "",
1572// otherwise it returns one of "static" or "shared".
1573func getLinkType(variant android.Module) string {
1574 linkType := ""
1575 if linkable, ok := variant.(cc.LinkableInterface); ok {
1576 if linkable.Shared() && linkable.Static() {
1577 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1578 } else if linkable.Shared() {
1579 linkType = "shared"
1580 } else if linkable.Static() {
1581 linkType = "static"
1582 } else {
1583 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1584 }
1585 }
1586 return linkType
1587}
1588
1589// Optimize the properties by extracting common properties from link type specific
1590// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001591func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001592 if len(archInfo.linkInfos) == 0 {
1593 return
1594 }
1595
Paul Duffin4b8b7932020-05-06 12:35:38 +01001596 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001597}
1598
Paul Duffinfc8dd232020-03-17 12:51:37 +00001599// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001600func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001601 archTypeName := archInfo.archType.Name
1602 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001603 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1604 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1605 archTypePropertySet.AddProperty("enabled", true)
1606 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001607 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001608
1609 for _, linkInfo := range archInfo.linkInfos {
1610 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001611 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001612 }
1613}
1614
Paul Duffin4b8b7932020-05-06 12:35:38 +01001615func (archInfo *archTypeSpecificInfo) String() string {
1616 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1617}
1618
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001619type linkTypeSpecificInfo struct {
1620 baseInfo
1621
1622 linkType string
1623}
1624
Paul Duffin4b8b7932020-05-06 12:35:38 +01001625var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1626
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001627// Create a new linkTypeSpecificInfo for the specified link type and its properties
1628// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001629func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001630 linkInfo := &linkTypeSpecificInfo{
1631 baseInfo: baseInfo{
1632 // Create the properties into which the link type specific properties will be
1633 // added.
1634 Properties: variantPropertiesFactory(),
1635 },
1636 linkType: linkType,
1637 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001638 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001639 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001640}
1641
Paul Duffin4b8b7932020-05-06 12:35:38 +01001642func (l *linkTypeSpecificInfo) String() string {
1643 return fmt.Sprintf("LinkType{%s}", l.linkType)
1644}
1645
Paul Duffin3a4eb502020-03-19 16:11:18 +00001646type memberContext struct {
1647 sdkMemberContext android.ModuleContext
1648 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001649 memberType android.SdkMemberType
1650 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001651}
1652
1653func (m *memberContext) SdkModuleContext() android.ModuleContext {
1654 return m.sdkMemberContext
1655}
1656
1657func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1658 return m.builder
1659}
1660
Paul Duffina551a1c2020-03-17 21:04:24 +00001661func (m *memberContext) MemberType() android.SdkMemberType {
1662 return m.memberType
1663}
1664
1665func (m *memberContext) Name() string {
1666 return m.name
1667}
1668
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001669func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001670
1671 memberType := member.memberType
1672
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001673 // Do not add the prefer property if the member snapshot module is a source module type.
1674 if !memberType.UsesSourceModuleTypeInSnapshot() {
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +00001675 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1676 // snapshot to be created that sets prefer: true.
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001677 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1678 // dynamically at build time not at snapshot generation time.
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001679 config := ctx.sdkMemberContext.Config()
1680 prefer := config.IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001681
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001682 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1683 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1684 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1685 // behavior is for the module.
1686 bpModule.insertAfter("name", "prefer", prefer)
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001687
1688 configVar := config.Getenv("SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR")
1689 if configVar != "" {
1690 parts := strings.Split(configVar, ":")
1691 cfp := android.ConfigVarProperties{
1692 Config_namespace: proptools.StringPtr(parts[0]),
1693 Var_name: proptools.StringPtr(parts[1]),
1694 }
1695 bpModule.insertAfter("prefer", "use_source_config_var", cfp)
1696 }
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001697 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001698
Paul Duffina04c1072020-03-02 10:16:35 +00001699 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001700 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001701 variants := member.Variants()
1702 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001703 osType := variant.Target().Os
1704 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001705 }
1706
Paul Duffina04c1072020-03-02 10:16:35 +00001707 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001708 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001709 properties := memberType.CreateVariantPropertiesStruct()
1710 base := properties.Base()
1711 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001712 return properties
1713 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001714
Paul Duffina04c1072020-03-02 10:16:35 +00001715 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001716
Paul Duffina04c1072020-03-02 10:16:35 +00001717 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001718 commonProperties := variantPropertiesFactory()
1719 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001720
Paul Duffinc097e362020-03-10 22:50:03 +00001721 // Create common value extractor that can be used to optimize the properties.
1722 commonValueExtractor := newCommonValueExtractor(commonProperties)
1723
Paul Duffina04c1072020-03-02 10:16:35 +00001724 // The list of property structures which are os type specific but common across
1725 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001726 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001727
1728 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001729 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001730 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001731 // Add the os specific properties to a list of os type specific yet architecture
1732 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001733 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001734
Paul Duffin00e46802020-03-12 20:40:35 +00001735 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001736 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001737 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001738
Paul Duffina04c1072020-03-02 10:16:35 +00001739 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001740 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001741
Paul Duffina04c1072020-03-02 10:16:35 +00001742 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001743 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001744
Paul Duffina04c1072020-03-02 10:16:35 +00001745 // Create a target property set into which target specific properties can be
1746 // added.
1747 targetPropertySet := bpModule.AddPropertySet("target")
1748
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001749 // If the member is host OS dependent and has host_supported then disable by
1750 // default and enable each host OS variant explicitly. This avoids problems
1751 // with implicitly enabled OS variants when the snapshot is used, which might
1752 // be different from this run (e.g. different build OS).
1753 if ctx.memberType.IsHostOsDependent() {
1754 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1755 if hostSupported {
1756 hostPropertySet := targetPropertySet.AddPropertySet("host")
1757 hostPropertySet.AddProperty("enabled", false)
1758 }
1759 }
1760
Paul Duffina04c1072020-03-02 10:16:35 +00001761 // Iterate over the os types in a fixed order.
1762 for _, osType := range s.getPossibleOsTypes() {
1763 osInfo := osTypeToInfo[osType]
1764 if osInfo == nil {
1765 continue
1766 }
1767
Paul Duffin3a4eb502020-03-19 16:11:18 +00001768 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001769 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001770}
1771
Paul Duffina04c1072020-03-02 10:16:35 +00001772// Compute the list of possible os types that this sdk could support.
1773func (s *sdk) getPossibleOsTypes() []android.OsType {
1774 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001775 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001776 if s.DeviceSupported() {
1777 if osType.Class == android.Device && osType != android.Fuchsia {
1778 osTypes = append(osTypes, osType)
1779 }
1780 }
1781 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001782 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001783 osTypes = append(osTypes, osType)
1784 }
1785 }
1786 }
1787 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1788 return osTypes
1789}
1790
Paul Duffinb28369a2020-05-04 15:39:59 +01001791// Given a set of properties (struct value), return the value of the field within that
1792// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001793type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1794
Paul Duffinc459f892020-04-30 18:08:29 +01001795// Checks the metadata to determine whether the property should be ignored for the
1796// purposes of common value extraction or not.
1797type extractorMetadataPredicate func(metadata propertiesContainer) bool
1798
1799// Indicates whether optimizable properties are provided by a host variant or
1800// not.
1801type isHostVariant interface {
1802 isHostVariant() bool
1803}
1804
Paul Duffinb28369a2020-05-04 15:39:59 +01001805// A property that can be optimized by the commonValueExtractor.
1806type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001807 // The name of the field for this property. It is a "."-separated path for
1808 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001809 name string
1810
Paul Duffinc459f892020-04-30 18:08:29 +01001811 // Filter that can use metadata associated with the properties being optimized
1812 // to determine whether the field should be ignored during common value
1813 // optimization.
1814 filter extractorMetadataPredicate
1815
Paul Duffinb28369a2020-05-04 15:39:59 +01001816 // Retrieves the value on which common value optimization will be performed.
1817 getter fieldAccessorFunc
1818
1819 // The empty value for the field.
1820 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001821
1822 // True if the property can support arch variants false otherwise.
1823 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001824}
1825
Paul Duffin4b8b7932020-05-06 12:35:38 +01001826func (p extractorProperty) String() string {
1827 return p.name
1828}
1829
Paul Duffinc097e362020-03-10 22:50:03 +00001830// Supports extracting common values from a number of instances of a properties
1831// structure into a separate common set of properties.
1832type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001833 // The properties that the extractor can optimize.
1834 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001835}
1836
1837// Create a new common value extractor for the structure type for the supplied
1838// properties struct.
1839//
1840// The returned extractor can be used on any properties structure of the same type
1841// as the supplied set of properties.
1842func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1843 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1844 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001845 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001846 return extractor
1847}
1848
1849// Gather the fields from the supplied structure type from which common values will
1850// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001851//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001852// This is recursive function. If it encounters a struct then it will recurse
1853// into it, passing in the accessor for the field and the struct name as prefix
1854// for the nested fields. That will then be used in the accessors for the fields
1855// in the embedded struct.
1856func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001857 for f := 0; f < structType.NumField(); f++ {
1858 field := structType.Field(f)
1859 if field.PkgPath != "" {
1860 // Ignore unexported fields.
1861 continue
1862 }
1863
Paul Duffinb07fa512020-03-10 22:17:04 +00001864 // Ignore fields whose value should be kept.
1865 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001866 continue
1867 }
1868
Paul Duffinc459f892020-04-30 18:08:29 +01001869 var filter extractorMetadataPredicate
1870
1871 // Add a filter
1872 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1873 filter = func(metadata propertiesContainer) bool {
1874 if m, ok := metadata.(isHostVariant); ok {
1875 if m.isHostVariant() {
1876 return false
1877 }
1878 }
1879 return true
1880 }
1881 }
1882
Paul Duffinc097e362020-03-10 22:50:03 +00001883 // Save a copy of the field index for use in the function.
1884 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001885
Martin Stjernholmb0249572020-09-15 02:32:35 +01001886 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001887
Paul Duffinc097e362020-03-10 22:50:03 +00001888 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001889 if containingStructAccessor != nil {
1890 // This is an embedded structure so first access the field for the embedded
1891 // structure.
1892 value = containingStructAccessor(value)
1893 }
1894
Paul Duffinc097e362020-03-10 22:50:03 +00001895 // Skip through interface and pointer values to find the structure.
1896 value = getStructValue(value)
1897
Paul Duffin4b8b7932020-05-06 12:35:38 +01001898 defer func() {
1899 if r := recover(); r != nil {
1900 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1901 }
1902 }()
1903
Paul Duffinc097e362020-03-10 22:50:03 +00001904 // Return the field.
1905 return value.Field(fieldIndex)
1906 }
1907
Martin Stjernholmb0249572020-09-15 02:32:35 +01001908 if field.Type.Kind() == reflect.Struct {
1909 // Gather fields from the nested or embedded structure.
1910 var subNamePrefix string
1911 if field.Anonymous {
1912 subNamePrefix = namePrefix
1913 } else {
1914 subNamePrefix = name + "."
1915 }
1916 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001917 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001918 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001919 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001920 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001921 fieldGetter,
1922 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001923 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001924 }
1925 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001926 }
Paul Duffinc097e362020-03-10 22:50:03 +00001927 }
1928}
1929
1930func getStructValue(value reflect.Value) reflect.Value {
1931foundStruct:
1932 for {
1933 kind := value.Kind()
1934 switch kind {
1935 case reflect.Interface, reflect.Ptr:
1936 value = value.Elem()
1937 case reflect.Struct:
1938 break foundStruct
1939 default:
1940 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1941 }
1942 }
1943 return value
1944}
1945
Paul Duffinf34f6d82020-04-30 15:48:31 +01001946// A container of properties to be optimized.
1947//
1948// Allows additional information to be associated with the properties, e.g. for
1949// filtering.
1950type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001951 fmt.Stringer
1952
Paul Duffinf34f6d82020-04-30 15:48:31 +01001953 // Get the properties that need optimizing.
1954 optimizableProperties() interface{}
1955}
1956
Paul Duffin2d1bb892021-04-24 11:32:59 +01001957// A wrapper for sdk variant related properties to allow them to be optimized.
1958type sdkVariantPropertiesContainer struct {
1959 sdkVariant *sdk
1960 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01001961}
1962
Paul Duffin2d1bb892021-04-24 11:32:59 +01001963func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
1964 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01001965}
1966
Paul Duffin2d1bb892021-04-24 11:32:59 +01001967func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001968 return c.sdkVariant.String()
1969}
1970
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001971// Extract common properties from a slice of property structures of the same type.
1972//
1973// All the property structures must be of the same type.
1974// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001975// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001976//
1977// Iterates over each exported field (capitalized name) and checks to see whether they
1978// have the same value (using DeepEquals) across all the input properties. If it does not then no
1979// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001980// and the field in each of the input properties structure is set to its default value. Nested
1981// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001982func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001983 commonPropertiesValue := reflect.ValueOf(commonProperties)
1984 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001985
Paul Duffinf34f6d82020-04-30 15:48:31 +01001986 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1987
Paul Duffinb28369a2020-05-04 15:39:59 +01001988 for _, property := range e.properties {
1989 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001990 filter := property.filter
1991 if filter == nil {
1992 filter = func(metadata propertiesContainer) bool {
1993 return true
1994 }
1995 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001996
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001997 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001998 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1999 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002000 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002001
Paul Duffin864e1b42020-05-06 10:23:19 +01002002 // Assume that all the values will be the same.
2003 //
2004 // While similar to this is not quite the same as commonValue == nil. If all the values
2005 // have been filtered out then this will be false but commonValue == nil will be true.
2006 valuesDiffer := false
2007
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002008 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002009 container := sliceValue.Index(i).Interface().(propertiesContainer)
2010 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002011 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002012
Paul Duffinc459f892020-04-30 18:08:29 +01002013 if !filter(container) {
2014 expectedValue := property.emptyValue.Interface()
2015 actualValue := fieldValue.Interface()
2016 if !reflect.DeepEqual(expectedValue, actualValue) {
2017 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2018 }
2019 continue
2020 }
2021
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002022 if commonValue == nil {
2023 // Use the first value as the commonProperties value.
2024 commonValue = &fieldValue
2025 } else {
2026 // If the value does not match the current common value then there is
2027 // no value in common so break out.
2028 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2029 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002030 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002031 break
2032 }
2033 }
2034 }
2035
Paul Duffin864e1b42020-05-06 10:23:19 +01002036 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002037 // and set the input struct's field to the empty value.
2038 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002039 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002040 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002041 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002042 container := sliceValue.Index(i).Interface().(propertiesContainer)
2043 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002044 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002045 fieldValue.Set(emptyValue)
2046 }
2047 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002048
2049 if valuesDiffer && !property.archVariant {
2050 // The values differ but the property does not support arch variants so it
2051 // is an error.
2052 var details strings.Builder
2053 for i := 0; i < sliceValue.Len(); i++ {
2054 container := sliceValue.Index(i).Interface().(propertiesContainer)
2055 itemValue := reflect.ValueOf(container.optimizableProperties())
2056 fieldValue := fieldGetter(itemValue)
2057
2058 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2059 }
2060
2061 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2062 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002063 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002064
2065 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002066}