blob: 248cf5dbfc1cb78daf6252f85ce9066977fb0126 [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 Cross440e0d02020-06-11 11:32:11 -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
32var pctx = android.NewPackageContext("android/soong/sdk")
33
Paul Duffin375058f2019-11-29 20:17:53 +000034var (
35 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
36 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000037 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000038 CommandDeps: []string{
39 "${config.Zip2ZipCmd}",
40 },
41 },
42 "destdir")
43
44 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
45 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -070046 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +000047 CommandDeps: []string{
48 "${config.SoongZipCmd}",
49 },
50 Rspfile: "$out.rsp",
51 RspfileContent: "$in",
52 },
53 "basedir")
54
55 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
56 blueprint.RuleParams{
57 Command: `${config.MergeZipsCmd} $out $in`,
58 CommandDeps: []string{
59 "${config.MergeZipsCmd}",
60 },
61 })
62)
63
Paul Duffinb645ec82019-11-27 17:43:54 +000064type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090065 content strings.Builder
66 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090067}
68
Paul Duffinb645ec82019-11-27 17:43:54 +000069// generatedFile abstracts operations for writing contents into a file and emit a build rule
70// for the file.
71type generatedFile struct {
72 generatedContents
73 path android.OutputPath
74}
75
Jiyong Park232e7852019-11-04 12:23:40 +090076func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +090077 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +000078 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +090079 }
80}
81
Paul Duffinb645ec82019-11-27 17:43:54 +000082func (gc *generatedContents) Indent() {
83 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +090084}
85
Paul Duffinb645ec82019-11-27 17:43:54 +000086func (gc *generatedContents) Dedent() {
87 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +090088}
89
Paul Duffinb645ec82019-11-27 17:43:54 +000090func (gc *generatedContents) Printfln(format string, args ...interface{}) {
Paul Duffin11108272020-05-11 22:59:25 +010091 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format+"\n", args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +090092}
93
94func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -080095 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +010096
97 content := gf.content.String()
98
99 // ninja consumes newline characters in rspfile_content. Prevent it by
100 // escaping the backslash in the newline character. The extra backslash
101 // is removed when the rspfile is written to the actual script file
102 content = strings.ReplaceAll(content, "\n", "\\n")
103
Jiyong Park9b409bc2019-10-11 14:59:13 +0900104 rb.Command().
105 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100106 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100107 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900108 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
109 rb.Command().
110 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800111 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900112}
113
Paul Duffin13879572019-11-28 14:31:38 +0000114// Collect all the members.
115//
Paul Duffincc3132e2021-04-24 01:10:30 +0100116// Updates the sdk module with a list of sdkMemberVariantDeps and details as to which multilibs
117// (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000118func (s *sdk) collectMembers(ctx android.ModuleContext) {
119 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000120 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
121 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000122 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
123 memberType := memberTag.SdkMemberType()
Jiyong Park9b409bc2019-10-11 14:59:13 +0900124
Paul Duffin13879572019-11-28 14:31:38 +0000125 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000126 if !memberType.IsInstance(child) {
127 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900128 }
Paul Duffin13879572019-11-28 14:31:38 +0000129
Paul Duffin6a7e9532020-03-20 17:50:07 +0000130 // Keep track of which multilib variants are used by the sdk.
131 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
132
Paul Duffin21827262021-04-24 12:16:36 +0100133 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{memberType, child.(android.SdkAware)})
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000134
135 // If the member type supports transitive sdk members then recurse down into
136 // its dependencies, otherwise exit traversal.
137 return memberType.HasTransitiveSdkMembers()
Jiyong Park73c54ee2019-10-22 20:31:18 +0900138 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000139
140 return false
Paul Duffin13879572019-11-28 14:31:38 +0000141 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000142}
143
Paul Duffincc3132e2021-04-24 01:10:30 +0100144// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
145// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000146//
Paul Duffincc3132e2021-04-24 01:10:30 +0100147// The sdkMember instances are then grouped into slices by member type. Within each such slice the
148// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000149//
Paul Duffincc3132e2021-04-24 01:10:30 +0100150// Finally, the member type slices are concatenated together to form a single slice. The order in
151// which they are concatenated is the order in which the member types were registered in the
152// android.SdkMemberTypesRegistry.
153func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000154 byType := make(map[android.SdkMemberType][]*sdkMember)
155 byName := make(map[string]*sdkMember)
156
Paul Duffin21827262021-04-24 12:16:36 +0100157 for _, memberVariantDep := range memberVariantDeps {
158 memberType := memberVariantDep.memberType
159 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000160
161 name := ctx.OtherModuleName(variant)
162 member := byName[name]
163 if member == nil {
164 member = &sdkMember{memberType: memberType, name: name}
165 byName[name] = member
166 byType[memberType] = append(byType[memberType], member)
167 }
168
Paul Duffin1356d8c2020-02-25 19:26:33 +0000169 // Only append new variants to the list. This is needed because a member can be both
170 // exported by the sdk and also be a transitive sdk member.
171 member.variants = appendUniqueVariants(member.variants, variant)
172 }
173
Paul Duffin13879572019-11-28 14:31:38 +0000174 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000175 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000176 membersOfType := byType[memberListProperty.memberType]
177 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900178 }
179
Paul Duffin6a7e9532020-03-20 17:50:07 +0000180 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900181}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900182
Paul Duffin72910952020-01-20 18:16:30 +0000183func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
184 for _, v := range variants {
185 if v == newVariant {
186 return variants
187 }
188 }
189 return append(variants, newVariant)
190}
191
Jiyong Park73c54ee2019-10-22 20:31:18 +0900192// SDK directory structure
193// <sdk_root>/
194// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
195// <api_ver>/ : below this directory are all auto-generated
196// Android.bp : definition of 'sdk_snapshot' module is here
197// aidl/
198// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
199// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900200// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900201// include/
202// bionic/libc/include/stdlib.h : an exported header file
203// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900204// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900205// <arch>/include/ : arch-specific exported headers
206// <arch>/include_gen/ : arch-specific generated headers
207// <arch>/lib/
208// libFoo.so : a stub library
209
Jiyong Park232e7852019-11-04 12:23:40 +0900210// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900211// This isn't visible to users, so could be changed in future.
212func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
213 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
214}
215
Jiyong Park232e7852019-11-04 12:23:40 +0900216// buildSnapshot is the main function in this source file. It creates rules to copy
217// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000218func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
219
Paul Duffin13f02712020-03-06 12:30:43 +0000220 allMembersByName := make(map[string]struct{})
221 exportedMembersByName := make(map[string]struct{})
Paul Duffin21827262021-04-24 12:16:36 +0100222 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000223 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100224 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffin865171e2020-03-02 18:38:15 +0000225
Paul Duffin13f02712020-03-06 12:30:43 +0000226 // Record the names of all the members, both explicitly specified and implicitly
227 // included.
Paul Duffin21827262021-04-24 12:16:36 +0100228 for _, memberVariantDep := range sdkVariant.memberVariantDeps {
229 allMembersByName[memberVariantDep.variant.Name()] = struct{}{}
Paul Duffin13f02712020-03-06 12:30:43 +0000230 }
231
Paul Duffin865171e2020-03-02 18:38:15 +0000232 // Merge the exported member sets from all sdk variants.
233 for key, _ := range sdkVariant.getExportedMembers() {
Paul Duffin13f02712020-03-06 12:30:43 +0000234 exportedMembersByName[key] = struct{}{}
Paul Duffin865171e2020-03-02 18:38:15 +0000235 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000236 }
237
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000238 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900239
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000240 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000241
242 bpFile := &bpFile{
243 modules: make(map[string]*bpModule),
244 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000245
246 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000247 ctx: ctx,
248 sdk: s,
249 version: "current",
250 snapshotDir: snapshotDir.OutputPath,
251 copies: make(map[string]string),
252 filesToZip: []android.Path{bp.path},
253 bpFile: bpFile,
254 prebuiltModules: make(map[string]*bpModule),
255 allMembersByName: allMembersByName,
256 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900257 }
Paul Duffinac37c502019-11-26 18:02:20 +0000258 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900259
Paul Duffincc3132e2021-04-24 01:10:30 +0100260 // Create the prebuilt modules for each of the member modules.
261 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000262 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000263 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000264
Paul Duffina551a1c2020-03-17 21:04:24 +0000265 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000266
267 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100268 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900269 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900270
Paul Duffine6c0d842020-01-15 14:08:51 +0000271 // Create a transformer that will transform an unversioned module into a versioned module.
272 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
273
Paul Duffin72910952020-01-20 18:16:30 +0000274 // Create a transformer that will transform an unversioned module by replacing any references
275 // to internal members with a unique module name and setting prefer: false.
276 unversionedTransformer := unversionedTransformation{builder: builder}
277
Paul Duffinb645ec82019-11-27 17:43:54 +0000278 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000279 // Prune any empty property sets.
280 unversioned = unversioned.transform(pruneEmptySetTransformer{})
281
Paul Duffinb645ec82019-11-27 17:43:54 +0000282 // Copy the unversioned module so it can be modified to make it versioned.
Paul Duffincc72e982020-01-14 15:53:11 +0000283 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000284
285 // Transform the unversioned module into a versioned one.
286 versioned.transform(unversionedToVersionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000287 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000288
Paul Duffin72910952020-01-20 18:16:30 +0000289 // Transform the unversioned module to make it suitable for use in the snapshot.
290 unversioned.transform(unversionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000291 bpFile.AddModule(unversioned)
292 }
293
Paul Duffin26197a62021-04-24 00:34:10 +0100294 // Add the sdk/module_exports_snapshot module to the bp file.
Paul Duffin21827262021-04-24 12:16:36 +0100295 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
Paul Duffin26197a62021-04-24 00:34:10 +0100296
297 // generate Android.bp
298 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
299 generateBpContents(&bp.generatedContents, bpFile)
300
301 contents := bp.content.String()
302 syntaxCheckSnapshotBpFile(ctx, contents)
303
304 bp.build(pctx, ctx, nil)
305
306 filesToZip := builder.filesToZip
307
308 // zip them all
309 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
310 outputDesc := "Building snapshot for " + ctx.ModuleName()
311
312 // If there are no zips to merge then generate the output zip directly.
313 // Otherwise, generate an intermediate zip file into which other zips can be
314 // merged.
315 var zipFile android.OutputPath
316 var desc string
317 if len(builder.zipsToMerge) == 0 {
318 zipFile = outputZipFile
319 desc = outputDesc
320 } else {
321 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
322 desc = "Building intermediate snapshot for " + ctx.ModuleName()
323 }
324
325 ctx.Build(pctx, android.BuildParams{
326 Description: desc,
327 Rule: zipFiles,
328 Inputs: filesToZip,
329 Output: zipFile,
330 Args: map[string]string{
331 "basedir": builder.snapshotDir.String(),
332 },
333 })
334
335 if len(builder.zipsToMerge) != 0 {
336 ctx.Build(pctx, android.BuildParams{
337 Description: outputDesc,
338 Rule: mergeZips,
339 Input: zipFile,
340 Inputs: builder.zipsToMerge,
341 Output: outputZipFile,
342 })
343 }
344
345 return outputZipFile
346}
347
348// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100349func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100350 bpFile := builder.bpFile
351
Paul Duffinb645ec82019-11-27 17:43:54 +0000352 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000353 var snapshotModuleType string
354 if s.properties.Module_exports {
355 snapshotModuleType = "module_exports_snapshot"
356 } else {
357 snapshotModuleType = "sdk_snapshot"
358 }
359 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000360 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000361
362 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100363 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000364 if len(visibility) != 0 {
365 snapshotModule.AddProperty("visibility", visibility)
366 }
367
Paul Duffin865171e2020-03-02 18:38:15 +0000368 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000369
Paul Duffinf34f6d82020-04-30 15:48:31 +0100370 var dynamicMemberPropertiesContainers []propertiesContainer
Paul Duffincc3132e2021-04-24 01:10:30 +0100371 osTypeToMemberProperties := make(map[android.OsType]interface{})
Paul Duffin865171e2020-03-02 18:38:15 +0000372 for _, sdkVariant := range sdkVariants {
373 properties := sdkVariant.dynamicMemberTypeListProperties
Paul Duffincc3132e2021-04-24 01:10:30 +0100374 osTypeToMemberProperties[sdkVariant.Target().Os] = properties
Paul Duffin4b8b7932020-05-06 12:35:38 +0100375 dynamicMemberPropertiesContainers = append(dynamicMemberPropertiesContainers, &dynamicMemberPropertiesContainer{sdkVariant, properties})
Paul Duffin865171e2020-03-02 18:38:15 +0000376 }
377
378 // Extract the common lists of members into a separate struct.
379 commonDynamicMemberProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffinc097e362020-03-10 22:50:03 +0000380 extractor := newCommonValueExtractor(commonDynamicMemberProperties)
Paul Duffin4b8b7932020-05-06 12:35:38 +0100381 extractCommonProperties(ctx, extractor, commonDynamicMemberProperties, dynamicMemberPropertiesContainers)
Paul Duffin865171e2020-03-02 18:38:15 +0000382
383 // Add properties common to all os types.
384 s.addMemberPropertiesToPropertySet(builder, snapshotModule, commonDynamicMemberProperties)
385
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100386 // Optimize other per-variant properties, besides the dynamic member lists.
387 type variantProperties struct {
388 Compile_multilib string `android:"arch_variant"`
389 }
390 var variantPropertiesContainers []propertiesContainer
Paul Duffincc3132e2021-04-24 01:10:30 +0100391 osTypeToVariantProperties := make(map[android.OsType]*variantProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100392 for _, sdkVariant := range sdkVariants {
393 props := &variantProperties{
394 Compile_multilib: sdkVariant.multilibUsages.String(),
395 }
396 variantPropertiesContainers = append(variantPropertiesContainers, &dynamicMemberPropertiesContainer{sdkVariant, props})
Paul Duffincc3132e2021-04-24 01:10:30 +0100397 osTypeToVariantProperties[sdkVariant.Target().Os] = props
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100398 }
399 commonVariantProperties := variantProperties{}
400 extractor = newCommonValueExtractor(commonVariantProperties)
401 extractCommonProperties(ctx, extractor, &commonVariantProperties, variantPropertiesContainers)
402 if commonVariantProperties.Compile_multilib != "" && commonVariantProperties.Compile_multilib != "both" {
403 // Compile_multilib defaults to both so only needs to be set when it's
404 // specified and not both.
405 snapshotModule.AddProperty("compile_multilib", commonVariantProperties.Compile_multilib)
406 }
407
Paul Duffin6a7e9532020-03-20 17:50:07 +0000408 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100409
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100410 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000411 for _, osType := range s.getPossibleOsTypes() {
Paul Duffincc3132e2021-04-24 01:10:30 +0100412 if properties, ok := osTypeToMemberProperties[osType]; ok {
413 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000414
Paul Duffincc3132e2021-04-24 01:10:30 +0100415 variantProps := osTypeToVariantProperties[osType]
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100416 if variantProps.Compile_multilib != "" && variantProps.Compile_multilib != "both" {
417 osPropertySet.AddProperty("compile_multilib", variantProps.Compile_multilib)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000418 }
419
Paul Duffincc3132e2021-04-24 01:10:30 +0100420 s.addMemberPropertiesToPropertySet(builder, osPropertySet, properties)
Paul Duffin13879572019-11-28 14:31:38 +0000421 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000422 }
Paul Duffin865171e2020-03-02 18:38:15 +0000423
Jiyong Park8fe14e62020-10-19 22:47:34 +0900424 // If host is supported and any member is host OS dependent then disable host
425 // by default, so that we can enable each host OS variant explicitly. This
426 // avoids problems with implicitly enabled OS variants when the snapshot is
427 // used, which might be different from this run (e.g. different build OS).
428 if s.HostSupported() {
429 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100430 for _, memberVariantDep := range memberVariantDeps {
431 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
432 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900433 if !android.InList(targetString, supportedHostTargets) {
434 supportedHostTargets = append(supportedHostTargets, targetString)
435 }
436 }
437 }
438 if len(supportedHostTargets) > 0 {
439 hostPropertySet := targetPropertySet.AddPropertySet("host")
440 hostPropertySet.AddProperty("enabled", false)
441 }
442 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
443 for _, hostTarget := range supportedHostTargets {
444 propertySet := targetPropertySet.AddPropertySet(hostTarget)
445 propertySet.AddProperty("enabled", true)
446 }
447 }
448
Paul Duffin865171e2020-03-02 18:38:15 +0000449 // Prune any empty property sets.
450 snapshotModule.transform(pruneEmptySetTransformer{})
451
Paul Duffinb645ec82019-11-27 17:43:54 +0000452 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900453}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000454
Paul Duffinf88d8e02020-05-07 20:21:34 +0100455// Check the syntax of the generated Android.bp file contents and if they are
456// invalid then log an error with the contents (tagged with line numbers) and the
457// errors that were found so that it is easy to see where the problem lies.
458func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
459 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
460 if len(errs) != 0 {
461 message := &strings.Builder{}
462 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
463
464Generated Android.bp contents
465========================================================================
466`)
467 for i, line := range strings.Split(contents, "\n") {
468 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
469 }
470
471 _, _ = fmt.Fprint(message, `
472========================================================================
473
474Errors found:
475`)
476
477 for _, err := range errs {
478 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
479 }
480
481 ctx.ModuleErrorf("%s", message.String())
482 }
483}
484
Paul Duffin4b8b7932020-05-06 12:35:38 +0100485func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
486 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
487 if err != nil {
488 ctx.ModuleErrorf("error extracting common properties: %s", err)
489 }
490}
491
Paul Duffin865171e2020-03-02 18:38:15 +0000492func (s *sdk) addMemberPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, dynamicMemberTypeListProperties interface{}) {
493 for _, memberListProperty := range s.memberListProperties() {
494 names := memberListProperty.getter(dynamicMemberTypeListProperties)
495 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000496 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000497 }
498 }
499}
500
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000501type propertyTag struct {
502 name string
503}
504
Paul Duffin0cb37b92020-03-04 14:52:46 +0000505// A BpPropertyTag to add to a property that contains references to other sdk members.
506//
507// This will cause the references to be rewritten to a versioned reference in the version
508// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000509var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000510var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000511
Paul Duffin0cb37b92020-03-04 14:52:46 +0000512// A BpPropertyTag that indicates the property should only be present in the versioned
513// module.
514//
515// This will cause the property to be removed from the unversioned instance of a
516// snapshot module.
517var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
518
Paul Duffine6c0d842020-01-15 14:08:51 +0000519type unversionedToVersionedTransformation struct {
520 identityTransformation
521 builder *snapshotBuilder
522}
523
Paul Duffine6c0d842020-01-15 14:08:51 +0000524func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
525 // Use a versioned name for the module but remember the original name for the
526 // snapshot.
527 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000528 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000529 module.insertAfter("name", "sdk_member_name", name)
530 return module
531}
532
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000533func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000534 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
535 required := tag == requiredSdkMemberReferencePropertyTag
536 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000537 } else {
538 return value, tag
539 }
540}
541
Paul Duffin72910952020-01-20 18:16:30 +0000542type unversionedTransformation struct {
543 identityTransformation
544 builder *snapshotBuilder
545}
546
547func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
548 // If the module is an internal member then use a unique name for it.
549 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000550 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000551
552 // Set prefer: false - this is not strictly required as that is the default.
553 module.insertAfter("name", "prefer", false)
554
555 return module
556}
557
558func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000559 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
560 required := tag == requiredSdkMemberReferencePropertyTag
561 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000562 } else if tag == sdkVersionedOnlyPropertyTag {
563 // The property is not allowed in the unversioned module so remove it.
564 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000565 } else {
566 return value, tag
567 }
568}
569
Paul Duffina78f3a72020-02-21 16:29:35 +0000570type pruneEmptySetTransformer struct {
571 identityTransformation
572}
573
574var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
575
576func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
577 if len(propertySet.properties) == 0 {
578 return nil, nil
579 } else {
580 return propertySet, tag
581 }
582}
583
Paul Duffinb645ec82019-11-27 17:43:54 +0000584func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000585 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
586 return true
587 })
588}
589
590func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffinb645ec82019-11-27 17:43:54 +0000591 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
592 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000593 if moduleFilter(bpModule) {
594 contents.Printfln("")
595 contents.Printfln("%s {", bpModule.moduleType)
596 outputPropertySet(contents, bpModule.bpPropertySet)
597 contents.Printfln("}")
598 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000599 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000600}
601
602func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
603 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000604
605 // Output the properties first, followed by the nested sets. This ensures a
606 // consistent output irrespective of whether property sets are created before
607 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000608 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000609 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000610
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000611 switch v := value.(type) {
612 case []string:
613 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000614 if length > 1 {
615 contents.Printfln("%s: [", name)
616 contents.Indent()
617 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000618 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000619 }
620 contents.Dedent()
621 contents.Printfln("],")
622 } else if length == 0 {
623 contents.Printfln("%s: [],", name)
624 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000625 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000626 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000627
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000628 case bool:
629 contents.Printfln("%s: %t,", name, v)
630
631 case *bpPropertySet:
632 // Do not write property sets in the properties phase.
Paul Duffinb645ec82019-11-27 17:43:54 +0000633
634 default:
635 contents.Printfln("%s: %q,", name, value)
636 }
637 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000638
639 for _, name := range set.order {
640 value := set.getValue(name)
641
642 // Only write property sets in the sets phase.
643 switch v := value.(type) {
644 case *bpPropertySet:
645 contents.Printfln("%s: {", name)
646 outputPropertySet(contents, v)
647 contents.Printfln("},")
648 }
649 }
650
Paul Duffinb645ec82019-11-27 17:43:54 +0000651 contents.Dedent()
652}
653
Paul Duffinac37c502019-11-26 18:02:20 +0000654func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000655 contents := &generatedContents{}
656 generateBpContents(contents, s.builderForTests.bpFile)
657 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000658}
659
Paul Duffind0759072021-02-17 11:23:00 +0000660func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
661 contents := &generatedContents{}
662 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
663 return !strings.Contains(module.properties["name"].(string), "@")
664 })
665 return contents.content.String()
666}
667
668func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
669 contents := &generatedContents{}
670 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
671 return strings.Contains(module.properties["name"].(string), "@")
672 })
673 return contents.content.String()
674}
675
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000676type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000677 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000678 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000679 version string
680 snapshotDir android.OutputPath
681 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000682
683 // Map from destination to source of each copy - used to eliminate duplicates and
684 // detect conflicts.
685 copies map[string]string
686
Paul Duffinb645ec82019-11-27 17:43:54 +0000687 filesToZip android.Paths
688 zipsToMerge android.Paths
689
690 prebuiltModules map[string]*bpModule
691 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000692
693 // The set of all members by name.
694 allMembersByName map[string]struct{}
695
696 // The set of exported members by name.
697 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000698}
699
700func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000701 if existing, ok := s.copies[dest]; ok {
702 if existing != src.String() {
703 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
704 return
705 }
706 } else {
707 path := s.snapshotDir.Join(s.ctx, dest)
708 s.ctx.Build(pctx, android.BuildParams{
709 Rule: android.Cp,
710 Input: src,
711 Output: path,
712 })
713 s.filesToZip = append(s.filesToZip, path)
714
715 s.copies[dest] = src.String()
716 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000717}
718
Paul Duffin91547182019-11-12 19:39:36 +0000719func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
720 ctx := s.ctx
721
722 // Repackage the zip file so that the entries are in the destDir directory.
723 // This will allow the zip file to be merged into the snapshot.
724 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000725
726 ctx.Build(pctx, android.BuildParams{
727 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
728 Rule: repackageZip,
729 Input: zipPath,
730 Output: tmpZipPath,
731 Args: map[string]string{
732 "destdir": destDir,
733 },
734 })
Paul Duffin91547182019-11-12 19:39:36 +0000735
736 // Add the repackaged zip file to the files to merge.
737 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
738}
739
Paul Duffin9d8d6092019-12-05 18:19:29 +0000740func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
741 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000742 if s.prebuiltModules[name] != nil {
743 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
744 }
745
746 m := s.bpFile.newModule(moduleType)
747 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000748
Paul Duffinbefa4b92020-03-04 14:22:45 +0000749 variant := member.Variants()[0]
750
Paul Duffin13f02712020-03-06 12:30:43 +0000751 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000752 // An internal member is only referenced from the sdk snapshot which is in the
753 // same package so can be marked as private.
754 m.AddProperty("visibility", []string{"//visibility:private"})
755 } else {
756 // Extract visibility information from a member variant. All variants have the same
757 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +0100758 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
759
760 // Add any additional visibility rules needed for the prebuilts to reference each other.
761 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
762 if err != nil {
763 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
764 }
765
766 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +0000767 if len(visibility) != 0 {
768 m.AddProperty("visibility", visibility)
769 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000770 }
771
Martin Stjernholm1e041092020-11-03 00:11:09 +0000772 // Where available copy apex_available properties from the member.
773 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
774 apexAvailable := apexAware.ApexAvailable()
775 if len(apexAvailable) == 0 {
776 // //apex_available:platform is the default.
777 apexAvailable = []string{android.AvailableToPlatform}
778 }
779
780 // Add in any baseline apex available settings.
781 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
782
783 // Remove duplicates and sort.
784 apexAvailable = android.FirstUniqueStrings(apexAvailable)
785 sort.Strings(apexAvailable)
786
787 m.AddProperty("apex_available", apexAvailable)
788 }
789
Paul Duffin865171e2020-03-02 18:38:15 +0000790 deviceSupported := false
791 hostSupported := false
792
793 for _, variant := range member.Variants() {
794 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +0900795 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +0000796 hostSupported = true
797 } else if osClass == android.Device {
798 deviceSupported = true
799 }
800 }
801
802 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000803
Paul Duffin0cb37b92020-03-04 14:52:46 +0000804 // Disable installation in the versioned module of those modules that are ever installable.
805 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
806 if installable.EverInstallable() {
807 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
808 }
809 }
810
Paul Duffinb645ec82019-11-27 17:43:54 +0000811 s.prebuiltModules[name] = m
812 s.prebuiltOrder = append(s.prebuiltOrder, m)
813 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000814}
815
Paul Duffin865171e2020-03-02 18:38:15 +0000816func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
817 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000818 bpModule.AddProperty("device_supported", false)
819 }
Paul Duffin865171e2020-03-02 18:38:15 +0000820 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000821 bpModule.AddProperty("host_supported", true)
822 }
823}
824
Paul Duffin13f02712020-03-06 12:30:43 +0000825func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
826 if required {
827 return requiredSdkMemberReferencePropertyTag
828 } else {
829 return optionalSdkMemberReferencePropertyTag
830 }
831}
832
833func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
834 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000835}
836
Paul Duffinb645ec82019-11-27 17:43:54 +0000837// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +0000838func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
839 if _, ok := s.allMembersByName[unversionedName]; !ok {
840 if required {
841 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
842 }
843 return unversionedName
844 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000845 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
846}
Paul Duffinb645ec82019-11-27 17:43:54 +0000847
Paul Duffin13f02712020-03-06 12:30:43 +0000848func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000849 var references []string = nil
850 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000851 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000852 }
853 return references
854}
Paul Duffin13879572019-11-28 14:31:38 +0000855
Paul Duffin72910952020-01-20 18:16:30 +0000856// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +0000857func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
858 if _, ok := s.allMembersByName[unversionedName]; !ok {
859 if required {
860 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
861 }
862 return unversionedName
863 }
864
865 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +0000866 return s.ctx.ModuleName() + "_" + unversionedName
867 } else {
868 return unversionedName
869 }
870}
871
Paul Duffin13f02712020-03-06 12:30:43 +0000872func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +0000873 var references []string = nil
874 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000875 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +0000876 }
877 return references
878}
879
Paul Duffin13f02712020-03-06 12:30:43 +0000880func (s *snapshotBuilder) isInternalMember(memberName string) bool {
881 _, ok := s.exportedMembersByName[memberName]
882 return !ok
883}
884
Martin Stjernholm89238f42020-07-10 00:14:03 +0100885// Add the properties from the given SdkMemberProperties to the blueprint
886// property set. This handles common properties in SdkMemberPropertiesBase and
887// calls the member-specific AddToPropertySet for the rest.
888func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
889 if memberProperties.Base().Compile_multilib != "" {
890 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
891 }
892
893 memberProperties.AddToPropertySet(ctx, targetPropertySet)
894}
895
Paul Duffin21827262021-04-24 12:16:36 +0100896// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
897type sdkMemberVariantDep struct {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000898 memberType android.SdkMemberType
899 variant android.SdkAware
900}
901
Paul Duffin13879572019-11-28 14:31:38 +0000902var _ android.SdkMember = (*sdkMember)(nil)
903
Paul Duffin21827262021-04-24 12:16:36 +0100904// sdkMember groups all the variants of a specific member module together along with the name of the
905// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +0000906type sdkMember struct {
907 memberType android.SdkMemberType
908 name string
909 variants []android.SdkAware
910}
911
912func (m *sdkMember) Name() string {
913 return m.name
914}
915
916func (m *sdkMember) Variants() []android.SdkAware {
917 return m.variants
918}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000919
Paul Duffin9c3760e2020-03-16 19:52:08 +0000920// Track usages of multilib variants.
921type multilibUsage int
922
923const (
924 multilibNone multilibUsage = 0
925 multilib32 multilibUsage = 1
926 multilib64 multilibUsage = 2
927 multilibBoth = multilib32 | multilib64
928)
929
930// Add the multilib that is used in the arch type.
931func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
932 multilib := archType.Multilib
933 switch multilib {
934 case "":
935 return m
936 case "lib32":
937 return m | multilib32
938 case "lib64":
939 return m | multilib64
940 default:
941 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
942 }
943}
944
945func (m multilibUsage) String() string {
946 switch m {
947 case multilibNone:
948 return ""
949 case multilib32:
950 return "32"
951 case multilib64:
952 return "64"
953 case multilibBoth:
954 return "both"
955 default:
956 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
957 m, multilibNone, multilib32, multilib64, multilibBoth))
958 }
959}
960
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000961type baseInfo struct {
962 Properties android.SdkMemberProperties
963}
964
Paul Duffinf34f6d82020-04-30 15:48:31 +0100965func (b *baseInfo) optimizableProperties() interface{} {
966 return b.Properties
967}
968
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000969type osTypeSpecificInfo struct {
970 baseInfo
971
Paul Duffin00e46802020-03-12 20:40:35 +0000972 osType android.OsType
973
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000974 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +0000975 //
976 // Nil if there is one variant whose arch type is common
977 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000978}
979
Paul Duffin4b8b7932020-05-06 12:35:38 +0100980var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
981
Paul Duffinfc8dd232020-03-17 12:51:37 +0000982type variantPropertiesFactoryFunc func() android.SdkMemberProperties
983
Paul Duffin00e46802020-03-12 20:40:35 +0000984// Create a new osTypeSpecificInfo for the specified os type and its properties
985// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000986func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +0000987 osInfo := &osTypeSpecificInfo{
988 osType: osType,
989 }
990
991 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
992 properties := variantPropertiesFactory()
993 properties.Base().Os = osType
994 return properties
995 }
996
997 // Create a structure into which properties common across the architectures in
998 // this os type will be stored.
999 osInfo.Properties = osSpecificVariantPropertiesFactory()
1000
1001 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001002 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001003 var archTypes []android.ArchType
1004 for _, variant := range osTypeVariants {
1005 archType := variant.Target().Arch.ArchType
1006 archTypeName := archType.Name
1007 if _, ok := variantsByArchName[archTypeName]; !ok {
1008 archTypes = append(archTypes, archType)
1009 }
1010
1011 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1012 }
1013
1014 if commonVariants, ok := variantsByArchName["common"]; ok {
1015 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001016 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 +00001017 }
1018
1019 // A common arch type only has one variant and its properties should be treated
1020 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001021 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001022 } else {
1023 // Create an arch specific info for each supported architecture type.
1024 for _, archType := range archTypes {
1025 archTypeName := archType.Name
1026
1027 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001028 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001029
1030 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1031 }
1032 }
1033
1034 return osInfo
1035}
1036
1037// Optimize the properties by extracting common properties from arch type specific
1038// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001039func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001040 // Nothing to do if there is only a single common architecture.
1041 if len(osInfo.archInfos) == 0 {
1042 return
1043 }
1044
Paul Duffin9c3760e2020-03-16 19:52:08 +00001045 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001046 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001047 multilib = multilib.addArchType(archInfo.archType)
1048
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001049 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001050 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001051 }
1052
Paul Duffin4b8b7932020-05-06 12:35:38 +01001053 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001054
1055 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001056 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001057}
1058
1059// Add the properties for an os to a property set.
1060//
1061// Maps the properties related to the os variants through to an appropriate
1062// module structure that will produce equivalent set of variants when it is
1063// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001064func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001065
1066 var osPropertySet android.BpPropertySet
1067 var archPropertySet android.BpPropertySet
1068 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001069 if osInfo.Properties.Base().Os_count == 1 &&
1070 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1071 // There is only one OS type present in the variants and it shouldn't have a
1072 // variant-specific target. The latter is the case if it's either for device
1073 // where there is only one OS (android), or for host and the member type
1074 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001075
1076 // Create a structure that looks like:
1077 // module_type {
1078 // name: "...",
1079 // ...
1080 // <common properties>
1081 // ...
1082 // <single os type specific properties>
1083 //
1084 // arch: {
1085 // <arch specific sections>
1086 // }
1087 //
1088 osPropertySet = bpModule
1089 archPropertySet = osPropertySet.AddPropertySet("arch")
1090
1091 // Arch specific properties need to be added to an arch specific section
1092 // within arch.
1093 archOsPrefix = ""
1094 } else {
1095 // Create a structure that looks like:
1096 // module_type {
1097 // name: "...",
1098 // ...
1099 // <common properties>
1100 // ...
1101 // target: {
1102 // <arch independent os specific sections, e.g. android>
1103 // ...
1104 // <arch and os specific sections, e.g. android_x86>
1105 // }
1106 //
1107 osType := osInfo.osType
1108 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1109 archPropertySet = targetPropertySet
1110
1111 // Arch specific properties need to be added to an os and arch specific
1112 // section prefixed with <os>_.
1113 archOsPrefix = osType.Name + "_"
1114 }
1115
1116 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001117 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001118
1119 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1120 // os) specific properties.
1121 //
1122 // The archInfos list will be empty if the os contains variants for the common
1123 // architecture.
1124 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001125 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001126 }
1127}
1128
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001129func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1130 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001131 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001132}
1133
1134var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1135
Paul Duffin4b8b7932020-05-06 12:35:38 +01001136func (osInfo *osTypeSpecificInfo) String() string {
1137 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1138}
1139
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001140type archTypeSpecificInfo struct {
1141 baseInfo
1142
1143 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001144 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001145
1146 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001147}
1148
Paul Duffin4b8b7932020-05-06 12:35:38 +01001149var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1150
Paul Duffinfc8dd232020-03-17 12:51:37 +00001151// Create a new archTypeSpecificInfo for the specified arch type and its properties
1152// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001153func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001154
Paul Duffinfc8dd232020-03-17 12:51:37 +00001155 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001156 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001157
1158 // Create the properties into which the arch type specific properties will be
1159 // added.
1160 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001161
1162 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001163 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001164 } else {
1165 // There is more than one variant for this arch type which must be differentiated
1166 // by link type.
1167 for _, linkVariant := range archVariants {
1168 linkType := getLinkType(linkVariant)
1169 if linkType == "" {
1170 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1171 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001172 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001173
1174 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1175 }
1176 }
1177 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001178
1179 return archInfo
1180}
1181
Paul Duffinf34f6d82020-04-30 15:48:31 +01001182func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1183 return archInfo.Properties
1184}
1185
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001186// Get the link type of the variant
1187//
1188// If the variant is not differentiated by link type then it returns "",
1189// otherwise it returns one of "static" or "shared".
1190func getLinkType(variant android.Module) string {
1191 linkType := ""
1192 if linkable, ok := variant.(cc.LinkableInterface); ok {
1193 if linkable.Shared() && linkable.Static() {
1194 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1195 } else if linkable.Shared() {
1196 linkType = "shared"
1197 } else if linkable.Static() {
1198 linkType = "static"
1199 } else {
1200 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1201 }
1202 }
1203 return linkType
1204}
1205
1206// Optimize the properties by extracting common properties from link type specific
1207// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001208func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001209 if len(archInfo.linkInfos) == 0 {
1210 return
1211 }
1212
Paul Duffin4b8b7932020-05-06 12:35:38 +01001213 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001214}
1215
Paul Duffinfc8dd232020-03-17 12:51:37 +00001216// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001217func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001218 archTypeName := archInfo.archType.Name
1219 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001220 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1221 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1222 archTypePropertySet.AddProperty("enabled", true)
1223 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001224 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001225
1226 for _, linkInfo := range archInfo.linkInfos {
1227 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001228 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001229 }
1230}
1231
Paul Duffin4b8b7932020-05-06 12:35:38 +01001232func (archInfo *archTypeSpecificInfo) String() string {
1233 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1234}
1235
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001236type linkTypeSpecificInfo struct {
1237 baseInfo
1238
1239 linkType string
1240}
1241
Paul Duffin4b8b7932020-05-06 12:35:38 +01001242var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1243
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001244// Create a new linkTypeSpecificInfo for the specified link type and its properties
1245// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001246func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001247 linkInfo := &linkTypeSpecificInfo{
1248 baseInfo: baseInfo{
1249 // Create the properties into which the link type specific properties will be
1250 // added.
1251 Properties: variantPropertiesFactory(),
1252 },
1253 linkType: linkType,
1254 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001255 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001256 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001257}
1258
Paul Duffin4b8b7932020-05-06 12:35:38 +01001259func (l *linkTypeSpecificInfo) String() string {
1260 return fmt.Sprintf("LinkType{%s}", l.linkType)
1261}
1262
Paul Duffin3a4eb502020-03-19 16:11:18 +00001263type memberContext struct {
1264 sdkMemberContext android.ModuleContext
1265 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001266 memberType android.SdkMemberType
1267 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001268}
1269
1270func (m *memberContext) SdkModuleContext() android.ModuleContext {
1271 return m.sdkMemberContext
1272}
1273
1274func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1275 return m.builder
1276}
1277
Paul Duffina551a1c2020-03-17 21:04:24 +00001278func (m *memberContext) MemberType() android.SdkMemberType {
1279 return m.memberType
1280}
1281
1282func (m *memberContext) Name() string {
1283 return m.name
1284}
1285
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001286func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001287
1288 memberType := member.memberType
1289
Paul Duffina04c1072020-03-02 10:16:35 +00001290 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001291 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001292 variants := member.Variants()
1293 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001294 osType := variant.Target().Os
1295 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001296 }
1297
Paul Duffina04c1072020-03-02 10:16:35 +00001298 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001299 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001300 properties := memberType.CreateVariantPropertiesStruct()
1301 base := properties.Base()
1302 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001303 return properties
1304 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001305
Paul Duffina04c1072020-03-02 10:16:35 +00001306 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001307
Paul Duffina04c1072020-03-02 10:16:35 +00001308 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001309 commonProperties := variantPropertiesFactory()
1310 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001311
Paul Duffinc097e362020-03-10 22:50:03 +00001312 // Create common value extractor that can be used to optimize the properties.
1313 commonValueExtractor := newCommonValueExtractor(commonProperties)
1314
Paul Duffina04c1072020-03-02 10:16:35 +00001315 // The list of property structures which are os type specific but common across
1316 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001317 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001318
1319 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001320 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001321 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001322 // Add the os specific properties to a list of os type specific yet architecture
1323 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001324 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001325
Paul Duffin00e46802020-03-12 20:40:35 +00001326 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001327 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001328 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001329
Paul Duffina04c1072020-03-02 10:16:35 +00001330 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001331 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001332
Paul Duffina04c1072020-03-02 10:16:35 +00001333 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001334 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001335
Paul Duffina04c1072020-03-02 10:16:35 +00001336 // Create a target property set into which target specific properties can be
1337 // added.
1338 targetPropertySet := bpModule.AddPropertySet("target")
1339
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001340 // If the member is host OS dependent and has host_supported then disable by
1341 // default and enable each host OS variant explicitly. This avoids problems
1342 // with implicitly enabled OS variants when the snapshot is used, which might
1343 // be different from this run (e.g. different build OS).
1344 if ctx.memberType.IsHostOsDependent() {
1345 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1346 if hostSupported {
1347 hostPropertySet := targetPropertySet.AddPropertySet("host")
1348 hostPropertySet.AddProperty("enabled", false)
1349 }
1350 }
1351
Paul Duffina04c1072020-03-02 10:16:35 +00001352 // Iterate over the os types in a fixed order.
1353 for _, osType := range s.getPossibleOsTypes() {
1354 osInfo := osTypeToInfo[osType]
1355 if osInfo == nil {
1356 continue
1357 }
1358
Paul Duffin3a4eb502020-03-19 16:11:18 +00001359 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001360 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001361}
1362
Paul Duffina04c1072020-03-02 10:16:35 +00001363// Compute the list of possible os types that this sdk could support.
1364func (s *sdk) getPossibleOsTypes() []android.OsType {
1365 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001366 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001367 if s.DeviceSupported() {
1368 if osType.Class == android.Device && osType != android.Fuchsia {
1369 osTypes = append(osTypes, osType)
1370 }
1371 }
1372 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001373 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001374 osTypes = append(osTypes, osType)
1375 }
1376 }
1377 }
1378 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1379 return osTypes
1380}
1381
Paul Duffinb28369a2020-05-04 15:39:59 +01001382// Given a set of properties (struct value), return the value of the field within that
1383// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001384type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1385
Paul Duffinc459f892020-04-30 18:08:29 +01001386// Checks the metadata to determine whether the property should be ignored for the
1387// purposes of common value extraction or not.
1388type extractorMetadataPredicate func(metadata propertiesContainer) bool
1389
1390// Indicates whether optimizable properties are provided by a host variant or
1391// not.
1392type isHostVariant interface {
1393 isHostVariant() bool
1394}
1395
Paul Duffinb28369a2020-05-04 15:39:59 +01001396// A property that can be optimized by the commonValueExtractor.
1397type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001398 // The name of the field for this property. It is a "."-separated path for
1399 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001400 name string
1401
Paul Duffinc459f892020-04-30 18:08:29 +01001402 // Filter that can use metadata associated with the properties being optimized
1403 // to determine whether the field should be ignored during common value
1404 // optimization.
1405 filter extractorMetadataPredicate
1406
Paul Duffinb28369a2020-05-04 15:39:59 +01001407 // Retrieves the value on which common value optimization will be performed.
1408 getter fieldAccessorFunc
1409
1410 // The empty value for the field.
1411 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001412
1413 // True if the property can support arch variants false otherwise.
1414 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001415}
1416
Paul Duffin4b8b7932020-05-06 12:35:38 +01001417func (p extractorProperty) String() string {
1418 return p.name
1419}
1420
Paul Duffinc097e362020-03-10 22:50:03 +00001421// Supports extracting common values from a number of instances of a properties
1422// structure into a separate common set of properties.
1423type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001424 // The properties that the extractor can optimize.
1425 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001426}
1427
1428// Create a new common value extractor for the structure type for the supplied
1429// properties struct.
1430//
1431// The returned extractor can be used on any properties structure of the same type
1432// as the supplied set of properties.
1433func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1434 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1435 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001436 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001437 return extractor
1438}
1439
1440// Gather the fields from the supplied structure type from which common values will
1441// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001442//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001443// This is recursive function. If it encounters a struct then it will recurse
1444// into it, passing in the accessor for the field and the struct name as prefix
1445// for the nested fields. That will then be used in the accessors for the fields
1446// in the embedded struct.
1447func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001448 for f := 0; f < structType.NumField(); f++ {
1449 field := structType.Field(f)
1450 if field.PkgPath != "" {
1451 // Ignore unexported fields.
1452 continue
1453 }
1454
Paul Duffinb07fa512020-03-10 22:17:04 +00001455 // Ignore fields whose value should be kept.
1456 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001457 continue
1458 }
1459
Paul Duffinc459f892020-04-30 18:08:29 +01001460 var filter extractorMetadataPredicate
1461
1462 // Add a filter
1463 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1464 filter = func(metadata propertiesContainer) bool {
1465 if m, ok := metadata.(isHostVariant); ok {
1466 if m.isHostVariant() {
1467 return false
1468 }
1469 }
1470 return true
1471 }
1472 }
1473
Paul Duffinc097e362020-03-10 22:50:03 +00001474 // Save a copy of the field index for use in the function.
1475 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001476
Martin Stjernholmb0249572020-09-15 02:32:35 +01001477 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001478
Paul Duffinc097e362020-03-10 22:50:03 +00001479 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001480 if containingStructAccessor != nil {
1481 // This is an embedded structure so first access the field for the embedded
1482 // structure.
1483 value = containingStructAccessor(value)
1484 }
1485
Paul Duffinc097e362020-03-10 22:50:03 +00001486 // Skip through interface and pointer values to find the structure.
1487 value = getStructValue(value)
1488
Paul Duffin4b8b7932020-05-06 12:35:38 +01001489 defer func() {
1490 if r := recover(); r != nil {
1491 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1492 }
1493 }()
1494
Paul Duffinc097e362020-03-10 22:50:03 +00001495 // Return the field.
1496 return value.Field(fieldIndex)
1497 }
1498
Martin Stjernholmb0249572020-09-15 02:32:35 +01001499 if field.Type.Kind() == reflect.Struct {
1500 // Gather fields from the nested or embedded structure.
1501 var subNamePrefix string
1502 if field.Anonymous {
1503 subNamePrefix = namePrefix
1504 } else {
1505 subNamePrefix = name + "."
1506 }
1507 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001508 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001509 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001510 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001511 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001512 fieldGetter,
1513 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001514 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001515 }
1516 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001517 }
Paul Duffinc097e362020-03-10 22:50:03 +00001518 }
1519}
1520
1521func getStructValue(value reflect.Value) reflect.Value {
1522foundStruct:
1523 for {
1524 kind := value.Kind()
1525 switch kind {
1526 case reflect.Interface, reflect.Ptr:
1527 value = value.Elem()
1528 case reflect.Struct:
1529 break foundStruct
1530 default:
1531 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1532 }
1533 }
1534 return value
1535}
1536
Paul Duffinf34f6d82020-04-30 15:48:31 +01001537// A container of properties to be optimized.
1538//
1539// Allows additional information to be associated with the properties, e.g. for
1540// filtering.
1541type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001542 fmt.Stringer
1543
Paul Duffinf34f6d82020-04-30 15:48:31 +01001544 // Get the properties that need optimizing.
1545 optimizableProperties() interface{}
1546}
1547
1548// A wrapper for dynamic member properties to allow them to be optimized.
1549type dynamicMemberPropertiesContainer struct {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001550 sdkVariant *sdk
Paul Duffinf34f6d82020-04-30 15:48:31 +01001551 dynamicMemberProperties interface{}
1552}
1553
1554func (c dynamicMemberPropertiesContainer) optimizableProperties() interface{} {
1555 return c.dynamicMemberProperties
1556}
1557
Paul Duffin4b8b7932020-05-06 12:35:38 +01001558func (c dynamicMemberPropertiesContainer) String() string {
1559 return c.sdkVariant.String()
1560}
1561
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001562// Extract common properties from a slice of property structures of the same type.
1563//
1564// All the property structures must be of the same type.
1565// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001566// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001567//
1568// Iterates over each exported field (capitalized name) and checks to see whether they
1569// have the same value (using DeepEquals) across all the input properties. If it does not then no
1570// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001571// and the field in each of the input properties structure is set to its default value. Nested
1572// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001573func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001574 commonPropertiesValue := reflect.ValueOf(commonProperties)
1575 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001576
Paul Duffinf34f6d82020-04-30 15:48:31 +01001577 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1578
Paul Duffinb28369a2020-05-04 15:39:59 +01001579 for _, property := range e.properties {
1580 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001581 filter := property.filter
1582 if filter == nil {
1583 filter = func(metadata propertiesContainer) bool {
1584 return true
1585 }
1586 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001587
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001588 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001589 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1590 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001591 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001592
Paul Duffin864e1b42020-05-06 10:23:19 +01001593 // Assume that all the values will be the same.
1594 //
1595 // While similar to this is not quite the same as commonValue == nil. If all the values
1596 // have been filtered out then this will be false but commonValue == nil will be true.
1597 valuesDiffer := false
1598
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001599 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001600 container := sliceValue.Index(i).Interface().(propertiesContainer)
1601 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001602 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001603
Paul Duffinc459f892020-04-30 18:08:29 +01001604 if !filter(container) {
1605 expectedValue := property.emptyValue.Interface()
1606 actualValue := fieldValue.Interface()
1607 if !reflect.DeepEqual(expectedValue, actualValue) {
1608 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1609 }
1610 continue
1611 }
1612
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001613 if commonValue == nil {
1614 // Use the first value as the commonProperties value.
1615 commonValue = &fieldValue
1616 } else {
1617 // If the value does not match the current common value then there is
1618 // no value in common so break out.
1619 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1620 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001621 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001622 break
1623 }
1624 }
1625 }
1626
Paul Duffin864e1b42020-05-06 10:23:19 +01001627 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001628 // and set the input struct's field to the empty value.
1629 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001630 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001631 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001632 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001633 container := sliceValue.Index(i).Interface().(propertiesContainer)
1634 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001635 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001636 fieldValue.Set(emptyValue)
1637 }
1638 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001639
1640 if valuesDiffer && !property.archVariant {
1641 // The values differ but the property does not support arch variants so it
1642 // is an error.
1643 var details strings.Builder
1644 for i := 0; i < sliceValue.Len(); i++ {
1645 container := sliceValue.Index(i).Interface().(propertiesContainer)
1646 itemValue := reflect.ValueOf(container.optimizableProperties())
1647 fieldValue := fieldGetter(itemValue)
1648
1649 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1650 }
1651
1652 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1653 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001654 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01001655
1656 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001657}