blob: 7bf5dea0abaf0fec90bb6ac657d3c199040d5568 [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) {
95 rb := android.NewRuleBuilder()
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).
Paul Duffin11108272020-05-11 22:59:25 +0100106 Text("echo").Text(proptools.ShellEscape(content)).
107 // 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)
111 rb.Build(pctx, ctx, gf.path.Base(), "Build "+gf.path.Base())
112}
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
291 // Create the snapshot module.
292 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000293 var snapshotModuleType string
294 if s.properties.Module_exports {
295 snapshotModuleType = "module_exports_snapshot"
296 } else {
297 snapshotModuleType = "sdk_snapshot"
298 }
299 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000300 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000301
302 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100303 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000304 if len(visibility) != 0 {
305 snapshotModule.AddProperty("visibility", visibility)
306 }
307
Paul Duffin865171e2020-03-02 18:38:15 +0000308 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000309
Paul Duffinf34f6d82020-04-30 15:48:31 +0100310 var dynamicMemberPropertiesContainers []propertiesContainer
Paul Duffin865171e2020-03-02 18:38:15 +0000311 osTypeToMemberProperties := make(map[android.OsType]*sdk)
312 for _, sdkVariant := range sdkVariants {
313 properties := sdkVariant.dynamicMemberTypeListProperties
314 osTypeToMemberProperties[sdkVariant.Target().Os] = sdkVariant
Paul Duffin4b8b7932020-05-06 12:35:38 +0100315 dynamicMemberPropertiesContainers = append(dynamicMemberPropertiesContainers, &dynamicMemberPropertiesContainer{sdkVariant, properties})
Paul Duffin865171e2020-03-02 18:38:15 +0000316 }
317
318 // Extract the common lists of members into a separate struct.
319 commonDynamicMemberProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffinc097e362020-03-10 22:50:03 +0000320 extractor := newCommonValueExtractor(commonDynamicMemberProperties)
Paul Duffin4b8b7932020-05-06 12:35:38 +0100321 extractCommonProperties(ctx, extractor, commonDynamicMemberProperties, dynamicMemberPropertiesContainers)
Paul Duffin865171e2020-03-02 18:38:15 +0000322
323 // Add properties common to all os types.
324 s.addMemberPropertiesToPropertySet(builder, snapshotModule, commonDynamicMemberProperties)
325
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100326 // Optimize other per-variant properties, besides the dynamic member lists.
327 type variantProperties struct {
328 Compile_multilib string `android:"arch_variant"`
329 }
330 var variantPropertiesContainers []propertiesContainer
331 variantToProperties := make(map[*sdk]*variantProperties)
332 for _, sdkVariant := range sdkVariants {
333 props := &variantProperties{
334 Compile_multilib: sdkVariant.multilibUsages.String(),
335 }
336 variantPropertiesContainers = append(variantPropertiesContainers, &dynamicMemberPropertiesContainer{sdkVariant, props})
337 variantToProperties[sdkVariant] = props
338 }
339 commonVariantProperties := variantProperties{}
340 extractor = newCommonValueExtractor(commonVariantProperties)
341 extractCommonProperties(ctx, extractor, &commonVariantProperties, variantPropertiesContainers)
342 if commonVariantProperties.Compile_multilib != "" && commonVariantProperties.Compile_multilib != "both" {
343 // Compile_multilib defaults to both so only needs to be set when it's
344 // specified and not both.
345 snapshotModule.AddProperty("compile_multilib", commonVariantProperties.Compile_multilib)
346 }
347
Paul Duffin6a7e9532020-03-20 17:50:07 +0000348 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100349
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100350 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000351 for _, osType := range s.getPossibleOsTypes() {
352 if sdkVariant, ok := osTypeToMemberProperties[osType]; ok {
353 osPropertySet := targetPropertySet.AddPropertySet(sdkVariant.Target().Os.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000354
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100355 variantProps := variantToProperties[sdkVariant]
356 if variantProps.Compile_multilib != "" && variantProps.Compile_multilib != "both" {
357 osPropertySet.AddProperty("compile_multilib", variantProps.Compile_multilib)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000358 }
359
Paul Duffin865171e2020-03-02 18:38:15 +0000360 s.addMemberPropertiesToPropertySet(builder, osPropertySet, sdkVariant.dynamicMemberTypeListProperties)
Paul Duffin13879572019-11-28 14:31:38 +0000361 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000362 }
Paul Duffin865171e2020-03-02 18:38:15 +0000363
Jiyong Park8fe14e62020-10-19 22:47:34 +0900364 // If host is supported and any member is host OS dependent then disable host
365 // by default, so that we can enable each host OS variant explicitly. This
366 // avoids problems with implicitly enabled OS variants when the snapshot is
367 // used, which might be different from this run (e.g. different build OS).
368 if s.HostSupported() {
369 var supportedHostTargets []string
370 for _, memberRef := range memberRefs {
371 if memberRef.memberType.IsHostOsDependent() && memberRef.variant.Target().Os.Class == android.Host {
372 targetString := memberRef.variant.Target().Os.String() + "_" + memberRef.variant.Target().Arch.ArchType.String()
373 if !android.InList(targetString, supportedHostTargets) {
374 supportedHostTargets = append(supportedHostTargets, targetString)
375 }
376 }
377 }
378 if len(supportedHostTargets) > 0 {
379 hostPropertySet := targetPropertySet.AddPropertySet("host")
380 hostPropertySet.AddProperty("enabled", false)
381 }
382 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
383 for _, hostTarget := range supportedHostTargets {
384 propertySet := targetPropertySet.AddPropertySet(hostTarget)
385 propertySet.AddProperty("enabled", true)
386 }
387 }
388
Paul Duffin865171e2020-03-02 18:38:15 +0000389 // Prune any empty property sets.
390 snapshotModule.transform(pruneEmptySetTransformer{})
391
Paul Duffinb645ec82019-11-27 17:43:54 +0000392 bpFile.AddModule(snapshotModule)
393
394 // generate Android.bp
395 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
396 generateBpContents(&bp.generatedContents, bpFile)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000397
Paul Duffinf88d8e02020-05-07 20:21:34 +0100398 contents := bp.content.String()
399 syntaxCheckSnapshotBpFile(ctx, contents)
400
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000401 bp.build(pctx, ctx, nil)
402
403 filesToZip := builder.filesToZip
Jiyong Park9b409bc2019-10-11 14:59:13 +0900404
Jiyong Park232e7852019-11-04 12:23:40 +0900405 // zip them all
Paul Duffin91547182019-11-12 19:39:36 +0000406 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000407 outputDesc := "Building snapshot for " + ctx.ModuleName()
408
409 // If there are no zips to merge then generate the output zip directly.
410 // Otherwise, generate an intermediate zip file into which other zips can be
411 // merged.
412 var zipFile android.OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000413 var desc string
414 if len(builder.zipsToMerge) == 0 {
415 zipFile = outputZipFile
Paul Duffin91547182019-11-12 19:39:36 +0000416 desc = outputDesc
417 } else {
418 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000419 desc = "Building intermediate snapshot for " + ctx.ModuleName()
420 }
421
Paul Duffin375058f2019-11-29 20:17:53 +0000422 ctx.Build(pctx, android.BuildParams{
423 Description: desc,
424 Rule: zipFiles,
425 Inputs: filesToZip,
426 Output: zipFile,
427 Args: map[string]string{
428 "basedir": builder.snapshotDir.String(),
429 },
430 })
Jiyong Park9b409bc2019-10-11 14:59:13 +0900431
Paul Duffin91547182019-11-12 19:39:36 +0000432 if len(builder.zipsToMerge) != 0 {
Paul Duffin375058f2019-11-29 20:17:53 +0000433 ctx.Build(pctx, android.BuildParams{
434 Description: outputDesc,
435 Rule: mergeZips,
436 Input: zipFile,
437 Inputs: builder.zipsToMerge,
438 Output: outputZipFile,
439 })
Paul Duffin91547182019-11-12 19:39:36 +0000440 }
441
442 return outputZipFile
Jiyong Park9b409bc2019-10-11 14:59:13 +0900443}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000444
Paul Duffinf88d8e02020-05-07 20:21:34 +0100445// Check the syntax of the generated Android.bp file contents and if they are
446// invalid then log an error with the contents (tagged with line numbers) and the
447// errors that were found so that it is easy to see where the problem lies.
448func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
449 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
450 if len(errs) != 0 {
451 message := &strings.Builder{}
452 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
453
454Generated Android.bp contents
455========================================================================
456`)
457 for i, line := range strings.Split(contents, "\n") {
458 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
459 }
460
461 _, _ = fmt.Fprint(message, `
462========================================================================
463
464Errors found:
465`)
466
467 for _, err := range errs {
468 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
469 }
470
471 ctx.ModuleErrorf("%s", message.String())
472 }
473}
474
Paul Duffin4b8b7932020-05-06 12:35:38 +0100475func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
476 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
477 if err != nil {
478 ctx.ModuleErrorf("error extracting common properties: %s", err)
479 }
480}
481
Paul Duffin865171e2020-03-02 18:38:15 +0000482func (s *sdk) addMemberPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, dynamicMemberTypeListProperties interface{}) {
483 for _, memberListProperty := range s.memberListProperties() {
484 names := memberListProperty.getter(dynamicMemberTypeListProperties)
485 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000486 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000487 }
488 }
489}
490
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000491type propertyTag struct {
492 name string
493}
494
Paul Duffin0cb37b92020-03-04 14:52:46 +0000495// A BpPropertyTag to add to a property that contains references to other sdk members.
496//
497// This will cause the references to be rewritten to a versioned reference in the version
498// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000499var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000500var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000501
Paul Duffin0cb37b92020-03-04 14:52:46 +0000502// A BpPropertyTag that indicates the property should only be present in the versioned
503// module.
504//
505// This will cause the property to be removed from the unversioned instance of a
506// snapshot module.
507var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
508
Paul Duffine6c0d842020-01-15 14:08:51 +0000509type unversionedToVersionedTransformation struct {
510 identityTransformation
511 builder *snapshotBuilder
512}
513
Paul Duffine6c0d842020-01-15 14:08:51 +0000514func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
515 // Use a versioned name for the module but remember the original name for the
516 // snapshot.
517 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000518 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000519 module.insertAfter("name", "sdk_member_name", name)
520 return module
521}
522
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000523func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000524 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
525 required := tag == requiredSdkMemberReferencePropertyTag
526 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000527 } else {
528 return value, tag
529 }
530}
531
Paul Duffin72910952020-01-20 18:16:30 +0000532type unversionedTransformation struct {
533 identityTransformation
534 builder *snapshotBuilder
535}
536
537func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
538 // If the module is an internal member then use a unique name for it.
539 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000540 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000541
542 // Set prefer: false - this is not strictly required as that is the default.
543 module.insertAfter("name", "prefer", false)
544
545 return module
546}
547
548func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000549 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
550 required := tag == requiredSdkMemberReferencePropertyTag
551 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000552 } else if tag == sdkVersionedOnlyPropertyTag {
553 // The property is not allowed in the unversioned module so remove it.
554 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000555 } else {
556 return value, tag
557 }
558}
559
Paul Duffina78f3a72020-02-21 16:29:35 +0000560type pruneEmptySetTransformer struct {
561 identityTransformation
562}
563
564var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
565
566func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
567 if len(propertySet.properties) == 0 {
568 return nil, nil
569 } else {
570 return propertySet, tag
571 }
572}
573
Paul Duffinb645ec82019-11-27 17:43:54 +0000574func generateBpContents(contents *generatedContents, bpFile *bpFile) {
575 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
576 for _, bpModule := range bpFile.order {
577 contents.Printfln("")
578 contents.Printfln("%s {", bpModule.moduleType)
Paul Duffincc72e982020-01-14 15:53:11 +0000579 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffinb645ec82019-11-27 17:43:54 +0000580 contents.Printfln("}")
581 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000582}
583
584func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
585 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000586
587 // Output the properties first, followed by the nested sets. This ensures a
588 // consistent output irrespective of whether property sets are created before
589 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000590 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000591 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000592
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000593 switch v := value.(type) {
594 case []string:
595 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000596 if length > 1 {
597 contents.Printfln("%s: [", name)
598 contents.Indent()
599 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000600 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000601 }
602 contents.Dedent()
603 contents.Printfln("],")
604 } else if length == 0 {
605 contents.Printfln("%s: [],", name)
606 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000607 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000608 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000609
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000610 case bool:
611 contents.Printfln("%s: %t,", name, v)
612
613 case *bpPropertySet:
614 // Do not write property sets in the properties phase.
Paul Duffinb645ec82019-11-27 17:43:54 +0000615
616 default:
617 contents.Printfln("%s: %q,", name, value)
618 }
619 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000620
621 for _, name := range set.order {
622 value := set.getValue(name)
623
624 // Only write property sets in the sets phase.
625 switch v := value.(type) {
626 case *bpPropertySet:
627 contents.Printfln("%s: {", name)
628 outputPropertySet(contents, v)
629 contents.Printfln("},")
630 }
631 }
632
Paul Duffinb645ec82019-11-27 17:43:54 +0000633 contents.Dedent()
634}
635
Paul Duffinac37c502019-11-26 18:02:20 +0000636func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000637 contents := &generatedContents{}
638 generateBpContents(contents, s.builderForTests.bpFile)
639 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000640}
641
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000642type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000643 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000644 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000645 version string
646 snapshotDir android.OutputPath
647 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000648
649 // Map from destination to source of each copy - used to eliminate duplicates and
650 // detect conflicts.
651 copies map[string]string
652
Paul Duffinb645ec82019-11-27 17:43:54 +0000653 filesToZip android.Paths
654 zipsToMerge android.Paths
655
656 prebuiltModules map[string]*bpModule
657 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000658
659 // The set of all members by name.
660 allMembersByName map[string]struct{}
661
662 // The set of exported members by name.
663 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000664}
665
666func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000667 if existing, ok := s.copies[dest]; ok {
668 if existing != src.String() {
669 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
670 return
671 }
672 } else {
673 path := s.snapshotDir.Join(s.ctx, dest)
674 s.ctx.Build(pctx, android.BuildParams{
675 Rule: android.Cp,
676 Input: src,
677 Output: path,
678 })
679 s.filesToZip = append(s.filesToZip, path)
680
681 s.copies[dest] = src.String()
682 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000683}
684
Paul Duffin91547182019-11-12 19:39:36 +0000685func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
686 ctx := s.ctx
687
688 // Repackage the zip file so that the entries are in the destDir directory.
689 // This will allow the zip file to be merged into the snapshot.
690 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000691
692 ctx.Build(pctx, android.BuildParams{
693 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
694 Rule: repackageZip,
695 Input: zipPath,
696 Output: tmpZipPath,
697 Args: map[string]string{
698 "destdir": destDir,
699 },
700 })
Paul Duffin91547182019-11-12 19:39:36 +0000701
702 // Add the repackaged zip file to the files to merge.
703 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
704}
705
Paul Duffin9d8d6092019-12-05 18:19:29 +0000706func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
707 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000708 if s.prebuiltModules[name] != nil {
709 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
710 }
711
712 m := s.bpFile.newModule(moduleType)
713 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000714
Paul Duffinbefa4b92020-03-04 14:22:45 +0000715 variant := member.Variants()[0]
716
Paul Duffin13f02712020-03-06 12:30:43 +0000717 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000718 // An internal member is only referenced from the sdk snapshot which is in the
719 // same package so can be marked as private.
720 m.AddProperty("visibility", []string{"//visibility:private"})
721 } else {
722 // Extract visibility information from a member variant. All variants have the same
723 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +0100724 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
725
726 // Add any additional visibility rules needed for the prebuilts to reference each other.
727 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
728 if err != nil {
729 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
730 }
731
732 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +0000733 if len(visibility) != 0 {
734 m.AddProperty("visibility", visibility)
735 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000736 }
737
Paul Duffin865171e2020-03-02 18:38:15 +0000738 deviceSupported := false
739 hostSupported := false
740
741 for _, variant := range member.Variants() {
742 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +0900743 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +0000744 hostSupported = true
745 } else if osClass == android.Device {
746 deviceSupported = true
747 }
748 }
749
750 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000751
Paul Duffinbefa4b92020-03-04 14:22:45 +0000752 // Where available copy apex_available properties from the member.
753 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
754 apexAvailable := apexAware.ApexAvailable()
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000755
Colin Cross440e0d02020-06-11 11:32:11 -0700756 // Add in any baseline apex available settings.
757 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000758
Paul Duffinbefa4b92020-03-04 14:22:45 +0000759 if len(apexAvailable) > 0 {
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000760 // Remove duplicates and sort.
761 apexAvailable = android.FirstUniqueStrings(apexAvailable)
762 sort.Strings(apexAvailable)
763
Paul Duffinbefa4b92020-03-04 14:22:45 +0000764 m.AddProperty("apex_available", apexAvailable)
765 }
766 }
767
Paul Duffin0cb37b92020-03-04 14:52:46 +0000768 // Disable installation in the versioned module of those modules that are ever installable.
769 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
770 if installable.EverInstallable() {
771 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
772 }
773 }
774
Paul Duffinb645ec82019-11-27 17:43:54 +0000775 s.prebuiltModules[name] = m
776 s.prebuiltOrder = append(s.prebuiltOrder, m)
777 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000778}
779
Paul Duffin865171e2020-03-02 18:38:15 +0000780func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
781 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000782 bpModule.AddProperty("device_supported", false)
783 }
Paul Duffin865171e2020-03-02 18:38:15 +0000784 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000785 bpModule.AddProperty("host_supported", true)
786 }
787}
788
Paul Duffin13f02712020-03-06 12:30:43 +0000789func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
790 if required {
791 return requiredSdkMemberReferencePropertyTag
792 } else {
793 return optionalSdkMemberReferencePropertyTag
794 }
795}
796
797func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
798 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000799}
800
Paul Duffinb645ec82019-11-27 17:43:54 +0000801// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +0000802func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
803 if _, ok := s.allMembersByName[unversionedName]; !ok {
804 if required {
805 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
806 }
807 return unversionedName
808 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000809 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
810}
Paul Duffinb645ec82019-11-27 17:43:54 +0000811
Paul Duffin13f02712020-03-06 12:30:43 +0000812func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000813 var references []string = nil
814 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000815 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000816 }
817 return references
818}
Paul Duffin13879572019-11-28 14:31:38 +0000819
Paul Duffin72910952020-01-20 18:16:30 +0000820// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +0000821func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
822 if _, ok := s.allMembersByName[unversionedName]; !ok {
823 if required {
824 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
825 }
826 return unversionedName
827 }
828
829 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +0000830 return s.ctx.ModuleName() + "_" + unversionedName
831 } else {
832 return unversionedName
833 }
834}
835
Paul Duffin13f02712020-03-06 12:30:43 +0000836func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +0000837 var references []string = nil
838 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000839 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +0000840 }
841 return references
842}
843
Paul Duffin13f02712020-03-06 12:30:43 +0000844func (s *snapshotBuilder) isInternalMember(memberName string) bool {
845 _, ok := s.exportedMembersByName[memberName]
846 return !ok
847}
848
Martin Stjernholm89238f42020-07-10 00:14:03 +0100849// Add the properties from the given SdkMemberProperties to the blueprint
850// property set. This handles common properties in SdkMemberPropertiesBase and
851// calls the member-specific AddToPropertySet for the rest.
852func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
853 if memberProperties.Base().Compile_multilib != "" {
854 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
855 }
856
857 memberProperties.AddToPropertySet(ctx, targetPropertySet)
858}
859
Paul Duffin1356d8c2020-02-25 19:26:33 +0000860type sdkMemberRef struct {
861 memberType android.SdkMemberType
862 variant android.SdkAware
863}
864
Paul Duffin13879572019-11-28 14:31:38 +0000865var _ android.SdkMember = (*sdkMember)(nil)
866
867type sdkMember struct {
868 memberType android.SdkMemberType
869 name string
870 variants []android.SdkAware
871}
872
873func (m *sdkMember) Name() string {
874 return m.name
875}
876
877func (m *sdkMember) Variants() []android.SdkAware {
878 return m.variants
879}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000880
Paul Duffin9c3760e2020-03-16 19:52:08 +0000881// Track usages of multilib variants.
882type multilibUsage int
883
884const (
885 multilibNone multilibUsage = 0
886 multilib32 multilibUsage = 1
887 multilib64 multilibUsage = 2
888 multilibBoth = multilib32 | multilib64
889)
890
891// Add the multilib that is used in the arch type.
892func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
893 multilib := archType.Multilib
894 switch multilib {
895 case "":
896 return m
897 case "lib32":
898 return m | multilib32
899 case "lib64":
900 return m | multilib64
901 default:
902 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
903 }
904}
905
906func (m multilibUsage) String() string {
907 switch m {
908 case multilibNone:
909 return ""
910 case multilib32:
911 return "32"
912 case multilib64:
913 return "64"
914 case multilibBoth:
915 return "both"
916 default:
917 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
918 m, multilibNone, multilib32, multilib64, multilibBoth))
919 }
920}
921
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000922type baseInfo struct {
923 Properties android.SdkMemberProperties
924}
925
Paul Duffinf34f6d82020-04-30 15:48:31 +0100926func (b *baseInfo) optimizableProperties() interface{} {
927 return b.Properties
928}
929
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000930type osTypeSpecificInfo struct {
931 baseInfo
932
Paul Duffin00e46802020-03-12 20:40:35 +0000933 osType android.OsType
934
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000935 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +0000936 //
937 // Nil if there is one variant whose arch type is common
938 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000939}
940
Paul Duffin4b8b7932020-05-06 12:35:38 +0100941var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
942
Paul Duffinfc8dd232020-03-17 12:51:37 +0000943type variantPropertiesFactoryFunc func() android.SdkMemberProperties
944
Paul Duffin00e46802020-03-12 20:40:35 +0000945// Create a new osTypeSpecificInfo for the specified os type and its properties
946// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000947func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +0000948 osInfo := &osTypeSpecificInfo{
949 osType: osType,
950 }
951
952 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
953 properties := variantPropertiesFactory()
954 properties.Base().Os = osType
955 return properties
956 }
957
958 // Create a structure into which properties common across the architectures in
959 // this os type will be stored.
960 osInfo.Properties = osSpecificVariantPropertiesFactory()
961
962 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000963 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +0000964 var archTypes []android.ArchType
965 for _, variant := range osTypeVariants {
966 archType := variant.Target().Arch.ArchType
967 archTypeName := archType.Name
968 if _, ok := variantsByArchName[archTypeName]; !ok {
969 archTypes = append(archTypes, archType)
970 }
971
972 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
973 }
974
975 if commonVariants, ok := variantsByArchName["common"]; ok {
976 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -0700977 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 +0000978 }
979
980 // A common arch type only has one variant and its properties should be treated
981 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000982 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +0000983 } else {
984 // Create an arch specific info for each supported architecture type.
985 for _, archType := range archTypes {
986 archTypeName := archType.Name
987
988 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +0900989 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +0000990
991 osInfo.archInfos = append(osInfo.archInfos, archInfo)
992 }
993 }
994
995 return osInfo
996}
997
998// Optimize the properties by extracting common properties from arch type specific
999// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001000func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001001 // Nothing to do if there is only a single common architecture.
1002 if len(osInfo.archInfos) == 0 {
1003 return
1004 }
1005
Paul Duffin9c3760e2020-03-16 19:52:08 +00001006 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001007 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001008 multilib = multilib.addArchType(archInfo.archType)
1009
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001010 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001011 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001012 }
1013
Paul Duffin4b8b7932020-05-06 12:35:38 +01001014 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001015
1016 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001017 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001018}
1019
1020// Add the properties for an os to a property set.
1021//
1022// Maps the properties related to the os variants through to an appropriate
1023// module structure that will produce equivalent set of variants when it is
1024// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001025func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001026
1027 var osPropertySet android.BpPropertySet
1028 var archPropertySet android.BpPropertySet
1029 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001030 if osInfo.Properties.Base().Os_count == 1 &&
1031 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1032 // There is only one OS type present in the variants and it shouldn't have a
1033 // variant-specific target. The latter is the case if it's either for device
1034 // where there is only one OS (android), or for host and the member type
1035 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001036
1037 // Create a structure that looks like:
1038 // module_type {
1039 // name: "...",
1040 // ...
1041 // <common properties>
1042 // ...
1043 // <single os type specific properties>
1044 //
1045 // arch: {
1046 // <arch specific sections>
1047 // }
1048 //
1049 osPropertySet = bpModule
1050 archPropertySet = osPropertySet.AddPropertySet("arch")
1051
1052 // Arch specific properties need to be added to an arch specific section
1053 // within arch.
1054 archOsPrefix = ""
1055 } else {
1056 // Create a structure that looks like:
1057 // module_type {
1058 // name: "...",
1059 // ...
1060 // <common properties>
1061 // ...
1062 // target: {
1063 // <arch independent os specific sections, e.g. android>
1064 // ...
1065 // <arch and os specific sections, e.g. android_x86>
1066 // }
1067 //
1068 osType := osInfo.osType
1069 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1070 archPropertySet = targetPropertySet
1071
1072 // Arch specific properties need to be added to an os and arch specific
1073 // section prefixed with <os>_.
1074 archOsPrefix = osType.Name + "_"
1075 }
1076
1077 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001078 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001079
1080 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1081 // os) specific properties.
1082 //
1083 // The archInfos list will be empty if the os contains variants for the common
1084 // architecture.
1085 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001086 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001087 }
1088}
1089
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001090func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1091 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001092 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001093}
1094
1095var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1096
Paul Duffin4b8b7932020-05-06 12:35:38 +01001097func (osInfo *osTypeSpecificInfo) String() string {
1098 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1099}
1100
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001101type archTypeSpecificInfo struct {
1102 baseInfo
1103
1104 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001105 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001106
1107 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001108}
1109
Paul Duffin4b8b7932020-05-06 12:35:38 +01001110var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1111
Paul Duffinfc8dd232020-03-17 12:51:37 +00001112// Create a new archTypeSpecificInfo for the specified arch type and its properties
1113// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001114func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001115
Paul Duffinfc8dd232020-03-17 12:51:37 +00001116 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001117 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001118
1119 // Create the properties into which the arch type specific properties will be
1120 // added.
1121 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001122
1123 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001124 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001125 } else {
1126 // There is more than one variant for this arch type which must be differentiated
1127 // by link type.
1128 for _, linkVariant := range archVariants {
1129 linkType := getLinkType(linkVariant)
1130 if linkType == "" {
1131 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1132 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001133 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001134
1135 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1136 }
1137 }
1138 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001139
1140 return archInfo
1141}
1142
Paul Duffinf34f6d82020-04-30 15:48:31 +01001143func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1144 return archInfo.Properties
1145}
1146
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001147// Get the link type of the variant
1148//
1149// If the variant is not differentiated by link type then it returns "",
1150// otherwise it returns one of "static" or "shared".
1151func getLinkType(variant android.Module) string {
1152 linkType := ""
1153 if linkable, ok := variant.(cc.LinkableInterface); ok {
1154 if linkable.Shared() && linkable.Static() {
1155 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1156 } else if linkable.Shared() {
1157 linkType = "shared"
1158 } else if linkable.Static() {
1159 linkType = "static"
1160 } else {
1161 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1162 }
1163 }
1164 return linkType
1165}
1166
1167// Optimize the properties by extracting common properties from link type specific
1168// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001169func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001170 if len(archInfo.linkInfos) == 0 {
1171 return
1172 }
1173
Paul Duffin4b8b7932020-05-06 12:35:38 +01001174 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001175}
1176
Paul Duffinfc8dd232020-03-17 12:51:37 +00001177// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001178func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001179 archTypeName := archInfo.archType.Name
1180 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001181 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1182 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1183 archTypePropertySet.AddProperty("enabled", true)
1184 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001185 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001186
1187 for _, linkInfo := range archInfo.linkInfos {
1188 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001189 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001190 }
1191}
1192
Paul Duffin4b8b7932020-05-06 12:35:38 +01001193func (archInfo *archTypeSpecificInfo) String() string {
1194 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1195}
1196
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001197type linkTypeSpecificInfo struct {
1198 baseInfo
1199
1200 linkType string
1201}
1202
Paul Duffin4b8b7932020-05-06 12:35:38 +01001203var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1204
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001205// Create a new linkTypeSpecificInfo for the specified link type and its properties
1206// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001207func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001208 linkInfo := &linkTypeSpecificInfo{
1209 baseInfo: baseInfo{
1210 // Create the properties into which the link type specific properties will be
1211 // added.
1212 Properties: variantPropertiesFactory(),
1213 },
1214 linkType: linkType,
1215 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001216 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001217 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001218}
1219
Paul Duffin4b8b7932020-05-06 12:35:38 +01001220func (l *linkTypeSpecificInfo) String() string {
1221 return fmt.Sprintf("LinkType{%s}", l.linkType)
1222}
1223
Paul Duffin3a4eb502020-03-19 16:11:18 +00001224type memberContext struct {
1225 sdkMemberContext android.ModuleContext
1226 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001227 memberType android.SdkMemberType
1228 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001229}
1230
1231func (m *memberContext) SdkModuleContext() android.ModuleContext {
1232 return m.sdkMemberContext
1233}
1234
1235func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1236 return m.builder
1237}
1238
Paul Duffina551a1c2020-03-17 21:04:24 +00001239func (m *memberContext) MemberType() android.SdkMemberType {
1240 return m.memberType
1241}
1242
1243func (m *memberContext) Name() string {
1244 return m.name
1245}
1246
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001247func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001248
1249 memberType := member.memberType
1250
Paul Duffina04c1072020-03-02 10:16:35 +00001251 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001252 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001253 variants := member.Variants()
1254 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001255 osType := variant.Target().Os
1256 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001257 }
1258
Paul Duffina04c1072020-03-02 10:16:35 +00001259 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001260 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001261 properties := memberType.CreateVariantPropertiesStruct()
1262 base := properties.Base()
1263 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001264 return properties
1265 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001266
Paul Duffina04c1072020-03-02 10:16:35 +00001267 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001268
Paul Duffina04c1072020-03-02 10:16:35 +00001269 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001270 commonProperties := variantPropertiesFactory()
1271 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001272
Paul Duffinc097e362020-03-10 22:50:03 +00001273 // Create common value extractor that can be used to optimize the properties.
1274 commonValueExtractor := newCommonValueExtractor(commonProperties)
1275
Paul Duffina04c1072020-03-02 10:16:35 +00001276 // The list of property structures which are os type specific but common across
1277 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001278 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001279
1280 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001281 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001282 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001283 // Add the os specific properties to a list of os type specific yet architecture
1284 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001285 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001286
Paul Duffin00e46802020-03-12 20:40:35 +00001287 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001288 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001289 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001290
Paul Duffina04c1072020-03-02 10:16:35 +00001291 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001292 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001293
Paul Duffina04c1072020-03-02 10:16:35 +00001294 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001295 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001296
Paul Duffina04c1072020-03-02 10:16:35 +00001297 // Create a target property set into which target specific properties can be
1298 // added.
1299 targetPropertySet := bpModule.AddPropertySet("target")
1300
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001301 // If the member is host OS dependent and has host_supported then disable by
1302 // default and enable each host OS variant explicitly. This avoids problems
1303 // with implicitly enabled OS variants when the snapshot is used, which might
1304 // be different from this run (e.g. different build OS).
1305 if ctx.memberType.IsHostOsDependent() {
1306 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1307 if hostSupported {
1308 hostPropertySet := targetPropertySet.AddPropertySet("host")
1309 hostPropertySet.AddProperty("enabled", false)
1310 }
1311 }
1312
Paul Duffina04c1072020-03-02 10:16:35 +00001313 // Iterate over the os types in a fixed order.
1314 for _, osType := range s.getPossibleOsTypes() {
1315 osInfo := osTypeToInfo[osType]
1316 if osInfo == nil {
1317 continue
1318 }
1319
Paul Duffin3a4eb502020-03-19 16:11:18 +00001320 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001321 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001322}
1323
Paul Duffina04c1072020-03-02 10:16:35 +00001324// Compute the list of possible os types that this sdk could support.
1325func (s *sdk) getPossibleOsTypes() []android.OsType {
1326 var osTypes []android.OsType
1327 for _, osType := range android.OsTypeList {
1328 if s.DeviceSupported() {
1329 if osType.Class == android.Device && osType != android.Fuchsia {
1330 osTypes = append(osTypes, osType)
1331 }
1332 }
1333 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001334 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001335 osTypes = append(osTypes, osType)
1336 }
1337 }
1338 }
1339 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1340 return osTypes
1341}
1342
Paul Duffinb28369a2020-05-04 15:39:59 +01001343// Given a set of properties (struct value), return the value of the field within that
1344// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001345type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1346
Paul Duffinc459f892020-04-30 18:08:29 +01001347// Checks the metadata to determine whether the property should be ignored for the
1348// purposes of common value extraction or not.
1349type extractorMetadataPredicate func(metadata propertiesContainer) bool
1350
1351// Indicates whether optimizable properties are provided by a host variant or
1352// not.
1353type isHostVariant interface {
1354 isHostVariant() bool
1355}
1356
Paul Duffinb28369a2020-05-04 15:39:59 +01001357// A property that can be optimized by the commonValueExtractor.
1358type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001359 // The name of the field for this property. It is a "."-separated path for
1360 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001361 name string
1362
Paul Duffinc459f892020-04-30 18:08:29 +01001363 // Filter that can use metadata associated with the properties being optimized
1364 // to determine whether the field should be ignored during common value
1365 // optimization.
1366 filter extractorMetadataPredicate
1367
Paul Duffinb28369a2020-05-04 15:39:59 +01001368 // Retrieves the value on which common value optimization will be performed.
1369 getter fieldAccessorFunc
1370
1371 // The empty value for the field.
1372 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001373
1374 // True if the property can support arch variants false otherwise.
1375 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001376}
1377
Paul Duffin4b8b7932020-05-06 12:35:38 +01001378func (p extractorProperty) String() string {
1379 return p.name
1380}
1381
Paul Duffinc097e362020-03-10 22:50:03 +00001382// Supports extracting common values from a number of instances of a properties
1383// structure into a separate common set of properties.
1384type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001385 // The properties that the extractor can optimize.
1386 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001387}
1388
1389// Create a new common value extractor for the structure type for the supplied
1390// properties struct.
1391//
1392// The returned extractor can be used on any properties structure of the same type
1393// as the supplied set of properties.
1394func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1395 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1396 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001397 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001398 return extractor
1399}
1400
1401// Gather the fields from the supplied structure type from which common values will
1402// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001403//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001404// This is recursive function. If it encounters a struct then it will recurse
1405// into it, passing in the accessor for the field and the struct name as prefix
1406// for the nested fields. That will then be used in the accessors for the fields
1407// in the embedded struct.
1408func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001409 for f := 0; f < structType.NumField(); f++ {
1410 field := structType.Field(f)
1411 if field.PkgPath != "" {
1412 // Ignore unexported fields.
1413 continue
1414 }
1415
Paul Duffinb07fa512020-03-10 22:17:04 +00001416 // Ignore fields whose value should be kept.
1417 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001418 continue
1419 }
1420
Paul Duffinc459f892020-04-30 18:08:29 +01001421 var filter extractorMetadataPredicate
1422
1423 // Add a filter
1424 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1425 filter = func(metadata propertiesContainer) bool {
1426 if m, ok := metadata.(isHostVariant); ok {
1427 if m.isHostVariant() {
1428 return false
1429 }
1430 }
1431 return true
1432 }
1433 }
1434
Paul Duffinc097e362020-03-10 22:50:03 +00001435 // Save a copy of the field index for use in the function.
1436 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001437
Martin Stjernholmb0249572020-09-15 02:32:35 +01001438 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001439
Paul Duffinc097e362020-03-10 22:50:03 +00001440 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001441 if containingStructAccessor != nil {
1442 // This is an embedded structure so first access the field for the embedded
1443 // structure.
1444 value = containingStructAccessor(value)
1445 }
1446
Paul Duffinc097e362020-03-10 22:50:03 +00001447 // Skip through interface and pointer values to find the structure.
1448 value = getStructValue(value)
1449
Paul Duffin4b8b7932020-05-06 12:35:38 +01001450 defer func() {
1451 if r := recover(); r != nil {
1452 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1453 }
1454 }()
1455
Paul Duffinc097e362020-03-10 22:50:03 +00001456 // Return the field.
1457 return value.Field(fieldIndex)
1458 }
1459
Martin Stjernholmb0249572020-09-15 02:32:35 +01001460 if field.Type.Kind() == reflect.Struct {
1461 // Gather fields from the nested or embedded structure.
1462 var subNamePrefix string
1463 if field.Anonymous {
1464 subNamePrefix = namePrefix
1465 } else {
1466 subNamePrefix = name + "."
1467 }
1468 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001469 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001470 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001471 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001472 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001473 fieldGetter,
1474 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001475 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001476 }
1477 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001478 }
Paul Duffinc097e362020-03-10 22:50:03 +00001479 }
1480}
1481
1482func getStructValue(value reflect.Value) reflect.Value {
1483foundStruct:
1484 for {
1485 kind := value.Kind()
1486 switch kind {
1487 case reflect.Interface, reflect.Ptr:
1488 value = value.Elem()
1489 case reflect.Struct:
1490 break foundStruct
1491 default:
1492 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1493 }
1494 }
1495 return value
1496}
1497
Paul Duffinf34f6d82020-04-30 15:48:31 +01001498// A container of properties to be optimized.
1499//
1500// Allows additional information to be associated with the properties, e.g. for
1501// filtering.
1502type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001503 fmt.Stringer
1504
Paul Duffinf34f6d82020-04-30 15:48:31 +01001505 // Get the properties that need optimizing.
1506 optimizableProperties() interface{}
1507}
1508
1509// A wrapper for dynamic member properties to allow them to be optimized.
1510type dynamicMemberPropertiesContainer struct {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001511 sdkVariant *sdk
Paul Duffinf34f6d82020-04-30 15:48:31 +01001512 dynamicMemberProperties interface{}
1513}
1514
1515func (c dynamicMemberPropertiesContainer) optimizableProperties() interface{} {
1516 return c.dynamicMemberProperties
1517}
1518
Paul Duffin4b8b7932020-05-06 12:35:38 +01001519func (c dynamicMemberPropertiesContainer) String() string {
1520 return c.sdkVariant.String()
1521}
1522
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001523// Extract common properties from a slice of property structures of the same type.
1524//
1525// All the property structures must be of the same type.
1526// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001527// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001528//
1529// Iterates over each exported field (capitalized name) and checks to see whether they
1530// have the same value (using DeepEquals) across all the input properties. If it does not then no
1531// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001532// and the field in each of the input properties structure is set to its default value. Nested
1533// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001534func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001535 commonPropertiesValue := reflect.ValueOf(commonProperties)
1536 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001537
Paul Duffinf34f6d82020-04-30 15:48:31 +01001538 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1539
Paul Duffinb28369a2020-05-04 15:39:59 +01001540 for _, property := range e.properties {
1541 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001542 filter := property.filter
1543 if filter == nil {
1544 filter = func(metadata propertiesContainer) bool {
1545 return true
1546 }
1547 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001548
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001549 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001550 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1551 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001552 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001553
Paul Duffin864e1b42020-05-06 10:23:19 +01001554 // Assume that all the values will be the same.
1555 //
1556 // While similar to this is not quite the same as commonValue == nil. If all the values
1557 // have been filtered out then this will be false but commonValue == nil will be true.
1558 valuesDiffer := false
1559
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001560 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001561 container := sliceValue.Index(i).Interface().(propertiesContainer)
1562 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001563 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001564
Paul Duffinc459f892020-04-30 18:08:29 +01001565 if !filter(container) {
1566 expectedValue := property.emptyValue.Interface()
1567 actualValue := fieldValue.Interface()
1568 if !reflect.DeepEqual(expectedValue, actualValue) {
1569 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1570 }
1571 continue
1572 }
1573
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001574 if commonValue == nil {
1575 // Use the first value as the commonProperties value.
1576 commonValue = &fieldValue
1577 } else {
1578 // If the value does not match the current common value then there is
1579 // no value in common so break out.
1580 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1581 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001582 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001583 break
1584 }
1585 }
1586 }
1587
Paul Duffin864e1b42020-05-06 10:23:19 +01001588 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001589 // and set the input struct's field to the empty value.
1590 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001591 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001592 fieldGetter(commonStructValue).Set(*commonValue)
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 fieldValue.Set(emptyValue)
1598 }
1599 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001600
1601 if valuesDiffer && !property.archVariant {
1602 // The values differ but the property does not support arch variants so it
1603 // is an error.
1604 var details strings.Builder
1605 for i := 0; i < sliceValue.Len(); i++ {
1606 container := sliceValue.Index(i).Interface().(propertiesContainer)
1607 itemValue := reflect.ValueOf(container.optimizableProperties())
1608 fieldValue := fieldGetter(itemValue)
1609
1610 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1611 }
1612
1613 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1614 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001615 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01001616
1617 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001618}