blob: 96a6e6913ca7e3212a2e07b9ec9bd4463a442530 [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"
Colin Crosscb0ac952021-07-20 13:17:15 -070025
Paul Duffin375058f2019-11-29 20:17:53 +000026 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090027 "github.com/google/blueprint/proptools"
28
29 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090030)
31
Paul Duffin64fb5262021-05-05 21:36:04 +010032// Environment variables that affect the generated snapshot
33// ========================================================
34//
35// SOONG_SDK_SNAPSHOT_PREFER
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +000036// By default every unversioned module in the generated snapshot has prefer: false. Building it
37// with SOONG_SDK_SNAPSHOT_PREFER=true will force them to use prefer: true.
Paul Duffin64fb5262021-05-05 21:36:04 +010038//
Paul Duffinfb9a7f92021-07-06 17:18:42 +010039// SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR
40// If set this specifies the Soong config var that can be used to control whether the prebuilt
41// modules from the generated snapshot or the original source modules. Values must be a colon
42// separated pair of strings, the first of which is the Soong config namespace, and the second
43// is the name of the variable within that namespace.
44//
45// The config namespace and var name are used to set the `use_source_config_var` property. That
46// in turn will cause the generated prebuilts to use the soong config variable to select whether
47// source or the prebuilt is used.
48// e.g. If an sdk snapshot is built using:
49// m SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR=acme:build_from_source sdkextensions-sdk
50// Then the resulting snapshot will include:
51// use_source_config_var: {
52// config_namespace: "acme",
53// var_name: "build_from_source",
54// }
55//
56// Assuming that the config variable is defined in .mk using something like:
57// $(call add_soong_config_namespace,acme)
58// $(call add_soong_config_var_value,acme,build_from_source,true)
59//
60// Then when the snapshot is unpacked in the repository it will have the following behavior:
61// m droid - will use the sdkextensions-sdk prebuilts if present. Otherwise, it will use the
62// sources.
63// m SOONG_CONFIG_acme_build_from_source=true droid - will use the sdkextensions-sdk
64// sources, if present. Otherwise, it will use the prebuilts.
65//
66// This is a temporary mechanism to control the prefer flags and will be removed once a more
67// maintainable solution has been implemented.
68// TODO(b/174997203): Remove when no longer necessary.
69//
Paul Duffin43f7bf02021-05-05 22:00:51 +010070// SOONG_SDK_SNAPSHOT_VERSION
71// This provides control over the version of the generated snapshot.
72//
73// SOONG_SDK_SNAPSHOT_VERSION=current will generate unversioned and versioned prebuilts and a
74// versioned snapshot module. This is the default behavior. The zip file containing the
75// generated snapshot will be <sdk-name>-current.zip.
76//
77// SOONG_SDK_SNAPSHOT_VERSION=unversioned will generate unversioned prebuilts only and the zip
78// file containing the generated snapshot will be <sdk-name>.zip.
79//
80// SOONG_SDK_SNAPSHOT_VERSION=<number> will generate versioned prebuilts and a versioned
81// snapshot module only. The zip file containing the generated snapshot will be
82// <sdk-name>-<number>.zip.
83//
Paul Duffin64fb5262021-05-05 21:36:04 +010084
Jiyong Park9b409bc2019-10-11 14:59:13 +090085var pctx = android.NewPackageContext("android/soong/sdk")
86
Paul Duffin375058f2019-11-29 20:17:53 +000087var (
88 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
89 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000090 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000091 CommandDeps: []string{
92 "${config.Zip2ZipCmd}",
93 },
94 },
95 "destdir")
96
97 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
98 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -070099 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +0000100 CommandDeps: []string{
101 "${config.SoongZipCmd}",
102 },
103 Rspfile: "$out.rsp",
104 RspfileContent: "$in",
105 },
106 "basedir")
107
108 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
109 blueprint.RuleParams{
110 Command: `${config.MergeZipsCmd} $out $in`,
111 CommandDeps: []string{
112 "${config.MergeZipsCmd}",
113 },
114 })
115)
116
Paul Duffin43f7bf02021-05-05 22:00:51 +0100117const (
118 soongSdkSnapshotVersionUnversioned = "unversioned"
119 soongSdkSnapshotVersionCurrent = "current"
120)
121
Paul Duffinb645ec82019-11-27 17:43:54 +0000122type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +0900123 content strings.Builder
124 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +0900125}
126
Paul Duffinb645ec82019-11-27 17:43:54 +0000127// generatedFile abstracts operations for writing contents into a file and emit a build rule
128// for the file.
129type generatedFile struct {
130 generatedContents
131 path android.OutputPath
132}
133
Jiyong Park232e7852019-11-04 12:23:40 +0900134func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +0900135 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +0000136 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +0900137 }
138}
139
Paul Duffinb645ec82019-11-27 17:43:54 +0000140func (gc *generatedContents) Indent() {
141 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +0900142}
143
Paul Duffinb645ec82019-11-27 17:43:54 +0000144func (gc *generatedContents) Dedent() {
145 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +0900146}
147
Paul Duffina08e4dc2021-06-22 18:19:19 +0100148// IndentedPrintf will add spaces to indent the line to the appropriate level before printing the
149// arguments.
150func (gc *generatedContents) IndentedPrintf(format string, args ...interface{}) {
151 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format, args...)
152}
153
154// UnindentedPrintf does not add spaces to indent the line to the appropriate level before printing
155// the arguments.
156func (gc *generatedContents) UnindentedPrintf(format string, args ...interface{}) {
157 fmt.Fprintf(&(gc.content), format, args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900158}
159
160func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -0800161 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +0100162
163 content := gf.content.String()
164
165 // ninja consumes newline characters in rspfile_content. Prevent it by
166 // escaping the backslash in the newline character. The extra backslash
167 // is removed when the rspfile is written to the actual script file
168 content = strings.ReplaceAll(content, "\n", "\\n")
169
Jiyong Park9b409bc2019-10-11 14:59:13 +0900170 rb.Command().
171 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100172 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100173 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900174 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
175 rb.Command().
176 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800177 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900178}
179
Paul Duffin13879572019-11-28 14:31:38 +0000180// Collect all the members.
181//
Paul Duffinb97b1572021-04-29 21:50:40 +0100182// Updates the sdk module with a list of sdkMemberVariantDep instances and details as to which
183// multilibs (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000184func (s *sdk) collectMembers(ctx android.ModuleContext) {
185 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000186 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
187 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000188 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
Paul Duffineee466e2021-04-27 23:17:56 +0100189 memberType := memberTag.SdkMemberType(child)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900190
Paul Duffin5cca7c42021-05-26 10:16:01 +0100191 // If a nil SdkMemberType was returned then this module should not be added to the sdk.
192 if memberType == nil {
193 return false
194 }
195
Paul Duffin13879572019-11-28 14:31:38 +0000196 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000197 if !memberType.IsInstance(child) {
198 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900199 }
Paul Duffin13879572019-11-28 14:31:38 +0000200
Paul Duffin6a7e9532020-03-20 17:50:07 +0000201 // Keep track of which multilib variants are used by the sdk.
202 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
203
Paul Duffinb97b1572021-04-29 21:50:40 +0100204 var exportedComponentsInfo android.ExportedComponentsInfo
205 if ctx.OtherModuleHasProvider(child, android.ExportedComponentsInfoProvider) {
206 exportedComponentsInfo = ctx.OtherModuleProvider(child, android.ExportedComponentsInfoProvider).(android.ExportedComponentsInfo)
207 }
208
Paul Duffina7208112021-04-23 21:20:20 +0100209 export := memberTag.ExportMember()
Paul Duffinb97b1572021-04-29 21:50:40 +0100210 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{
211 s, memberType, child.(android.SdkAware), export, exportedComponentsInfo,
212 })
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000213
Paul Duffin2d3da312021-05-06 12:02:27 +0100214 // Recurse down into the member's dependencies as it may have dependencies that need to be
215 // automatically added to the sdk.
216 return true
Jiyong Park73c54ee2019-10-22 20:31:18 +0900217 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000218
219 return false
Paul Duffin13879572019-11-28 14:31:38 +0000220 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000221}
222
Paul Duffincc3132e2021-04-24 01:10:30 +0100223// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
224// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000225//
Paul Duffincc3132e2021-04-24 01:10:30 +0100226// The sdkMember instances are then grouped into slices by member type. Within each such slice the
227// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000228//
Paul Duffincc3132e2021-04-24 01:10:30 +0100229// Finally, the member type slices are concatenated together to form a single slice. The order in
230// which they are concatenated is the order in which the member types were registered in the
231// android.SdkMemberTypesRegistry.
232func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000233 byType := make(map[android.SdkMemberType][]*sdkMember)
234 byName := make(map[string]*sdkMember)
235
Paul Duffin21827262021-04-24 12:16:36 +0100236 for _, memberVariantDep := range memberVariantDeps {
237 memberType := memberVariantDep.memberType
238 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000239
240 name := ctx.OtherModuleName(variant)
241 member := byName[name]
242 if member == nil {
243 member = &sdkMember{memberType: memberType, name: name}
244 byName[name] = member
245 byType[memberType] = append(byType[memberType], member)
246 }
247
Paul Duffin1356d8c2020-02-25 19:26:33 +0000248 // Only append new variants to the list. This is needed because a member can be both
249 // exported by the sdk and also be a transitive sdk member.
250 member.variants = appendUniqueVariants(member.variants, variant)
251 }
252
Paul Duffin13879572019-11-28 14:31:38 +0000253 var members []*sdkMember
Paul Duffin62782de2021-07-14 12:05:16 +0100254 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000255 membersOfType := byType[memberListProperty.memberType]
256 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900257 }
258
Paul Duffin6a7e9532020-03-20 17:50:07 +0000259 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900260}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900261
Paul Duffin72910952020-01-20 18:16:30 +0000262func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
263 for _, v := range variants {
264 if v == newVariant {
265 return variants
266 }
267 }
268 return append(variants, newVariant)
269}
270
Jiyong Park73c54ee2019-10-22 20:31:18 +0900271// SDK directory structure
272// <sdk_root>/
273// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
274// <api_ver>/ : below this directory are all auto-generated
275// Android.bp : definition of 'sdk_snapshot' module is here
276// aidl/
277// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
278// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900279// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900280// include/
281// bionic/libc/include/stdlib.h : an exported header file
282// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900283// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900284// <arch>/include/ : arch-specific exported headers
285// <arch>/include_gen/ : arch-specific generated headers
286// <arch>/lib/
287// libFoo.so : a stub library
288
Jiyong Park232e7852019-11-04 12:23:40 +0900289// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900290// This isn't visible to users, so could be changed in future.
291func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
292 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
293}
294
Jiyong Park232e7852019-11-04 12:23:40 +0900295// buildSnapshot is the main function in this source file. It creates rules to copy
296// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000297func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
298
Paul Duffinb97b1572021-04-29 21:50:40 +0100299 // Aggregate all the sdkMemberVariantDep instances from all the sdk variants.
Paul Duffin62131702021-05-07 01:10:01 +0100300 hasLicenses := false
Paul Duffin21827262021-04-24 12:16:36 +0100301 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000302 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100303 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffinb97b1572021-04-29 21:50:40 +0100304 }
Paul Duffin865171e2020-03-02 18:38:15 +0000305
Paul Duffinb97b1572021-04-29 21:50:40 +0100306 // Filter out any sdkMemberVariantDep that is a component of another.
307 memberVariantDeps = filterOutComponents(ctx, memberVariantDeps)
Paul Duffin13f02712020-03-06 12:30:43 +0000308
Paul Duffinb97b1572021-04-29 21:50:40 +0100309 // Record the names of all the members, both explicitly specified and implicitly
310 // included.
311 allMembersByName := make(map[string]struct{})
312 exportedMembersByName := make(map[string]struct{})
Paul Duffin62131702021-05-07 01:10:01 +0100313
Paul Duffinb97b1572021-04-29 21:50:40 +0100314 addMember := func(name string, export bool) {
315 allMembersByName[name] = struct{}{}
316 if export {
317 exportedMembersByName[name] = struct{}{}
318 }
319 }
320
321 for _, memberVariantDep := range memberVariantDeps {
322 name := memberVariantDep.variant.Name()
323 export := memberVariantDep.export
324
325 addMember(name, export)
326
327 // Add any components provided by the module.
328 for _, component := range memberVariantDep.exportedComponentsInfo.Components {
329 addMember(component, export)
330 }
331
332 if memberVariantDep.memberType == android.LicenseModuleSdkMemberType {
333 hasLicenses = true
Paul Duffin865171e2020-03-02 18:38:15 +0000334 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000335 }
336
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000337 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900338
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000339 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000340
341 bpFile := &bpFile{
342 modules: make(map[string]*bpModule),
343 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000344
Paul Duffin43f7bf02021-05-05 22:00:51 +0100345 config := ctx.Config()
346 version := config.GetenvWithDefault("SOONG_SDK_SNAPSHOT_VERSION", "current")
347
348 // Generate versioned modules in the snapshot unless an unversioned snapshot has been requested.
349 generateVersioned := version != soongSdkSnapshotVersionUnversioned
350
351 // Generate unversioned modules in the snapshot unless a numbered snapshot has been requested.
352 //
353 // Unversioned modules are not required in that case because the numbered version will be a
354 // finalized version of the snapshot that is intended to be kept separate from the
355 generateUnversioned := version == soongSdkSnapshotVersionUnversioned || version == soongSdkSnapshotVersionCurrent
356 snapshotZipFileSuffix := ""
357 if generateVersioned {
358 snapshotZipFileSuffix = "-" + version
359 }
360
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000361 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000362 ctx: ctx,
363 sdk: s,
Paul Duffin43f7bf02021-05-05 22:00:51 +0100364 version: version,
Paul Duffin13f02712020-03-06 12:30:43 +0000365 snapshotDir: snapshotDir.OutputPath,
366 copies: make(map[string]string),
367 filesToZip: []android.Path{bp.path},
368 bpFile: bpFile,
369 prebuiltModules: make(map[string]*bpModule),
370 allMembersByName: allMembersByName,
371 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900372 }
Paul Duffinac37c502019-11-26 18:02:20 +0000373 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900374
Paul Duffin62131702021-05-07 01:10:01 +0100375 // If the sdk snapshot includes any license modules then add a package module which has a
376 // default_applicable_licenses property. That will prevent the LSC license process from updating
377 // the generated Android.bp file to add a package module that includes all licenses used by all
378 // the modules in that package. That would be unnecessary as every module in the sdk should have
379 // their own licenses property specified.
380 if hasLicenses {
381 pkg := bpFile.newModule("package")
382 property := "default_applicable_licenses"
383 pkg.AddCommentForProperty(property, `
384A default list here prevents the license LSC from adding its own list which would
385be unnecessary as every module in the sdk already has its own licenses property.
386`)
387 pkg.AddProperty(property, []string{"Android-Apache-2.0"})
388 bpFile.AddModule(pkg)
389 }
390
Paul Duffin0df49682021-05-07 01:10:01 +0100391 // Group the variants for each member module together and then group the members of each member
392 // type together.
Paul Duffincc3132e2021-04-24 01:10:30 +0100393 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin0df49682021-05-07 01:10:01 +0100394
395 // Create the prebuilt modules for each of the member modules.
Paul Duffin13ad94f2020-02-19 16:19:27 +0000396 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000397 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000398
Paul Duffina551a1c2020-03-17 21:04:24 +0000399 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000400
401 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100402 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900403 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900404
Paul Duffine6c0d842020-01-15 14:08:51 +0000405 // Create a transformer that will transform an unversioned module into a versioned module.
406 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
407
Paul Duffin72910952020-01-20 18:16:30 +0000408 // Create a transformer that will transform an unversioned module by replacing any references
409 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100410 unversionedTransformer := unversionedTransformation{
411 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100412 }
Paul Duffin72910952020-01-20 18:16:30 +0000413
Paul Duffinb645ec82019-11-27 17:43:54 +0000414 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000415 // Prune any empty property sets.
416 unversioned = unversioned.transform(pruneEmptySetTransformer{})
417
Paul Duffin43f7bf02021-05-05 22:00:51 +0100418 if generateVersioned {
419 // Copy the unversioned module so it can be modified to make it versioned.
420 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000421
Paul Duffin43f7bf02021-05-05 22:00:51 +0100422 // Transform the unversioned module into a versioned one.
423 versioned.transform(unversionedToVersionedTransformer)
424 bpFile.AddModule(versioned)
425 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000426
Paul Duffin43f7bf02021-05-05 22:00:51 +0100427 if generateUnversioned {
428 // Transform the unversioned module to make it suitable for use in the snapshot.
429 unversioned.transform(unversionedTransformer)
430 bpFile.AddModule(unversioned)
431 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000432 }
433
Paul Duffin43f7bf02021-05-05 22:00:51 +0100434 if generateVersioned {
435 // Add the sdk/module_exports_snapshot module to the bp file.
436 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
437 }
Paul Duffin26197a62021-04-24 00:34:10 +0100438
439 // generate Android.bp
440 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
441 generateBpContents(&bp.generatedContents, bpFile)
442
443 contents := bp.content.String()
444 syntaxCheckSnapshotBpFile(ctx, contents)
445
446 bp.build(pctx, ctx, nil)
447
448 filesToZip := builder.filesToZip
449
450 // zip them all
Paul Duffin43f7bf02021-05-05 22:00:51 +0100451 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotZipFileSuffix)
452 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100453 outputDesc := "Building snapshot for " + ctx.ModuleName()
454
455 // If there are no zips to merge then generate the output zip directly.
456 // Otherwise, generate an intermediate zip file into which other zips can be
457 // merged.
458 var zipFile android.OutputPath
459 var desc string
460 if len(builder.zipsToMerge) == 0 {
461 zipFile = outputZipFile
462 desc = outputDesc
463 } else {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100464 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotZipFileSuffix)
465 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100466 desc = "Building intermediate snapshot for " + ctx.ModuleName()
467 }
468
469 ctx.Build(pctx, android.BuildParams{
470 Description: desc,
471 Rule: zipFiles,
472 Inputs: filesToZip,
473 Output: zipFile,
474 Args: map[string]string{
475 "basedir": builder.snapshotDir.String(),
476 },
477 })
478
479 if len(builder.zipsToMerge) != 0 {
480 ctx.Build(pctx, android.BuildParams{
481 Description: outputDesc,
482 Rule: mergeZips,
483 Input: zipFile,
484 Inputs: builder.zipsToMerge,
485 Output: outputZipFile,
486 })
487 }
488
489 return outputZipFile
490}
491
Paul Duffinb97b1572021-04-29 21:50:40 +0100492// filterOutComponents removes any item from the deps list that is a component of another item in
493// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
494// then it will remove "foo.stubs" from the deps.
495func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
496 // Collate the set of components that all the modules added to the sdk provide.
497 components := map[string]*sdkMemberVariantDep{}
498 for i, _ := range deps {
499 dep := &deps[i]
500 for _, c := range dep.exportedComponentsInfo.Components {
501 components[c] = dep
502 }
503 }
504
505 // If no module provides components then return the input deps unfiltered.
506 if len(components) == 0 {
507 return deps
508 }
509
510 filtered := make([]sdkMemberVariantDep, 0, len(deps))
511 for _, dep := range deps {
512 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
513 if owner, ok := components[name]; ok {
514 // This is a component of another module that is a member of the sdk.
515
516 // If the component is exported but the owning module is not then the configuration is not
517 // supported.
518 if dep.export && !owner.export {
519 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
520 continue
521 }
522
523 // This module must not be added to the list of members of the sdk as that would result in a
524 // duplicate module in the sdk snapshot.
525 continue
526 }
527
528 filtered = append(filtered, dep)
529 }
530 return filtered
531}
532
Paul Duffin26197a62021-04-24 00:34:10 +0100533// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100534func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100535 bpFile := builder.bpFile
536
Paul Duffinb645ec82019-11-27 17:43:54 +0000537 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000538 var snapshotModuleType string
539 if s.properties.Module_exports {
540 snapshotModuleType = "module_exports_snapshot"
541 } else {
542 snapshotModuleType = "sdk_snapshot"
543 }
544 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000545 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000546
547 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100548 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000549 if len(visibility) != 0 {
550 snapshotModule.AddProperty("visibility", visibility)
551 }
552
Paul Duffin865171e2020-03-02 18:38:15 +0000553 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000554
Paul Duffincd064672021-04-24 00:47:29 +0100555 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100556 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000557
Paul Duffin2d1bb892021-04-24 11:32:59 +0100558 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100559
Paul Duffin6a7e9532020-03-20 17:50:07 +0000560 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100561
Paul Duffin2d1bb892021-04-24 11:32:59 +0100562 // Create a mapping from osType to combined properties.
563 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
564 for _, combined := range combinedPropertiesList {
565 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
566 }
567
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100568 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000569 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100570 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100571 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000572
Paul Duffin2d1bb892021-04-24 11:32:59 +0100573 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000574 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000575 }
Paul Duffin865171e2020-03-02 18:38:15 +0000576
Jiyong Park8fe14e62020-10-19 22:47:34 +0900577 // If host is supported and any member is host OS dependent then disable host
578 // by default, so that we can enable each host OS variant explicitly. This
579 // avoids problems with implicitly enabled OS variants when the snapshot is
580 // used, which might be different from this run (e.g. different build OS).
581 if s.HostSupported() {
582 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100583 for _, memberVariantDep := range memberVariantDeps {
584 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
585 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900586 if !android.InList(targetString, supportedHostTargets) {
587 supportedHostTargets = append(supportedHostTargets, targetString)
588 }
589 }
590 }
591 if len(supportedHostTargets) > 0 {
592 hostPropertySet := targetPropertySet.AddPropertySet("host")
593 hostPropertySet.AddProperty("enabled", false)
594 }
595 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
596 for _, hostTarget := range supportedHostTargets {
597 propertySet := targetPropertySet.AddPropertySet(hostTarget)
598 propertySet.AddProperty("enabled", true)
599 }
600 }
601
Paul Duffin865171e2020-03-02 18:38:15 +0000602 // Prune any empty property sets.
603 snapshotModule.transform(pruneEmptySetTransformer{})
604
Paul Duffinb645ec82019-11-27 17:43:54 +0000605 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900606}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000607
Paul Duffinf88d8e02020-05-07 20:21:34 +0100608// Check the syntax of the generated Android.bp file contents and if they are
609// invalid then log an error with the contents (tagged with line numbers) and the
610// errors that were found so that it is easy to see where the problem lies.
611func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
612 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
613 if len(errs) != 0 {
614 message := &strings.Builder{}
615 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
616
617Generated Android.bp contents
618========================================================================
619`)
620 for i, line := range strings.Split(contents, "\n") {
621 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
622 }
623
624 _, _ = fmt.Fprint(message, `
625========================================================================
626
627Errors found:
628`)
629
630 for _, err := range errs {
631 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
632 }
633
634 ctx.ModuleErrorf("%s", message.String())
635 }
636}
637
Paul Duffin4b8b7932020-05-06 12:35:38 +0100638func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
639 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
640 if err != nil {
641 ctx.ModuleErrorf("error extracting common properties: %s", err)
642 }
643}
644
Paul Duffinfbe470e2021-04-24 12:37:13 +0100645// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
646type snapshotModuleStaticProperties struct {
647 Compile_multilib string `android:"arch_variant"`
648}
649
Paul Duffin2d1bb892021-04-24 11:32:59 +0100650// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
651type combinedSnapshotModuleProperties struct {
652 // The sdk variant from which this information was collected.
653 sdkVariant *sdk
654
655 // Static snapshot module properties.
656 staticProperties *snapshotModuleStaticProperties
657
658 // The dynamically generated member list properties.
659 dynamicProperties interface{}
660}
661
662// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100663func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
664 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100665 var list []*combinedSnapshotModuleProperties
666 for _, sdkVariant := range sdkVariants {
667 staticProperties := &snapshotModuleStaticProperties{
668 Compile_multilib: sdkVariant.multilibUsages.String(),
669 }
Paul Duffin62782de2021-07-14 12:05:16 +0100670 dynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100671
Paul Duffincd064672021-04-24 00:47:29 +0100672 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100673 sdkVariant: sdkVariant,
674 staticProperties: staticProperties,
675 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100676 }
677 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
678
679 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100680 }
Paul Duffincd064672021-04-24 00:47:29 +0100681
682 for _, memberVariantDep := range memberVariantDeps {
683 // If the member dependency is internal then do not add the dependency to the snapshot member
684 // list properties.
685 if !memberVariantDep.export {
686 continue
687 }
688
689 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin62782de2021-07-14 12:05:16 +0100690 memberListProperty := s.memberTypeListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100691 memberName := ctx.OtherModuleName(memberVariantDep.variant)
692
Paul Duffin13082052021-05-11 00:31:38 +0100693 if memberListProperty.getter == nil {
694 continue
695 }
696
Paul Duffincd064672021-04-24 00:47:29 +0100697 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100698 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100699 if !android.InList(memberName, memberList) {
700 memberList = append(memberList, memberName)
701 }
Paul Duffin13082052021-05-11 00:31:38 +0100702 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100703 }
704
Paul Duffin2d1bb892021-04-24 11:32:59 +0100705 return list
706}
707
708func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
709
710 // Extract the dynamic properties and add them to a list of propertiesContainer.
711 propertyContainers := []propertiesContainer{}
712 for _, i := range list {
713 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
714 sdkVariant: i.sdkVariant,
715 properties: i.dynamicProperties,
716 })
717 }
718
719 // Extract the common members, removing them from the original properties.
Paul Duffin62782de2021-07-14 12:05:16 +0100720 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100721 extractor := newCommonValueExtractor(commonDynamicProperties)
722 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
723
724 // Extract the static properties and add them to a list of propertiesContainer.
725 propertyContainers = []propertiesContainer{}
726 for _, i := range list {
727 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
728 sdkVariant: i.sdkVariant,
729 properties: i.staticProperties,
730 })
731 }
732
733 commonStaticProperties := &snapshotModuleStaticProperties{}
734 extractor = newCommonValueExtractor(commonStaticProperties)
735 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
736
737 return &combinedSnapshotModuleProperties{
738 sdkVariant: nil,
739 staticProperties: commonStaticProperties,
740 dynamicProperties: commonDynamicProperties,
741 }
742}
743
744func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
745 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100746 multilib := staticProperties.Compile_multilib
747 if multilib != "" && multilib != "both" {
748 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
749 propertySet.AddProperty("compile_multilib", multilib)
750 }
751
Paul Duffin2d1bb892021-04-24 11:32:59 +0100752 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin62782de2021-07-14 12:05:16 +0100753 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100754 if memberListProperty.getter == nil {
755 continue
756 }
Paul Duffin865171e2020-03-02 18:38:15 +0000757 names := memberListProperty.getter(dynamicMemberTypeListProperties)
758 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000759 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000760 }
761 }
762}
763
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000764type propertyTag struct {
765 name string
766}
767
Paul Duffin0cb37b92020-03-04 14:52:46 +0000768// A BpPropertyTag to add to a property that contains references to other sdk members.
769//
770// This will cause the references to be rewritten to a versioned reference in the version
771// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000772var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000773var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000774
Paul Duffin0cb37b92020-03-04 14:52:46 +0000775// A BpPropertyTag that indicates the property should only be present in the versioned
776// module.
777//
778// This will cause the property to be removed from the unversioned instance of a
779// snapshot module.
780var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
781
Paul Duffine6c0d842020-01-15 14:08:51 +0000782type unversionedToVersionedTransformation struct {
783 identityTransformation
784 builder *snapshotBuilder
785}
786
Paul Duffine6c0d842020-01-15 14:08:51 +0000787func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
788 // Use a versioned name for the module but remember the original name for the
789 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100790 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000791 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000792 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100793 // Remove the prefer property if present as versioned modules never need marking with prefer.
794 module.removeProperty("prefer")
Paul Duffinfb9a7f92021-07-06 17:18:42 +0100795 // Ditto for use_source_config_var
796 module.removeProperty("use_source_config_var")
Paul Duffine6c0d842020-01-15 14:08:51 +0000797 return module
798}
799
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000800func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000801 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
802 required := tag == requiredSdkMemberReferencePropertyTag
803 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000804 } else {
805 return value, tag
806 }
807}
808
Paul Duffin72910952020-01-20 18:16:30 +0000809type unversionedTransformation struct {
810 identityTransformation
811 builder *snapshotBuilder
812}
813
814func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
815 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100816 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000817 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000818 return module
819}
820
821func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000822 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
823 required := tag == requiredSdkMemberReferencePropertyTag
824 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000825 } else if tag == sdkVersionedOnlyPropertyTag {
826 // The property is not allowed in the unversioned module so remove it.
827 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000828 } else {
829 return value, tag
830 }
831}
832
Paul Duffina78f3a72020-02-21 16:29:35 +0000833type pruneEmptySetTransformer struct {
834 identityTransformation
835}
836
837var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
838
839func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
840 if len(propertySet.properties) == 0 {
841 return nil, nil
842 } else {
843 return propertySet, tag
844 }
845}
846
Paul Duffinb645ec82019-11-27 17:43:54 +0000847func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000848 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
849 return true
850 })
851}
852
853func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100854 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000855 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000856 if moduleFilter(bpModule) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100857 contents.IndentedPrintf("\n")
858 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
Paul Duffind0759072021-02-17 11:23:00 +0000859 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100860 contents.IndentedPrintf("}\n")
Paul Duffind0759072021-02-17 11:23:00 +0000861 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000862 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000863}
864
865func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
866 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000867
Paul Duffin0df49682021-05-07 01:10:01 +0100868 addComment := func(name string) {
869 if text, ok := set.comments[name]; ok {
870 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100871 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100872 }
873 }
874 }
875
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000876 // Output the properties first, followed by the nested sets. This ensures a
877 // consistent output irrespective of whether property sets are created before
878 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000879 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000880 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000881
Paul Duffin0df49682021-05-07 01:10:01 +0100882 // Do not write property sets in the properties phase.
883 if _, ok := value.(*bpPropertySet); ok {
884 continue
885 }
886
887 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100888 reflectValue := reflect.ValueOf(value)
889 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000890 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000891
892 for _, name := range set.order {
893 value := set.getValue(name)
894
895 // Only write property sets in the sets phase.
896 switch v := value.(type) {
897 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100898 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100899 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000900 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100901 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000902 }
903 }
904
Paul Duffinb645ec82019-11-27 17:43:54 +0000905 contents.Dedent()
906}
907
Paul Duffina08e4dc2021-06-22 18:19:19 +0100908// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
909// by the value and then followed by a , and a newline.
910func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
911 contents.IndentedPrintf("%s: ", name)
912 outputUnnamedValue(contents, value)
913 contents.UnindentedPrintf(",\n")
914}
915
916// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
917// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
918// indented and all but the last line will end with a newline.
919func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
920 valueType := value.Type()
921 switch valueType.Kind() {
922 case reflect.Bool:
923 contents.UnindentedPrintf("%t", value.Bool())
924
925 case reflect.String:
926 contents.UnindentedPrintf("%q", value)
927
Paul Duffin51227d82021-05-18 12:54:27 +0100928 case reflect.Ptr:
929 outputUnnamedValue(contents, value.Elem())
930
Paul Duffina08e4dc2021-06-22 18:19:19 +0100931 case reflect.Slice:
932 length := value.Len()
933 if length == 0 {
934 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100935 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100936 firstValue := value.Index(0)
937 if length == 1 && !multiLineValue(firstValue) {
938 contents.UnindentedPrintf("[")
939 outputUnnamedValue(contents, firstValue)
940 contents.UnindentedPrintf("]")
941 } else {
942 contents.UnindentedPrintf("[\n")
943 contents.Indent()
944 for i := 0; i < length; i++ {
945 itemValue := value.Index(i)
946 contents.IndentedPrintf("")
947 outputUnnamedValue(contents, itemValue)
948 contents.UnindentedPrintf(",\n")
949 }
950 contents.Dedent()
951 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100952 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100953 }
954
Paul Duffin51227d82021-05-18 12:54:27 +0100955 case reflect.Struct:
956 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
957 v := value.Interface()
958 if _, ok := v.(android.BpPrintable); !ok {
959 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
960 }
961 contents.UnindentedPrintf("{\n")
962 contents.Indent()
963 for f := 0; f < valueType.NumField(); f++ {
964 fieldType := valueType.Field(f)
965 if fieldType.Anonymous {
966 continue
967 }
968 fieldValue := value.Field(f)
969 fieldName := fieldType.Name
970 propertyName := proptools.PropertyNameForField(fieldName)
971 outputNamedValue(contents, propertyName, fieldValue)
972 }
973 contents.Dedent()
974 contents.IndentedPrintf("}")
975
Paul Duffina08e4dc2021-06-22 18:19:19 +0100976 default:
977 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
978 }
979}
980
Paul Duffin51227d82021-05-18 12:54:27 +0100981// multiLineValue returns true if the supplied value may require multiple lines in the output.
982func multiLineValue(value reflect.Value) bool {
983 kind := value.Kind()
984 return kind == reflect.Slice || kind == reflect.Struct
985}
986
Paul Duffinac37c502019-11-26 18:02:20 +0000987func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000988 contents := &generatedContents{}
989 generateBpContents(contents, s.builderForTests.bpFile)
990 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000991}
992
Paul Duffind0759072021-02-17 11:23:00 +0000993func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
994 contents := &generatedContents{}
995 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100996 name := module.Name()
997 // Include modules that are either unversioned or have no name.
998 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +0000999 })
1000 return contents.content.String()
1001}
1002
1003func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
1004 contents := &generatedContents{}
1005 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001006 name := module.Name()
1007 // Include modules that are either versioned or have no name.
1008 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001009 })
1010 return contents.content.String()
1011}
1012
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001013type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +01001014 ctx android.ModuleContext
1015 sdk *sdk
1016
1017 // The version of the generated snapshot.
1018 //
1019 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
1020 // this field.
1021 version string
1022
Paul Duffinb645ec82019-11-27 17:43:54 +00001023 snapshotDir android.OutputPath
1024 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +00001025
1026 // Map from destination to source of each copy - used to eliminate duplicates and
1027 // detect conflicts.
1028 copies map[string]string
1029
Paul Duffinb645ec82019-11-27 17:43:54 +00001030 filesToZip android.Paths
1031 zipsToMerge android.Paths
1032
Paul Duffin5c211452021-07-15 12:42:44 +01001033 // The path to an empty file.
1034 emptyFile android.WritablePath
1035
Paul Duffinb645ec82019-11-27 17:43:54 +00001036 prebuiltModules map[string]*bpModule
1037 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001038
1039 // The set of all members by name.
1040 allMembersByName map[string]struct{}
1041
1042 // The set of exported members by name.
1043 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001044}
1045
1046func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001047 if existing, ok := s.copies[dest]; ok {
1048 if existing != src.String() {
1049 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1050 return
1051 }
1052 } else {
1053 path := s.snapshotDir.Join(s.ctx, dest)
1054 s.ctx.Build(pctx, android.BuildParams{
1055 Rule: android.Cp,
1056 Input: src,
1057 Output: path,
1058 })
1059 s.filesToZip = append(s.filesToZip, path)
1060
1061 s.copies[dest] = src.String()
1062 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001063}
1064
Paul Duffin91547182019-11-12 19:39:36 +00001065func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1066 ctx := s.ctx
1067
1068 // Repackage the zip file so that the entries are in the destDir directory.
1069 // This will allow the zip file to be merged into the snapshot.
1070 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001071
1072 ctx.Build(pctx, android.BuildParams{
1073 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1074 Rule: repackageZip,
1075 Input: zipPath,
1076 Output: tmpZipPath,
1077 Args: map[string]string{
1078 "destdir": destDir,
1079 },
1080 })
Paul Duffin91547182019-11-12 19:39:36 +00001081
1082 // Add the repackaged zip file to the files to merge.
1083 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1084}
1085
Paul Duffin5c211452021-07-15 12:42:44 +01001086func (s *snapshotBuilder) EmptyFile() android.Path {
1087 if s.emptyFile == nil {
1088 ctx := s.ctx
1089 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1090 s.ctx.Build(pctx, android.BuildParams{
1091 Rule: android.Touch,
1092 Output: s.emptyFile,
1093 })
1094 }
1095
1096 return s.emptyFile
1097}
1098
Paul Duffin9d8d6092019-12-05 18:19:29 +00001099func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1100 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001101 if s.prebuiltModules[name] != nil {
1102 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1103 }
1104
1105 m := s.bpFile.newModule(moduleType)
1106 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001107
Paul Duffinbefa4b92020-03-04 14:22:45 +00001108 variant := member.Variants()[0]
1109
Paul Duffin13f02712020-03-06 12:30:43 +00001110 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001111 // An internal member is only referenced from the sdk snapshot which is in the
1112 // same package so can be marked as private.
1113 m.AddProperty("visibility", []string{"//visibility:private"})
1114 } else {
1115 // Extract visibility information from a member variant. All variants have the same
1116 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001117 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1118
1119 // Add any additional visibility rules needed for the prebuilts to reference each other.
1120 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1121 if err != nil {
1122 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1123 }
1124
1125 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001126 if len(visibility) != 0 {
1127 m.AddProperty("visibility", visibility)
1128 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001129 }
1130
Martin Stjernholm1e041092020-11-03 00:11:09 +00001131 // Where available copy apex_available properties from the member.
1132 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1133 apexAvailable := apexAware.ApexAvailable()
1134 if len(apexAvailable) == 0 {
1135 // //apex_available:platform is the default.
1136 apexAvailable = []string{android.AvailableToPlatform}
1137 }
1138
1139 // Add in any baseline apex available settings.
1140 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1141
1142 // Remove duplicates and sort.
1143 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1144 sort.Strings(apexAvailable)
1145
1146 m.AddProperty("apex_available", apexAvailable)
1147 }
1148
Paul Duffinb0bb3762021-05-06 16:48:05 +01001149 // The licenses are the same for all variants.
1150 mctx := s.ctx
1151 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1152 if len(licenseInfo.Licenses) > 0 {
1153 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1154 }
1155
Paul Duffin865171e2020-03-02 18:38:15 +00001156 deviceSupported := false
1157 hostSupported := false
1158
1159 for _, variant := range member.Variants() {
1160 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001161 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001162 hostSupported = true
1163 } else if osClass == android.Device {
1164 deviceSupported = true
1165 }
1166 }
1167
1168 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001169
Paul Duffin0cb37b92020-03-04 14:52:46 +00001170 // Disable installation in the versioned module of those modules that are ever installable.
1171 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1172 if installable.EverInstallable() {
1173 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1174 }
1175 }
1176
Paul Duffinb645ec82019-11-27 17:43:54 +00001177 s.prebuiltModules[name] = m
1178 s.prebuiltOrder = append(s.prebuiltOrder, m)
1179 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001180}
1181
Paul Duffin865171e2020-03-02 18:38:15 +00001182func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001183 // If neither device or host is supported then this module does not support either so will not
1184 // recognize the properties.
1185 if !deviceSupported && !hostSupported {
1186 return
1187 }
1188
Paul Duffin865171e2020-03-02 18:38:15 +00001189 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001190 bpModule.AddProperty("device_supported", false)
1191 }
Paul Duffin865171e2020-03-02 18:38:15 +00001192 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001193 bpModule.AddProperty("host_supported", true)
1194 }
1195}
1196
Paul Duffin13f02712020-03-06 12:30:43 +00001197func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1198 if required {
1199 return requiredSdkMemberReferencePropertyTag
1200 } else {
1201 return optionalSdkMemberReferencePropertyTag
1202 }
1203}
1204
1205func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1206 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001207}
1208
Paul Duffinb645ec82019-11-27 17:43:54 +00001209// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001210func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1211 if _, ok := s.allMembersByName[unversionedName]; !ok {
1212 if required {
1213 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1214 }
1215 return unversionedName
1216 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001217 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1218}
Paul Duffinb645ec82019-11-27 17:43:54 +00001219
Paul Duffin13f02712020-03-06 12:30:43 +00001220func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001221 var references []string = nil
1222 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001223 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001224 }
1225 return references
1226}
Paul Duffin13879572019-11-28 14:31:38 +00001227
Paul Duffin72910952020-01-20 18:16:30 +00001228// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001229func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1230 if _, ok := s.allMembersByName[unversionedName]; !ok {
1231 if required {
1232 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1233 }
1234 return unversionedName
1235 }
1236
1237 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001238 return s.ctx.ModuleName() + "_" + unversionedName
1239 } else {
1240 return unversionedName
1241 }
1242}
1243
Paul Duffin13f02712020-03-06 12:30:43 +00001244func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001245 var references []string = nil
1246 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001247 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001248 }
1249 return references
1250}
1251
Paul Duffin13f02712020-03-06 12:30:43 +00001252func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1253 _, ok := s.exportedMembersByName[memberName]
1254 return !ok
1255}
1256
Martin Stjernholm89238f42020-07-10 00:14:03 +01001257// Add the properties from the given SdkMemberProperties to the blueprint
1258// property set. This handles common properties in SdkMemberPropertiesBase and
1259// calls the member-specific AddToPropertySet for the rest.
1260func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1261 if memberProperties.Base().Compile_multilib != "" {
1262 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1263 }
1264
1265 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1266}
1267
Paul Duffin21827262021-04-24 12:16:36 +01001268// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1269type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001270 // The sdk variant that depends (possibly indirectly) on the member variant.
1271 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001272
1273 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001274 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001275
1276 // The variant that is added to the sdk.
1277 variant android.SdkAware
1278
1279 // True if the member should be exported, i.e. accessible, from outside the sdk.
1280 export bool
1281
1282 // The names of additional component modules provided by the variant.
1283 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001284}
1285
Paul Duffin13879572019-11-28 14:31:38 +00001286var _ android.SdkMember = (*sdkMember)(nil)
1287
Paul Duffin21827262021-04-24 12:16:36 +01001288// sdkMember groups all the variants of a specific member module together along with the name of the
1289// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001290type sdkMember struct {
1291 memberType android.SdkMemberType
1292 name string
1293 variants []android.SdkAware
1294}
1295
1296func (m *sdkMember) Name() string {
1297 return m.name
1298}
1299
1300func (m *sdkMember) Variants() []android.SdkAware {
1301 return m.variants
1302}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001303
Paul Duffin9c3760e2020-03-16 19:52:08 +00001304// Track usages of multilib variants.
1305type multilibUsage int
1306
1307const (
1308 multilibNone multilibUsage = 0
1309 multilib32 multilibUsage = 1
1310 multilib64 multilibUsage = 2
1311 multilibBoth = multilib32 | multilib64
1312)
1313
1314// Add the multilib that is used in the arch type.
1315func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1316 multilib := archType.Multilib
1317 switch multilib {
1318 case "":
1319 return m
1320 case "lib32":
1321 return m | multilib32
1322 case "lib64":
1323 return m | multilib64
1324 default:
1325 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1326 }
1327}
1328
1329func (m multilibUsage) String() string {
1330 switch m {
1331 case multilibNone:
1332 return ""
1333 case multilib32:
1334 return "32"
1335 case multilib64:
1336 return "64"
1337 case multilibBoth:
1338 return "both"
1339 default:
1340 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1341 m, multilibNone, multilib32, multilib64, multilibBoth))
1342 }
1343}
1344
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001345type baseInfo struct {
1346 Properties android.SdkMemberProperties
1347}
1348
Paul Duffinf34f6d82020-04-30 15:48:31 +01001349func (b *baseInfo) optimizableProperties() interface{} {
1350 return b.Properties
1351}
1352
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001353type osTypeSpecificInfo struct {
1354 baseInfo
1355
Paul Duffin00e46802020-03-12 20:40:35 +00001356 osType android.OsType
1357
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001358 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001359 //
1360 // Nil if there is one variant whose arch type is common
1361 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001362}
1363
Paul Duffin4b8b7932020-05-06 12:35:38 +01001364var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1365
Paul Duffinfc8dd232020-03-17 12:51:37 +00001366type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1367
Paul Duffin00e46802020-03-12 20:40:35 +00001368// Create a new osTypeSpecificInfo for the specified os type and its properties
1369// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001370func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001371 osInfo := &osTypeSpecificInfo{
1372 osType: osType,
1373 }
1374
1375 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1376 properties := variantPropertiesFactory()
1377 properties.Base().Os = osType
1378 return properties
1379 }
1380
1381 // Create a structure into which properties common across the architectures in
1382 // this os type will be stored.
1383 osInfo.Properties = osSpecificVariantPropertiesFactory()
1384
1385 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001386 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001387 var archTypes []android.ArchType
1388 for _, variant := range osTypeVariants {
1389 archType := variant.Target().Arch.ArchType
1390 archTypeName := archType.Name
1391 if _, ok := variantsByArchName[archTypeName]; !ok {
1392 archTypes = append(archTypes, archType)
1393 }
1394
1395 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1396 }
1397
1398 if commonVariants, ok := variantsByArchName["common"]; ok {
1399 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001400 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 +00001401 }
1402
1403 // A common arch type only has one variant and its properties should be treated
1404 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001405 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001406 } else {
1407 // Create an arch specific info for each supported architecture type.
1408 for _, archType := range archTypes {
1409 archTypeName := archType.Name
1410
1411 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001412 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001413
1414 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1415 }
1416 }
1417
1418 return osInfo
1419}
1420
1421// Optimize the properties by extracting common properties from arch type specific
1422// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001423func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001424 // Nothing to do if there is only a single common architecture.
1425 if len(osInfo.archInfos) == 0 {
1426 return
1427 }
1428
Paul Duffin9c3760e2020-03-16 19:52:08 +00001429 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001430 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001431 multilib = multilib.addArchType(archInfo.archType)
1432
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001433 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001434 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001435 }
1436
Paul Duffin4b8b7932020-05-06 12:35:38 +01001437 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001438
1439 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001440 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001441}
1442
1443// Add the properties for an os to a property set.
1444//
1445// Maps the properties related to the os variants through to an appropriate
1446// module structure that will produce equivalent set of variants when it is
1447// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001448func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001449
1450 var osPropertySet android.BpPropertySet
1451 var archPropertySet android.BpPropertySet
1452 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001453 if osInfo.Properties.Base().Os_count == 1 &&
1454 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1455 // There is only one OS type present in the variants and it shouldn't have a
1456 // variant-specific target. The latter is the case if it's either for device
1457 // where there is only one OS (android), or for host and the member type
1458 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001459
1460 // Create a structure that looks like:
1461 // module_type {
1462 // name: "...",
1463 // ...
1464 // <common properties>
1465 // ...
1466 // <single os type specific properties>
1467 //
1468 // arch: {
1469 // <arch specific sections>
1470 // }
1471 //
1472 osPropertySet = bpModule
1473 archPropertySet = osPropertySet.AddPropertySet("arch")
1474
1475 // Arch specific properties need to be added to an arch specific section
1476 // within arch.
1477 archOsPrefix = ""
1478 } else {
1479 // Create a structure that looks like:
1480 // module_type {
1481 // name: "...",
1482 // ...
1483 // <common properties>
1484 // ...
1485 // target: {
1486 // <arch independent os specific sections, e.g. android>
1487 // ...
1488 // <arch and os specific sections, e.g. android_x86>
1489 // }
1490 //
1491 osType := osInfo.osType
1492 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1493 archPropertySet = targetPropertySet
1494
1495 // Arch specific properties need to be added to an os and arch specific
1496 // section prefixed with <os>_.
1497 archOsPrefix = osType.Name + "_"
1498 }
1499
1500 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001501 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001502
1503 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1504 // os) specific properties.
1505 //
1506 // The archInfos list will be empty if the os contains variants for the common
1507 // architecture.
1508 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001509 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001510 }
1511}
1512
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001513func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1514 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001515 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001516}
1517
1518var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1519
Paul Duffin4b8b7932020-05-06 12:35:38 +01001520func (osInfo *osTypeSpecificInfo) String() string {
1521 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1522}
1523
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001524type archTypeSpecificInfo struct {
1525 baseInfo
1526
1527 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001528 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001529
1530 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001531}
1532
Paul Duffin4b8b7932020-05-06 12:35:38 +01001533var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1534
Paul Duffinfc8dd232020-03-17 12:51:37 +00001535// Create a new archTypeSpecificInfo for the specified arch type and its properties
1536// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001537func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001538
Paul Duffinfc8dd232020-03-17 12:51:37 +00001539 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001540 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001541
1542 // Create the properties into which the arch type specific properties will be
1543 // added.
1544 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001545
1546 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001547 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001548 } else {
1549 // There is more than one variant for this arch type which must be differentiated
1550 // by link type.
1551 for _, linkVariant := range archVariants {
1552 linkType := getLinkType(linkVariant)
1553 if linkType == "" {
1554 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1555 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001556 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001557
1558 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1559 }
1560 }
1561 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001562
1563 return archInfo
1564}
1565
Paul Duffinf34f6d82020-04-30 15:48:31 +01001566func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1567 return archInfo.Properties
1568}
1569
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001570// Get the link type of the variant
1571//
1572// If the variant is not differentiated by link type then it returns "",
1573// otherwise it returns one of "static" or "shared".
1574func getLinkType(variant android.Module) string {
1575 linkType := ""
1576 if linkable, ok := variant.(cc.LinkableInterface); ok {
1577 if linkable.Shared() && linkable.Static() {
1578 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1579 } else if linkable.Shared() {
1580 linkType = "shared"
1581 } else if linkable.Static() {
1582 linkType = "static"
1583 } else {
1584 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1585 }
1586 }
1587 return linkType
1588}
1589
1590// Optimize the properties by extracting common properties from link type specific
1591// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001592func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001593 if len(archInfo.linkInfos) == 0 {
1594 return
1595 }
1596
Paul Duffin4b8b7932020-05-06 12:35:38 +01001597 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001598}
1599
Paul Duffinfc8dd232020-03-17 12:51:37 +00001600// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001601func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001602 archTypeName := archInfo.archType.Name
1603 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001604 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1605 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1606 archTypePropertySet.AddProperty("enabled", true)
1607 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001608 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001609
1610 for _, linkInfo := range archInfo.linkInfos {
1611 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001612 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001613 }
1614}
1615
Paul Duffin4b8b7932020-05-06 12:35:38 +01001616func (archInfo *archTypeSpecificInfo) String() string {
1617 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1618}
1619
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001620type linkTypeSpecificInfo struct {
1621 baseInfo
1622
1623 linkType string
1624}
1625
Paul Duffin4b8b7932020-05-06 12:35:38 +01001626var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1627
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001628// Create a new linkTypeSpecificInfo for the specified link type and its properties
1629// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001630func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001631 linkInfo := &linkTypeSpecificInfo{
1632 baseInfo: baseInfo{
1633 // Create the properties into which the link type specific properties will be
1634 // added.
1635 Properties: variantPropertiesFactory(),
1636 },
1637 linkType: linkType,
1638 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001639 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001640 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001641}
1642
Paul Duffin4b8b7932020-05-06 12:35:38 +01001643func (l *linkTypeSpecificInfo) String() string {
1644 return fmt.Sprintf("LinkType{%s}", l.linkType)
1645}
1646
Paul Duffin3a4eb502020-03-19 16:11:18 +00001647type memberContext struct {
1648 sdkMemberContext android.ModuleContext
1649 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001650 memberType android.SdkMemberType
1651 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001652}
1653
1654func (m *memberContext) SdkModuleContext() android.ModuleContext {
1655 return m.sdkMemberContext
1656}
1657
1658func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1659 return m.builder
1660}
1661
Paul Duffina551a1c2020-03-17 21:04:24 +00001662func (m *memberContext) MemberType() android.SdkMemberType {
1663 return m.memberType
1664}
1665
1666func (m *memberContext) Name() string {
1667 return m.name
1668}
1669
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001670func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001671
1672 memberType := member.memberType
1673
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001674 // Do not add the prefer property if the member snapshot module is a source module type.
1675 if !memberType.UsesSourceModuleTypeInSnapshot() {
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +00001676 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1677 // snapshot to be created that sets prefer: true.
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001678 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1679 // dynamically at build time not at snapshot generation time.
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001680 config := ctx.sdkMemberContext.Config()
1681 prefer := config.IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001682
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001683 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1684 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1685 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1686 // behavior is for the module.
1687 bpModule.insertAfter("name", "prefer", prefer)
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001688
1689 configVar := config.Getenv("SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR")
1690 if configVar != "" {
1691 parts := strings.Split(configVar, ":")
1692 cfp := android.ConfigVarProperties{
1693 Config_namespace: proptools.StringPtr(parts[0]),
1694 Var_name: proptools.StringPtr(parts[1]),
1695 }
1696 bpModule.insertAfter("prefer", "use_source_config_var", cfp)
1697 }
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001698 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001699
Paul Duffina04c1072020-03-02 10:16:35 +00001700 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001701 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001702 variants := member.Variants()
1703 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001704 osType := variant.Target().Os
1705 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001706 }
1707
Paul Duffina04c1072020-03-02 10:16:35 +00001708 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001709 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001710 properties := memberType.CreateVariantPropertiesStruct()
1711 base := properties.Base()
1712 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001713 return properties
1714 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001715
Paul Duffina04c1072020-03-02 10:16:35 +00001716 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001717
Paul Duffina04c1072020-03-02 10:16:35 +00001718 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001719 commonProperties := variantPropertiesFactory()
1720 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001721
Paul Duffinc097e362020-03-10 22:50:03 +00001722 // Create common value extractor that can be used to optimize the properties.
1723 commonValueExtractor := newCommonValueExtractor(commonProperties)
1724
Paul Duffina04c1072020-03-02 10:16:35 +00001725 // The list of property structures which are os type specific but common across
1726 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001727 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001728
1729 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001730 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001731 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001732 // Add the os specific properties to a list of os type specific yet architecture
1733 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001734 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001735
Paul Duffin00e46802020-03-12 20:40:35 +00001736 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001737 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001738 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001739
Paul Duffina04c1072020-03-02 10:16:35 +00001740 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001741 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001742
Paul Duffina04c1072020-03-02 10:16:35 +00001743 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001744 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001745
Paul Duffina04c1072020-03-02 10:16:35 +00001746 // Create a target property set into which target specific properties can be
1747 // added.
1748 targetPropertySet := bpModule.AddPropertySet("target")
1749
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001750 // If the member is host OS dependent and has host_supported then disable by
1751 // default and enable each host OS variant explicitly. This avoids problems
1752 // with implicitly enabled OS variants when the snapshot is used, which might
1753 // be different from this run (e.g. different build OS).
1754 if ctx.memberType.IsHostOsDependent() {
1755 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1756 if hostSupported {
1757 hostPropertySet := targetPropertySet.AddPropertySet("host")
1758 hostPropertySet.AddProperty("enabled", false)
1759 }
1760 }
1761
Paul Duffina04c1072020-03-02 10:16:35 +00001762 // Iterate over the os types in a fixed order.
1763 for _, osType := range s.getPossibleOsTypes() {
1764 osInfo := osTypeToInfo[osType]
1765 if osInfo == nil {
1766 continue
1767 }
1768
Paul Duffin3a4eb502020-03-19 16:11:18 +00001769 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001770 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001771}
1772
Paul Duffina04c1072020-03-02 10:16:35 +00001773// Compute the list of possible os types that this sdk could support.
1774func (s *sdk) getPossibleOsTypes() []android.OsType {
1775 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001776 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001777 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07001778 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00001779 osTypes = append(osTypes, osType)
1780 }
1781 }
1782 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001783 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001784 osTypes = append(osTypes, osType)
1785 }
1786 }
1787 }
1788 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1789 return osTypes
1790}
1791
Paul Duffinb28369a2020-05-04 15:39:59 +01001792// Given a set of properties (struct value), return the value of the field within that
1793// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001794type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1795
Paul Duffinc459f892020-04-30 18:08:29 +01001796// Checks the metadata to determine whether the property should be ignored for the
1797// purposes of common value extraction or not.
1798type extractorMetadataPredicate func(metadata propertiesContainer) bool
1799
1800// Indicates whether optimizable properties are provided by a host variant or
1801// not.
1802type isHostVariant interface {
1803 isHostVariant() bool
1804}
1805
Paul Duffinb28369a2020-05-04 15:39:59 +01001806// A property that can be optimized by the commonValueExtractor.
1807type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001808 // The name of the field for this property. It is a "."-separated path for
1809 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001810 name string
1811
Paul Duffinc459f892020-04-30 18:08:29 +01001812 // Filter that can use metadata associated with the properties being optimized
1813 // to determine whether the field should be ignored during common value
1814 // optimization.
1815 filter extractorMetadataPredicate
1816
Paul Duffinb28369a2020-05-04 15:39:59 +01001817 // Retrieves the value on which common value optimization will be performed.
1818 getter fieldAccessorFunc
1819
1820 // The empty value for the field.
1821 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001822
1823 // True if the property can support arch variants false otherwise.
1824 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001825}
1826
Paul Duffin4b8b7932020-05-06 12:35:38 +01001827func (p extractorProperty) String() string {
1828 return p.name
1829}
1830
Paul Duffinc097e362020-03-10 22:50:03 +00001831// Supports extracting common values from a number of instances of a properties
1832// structure into a separate common set of properties.
1833type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001834 // The properties that the extractor can optimize.
1835 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001836}
1837
1838// Create a new common value extractor for the structure type for the supplied
1839// properties struct.
1840//
1841// The returned extractor can be used on any properties structure of the same type
1842// as the supplied set of properties.
1843func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1844 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1845 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001846 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001847 return extractor
1848}
1849
1850// Gather the fields from the supplied structure type from which common values will
1851// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001852//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001853// This is recursive function. If it encounters a struct then it will recurse
1854// into it, passing in the accessor for the field and the struct name as prefix
1855// for the nested fields. That will then be used in the accessors for the fields
1856// in the embedded struct.
1857func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001858 for f := 0; f < structType.NumField(); f++ {
1859 field := structType.Field(f)
1860 if field.PkgPath != "" {
1861 // Ignore unexported fields.
1862 continue
1863 }
1864
Paul Duffinb07fa512020-03-10 22:17:04 +00001865 // Ignore fields whose value should be kept.
1866 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001867 continue
1868 }
1869
Paul Duffinc459f892020-04-30 18:08:29 +01001870 var filter extractorMetadataPredicate
1871
1872 // Add a filter
1873 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1874 filter = func(metadata propertiesContainer) bool {
1875 if m, ok := metadata.(isHostVariant); ok {
1876 if m.isHostVariant() {
1877 return false
1878 }
1879 }
1880 return true
1881 }
1882 }
1883
Paul Duffinc097e362020-03-10 22:50:03 +00001884 // Save a copy of the field index for use in the function.
1885 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001886
Martin Stjernholmb0249572020-09-15 02:32:35 +01001887 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001888
Paul Duffinc097e362020-03-10 22:50:03 +00001889 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001890 if containingStructAccessor != nil {
1891 // This is an embedded structure so first access the field for the embedded
1892 // structure.
1893 value = containingStructAccessor(value)
1894 }
1895
Paul Duffinc097e362020-03-10 22:50:03 +00001896 // Skip through interface and pointer values to find the structure.
1897 value = getStructValue(value)
1898
Paul Duffin4b8b7932020-05-06 12:35:38 +01001899 defer func() {
1900 if r := recover(); r != nil {
1901 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1902 }
1903 }()
1904
Paul Duffinc097e362020-03-10 22:50:03 +00001905 // Return the field.
1906 return value.Field(fieldIndex)
1907 }
1908
Martin Stjernholmb0249572020-09-15 02:32:35 +01001909 if field.Type.Kind() == reflect.Struct {
1910 // Gather fields from the nested or embedded structure.
1911 var subNamePrefix string
1912 if field.Anonymous {
1913 subNamePrefix = namePrefix
1914 } else {
1915 subNamePrefix = name + "."
1916 }
1917 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001918 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001919 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001920 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001921 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001922 fieldGetter,
1923 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001924 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001925 }
1926 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001927 }
Paul Duffinc097e362020-03-10 22:50:03 +00001928 }
1929}
1930
1931func getStructValue(value reflect.Value) reflect.Value {
1932foundStruct:
1933 for {
1934 kind := value.Kind()
1935 switch kind {
1936 case reflect.Interface, reflect.Ptr:
1937 value = value.Elem()
1938 case reflect.Struct:
1939 break foundStruct
1940 default:
1941 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1942 }
1943 }
1944 return value
1945}
1946
Paul Duffinf34f6d82020-04-30 15:48:31 +01001947// A container of properties to be optimized.
1948//
1949// Allows additional information to be associated with the properties, e.g. for
1950// filtering.
1951type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001952 fmt.Stringer
1953
Paul Duffinf34f6d82020-04-30 15:48:31 +01001954 // Get the properties that need optimizing.
1955 optimizableProperties() interface{}
1956}
1957
Paul Duffin2d1bb892021-04-24 11:32:59 +01001958// A wrapper for sdk variant related properties to allow them to be optimized.
1959type sdkVariantPropertiesContainer struct {
1960 sdkVariant *sdk
1961 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01001962}
1963
Paul Duffin2d1bb892021-04-24 11:32:59 +01001964func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
1965 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01001966}
1967
Paul Duffin2d1bb892021-04-24 11:32:59 +01001968func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001969 return c.sdkVariant.String()
1970}
1971
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001972// Extract common properties from a slice of property structures of the same type.
1973//
1974// All the property structures must be of the same type.
1975// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001976// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001977//
1978// Iterates over each exported field (capitalized name) and checks to see whether they
1979// have the same value (using DeepEquals) across all the input properties. If it does not then no
1980// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001981// and the field in each of the input properties structure is set to its default value. Nested
1982// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001983func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001984 commonPropertiesValue := reflect.ValueOf(commonProperties)
1985 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001986
Paul Duffinf34f6d82020-04-30 15:48:31 +01001987 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1988
Paul Duffinb28369a2020-05-04 15:39:59 +01001989 for _, property := range e.properties {
1990 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001991 filter := property.filter
1992 if filter == nil {
1993 filter = func(metadata propertiesContainer) bool {
1994 return true
1995 }
1996 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001997
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001998 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001999 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2000 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002001 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002002
Paul Duffin864e1b42020-05-06 10:23:19 +01002003 // Assume that all the values will be the same.
2004 //
2005 // While similar to this is not quite the same as commonValue == nil. If all the values
2006 // have been filtered out then this will be false but commonValue == nil will be true.
2007 valuesDiffer := false
2008
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002009 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002010 container := sliceValue.Index(i).Interface().(propertiesContainer)
2011 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002012 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002013
Paul Duffinc459f892020-04-30 18:08:29 +01002014 if !filter(container) {
2015 expectedValue := property.emptyValue.Interface()
2016 actualValue := fieldValue.Interface()
2017 if !reflect.DeepEqual(expectedValue, actualValue) {
2018 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2019 }
2020 continue
2021 }
2022
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002023 if commonValue == nil {
2024 // Use the first value as the commonProperties value.
2025 commonValue = &fieldValue
2026 } else {
2027 // If the value does not match the current common value then there is
2028 // no value in common so break out.
2029 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2030 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002031 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002032 break
2033 }
2034 }
2035 }
2036
Paul Duffin864e1b42020-05-06 10:23:19 +01002037 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002038 // and set the input struct's field to the empty value.
2039 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002040 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002041 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002042 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002043 container := sliceValue.Index(i).Interface().(propertiesContainer)
2044 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002045 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002046 fieldValue.Set(emptyValue)
2047 }
2048 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002049
2050 if valuesDiffer && !property.archVariant {
2051 // The values differ but the property does not support arch variants so it
2052 // is an error.
2053 var details strings.Builder
2054 for i := 0; i < sliceValue.Len(); i++ {
2055 container := sliceValue.Index(i).Interface().(propertiesContainer)
2056 itemValue := reflect.ValueOf(container.optimizableProperties())
2057 fieldValue := fieldGetter(itemValue)
2058
2059 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2060 }
2061
2062 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2063 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002064 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002065
2066 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002067}