blob: 8b75da27abedc108fd6eae7115fd454d0c3169e2 [file] [log] [blame]
Jiyong Park9b409bc2019-10-11 14:59:13 +09001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package sdk
16
17import (
18 "fmt"
Paul Duffinb645ec82019-11-27 17:43:54 +000019 "reflect"
Paul Duffina04c1072020-03-02 10:16:35 +000020 "sort"
Jiyong Park9b409bc2019-10-11 14:59:13 +090021 "strings"
22
Paul Duffin7d74e7b2020-03-06 12:30:13 +000023 "android/soong/apex"
Paul Duffin9b76c0b2020-03-12 10:24:35 +000024 "android/soong/cc"
Colin Cross440e0d02020-06-11 11:32:11 -070025
Paul Duffin375058f2019-11-29 20:17:53 +000026 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090027 "github.com/google/blueprint/proptools"
28
29 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090030)
31
32var pctx = android.NewPackageContext("android/soong/sdk")
33
Paul Duffin375058f2019-11-29 20:17:53 +000034var (
35 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
36 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000037 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000038 CommandDeps: []string{
39 "${config.Zip2ZipCmd}",
40 },
41 },
42 "destdir")
43
44 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
45 blueprint.RuleParams{
Colin Cross053fca12020-08-19 13:51:47 -070046 Command: `${config.SoongZipCmd} -C $basedir -r $out.rsp -o $out`,
Paul Duffin375058f2019-11-29 20:17:53 +000047 CommandDeps: []string{
48 "${config.SoongZipCmd}",
49 },
50 Rspfile: "$out.rsp",
51 RspfileContent: "$in",
52 },
53 "basedir")
54
55 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
56 blueprint.RuleParams{
57 Command: `${config.MergeZipsCmd} $out $in`,
58 CommandDeps: []string{
59 "${config.MergeZipsCmd}",
60 },
61 })
62)
63
Paul Duffinb645ec82019-11-27 17:43:54 +000064type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090065 content strings.Builder
66 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090067}
68
Paul Duffinb645ec82019-11-27 17:43:54 +000069// generatedFile abstracts operations for writing contents into a file and emit a build rule
70// for the file.
71type generatedFile struct {
72 generatedContents
73 path android.OutputPath
74}
75
Jiyong Park232e7852019-11-04 12:23:40 +090076func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +090077 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +000078 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +090079 }
80}
81
Paul Duffinb645ec82019-11-27 17:43:54 +000082func (gc *generatedContents) Indent() {
83 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +090084}
85
Paul Duffinb645ec82019-11-27 17:43:54 +000086func (gc *generatedContents) Dedent() {
87 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +090088}
89
Paul Duffinb645ec82019-11-27 17:43:54 +000090func (gc *generatedContents) Printfln(format string, args ...interface{}) {
Paul Duffin11108272020-05-11 22:59:25 +010091 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format+"\n", args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +090092}
93
94func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
Colin Crossf1a035e2020-11-16 17:32:30 -080095 rb := android.NewRuleBuilder(pctx, ctx)
Paul Duffin11108272020-05-11 22:59:25 +010096
97 content := gf.content.String()
98
99 // ninja consumes newline characters in rspfile_content. Prevent it by
100 // escaping the backslash in the newline character. The extra backslash
101 // is removed when the rspfile is written to the actual script file
102 content = strings.ReplaceAll(content, "\n", "\\n")
103
Jiyong Park9b409bc2019-10-11 14:59:13 +0900104 rb.Command().
105 Implicits(implicits).
Martin Stjernholmee9b24e2021-04-20 15:54:21 +0100106 Text("echo -n").Text(proptools.ShellEscape(content)).
Paul Duffin11108272020-05-11 22:59:25 +0100107 // convert \\n to \n
Jiyong Park9b409bc2019-10-11 14:59:13 +0900108 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
109 rb.Command().
110 Text("chmod a+x").Output(gf.path)
Colin Crossf1a035e2020-11-16 17:32:30 -0800111 rb.Build(gf.path.Base(), "Build "+gf.path.Base())
Jiyong Park9b409bc2019-10-11 14:59:13 +0900112}
113
Paul Duffin13879572019-11-28 14:31:38 +0000114// Collect all the members.
115//
Paul Duffincc3132e2021-04-24 01:10:30 +0100116// Updates the sdk module with a list of sdkMemberVariantDeps and details as to which multilibs
117// (32/64/both) are used by this sdk variant.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000118func (s *sdk) collectMembers(ctx android.ModuleContext) {
119 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000120 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
121 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000122 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
123 memberType := memberTag.SdkMemberType()
Jiyong Park9b409bc2019-10-11 14:59:13 +0900124
Paul Duffin13879572019-11-28 14:31:38 +0000125 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000126 if !memberType.IsInstance(child) {
127 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900128 }
Paul Duffin13879572019-11-28 14:31:38 +0000129
Paul Duffin6a7e9532020-03-20 17:50:07 +0000130 // Keep track of which multilib variants are used by the sdk.
131 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
132
Paul Duffin21827262021-04-24 12:16:36 +0100133 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{memberType, child.(android.SdkAware)})
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000134
135 // If the member type supports transitive sdk members then recurse down into
136 // its dependencies, otherwise exit traversal.
137 return memberType.HasTransitiveSdkMembers()
Jiyong Park73c54ee2019-10-22 20:31:18 +0900138 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000139
140 return false
Paul Duffin13879572019-11-28 14:31:38 +0000141 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000142}
143
Paul Duffincc3132e2021-04-24 01:10:30 +0100144// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
145// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000146//
Paul Duffincc3132e2021-04-24 01:10:30 +0100147// The sdkMember instances are then grouped into slices by member type. Within each such slice the
148// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000149//
Paul Duffincc3132e2021-04-24 01:10:30 +0100150// Finally, the member type slices are concatenated together to form a single slice. The order in
151// which they are concatenated is the order in which the member types were registered in the
152// android.SdkMemberTypesRegistry.
153func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000154 byType := make(map[android.SdkMemberType][]*sdkMember)
155 byName := make(map[string]*sdkMember)
156
Paul Duffin21827262021-04-24 12:16:36 +0100157 for _, memberVariantDep := range memberVariantDeps {
158 memberType := memberVariantDep.memberType
159 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000160
161 name := ctx.OtherModuleName(variant)
162 member := byName[name]
163 if member == nil {
164 member = &sdkMember{memberType: memberType, name: name}
165 byName[name] = member
166 byType[memberType] = append(byType[memberType], member)
167 }
168
Paul Duffin1356d8c2020-02-25 19:26:33 +0000169 // Only append new variants to the list. This is needed because a member can be both
170 // exported by the sdk and also be a transitive sdk member.
171 member.variants = appendUniqueVariants(member.variants, variant)
172 }
173
Paul Duffin13879572019-11-28 14:31:38 +0000174 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000175 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000176 membersOfType := byType[memberListProperty.memberType]
177 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900178 }
179
Paul Duffin6a7e9532020-03-20 17:50:07 +0000180 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900181}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900182
Paul Duffin72910952020-01-20 18:16:30 +0000183func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
184 for _, v := range variants {
185 if v == newVariant {
186 return variants
187 }
188 }
189 return append(variants, newVariant)
190}
191
Jiyong Park73c54ee2019-10-22 20:31:18 +0900192// SDK directory structure
193// <sdk_root>/
194// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
195// <api_ver>/ : below this directory are all auto-generated
196// Android.bp : definition of 'sdk_snapshot' module is here
197// aidl/
198// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
199// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900200// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900201// include/
202// bionic/libc/include/stdlib.h : an exported header file
203// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900204// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900205// <arch>/include/ : arch-specific exported headers
206// <arch>/include_gen/ : arch-specific generated headers
207// <arch>/lib/
208// libFoo.so : a stub library
209
Jiyong Park232e7852019-11-04 12:23:40 +0900210// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900211// This isn't visible to users, so could be changed in future.
212func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
213 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
214}
215
Jiyong Park232e7852019-11-04 12:23:40 +0900216// buildSnapshot is the main function in this source file. It creates rules to copy
217// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000218func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
219
Paul Duffin13f02712020-03-06 12:30:43 +0000220 allMembersByName := make(map[string]struct{})
221 exportedMembersByName := make(map[string]struct{})
Paul Duffin21827262021-04-24 12:16:36 +0100222 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000223 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100224 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffin865171e2020-03-02 18:38:15 +0000225
Paul Duffin13f02712020-03-06 12:30:43 +0000226 // Record the names of all the members, both explicitly specified and implicitly
227 // included.
Paul Duffin21827262021-04-24 12:16:36 +0100228 for _, memberVariantDep := range sdkVariant.memberVariantDeps {
229 allMembersByName[memberVariantDep.variant.Name()] = struct{}{}
Paul Duffin13f02712020-03-06 12:30:43 +0000230 }
231
Paul Duffin865171e2020-03-02 18:38:15 +0000232 // Merge the exported member sets from all sdk variants.
233 for key, _ := range sdkVariant.getExportedMembers() {
Paul Duffin13f02712020-03-06 12:30:43 +0000234 exportedMembersByName[key] = struct{}{}
Paul Duffin865171e2020-03-02 18:38:15 +0000235 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000236 }
237
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000238 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900239
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000240 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000241
242 bpFile := &bpFile{
243 modules: make(map[string]*bpModule),
244 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000245
246 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000247 ctx: ctx,
248 sdk: s,
249 version: "current",
250 snapshotDir: snapshotDir.OutputPath,
251 copies: make(map[string]string),
252 filesToZip: []android.Path{bp.path},
253 bpFile: bpFile,
254 prebuiltModules: make(map[string]*bpModule),
255 allMembersByName: allMembersByName,
256 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900257 }
Paul Duffinac37c502019-11-26 18:02:20 +0000258 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900259
Paul Duffincc3132e2021-04-24 01:10:30 +0100260 // Create the prebuilt modules for each of the member modules.
261 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000262 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000263 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000264
Paul Duffina551a1c2020-03-17 21:04:24 +0000265 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000266
267 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100268 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900269 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900270
Paul Duffine6c0d842020-01-15 14:08:51 +0000271 // Create a transformer that will transform an unversioned module into a versioned module.
272 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
273
Paul Duffin72910952020-01-20 18:16:30 +0000274 // Create a transformer that will transform an unversioned module by replacing any references
275 // to internal members with a unique module name and setting prefer: false.
276 unversionedTransformer := unversionedTransformation{builder: builder}
277
Paul Duffinb645ec82019-11-27 17:43:54 +0000278 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000279 // Prune any empty property sets.
280 unversioned = unversioned.transform(pruneEmptySetTransformer{})
281
Paul Duffinb645ec82019-11-27 17:43:54 +0000282 // Copy the unversioned module so it can be modified to make it versioned.
Paul Duffincc72e982020-01-14 15:53:11 +0000283 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000284
285 // Transform the unversioned module into a versioned one.
286 versioned.transform(unversionedToVersionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000287 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000288
Paul Duffin72910952020-01-20 18:16:30 +0000289 // Transform the unversioned module to make it suitable for use in the snapshot.
290 unversioned.transform(unversionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000291 bpFile.AddModule(unversioned)
292 }
293
Paul Duffin26197a62021-04-24 00:34:10 +0100294 // Add the sdk/module_exports_snapshot module to the bp file.
Paul Duffin21827262021-04-24 12:16:36 +0100295 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
Paul Duffin26197a62021-04-24 00:34:10 +0100296
297 // generate Android.bp
298 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
299 generateBpContents(&bp.generatedContents, bpFile)
300
301 contents := bp.content.String()
302 syntaxCheckSnapshotBpFile(ctx, contents)
303
304 bp.build(pctx, ctx, nil)
305
306 filesToZip := builder.filesToZip
307
308 // zip them all
309 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
310 outputDesc := "Building snapshot for " + ctx.ModuleName()
311
312 // If there are no zips to merge then generate the output zip directly.
313 // Otherwise, generate an intermediate zip file into which other zips can be
314 // merged.
315 var zipFile android.OutputPath
316 var desc string
317 if len(builder.zipsToMerge) == 0 {
318 zipFile = outputZipFile
319 desc = outputDesc
320 } else {
321 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
322 desc = "Building intermediate snapshot for " + ctx.ModuleName()
323 }
324
325 ctx.Build(pctx, android.BuildParams{
326 Description: desc,
327 Rule: zipFiles,
328 Inputs: filesToZip,
329 Output: zipFile,
330 Args: map[string]string{
331 "basedir": builder.snapshotDir.String(),
332 },
333 })
334
335 if len(builder.zipsToMerge) != 0 {
336 ctx.Build(pctx, android.BuildParams{
337 Description: outputDesc,
338 Rule: mergeZips,
339 Input: zipFile,
340 Inputs: builder.zipsToMerge,
341 Output: outputZipFile,
342 })
343 }
344
345 return outputZipFile
346}
347
348// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100349func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100350 bpFile := builder.bpFile
351
Paul Duffinb645ec82019-11-27 17:43:54 +0000352 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000353 var snapshotModuleType string
354 if s.properties.Module_exports {
355 snapshotModuleType = "module_exports_snapshot"
356 } else {
357 snapshotModuleType = "sdk_snapshot"
358 }
359 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000360 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000361
362 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100363 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000364 if len(visibility) != 0 {
365 snapshotModule.AddProperty("visibility", visibility)
366 }
367
Paul Duffin865171e2020-03-02 18:38:15 +0000368 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000369
Paul Duffin2d1bb892021-04-24 11:32:59 +0100370 combinedPropertiesList := s.collateSnapshotModuleInfo(sdkVariants)
371 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000372
Paul Duffin2d1bb892021-04-24 11:32:59 +0100373 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100374
Paul Duffin6a7e9532020-03-20 17:50:07 +0000375 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100376
Paul Duffin2d1bb892021-04-24 11:32:59 +0100377 // Create a mapping from osType to combined properties.
378 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
379 for _, combined := range combinedPropertiesList {
380 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
381 }
382
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100383 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000384 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100385 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100386 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000387
Paul Duffin2d1bb892021-04-24 11:32:59 +0100388 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000389 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000390 }
Paul Duffin865171e2020-03-02 18:38:15 +0000391
Jiyong Park8fe14e62020-10-19 22:47:34 +0900392 // If host is supported and any member is host OS dependent then disable host
393 // by default, so that we can enable each host OS variant explicitly. This
394 // avoids problems with implicitly enabled OS variants when the snapshot is
395 // used, which might be different from this run (e.g. different build OS).
396 if s.HostSupported() {
397 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100398 for _, memberVariantDep := range memberVariantDeps {
399 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
400 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900401 if !android.InList(targetString, supportedHostTargets) {
402 supportedHostTargets = append(supportedHostTargets, targetString)
403 }
404 }
405 }
406 if len(supportedHostTargets) > 0 {
407 hostPropertySet := targetPropertySet.AddPropertySet("host")
408 hostPropertySet.AddProperty("enabled", false)
409 }
410 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
411 for _, hostTarget := range supportedHostTargets {
412 propertySet := targetPropertySet.AddPropertySet(hostTarget)
413 propertySet.AddProperty("enabled", true)
414 }
415 }
416
Paul Duffin865171e2020-03-02 18:38:15 +0000417 // Prune any empty property sets.
418 snapshotModule.transform(pruneEmptySetTransformer{})
419
Paul Duffinb645ec82019-11-27 17:43:54 +0000420 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900421}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000422
Paul Duffinf88d8e02020-05-07 20:21:34 +0100423// Check the syntax of the generated Android.bp file contents and if they are
424// invalid then log an error with the contents (tagged with line numbers) and the
425// errors that were found so that it is easy to see where the problem lies.
426func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
427 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
428 if len(errs) != 0 {
429 message := &strings.Builder{}
430 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
431
432Generated Android.bp contents
433========================================================================
434`)
435 for i, line := range strings.Split(contents, "\n") {
436 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
437 }
438
439 _, _ = fmt.Fprint(message, `
440========================================================================
441
442Errors found:
443`)
444
445 for _, err := range errs {
446 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
447 }
448
449 ctx.ModuleErrorf("%s", message.String())
450 }
451}
452
Paul Duffin4b8b7932020-05-06 12:35:38 +0100453func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
454 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
455 if err != nil {
456 ctx.ModuleErrorf("error extracting common properties: %s", err)
457 }
458}
459
Paul Duffinfbe470e2021-04-24 12:37:13 +0100460// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
461type snapshotModuleStaticProperties struct {
462 Compile_multilib string `android:"arch_variant"`
463}
464
Paul Duffin2d1bb892021-04-24 11:32:59 +0100465// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
466type combinedSnapshotModuleProperties struct {
467 // The sdk variant from which this information was collected.
468 sdkVariant *sdk
469
470 // Static snapshot module properties.
471 staticProperties *snapshotModuleStaticProperties
472
473 // The dynamically generated member list properties.
474 dynamicProperties interface{}
475}
476
477// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
478func (s *sdk) collateSnapshotModuleInfo(sdkVariants []*sdk) []*combinedSnapshotModuleProperties {
479 var list []*combinedSnapshotModuleProperties
480 for _, sdkVariant := range sdkVariants {
481 staticProperties := &snapshotModuleStaticProperties{
482 Compile_multilib: sdkVariant.multilibUsages.String(),
483 }
484 dynamicProperties := sdkVariant.dynamicMemberTypeListProperties
485
486 list = append(list, &combinedSnapshotModuleProperties{
487 sdkVariant: sdkVariant,
488 staticProperties: staticProperties,
489 dynamicProperties: dynamicProperties,
490 })
491 }
492 return list
493}
494
495func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
496
497 // Extract the dynamic properties and add them to a list of propertiesContainer.
498 propertyContainers := []propertiesContainer{}
499 for _, i := range list {
500 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
501 sdkVariant: i.sdkVariant,
502 properties: i.dynamicProperties,
503 })
504 }
505
506 // Extract the common members, removing them from the original properties.
507 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
508 extractor := newCommonValueExtractor(commonDynamicProperties)
509 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
510
511 // Extract the static properties and add them to a list of propertiesContainer.
512 propertyContainers = []propertiesContainer{}
513 for _, i := range list {
514 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
515 sdkVariant: i.sdkVariant,
516 properties: i.staticProperties,
517 })
518 }
519
520 commonStaticProperties := &snapshotModuleStaticProperties{}
521 extractor = newCommonValueExtractor(commonStaticProperties)
522 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
523
524 return &combinedSnapshotModuleProperties{
525 sdkVariant: nil,
526 staticProperties: commonStaticProperties,
527 dynamicProperties: commonDynamicProperties,
528 }
529}
530
531func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
532 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100533 multilib := staticProperties.Compile_multilib
534 if multilib != "" && multilib != "both" {
535 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
536 propertySet.AddProperty("compile_multilib", multilib)
537 }
538
Paul Duffin2d1bb892021-04-24 11:32:59 +0100539 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin865171e2020-03-02 18:38:15 +0000540 for _, memberListProperty := range s.memberListProperties() {
541 names := memberListProperty.getter(dynamicMemberTypeListProperties)
542 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000543 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000544 }
545 }
546}
547
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000548type propertyTag struct {
549 name string
550}
551
Paul Duffin0cb37b92020-03-04 14:52:46 +0000552// A BpPropertyTag to add to a property that contains references to other sdk members.
553//
554// This will cause the references to be rewritten to a versioned reference in the version
555// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000556var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000557var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000558
Paul Duffin0cb37b92020-03-04 14:52:46 +0000559// A BpPropertyTag that indicates the property should only be present in the versioned
560// module.
561//
562// This will cause the property to be removed from the unversioned instance of a
563// snapshot module.
564var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
565
Paul Duffine6c0d842020-01-15 14:08:51 +0000566type unversionedToVersionedTransformation struct {
567 identityTransformation
568 builder *snapshotBuilder
569}
570
Paul Duffine6c0d842020-01-15 14:08:51 +0000571func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
572 // Use a versioned name for the module but remember the original name for the
573 // snapshot.
574 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000575 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000576 module.insertAfter("name", "sdk_member_name", name)
577 return module
578}
579
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000580func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000581 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
582 required := tag == requiredSdkMemberReferencePropertyTag
583 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000584 } else {
585 return value, tag
586 }
587}
588
Paul Duffin72910952020-01-20 18:16:30 +0000589type unversionedTransformation struct {
590 identityTransformation
591 builder *snapshotBuilder
592}
593
594func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
595 // If the module is an internal member then use a unique name for it.
596 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000597 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000598
599 // Set prefer: false - this is not strictly required as that is the default.
600 module.insertAfter("name", "prefer", false)
601
602 return module
603}
604
605func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000606 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
607 required := tag == requiredSdkMemberReferencePropertyTag
608 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000609 } else if tag == sdkVersionedOnlyPropertyTag {
610 // The property is not allowed in the unversioned module so remove it.
611 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000612 } else {
613 return value, tag
614 }
615}
616
Paul Duffina78f3a72020-02-21 16:29:35 +0000617type pruneEmptySetTransformer struct {
618 identityTransformation
619}
620
621var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
622
623func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
624 if len(propertySet.properties) == 0 {
625 return nil, nil
626 } else {
627 return propertySet, tag
628 }
629}
630
Paul Duffinb645ec82019-11-27 17:43:54 +0000631func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000632 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
633 return true
634 })
635}
636
637func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffinb645ec82019-11-27 17:43:54 +0000638 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
639 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000640 if moduleFilter(bpModule) {
641 contents.Printfln("")
642 contents.Printfln("%s {", bpModule.moduleType)
643 outputPropertySet(contents, bpModule.bpPropertySet)
644 contents.Printfln("}")
645 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000646 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000647}
648
649func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
650 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000651
652 // Output the properties first, followed by the nested sets. This ensures a
653 // consistent output irrespective of whether property sets are created before
654 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000655 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000656 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000657
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000658 switch v := value.(type) {
659 case []string:
660 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000661 if length > 1 {
662 contents.Printfln("%s: [", name)
663 contents.Indent()
664 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000665 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000666 }
667 contents.Dedent()
668 contents.Printfln("],")
669 } else if length == 0 {
670 contents.Printfln("%s: [],", name)
671 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000672 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000673 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000674
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000675 case bool:
676 contents.Printfln("%s: %t,", name, v)
677
678 case *bpPropertySet:
679 // Do not write property sets in the properties phase.
Paul Duffinb645ec82019-11-27 17:43:54 +0000680
681 default:
682 contents.Printfln("%s: %q,", name, value)
683 }
684 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000685
686 for _, name := range set.order {
687 value := set.getValue(name)
688
689 // Only write property sets in the sets phase.
690 switch v := value.(type) {
691 case *bpPropertySet:
692 contents.Printfln("%s: {", name)
693 outputPropertySet(contents, v)
694 contents.Printfln("},")
695 }
696 }
697
Paul Duffinb645ec82019-11-27 17:43:54 +0000698 contents.Dedent()
699}
700
Paul Duffinac37c502019-11-26 18:02:20 +0000701func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000702 contents := &generatedContents{}
703 generateBpContents(contents, s.builderForTests.bpFile)
704 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000705}
706
Paul Duffind0759072021-02-17 11:23:00 +0000707func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
708 contents := &generatedContents{}
709 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
710 return !strings.Contains(module.properties["name"].(string), "@")
711 })
712 return contents.content.String()
713}
714
715func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
716 contents := &generatedContents{}
717 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
718 return strings.Contains(module.properties["name"].(string), "@")
719 })
720 return contents.content.String()
721}
722
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000723type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000724 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000725 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000726 version string
727 snapshotDir android.OutputPath
728 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000729
730 // Map from destination to source of each copy - used to eliminate duplicates and
731 // detect conflicts.
732 copies map[string]string
733
Paul Duffinb645ec82019-11-27 17:43:54 +0000734 filesToZip android.Paths
735 zipsToMerge android.Paths
736
737 prebuiltModules map[string]*bpModule
738 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000739
740 // The set of all members by name.
741 allMembersByName map[string]struct{}
742
743 // The set of exported members by name.
744 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000745}
746
747func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000748 if existing, ok := s.copies[dest]; ok {
749 if existing != src.String() {
750 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
751 return
752 }
753 } else {
754 path := s.snapshotDir.Join(s.ctx, dest)
755 s.ctx.Build(pctx, android.BuildParams{
756 Rule: android.Cp,
757 Input: src,
758 Output: path,
759 })
760 s.filesToZip = append(s.filesToZip, path)
761
762 s.copies[dest] = src.String()
763 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000764}
765
Paul Duffin91547182019-11-12 19:39:36 +0000766func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
767 ctx := s.ctx
768
769 // Repackage the zip file so that the entries are in the destDir directory.
770 // This will allow the zip file to be merged into the snapshot.
771 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000772
773 ctx.Build(pctx, android.BuildParams{
774 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
775 Rule: repackageZip,
776 Input: zipPath,
777 Output: tmpZipPath,
778 Args: map[string]string{
779 "destdir": destDir,
780 },
781 })
Paul Duffin91547182019-11-12 19:39:36 +0000782
783 // Add the repackaged zip file to the files to merge.
784 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
785}
786
Paul Duffin9d8d6092019-12-05 18:19:29 +0000787func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
788 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000789 if s.prebuiltModules[name] != nil {
790 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
791 }
792
793 m := s.bpFile.newModule(moduleType)
794 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000795
Paul Duffinbefa4b92020-03-04 14:22:45 +0000796 variant := member.Variants()[0]
797
Paul Duffin13f02712020-03-06 12:30:43 +0000798 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000799 // An internal member is only referenced from the sdk snapshot which is in the
800 // same package so can be marked as private.
801 m.AddProperty("visibility", []string{"//visibility:private"})
802 } else {
803 // Extract visibility information from a member variant. All variants have the same
804 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +0100805 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
806
807 // Add any additional visibility rules needed for the prebuilts to reference each other.
808 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
809 if err != nil {
810 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
811 }
812
813 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +0000814 if len(visibility) != 0 {
815 m.AddProperty("visibility", visibility)
816 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000817 }
818
Martin Stjernholm1e041092020-11-03 00:11:09 +0000819 // Where available copy apex_available properties from the member.
820 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
821 apexAvailable := apexAware.ApexAvailable()
822 if len(apexAvailable) == 0 {
823 // //apex_available:platform is the default.
824 apexAvailable = []string{android.AvailableToPlatform}
825 }
826
827 // Add in any baseline apex available settings.
828 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
829
830 // Remove duplicates and sort.
831 apexAvailable = android.FirstUniqueStrings(apexAvailable)
832 sort.Strings(apexAvailable)
833
834 m.AddProperty("apex_available", apexAvailable)
835 }
836
Paul Duffin865171e2020-03-02 18:38:15 +0000837 deviceSupported := false
838 hostSupported := false
839
840 for _, variant := range member.Variants() {
841 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +0900842 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +0000843 hostSupported = true
844 } else if osClass == android.Device {
845 deviceSupported = true
846 }
847 }
848
849 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000850
Paul Duffin0cb37b92020-03-04 14:52:46 +0000851 // Disable installation in the versioned module of those modules that are ever installable.
852 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
853 if installable.EverInstallable() {
854 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
855 }
856 }
857
Paul Duffinb645ec82019-11-27 17:43:54 +0000858 s.prebuiltModules[name] = m
859 s.prebuiltOrder = append(s.prebuiltOrder, m)
860 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000861}
862
Paul Duffin865171e2020-03-02 18:38:15 +0000863func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
864 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000865 bpModule.AddProperty("device_supported", false)
866 }
Paul Duffin865171e2020-03-02 18:38:15 +0000867 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000868 bpModule.AddProperty("host_supported", true)
869 }
870}
871
Paul Duffin13f02712020-03-06 12:30:43 +0000872func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
873 if required {
874 return requiredSdkMemberReferencePropertyTag
875 } else {
876 return optionalSdkMemberReferencePropertyTag
877 }
878}
879
880func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
881 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000882}
883
Paul Duffinb645ec82019-11-27 17:43:54 +0000884// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +0000885func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
886 if _, ok := s.allMembersByName[unversionedName]; !ok {
887 if required {
888 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
889 }
890 return unversionedName
891 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000892 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
893}
Paul Duffinb645ec82019-11-27 17:43:54 +0000894
Paul Duffin13f02712020-03-06 12:30:43 +0000895func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000896 var references []string = nil
897 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000898 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000899 }
900 return references
901}
Paul Duffin13879572019-11-28 14:31:38 +0000902
Paul Duffin72910952020-01-20 18:16:30 +0000903// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +0000904func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
905 if _, ok := s.allMembersByName[unversionedName]; !ok {
906 if required {
907 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
908 }
909 return unversionedName
910 }
911
912 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +0000913 return s.ctx.ModuleName() + "_" + unversionedName
914 } else {
915 return unversionedName
916 }
917}
918
Paul Duffin13f02712020-03-06 12:30:43 +0000919func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +0000920 var references []string = nil
921 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000922 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +0000923 }
924 return references
925}
926
Paul Duffin13f02712020-03-06 12:30:43 +0000927func (s *snapshotBuilder) isInternalMember(memberName string) bool {
928 _, ok := s.exportedMembersByName[memberName]
929 return !ok
930}
931
Martin Stjernholm89238f42020-07-10 00:14:03 +0100932// Add the properties from the given SdkMemberProperties to the blueprint
933// property set. This handles common properties in SdkMemberPropertiesBase and
934// calls the member-specific AddToPropertySet for the rest.
935func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
936 if memberProperties.Base().Compile_multilib != "" {
937 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
938 }
939
940 memberProperties.AddToPropertySet(ctx, targetPropertySet)
941}
942
Paul Duffin21827262021-04-24 12:16:36 +0100943// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
944type sdkMemberVariantDep struct {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000945 memberType android.SdkMemberType
946 variant android.SdkAware
947}
948
Paul Duffin13879572019-11-28 14:31:38 +0000949var _ android.SdkMember = (*sdkMember)(nil)
950
Paul Duffin21827262021-04-24 12:16:36 +0100951// sdkMember groups all the variants of a specific member module together along with the name of the
952// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +0000953type sdkMember struct {
954 memberType android.SdkMemberType
955 name string
956 variants []android.SdkAware
957}
958
959func (m *sdkMember) Name() string {
960 return m.name
961}
962
963func (m *sdkMember) Variants() []android.SdkAware {
964 return m.variants
965}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000966
Paul Duffin9c3760e2020-03-16 19:52:08 +0000967// Track usages of multilib variants.
968type multilibUsage int
969
970const (
971 multilibNone multilibUsage = 0
972 multilib32 multilibUsage = 1
973 multilib64 multilibUsage = 2
974 multilibBoth = multilib32 | multilib64
975)
976
977// Add the multilib that is used in the arch type.
978func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
979 multilib := archType.Multilib
980 switch multilib {
981 case "":
982 return m
983 case "lib32":
984 return m | multilib32
985 case "lib64":
986 return m | multilib64
987 default:
988 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
989 }
990}
991
992func (m multilibUsage) String() string {
993 switch m {
994 case multilibNone:
995 return ""
996 case multilib32:
997 return "32"
998 case multilib64:
999 return "64"
1000 case multilibBoth:
1001 return "both"
1002 default:
1003 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1004 m, multilibNone, multilib32, multilib64, multilibBoth))
1005 }
1006}
1007
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001008type baseInfo struct {
1009 Properties android.SdkMemberProperties
1010}
1011
Paul Duffinf34f6d82020-04-30 15:48:31 +01001012func (b *baseInfo) optimizableProperties() interface{} {
1013 return b.Properties
1014}
1015
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001016type osTypeSpecificInfo struct {
1017 baseInfo
1018
Paul Duffin00e46802020-03-12 20:40:35 +00001019 osType android.OsType
1020
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001021 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001022 //
1023 // Nil if there is one variant whose arch type is common
1024 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001025}
1026
Paul Duffin4b8b7932020-05-06 12:35:38 +01001027var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1028
Paul Duffinfc8dd232020-03-17 12:51:37 +00001029type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1030
Paul Duffin00e46802020-03-12 20:40:35 +00001031// Create a new osTypeSpecificInfo for the specified os type and its properties
1032// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001033func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001034 osInfo := &osTypeSpecificInfo{
1035 osType: osType,
1036 }
1037
1038 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1039 properties := variantPropertiesFactory()
1040 properties.Base().Os = osType
1041 return properties
1042 }
1043
1044 // Create a structure into which properties common across the architectures in
1045 // this os type will be stored.
1046 osInfo.Properties = osSpecificVariantPropertiesFactory()
1047
1048 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001049 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001050 var archTypes []android.ArchType
1051 for _, variant := range osTypeVariants {
1052 archType := variant.Target().Arch.ArchType
1053 archTypeName := archType.Name
1054 if _, ok := variantsByArchName[archTypeName]; !ok {
1055 archTypes = append(archTypes, archType)
1056 }
1057
1058 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1059 }
1060
1061 if commonVariants, ok := variantsByArchName["common"]; ok {
1062 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001063 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 +00001064 }
1065
1066 // A common arch type only has one variant and its properties should be treated
1067 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001068 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001069 } else {
1070 // Create an arch specific info for each supported architecture type.
1071 for _, archType := range archTypes {
1072 archTypeName := archType.Name
1073
1074 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001075 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001076
1077 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1078 }
1079 }
1080
1081 return osInfo
1082}
1083
1084// Optimize the properties by extracting common properties from arch type specific
1085// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001086func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001087 // Nothing to do if there is only a single common architecture.
1088 if len(osInfo.archInfos) == 0 {
1089 return
1090 }
1091
Paul Duffin9c3760e2020-03-16 19:52:08 +00001092 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001093 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001094 multilib = multilib.addArchType(archInfo.archType)
1095
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001096 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001097 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001098 }
1099
Paul Duffin4b8b7932020-05-06 12:35:38 +01001100 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001101
1102 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001103 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001104}
1105
1106// Add the properties for an os to a property set.
1107//
1108// Maps the properties related to the os variants through to an appropriate
1109// module structure that will produce equivalent set of variants when it is
1110// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001111func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001112
1113 var osPropertySet android.BpPropertySet
1114 var archPropertySet android.BpPropertySet
1115 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001116 if osInfo.Properties.Base().Os_count == 1 &&
1117 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1118 // There is only one OS type present in the variants and it shouldn't have a
1119 // variant-specific target. The latter is the case if it's either for device
1120 // where there is only one OS (android), or for host and the member type
1121 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001122
1123 // Create a structure that looks like:
1124 // module_type {
1125 // name: "...",
1126 // ...
1127 // <common properties>
1128 // ...
1129 // <single os type specific properties>
1130 //
1131 // arch: {
1132 // <arch specific sections>
1133 // }
1134 //
1135 osPropertySet = bpModule
1136 archPropertySet = osPropertySet.AddPropertySet("arch")
1137
1138 // Arch specific properties need to be added to an arch specific section
1139 // within arch.
1140 archOsPrefix = ""
1141 } else {
1142 // Create a structure that looks like:
1143 // module_type {
1144 // name: "...",
1145 // ...
1146 // <common properties>
1147 // ...
1148 // target: {
1149 // <arch independent os specific sections, e.g. android>
1150 // ...
1151 // <arch and os specific sections, e.g. android_x86>
1152 // }
1153 //
1154 osType := osInfo.osType
1155 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1156 archPropertySet = targetPropertySet
1157
1158 // Arch specific properties need to be added to an os and arch specific
1159 // section prefixed with <os>_.
1160 archOsPrefix = osType.Name + "_"
1161 }
1162
1163 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001164 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001165
1166 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1167 // os) specific properties.
1168 //
1169 // The archInfos list will be empty if the os contains variants for the common
1170 // architecture.
1171 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001172 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001173 }
1174}
1175
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001176func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1177 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001178 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001179}
1180
1181var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1182
Paul Duffin4b8b7932020-05-06 12:35:38 +01001183func (osInfo *osTypeSpecificInfo) String() string {
1184 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1185}
1186
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001187type archTypeSpecificInfo struct {
1188 baseInfo
1189
1190 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001191 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001192
1193 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001194}
1195
Paul Duffin4b8b7932020-05-06 12:35:38 +01001196var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1197
Paul Duffinfc8dd232020-03-17 12:51:37 +00001198// Create a new archTypeSpecificInfo for the specified arch type and its properties
1199// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001200func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001201
Paul Duffinfc8dd232020-03-17 12:51:37 +00001202 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001203 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001204
1205 // Create the properties into which the arch type specific properties will be
1206 // added.
1207 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001208
1209 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001210 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001211 } else {
1212 // There is more than one variant for this arch type which must be differentiated
1213 // by link type.
1214 for _, linkVariant := range archVariants {
1215 linkType := getLinkType(linkVariant)
1216 if linkType == "" {
1217 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1218 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001219 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001220
1221 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1222 }
1223 }
1224 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001225
1226 return archInfo
1227}
1228
Paul Duffinf34f6d82020-04-30 15:48:31 +01001229func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1230 return archInfo.Properties
1231}
1232
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001233// Get the link type of the variant
1234//
1235// If the variant is not differentiated by link type then it returns "",
1236// otherwise it returns one of "static" or "shared".
1237func getLinkType(variant android.Module) string {
1238 linkType := ""
1239 if linkable, ok := variant.(cc.LinkableInterface); ok {
1240 if linkable.Shared() && linkable.Static() {
1241 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1242 } else if linkable.Shared() {
1243 linkType = "shared"
1244 } else if linkable.Static() {
1245 linkType = "static"
1246 } else {
1247 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1248 }
1249 }
1250 return linkType
1251}
1252
1253// Optimize the properties by extracting common properties from link type specific
1254// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001255func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001256 if len(archInfo.linkInfos) == 0 {
1257 return
1258 }
1259
Paul Duffin4b8b7932020-05-06 12:35:38 +01001260 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001261}
1262
Paul Duffinfc8dd232020-03-17 12:51:37 +00001263// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001264func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001265 archTypeName := archInfo.archType.Name
1266 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001267 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1268 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1269 archTypePropertySet.AddProperty("enabled", true)
1270 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001271 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001272
1273 for _, linkInfo := range archInfo.linkInfos {
1274 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001275 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001276 }
1277}
1278
Paul Duffin4b8b7932020-05-06 12:35:38 +01001279func (archInfo *archTypeSpecificInfo) String() string {
1280 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1281}
1282
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001283type linkTypeSpecificInfo struct {
1284 baseInfo
1285
1286 linkType string
1287}
1288
Paul Duffin4b8b7932020-05-06 12:35:38 +01001289var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1290
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001291// Create a new linkTypeSpecificInfo for the specified link type and its properties
1292// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001293func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001294 linkInfo := &linkTypeSpecificInfo{
1295 baseInfo: baseInfo{
1296 // Create the properties into which the link type specific properties will be
1297 // added.
1298 Properties: variantPropertiesFactory(),
1299 },
1300 linkType: linkType,
1301 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001302 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001303 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001304}
1305
Paul Duffin4b8b7932020-05-06 12:35:38 +01001306func (l *linkTypeSpecificInfo) String() string {
1307 return fmt.Sprintf("LinkType{%s}", l.linkType)
1308}
1309
Paul Duffin3a4eb502020-03-19 16:11:18 +00001310type memberContext struct {
1311 sdkMemberContext android.ModuleContext
1312 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001313 memberType android.SdkMemberType
1314 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001315}
1316
1317func (m *memberContext) SdkModuleContext() android.ModuleContext {
1318 return m.sdkMemberContext
1319}
1320
1321func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1322 return m.builder
1323}
1324
Paul Duffina551a1c2020-03-17 21:04:24 +00001325func (m *memberContext) MemberType() android.SdkMemberType {
1326 return m.memberType
1327}
1328
1329func (m *memberContext) Name() string {
1330 return m.name
1331}
1332
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001333func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001334
1335 memberType := member.memberType
1336
Paul Duffina04c1072020-03-02 10:16:35 +00001337 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001338 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001339 variants := member.Variants()
1340 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001341 osType := variant.Target().Os
1342 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001343 }
1344
Paul Duffina04c1072020-03-02 10:16:35 +00001345 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001346 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001347 properties := memberType.CreateVariantPropertiesStruct()
1348 base := properties.Base()
1349 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001350 return properties
1351 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001352
Paul Duffina04c1072020-03-02 10:16:35 +00001353 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001354
Paul Duffina04c1072020-03-02 10:16:35 +00001355 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001356 commonProperties := variantPropertiesFactory()
1357 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001358
Paul Duffinc097e362020-03-10 22:50:03 +00001359 // Create common value extractor that can be used to optimize the properties.
1360 commonValueExtractor := newCommonValueExtractor(commonProperties)
1361
Paul Duffina04c1072020-03-02 10:16:35 +00001362 // The list of property structures which are os type specific but common across
1363 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001364 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001365
1366 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001367 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001368 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001369 // Add the os specific properties to a list of os type specific yet architecture
1370 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001371 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001372
Paul Duffin00e46802020-03-12 20:40:35 +00001373 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001374 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001375 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001376
Paul Duffina04c1072020-03-02 10:16:35 +00001377 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001378 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001379
Paul Duffina04c1072020-03-02 10:16:35 +00001380 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001381 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001382
Paul Duffina04c1072020-03-02 10:16:35 +00001383 // Create a target property set into which target specific properties can be
1384 // added.
1385 targetPropertySet := bpModule.AddPropertySet("target")
1386
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001387 // If the member is host OS dependent and has host_supported then disable by
1388 // default and enable each host OS variant explicitly. This avoids problems
1389 // with implicitly enabled OS variants when the snapshot is used, which might
1390 // be different from this run (e.g. different build OS).
1391 if ctx.memberType.IsHostOsDependent() {
1392 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1393 if hostSupported {
1394 hostPropertySet := targetPropertySet.AddPropertySet("host")
1395 hostPropertySet.AddProperty("enabled", false)
1396 }
1397 }
1398
Paul Duffina04c1072020-03-02 10:16:35 +00001399 // Iterate over the os types in a fixed order.
1400 for _, osType := range s.getPossibleOsTypes() {
1401 osInfo := osTypeToInfo[osType]
1402 if osInfo == nil {
1403 continue
1404 }
1405
Paul Duffin3a4eb502020-03-19 16:11:18 +00001406 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001407 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001408}
1409
Paul Duffina04c1072020-03-02 10:16:35 +00001410// Compute the list of possible os types that this sdk could support.
1411func (s *sdk) getPossibleOsTypes() []android.OsType {
1412 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001413 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001414 if s.DeviceSupported() {
1415 if osType.Class == android.Device && osType != android.Fuchsia {
1416 osTypes = append(osTypes, osType)
1417 }
1418 }
1419 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001420 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001421 osTypes = append(osTypes, osType)
1422 }
1423 }
1424 }
1425 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1426 return osTypes
1427}
1428
Paul Duffinb28369a2020-05-04 15:39:59 +01001429// Given a set of properties (struct value), return the value of the field within that
1430// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001431type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1432
Paul Duffinc459f892020-04-30 18:08:29 +01001433// Checks the metadata to determine whether the property should be ignored for the
1434// purposes of common value extraction or not.
1435type extractorMetadataPredicate func(metadata propertiesContainer) bool
1436
1437// Indicates whether optimizable properties are provided by a host variant or
1438// not.
1439type isHostVariant interface {
1440 isHostVariant() bool
1441}
1442
Paul Duffinb28369a2020-05-04 15:39:59 +01001443// A property that can be optimized by the commonValueExtractor.
1444type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001445 // The name of the field for this property. It is a "."-separated path for
1446 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001447 name string
1448
Paul Duffinc459f892020-04-30 18:08:29 +01001449 // Filter that can use metadata associated with the properties being optimized
1450 // to determine whether the field should be ignored during common value
1451 // optimization.
1452 filter extractorMetadataPredicate
1453
Paul Duffinb28369a2020-05-04 15:39:59 +01001454 // Retrieves the value on which common value optimization will be performed.
1455 getter fieldAccessorFunc
1456
1457 // The empty value for the field.
1458 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001459
1460 // True if the property can support arch variants false otherwise.
1461 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001462}
1463
Paul Duffin4b8b7932020-05-06 12:35:38 +01001464func (p extractorProperty) String() string {
1465 return p.name
1466}
1467
Paul Duffinc097e362020-03-10 22:50:03 +00001468// Supports extracting common values from a number of instances of a properties
1469// structure into a separate common set of properties.
1470type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001471 // The properties that the extractor can optimize.
1472 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001473}
1474
1475// Create a new common value extractor for the structure type for the supplied
1476// properties struct.
1477//
1478// The returned extractor can be used on any properties structure of the same type
1479// as the supplied set of properties.
1480func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1481 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1482 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001483 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001484 return extractor
1485}
1486
1487// Gather the fields from the supplied structure type from which common values will
1488// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001489//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001490// This is recursive function. If it encounters a struct then it will recurse
1491// into it, passing in the accessor for the field and the struct name as prefix
1492// for the nested fields. That will then be used in the accessors for the fields
1493// in the embedded struct.
1494func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001495 for f := 0; f < structType.NumField(); f++ {
1496 field := structType.Field(f)
1497 if field.PkgPath != "" {
1498 // Ignore unexported fields.
1499 continue
1500 }
1501
Paul Duffinb07fa512020-03-10 22:17:04 +00001502 // Ignore fields whose value should be kept.
1503 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001504 continue
1505 }
1506
Paul Duffinc459f892020-04-30 18:08:29 +01001507 var filter extractorMetadataPredicate
1508
1509 // Add a filter
1510 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1511 filter = func(metadata propertiesContainer) bool {
1512 if m, ok := metadata.(isHostVariant); ok {
1513 if m.isHostVariant() {
1514 return false
1515 }
1516 }
1517 return true
1518 }
1519 }
1520
Paul Duffinc097e362020-03-10 22:50:03 +00001521 // Save a copy of the field index for use in the function.
1522 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001523
Martin Stjernholmb0249572020-09-15 02:32:35 +01001524 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001525
Paul Duffinc097e362020-03-10 22:50:03 +00001526 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001527 if containingStructAccessor != nil {
1528 // This is an embedded structure so first access the field for the embedded
1529 // structure.
1530 value = containingStructAccessor(value)
1531 }
1532
Paul Duffinc097e362020-03-10 22:50:03 +00001533 // Skip through interface and pointer values to find the structure.
1534 value = getStructValue(value)
1535
Paul Duffin4b8b7932020-05-06 12:35:38 +01001536 defer func() {
1537 if r := recover(); r != nil {
1538 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1539 }
1540 }()
1541
Paul Duffinc097e362020-03-10 22:50:03 +00001542 // Return the field.
1543 return value.Field(fieldIndex)
1544 }
1545
Martin Stjernholmb0249572020-09-15 02:32:35 +01001546 if field.Type.Kind() == reflect.Struct {
1547 // Gather fields from the nested or embedded structure.
1548 var subNamePrefix string
1549 if field.Anonymous {
1550 subNamePrefix = namePrefix
1551 } else {
1552 subNamePrefix = name + "."
1553 }
1554 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001555 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001556 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001557 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001558 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001559 fieldGetter,
1560 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001561 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001562 }
1563 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001564 }
Paul Duffinc097e362020-03-10 22:50:03 +00001565 }
1566}
1567
1568func getStructValue(value reflect.Value) reflect.Value {
1569foundStruct:
1570 for {
1571 kind := value.Kind()
1572 switch kind {
1573 case reflect.Interface, reflect.Ptr:
1574 value = value.Elem()
1575 case reflect.Struct:
1576 break foundStruct
1577 default:
1578 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1579 }
1580 }
1581 return value
1582}
1583
Paul Duffinf34f6d82020-04-30 15:48:31 +01001584// A container of properties to be optimized.
1585//
1586// Allows additional information to be associated with the properties, e.g. for
1587// filtering.
1588type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001589 fmt.Stringer
1590
Paul Duffinf34f6d82020-04-30 15:48:31 +01001591 // Get the properties that need optimizing.
1592 optimizableProperties() interface{}
1593}
1594
Paul Duffin2d1bb892021-04-24 11:32:59 +01001595// A wrapper for sdk variant related properties to allow them to be optimized.
1596type sdkVariantPropertiesContainer struct {
1597 sdkVariant *sdk
1598 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01001599}
1600
Paul Duffin2d1bb892021-04-24 11:32:59 +01001601func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
1602 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01001603}
1604
Paul Duffin2d1bb892021-04-24 11:32:59 +01001605func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001606 return c.sdkVariant.String()
1607}
1608
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001609// Extract common properties from a slice of property structures of the same type.
1610//
1611// All the property structures must be of the same type.
1612// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001613// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001614//
1615// Iterates over each exported field (capitalized name) and checks to see whether they
1616// have the same value (using DeepEquals) across all the input properties. If it does not then no
1617// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001618// and the field in each of the input properties structure is set to its default value. Nested
1619// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001620func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001621 commonPropertiesValue := reflect.ValueOf(commonProperties)
1622 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001623
Paul Duffinf34f6d82020-04-30 15:48:31 +01001624 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1625
Paul Duffinb28369a2020-05-04 15:39:59 +01001626 for _, property := range e.properties {
1627 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001628 filter := property.filter
1629 if filter == nil {
1630 filter = func(metadata propertiesContainer) bool {
1631 return true
1632 }
1633 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001634
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001635 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001636 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1637 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001638 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001639
Paul Duffin864e1b42020-05-06 10:23:19 +01001640 // Assume that all the values will be the same.
1641 //
1642 // While similar to this is not quite the same as commonValue == nil. If all the values
1643 // have been filtered out then this will be false but commonValue == nil will be true.
1644 valuesDiffer := false
1645
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001646 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001647 container := sliceValue.Index(i).Interface().(propertiesContainer)
1648 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001649 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001650
Paul Duffinc459f892020-04-30 18:08:29 +01001651 if !filter(container) {
1652 expectedValue := property.emptyValue.Interface()
1653 actualValue := fieldValue.Interface()
1654 if !reflect.DeepEqual(expectedValue, actualValue) {
1655 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1656 }
1657 continue
1658 }
1659
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001660 if commonValue == nil {
1661 // Use the first value as the commonProperties value.
1662 commonValue = &fieldValue
1663 } else {
1664 // If the value does not match the current common value then there is
1665 // no value in common so break out.
1666 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1667 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001668 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001669 break
1670 }
1671 }
1672 }
1673
Paul Duffin864e1b42020-05-06 10:23:19 +01001674 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001675 // and set the input struct's field to the empty value.
1676 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001677 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001678 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001679 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001680 container := sliceValue.Index(i).Interface().(propertiesContainer)
1681 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001682 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001683 fieldValue.Set(emptyValue)
1684 }
1685 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001686
1687 if valuesDiffer && !property.archVariant {
1688 // The values differ but the property does not support arch variants so it
1689 // is an error.
1690 var details strings.Builder
1691 for i := 0; i < sliceValue.Len(); i++ {
1692 container := sliceValue.Index(i).Interface().(propertiesContainer)
1693 itemValue := reflect.ValueOf(container.optimizableProperties())
1694 fieldValue := fieldGetter(itemValue)
1695
1696 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1697 }
1698
1699 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1700 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001701 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01001702
1703 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001704}