blob: 89a5c92697ee9c136a6974fbb698e7e90cb661ac [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 Duffinf7b3d0d2021-09-02 14:29:21 +0100188 if memberTag, ok := tag.(android.SdkMemberDependencyTag); 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 Duffin94289702021-09-09 15:38:32 +0100768var _ android.BpPropertyTag = propertyTag{}
769
Paul Duffin0cb37b92020-03-04 14:52:46 +0000770// A BpPropertyTag to add to a property that contains references to other sdk members.
771//
772// This will cause the references to be rewritten to a versioned reference in the version
773// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000774var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000775var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000776
Paul Duffin0cb37b92020-03-04 14:52:46 +0000777// A BpPropertyTag that indicates the property should only be present in the versioned
778// module.
779//
780// This will cause the property to be removed from the unversioned instance of a
781// snapshot module.
782var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
783
Paul Duffine6c0d842020-01-15 14:08:51 +0000784type unversionedToVersionedTransformation struct {
785 identityTransformation
786 builder *snapshotBuilder
787}
788
Paul Duffine6c0d842020-01-15 14:08:51 +0000789func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
790 // Use a versioned name for the module but remember the original name for the
791 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100792 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000793 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000794 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100795 // Remove the prefer property if present as versioned modules never need marking with prefer.
796 module.removeProperty("prefer")
Paul Duffinfb9a7f92021-07-06 17:18:42 +0100797 // Ditto for use_source_config_var
798 module.removeProperty("use_source_config_var")
Paul Duffine6c0d842020-01-15 14:08:51 +0000799 return module
800}
801
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000802func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000803 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
804 required := tag == requiredSdkMemberReferencePropertyTag
805 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000806 } else {
807 return value, tag
808 }
809}
810
Paul Duffin72910952020-01-20 18:16:30 +0000811type unversionedTransformation struct {
812 identityTransformation
813 builder *snapshotBuilder
814}
815
816func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
817 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100818 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000819 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000820 return module
821}
822
823func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000824 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
825 required := tag == requiredSdkMemberReferencePropertyTag
826 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000827 } else if tag == sdkVersionedOnlyPropertyTag {
828 // The property is not allowed in the unversioned module so remove it.
829 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000830 } else {
831 return value, tag
832 }
833}
834
Paul Duffina78f3a72020-02-21 16:29:35 +0000835type pruneEmptySetTransformer struct {
836 identityTransformation
837}
838
839var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
840
841func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
842 if len(propertySet.properties) == 0 {
843 return nil, nil
844 } else {
845 return propertySet, tag
846 }
847}
848
Paul Duffinb645ec82019-11-27 17:43:54 +0000849func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000850 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
851 return true
852 })
853}
854
855func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100856 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000857 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000858 if moduleFilter(bpModule) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100859 contents.IndentedPrintf("\n")
860 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
Paul Duffind0759072021-02-17 11:23:00 +0000861 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100862 contents.IndentedPrintf("}\n")
Paul Duffind0759072021-02-17 11:23:00 +0000863 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000864 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000865}
866
867func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
868 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000869
Paul Duffin0df49682021-05-07 01:10:01 +0100870 addComment := func(name string) {
871 if text, ok := set.comments[name]; ok {
872 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100873 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100874 }
875 }
876 }
877
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000878 // Output the properties first, followed by the nested sets. This ensures a
879 // consistent output irrespective of whether property sets are created before
880 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000881 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000882 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000883
Paul Duffin0df49682021-05-07 01:10:01 +0100884 // Do not write property sets in the properties phase.
885 if _, ok := value.(*bpPropertySet); ok {
886 continue
887 }
888
889 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100890 reflectValue := reflect.ValueOf(value)
891 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000892 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000893
894 for _, name := range set.order {
895 value := set.getValue(name)
896
897 // Only write property sets in the sets phase.
898 switch v := value.(type) {
899 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100900 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100901 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000902 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100903 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000904 }
905 }
906
Paul Duffinb645ec82019-11-27 17:43:54 +0000907 contents.Dedent()
908}
909
Paul Duffina08e4dc2021-06-22 18:19:19 +0100910// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
911// by the value and then followed by a , and a newline.
912func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
913 contents.IndentedPrintf("%s: ", name)
914 outputUnnamedValue(contents, value)
915 contents.UnindentedPrintf(",\n")
916}
917
918// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
919// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
920// indented and all but the last line will end with a newline.
921func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
922 valueType := value.Type()
923 switch valueType.Kind() {
924 case reflect.Bool:
925 contents.UnindentedPrintf("%t", value.Bool())
926
927 case reflect.String:
928 contents.UnindentedPrintf("%q", value)
929
Paul Duffin51227d82021-05-18 12:54:27 +0100930 case reflect.Ptr:
931 outputUnnamedValue(contents, value.Elem())
932
Paul Duffina08e4dc2021-06-22 18:19:19 +0100933 case reflect.Slice:
934 length := value.Len()
935 if length == 0 {
936 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100937 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100938 firstValue := value.Index(0)
939 if length == 1 && !multiLineValue(firstValue) {
940 contents.UnindentedPrintf("[")
941 outputUnnamedValue(contents, firstValue)
942 contents.UnindentedPrintf("]")
943 } else {
944 contents.UnindentedPrintf("[\n")
945 contents.Indent()
946 for i := 0; i < length; i++ {
947 itemValue := value.Index(i)
948 contents.IndentedPrintf("")
949 outputUnnamedValue(contents, itemValue)
950 contents.UnindentedPrintf(",\n")
951 }
952 contents.Dedent()
953 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100954 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100955 }
956
Paul Duffin51227d82021-05-18 12:54:27 +0100957 case reflect.Struct:
958 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
959 v := value.Interface()
960 if _, ok := v.(android.BpPrintable); !ok {
961 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
962 }
963 contents.UnindentedPrintf("{\n")
964 contents.Indent()
965 for f := 0; f < valueType.NumField(); f++ {
966 fieldType := valueType.Field(f)
967 if fieldType.Anonymous {
968 continue
969 }
970 fieldValue := value.Field(f)
971 fieldName := fieldType.Name
972 propertyName := proptools.PropertyNameForField(fieldName)
973 outputNamedValue(contents, propertyName, fieldValue)
974 }
975 contents.Dedent()
976 contents.IndentedPrintf("}")
977
Paul Duffina08e4dc2021-06-22 18:19:19 +0100978 default:
979 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
980 }
981}
982
Paul Duffin51227d82021-05-18 12:54:27 +0100983// multiLineValue returns true if the supplied value may require multiple lines in the output.
984func multiLineValue(value reflect.Value) bool {
985 kind := value.Kind()
986 return kind == reflect.Slice || kind == reflect.Struct
987}
988
Paul Duffinac37c502019-11-26 18:02:20 +0000989func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000990 contents := &generatedContents{}
991 generateBpContents(contents, s.builderForTests.bpFile)
992 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000993}
994
Paul Duffind0759072021-02-17 11:23:00 +0000995func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
996 contents := &generatedContents{}
997 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +0100998 name := module.Name()
999 // Include modules that are either unversioned or have no name.
1000 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001001 })
1002 return contents.content.String()
1003}
1004
1005func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
1006 contents := &generatedContents{}
1007 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001008 name := module.Name()
1009 // Include modules that are either versioned or have no name.
1010 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001011 })
1012 return contents.content.String()
1013}
1014
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001015type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +01001016 ctx android.ModuleContext
1017 sdk *sdk
1018
1019 // The version of the generated snapshot.
1020 //
1021 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
1022 // this field.
1023 version string
1024
Paul Duffinb645ec82019-11-27 17:43:54 +00001025 snapshotDir android.OutputPath
1026 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +00001027
1028 // Map from destination to source of each copy - used to eliminate duplicates and
1029 // detect conflicts.
1030 copies map[string]string
1031
Paul Duffinb645ec82019-11-27 17:43:54 +00001032 filesToZip android.Paths
1033 zipsToMerge android.Paths
1034
Paul Duffin5c211452021-07-15 12:42:44 +01001035 // The path to an empty file.
1036 emptyFile android.WritablePath
1037
Paul Duffinb645ec82019-11-27 17:43:54 +00001038 prebuiltModules map[string]*bpModule
1039 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001040
1041 // The set of all members by name.
1042 allMembersByName map[string]struct{}
1043
1044 // The set of exported members by name.
1045 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001046}
1047
1048func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001049 if existing, ok := s.copies[dest]; ok {
1050 if existing != src.String() {
1051 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1052 return
1053 }
1054 } else {
1055 path := s.snapshotDir.Join(s.ctx, dest)
1056 s.ctx.Build(pctx, android.BuildParams{
1057 Rule: android.Cp,
1058 Input: src,
1059 Output: path,
1060 })
1061 s.filesToZip = append(s.filesToZip, path)
1062
1063 s.copies[dest] = src.String()
1064 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001065}
1066
Paul Duffin91547182019-11-12 19:39:36 +00001067func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1068 ctx := s.ctx
1069
1070 // Repackage the zip file so that the entries are in the destDir directory.
1071 // This will allow the zip file to be merged into the snapshot.
1072 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001073
1074 ctx.Build(pctx, android.BuildParams{
1075 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1076 Rule: repackageZip,
1077 Input: zipPath,
1078 Output: tmpZipPath,
1079 Args: map[string]string{
1080 "destdir": destDir,
1081 },
1082 })
Paul Duffin91547182019-11-12 19:39:36 +00001083
1084 // Add the repackaged zip file to the files to merge.
1085 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1086}
1087
Paul Duffin5c211452021-07-15 12:42:44 +01001088func (s *snapshotBuilder) EmptyFile() android.Path {
1089 if s.emptyFile == nil {
1090 ctx := s.ctx
1091 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1092 s.ctx.Build(pctx, android.BuildParams{
1093 Rule: android.Touch,
1094 Output: s.emptyFile,
1095 })
1096 }
1097
1098 return s.emptyFile
1099}
1100
Paul Duffin9d8d6092019-12-05 18:19:29 +00001101func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1102 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001103 if s.prebuiltModules[name] != nil {
1104 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1105 }
1106
1107 m := s.bpFile.newModule(moduleType)
1108 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001109
Paul Duffinbefa4b92020-03-04 14:22:45 +00001110 variant := member.Variants()[0]
1111
Paul Duffin13f02712020-03-06 12:30:43 +00001112 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001113 // An internal member is only referenced from the sdk snapshot which is in the
1114 // same package so can be marked as private.
1115 m.AddProperty("visibility", []string{"//visibility:private"})
1116 } else {
1117 // Extract visibility information from a member variant. All variants have the same
1118 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001119 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1120
1121 // Add any additional visibility rules needed for the prebuilts to reference each other.
1122 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1123 if err != nil {
1124 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1125 }
1126
1127 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001128 if len(visibility) != 0 {
1129 m.AddProperty("visibility", visibility)
1130 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001131 }
1132
Martin Stjernholm1e041092020-11-03 00:11:09 +00001133 // Where available copy apex_available properties from the member.
1134 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1135 apexAvailable := apexAware.ApexAvailable()
1136 if len(apexAvailable) == 0 {
1137 // //apex_available:platform is the default.
1138 apexAvailable = []string{android.AvailableToPlatform}
1139 }
1140
1141 // Add in any baseline apex available settings.
1142 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1143
1144 // Remove duplicates and sort.
1145 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1146 sort.Strings(apexAvailable)
1147
1148 m.AddProperty("apex_available", apexAvailable)
1149 }
1150
Paul Duffinb0bb3762021-05-06 16:48:05 +01001151 // The licenses are the same for all variants.
1152 mctx := s.ctx
1153 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1154 if len(licenseInfo.Licenses) > 0 {
1155 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1156 }
1157
Paul Duffin865171e2020-03-02 18:38:15 +00001158 deviceSupported := false
1159 hostSupported := false
1160
1161 for _, variant := range member.Variants() {
1162 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001163 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001164 hostSupported = true
1165 } else if osClass == android.Device {
1166 deviceSupported = true
1167 }
1168 }
1169
1170 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001171
Paul Duffin0cb37b92020-03-04 14:52:46 +00001172 // Disable installation in the versioned module of those modules that are ever installable.
1173 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1174 if installable.EverInstallable() {
1175 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1176 }
1177 }
1178
Paul Duffinb645ec82019-11-27 17:43:54 +00001179 s.prebuiltModules[name] = m
1180 s.prebuiltOrder = append(s.prebuiltOrder, m)
1181 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001182}
1183
Paul Duffin865171e2020-03-02 18:38:15 +00001184func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001185 // If neither device or host is supported then this module does not support either so will not
1186 // recognize the properties.
1187 if !deviceSupported && !hostSupported {
1188 return
1189 }
1190
Paul Duffin865171e2020-03-02 18:38:15 +00001191 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001192 bpModule.AddProperty("device_supported", false)
1193 }
Paul Duffin865171e2020-03-02 18:38:15 +00001194 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001195 bpModule.AddProperty("host_supported", true)
1196 }
1197}
1198
Paul Duffin13f02712020-03-06 12:30:43 +00001199func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1200 if required {
1201 return requiredSdkMemberReferencePropertyTag
1202 } else {
1203 return optionalSdkMemberReferencePropertyTag
1204 }
1205}
1206
1207func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1208 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001209}
1210
Paul Duffinb645ec82019-11-27 17:43:54 +00001211// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001212func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1213 if _, ok := s.allMembersByName[unversionedName]; !ok {
1214 if required {
1215 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1216 }
1217 return unversionedName
1218 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001219 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1220}
Paul Duffinb645ec82019-11-27 17:43:54 +00001221
Paul Duffin13f02712020-03-06 12:30:43 +00001222func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001223 var references []string = nil
1224 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001225 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001226 }
1227 return references
1228}
Paul Duffin13879572019-11-28 14:31:38 +00001229
Paul Duffin72910952020-01-20 18:16:30 +00001230// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001231func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1232 if _, ok := s.allMembersByName[unversionedName]; !ok {
1233 if required {
1234 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1235 }
1236 return unversionedName
1237 }
1238
1239 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001240 return s.ctx.ModuleName() + "_" + unversionedName
1241 } else {
1242 return unversionedName
1243 }
1244}
1245
Paul Duffin13f02712020-03-06 12:30:43 +00001246func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001247 var references []string = nil
1248 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001249 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001250 }
1251 return references
1252}
1253
Paul Duffin13f02712020-03-06 12:30:43 +00001254func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1255 _, ok := s.exportedMembersByName[memberName]
1256 return !ok
1257}
1258
Martin Stjernholm89238f42020-07-10 00:14:03 +01001259// Add the properties from the given SdkMemberProperties to the blueprint
1260// property set. This handles common properties in SdkMemberPropertiesBase and
1261// calls the member-specific AddToPropertySet for the rest.
1262func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1263 if memberProperties.Base().Compile_multilib != "" {
1264 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1265 }
1266
1267 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1268}
1269
Paul Duffin21827262021-04-24 12:16:36 +01001270// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1271type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001272 // The sdk variant that depends (possibly indirectly) on the member variant.
1273 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001274
1275 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001276 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001277
1278 // The variant that is added to the sdk.
1279 variant android.SdkAware
1280
1281 // True if the member should be exported, i.e. accessible, from outside the sdk.
1282 export bool
1283
1284 // The names of additional component modules provided by the variant.
1285 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001286}
1287
Paul Duffin13879572019-11-28 14:31:38 +00001288var _ android.SdkMember = (*sdkMember)(nil)
1289
Paul Duffin21827262021-04-24 12:16:36 +01001290// sdkMember groups all the variants of a specific member module together along with the name of the
1291// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001292type sdkMember struct {
1293 memberType android.SdkMemberType
1294 name string
1295 variants []android.SdkAware
1296}
1297
1298func (m *sdkMember) Name() string {
1299 return m.name
1300}
1301
1302func (m *sdkMember) Variants() []android.SdkAware {
1303 return m.variants
1304}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001305
Paul Duffin9c3760e2020-03-16 19:52:08 +00001306// Track usages of multilib variants.
1307type multilibUsage int
1308
1309const (
1310 multilibNone multilibUsage = 0
1311 multilib32 multilibUsage = 1
1312 multilib64 multilibUsage = 2
1313 multilibBoth = multilib32 | multilib64
1314)
1315
1316// Add the multilib that is used in the arch type.
1317func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1318 multilib := archType.Multilib
1319 switch multilib {
1320 case "":
1321 return m
1322 case "lib32":
1323 return m | multilib32
1324 case "lib64":
1325 return m | multilib64
1326 default:
1327 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1328 }
1329}
1330
1331func (m multilibUsage) String() string {
1332 switch m {
1333 case multilibNone:
1334 return ""
1335 case multilib32:
1336 return "32"
1337 case multilib64:
1338 return "64"
1339 case multilibBoth:
1340 return "both"
1341 default:
1342 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1343 m, multilibNone, multilib32, multilib64, multilibBoth))
1344 }
1345}
1346
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001347type baseInfo struct {
1348 Properties android.SdkMemberProperties
1349}
1350
Paul Duffinf34f6d82020-04-30 15:48:31 +01001351func (b *baseInfo) optimizableProperties() interface{} {
1352 return b.Properties
1353}
1354
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001355type osTypeSpecificInfo struct {
1356 baseInfo
1357
Paul Duffin00e46802020-03-12 20:40:35 +00001358 osType android.OsType
1359
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001360 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001361 //
1362 // Nil if there is one variant whose arch type is common
1363 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001364}
1365
Paul Duffin4b8b7932020-05-06 12:35:38 +01001366var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1367
Paul Duffinfc8dd232020-03-17 12:51:37 +00001368type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1369
Paul Duffin00e46802020-03-12 20:40:35 +00001370// Create a new osTypeSpecificInfo for the specified os type and its properties
1371// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001372func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001373 osInfo := &osTypeSpecificInfo{
1374 osType: osType,
1375 }
1376
1377 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1378 properties := variantPropertiesFactory()
1379 properties.Base().Os = osType
1380 return properties
1381 }
1382
1383 // Create a structure into which properties common across the architectures in
1384 // this os type will be stored.
1385 osInfo.Properties = osSpecificVariantPropertiesFactory()
1386
1387 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001388 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001389 var archTypes []android.ArchType
1390 for _, variant := range osTypeVariants {
1391 archType := variant.Target().Arch.ArchType
1392 archTypeName := archType.Name
1393 if _, ok := variantsByArchName[archTypeName]; !ok {
1394 archTypes = append(archTypes, archType)
1395 }
1396
1397 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1398 }
1399
1400 if commonVariants, ok := variantsByArchName["common"]; ok {
1401 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001402 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 +00001403 }
1404
1405 // A common arch type only has one variant and its properties should be treated
1406 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001407 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001408 } else {
1409 // Create an arch specific info for each supported architecture type.
1410 for _, archType := range archTypes {
1411 archTypeName := archType.Name
1412
1413 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001414 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001415
1416 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1417 }
1418 }
1419
1420 return osInfo
1421}
1422
1423// Optimize the properties by extracting common properties from arch type specific
1424// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001425func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001426 // Nothing to do if there is only a single common architecture.
1427 if len(osInfo.archInfos) == 0 {
1428 return
1429 }
1430
Paul Duffin9c3760e2020-03-16 19:52:08 +00001431 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001432 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001433 multilib = multilib.addArchType(archInfo.archType)
1434
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001435 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001436 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001437 }
1438
Paul Duffin4b8b7932020-05-06 12:35:38 +01001439 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001440
1441 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001442 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001443}
1444
1445// Add the properties for an os to a property set.
1446//
1447// Maps the properties related to the os variants through to an appropriate
1448// module structure that will produce equivalent set of variants when it is
1449// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001450func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001451
1452 var osPropertySet android.BpPropertySet
1453 var archPropertySet android.BpPropertySet
1454 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001455 if osInfo.Properties.Base().Os_count == 1 &&
1456 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1457 // There is only one OS type present in the variants and it shouldn't have a
1458 // variant-specific target. The latter is the case if it's either for device
1459 // where there is only one OS (android), or for host and the member type
1460 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001461
1462 // Create a structure that looks like:
1463 // module_type {
1464 // name: "...",
1465 // ...
1466 // <common properties>
1467 // ...
1468 // <single os type specific properties>
1469 //
1470 // arch: {
1471 // <arch specific sections>
1472 // }
1473 //
1474 osPropertySet = bpModule
1475 archPropertySet = osPropertySet.AddPropertySet("arch")
1476
1477 // Arch specific properties need to be added to an arch specific section
1478 // within arch.
1479 archOsPrefix = ""
1480 } else {
1481 // Create a structure that looks like:
1482 // module_type {
1483 // name: "...",
1484 // ...
1485 // <common properties>
1486 // ...
1487 // target: {
1488 // <arch independent os specific sections, e.g. android>
1489 // ...
1490 // <arch and os specific sections, e.g. android_x86>
1491 // }
1492 //
1493 osType := osInfo.osType
1494 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1495 archPropertySet = targetPropertySet
1496
1497 // Arch specific properties need to be added to an os and arch specific
1498 // section prefixed with <os>_.
1499 archOsPrefix = osType.Name + "_"
1500 }
1501
1502 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001503 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001504
1505 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1506 // os) specific properties.
1507 //
1508 // The archInfos list will be empty if the os contains variants for the common
1509 // architecture.
1510 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001511 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001512 }
1513}
1514
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001515func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1516 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001517 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001518}
1519
1520var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1521
Paul Duffin4b8b7932020-05-06 12:35:38 +01001522func (osInfo *osTypeSpecificInfo) String() string {
1523 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1524}
1525
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001526type archTypeSpecificInfo struct {
1527 baseInfo
1528
1529 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001530 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001531
1532 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001533}
1534
Paul Duffin4b8b7932020-05-06 12:35:38 +01001535var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1536
Paul Duffinfc8dd232020-03-17 12:51:37 +00001537// Create a new archTypeSpecificInfo for the specified arch type and its properties
1538// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001539func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001540
Paul Duffinfc8dd232020-03-17 12:51:37 +00001541 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001542 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001543
1544 // Create the properties into which the arch type specific properties will be
1545 // added.
1546 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001547
1548 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001549 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001550 } else {
1551 // There is more than one variant for this arch type which must be differentiated
1552 // by link type.
1553 for _, linkVariant := range archVariants {
1554 linkType := getLinkType(linkVariant)
1555 if linkType == "" {
1556 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1557 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001558 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001559
1560 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1561 }
1562 }
1563 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001564
1565 return archInfo
1566}
1567
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001568// Get the link type of the variant
1569//
1570// If the variant is not differentiated by link type then it returns "",
1571// otherwise it returns one of "static" or "shared".
1572func getLinkType(variant android.Module) string {
1573 linkType := ""
1574 if linkable, ok := variant.(cc.LinkableInterface); ok {
1575 if linkable.Shared() && linkable.Static() {
1576 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1577 } else if linkable.Shared() {
1578 linkType = "shared"
1579 } else if linkable.Static() {
1580 linkType = "static"
1581 } else {
1582 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1583 }
1584 }
1585 return linkType
1586}
1587
1588// Optimize the properties by extracting common properties from link type specific
1589// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001590func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001591 if len(archInfo.linkInfos) == 0 {
1592 return
1593 }
1594
Paul Duffin4b8b7932020-05-06 12:35:38 +01001595 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001596}
1597
Paul Duffinfc8dd232020-03-17 12:51:37 +00001598// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001599func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001600 archTypeName := archInfo.archType.Name
1601 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001602 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1603 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1604 archTypePropertySet.AddProperty("enabled", true)
1605 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001606 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001607
1608 for _, linkInfo := range archInfo.linkInfos {
Paul Duffinf68f85a2021-09-09 16:11:42 +01001609 linkInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001610 }
1611}
1612
Paul Duffin4b8b7932020-05-06 12:35:38 +01001613func (archInfo *archTypeSpecificInfo) String() string {
1614 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1615}
1616
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001617type linkTypeSpecificInfo struct {
1618 baseInfo
1619
1620 linkType string
1621}
1622
Paul Duffin4b8b7932020-05-06 12:35:38 +01001623var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1624
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001625// Create a new linkTypeSpecificInfo for the specified link type and its properties
1626// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001627func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001628 linkInfo := &linkTypeSpecificInfo{
1629 baseInfo: baseInfo{
1630 // Create the properties into which the link type specific properties will be
1631 // added.
1632 Properties: variantPropertiesFactory(),
1633 },
1634 linkType: linkType,
1635 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001636 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001637 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001638}
1639
Paul Duffinf68f85a2021-09-09 16:11:42 +01001640func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1641 linkPropertySet := propertySet.AddPropertySet(l.linkType)
1642 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
1643}
1644
Paul Duffin4b8b7932020-05-06 12:35:38 +01001645func (l *linkTypeSpecificInfo) String() string {
1646 return fmt.Sprintf("LinkType{%s}", l.linkType)
1647}
1648
Paul Duffin3a4eb502020-03-19 16:11:18 +00001649type memberContext struct {
1650 sdkMemberContext android.ModuleContext
1651 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001652 memberType android.SdkMemberType
1653 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001654}
1655
1656func (m *memberContext) SdkModuleContext() android.ModuleContext {
1657 return m.sdkMemberContext
1658}
1659
1660func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1661 return m.builder
1662}
1663
Paul Duffina551a1c2020-03-17 21:04:24 +00001664func (m *memberContext) MemberType() android.SdkMemberType {
1665 return m.memberType
1666}
1667
1668func (m *memberContext) Name() string {
1669 return m.name
1670}
1671
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001672func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001673
1674 memberType := member.memberType
1675
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001676 // Do not add the prefer property if the member snapshot module is a source module type.
1677 if !memberType.UsesSourceModuleTypeInSnapshot() {
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +00001678 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1679 // snapshot to be created that sets prefer: true.
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001680 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1681 // dynamically at build time not at snapshot generation time.
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001682 config := ctx.sdkMemberContext.Config()
1683 prefer := config.IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001684
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001685 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1686 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1687 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1688 // behavior is for the module.
1689 bpModule.insertAfter("name", "prefer", prefer)
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001690
1691 configVar := config.Getenv("SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR")
1692 if configVar != "" {
1693 parts := strings.Split(configVar, ":")
1694 cfp := android.ConfigVarProperties{
1695 Config_namespace: proptools.StringPtr(parts[0]),
1696 Var_name: proptools.StringPtr(parts[1]),
1697 }
1698 bpModule.insertAfter("prefer", "use_source_config_var", cfp)
1699 }
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001700 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001701
Paul Duffina04c1072020-03-02 10:16:35 +00001702 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001703 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001704 variants := member.Variants()
1705 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001706 osType := variant.Target().Os
1707 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001708 }
1709
Paul Duffina04c1072020-03-02 10:16:35 +00001710 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001711 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001712 properties := memberType.CreateVariantPropertiesStruct()
1713 base := properties.Base()
1714 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001715 return properties
1716 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001717
Paul Duffina04c1072020-03-02 10:16:35 +00001718 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001719
Paul Duffina04c1072020-03-02 10:16:35 +00001720 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001721 commonProperties := variantPropertiesFactory()
1722 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001723
Paul Duffinc097e362020-03-10 22:50:03 +00001724 // Create common value extractor that can be used to optimize the properties.
1725 commonValueExtractor := newCommonValueExtractor(commonProperties)
1726
Paul Duffina04c1072020-03-02 10:16:35 +00001727 // The list of property structures which are os type specific but common across
1728 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001729 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001730
1731 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001732 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001733 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001734 // Add the os specific properties to a list of os type specific yet architecture
1735 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001736 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001737
Paul Duffin00e46802020-03-12 20:40:35 +00001738 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001739 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001740 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001741
Paul Duffina04c1072020-03-02 10:16:35 +00001742 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001743 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001744
Paul Duffina04c1072020-03-02 10:16:35 +00001745 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001746 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001747
Paul Duffina04c1072020-03-02 10:16:35 +00001748 // Create a target property set into which target specific properties can be
1749 // added.
1750 targetPropertySet := bpModule.AddPropertySet("target")
1751
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001752 // If the member is host OS dependent and has host_supported then disable by
1753 // default and enable each host OS variant explicitly. This avoids problems
1754 // with implicitly enabled OS variants when the snapshot is used, which might
1755 // be different from this run (e.g. different build OS).
1756 if ctx.memberType.IsHostOsDependent() {
1757 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1758 if hostSupported {
1759 hostPropertySet := targetPropertySet.AddPropertySet("host")
1760 hostPropertySet.AddProperty("enabled", false)
1761 }
1762 }
1763
Paul Duffina04c1072020-03-02 10:16:35 +00001764 // Iterate over the os types in a fixed order.
1765 for _, osType := range s.getPossibleOsTypes() {
1766 osInfo := osTypeToInfo[osType]
1767 if osInfo == nil {
1768 continue
1769 }
1770
Paul Duffin3a4eb502020-03-19 16:11:18 +00001771 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001772 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001773}
1774
Paul Duffina04c1072020-03-02 10:16:35 +00001775// Compute the list of possible os types that this sdk could support.
1776func (s *sdk) getPossibleOsTypes() []android.OsType {
1777 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001778 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001779 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07001780 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00001781 osTypes = append(osTypes, osType)
1782 }
1783 }
1784 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001785 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001786 osTypes = append(osTypes, osType)
1787 }
1788 }
1789 }
1790 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1791 return osTypes
1792}
1793
Paul Duffinb28369a2020-05-04 15:39:59 +01001794// Given a set of properties (struct value), return the value of the field within that
1795// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001796type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1797
Paul Duffinc459f892020-04-30 18:08:29 +01001798// Checks the metadata to determine whether the property should be ignored for the
1799// purposes of common value extraction or not.
1800type extractorMetadataPredicate func(metadata propertiesContainer) bool
1801
1802// Indicates whether optimizable properties are provided by a host variant or
1803// not.
1804type isHostVariant interface {
1805 isHostVariant() bool
1806}
1807
Paul Duffinb28369a2020-05-04 15:39:59 +01001808// A property that can be optimized by the commonValueExtractor.
1809type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001810 // The name of the field for this property. It is a "."-separated path for
1811 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001812 name string
1813
Paul Duffinc459f892020-04-30 18:08:29 +01001814 // Filter that can use metadata associated with the properties being optimized
1815 // to determine whether the field should be ignored during common value
1816 // optimization.
1817 filter extractorMetadataPredicate
1818
Paul Duffinb28369a2020-05-04 15:39:59 +01001819 // Retrieves the value on which common value optimization will be performed.
1820 getter fieldAccessorFunc
1821
1822 // The empty value for the field.
1823 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001824
1825 // True if the property can support arch variants false otherwise.
1826 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001827}
1828
Paul Duffin4b8b7932020-05-06 12:35:38 +01001829func (p extractorProperty) String() string {
1830 return p.name
1831}
1832
Paul Duffinc097e362020-03-10 22:50:03 +00001833// Supports extracting common values from a number of instances of a properties
1834// structure into a separate common set of properties.
1835type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001836 // The properties that the extractor can optimize.
1837 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001838}
1839
1840// Create a new common value extractor for the structure type for the supplied
1841// properties struct.
1842//
1843// The returned extractor can be used on any properties structure of the same type
1844// as the supplied set of properties.
1845func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1846 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1847 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001848 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001849 return extractor
1850}
1851
1852// Gather the fields from the supplied structure type from which common values will
1853// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001854//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001855// This is recursive function. If it encounters a struct then it will recurse
1856// into it, passing in the accessor for the field and the struct name as prefix
1857// for the nested fields. That will then be used in the accessors for the fields
1858// in the embedded struct.
1859func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001860 for f := 0; f < structType.NumField(); f++ {
1861 field := structType.Field(f)
1862 if field.PkgPath != "" {
1863 // Ignore unexported fields.
1864 continue
1865 }
1866
Paul Duffinb07fa512020-03-10 22:17:04 +00001867 // Ignore fields whose value should be kept.
1868 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001869 continue
1870 }
1871
Paul Duffinc459f892020-04-30 18:08:29 +01001872 var filter extractorMetadataPredicate
1873
1874 // Add a filter
1875 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1876 filter = func(metadata propertiesContainer) bool {
1877 if m, ok := metadata.(isHostVariant); ok {
1878 if m.isHostVariant() {
1879 return false
1880 }
1881 }
1882 return true
1883 }
1884 }
1885
Paul Duffinc097e362020-03-10 22:50:03 +00001886 // Save a copy of the field index for use in the function.
1887 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001888
Martin Stjernholmb0249572020-09-15 02:32:35 +01001889 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001890
Paul Duffinc097e362020-03-10 22:50:03 +00001891 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001892 if containingStructAccessor != nil {
1893 // This is an embedded structure so first access the field for the embedded
1894 // structure.
1895 value = containingStructAccessor(value)
1896 }
1897
Paul Duffinc097e362020-03-10 22:50:03 +00001898 // Skip through interface and pointer values to find the structure.
1899 value = getStructValue(value)
1900
Paul Duffin4b8b7932020-05-06 12:35:38 +01001901 defer func() {
1902 if r := recover(); r != nil {
1903 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1904 }
1905 }()
1906
Paul Duffinc097e362020-03-10 22:50:03 +00001907 // Return the field.
1908 return value.Field(fieldIndex)
1909 }
1910
Martin Stjernholmb0249572020-09-15 02:32:35 +01001911 if field.Type.Kind() == reflect.Struct {
1912 // Gather fields from the nested or embedded structure.
1913 var subNamePrefix string
1914 if field.Anonymous {
1915 subNamePrefix = namePrefix
1916 } else {
1917 subNamePrefix = name + "."
1918 }
1919 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001920 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001921 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001922 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001923 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001924 fieldGetter,
1925 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001926 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001927 }
1928 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001929 }
Paul Duffinc097e362020-03-10 22:50:03 +00001930 }
1931}
1932
1933func getStructValue(value reflect.Value) reflect.Value {
1934foundStruct:
1935 for {
1936 kind := value.Kind()
1937 switch kind {
1938 case reflect.Interface, reflect.Ptr:
1939 value = value.Elem()
1940 case reflect.Struct:
1941 break foundStruct
1942 default:
1943 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1944 }
1945 }
1946 return value
1947}
1948
Paul Duffinf34f6d82020-04-30 15:48:31 +01001949// A container of properties to be optimized.
1950//
1951// Allows additional information to be associated with the properties, e.g. for
1952// filtering.
1953type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001954 fmt.Stringer
1955
Paul Duffinf34f6d82020-04-30 15:48:31 +01001956 // Get the properties that need optimizing.
1957 optimizableProperties() interface{}
1958}
1959
Paul Duffin2d1bb892021-04-24 11:32:59 +01001960// A wrapper for sdk variant related properties to allow them to be optimized.
1961type sdkVariantPropertiesContainer struct {
1962 sdkVariant *sdk
1963 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01001964}
1965
Paul Duffin2d1bb892021-04-24 11:32:59 +01001966func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
1967 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01001968}
1969
Paul Duffin2d1bb892021-04-24 11:32:59 +01001970func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001971 return c.sdkVariant.String()
1972}
1973
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001974// Extract common properties from a slice of property structures of the same type.
1975//
1976// All the property structures must be of the same type.
1977// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001978// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001979//
1980// Iterates over each exported field (capitalized name) and checks to see whether they
1981// have the same value (using DeepEquals) across all the input properties. If it does not then no
1982// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001983// and the field in each of the input properties structure is set to its default value. Nested
1984// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001985func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001986 commonPropertiesValue := reflect.ValueOf(commonProperties)
1987 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001988
Paul Duffinf34f6d82020-04-30 15:48:31 +01001989 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1990
Paul Duffinb28369a2020-05-04 15:39:59 +01001991 for _, property := range e.properties {
1992 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001993 filter := property.filter
1994 if filter == nil {
1995 filter = func(metadata propertiesContainer) bool {
1996 return true
1997 }
1998 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001999
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002000 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002001 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2002 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002003 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002004
Paul Duffin864e1b42020-05-06 10:23:19 +01002005 // Assume that all the values will be the same.
2006 //
2007 // While similar to this is not quite the same as commonValue == nil. If all the values
2008 // have been filtered out then this will be false but commonValue == nil will be true.
2009 valuesDiffer := false
2010
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002011 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002012 container := sliceValue.Index(i).Interface().(propertiesContainer)
2013 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002014 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002015
Paul Duffinc459f892020-04-30 18:08:29 +01002016 if !filter(container) {
2017 expectedValue := property.emptyValue.Interface()
2018 actualValue := fieldValue.Interface()
2019 if !reflect.DeepEqual(expectedValue, actualValue) {
2020 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2021 }
2022 continue
2023 }
2024
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002025 if commonValue == nil {
2026 // Use the first value as the commonProperties value.
2027 commonValue = &fieldValue
2028 } else {
2029 // If the value does not match the current common value then there is
2030 // no value in common so break out.
2031 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2032 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002033 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002034 break
2035 }
2036 }
2037 }
2038
Paul Duffin864e1b42020-05-06 10:23:19 +01002039 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002040 // and set the input struct's field to the empty value.
2041 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002042 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002043 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002044 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002045 container := sliceValue.Index(i).Interface().(propertiesContainer)
2046 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002047 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002048 fieldValue.Set(emptyValue)
2049 }
2050 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002051
2052 if valuesDiffer && !property.archVariant {
2053 // The values differ but the property does not support arch variants so it
2054 // is an error.
2055 var details strings.Builder
2056 for i := 0; i < sliceValue.Len(); i++ {
2057 container := sliceValue.Index(i).Interface().(propertiesContainer)
2058 itemValue := reflect.ValueOf(container.optimizableProperties())
2059 fieldValue := fieldGetter(itemValue)
2060
2061 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2062 }
2063
2064 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2065 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002066 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002067
2068 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002069}