blob: e889f3a369c91a9259dfbbe7374677682c787b41 [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 Duffind19f8942021-07-14 12:08:37 +0100396 traits := s.gatherTraits()
Paul Duffin13ad94f2020-02-19 16:19:27 +0000397 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000398 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000399
Paul Duffind19f8942021-07-14 12:08:37 +0100400 name := member.name
401 requiredTraits := traits[name]
402 if requiredTraits == nil {
403 requiredTraits = android.EmptySdkMemberTraitSet()
404 }
405
406 // Create the snapshot for the member.
407 memberCtx := &memberContext{ctx, builder, memberType, name, requiredTraits}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000408
409 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100410 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900411 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900412
Paul Duffine6c0d842020-01-15 14:08:51 +0000413 // Create a transformer that will transform an unversioned module into a versioned module.
414 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
415
Paul Duffin72910952020-01-20 18:16:30 +0000416 // Create a transformer that will transform an unversioned module by replacing any references
417 // to internal members with a unique module name and setting prefer: false.
Paul Duffin64fb5262021-05-05 21:36:04 +0100418 unversionedTransformer := unversionedTransformation{
419 builder: builder,
Paul Duffin64fb5262021-05-05 21:36:04 +0100420 }
Paul Duffin72910952020-01-20 18:16:30 +0000421
Paul Duffinb645ec82019-11-27 17:43:54 +0000422 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000423 // Prune any empty property sets.
424 unversioned = unversioned.transform(pruneEmptySetTransformer{})
425
Paul Duffin43f7bf02021-05-05 22:00:51 +0100426 if generateVersioned {
427 // Copy the unversioned module so it can be modified to make it versioned.
428 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000429
Paul Duffin43f7bf02021-05-05 22:00:51 +0100430 // Transform the unversioned module into a versioned one.
431 versioned.transform(unversionedToVersionedTransformer)
432 bpFile.AddModule(versioned)
433 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000434
Paul Duffin43f7bf02021-05-05 22:00:51 +0100435 if generateUnversioned {
436 // Transform the unversioned module to make it suitable for use in the snapshot.
437 unversioned.transform(unversionedTransformer)
438 bpFile.AddModule(unversioned)
439 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000440 }
441
Paul Duffin43f7bf02021-05-05 22:00:51 +0100442 if generateVersioned {
443 // Add the sdk/module_exports_snapshot module to the bp file.
444 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
445 }
Paul Duffin26197a62021-04-24 00:34:10 +0100446
447 // generate Android.bp
448 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
449 generateBpContents(&bp.generatedContents, bpFile)
450
451 contents := bp.content.String()
452 syntaxCheckSnapshotBpFile(ctx, contents)
453
454 bp.build(pctx, ctx, nil)
455
456 filesToZip := builder.filesToZip
457
458 // zip them all
Paul Duffin43f7bf02021-05-05 22:00:51 +0100459 zipPath := fmt.Sprintf("%s%s.zip", ctx.ModuleName(), snapshotZipFileSuffix)
460 outputZipFile := android.PathForModuleOut(ctx, zipPath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100461 outputDesc := "Building snapshot for " + ctx.ModuleName()
462
463 // If there are no zips to merge then generate the output zip directly.
464 // Otherwise, generate an intermediate zip file into which other zips can be
465 // merged.
466 var zipFile android.OutputPath
467 var desc string
468 if len(builder.zipsToMerge) == 0 {
469 zipFile = outputZipFile
470 desc = outputDesc
471 } else {
Paul Duffin43f7bf02021-05-05 22:00:51 +0100472 intermediatePath := fmt.Sprintf("%s%s.unmerged.zip", ctx.ModuleName(), snapshotZipFileSuffix)
473 zipFile = android.PathForModuleOut(ctx, intermediatePath).OutputPath
Paul Duffin26197a62021-04-24 00:34:10 +0100474 desc = "Building intermediate snapshot for " + ctx.ModuleName()
475 }
476
477 ctx.Build(pctx, android.BuildParams{
478 Description: desc,
479 Rule: zipFiles,
480 Inputs: filesToZip,
481 Output: zipFile,
482 Args: map[string]string{
483 "basedir": builder.snapshotDir.String(),
484 },
485 })
486
487 if len(builder.zipsToMerge) != 0 {
488 ctx.Build(pctx, android.BuildParams{
489 Description: outputDesc,
490 Rule: mergeZips,
491 Input: zipFile,
492 Inputs: builder.zipsToMerge,
493 Output: outputZipFile,
494 })
495 }
496
497 return outputZipFile
498}
499
Paul Duffinb97b1572021-04-29 21:50:40 +0100500// filterOutComponents removes any item from the deps list that is a component of another item in
501// the deps list, e.g. if the deps list contains "foo" and "foo.stubs" which is component of "foo"
502// then it will remove "foo.stubs" from the deps.
503func filterOutComponents(ctx android.ModuleContext, deps []sdkMemberVariantDep) []sdkMemberVariantDep {
504 // Collate the set of components that all the modules added to the sdk provide.
505 components := map[string]*sdkMemberVariantDep{}
506 for i, _ := range deps {
507 dep := &deps[i]
508 for _, c := range dep.exportedComponentsInfo.Components {
509 components[c] = dep
510 }
511 }
512
513 // If no module provides components then return the input deps unfiltered.
514 if len(components) == 0 {
515 return deps
516 }
517
518 filtered := make([]sdkMemberVariantDep, 0, len(deps))
519 for _, dep := range deps {
520 name := android.RemoveOptionalPrebuiltPrefix(ctx.OtherModuleName(dep.variant))
521 if owner, ok := components[name]; ok {
522 // This is a component of another module that is a member of the sdk.
523
524 // If the component is exported but the owning module is not then the configuration is not
525 // supported.
526 if dep.export && !owner.export {
527 ctx.ModuleErrorf("Module %s is internal to the SDK but provides component %s which is used outside the SDK")
528 continue
529 }
530
531 // This module must not be added to the list of members of the sdk as that would result in a
532 // duplicate module in the sdk snapshot.
533 continue
534 }
535
536 filtered = append(filtered, dep)
537 }
538 return filtered
539}
540
Paul Duffin26197a62021-04-24 00:34:10 +0100541// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100542func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100543 bpFile := builder.bpFile
544
Paul Duffinb645ec82019-11-27 17:43:54 +0000545 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000546 var snapshotModuleType string
547 if s.properties.Module_exports {
548 snapshotModuleType = "module_exports_snapshot"
549 } else {
550 snapshotModuleType = "sdk_snapshot"
551 }
552 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000553 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000554
555 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100556 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000557 if len(visibility) != 0 {
558 snapshotModule.AddProperty("visibility", visibility)
559 }
560
Paul Duffin865171e2020-03-02 18:38:15 +0000561 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000562
Paul Duffincd064672021-04-24 00:47:29 +0100563 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100564 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000565
Paul Duffin2d1bb892021-04-24 11:32:59 +0100566 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100567
Paul Duffin6a7e9532020-03-20 17:50:07 +0000568 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100569
Paul Duffin2d1bb892021-04-24 11:32:59 +0100570 // Create a mapping from osType to combined properties.
571 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
572 for _, combined := range combinedPropertiesList {
573 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
574 }
575
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100576 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000577 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100578 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100579 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000580
Paul Duffin2d1bb892021-04-24 11:32:59 +0100581 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000582 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000583 }
Paul Duffin865171e2020-03-02 18:38:15 +0000584
Jiyong Park8fe14e62020-10-19 22:47:34 +0900585 // If host is supported and any member is host OS dependent then disable host
586 // by default, so that we can enable each host OS variant explicitly. This
587 // avoids problems with implicitly enabled OS variants when the snapshot is
588 // used, which might be different from this run (e.g. different build OS).
589 if s.HostSupported() {
590 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100591 for _, memberVariantDep := range memberVariantDeps {
592 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
593 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900594 if !android.InList(targetString, supportedHostTargets) {
595 supportedHostTargets = append(supportedHostTargets, targetString)
596 }
597 }
598 }
599 if len(supportedHostTargets) > 0 {
600 hostPropertySet := targetPropertySet.AddPropertySet("host")
601 hostPropertySet.AddProperty("enabled", false)
602 }
603 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
604 for _, hostTarget := range supportedHostTargets {
605 propertySet := targetPropertySet.AddPropertySet(hostTarget)
606 propertySet.AddProperty("enabled", true)
607 }
608 }
609
Paul Duffin865171e2020-03-02 18:38:15 +0000610 // Prune any empty property sets.
611 snapshotModule.transform(pruneEmptySetTransformer{})
612
Paul Duffinb645ec82019-11-27 17:43:54 +0000613 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900614}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000615
Paul Duffinf88d8e02020-05-07 20:21:34 +0100616// Check the syntax of the generated Android.bp file contents and if they are
617// invalid then log an error with the contents (tagged with line numbers) and the
618// errors that were found so that it is easy to see where the problem lies.
619func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
620 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
621 if len(errs) != 0 {
622 message := &strings.Builder{}
623 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
624
625Generated Android.bp contents
626========================================================================
627`)
628 for i, line := range strings.Split(contents, "\n") {
629 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
630 }
631
632 _, _ = fmt.Fprint(message, `
633========================================================================
634
635Errors found:
636`)
637
638 for _, err := range errs {
639 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
640 }
641
642 ctx.ModuleErrorf("%s", message.String())
643 }
644}
645
Paul Duffin4b8b7932020-05-06 12:35:38 +0100646func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
647 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
648 if err != nil {
649 ctx.ModuleErrorf("error extracting common properties: %s", err)
650 }
651}
652
Paul Duffinfbe470e2021-04-24 12:37:13 +0100653// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
654type snapshotModuleStaticProperties struct {
655 Compile_multilib string `android:"arch_variant"`
656}
657
Paul Duffin2d1bb892021-04-24 11:32:59 +0100658// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
659type combinedSnapshotModuleProperties struct {
660 // The sdk variant from which this information was collected.
661 sdkVariant *sdk
662
663 // Static snapshot module properties.
664 staticProperties *snapshotModuleStaticProperties
665
666 // The dynamically generated member list properties.
667 dynamicProperties interface{}
668}
669
670// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100671func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
672 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100673 var list []*combinedSnapshotModuleProperties
674 for _, sdkVariant := range sdkVariants {
675 staticProperties := &snapshotModuleStaticProperties{
676 Compile_multilib: sdkVariant.multilibUsages.String(),
677 }
Paul Duffin62782de2021-07-14 12:05:16 +0100678 dynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100679
Paul Duffincd064672021-04-24 00:47:29 +0100680 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100681 sdkVariant: sdkVariant,
682 staticProperties: staticProperties,
683 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100684 }
685 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
686
687 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100688 }
Paul Duffincd064672021-04-24 00:47:29 +0100689
690 for _, memberVariantDep := range memberVariantDeps {
691 // If the member dependency is internal then do not add the dependency to the snapshot member
692 // list properties.
693 if !memberVariantDep.export {
694 continue
695 }
696
697 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
Paul Duffin62782de2021-07-14 12:05:16 +0100698 memberListProperty := s.memberTypeListProperty(memberVariantDep.memberType)
Paul Duffincd064672021-04-24 00:47:29 +0100699 memberName := ctx.OtherModuleName(memberVariantDep.variant)
700
Paul Duffin13082052021-05-11 00:31:38 +0100701 if memberListProperty.getter == nil {
702 continue
703 }
704
Paul Duffincd064672021-04-24 00:47:29 +0100705 // Append the member to the appropriate list, if it is not already present in the list.
Paul Duffin13082052021-05-11 00:31:38 +0100706 memberList := memberListProperty.getter(combined.dynamicProperties)
Paul Duffincd064672021-04-24 00:47:29 +0100707 if !android.InList(memberName, memberList) {
708 memberList = append(memberList, memberName)
709 }
Paul Duffin13082052021-05-11 00:31:38 +0100710 memberListProperty.setter(combined.dynamicProperties, memberList)
Paul Duffincd064672021-04-24 00:47:29 +0100711 }
712
Paul Duffin2d1bb892021-04-24 11:32:59 +0100713 return list
714}
715
716func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
717
718 // Extract the dynamic properties and add them to a list of propertiesContainer.
719 propertyContainers := []propertiesContainer{}
720 for _, i := range list {
721 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
722 sdkVariant: i.sdkVariant,
723 properties: i.dynamicProperties,
724 })
725 }
726
727 // Extract the common members, removing them from the original properties.
Paul Duffin62782de2021-07-14 12:05:16 +0100728 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberTypeListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100729 extractor := newCommonValueExtractor(commonDynamicProperties)
730 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
731
732 // Extract the static properties and add them to a list of propertiesContainer.
733 propertyContainers = []propertiesContainer{}
734 for _, i := range list {
735 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
736 sdkVariant: i.sdkVariant,
737 properties: i.staticProperties,
738 })
739 }
740
741 commonStaticProperties := &snapshotModuleStaticProperties{}
742 extractor = newCommonValueExtractor(commonStaticProperties)
743 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
744
745 return &combinedSnapshotModuleProperties{
746 sdkVariant: nil,
747 staticProperties: commonStaticProperties,
748 dynamicProperties: commonDynamicProperties,
749 }
750}
751
752func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
753 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100754 multilib := staticProperties.Compile_multilib
755 if multilib != "" && multilib != "both" {
756 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
757 propertySet.AddProperty("compile_multilib", multilib)
758 }
759
Paul Duffin2d1bb892021-04-24 11:32:59 +0100760 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin62782de2021-07-14 12:05:16 +0100761 for _, memberListProperty := range s.memberTypeListProperties() {
Paul Duffin13082052021-05-11 00:31:38 +0100762 if memberListProperty.getter == nil {
763 continue
764 }
Paul Duffin865171e2020-03-02 18:38:15 +0000765 names := memberListProperty.getter(dynamicMemberTypeListProperties)
766 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000767 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000768 }
769 }
770}
771
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000772type propertyTag struct {
773 name string
774}
775
Paul Duffin94289702021-09-09 15:38:32 +0100776var _ android.BpPropertyTag = propertyTag{}
777
Paul Duffin0cb37b92020-03-04 14:52:46 +0000778// A BpPropertyTag to add to a property that contains references to other sdk members.
779//
780// This will cause the references to be rewritten to a versioned reference in the version
781// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000782var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000783var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000784
Paul Duffin0cb37b92020-03-04 14:52:46 +0000785// A BpPropertyTag that indicates the property should only be present in the versioned
786// module.
787//
788// This will cause the property to be removed from the unversioned instance of a
789// snapshot module.
790var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
791
Paul Duffine6c0d842020-01-15 14:08:51 +0000792type unversionedToVersionedTransformation struct {
793 identityTransformation
794 builder *snapshotBuilder
795}
796
Paul Duffine6c0d842020-01-15 14:08:51 +0000797func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
798 // Use a versioned name for the module but remember the original name for the
799 // snapshot.
Paul Duffin0df49682021-05-07 01:10:01 +0100800 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000801 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000802 module.insertAfter("name", "sdk_member_name", name)
Paul Duffin83ad9562021-05-10 23:49:04 +0100803 // Remove the prefer property if present as versioned modules never need marking with prefer.
804 module.removeProperty("prefer")
Paul Duffinfb9a7f92021-07-06 17:18:42 +0100805 // Ditto for use_source_config_var
806 module.removeProperty("use_source_config_var")
Paul Duffine6c0d842020-01-15 14:08:51 +0000807 return module
808}
809
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000810func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000811 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
812 required := tag == requiredSdkMemberReferencePropertyTag
813 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000814 } else {
815 return value, tag
816 }
817}
818
Paul Duffin72910952020-01-20 18:16:30 +0000819type unversionedTransformation struct {
820 identityTransformation
821 builder *snapshotBuilder
822}
823
824func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
825 // If the module is an internal member then use a unique name for it.
Paul Duffin0df49682021-05-07 01:10:01 +0100826 name := module.Name()
Paul Duffin13f02712020-03-06 12:30:43 +0000827 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000828 return module
829}
830
831func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000832 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
833 required := tag == requiredSdkMemberReferencePropertyTag
834 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000835 } else if tag == sdkVersionedOnlyPropertyTag {
836 // The property is not allowed in the unversioned module so remove it.
837 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000838 } else {
839 return value, tag
840 }
841}
842
Paul Duffina78f3a72020-02-21 16:29:35 +0000843type pruneEmptySetTransformer struct {
844 identityTransformation
845}
846
847var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
848
849func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
850 if len(propertySet.properties) == 0 {
851 return nil, nil
852 } else {
853 return propertySet, tag
854 }
855}
856
Paul Duffinb645ec82019-11-27 17:43:54 +0000857func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000858 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
859 return true
860 })
861}
862
863func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100864 contents.IndentedPrintf("// This is auto-generated. DO NOT EDIT.\n")
Paul Duffinb645ec82019-11-27 17:43:54 +0000865 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000866 if moduleFilter(bpModule) {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100867 contents.IndentedPrintf("\n")
868 contents.IndentedPrintf("%s {\n", bpModule.moduleType)
Paul Duffind0759072021-02-17 11:23:00 +0000869 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100870 contents.IndentedPrintf("}\n")
Paul Duffind0759072021-02-17 11:23:00 +0000871 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000872 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000873}
874
875func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
876 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000877
Paul Duffin0df49682021-05-07 01:10:01 +0100878 addComment := func(name string) {
879 if text, ok := set.comments[name]; ok {
880 for _, line := range strings.Split(text, "\n") {
Paul Duffina08e4dc2021-06-22 18:19:19 +0100881 contents.IndentedPrintf("// %s\n", line)
Paul Duffin0df49682021-05-07 01:10:01 +0100882 }
883 }
884 }
885
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000886 // Output the properties first, followed by the nested sets. This ensures a
887 // consistent output irrespective of whether property sets are created before
888 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000889 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000890 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000891
Paul Duffin0df49682021-05-07 01:10:01 +0100892 // Do not write property sets in the properties phase.
893 if _, ok := value.(*bpPropertySet); ok {
894 continue
895 }
896
897 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100898 reflectValue := reflect.ValueOf(value)
899 outputNamedValue(contents, name, reflectValue)
Paul Duffinb645ec82019-11-27 17:43:54 +0000900 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000901
902 for _, name := range set.order {
903 value := set.getValue(name)
904
905 // Only write property sets in the sets phase.
906 switch v := value.(type) {
907 case *bpPropertySet:
Paul Duffin0df49682021-05-07 01:10:01 +0100908 addComment(name)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100909 contents.IndentedPrintf("%s: {\n", name)
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000910 outputPropertySet(contents, v)
Paul Duffina08e4dc2021-06-22 18:19:19 +0100911 contents.IndentedPrintf("},\n")
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000912 }
913 }
914
Paul Duffinb645ec82019-11-27 17:43:54 +0000915 contents.Dedent()
916}
917
Paul Duffina08e4dc2021-06-22 18:19:19 +0100918// outputNamedValue outputs a value that has an associated name. The name will be indented, followed
919// by the value and then followed by a , and a newline.
920func outputNamedValue(contents *generatedContents, name string, value reflect.Value) {
921 contents.IndentedPrintf("%s: ", name)
922 outputUnnamedValue(contents, value)
923 contents.UnindentedPrintf(",\n")
924}
925
926// outputUnnamedValue outputs a single value. The value is not indented and is not followed by
927// either a , or a newline. With multi-line values, e.g. slices, all but the first line will be
928// indented and all but the last line will end with a newline.
929func outputUnnamedValue(contents *generatedContents, value reflect.Value) {
930 valueType := value.Type()
931 switch valueType.Kind() {
932 case reflect.Bool:
933 contents.UnindentedPrintf("%t", value.Bool())
934
935 case reflect.String:
936 contents.UnindentedPrintf("%q", value)
937
Paul Duffin51227d82021-05-18 12:54:27 +0100938 case reflect.Ptr:
939 outputUnnamedValue(contents, value.Elem())
940
Paul Duffina08e4dc2021-06-22 18:19:19 +0100941 case reflect.Slice:
942 length := value.Len()
943 if length == 0 {
944 contents.UnindentedPrintf("[]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100945 } else {
Paul Duffin51227d82021-05-18 12:54:27 +0100946 firstValue := value.Index(0)
947 if length == 1 && !multiLineValue(firstValue) {
948 contents.UnindentedPrintf("[")
949 outputUnnamedValue(contents, firstValue)
950 contents.UnindentedPrintf("]")
951 } else {
952 contents.UnindentedPrintf("[\n")
953 contents.Indent()
954 for i := 0; i < length; i++ {
955 itemValue := value.Index(i)
956 contents.IndentedPrintf("")
957 outputUnnamedValue(contents, itemValue)
958 contents.UnindentedPrintf(",\n")
959 }
960 contents.Dedent()
961 contents.IndentedPrintf("]")
Paul Duffina08e4dc2021-06-22 18:19:19 +0100962 }
Paul Duffina08e4dc2021-06-22 18:19:19 +0100963 }
964
Paul Duffin51227d82021-05-18 12:54:27 +0100965 case reflect.Struct:
966 // Avoid unlimited recursion by requiring every structure to implement android.BpPrintable.
967 v := value.Interface()
968 if _, ok := v.(android.BpPrintable); !ok {
969 panic(fmt.Errorf("property value %#v of type %T does not implement android.BpPrintable", v, v))
970 }
971 contents.UnindentedPrintf("{\n")
972 contents.Indent()
973 for f := 0; f < valueType.NumField(); f++ {
974 fieldType := valueType.Field(f)
975 if fieldType.Anonymous {
976 continue
977 }
978 fieldValue := value.Field(f)
979 fieldName := fieldType.Name
980 propertyName := proptools.PropertyNameForField(fieldName)
981 outputNamedValue(contents, propertyName, fieldValue)
982 }
983 contents.Dedent()
984 contents.IndentedPrintf("}")
985
Paul Duffina08e4dc2021-06-22 18:19:19 +0100986 default:
987 panic(fmt.Errorf("Unknown type: %T of value %#v", value, value))
988 }
989}
990
Paul Duffin51227d82021-05-18 12:54:27 +0100991// multiLineValue returns true if the supplied value may require multiple lines in the output.
992func multiLineValue(value reflect.Value) bool {
993 kind := value.Kind()
994 return kind == reflect.Slice || kind == reflect.Struct
995}
996
Paul Duffinac37c502019-11-26 18:02:20 +0000997func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000998 contents := &generatedContents{}
999 generateBpContents(contents, s.builderForTests.bpFile)
1000 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +00001001}
1002
Paul Duffind0759072021-02-17 11:23:00 +00001003func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
1004 contents := &generatedContents{}
1005 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001006 name := module.Name()
1007 // Include modules that are either unversioned or have no name.
1008 return !strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001009 })
1010 return contents.content.String()
1011}
1012
1013func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
1014 contents := &generatedContents{}
1015 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
Paul Duffin0df49682021-05-07 01:10:01 +01001016 name := module.Name()
1017 // Include modules that are either versioned or have no name.
1018 return name == "" || strings.Contains(name, "@")
Paul Duffind0759072021-02-17 11:23:00 +00001019 })
1020 return contents.content.String()
1021}
1022
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001023type snapshotBuilder struct {
Paul Duffin43f7bf02021-05-05 22:00:51 +01001024 ctx android.ModuleContext
1025 sdk *sdk
1026
1027 // The version of the generated snapshot.
1028 //
1029 // See the documentation of SOONG_SDK_SNAPSHOT_VERSION above for details of the valid values of
1030 // this field.
1031 version string
1032
Paul Duffinb645ec82019-11-27 17:43:54 +00001033 snapshotDir android.OutputPath
1034 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +00001035
1036 // Map from destination to source of each copy - used to eliminate duplicates and
1037 // detect conflicts.
1038 copies map[string]string
1039
Paul Duffinb645ec82019-11-27 17:43:54 +00001040 filesToZip android.Paths
1041 zipsToMerge android.Paths
1042
Paul Duffin5c211452021-07-15 12:42:44 +01001043 // The path to an empty file.
1044 emptyFile android.WritablePath
1045
Paul Duffinb645ec82019-11-27 17:43:54 +00001046 prebuiltModules map[string]*bpModule
1047 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +00001048
1049 // The set of all members by name.
1050 allMembersByName map[string]struct{}
1051
1052 // The set of exported members by name.
1053 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001054}
1055
1056func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +00001057 if existing, ok := s.copies[dest]; ok {
1058 if existing != src.String() {
1059 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
1060 return
1061 }
1062 } else {
1063 path := s.snapshotDir.Join(s.ctx, dest)
1064 s.ctx.Build(pctx, android.BuildParams{
1065 Rule: android.Cp,
1066 Input: src,
1067 Output: path,
1068 })
1069 s.filesToZip = append(s.filesToZip, path)
1070
1071 s.copies[dest] = src.String()
1072 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001073}
1074
Paul Duffin91547182019-11-12 19:39:36 +00001075func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
1076 ctx := s.ctx
1077
1078 // Repackage the zip file so that the entries are in the destDir directory.
1079 // This will allow the zip file to be merged into the snapshot.
1080 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +00001081
1082 ctx.Build(pctx, android.BuildParams{
1083 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
1084 Rule: repackageZip,
1085 Input: zipPath,
1086 Output: tmpZipPath,
1087 Args: map[string]string{
1088 "destdir": destDir,
1089 },
1090 })
Paul Duffin91547182019-11-12 19:39:36 +00001091
1092 // Add the repackaged zip file to the files to merge.
1093 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
1094}
1095
Paul Duffin5c211452021-07-15 12:42:44 +01001096func (s *snapshotBuilder) EmptyFile() android.Path {
1097 if s.emptyFile == nil {
1098 ctx := s.ctx
1099 s.emptyFile = android.PathForModuleOut(ctx, "empty")
1100 s.ctx.Build(pctx, android.BuildParams{
1101 Rule: android.Touch,
1102 Output: s.emptyFile,
1103 })
1104 }
1105
1106 return s.emptyFile
1107}
1108
Paul Duffin9d8d6092019-12-05 18:19:29 +00001109func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
1110 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +00001111 if s.prebuiltModules[name] != nil {
1112 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
1113 }
1114
1115 m := s.bpFile.newModule(moduleType)
1116 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +00001117
Paul Duffinbefa4b92020-03-04 14:22:45 +00001118 variant := member.Variants()[0]
1119
Paul Duffin13f02712020-03-06 12:30:43 +00001120 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +00001121 // An internal member is only referenced from the sdk snapshot which is in the
1122 // same package so can be marked as private.
1123 m.AddProperty("visibility", []string{"//visibility:private"})
1124 } else {
1125 // Extract visibility information from a member variant. All variants have the same
1126 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +01001127 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
1128
1129 // Add any additional visibility rules needed for the prebuilts to reference each other.
1130 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
1131 if err != nil {
1132 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
1133 }
1134
1135 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +00001136 if len(visibility) != 0 {
1137 m.AddProperty("visibility", visibility)
1138 }
Paul Duffin593b3c92019-12-05 14:31:48 +00001139 }
1140
Martin Stjernholm1e041092020-11-03 00:11:09 +00001141 // Where available copy apex_available properties from the member.
1142 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
1143 apexAvailable := apexAware.ApexAvailable()
1144 if len(apexAvailable) == 0 {
1145 // //apex_available:platform is the default.
1146 apexAvailable = []string{android.AvailableToPlatform}
1147 }
1148
1149 // Add in any baseline apex available settings.
1150 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
1151
1152 // Remove duplicates and sort.
1153 apexAvailable = android.FirstUniqueStrings(apexAvailable)
1154 sort.Strings(apexAvailable)
1155
1156 m.AddProperty("apex_available", apexAvailable)
1157 }
1158
Paul Duffinb0bb3762021-05-06 16:48:05 +01001159 // The licenses are the same for all variants.
1160 mctx := s.ctx
1161 licenseInfo := mctx.OtherModuleProvider(variant, android.LicenseInfoProvider).(android.LicenseInfo)
1162 if len(licenseInfo.Licenses) > 0 {
1163 m.AddPropertyWithTag("licenses", licenseInfo.Licenses, s.OptionalSdkMemberReferencePropertyTag())
1164 }
1165
Paul Duffin865171e2020-03-02 18:38:15 +00001166 deviceSupported := false
1167 hostSupported := false
1168
1169 for _, variant := range member.Variants() {
1170 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001171 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +00001172 hostSupported = true
1173 } else if osClass == android.Device {
1174 deviceSupported = true
1175 }
1176 }
1177
1178 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +00001179
Paul Duffin0cb37b92020-03-04 14:52:46 +00001180 // Disable installation in the versioned module of those modules that are ever installable.
1181 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
1182 if installable.EverInstallable() {
1183 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
1184 }
1185 }
1186
Paul Duffinb645ec82019-11-27 17:43:54 +00001187 s.prebuiltModules[name] = m
1188 s.prebuiltOrder = append(s.prebuiltOrder, m)
1189 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001190}
1191
Paul Duffin865171e2020-03-02 18:38:15 +00001192func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
Paul Duffinb0bb3762021-05-06 16:48:05 +01001193 // If neither device or host is supported then this module does not support either so will not
1194 // recognize the properties.
1195 if !deviceSupported && !hostSupported {
1196 return
1197 }
1198
Paul Duffin865171e2020-03-02 18:38:15 +00001199 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001200 bpModule.AddProperty("device_supported", false)
1201 }
Paul Duffin865171e2020-03-02 18:38:15 +00001202 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +00001203 bpModule.AddProperty("host_supported", true)
1204 }
1205}
1206
Paul Duffin13f02712020-03-06 12:30:43 +00001207func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
1208 if required {
1209 return requiredSdkMemberReferencePropertyTag
1210 } else {
1211 return optionalSdkMemberReferencePropertyTag
1212 }
1213}
1214
1215func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
1216 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +00001217}
1218
Paul Duffinb645ec82019-11-27 17:43:54 +00001219// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +00001220func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
1221 if _, ok := s.allMembersByName[unversionedName]; !ok {
1222 if required {
1223 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1224 }
1225 return unversionedName
1226 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +00001227 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
1228}
Paul Duffinb645ec82019-11-27 17:43:54 +00001229
Paul Duffin13f02712020-03-06 12:30:43 +00001230func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +00001231 var references []string = nil
1232 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001233 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +00001234 }
1235 return references
1236}
Paul Duffin13879572019-11-28 14:31:38 +00001237
Paul Duffin72910952020-01-20 18:16:30 +00001238// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +00001239func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
1240 if _, ok := s.allMembersByName[unversionedName]; !ok {
1241 if required {
1242 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
1243 }
1244 return unversionedName
1245 }
1246
1247 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +00001248 return s.ctx.ModuleName() + "_" + unversionedName
1249 } else {
1250 return unversionedName
1251 }
1252}
1253
Paul Duffin13f02712020-03-06 12:30:43 +00001254func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +00001255 var references []string = nil
1256 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +00001257 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +00001258 }
1259 return references
1260}
1261
Paul Duffin13f02712020-03-06 12:30:43 +00001262func (s *snapshotBuilder) isInternalMember(memberName string) bool {
1263 _, ok := s.exportedMembersByName[memberName]
1264 return !ok
1265}
1266
Martin Stjernholm89238f42020-07-10 00:14:03 +01001267// Add the properties from the given SdkMemberProperties to the blueprint
1268// property set. This handles common properties in SdkMemberPropertiesBase and
1269// calls the member-specific AddToPropertySet for the rest.
1270func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
1271 if memberProperties.Base().Compile_multilib != "" {
1272 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
1273 }
1274
1275 memberProperties.AddToPropertySet(ctx, targetPropertySet)
1276}
1277
Paul Duffin21827262021-04-24 12:16:36 +01001278// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
1279type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +01001280 // The sdk variant that depends (possibly indirectly) on the member variant.
1281 sdkVariant *sdk
Paul Duffinb97b1572021-04-29 21:50:40 +01001282
1283 // The type of sdk member the variant is to be treated as.
Paul Duffin1356d8c2020-02-25 19:26:33 +00001284 memberType android.SdkMemberType
Paul Duffinb97b1572021-04-29 21:50:40 +01001285
1286 // The variant that is added to the sdk.
1287 variant android.SdkAware
1288
1289 // True if the member should be exported, i.e. accessible, from outside the sdk.
1290 export bool
1291
1292 // The names of additional component modules provided by the variant.
1293 exportedComponentsInfo android.ExportedComponentsInfo
Paul Duffin1356d8c2020-02-25 19:26:33 +00001294}
1295
Paul Duffin13879572019-11-28 14:31:38 +00001296var _ android.SdkMember = (*sdkMember)(nil)
1297
Paul Duffin21827262021-04-24 12:16:36 +01001298// sdkMember groups all the variants of a specific member module together along with the name of the
1299// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +00001300type sdkMember struct {
1301 memberType android.SdkMemberType
1302 name string
1303 variants []android.SdkAware
1304}
1305
1306func (m *sdkMember) Name() string {
1307 return m.name
1308}
1309
1310func (m *sdkMember) Variants() []android.SdkAware {
1311 return m.variants
1312}
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001313
Paul Duffin9c3760e2020-03-16 19:52:08 +00001314// Track usages of multilib variants.
1315type multilibUsage int
1316
1317const (
1318 multilibNone multilibUsage = 0
1319 multilib32 multilibUsage = 1
1320 multilib64 multilibUsage = 2
1321 multilibBoth = multilib32 | multilib64
1322)
1323
1324// Add the multilib that is used in the arch type.
1325func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1326 multilib := archType.Multilib
1327 switch multilib {
1328 case "":
1329 return m
1330 case "lib32":
1331 return m | multilib32
1332 case "lib64":
1333 return m | multilib64
1334 default:
1335 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1336 }
1337}
1338
1339func (m multilibUsage) String() string {
1340 switch m {
1341 case multilibNone:
1342 return ""
1343 case multilib32:
1344 return "32"
1345 case multilib64:
1346 return "64"
1347 case multilibBoth:
1348 return "both"
1349 default:
1350 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1351 m, multilibNone, multilib32, multilib64, multilibBoth))
1352 }
1353}
1354
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001355type baseInfo struct {
1356 Properties android.SdkMemberProperties
1357}
1358
Paul Duffinf34f6d82020-04-30 15:48:31 +01001359func (b *baseInfo) optimizableProperties() interface{} {
1360 return b.Properties
1361}
1362
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001363type osTypeSpecificInfo struct {
1364 baseInfo
1365
Paul Duffin00e46802020-03-12 20:40:35 +00001366 osType android.OsType
1367
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001368 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001369 //
1370 // Nil if there is one variant whose arch type is common
1371 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001372}
1373
Paul Duffin4b8b7932020-05-06 12:35:38 +01001374var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1375
Paul Duffinfc8dd232020-03-17 12:51:37 +00001376type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1377
Paul Duffin00e46802020-03-12 20:40:35 +00001378// Create a new osTypeSpecificInfo for the specified os type and its properties
1379// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001380func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001381 osInfo := &osTypeSpecificInfo{
1382 osType: osType,
1383 }
1384
1385 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1386 properties := variantPropertiesFactory()
1387 properties.Base().Os = osType
1388 return properties
1389 }
1390
1391 // Create a structure into which properties common across the architectures in
1392 // this os type will be stored.
1393 osInfo.Properties = osSpecificVariantPropertiesFactory()
1394
1395 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001396 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001397 var archTypes []android.ArchType
1398 for _, variant := range osTypeVariants {
1399 archType := variant.Target().Arch.ArchType
1400 archTypeName := archType.Name
1401 if _, ok := variantsByArchName[archTypeName]; !ok {
1402 archTypes = append(archTypes, archType)
1403 }
1404
1405 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1406 }
1407
1408 if commonVariants, ok := variantsByArchName["common"]; ok {
1409 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001410 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 +00001411 }
1412
1413 // A common arch type only has one variant and its properties should be treated
1414 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001415 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001416 } else {
1417 // Create an arch specific info for each supported architecture type.
1418 for _, archType := range archTypes {
1419 archTypeName := archType.Name
1420
1421 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001422 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001423
1424 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1425 }
1426 }
1427
1428 return osInfo
1429}
1430
1431// Optimize the properties by extracting common properties from arch type specific
1432// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001433func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001434 // Nothing to do if there is only a single common architecture.
1435 if len(osInfo.archInfos) == 0 {
1436 return
1437 }
1438
Paul Duffin9c3760e2020-03-16 19:52:08 +00001439 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001440 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001441 multilib = multilib.addArchType(archInfo.archType)
1442
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001443 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001444 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001445 }
1446
Paul Duffin4b8b7932020-05-06 12:35:38 +01001447 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001448
1449 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001450 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001451}
1452
1453// Add the properties for an os to a property set.
1454//
1455// Maps the properties related to the os variants through to an appropriate
1456// module structure that will produce equivalent set of variants when it is
1457// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001458func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001459
1460 var osPropertySet android.BpPropertySet
1461 var archPropertySet android.BpPropertySet
1462 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001463 if osInfo.Properties.Base().Os_count == 1 &&
1464 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1465 // There is only one OS type present in the variants and it shouldn't have a
1466 // variant-specific target. The latter is the case if it's either for device
1467 // where there is only one OS (android), or for host and the member type
1468 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001469
1470 // Create a structure that looks like:
1471 // module_type {
1472 // name: "...",
1473 // ...
1474 // <common properties>
1475 // ...
1476 // <single os type specific properties>
1477 //
1478 // arch: {
1479 // <arch specific sections>
1480 // }
1481 //
1482 osPropertySet = bpModule
1483 archPropertySet = osPropertySet.AddPropertySet("arch")
1484
1485 // Arch specific properties need to be added to an arch specific section
1486 // within arch.
1487 archOsPrefix = ""
1488 } else {
1489 // Create a structure that looks like:
1490 // module_type {
1491 // name: "...",
1492 // ...
1493 // <common properties>
1494 // ...
1495 // target: {
1496 // <arch independent os specific sections, e.g. android>
1497 // ...
1498 // <arch and os specific sections, e.g. android_x86>
1499 // }
1500 //
1501 osType := osInfo.osType
1502 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1503 archPropertySet = targetPropertySet
1504
1505 // Arch specific properties need to be added to an os and arch specific
1506 // section prefixed with <os>_.
1507 archOsPrefix = osType.Name + "_"
1508 }
1509
1510 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001511 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001512
1513 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1514 // os) specific properties.
1515 //
1516 // The archInfos list will be empty if the os contains variants for the common
1517 // architecture.
1518 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001519 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001520 }
1521}
1522
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001523func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1524 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001525 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001526}
1527
1528var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1529
Paul Duffin4b8b7932020-05-06 12:35:38 +01001530func (osInfo *osTypeSpecificInfo) String() string {
1531 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1532}
1533
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001534type archTypeSpecificInfo struct {
1535 baseInfo
1536
1537 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001538 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001539
1540 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001541}
1542
Paul Duffin4b8b7932020-05-06 12:35:38 +01001543var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1544
Paul Duffinfc8dd232020-03-17 12:51:37 +00001545// Create a new archTypeSpecificInfo for the specified arch type and its properties
1546// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001547func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001548
Paul Duffinfc8dd232020-03-17 12:51:37 +00001549 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001550 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001551
1552 // Create the properties into which the arch type specific properties will be
1553 // added.
1554 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001555
1556 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001557 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001558 } else {
1559 // There is more than one variant for this arch type which must be differentiated
1560 // by link type.
1561 for _, linkVariant := range archVariants {
1562 linkType := getLinkType(linkVariant)
1563 if linkType == "" {
1564 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1565 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001566 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001567
1568 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1569 }
1570 }
1571 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001572
1573 return archInfo
1574}
1575
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001576// Get the link type of the variant
1577//
1578// If the variant is not differentiated by link type then it returns "",
1579// otherwise it returns one of "static" or "shared".
1580func getLinkType(variant android.Module) string {
1581 linkType := ""
1582 if linkable, ok := variant.(cc.LinkableInterface); ok {
1583 if linkable.Shared() && linkable.Static() {
1584 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1585 } else if linkable.Shared() {
1586 linkType = "shared"
1587 } else if linkable.Static() {
1588 linkType = "static"
1589 } else {
1590 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1591 }
1592 }
1593 return linkType
1594}
1595
1596// Optimize the properties by extracting common properties from link type specific
1597// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001598func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001599 if len(archInfo.linkInfos) == 0 {
1600 return
1601 }
1602
Paul Duffin4b8b7932020-05-06 12:35:38 +01001603 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001604}
1605
Paul Duffinfc8dd232020-03-17 12:51:37 +00001606// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001607func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001608 archTypeName := archInfo.archType.Name
1609 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001610 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1611 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1612 archTypePropertySet.AddProperty("enabled", true)
1613 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001614 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001615
1616 for _, linkInfo := range archInfo.linkInfos {
Paul Duffinf68f85a2021-09-09 16:11:42 +01001617 linkInfo.addToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001618 }
1619}
1620
Paul Duffin4b8b7932020-05-06 12:35:38 +01001621func (archInfo *archTypeSpecificInfo) String() string {
1622 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1623}
1624
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001625type linkTypeSpecificInfo struct {
1626 baseInfo
1627
1628 linkType string
1629}
1630
Paul Duffin4b8b7932020-05-06 12:35:38 +01001631var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1632
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001633// Create a new linkTypeSpecificInfo for the specified link type and its properties
1634// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001635func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001636 linkInfo := &linkTypeSpecificInfo{
1637 baseInfo: baseInfo{
1638 // Create the properties into which the link type specific properties will be
1639 // added.
1640 Properties: variantPropertiesFactory(),
1641 },
1642 linkType: linkType,
1643 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001644 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001645 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001646}
1647
Paul Duffinf68f85a2021-09-09 16:11:42 +01001648func (l *linkTypeSpecificInfo) addToPropertySet(ctx *memberContext, propertySet android.BpPropertySet) {
1649 linkPropertySet := propertySet.AddPropertySet(l.linkType)
1650 addSdkMemberPropertiesToSet(ctx, l.Properties, linkPropertySet)
1651}
1652
Paul Duffin4b8b7932020-05-06 12:35:38 +01001653func (l *linkTypeSpecificInfo) String() string {
1654 return fmt.Sprintf("LinkType{%s}", l.linkType)
1655}
1656
Paul Duffin3a4eb502020-03-19 16:11:18 +00001657type memberContext struct {
1658 sdkMemberContext android.ModuleContext
1659 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001660 memberType android.SdkMemberType
1661 name string
Paul Duffind19f8942021-07-14 12:08:37 +01001662
1663 // The set of traits required of this member.
1664 requiredTraits android.SdkMemberTraitSet
Paul Duffin3a4eb502020-03-19 16:11:18 +00001665}
1666
1667func (m *memberContext) SdkModuleContext() android.ModuleContext {
1668 return m.sdkMemberContext
1669}
1670
1671func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1672 return m.builder
1673}
1674
Paul Duffina551a1c2020-03-17 21:04:24 +00001675func (m *memberContext) MemberType() android.SdkMemberType {
1676 return m.memberType
1677}
1678
1679func (m *memberContext) Name() string {
1680 return m.name
1681}
1682
Paul Duffind19f8942021-07-14 12:08:37 +01001683func (m *memberContext) RequiresTrait(trait android.SdkMemberTrait) bool {
1684 return m.requiredTraits.Contains(trait)
1685}
1686
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001687func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001688
1689 memberType := member.memberType
1690
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001691 // Do not add the prefer property if the member snapshot module is a source module type.
1692 if !memberType.UsesSourceModuleTypeInSnapshot() {
Mathew Inwood7e9ddbe2021-07-07 12:47:51 +00001693 // Set the prefer based on the environment variable. This is a temporary work around to allow a
1694 // snapshot to be created that sets prefer: true.
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001695 // TODO(b/174997203): Remove once the ability to select the modules to prefer can be done
1696 // dynamically at build time not at snapshot generation time.
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001697 config := ctx.sdkMemberContext.Config()
1698 prefer := config.IsEnvTrue("SOONG_SDK_SNAPSHOT_PREFER")
Paul Duffin83ad9562021-05-10 23:49:04 +01001699
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001700 // Set prefer. Setting this to false is not strictly required as that is the default but it does
1701 // provide a convenient hook to post-process the generated Android.bp file, e.g. in tests to
1702 // check the behavior when a prebuilt is preferred. It also makes it explicit what the default
1703 // behavior is for the module.
1704 bpModule.insertAfter("name", "prefer", prefer)
Paul Duffinfb9a7f92021-07-06 17:18:42 +01001705
1706 configVar := config.Getenv("SOONG_SDK_SNAPSHOT_USE_SOURCE_CONFIG_VAR")
1707 if configVar != "" {
1708 parts := strings.Split(configVar, ":")
1709 cfp := android.ConfigVarProperties{
1710 Config_namespace: proptools.StringPtr(parts[0]),
1711 Var_name: proptools.StringPtr(parts[1]),
1712 }
1713 bpModule.insertAfter("prefer", "use_source_config_var", cfp)
1714 }
Paul Duffin0d4ed0a2021-05-10 23:58:40 +01001715 }
Paul Duffin83ad9562021-05-10 23:49:04 +01001716
Paul Duffina04c1072020-03-02 10:16:35 +00001717 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001718 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001719 variants := member.Variants()
1720 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001721 osType := variant.Target().Os
1722 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001723 }
1724
Paul Duffina04c1072020-03-02 10:16:35 +00001725 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001726 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001727 properties := memberType.CreateVariantPropertiesStruct()
1728 base := properties.Base()
1729 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001730 return properties
1731 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001732
Paul Duffina04c1072020-03-02 10:16:35 +00001733 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001734
Paul Duffina04c1072020-03-02 10:16:35 +00001735 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001736 commonProperties := variantPropertiesFactory()
1737 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001738
Paul Duffinc097e362020-03-10 22:50:03 +00001739 // Create common value extractor that can be used to optimize the properties.
1740 commonValueExtractor := newCommonValueExtractor(commonProperties)
1741
Paul Duffina04c1072020-03-02 10:16:35 +00001742 // The list of property structures which are os type specific but common across
1743 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001744 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001745
1746 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001747 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001748 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001749 // Add the os specific properties to a list of os type specific yet architecture
1750 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001751 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001752
Paul Duffin00e46802020-03-12 20:40:35 +00001753 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001754 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001755 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001756
Paul Duffina04c1072020-03-02 10:16:35 +00001757 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001758 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001759
Paul Duffina04c1072020-03-02 10:16:35 +00001760 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001761 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001762
Paul Duffina04c1072020-03-02 10:16:35 +00001763 // Create a target property set into which target specific properties can be
1764 // added.
1765 targetPropertySet := bpModule.AddPropertySet("target")
1766
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001767 // If the member is host OS dependent and has host_supported then disable by
1768 // default and enable each host OS variant explicitly. This avoids problems
1769 // with implicitly enabled OS variants when the snapshot is used, which might
1770 // be different from this run (e.g. different build OS).
1771 if ctx.memberType.IsHostOsDependent() {
1772 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1773 if hostSupported {
1774 hostPropertySet := targetPropertySet.AddPropertySet("host")
1775 hostPropertySet.AddProperty("enabled", false)
1776 }
1777 }
1778
Paul Duffina04c1072020-03-02 10:16:35 +00001779 // Iterate over the os types in a fixed order.
1780 for _, osType := range s.getPossibleOsTypes() {
1781 osInfo := osTypeToInfo[osType]
1782 if osInfo == nil {
1783 continue
1784 }
1785
Paul Duffin3a4eb502020-03-19 16:11:18 +00001786 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001787 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001788}
1789
Paul Duffina04c1072020-03-02 10:16:35 +00001790// Compute the list of possible os types that this sdk could support.
1791func (s *sdk) getPossibleOsTypes() []android.OsType {
1792 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001793 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001794 if s.DeviceSupported() {
Colin Crosscb0ac952021-07-20 13:17:15 -07001795 if osType.Class == android.Device {
Paul Duffina04c1072020-03-02 10:16:35 +00001796 osTypes = append(osTypes, osType)
1797 }
1798 }
1799 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001800 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001801 osTypes = append(osTypes, osType)
1802 }
1803 }
1804 }
1805 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1806 return osTypes
1807}
1808
Paul Duffinb28369a2020-05-04 15:39:59 +01001809// Given a set of properties (struct value), return the value of the field within that
1810// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001811type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1812
Paul Duffinc459f892020-04-30 18:08:29 +01001813// Checks the metadata to determine whether the property should be ignored for the
1814// purposes of common value extraction or not.
1815type extractorMetadataPredicate func(metadata propertiesContainer) bool
1816
1817// Indicates whether optimizable properties are provided by a host variant or
1818// not.
1819type isHostVariant interface {
1820 isHostVariant() bool
1821}
1822
Paul Duffinb28369a2020-05-04 15:39:59 +01001823// A property that can be optimized by the commonValueExtractor.
1824type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001825 // The name of the field for this property. It is a "."-separated path for
1826 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001827 name string
1828
Paul Duffinc459f892020-04-30 18:08:29 +01001829 // Filter that can use metadata associated with the properties being optimized
1830 // to determine whether the field should be ignored during common value
1831 // optimization.
1832 filter extractorMetadataPredicate
1833
Paul Duffinb28369a2020-05-04 15:39:59 +01001834 // Retrieves the value on which common value optimization will be performed.
1835 getter fieldAccessorFunc
1836
1837 // The empty value for the field.
1838 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001839
1840 // True if the property can support arch variants false otherwise.
1841 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001842}
1843
Paul Duffin4b8b7932020-05-06 12:35:38 +01001844func (p extractorProperty) String() string {
1845 return p.name
1846}
1847
Paul Duffinc097e362020-03-10 22:50:03 +00001848// Supports extracting common values from a number of instances of a properties
1849// structure into a separate common set of properties.
1850type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001851 // The properties that the extractor can optimize.
1852 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001853}
1854
1855// Create a new common value extractor for the structure type for the supplied
1856// properties struct.
1857//
1858// The returned extractor can be used on any properties structure of the same type
1859// as the supplied set of properties.
1860func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1861 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1862 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001863 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001864 return extractor
1865}
1866
1867// Gather the fields from the supplied structure type from which common values will
1868// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001869//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001870// This is recursive function. If it encounters a struct then it will recurse
1871// into it, passing in the accessor for the field and the struct name as prefix
1872// for the nested fields. That will then be used in the accessors for the fields
1873// in the embedded struct.
1874func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001875 for f := 0; f < structType.NumField(); f++ {
1876 field := structType.Field(f)
1877 if field.PkgPath != "" {
1878 // Ignore unexported fields.
1879 continue
1880 }
1881
Paul Duffinb07fa512020-03-10 22:17:04 +00001882 // Ignore fields whose value should be kept.
1883 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001884 continue
1885 }
1886
Paul Duffinc459f892020-04-30 18:08:29 +01001887 var filter extractorMetadataPredicate
1888
1889 // Add a filter
1890 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1891 filter = func(metadata propertiesContainer) bool {
1892 if m, ok := metadata.(isHostVariant); ok {
1893 if m.isHostVariant() {
1894 return false
1895 }
1896 }
1897 return true
1898 }
1899 }
1900
Paul Duffinc097e362020-03-10 22:50:03 +00001901 // Save a copy of the field index for use in the function.
1902 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001903
Martin Stjernholmb0249572020-09-15 02:32:35 +01001904 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001905
Paul Duffinc097e362020-03-10 22:50:03 +00001906 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001907 if containingStructAccessor != nil {
1908 // This is an embedded structure so first access the field for the embedded
1909 // structure.
1910 value = containingStructAccessor(value)
1911 }
1912
Paul Duffinc097e362020-03-10 22:50:03 +00001913 // Skip through interface and pointer values to find the structure.
1914 value = getStructValue(value)
1915
Paul Duffin4b8b7932020-05-06 12:35:38 +01001916 defer func() {
1917 if r := recover(); r != nil {
1918 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1919 }
1920 }()
1921
Paul Duffinc097e362020-03-10 22:50:03 +00001922 // Return the field.
1923 return value.Field(fieldIndex)
1924 }
1925
Martin Stjernholmb0249572020-09-15 02:32:35 +01001926 if field.Type.Kind() == reflect.Struct {
1927 // Gather fields from the nested or embedded structure.
1928 var subNamePrefix string
1929 if field.Anonymous {
1930 subNamePrefix = namePrefix
1931 } else {
1932 subNamePrefix = name + "."
1933 }
1934 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001935 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001936 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001937 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001938 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001939 fieldGetter,
1940 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001941 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001942 }
1943 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001944 }
Paul Duffinc097e362020-03-10 22:50:03 +00001945 }
1946}
1947
1948func getStructValue(value reflect.Value) reflect.Value {
1949foundStruct:
1950 for {
1951 kind := value.Kind()
1952 switch kind {
1953 case reflect.Interface, reflect.Ptr:
1954 value = value.Elem()
1955 case reflect.Struct:
1956 break foundStruct
1957 default:
1958 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1959 }
1960 }
1961 return value
1962}
1963
Paul Duffinf34f6d82020-04-30 15:48:31 +01001964// A container of properties to be optimized.
1965//
1966// Allows additional information to be associated with the properties, e.g. for
1967// filtering.
1968type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001969 fmt.Stringer
1970
Paul Duffinf34f6d82020-04-30 15:48:31 +01001971 // Get the properties that need optimizing.
1972 optimizableProperties() interface{}
1973}
1974
Paul Duffin2d1bb892021-04-24 11:32:59 +01001975// A wrapper for sdk variant related properties to allow them to be optimized.
1976type sdkVariantPropertiesContainer struct {
1977 sdkVariant *sdk
1978 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01001979}
1980
Paul Duffin2d1bb892021-04-24 11:32:59 +01001981func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
1982 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01001983}
1984
Paul Duffin2d1bb892021-04-24 11:32:59 +01001985func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001986 return c.sdkVariant.String()
1987}
1988
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001989// Extract common properties from a slice of property structures of the same type.
1990//
1991// All the property structures must be of the same type.
1992// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001993// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001994//
1995// Iterates over each exported field (capitalized name) and checks to see whether they
1996// have the same value (using DeepEquals) across all the input properties. If it does not then no
1997// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001998// and the field in each of the input properties structure is set to its default value. Nested
1999// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01002000func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002001 commonPropertiesValue := reflect.ValueOf(commonProperties)
2002 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002003
Paul Duffinf34f6d82020-04-30 15:48:31 +01002004 sliceValue := reflect.ValueOf(inputPropertiesSlice)
2005
Paul Duffinb28369a2020-05-04 15:39:59 +01002006 for _, property := range e.properties {
2007 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01002008 filter := property.filter
2009 if filter == nil {
2010 filter = func(metadata propertiesContainer) bool {
2011 return true
2012 }
2013 }
Paul Duffinb28369a2020-05-04 15:39:59 +01002014
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002015 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01002016 // is nil on entry to the loop and if it is nil on exit then there is no common value or
2017 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002018 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002019
Paul Duffin864e1b42020-05-06 10:23:19 +01002020 // Assume that all the values will be the same.
2021 //
2022 // While similar to this is not quite the same as commonValue == nil. If all the values
2023 // have been filtered out then this will be false but commonValue == nil will be true.
2024 valuesDiffer := false
2025
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002026 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002027 container := sliceValue.Index(i).Interface().(propertiesContainer)
2028 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002029 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002030
Paul Duffinc459f892020-04-30 18:08:29 +01002031 if !filter(container) {
2032 expectedValue := property.emptyValue.Interface()
2033 actualValue := fieldValue.Interface()
2034 if !reflect.DeepEqual(expectedValue, actualValue) {
2035 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
2036 }
2037 continue
2038 }
2039
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002040 if commonValue == nil {
2041 // Use the first value as the commonProperties value.
2042 commonValue = &fieldValue
2043 } else {
2044 // If the value does not match the current common value then there is
2045 // no value in common so break out.
2046 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
2047 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01002048 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002049 break
2050 }
2051 }
2052 }
2053
Paul Duffin864e1b42020-05-06 10:23:19 +01002054 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002055 // and set the input struct's field to the empty value.
2056 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01002057 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00002058 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002059 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01002060 container := sliceValue.Index(i).Interface().(propertiesContainer)
2061 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00002062 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002063 fieldValue.Set(emptyValue)
2064 }
2065 }
Paul Duffin864e1b42020-05-06 10:23:19 +01002066
2067 if valuesDiffer && !property.archVariant {
2068 // The values differ but the property does not support arch variants so it
2069 // is an error.
2070 var details strings.Builder
2071 for i := 0; i < sliceValue.Len(); i++ {
2072 container := sliceValue.Index(i).Interface().(propertiesContainer)
2073 itemValue := reflect.ValueOf(container.optimizableProperties())
2074 fieldValue := fieldGetter(itemValue)
2075
2076 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
2077 }
2078
2079 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
2080 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002081 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01002082
2083 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00002084}