blob: ef6a7b016dfa02cc49b2c757058858585b34681f [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 Duffin6a7e9532020-03-20 17:50:07 +0000116// Returns a list containing type (extracted from the dependency tag) and the variant
117// plus the multilib usages.
118func (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
133 s.memberRefs = append(s.memberRefs, sdkMemberRef{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
144// Organize the members.
145//
146// The members are first grouped by type and then grouped by name. The order of
147// the types is the order they are referenced in android.SdkMemberTypesRegistry.
148// The names are in the order in which the dependencies were added.
149//
150// Returns the members as well as the multilib setting to use.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000151func (s *sdk) organizeMembers(ctx android.ModuleContext, memberRefs []sdkMemberRef) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000152 byType := make(map[android.SdkMemberType][]*sdkMember)
153 byName := make(map[string]*sdkMember)
154
Paul Duffin1356d8c2020-02-25 19:26:33 +0000155 for _, memberRef := range memberRefs {
156 memberType := memberRef.memberType
157 variant := memberRef.variant
158
159 name := ctx.OtherModuleName(variant)
160 member := byName[name]
161 if member == nil {
162 member = &sdkMember{memberType: memberType, name: name}
163 byName[name] = member
164 byType[memberType] = append(byType[memberType], member)
165 }
166
Paul Duffin1356d8c2020-02-25 19:26:33 +0000167 // Only append new variants to the list. This is needed because a member can be both
168 // exported by the sdk and also be a transitive sdk member.
169 member.variants = appendUniqueVariants(member.variants, variant)
170 }
171
Paul Duffin13879572019-11-28 14:31:38 +0000172 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000173 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000174 membersOfType := byType[memberListProperty.memberType]
175 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900176 }
177
Paul Duffin6a7e9532020-03-20 17:50:07 +0000178 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900179}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900180
Paul Duffin72910952020-01-20 18:16:30 +0000181func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
182 for _, v := range variants {
183 if v == newVariant {
184 return variants
185 }
186 }
187 return append(variants, newVariant)
188}
189
Jiyong Park73c54ee2019-10-22 20:31:18 +0900190// SDK directory structure
191// <sdk_root>/
192// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
193// <api_ver>/ : below this directory are all auto-generated
194// Android.bp : definition of 'sdk_snapshot' module is here
195// aidl/
196// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
197// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900198// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900199// include/
200// bionic/libc/include/stdlib.h : an exported header file
201// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900202// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900203// <arch>/include/ : arch-specific exported headers
204// <arch>/include_gen/ : arch-specific generated headers
205// <arch>/lib/
206// libFoo.so : a stub library
207
Jiyong Park232e7852019-11-04 12:23:40 +0900208// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900209// This isn't visible to users, so could be changed in future.
210func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
211 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
212}
213
Jiyong Park232e7852019-11-04 12:23:40 +0900214// buildSnapshot is the main function in this source file. It creates rules to copy
215// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000216func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
217
Paul Duffin13f02712020-03-06 12:30:43 +0000218 allMembersByName := make(map[string]struct{})
219 exportedMembersByName := make(map[string]struct{})
Paul Duffin1356d8c2020-02-25 19:26:33 +0000220 var memberRefs []sdkMemberRef
221 for _, sdkVariant := range sdkVariants {
222 memberRefs = append(memberRefs, sdkVariant.memberRefs...)
Paul Duffin865171e2020-03-02 18:38:15 +0000223
Paul Duffin13f02712020-03-06 12:30:43 +0000224 // Record the names of all the members, both explicitly specified and implicitly
225 // included.
226 for _, memberRef := range sdkVariant.memberRefs {
227 allMembersByName[memberRef.variant.Name()] = struct{}{}
228 }
229
Paul Duffin865171e2020-03-02 18:38:15 +0000230 // Merge the exported member sets from all sdk variants.
231 for key, _ := range sdkVariant.getExportedMembers() {
Paul Duffin13f02712020-03-06 12:30:43 +0000232 exportedMembersByName[key] = struct{}{}
Paul Duffin865171e2020-03-02 18:38:15 +0000233 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000234 }
235
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000236 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900237
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000238 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000239
240 bpFile := &bpFile{
241 modules: make(map[string]*bpModule),
242 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000243
244 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000245 ctx: ctx,
246 sdk: s,
247 version: "current",
248 snapshotDir: snapshotDir.OutputPath,
249 copies: make(map[string]string),
250 filesToZip: []android.Path{bp.path},
251 bpFile: bpFile,
252 prebuiltModules: make(map[string]*bpModule),
253 allMembersByName: allMembersByName,
254 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900255 }
Paul Duffinac37c502019-11-26 18:02:20 +0000256 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900257
Paul Duffin6a7e9532020-03-20 17:50:07 +0000258 members := s.organizeMembers(ctx, memberRefs)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000259 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000260 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000261
Paul Duffina551a1c2020-03-17 21:04:24 +0000262 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000263
264 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100265 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900266 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900267
Paul Duffine6c0d842020-01-15 14:08:51 +0000268 // Create a transformer that will transform an unversioned module into a versioned module.
269 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
270
Paul Duffin72910952020-01-20 18:16:30 +0000271 // Create a transformer that will transform an unversioned module by replacing any references
272 // to internal members with a unique module name and setting prefer: false.
273 unversionedTransformer := unversionedTransformation{builder: builder}
274
Paul Duffinb645ec82019-11-27 17:43:54 +0000275 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000276 // Prune any empty property sets.
277 unversioned = unversioned.transform(pruneEmptySetTransformer{})
278
Paul Duffinb645ec82019-11-27 17:43:54 +0000279 // Copy the unversioned module so it can be modified to make it versioned.
Paul Duffincc72e982020-01-14 15:53:11 +0000280 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000281
282 // Transform the unversioned module into a versioned one.
283 versioned.transform(unversionedToVersionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000284 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000285
Paul Duffin72910952020-01-20 18:16:30 +0000286 // Transform the unversioned module to make it suitable for use in the snapshot.
287 unversioned.transform(unversionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000288 bpFile.AddModule(unversioned)
289 }
290
Paul Duffin26197a62021-04-24 00:34:10 +0100291 // Add the sdk/module_exports_snapshot module to the bp file.
292 s.addSnapshotModule(ctx, builder, sdkVariants, memberRefs)
293
294 // generate Android.bp
295 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
296 generateBpContents(&bp.generatedContents, bpFile)
297
298 contents := bp.content.String()
299 syntaxCheckSnapshotBpFile(ctx, contents)
300
301 bp.build(pctx, ctx, nil)
302
303 filesToZip := builder.filesToZip
304
305 // zip them all
306 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
307 outputDesc := "Building snapshot for " + ctx.ModuleName()
308
309 // If there are no zips to merge then generate the output zip directly.
310 // Otherwise, generate an intermediate zip file into which other zips can be
311 // merged.
312 var zipFile android.OutputPath
313 var desc string
314 if len(builder.zipsToMerge) == 0 {
315 zipFile = outputZipFile
316 desc = outputDesc
317 } else {
318 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
319 desc = "Building intermediate snapshot for " + ctx.ModuleName()
320 }
321
322 ctx.Build(pctx, android.BuildParams{
323 Description: desc,
324 Rule: zipFiles,
325 Inputs: filesToZip,
326 Output: zipFile,
327 Args: map[string]string{
328 "basedir": builder.snapshotDir.String(),
329 },
330 })
331
332 if len(builder.zipsToMerge) != 0 {
333 ctx.Build(pctx, android.BuildParams{
334 Description: outputDesc,
335 Rule: mergeZips,
336 Input: zipFile,
337 Inputs: builder.zipsToMerge,
338 Output: outputZipFile,
339 })
340 }
341
342 return outputZipFile
343}
344
345// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
346func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberRefs []sdkMemberRef) {
347 bpFile := builder.bpFile
348
Paul Duffinb645ec82019-11-27 17:43:54 +0000349 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000350 var snapshotModuleType string
351 if s.properties.Module_exports {
352 snapshotModuleType = "module_exports_snapshot"
353 } else {
354 snapshotModuleType = "sdk_snapshot"
355 }
356 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000357 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000358
359 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100360 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000361 if len(visibility) != 0 {
362 snapshotModule.AddProperty("visibility", visibility)
363 }
364
Paul Duffin865171e2020-03-02 18:38:15 +0000365 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000366
Paul Duffinf34f6d82020-04-30 15:48:31 +0100367 var dynamicMemberPropertiesContainers []propertiesContainer
Paul Duffin865171e2020-03-02 18:38:15 +0000368 osTypeToMemberProperties := make(map[android.OsType]*sdk)
369 for _, sdkVariant := range sdkVariants {
370 properties := sdkVariant.dynamicMemberTypeListProperties
371 osTypeToMemberProperties[sdkVariant.Target().Os] = sdkVariant
Paul Duffin4b8b7932020-05-06 12:35:38 +0100372 dynamicMemberPropertiesContainers = append(dynamicMemberPropertiesContainers, &dynamicMemberPropertiesContainer{sdkVariant, properties})
Paul Duffin865171e2020-03-02 18:38:15 +0000373 }
374
375 // Extract the common lists of members into a separate struct.
376 commonDynamicMemberProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffinc097e362020-03-10 22:50:03 +0000377 extractor := newCommonValueExtractor(commonDynamicMemberProperties)
Paul Duffin4b8b7932020-05-06 12:35:38 +0100378 extractCommonProperties(ctx, extractor, commonDynamicMemberProperties, dynamicMemberPropertiesContainers)
Paul Duffin865171e2020-03-02 18:38:15 +0000379
380 // Add properties common to all os types.
381 s.addMemberPropertiesToPropertySet(builder, snapshotModule, commonDynamicMemberProperties)
382
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100383 // Optimize other per-variant properties, besides the dynamic member lists.
384 type variantProperties struct {
385 Compile_multilib string `android:"arch_variant"`
386 }
387 var variantPropertiesContainers []propertiesContainer
388 variantToProperties := make(map[*sdk]*variantProperties)
389 for _, sdkVariant := range sdkVariants {
390 props := &variantProperties{
391 Compile_multilib: sdkVariant.multilibUsages.String(),
392 }
393 variantPropertiesContainers = append(variantPropertiesContainers, &dynamicMemberPropertiesContainer{sdkVariant, props})
394 variantToProperties[sdkVariant] = props
395 }
396 commonVariantProperties := variantProperties{}
397 extractor = newCommonValueExtractor(commonVariantProperties)
398 extractCommonProperties(ctx, extractor, &commonVariantProperties, variantPropertiesContainers)
399 if commonVariantProperties.Compile_multilib != "" && commonVariantProperties.Compile_multilib != "both" {
400 // Compile_multilib defaults to both so only needs to be set when it's
401 // specified and not both.
402 snapshotModule.AddProperty("compile_multilib", commonVariantProperties.Compile_multilib)
403 }
404
Paul Duffin6a7e9532020-03-20 17:50:07 +0000405 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100406
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100407 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000408 for _, osType := range s.getPossibleOsTypes() {
409 if sdkVariant, ok := osTypeToMemberProperties[osType]; ok {
410 osPropertySet := targetPropertySet.AddPropertySet(sdkVariant.Target().Os.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000411
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100412 variantProps := variantToProperties[sdkVariant]
413 if variantProps.Compile_multilib != "" && variantProps.Compile_multilib != "both" {
414 osPropertySet.AddProperty("compile_multilib", variantProps.Compile_multilib)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000415 }
416
Paul Duffin865171e2020-03-02 18:38:15 +0000417 s.addMemberPropertiesToPropertySet(builder, osPropertySet, sdkVariant.dynamicMemberTypeListProperties)
Paul Duffin13879572019-11-28 14:31:38 +0000418 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000419 }
Paul Duffin865171e2020-03-02 18:38:15 +0000420
Jiyong Park8fe14e62020-10-19 22:47:34 +0900421 // If host is supported and any member is host OS dependent then disable host
422 // by default, so that we can enable each host OS variant explicitly. This
423 // avoids problems with implicitly enabled OS variants when the snapshot is
424 // used, which might be different from this run (e.g. different build OS).
425 if s.HostSupported() {
426 var supportedHostTargets []string
427 for _, memberRef := range memberRefs {
428 if memberRef.memberType.IsHostOsDependent() && memberRef.variant.Target().Os.Class == android.Host {
429 targetString := memberRef.variant.Target().Os.String() + "_" + memberRef.variant.Target().Arch.ArchType.String()
430 if !android.InList(targetString, supportedHostTargets) {
431 supportedHostTargets = append(supportedHostTargets, targetString)
432 }
433 }
434 }
435 if len(supportedHostTargets) > 0 {
436 hostPropertySet := targetPropertySet.AddPropertySet("host")
437 hostPropertySet.AddProperty("enabled", false)
438 }
439 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
440 for _, hostTarget := range supportedHostTargets {
441 propertySet := targetPropertySet.AddPropertySet(hostTarget)
442 propertySet.AddProperty("enabled", true)
443 }
444 }
445
Paul Duffin865171e2020-03-02 18:38:15 +0000446 // Prune any empty property sets.
447 snapshotModule.transform(pruneEmptySetTransformer{})
448
Paul Duffinb645ec82019-11-27 17:43:54 +0000449 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900450}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000451
Paul Duffinf88d8e02020-05-07 20:21:34 +0100452// Check the syntax of the generated Android.bp file contents and if they are
453// invalid then log an error with the contents (tagged with line numbers) and the
454// errors that were found so that it is easy to see where the problem lies.
455func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
456 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
457 if len(errs) != 0 {
458 message := &strings.Builder{}
459 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
460
461Generated Android.bp contents
462========================================================================
463`)
464 for i, line := range strings.Split(contents, "\n") {
465 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
466 }
467
468 _, _ = fmt.Fprint(message, `
469========================================================================
470
471Errors found:
472`)
473
474 for _, err := range errs {
475 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
476 }
477
478 ctx.ModuleErrorf("%s", message.String())
479 }
480}
481
Paul Duffin4b8b7932020-05-06 12:35:38 +0100482func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
483 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
484 if err != nil {
485 ctx.ModuleErrorf("error extracting common properties: %s", err)
486 }
487}
488
Paul Duffin865171e2020-03-02 18:38:15 +0000489func (s *sdk) addMemberPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, dynamicMemberTypeListProperties interface{}) {
490 for _, memberListProperty := range s.memberListProperties() {
491 names := memberListProperty.getter(dynamicMemberTypeListProperties)
492 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000493 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000494 }
495 }
496}
497
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000498type propertyTag struct {
499 name string
500}
501
Paul Duffin0cb37b92020-03-04 14:52:46 +0000502// A BpPropertyTag to add to a property that contains references to other sdk members.
503//
504// This will cause the references to be rewritten to a versioned reference in the version
505// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000506var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000507var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000508
Paul Duffin0cb37b92020-03-04 14:52:46 +0000509// A BpPropertyTag that indicates the property should only be present in the versioned
510// module.
511//
512// This will cause the property to be removed from the unversioned instance of a
513// snapshot module.
514var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
515
Paul Duffine6c0d842020-01-15 14:08:51 +0000516type unversionedToVersionedTransformation struct {
517 identityTransformation
518 builder *snapshotBuilder
519}
520
Paul Duffine6c0d842020-01-15 14:08:51 +0000521func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
522 // Use a versioned name for the module but remember the original name for the
523 // snapshot.
524 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000525 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000526 module.insertAfter("name", "sdk_member_name", name)
527 return module
528}
529
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000530func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000531 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
532 required := tag == requiredSdkMemberReferencePropertyTag
533 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000534 } else {
535 return value, tag
536 }
537}
538
Paul Duffin72910952020-01-20 18:16:30 +0000539type unversionedTransformation struct {
540 identityTransformation
541 builder *snapshotBuilder
542}
543
544func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
545 // If the module is an internal member then use a unique name for it.
546 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000547 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000548
549 // Set prefer: false - this is not strictly required as that is the default.
550 module.insertAfter("name", "prefer", false)
551
552 return module
553}
554
555func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000556 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
557 required := tag == requiredSdkMemberReferencePropertyTag
558 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000559 } else if tag == sdkVersionedOnlyPropertyTag {
560 // The property is not allowed in the unversioned module so remove it.
561 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000562 } else {
563 return value, tag
564 }
565}
566
Paul Duffina78f3a72020-02-21 16:29:35 +0000567type pruneEmptySetTransformer struct {
568 identityTransformation
569}
570
571var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
572
573func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
574 if len(propertySet.properties) == 0 {
575 return nil, nil
576 } else {
577 return propertySet, tag
578 }
579}
580
Paul Duffinb645ec82019-11-27 17:43:54 +0000581func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000582 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
583 return true
584 })
585}
586
587func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffinb645ec82019-11-27 17:43:54 +0000588 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
589 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000590 if moduleFilter(bpModule) {
591 contents.Printfln("")
592 contents.Printfln("%s {", bpModule.moduleType)
593 outputPropertySet(contents, bpModule.bpPropertySet)
594 contents.Printfln("}")
595 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000596 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000597}
598
599func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
600 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000601
602 // Output the properties first, followed by the nested sets. This ensures a
603 // consistent output irrespective of whether property sets are created before
604 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000605 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000606 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000607
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000608 switch v := value.(type) {
609 case []string:
610 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000611 if length > 1 {
612 contents.Printfln("%s: [", name)
613 contents.Indent()
614 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000615 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000616 }
617 contents.Dedent()
618 contents.Printfln("],")
619 } else if length == 0 {
620 contents.Printfln("%s: [],", name)
621 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000622 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000623 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000624
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000625 case bool:
626 contents.Printfln("%s: %t,", name, v)
627
628 case *bpPropertySet:
629 // Do not write property sets in the properties phase.
Paul Duffinb645ec82019-11-27 17:43:54 +0000630
631 default:
632 contents.Printfln("%s: %q,", name, value)
633 }
634 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000635
636 for _, name := range set.order {
637 value := set.getValue(name)
638
639 // Only write property sets in the sets phase.
640 switch v := value.(type) {
641 case *bpPropertySet:
642 contents.Printfln("%s: {", name)
643 outputPropertySet(contents, v)
644 contents.Printfln("},")
645 }
646 }
647
Paul Duffinb645ec82019-11-27 17:43:54 +0000648 contents.Dedent()
649}
650
Paul Duffinac37c502019-11-26 18:02:20 +0000651func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000652 contents := &generatedContents{}
653 generateBpContents(contents, s.builderForTests.bpFile)
654 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000655}
656
Paul Duffind0759072021-02-17 11:23:00 +0000657func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
658 contents := &generatedContents{}
659 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
660 return !strings.Contains(module.properties["name"].(string), "@")
661 })
662 return contents.content.String()
663}
664
665func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
666 contents := &generatedContents{}
667 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
668 return strings.Contains(module.properties["name"].(string), "@")
669 })
670 return contents.content.String()
671}
672
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000673type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000674 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000675 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000676 version string
677 snapshotDir android.OutputPath
678 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000679
680 // Map from destination to source of each copy - used to eliminate duplicates and
681 // detect conflicts.
682 copies map[string]string
683
Paul Duffinb645ec82019-11-27 17:43:54 +0000684 filesToZip android.Paths
685 zipsToMerge android.Paths
686
687 prebuiltModules map[string]*bpModule
688 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000689
690 // The set of all members by name.
691 allMembersByName map[string]struct{}
692
693 // The set of exported members by name.
694 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000695}
696
697func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000698 if existing, ok := s.copies[dest]; ok {
699 if existing != src.String() {
700 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
701 return
702 }
703 } else {
704 path := s.snapshotDir.Join(s.ctx, dest)
705 s.ctx.Build(pctx, android.BuildParams{
706 Rule: android.Cp,
707 Input: src,
708 Output: path,
709 })
710 s.filesToZip = append(s.filesToZip, path)
711
712 s.copies[dest] = src.String()
713 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000714}
715
Paul Duffin91547182019-11-12 19:39:36 +0000716func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
717 ctx := s.ctx
718
719 // Repackage the zip file so that the entries are in the destDir directory.
720 // This will allow the zip file to be merged into the snapshot.
721 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000722
723 ctx.Build(pctx, android.BuildParams{
724 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
725 Rule: repackageZip,
726 Input: zipPath,
727 Output: tmpZipPath,
728 Args: map[string]string{
729 "destdir": destDir,
730 },
731 })
Paul Duffin91547182019-11-12 19:39:36 +0000732
733 // Add the repackaged zip file to the files to merge.
734 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
735}
736
Paul Duffin9d8d6092019-12-05 18:19:29 +0000737func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
738 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000739 if s.prebuiltModules[name] != nil {
740 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
741 }
742
743 m := s.bpFile.newModule(moduleType)
744 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000745
Paul Duffinbefa4b92020-03-04 14:22:45 +0000746 variant := member.Variants()[0]
747
Paul Duffin13f02712020-03-06 12:30:43 +0000748 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000749 // An internal member is only referenced from the sdk snapshot which is in the
750 // same package so can be marked as private.
751 m.AddProperty("visibility", []string{"//visibility:private"})
752 } else {
753 // Extract visibility information from a member variant. All variants have the same
754 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +0100755 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
756
757 // Add any additional visibility rules needed for the prebuilts to reference each other.
758 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
759 if err != nil {
760 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
761 }
762
763 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +0000764 if len(visibility) != 0 {
765 m.AddProperty("visibility", visibility)
766 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000767 }
768
Martin Stjernholm1e041092020-11-03 00:11:09 +0000769 // Where available copy apex_available properties from the member.
770 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
771 apexAvailable := apexAware.ApexAvailable()
772 if len(apexAvailable) == 0 {
773 // //apex_available:platform is the default.
774 apexAvailable = []string{android.AvailableToPlatform}
775 }
776
777 // Add in any baseline apex available settings.
778 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
779
780 // Remove duplicates and sort.
781 apexAvailable = android.FirstUniqueStrings(apexAvailable)
782 sort.Strings(apexAvailable)
783
784 m.AddProperty("apex_available", apexAvailable)
785 }
786
Paul Duffin865171e2020-03-02 18:38:15 +0000787 deviceSupported := false
788 hostSupported := false
789
790 for _, variant := range member.Variants() {
791 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +0900792 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +0000793 hostSupported = true
794 } else if osClass == android.Device {
795 deviceSupported = true
796 }
797 }
798
799 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000800
Paul Duffin0cb37b92020-03-04 14:52:46 +0000801 // Disable installation in the versioned module of those modules that are ever installable.
802 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
803 if installable.EverInstallable() {
804 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
805 }
806 }
807
Paul Duffinb645ec82019-11-27 17:43:54 +0000808 s.prebuiltModules[name] = m
809 s.prebuiltOrder = append(s.prebuiltOrder, m)
810 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000811}
812
Paul Duffin865171e2020-03-02 18:38:15 +0000813func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
814 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000815 bpModule.AddProperty("device_supported", false)
816 }
Paul Duffin865171e2020-03-02 18:38:15 +0000817 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000818 bpModule.AddProperty("host_supported", true)
819 }
820}
821
Paul Duffin13f02712020-03-06 12:30:43 +0000822func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
823 if required {
824 return requiredSdkMemberReferencePropertyTag
825 } else {
826 return optionalSdkMemberReferencePropertyTag
827 }
828}
829
830func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
831 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000832}
833
Paul Duffinb645ec82019-11-27 17:43:54 +0000834// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +0000835func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
836 if _, ok := s.allMembersByName[unversionedName]; !ok {
837 if required {
838 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
839 }
840 return unversionedName
841 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000842 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
843}
Paul Duffinb645ec82019-11-27 17:43:54 +0000844
Paul Duffin13f02712020-03-06 12:30:43 +0000845func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000846 var references []string = nil
847 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000848 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000849 }
850 return references
851}
Paul Duffin13879572019-11-28 14:31:38 +0000852
Paul Duffin72910952020-01-20 18:16:30 +0000853// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +0000854func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
855 if _, ok := s.allMembersByName[unversionedName]; !ok {
856 if required {
857 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
858 }
859 return unversionedName
860 }
861
862 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +0000863 return s.ctx.ModuleName() + "_" + unversionedName
864 } else {
865 return unversionedName
866 }
867}
868
Paul Duffin13f02712020-03-06 12:30:43 +0000869func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +0000870 var references []string = nil
871 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000872 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +0000873 }
874 return references
875}
876
Paul Duffin13f02712020-03-06 12:30:43 +0000877func (s *snapshotBuilder) isInternalMember(memberName string) bool {
878 _, ok := s.exportedMembersByName[memberName]
879 return !ok
880}
881
Martin Stjernholm89238f42020-07-10 00:14:03 +0100882// Add the properties from the given SdkMemberProperties to the blueprint
883// property set. This handles common properties in SdkMemberPropertiesBase and
884// calls the member-specific AddToPropertySet for the rest.
885func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
886 if memberProperties.Base().Compile_multilib != "" {
887 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
888 }
889
890 memberProperties.AddToPropertySet(ctx, targetPropertySet)
891}
892
Paul Duffin1356d8c2020-02-25 19:26:33 +0000893type sdkMemberRef struct {
894 memberType android.SdkMemberType
895 variant android.SdkAware
896}
897
Paul Duffin13879572019-11-28 14:31:38 +0000898var _ android.SdkMember = (*sdkMember)(nil)
899
900type sdkMember struct {
901 memberType android.SdkMemberType
902 name string
903 variants []android.SdkAware
904}
905
906func (m *sdkMember) Name() string {
907 return m.name
908}
909
910func (m *sdkMember) Variants() []android.SdkAware {
911 return m.variants
912}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000913
Paul Duffin9c3760e2020-03-16 19:52:08 +0000914// Track usages of multilib variants.
915type multilibUsage int
916
917const (
918 multilibNone multilibUsage = 0
919 multilib32 multilibUsage = 1
920 multilib64 multilibUsage = 2
921 multilibBoth = multilib32 | multilib64
922)
923
924// Add the multilib that is used in the arch type.
925func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
926 multilib := archType.Multilib
927 switch multilib {
928 case "":
929 return m
930 case "lib32":
931 return m | multilib32
932 case "lib64":
933 return m | multilib64
934 default:
935 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
936 }
937}
938
939func (m multilibUsage) String() string {
940 switch m {
941 case multilibNone:
942 return ""
943 case multilib32:
944 return "32"
945 case multilib64:
946 return "64"
947 case multilibBoth:
948 return "both"
949 default:
950 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
951 m, multilibNone, multilib32, multilib64, multilibBoth))
952 }
953}
954
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000955type baseInfo struct {
956 Properties android.SdkMemberProperties
957}
958
Paul Duffinf34f6d82020-04-30 15:48:31 +0100959func (b *baseInfo) optimizableProperties() interface{} {
960 return b.Properties
961}
962
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000963type osTypeSpecificInfo struct {
964 baseInfo
965
Paul Duffin00e46802020-03-12 20:40:35 +0000966 osType android.OsType
967
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000968 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +0000969 //
970 // Nil if there is one variant whose arch type is common
971 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000972}
973
Paul Duffin4b8b7932020-05-06 12:35:38 +0100974var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
975
Paul Duffinfc8dd232020-03-17 12:51:37 +0000976type variantPropertiesFactoryFunc func() android.SdkMemberProperties
977
Paul Duffin00e46802020-03-12 20:40:35 +0000978// Create a new osTypeSpecificInfo for the specified os type and its properties
979// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000980func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +0000981 osInfo := &osTypeSpecificInfo{
982 osType: osType,
983 }
984
985 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
986 properties := variantPropertiesFactory()
987 properties.Base().Os = osType
988 return properties
989 }
990
991 // Create a structure into which properties common across the architectures in
992 // this os type will be stored.
993 osInfo.Properties = osSpecificVariantPropertiesFactory()
994
995 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000996 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +0000997 var archTypes []android.ArchType
998 for _, variant := range osTypeVariants {
999 archType := variant.Target().Arch.ArchType
1000 archTypeName := archType.Name
1001 if _, ok := variantsByArchName[archTypeName]; !ok {
1002 archTypes = append(archTypes, archType)
1003 }
1004
1005 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1006 }
1007
1008 if commonVariants, ok := variantsByArchName["common"]; ok {
1009 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001010 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 +00001011 }
1012
1013 // A common arch type only has one variant and its properties should be treated
1014 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001015 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001016 } else {
1017 // Create an arch specific info for each supported architecture type.
1018 for _, archType := range archTypes {
1019 archTypeName := archType.Name
1020
1021 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001022 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001023
1024 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1025 }
1026 }
1027
1028 return osInfo
1029}
1030
1031// Optimize the properties by extracting common properties from arch type specific
1032// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001033func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001034 // Nothing to do if there is only a single common architecture.
1035 if len(osInfo.archInfos) == 0 {
1036 return
1037 }
1038
Paul Duffin9c3760e2020-03-16 19:52:08 +00001039 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001040 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001041 multilib = multilib.addArchType(archInfo.archType)
1042
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001043 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001044 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001045 }
1046
Paul Duffin4b8b7932020-05-06 12:35:38 +01001047 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001048
1049 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001050 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001051}
1052
1053// Add the properties for an os to a property set.
1054//
1055// Maps the properties related to the os variants through to an appropriate
1056// module structure that will produce equivalent set of variants when it is
1057// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001058func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001059
1060 var osPropertySet android.BpPropertySet
1061 var archPropertySet android.BpPropertySet
1062 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001063 if osInfo.Properties.Base().Os_count == 1 &&
1064 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1065 // There is only one OS type present in the variants and it shouldn't have a
1066 // variant-specific target. The latter is the case if it's either for device
1067 // where there is only one OS (android), or for host and the member type
1068 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001069
1070 // Create a structure that looks like:
1071 // module_type {
1072 // name: "...",
1073 // ...
1074 // <common properties>
1075 // ...
1076 // <single os type specific properties>
1077 //
1078 // arch: {
1079 // <arch specific sections>
1080 // }
1081 //
1082 osPropertySet = bpModule
1083 archPropertySet = osPropertySet.AddPropertySet("arch")
1084
1085 // Arch specific properties need to be added to an arch specific section
1086 // within arch.
1087 archOsPrefix = ""
1088 } else {
1089 // Create a structure that looks like:
1090 // module_type {
1091 // name: "...",
1092 // ...
1093 // <common properties>
1094 // ...
1095 // target: {
1096 // <arch independent os specific sections, e.g. android>
1097 // ...
1098 // <arch and os specific sections, e.g. android_x86>
1099 // }
1100 //
1101 osType := osInfo.osType
1102 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1103 archPropertySet = targetPropertySet
1104
1105 // Arch specific properties need to be added to an os and arch specific
1106 // section prefixed with <os>_.
1107 archOsPrefix = osType.Name + "_"
1108 }
1109
1110 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001111 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001112
1113 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1114 // os) specific properties.
1115 //
1116 // The archInfos list will be empty if the os contains variants for the common
1117 // architecture.
1118 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001119 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001120 }
1121}
1122
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001123func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1124 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001125 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001126}
1127
1128var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1129
Paul Duffin4b8b7932020-05-06 12:35:38 +01001130func (osInfo *osTypeSpecificInfo) String() string {
1131 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1132}
1133
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001134type archTypeSpecificInfo struct {
1135 baseInfo
1136
1137 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001138 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001139
1140 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001141}
1142
Paul Duffin4b8b7932020-05-06 12:35:38 +01001143var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1144
Paul Duffinfc8dd232020-03-17 12:51:37 +00001145// Create a new archTypeSpecificInfo for the specified arch type and its properties
1146// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001147func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001148
Paul Duffinfc8dd232020-03-17 12:51:37 +00001149 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001150 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001151
1152 // Create the properties into which the arch type specific properties will be
1153 // added.
1154 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001155
1156 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001157 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001158 } else {
1159 // There is more than one variant for this arch type which must be differentiated
1160 // by link type.
1161 for _, linkVariant := range archVariants {
1162 linkType := getLinkType(linkVariant)
1163 if linkType == "" {
1164 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1165 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001166 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001167
1168 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1169 }
1170 }
1171 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001172
1173 return archInfo
1174}
1175
Paul Duffinf34f6d82020-04-30 15:48:31 +01001176func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1177 return archInfo.Properties
1178}
1179
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001180// Get the link type of the variant
1181//
1182// If the variant is not differentiated by link type then it returns "",
1183// otherwise it returns one of "static" or "shared".
1184func getLinkType(variant android.Module) string {
1185 linkType := ""
1186 if linkable, ok := variant.(cc.LinkableInterface); ok {
1187 if linkable.Shared() && linkable.Static() {
1188 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1189 } else if linkable.Shared() {
1190 linkType = "shared"
1191 } else if linkable.Static() {
1192 linkType = "static"
1193 } else {
1194 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1195 }
1196 }
1197 return linkType
1198}
1199
1200// Optimize the properties by extracting common properties from link type specific
1201// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001202func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001203 if len(archInfo.linkInfos) == 0 {
1204 return
1205 }
1206
Paul Duffin4b8b7932020-05-06 12:35:38 +01001207 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001208}
1209
Paul Duffinfc8dd232020-03-17 12:51:37 +00001210// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001211func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001212 archTypeName := archInfo.archType.Name
1213 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001214 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1215 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1216 archTypePropertySet.AddProperty("enabled", true)
1217 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001218 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001219
1220 for _, linkInfo := range archInfo.linkInfos {
1221 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001222 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001223 }
1224}
1225
Paul Duffin4b8b7932020-05-06 12:35:38 +01001226func (archInfo *archTypeSpecificInfo) String() string {
1227 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1228}
1229
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001230type linkTypeSpecificInfo struct {
1231 baseInfo
1232
1233 linkType string
1234}
1235
Paul Duffin4b8b7932020-05-06 12:35:38 +01001236var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1237
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001238// Create a new linkTypeSpecificInfo for the specified link type and its properties
1239// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001240func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001241 linkInfo := &linkTypeSpecificInfo{
1242 baseInfo: baseInfo{
1243 // Create the properties into which the link type specific properties will be
1244 // added.
1245 Properties: variantPropertiesFactory(),
1246 },
1247 linkType: linkType,
1248 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001249 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001250 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001251}
1252
Paul Duffin4b8b7932020-05-06 12:35:38 +01001253func (l *linkTypeSpecificInfo) String() string {
1254 return fmt.Sprintf("LinkType{%s}", l.linkType)
1255}
1256
Paul Duffin3a4eb502020-03-19 16:11:18 +00001257type memberContext struct {
1258 sdkMemberContext android.ModuleContext
1259 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001260 memberType android.SdkMemberType
1261 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001262}
1263
1264func (m *memberContext) SdkModuleContext() android.ModuleContext {
1265 return m.sdkMemberContext
1266}
1267
1268func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1269 return m.builder
1270}
1271
Paul Duffina551a1c2020-03-17 21:04:24 +00001272func (m *memberContext) MemberType() android.SdkMemberType {
1273 return m.memberType
1274}
1275
1276func (m *memberContext) Name() string {
1277 return m.name
1278}
1279
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001280func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001281
1282 memberType := member.memberType
1283
Paul Duffina04c1072020-03-02 10:16:35 +00001284 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001285 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001286 variants := member.Variants()
1287 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001288 osType := variant.Target().Os
1289 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001290 }
1291
Paul Duffina04c1072020-03-02 10:16:35 +00001292 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001293 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001294 properties := memberType.CreateVariantPropertiesStruct()
1295 base := properties.Base()
1296 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001297 return properties
1298 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001299
Paul Duffina04c1072020-03-02 10:16:35 +00001300 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001301
Paul Duffina04c1072020-03-02 10:16:35 +00001302 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001303 commonProperties := variantPropertiesFactory()
1304 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001305
Paul Duffinc097e362020-03-10 22:50:03 +00001306 // Create common value extractor that can be used to optimize the properties.
1307 commonValueExtractor := newCommonValueExtractor(commonProperties)
1308
Paul Duffina04c1072020-03-02 10:16:35 +00001309 // The list of property structures which are os type specific but common across
1310 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001311 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001312
1313 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001314 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001315 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001316 // Add the os specific properties to a list of os type specific yet architecture
1317 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001318 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001319
Paul Duffin00e46802020-03-12 20:40:35 +00001320 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001321 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001322 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001323
Paul Duffina04c1072020-03-02 10:16:35 +00001324 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001325 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001326
Paul Duffina04c1072020-03-02 10:16:35 +00001327 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001328 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001329
Paul Duffina04c1072020-03-02 10:16:35 +00001330 // Create a target property set into which target specific properties can be
1331 // added.
1332 targetPropertySet := bpModule.AddPropertySet("target")
1333
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001334 // If the member is host OS dependent and has host_supported then disable by
1335 // default and enable each host OS variant explicitly. This avoids problems
1336 // with implicitly enabled OS variants when the snapshot is used, which might
1337 // be different from this run (e.g. different build OS).
1338 if ctx.memberType.IsHostOsDependent() {
1339 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1340 if hostSupported {
1341 hostPropertySet := targetPropertySet.AddPropertySet("host")
1342 hostPropertySet.AddProperty("enabled", false)
1343 }
1344 }
1345
Paul Duffina04c1072020-03-02 10:16:35 +00001346 // Iterate over the os types in a fixed order.
1347 for _, osType := range s.getPossibleOsTypes() {
1348 osInfo := osTypeToInfo[osType]
1349 if osInfo == nil {
1350 continue
1351 }
1352
Paul Duffin3a4eb502020-03-19 16:11:18 +00001353 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001354 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001355}
1356
Paul Duffina04c1072020-03-02 10:16:35 +00001357// Compute the list of possible os types that this sdk could support.
1358func (s *sdk) getPossibleOsTypes() []android.OsType {
1359 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001360 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001361 if s.DeviceSupported() {
1362 if osType.Class == android.Device && osType != android.Fuchsia {
1363 osTypes = append(osTypes, osType)
1364 }
1365 }
1366 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001367 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001368 osTypes = append(osTypes, osType)
1369 }
1370 }
1371 }
1372 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1373 return osTypes
1374}
1375
Paul Duffinb28369a2020-05-04 15:39:59 +01001376// Given a set of properties (struct value), return the value of the field within that
1377// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001378type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1379
Paul Duffinc459f892020-04-30 18:08:29 +01001380// Checks the metadata to determine whether the property should be ignored for the
1381// purposes of common value extraction or not.
1382type extractorMetadataPredicate func(metadata propertiesContainer) bool
1383
1384// Indicates whether optimizable properties are provided by a host variant or
1385// not.
1386type isHostVariant interface {
1387 isHostVariant() bool
1388}
1389
Paul Duffinb28369a2020-05-04 15:39:59 +01001390// A property that can be optimized by the commonValueExtractor.
1391type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001392 // The name of the field for this property. It is a "."-separated path for
1393 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001394 name string
1395
Paul Duffinc459f892020-04-30 18:08:29 +01001396 // Filter that can use metadata associated with the properties being optimized
1397 // to determine whether the field should be ignored during common value
1398 // optimization.
1399 filter extractorMetadataPredicate
1400
Paul Duffinb28369a2020-05-04 15:39:59 +01001401 // Retrieves the value on which common value optimization will be performed.
1402 getter fieldAccessorFunc
1403
1404 // The empty value for the field.
1405 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001406
1407 // True if the property can support arch variants false otherwise.
1408 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001409}
1410
Paul Duffin4b8b7932020-05-06 12:35:38 +01001411func (p extractorProperty) String() string {
1412 return p.name
1413}
1414
Paul Duffinc097e362020-03-10 22:50:03 +00001415// Supports extracting common values from a number of instances of a properties
1416// structure into a separate common set of properties.
1417type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001418 // The properties that the extractor can optimize.
1419 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001420}
1421
1422// Create a new common value extractor for the structure type for the supplied
1423// properties struct.
1424//
1425// The returned extractor can be used on any properties structure of the same type
1426// as the supplied set of properties.
1427func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1428 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1429 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001430 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001431 return extractor
1432}
1433
1434// Gather the fields from the supplied structure type from which common values will
1435// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001436//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001437// This is recursive function. If it encounters a struct then it will recurse
1438// into it, passing in the accessor for the field and the struct name as prefix
1439// for the nested fields. That will then be used in the accessors for the fields
1440// in the embedded struct.
1441func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001442 for f := 0; f < structType.NumField(); f++ {
1443 field := structType.Field(f)
1444 if field.PkgPath != "" {
1445 // Ignore unexported fields.
1446 continue
1447 }
1448
Paul Duffinb07fa512020-03-10 22:17:04 +00001449 // Ignore fields whose value should be kept.
1450 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001451 continue
1452 }
1453
Paul Duffinc459f892020-04-30 18:08:29 +01001454 var filter extractorMetadataPredicate
1455
1456 // Add a filter
1457 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1458 filter = func(metadata propertiesContainer) bool {
1459 if m, ok := metadata.(isHostVariant); ok {
1460 if m.isHostVariant() {
1461 return false
1462 }
1463 }
1464 return true
1465 }
1466 }
1467
Paul Duffinc097e362020-03-10 22:50:03 +00001468 // Save a copy of the field index for use in the function.
1469 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001470
Martin Stjernholmb0249572020-09-15 02:32:35 +01001471 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001472
Paul Duffinc097e362020-03-10 22:50:03 +00001473 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001474 if containingStructAccessor != nil {
1475 // This is an embedded structure so first access the field for the embedded
1476 // structure.
1477 value = containingStructAccessor(value)
1478 }
1479
Paul Duffinc097e362020-03-10 22:50:03 +00001480 // Skip through interface and pointer values to find the structure.
1481 value = getStructValue(value)
1482
Paul Duffin4b8b7932020-05-06 12:35:38 +01001483 defer func() {
1484 if r := recover(); r != nil {
1485 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1486 }
1487 }()
1488
Paul Duffinc097e362020-03-10 22:50:03 +00001489 // Return the field.
1490 return value.Field(fieldIndex)
1491 }
1492
Martin Stjernholmb0249572020-09-15 02:32:35 +01001493 if field.Type.Kind() == reflect.Struct {
1494 // Gather fields from the nested or embedded structure.
1495 var subNamePrefix string
1496 if field.Anonymous {
1497 subNamePrefix = namePrefix
1498 } else {
1499 subNamePrefix = name + "."
1500 }
1501 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001502 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001503 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001504 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001505 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001506 fieldGetter,
1507 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001508 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001509 }
1510 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001511 }
Paul Duffinc097e362020-03-10 22:50:03 +00001512 }
1513}
1514
1515func getStructValue(value reflect.Value) reflect.Value {
1516foundStruct:
1517 for {
1518 kind := value.Kind()
1519 switch kind {
1520 case reflect.Interface, reflect.Ptr:
1521 value = value.Elem()
1522 case reflect.Struct:
1523 break foundStruct
1524 default:
1525 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1526 }
1527 }
1528 return value
1529}
1530
Paul Duffinf34f6d82020-04-30 15:48:31 +01001531// A container of properties to be optimized.
1532//
1533// Allows additional information to be associated with the properties, e.g. for
1534// filtering.
1535type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001536 fmt.Stringer
1537
Paul Duffinf34f6d82020-04-30 15:48:31 +01001538 // Get the properties that need optimizing.
1539 optimizableProperties() interface{}
1540}
1541
1542// A wrapper for dynamic member properties to allow them to be optimized.
1543type dynamicMemberPropertiesContainer struct {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001544 sdkVariant *sdk
Paul Duffinf34f6d82020-04-30 15:48:31 +01001545 dynamicMemberProperties interface{}
1546}
1547
1548func (c dynamicMemberPropertiesContainer) optimizableProperties() interface{} {
1549 return c.dynamicMemberProperties
1550}
1551
Paul Duffin4b8b7932020-05-06 12:35:38 +01001552func (c dynamicMemberPropertiesContainer) String() string {
1553 return c.sdkVariant.String()
1554}
1555
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001556// Extract common properties from a slice of property structures of the same type.
1557//
1558// All the property structures must be of the same type.
1559// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001560// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001561//
1562// Iterates over each exported field (capitalized name) and checks to see whether they
1563// have the same value (using DeepEquals) across all the input properties. If it does not then no
1564// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001565// and the field in each of the input properties structure is set to its default value. Nested
1566// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001567func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001568 commonPropertiesValue := reflect.ValueOf(commonProperties)
1569 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001570
Paul Duffinf34f6d82020-04-30 15:48:31 +01001571 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1572
Paul Duffinb28369a2020-05-04 15:39:59 +01001573 for _, property := range e.properties {
1574 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001575 filter := property.filter
1576 if filter == nil {
1577 filter = func(metadata propertiesContainer) bool {
1578 return true
1579 }
1580 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001581
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001582 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001583 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1584 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001585 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001586
Paul Duffin864e1b42020-05-06 10:23:19 +01001587 // Assume that all the values will be the same.
1588 //
1589 // While similar to this is not quite the same as commonValue == nil. If all the values
1590 // have been filtered out then this will be false but commonValue == nil will be true.
1591 valuesDiffer := false
1592
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001593 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001594 container := sliceValue.Index(i).Interface().(propertiesContainer)
1595 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001596 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001597
Paul Duffinc459f892020-04-30 18:08:29 +01001598 if !filter(container) {
1599 expectedValue := property.emptyValue.Interface()
1600 actualValue := fieldValue.Interface()
1601 if !reflect.DeepEqual(expectedValue, actualValue) {
1602 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1603 }
1604 continue
1605 }
1606
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001607 if commonValue == nil {
1608 // Use the first value as the commonProperties value.
1609 commonValue = &fieldValue
1610 } else {
1611 // If the value does not match the current common value then there is
1612 // no value in common so break out.
1613 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1614 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001615 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001616 break
1617 }
1618 }
1619 }
1620
Paul Duffin864e1b42020-05-06 10:23:19 +01001621 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001622 // and set the input struct's field to the empty value.
1623 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001624 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001625 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001626 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001627 container := sliceValue.Index(i).Interface().(propertiesContainer)
1628 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001629 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001630 fieldValue.Set(emptyValue)
1631 }
1632 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001633
1634 if valuesDiffer && !property.archVariant {
1635 // The values differ but the property does not support arch variants so it
1636 // is an error.
1637 var details strings.Builder
1638 for i := 0; i < sliceValue.Len(); i++ {
1639 container := sliceValue.Index(i).Interface().(propertiesContainer)
1640 itemValue := reflect.ValueOf(container.optimizableProperties())
1641 fieldValue := fieldGetter(itemValue)
1642
1643 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1644 }
1645
1646 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1647 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001648 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01001649
1650 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001651}