blob: 3668b461fdb322b75298af8a409386b03bb8904f [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 Duffina7208112021-04-23 21:20:20 +0100133 export := memberTag.ExportMember()
Paul Duffincd064672021-04-24 00:47:29 +0100134 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{s, memberType, child.(android.SdkAware), export})
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000135
136 // If the member type supports transitive sdk members then recurse down into
137 // its dependencies, otherwise exit traversal.
138 return memberType.HasTransitiveSdkMembers()
Jiyong Park73c54ee2019-10-22 20:31:18 +0900139 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000140
141 return false
Paul Duffin13879572019-11-28 14:31:38 +0000142 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000143}
144
Paul Duffincc3132e2021-04-24 01:10:30 +0100145// groupMemberVariantsByMemberThenType groups the member variant dependencies so that all the
146// variants of each member are grouped together within an sdkMember instance.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000147//
Paul Duffincc3132e2021-04-24 01:10:30 +0100148// The sdkMember instances are then grouped into slices by member type. Within each such slice the
149// sdkMember instances appear in the order they were added as dependencies.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000150//
Paul Duffincc3132e2021-04-24 01:10:30 +0100151// Finally, the member type slices are concatenated together to form a single slice. The order in
152// which they are concatenated is the order in which the member types were registered in the
153// android.SdkMemberTypesRegistry.
154func (s *sdk) groupMemberVariantsByMemberThenType(ctx android.ModuleContext, memberVariantDeps []sdkMemberVariantDep) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000155 byType := make(map[android.SdkMemberType][]*sdkMember)
156 byName := make(map[string]*sdkMember)
157
Paul Duffin21827262021-04-24 12:16:36 +0100158 for _, memberVariantDep := range memberVariantDeps {
159 memberType := memberVariantDep.memberType
160 variant := memberVariantDep.variant
Paul Duffin1356d8c2020-02-25 19:26:33 +0000161
162 name := ctx.OtherModuleName(variant)
163 member := byName[name]
164 if member == nil {
165 member = &sdkMember{memberType: memberType, name: name}
166 byName[name] = member
167 byType[memberType] = append(byType[memberType], member)
168 }
169
Paul Duffin1356d8c2020-02-25 19:26:33 +0000170 // Only append new variants to the list. This is needed because a member can be both
171 // exported by the sdk and also be a transitive sdk member.
172 member.variants = appendUniqueVariants(member.variants, variant)
173 }
174
Paul Duffin13879572019-11-28 14:31:38 +0000175 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000176 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000177 membersOfType := byType[memberListProperty.memberType]
178 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900179 }
180
Paul Duffin6a7e9532020-03-20 17:50:07 +0000181 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900182}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900183
Paul Duffin72910952020-01-20 18:16:30 +0000184func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
185 for _, v := range variants {
186 if v == newVariant {
187 return variants
188 }
189 }
190 return append(variants, newVariant)
191}
192
Jiyong Park73c54ee2019-10-22 20:31:18 +0900193// SDK directory structure
194// <sdk_root>/
195// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
196// <api_ver>/ : below this directory are all auto-generated
197// Android.bp : definition of 'sdk_snapshot' module is here
198// aidl/
199// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
200// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900201// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900202// include/
203// bionic/libc/include/stdlib.h : an exported header file
204// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900205// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900206// <arch>/include/ : arch-specific exported headers
207// <arch>/include_gen/ : arch-specific generated headers
208// <arch>/lib/
209// libFoo.so : a stub library
210
Jiyong Park232e7852019-11-04 12:23:40 +0900211// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900212// This isn't visible to users, so could be changed in future.
213func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
214 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
215}
216
Jiyong Park232e7852019-11-04 12:23:40 +0900217// buildSnapshot is the main function in this source file. It creates rules to copy
218// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000219func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
220
Paul Duffin13f02712020-03-06 12:30:43 +0000221 allMembersByName := make(map[string]struct{})
222 exportedMembersByName := make(map[string]struct{})
Paul Duffin21827262021-04-24 12:16:36 +0100223 var memberVariantDeps []sdkMemberVariantDep
Paul Duffin1356d8c2020-02-25 19:26:33 +0000224 for _, sdkVariant := range sdkVariants {
Paul Duffin21827262021-04-24 12:16:36 +0100225 memberVariantDeps = append(memberVariantDeps, sdkVariant.memberVariantDeps...)
Paul Duffin865171e2020-03-02 18:38:15 +0000226
Paul Duffin13f02712020-03-06 12:30:43 +0000227 // Record the names of all the members, both explicitly specified and implicitly
228 // included.
Paul Duffin21827262021-04-24 12:16:36 +0100229 for _, memberVariantDep := range sdkVariant.memberVariantDeps {
Paul Duffina7208112021-04-23 21:20:20 +0100230 name := memberVariantDep.variant.Name()
231 allMembersByName[name] = struct{}{}
Paul Duffin13f02712020-03-06 12:30:43 +0000232
Paul Duffina7208112021-04-23 21:20:20 +0100233 if memberVariantDep.export {
234 exportedMembersByName[name] = struct{}{}
235 }
Paul Duffin865171e2020-03-02 18:38:15 +0000236 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000237 }
238
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000239 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900240
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000241 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000242
243 bpFile := &bpFile{
244 modules: make(map[string]*bpModule),
245 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000246
247 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000248 ctx: ctx,
249 sdk: s,
250 version: "current",
251 snapshotDir: snapshotDir.OutputPath,
252 copies: make(map[string]string),
253 filesToZip: []android.Path{bp.path},
254 bpFile: bpFile,
255 prebuiltModules: make(map[string]*bpModule),
256 allMembersByName: allMembersByName,
257 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900258 }
Paul Duffinac37c502019-11-26 18:02:20 +0000259 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900260
Paul Duffincc3132e2021-04-24 01:10:30 +0100261 // Create the prebuilt modules for each of the member modules.
262 members := s.groupMemberVariantsByMemberThenType(ctx, memberVariantDeps)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000263 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000264 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000265
Paul Duffina551a1c2020-03-17 21:04:24 +0000266 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000267
268 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100269 s.createMemberSnapshot(memberCtx, member, prebuiltModule.(*bpModule))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900270 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900271
Paul Duffine6c0d842020-01-15 14:08:51 +0000272 // Create a transformer that will transform an unversioned module into a versioned module.
273 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
274
Paul Duffin72910952020-01-20 18:16:30 +0000275 // Create a transformer that will transform an unversioned module by replacing any references
276 // to internal members with a unique module name and setting prefer: false.
277 unversionedTransformer := unversionedTransformation{builder: builder}
278
Paul Duffinb645ec82019-11-27 17:43:54 +0000279 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000280 // Prune any empty property sets.
281 unversioned = unversioned.transform(pruneEmptySetTransformer{})
282
Paul Duffinb645ec82019-11-27 17:43:54 +0000283 // Copy the unversioned module so it can be modified to make it versioned.
Paul Duffincc72e982020-01-14 15:53:11 +0000284 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000285
286 // Transform the unversioned module into a versioned one.
287 versioned.transform(unversionedToVersionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000288 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000289
Paul Duffin72910952020-01-20 18:16:30 +0000290 // Transform the unversioned module to make it suitable for use in the snapshot.
291 unversioned.transform(unversionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000292 bpFile.AddModule(unversioned)
293 }
294
Paul Duffin26197a62021-04-24 00:34:10 +0100295 // Add the sdk/module_exports_snapshot module to the bp file.
Paul Duffin21827262021-04-24 12:16:36 +0100296 s.addSnapshotModule(ctx, builder, sdkVariants, memberVariantDeps)
Paul Duffin26197a62021-04-24 00:34:10 +0100297
298 // generate Android.bp
299 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
300 generateBpContents(&bp.generatedContents, bpFile)
301
302 contents := bp.content.String()
303 syntaxCheckSnapshotBpFile(ctx, contents)
304
305 bp.build(pctx, ctx, nil)
306
307 filesToZip := builder.filesToZip
308
309 // zip them all
310 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
311 outputDesc := "Building snapshot for " + ctx.ModuleName()
312
313 // If there are no zips to merge then generate the output zip directly.
314 // Otherwise, generate an intermediate zip file into which other zips can be
315 // merged.
316 var zipFile android.OutputPath
317 var desc string
318 if len(builder.zipsToMerge) == 0 {
319 zipFile = outputZipFile
320 desc = outputDesc
321 } else {
322 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
323 desc = "Building intermediate snapshot for " + ctx.ModuleName()
324 }
325
326 ctx.Build(pctx, android.BuildParams{
327 Description: desc,
328 Rule: zipFiles,
329 Inputs: filesToZip,
330 Output: zipFile,
331 Args: map[string]string{
332 "basedir": builder.snapshotDir.String(),
333 },
334 })
335
336 if len(builder.zipsToMerge) != 0 {
337 ctx.Build(pctx, android.BuildParams{
338 Description: outputDesc,
339 Rule: mergeZips,
340 Input: zipFile,
341 Inputs: builder.zipsToMerge,
342 Output: outputZipFile,
343 })
344 }
345
346 return outputZipFile
347}
348
349// addSnapshotModule adds the sdk_snapshot/module_exports_snapshot module to the builder.
Paul Duffin21827262021-04-24 12:16:36 +0100350func (s *sdk) addSnapshotModule(ctx android.ModuleContext, builder *snapshotBuilder, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) {
Paul Duffin26197a62021-04-24 00:34:10 +0100351 bpFile := builder.bpFile
352
Paul Duffinb645ec82019-11-27 17:43:54 +0000353 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000354 var snapshotModuleType string
355 if s.properties.Module_exports {
356 snapshotModuleType = "module_exports_snapshot"
357 } else {
358 snapshotModuleType = "sdk_snapshot"
359 }
360 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000361 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000362
363 // Make sure that the snapshot has the same visibility as the sdk.
Paul Duffin157f40f2020-09-29 16:01:08 +0100364 visibility := android.EffectiveVisibilityRules(ctx, s).Strings()
Paul Duffin593b3c92019-12-05 14:31:48 +0000365 if len(visibility) != 0 {
366 snapshotModule.AddProperty("visibility", visibility)
367 }
368
Paul Duffin865171e2020-03-02 18:38:15 +0000369 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000370
Paul Duffincd064672021-04-24 00:47:29 +0100371 combinedPropertiesList := s.collateSnapshotModuleInfo(ctx, sdkVariants, memberVariantDeps)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100372 commonCombinedProperties := s.optimizeSnapshotModuleProperties(ctx, combinedPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000373
Paul Duffin2d1bb892021-04-24 11:32:59 +0100374 s.addSnapshotPropertiesToPropertySet(builder, snapshotModule, commonCombinedProperties)
Martin Stjernholm4cfa2c62020-07-10 19:55:36 +0100375
Paul Duffin6a7e9532020-03-20 17:50:07 +0000376 targetPropertySet := snapshotModule.AddPropertySet("target")
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100377
Paul Duffin2d1bb892021-04-24 11:32:59 +0100378 // Create a mapping from osType to combined properties.
379 osTypeToCombinedProperties := map[android.OsType]*combinedSnapshotModuleProperties{}
380 for _, combined := range combinedPropertiesList {
381 osTypeToCombinedProperties[combined.sdkVariant.Os()] = combined
382 }
383
Martin Stjernholmcaa47d72020-07-11 04:52:24 +0100384 // Iterate over the os types in a fixed order.
Paul Duffin865171e2020-03-02 18:38:15 +0000385 for _, osType := range s.getPossibleOsTypes() {
Paul Duffin2d1bb892021-04-24 11:32:59 +0100386 if combined, ok := osTypeToCombinedProperties[osType]; ok {
Paul Duffincc3132e2021-04-24 01:10:30 +0100387 osPropertySet := targetPropertySet.AddPropertySet(osType.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000388
Paul Duffin2d1bb892021-04-24 11:32:59 +0100389 s.addSnapshotPropertiesToPropertySet(builder, osPropertySet, combined)
Paul Duffin13879572019-11-28 14:31:38 +0000390 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000391 }
Paul Duffin865171e2020-03-02 18:38:15 +0000392
Jiyong Park8fe14e62020-10-19 22:47:34 +0900393 // If host is supported and any member is host OS dependent then disable host
394 // by default, so that we can enable each host OS variant explicitly. This
395 // avoids problems with implicitly enabled OS variants when the snapshot is
396 // used, which might be different from this run (e.g. different build OS).
397 if s.HostSupported() {
398 var supportedHostTargets []string
Paul Duffin21827262021-04-24 12:16:36 +0100399 for _, memberVariantDep := range memberVariantDeps {
400 if memberVariantDep.memberType.IsHostOsDependent() && memberVariantDep.variant.Target().Os.Class == android.Host {
401 targetString := memberVariantDep.variant.Target().Os.String() + "_" + memberVariantDep.variant.Target().Arch.ArchType.String()
Jiyong Park8fe14e62020-10-19 22:47:34 +0900402 if !android.InList(targetString, supportedHostTargets) {
403 supportedHostTargets = append(supportedHostTargets, targetString)
404 }
405 }
406 }
407 if len(supportedHostTargets) > 0 {
408 hostPropertySet := targetPropertySet.AddPropertySet("host")
409 hostPropertySet.AddProperty("enabled", false)
410 }
411 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
412 for _, hostTarget := range supportedHostTargets {
413 propertySet := targetPropertySet.AddPropertySet(hostTarget)
414 propertySet.AddProperty("enabled", true)
415 }
416 }
417
Paul Duffin865171e2020-03-02 18:38:15 +0000418 // Prune any empty property sets.
419 snapshotModule.transform(pruneEmptySetTransformer{})
420
Paul Duffinb645ec82019-11-27 17:43:54 +0000421 bpFile.AddModule(snapshotModule)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900422}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000423
Paul Duffinf88d8e02020-05-07 20:21:34 +0100424// Check the syntax of the generated Android.bp file contents and if they are
425// invalid then log an error with the contents (tagged with line numbers) and the
426// errors that were found so that it is easy to see where the problem lies.
427func syntaxCheckSnapshotBpFile(ctx android.ModuleContext, contents string) {
428 errs := android.CheckBlueprintSyntax(ctx, "Android.bp", contents)
429 if len(errs) != 0 {
430 message := &strings.Builder{}
431 _, _ = fmt.Fprint(message, `errors in generated Android.bp snapshot:
432
433Generated Android.bp contents
434========================================================================
435`)
436 for i, line := range strings.Split(contents, "\n") {
437 _, _ = fmt.Fprintf(message, "%6d: %s\n", i+1, line)
438 }
439
440 _, _ = fmt.Fprint(message, `
441========================================================================
442
443Errors found:
444`)
445
446 for _, err := range errs {
447 _, _ = fmt.Fprintf(message, "%s\n", err.Error())
448 }
449
450 ctx.ModuleErrorf("%s", message.String())
451 }
452}
453
Paul Duffin4b8b7932020-05-06 12:35:38 +0100454func extractCommonProperties(ctx android.ModuleContext, extractor *commonValueExtractor, commonProperties interface{}, inputPropertiesSlice interface{}) {
455 err := extractor.extractCommonProperties(commonProperties, inputPropertiesSlice)
456 if err != nil {
457 ctx.ModuleErrorf("error extracting common properties: %s", err)
458 }
459}
460
Paul Duffinfbe470e2021-04-24 12:37:13 +0100461// snapshotModuleStaticProperties contains snapshot static (i.e. not dynamically generated) properties.
462type snapshotModuleStaticProperties struct {
463 Compile_multilib string `android:"arch_variant"`
464}
465
Paul Duffin2d1bb892021-04-24 11:32:59 +0100466// combinedSnapshotModuleProperties are the properties that are associated with the snapshot module.
467type combinedSnapshotModuleProperties struct {
468 // The sdk variant from which this information was collected.
469 sdkVariant *sdk
470
471 // Static snapshot module properties.
472 staticProperties *snapshotModuleStaticProperties
473
474 // The dynamically generated member list properties.
475 dynamicProperties interface{}
476}
477
478// collateSnapshotModuleInfo collates all the snapshot module info from supplied sdk variants.
Paul Duffincd064672021-04-24 00:47:29 +0100479func (s *sdk) collateSnapshotModuleInfo(ctx android.BaseModuleContext, sdkVariants []*sdk, memberVariantDeps []sdkMemberVariantDep) []*combinedSnapshotModuleProperties {
480 sdkVariantToCombinedProperties := map[*sdk]*combinedSnapshotModuleProperties{}
Paul Duffin2d1bb892021-04-24 11:32:59 +0100481 var list []*combinedSnapshotModuleProperties
482 for _, sdkVariant := range sdkVariants {
483 staticProperties := &snapshotModuleStaticProperties{
484 Compile_multilib: sdkVariant.multilibUsages.String(),
485 }
Paul Duffincd064672021-04-24 00:47:29 +0100486 dynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffin2d1bb892021-04-24 11:32:59 +0100487
Paul Duffincd064672021-04-24 00:47:29 +0100488 combinedProperties := &combinedSnapshotModuleProperties{
Paul Duffin2d1bb892021-04-24 11:32:59 +0100489 sdkVariant: sdkVariant,
490 staticProperties: staticProperties,
491 dynamicProperties: dynamicProperties,
Paul Duffincd064672021-04-24 00:47:29 +0100492 }
493 sdkVariantToCombinedProperties[sdkVariant] = combinedProperties
494
495 list = append(list, combinedProperties)
Paul Duffin2d1bb892021-04-24 11:32:59 +0100496 }
Paul Duffincd064672021-04-24 00:47:29 +0100497
498 for _, memberVariantDep := range memberVariantDeps {
499 // If the member dependency is internal then do not add the dependency to the snapshot member
500 // list properties.
501 if !memberVariantDep.export {
502 continue
503 }
504
505 combined := sdkVariantToCombinedProperties[memberVariantDep.sdkVariant]
506 memberTypeProperty := s.memberListProperty(memberVariantDep.memberType)
507 memberName := ctx.OtherModuleName(memberVariantDep.variant)
508
509 // Append the member to the appropriate list, if it is not already present in the list.
510 memberList := memberTypeProperty.getter(combined.dynamicProperties)
511 if !android.InList(memberName, memberList) {
512 memberList = append(memberList, memberName)
513 }
514 memberTypeProperty.setter(combined.dynamicProperties, memberList)
515 }
516
Paul Duffin2d1bb892021-04-24 11:32:59 +0100517 return list
518}
519
520func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
521
522 // Extract the dynamic properties and add them to a list of propertiesContainer.
523 propertyContainers := []propertiesContainer{}
524 for _, i := range list {
525 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
526 sdkVariant: i.sdkVariant,
527 properties: i.dynamicProperties,
528 })
529 }
530
531 // Extract the common members, removing them from the original properties.
532 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
533 extractor := newCommonValueExtractor(commonDynamicProperties)
534 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
535
536 // Extract the static properties and add them to a list of propertiesContainer.
537 propertyContainers = []propertiesContainer{}
538 for _, i := range list {
539 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
540 sdkVariant: i.sdkVariant,
541 properties: i.staticProperties,
542 })
543 }
544
545 commonStaticProperties := &snapshotModuleStaticProperties{}
546 extractor = newCommonValueExtractor(commonStaticProperties)
547 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
548
549 return &combinedSnapshotModuleProperties{
550 sdkVariant: nil,
551 staticProperties: commonStaticProperties,
552 dynamicProperties: commonDynamicProperties,
553 }
554}
555
556func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
557 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100558 multilib := staticProperties.Compile_multilib
559 if multilib != "" && multilib != "both" {
560 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
561 propertySet.AddProperty("compile_multilib", multilib)
562 }
563
Paul Duffin2d1bb892021-04-24 11:32:59 +0100564 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin865171e2020-03-02 18:38:15 +0000565 for _, memberListProperty := range s.memberListProperties() {
566 names := memberListProperty.getter(dynamicMemberTypeListProperties)
567 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000568 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000569 }
570 }
571}
572
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000573type propertyTag struct {
574 name string
575}
576
Paul Duffin0cb37b92020-03-04 14:52:46 +0000577// A BpPropertyTag to add to a property that contains references to other sdk members.
578//
579// This will cause the references to be rewritten to a versioned reference in the version
580// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000581var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000582var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000583
Paul Duffin0cb37b92020-03-04 14:52:46 +0000584// A BpPropertyTag that indicates the property should only be present in the versioned
585// module.
586//
587// This will cause the property to be removed from the unversioned instance of a
588// snapshot module.
589var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
590
Paul Duffine6c0d842020-01-15 14:08:51 +0000591type unversionedToVersionedTransformation struct {
592 identityTransformation
593 builder *snapshotBuilder
594}
595
Paul Duffine6c0d842020-01-15 14:08:51 +0000596func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
597 // Use a versioned name for the module but remember the original name for the
598 // snapshot.
599 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000600 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000601 module.insertAfter("name", "sdk_member_name", name)
602 return module
603}
604
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000605func (t unversionedToVersionedTransformation) 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.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000609 } else {
610 return value, tag
611 }
612}
613
Paul Duffin72910952020-01-20 18:16:30 +0000614type unversionedTransformation struct {
615 identityTransformation
616 builder *snapshotBuilder
617}
618
619func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
620 // If the module is an internal member then use a unique name for it.
621 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000622 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000623
624 // Set prefer: false - this is not strictly required as that is the default.
625 module.insertAfter("name", "prefer", false)
626
627 return module
628}
629
630func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000631 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
632 required := tag == requiredSdkMemberReferencePropertyTag
633 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000634 } else if tag == sdkVersionedOnlyPropertyTag {
635 // The property is not allowed in the unversioned module so remove it.
636 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000637 } else {
638 return value, tag
639 }
640}
641
Paul Duffina78f3a72020-02-21 16:29:35 +0000642type pruneEmptySetTransformer struct {
643 identityTransformation
644}
645
646var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
647
648func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
649 if len(propertySet.properties) == 0 {
650 return nil, nil
651 } else {
652 return propertySet, tag
653 }
654}
655
Paul Duffinb645ec82019-11-27 17:43:54 +0000656func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000657 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
658 return true
659 })
660}
661
662func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffinb645ec82019-11-27 17:43:54 +0000663 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
664 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000665 if moduleFilter(bpModule) {
666 contents.Printfln("")
667 contents.Printfln("%s {", bpModule.moduleType)
668 outputPropertySet(contents, bpModule.bpPropertySet)
669 contents.Printfln("}")
670 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000671 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000672}
673
674func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
675 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000676
677 // Output the properties first, followed by the nested sets. This ensures a
678 // consistent output irrespective of whether property sets are created before
679 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000680 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000681 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000682
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000683 switch v := value.(type) {
684 case []string:
685 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000686 if length > 1 {
687 contents.Printfln("%s: [", name)
688 contents.Indent()
689 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000690 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000691 }
692 contents.Dedent()
693 contents.Printfln("],")
694 } else if length == 0 {
695 contents.Printfln("%s: [],", name)
696 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000697 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000698 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000699
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000700 case bool:
701 contents.Printfln("%s: %t,", name, v)
702
703 case *bpPropertySet:
704 // Do not write property sets in the properties phase.
Paul Duffinb645ec82019-11-27 17:43:54 +0000705
706 default:
707 contents.Printfln("%s: %q,", name, value)
708 }
709 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000710
711 for _, name := range set.order {
712 value := set.getValue(name)
713
714 // Only write property sets in the sets phase.
715 switch v := value.(type) {
716 case *bpPropertySet:
717 contents.Printfln("%s: {", name)
718 outputPropertySet(contents, v)
719 contents.Printfln("},")
720 }
721 }
722
Paul Duffinb645ec82019-11-27 17:43:54 +0000723 contents.Dedent()
724}
725
Paul Duffinac37c502019-11-26 18:02:20 +0000726func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000727 contents := &generatedContents{}
728 generateBpContents(contents, s.builderForTests.bpFile)
729 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000730}
731
Paul Duffind0759072021-02-17 11:23:00 +0000732func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
733 contents := &generatedContents{}
734 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
735 return !strings.Contains(module.properties["name"].(string), "@")
736 })
737 return contents.content.String()
738}
739
740func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
741 contents := &generatedContents{}
742 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
743 return strings.Contains(module.properties["name"].(string), "@")
744 })
745 return contents.content.String()
746}
747
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000748type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000749 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000750 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000751 version string
752 snapshotDir android.OutputPath
753 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000754
755 // Map from destination to source of each copy - used to eliminate duplicates and
756 // detect conflicts.
757 copies map[string]string
758
Paul Duffinb645ec82019-11-27 17:43:54 +0000759 filesToZip android.Paths
760 zipsToMerge android.Paths
761
762 prebuiltModules map[string]*bpModule
763 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000764
765 // The set of all members by name.
766 allMembersByName map[string]struct{}
767
768 // The set of exported members by name.
769 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000770}
771
772func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000773 if existing, ok := s.copies[dest]; ok {
774 if existing != src.String() {
775 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
776 return
777 }
778 } else {
779 path := s.snapshotDir.Join(s.ctx, dest)
780 s.ctx.Build(pctx, android.BuildParams{
781 Rule: android.Cp,
782 Input: src,
783 Output: path,
784 })
785 s.filesToZip = append(s.filesToZip, path)
786
787 s.copies[dest] = src.String()
788 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000789}
790
Paul Duffin91547182019-11-12 19:39:36 +0000791func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
792 ctx := s.ctx
793
794 // Repackage the zip file so that the entries are in the destDir directory.
795 // This will allow the zip file to be merged into the snapshot.
796 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000797
798 ctx.Build(pctx, android.BuildParams{
799 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
800 Rule: repackageZip,
801 Input: zipPath,
802 Output: tmpZipPath,
803 Args: map[string]string{
804 "destdir": destDir,
805 },
806 })
Paul Duffin91547182019-11-12 19:39:36 +0000807
808 // Add the repackaged zip file to the files to merge.
809 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
810}
811
Paul Duffin9d8d6092019-12-05 18:19:29 +0000812func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
813 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000814 if s.prebuiltModules[name] != nil {
815 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
816 }
817
818 m := s.bpFile.newModule(moduleType)
819 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000820
Paul Duffinbefa4b92020-03-04 14:22:45 +0000821 variant := member.Variants()[0]
822
Paul Duffin13f02712020-03-06 12:30:43 +0000823 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000824 // An internal member is only referenced from the sdk snapshot which is in the
825 // same package so can be marked as private.
826 m.AddProperty("visibility", []string{"//visibility:private"})
827 } else {
828 // Extract visibility information from a member variant. All variants have the same
829 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +0100830 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
831
832 // Add any additional visibility rules needed for the prebuilts to reference each other.
833 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
834 if err != nil {
835 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
836 }
837
838 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +0000839 if len(visibility) != 0 {
840 m.AddProperty("visibility", visibility)
841 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000842 }
843
Martin Stjernholm1e041092020-11-03 00:11:09 +0000844 // Where available copy apex_available properties from the member.
845 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
846 apexAvailable := apexAware.ApexAvailable()
847 if len(apexAvailable) == 0 {
848 // //apex_available:platform is the default.
849 apexAvailable = []string{android.AvailableToPlatform}
850 }
851
852 // Add in any baseline apex available settings.
853 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
854
855 // Remove duplicates and sort.
856 apexAvailable = android.FirstUniqueStrings(apexAvailable)
857 sort.Strings(apexAvailable)
858
859 m.AddProperty("apex_available", apexAvailable)
860 }
861
Paul Duffin865171e2020-03-02 18:38:15 +0000862 deviceSupported := false
863 hostSupported := false
864
865 for _, variant := range member.Variants() {
866 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +0900867 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +0000868 hostSupported = true
869 } else if osClass == android.Device {
870 deviceSupported = true
871 }
872 }
873
874 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000875
Paul Duffin0cb37b92020-03-04 14:52:46 +0000876 // Disable installation in the versioned module of those modules that are ever installable.
877 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
878 if installable.EverInstallable() {
879 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
880 }
881 }
882
Paul Duffinb645ec82019-11-27 17:43:54 +0000883 s.prebuiltModules[name] = m
884 s.prebuiltOrder = append(s.prebuiltOrder, m)
885 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000886}
887
Paul Duffin865171e2020-03-02 18:38:15 +0000888func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
889 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000890 bpModule.AddProperty("device_supported", false)
891 }
Paul Duffin865171e2020-03-02 18:38:15 +0000892 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000893 bpModule.AddProperty("host_supported", true)
894 }
895}
896
Paul Duffin13f02712020-03-06 12:30:43 +0000897func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
898 if required {
899 return requiredSdkMemberReferencePropertyTag
900 } else {
901 return optionalSdkMemberReferencePropertyTag
902 }
903}
904
905func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
906 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000907}
908
Paul Duffinb645ec82019-11-27 17:43:54 +0000909// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +0000910func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
911 if _, ok := s.allMembersByName[unversionedName]; !ok {
912 if required {
913 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
914 }
915 return unversionedName
916 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000917 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
918}
Paul Duffinb645ec82019-11-27 17:43:54 +0000919
Paul Duffin13f02712020-03-06 12:30:43 +0000920func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000921 var references []string = nil
922 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000923 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000924 }
925 return references
926}
Paul Duffin13879572019-11-28 14:31:38 +0000927
Paul Duffin72910952020-01-20 18:16:30 +0000928// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +0000929func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
930 if _, ok := s.allMembersByName[unversionedName]; !ok {
931 if required {
932 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
933 }
934 return unversionedName
935 }
936
937 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +0000938 return s.ctx.ModuleName() + "_" + unversionedName
939 } else {
940 return unversionedName
941 }
942}
943
Paul Duffin13f02712020-03-06 12:30:43 +0000944func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +0000945 var references []string = nil
946 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000947 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +0000948 }
949 return references
950}
951
Paul Duffin13f02712020-03-06 12:30:43 +0000952func (s *snapshotBuilder) isInternalMember(memberName string) bool {
953 _, ok := s.exportedMembersByName[memberName]
954 return !ok
955}
956
Martin Stjernholm89238f42020-07-10 00:14:03 +0100957// Add the properties from the given SdkMemberProperties to the blueprint
958// property set. This handles common properties in SdkMemberPropertiesBase and
959// calls the member-specific AddToPropertySet for the rest.
960func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
961 if memberProperties.Base().Compile_multilib != "" {
962 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
963 }
964
965 memberProperties.AddToPropertySet(ctx, targetPropertySet)
966}
967
Paul Duffin21827262021-04-24 12:16:36 +0100968// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
969type sdkMemberVariantDep struct {
Paul Duffincd064672021-04-24 00:47:29 +0100970 // The sdk variant that depends (possibly indirectly) on the member variant.
971 sdkVariant *sdk
Paul Duffin1356d8c2020-02-25 19:26:33 +0000972 memberType android.SdkMemberType
973 variant android.SdkAware
Paul Duffina7208112021-04-23 21:20:20 +0100974 export bool
Paul Duffin1356d8c2020-02-25 19:26:33 +0000975}
976
Paul Duffin13879572019-11-28 14:31:38 +0000977var _ android.SdkMember = (*sdkMember)(nil)
978
Paul Duffin21827262021-04-24 12:16:36 +0100979// sdkMember groups all the variants of a specific member module together along with the name of the
980// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +0000981type sdkMember struct {
982 memberType android.SdkMemberType
983 name string
984 variants []android.SdkAware
985}
986
987func (m *sdkMember) Name() string {
988 return m.name
989}
990
991func (m *sdkMember) Variants() []android.SdkAware {
992 return m.variants
993}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000994
Paul Duffin9c3760e2020-03-16 19:52:08 +0000995// Track usages of multilib variants.
996type multilibUsage int
997
998const (
999 multilibNone multilibUsage = 0
1000 multilib32 multilibUsage = 1
1001 multilib64 multilibUsage = 2
1002 multilibBoth = multilib32 | multilib64
1003)
1004
1005// Add the multilib that is used in the arch type.
1006func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
1007 multilib := archType.Multilib
1008 switch multilib {
1009 case "":
1010 return m
1011 case "lib32":
1012 return m | multilib32
1013 case "lib64":
1014 return m | multilib64
1015 default:
1016 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
1017 }
1018}
1019
1020func (m multilibUsage) String() string {
1021 switch m {
1022 case multilibNone:
1023 return ""
1024 case multilib32:
1025 return "32"
1026 case multilib64:
1027 return "64"
1028 case multilibBoth:
1029 return "both"
1030 default:
1031 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1032 m, multilibNone, multilib32, multilib64, multilibBoth))
1033 }
1034}
1035
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001036type baseInfo struct {
1037 Properties android.SdkMemberProperties
1038}
1039
Paul Duffinf34f6d82020-04-30 15:48:31 +01001040func (b *baseInfo) optimizableProperties() interface{} {
1041 return b.Properties
1042}
1043
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001044type osTypeSpecificInfo struct {
1045 baseInfo
1046
Paul Duffin00e46802020-03-12 20:40:35 +00001047 osType android.OsType
1048
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001049 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001050 //
1051 // Nil if there is one variant whose arch type is common
1052 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001053}
1054
Paul Duffin4b8b7932020-05-06 12:35:38 +01001055var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1056
Paul Duffinfc8dd232020-03-17 12:51:37 +00001057type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1058
Paul Duffin00e46802020-03-12 20:40:35 +00001059// Create a new osTypeSpecificInfo for the specified os type and its properties
1060// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001061func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001062 osInfo := &osTypeSpecificInfo{
1063 osType: osType,
1064 }
1065
1066 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1067 properties := variantPropertiesFactory()
1068 properties.Base().Os = osType
1069 return properties
1070 }
1071
1072 // Create a structure into which properties common across the architectures in
1073 // this os type will be stored.
1074 osInfo.Properties = osSpecificVariantPropertiesFactory()
1075
1076 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001077 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001078 var archTypes []android.ArchType
1079 for _, variant := range osTypeVariants {
1080 archType := variant.Target().Arch.ArchType
1081 archTypeName := archType.Name
1082 if _, ok := variantsByArchName[archTypeName]; !ok {
1083 archTypes = append(archTypes, archType)
1084 }
1085
1086 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1087 }
1088
1089 if commonVariants, ok := variantsByArchName["common"]; ok {
1090 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001091 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 +00001092 }
1093
1094 // A common arch type only has one variant and its properties should be treated
1095 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001096 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001097 } else {
1098 // Create an arch specific info for each supported architecture type.
1099 for _, archType := range archTypes {
1100 archTypeName := archType.Name
1101
1102 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001103 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001104
1105 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1106 }
1107 }
1108
1109 return osInfo
1110}
1111
1112// Optimize the properties by extracting common properties from arch type specific
1113// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001114func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001115 // Nothing to do if there is only a single common architecture.
1116 if len(osInfo.archInfos) == 0 {
1117 return
1118 }
1119
Paul Duffin9c3760e2020-03-16 19:52:08 +00001120 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001121 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001122 multilib = multilib.addArchType(archInfo.archType)
1123
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001124 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001125 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001126 }
1127
Paul Duffin4b8b7932020-05-06 12:35:38 +01001128 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001129
1130 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001131 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001132}
1133
1134// Add the properties for an os to a property set.
1135//
1136// Maps the properties related to the os variants through to an appropriate
1137// module structure that will produce equivalent set of variants when it is
1138// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001139func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001140
1141 var osPropertySet android.BpPropertySet
1142 var archPropertySet android.BpPropertySet
1143 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001144 if osInfo.Properties.Base().Os_count == 1 &&
1145 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1146 // There is only one OS type present in the variants and it shouldn't have a
1147 // variant-specific target. The latter is the case if it's either for device
1148 // where there is only one OS (android), or for host and the member type
1149 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001150
1151 // Create a structure that looks like:
1152 // module_type {
1153 // name: "...",
1154 // ...
1155 // <common properties>
1156 // ...
1157 // <single os type specific properties>
1158 //
1159 // arch: {
1160 // <arch specific sections>
1161 // }
1162 //
1163 osPropertySet = bpModule
1164 archPropertySet = osPropertySet.AddPropertySet("arch")
1165
1166 // Arch specific properties need to be added to an arch specific section
1167 // within arch.
1168 archOsPrefix = ""
1169 } else {
1170 // Create a structure that looks like:
1171 // module_type {
1172 // name: "...",
1173 // ...
1174 // <common properties>
1175 // ...
1176 // target: {
1177 // <arch independent os specific sections, e.g. android>
1178 // ...
1179 // <arch and os specific sections, e.g. android_x86>
1180 // }
1181 //
1182 osType := osInfo.osType
1183 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1184 archPropertySet = targetPropertySet
1185
1186 // Arch specific properties need to be added to an os and arch specific
1187 // section prefixed with <os>_.
1188 archOsPrefix = osType.Name + "_"
1189 }
1190
1191 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001192 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001193
1194 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1195 // os) specific properties.
1196 //
1197 // The archInfos list will be empty if the os contains variants for the common
1198 // architecture.
1199 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001200 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001201 }
1202}
1203
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001204func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1205 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001206 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001207}
1208
1209var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1210
Paul Duffin4b8b7932020-05-06 12:35:38 +01001211func (osInfo *osTypeSpecificInfo) String() string {
1212 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1213}
1214
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001215type archTypeSpecificInfo struct {
1216 baseInfo
1217
1218 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001219 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001220
1221 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001222}
1223
Paul Duffin4b8b7932020-05-06 12:35:38 +01001224var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1225
Paul Duffinfc8dd232020-03-17 12:51:37 +00001226// Create a new archTypeSpecificInfo for the specified arch type and its properties
1227// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001228func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001229
Paul Duffinfc8dd232020-03-17 12:51:37 +00001230 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001231 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001232
1233 // Create the properties into which the arch type specific properties will be
1234 // added.
1235 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001236
1237 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001238 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001239 } else {
1240 // There is more than one variant for this arch type which must be differentiated
1241 // by link type.
1242 for _, linkVariant := range archVariants {
1243 linkType := getLinkType(linkVariant)
1244 if linkType == "" {
1245 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1246 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001247 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001248
1249 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1250 }
1251 }
1252 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001253
1254 return archInfo
1255}
1256
Paul Duffinf34f6d82020-04-30 15:48:31 +01001257func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1258 return archInfo.Properties
1259}
1260
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001261// Get the link type of the variant
1262//
1263// If the variant is not differentiated by link type then it returns "",
1264// otherwise it returns one of "static" or "shared".
1265func getLinkType(variant android.Module) string {
1266 linkType := ""
1267 if linkable, ok := variant.(cc.LinkableInterface); ok {
1268 if linkable.Shared() && linkable.Static() {
1269 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1270 } else if linkable.Shared() {
1271 linkType = "shared"
1272 } else if linkable.Static() {
1273 linkType = "static"
1274 } else {
1275 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1276 }
1277 }
1278 return linkType
1279}
1280
1281// Optimize the properties by extracting common properties from link type specific
1282// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001283func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001284 if len(archInfo.linkInfos) == 0 {
1285 return
1286 }
1287
Paul Duffin4b8b7932020-05-06 12:35:38 +01001288 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001289}
1290
Paul Duffinfc8dd232020-03-17 12:51:37 +00001291// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001292func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001293 archTypeName := archInfo.archType.Name
1294 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001295 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1296 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1297 archTypePropertySet.AddProperty("enabled", true)
1298 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001299 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001300
1301 for _, linkInfo := range archInfo.linkInfos {
1302 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001303 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001304 }
1305}
1306
Paul Duffin4b8b7932020-05-06 12:35:38 +01001307func (archInfo *archTypeSpecificInfo) String() string {
1308 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1309}
1310
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001311type linkTypeSpecificInfo struct {
1312 baseInfo
1313
1314 linkType string
1315}
1316
Paul Duffin4b8b7932020-05-06 12:35:38 +01001317var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1318
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001319// Create a new linkTypeSpecificInfo for the specified link type and its properties
1320// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001321func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001322 linkInfo := &linkTypeSpecificInfo{
1323 baseInfo: baseInfo{
1324 // Create the properties into which the link type specific properties will be
1325 // added.
1326 Properties: variantPropertiesFactory(),
1327 },
1328 linkType: linkType,
1329 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001330 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001331 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001332}
1333
Paul Duffin4b8b7932020-05-06 12:35:38 +01001334func (l *linkTypeSpecificInfo) String() string {
1335 return fmt.Sprintf("LinkType{%s}", l.linkType)
1336}
1337
Paul Duffin3a4eb502020-03-19 16:11:18 +00001338type memberContext struct {
1339 sdkMemberContext android.ModuleContext
1340 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001341 memberType android.SdkMemberType
1342 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001343}
1344
1345func (m *memberContext) SdkModuleContext() android.ModuleContext {
1346 return m.sdkMemberContext
1347}
1348
1349func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1350 return m.builder
1351}
1352
Paul Duffina551a1c2020-03-17 21:04:24 +00001353func (m *memberContext) MemberType() android.SdkMemberType {
1354 return m.memberType
1355}
1356
1357func (m *memberContext) Name() string {
1358 return m.name
1359}
1360
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001361func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001362
1363 memberType := member.memberType
1364
Paul Duffina04c1072020-03-02 10:16:35 +00001365 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001366 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001367 variants := member.Variants()
1368 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001369 osType := variant.Target().Os
1370 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001371 }
1372
Paul Duffina04c1072020-03-02 10:16:35 +00001373 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001374 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001375 properties := memberType.CreateVariantPropertiesStruct()
1376 base := properties.Base()
1377 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001378 return properties
1379 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001380
Paul Duffina04c1072020-03-02 10:16:35 +00001381 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001382
Paul Duffina04c1072020-03-02 10:16:35 +00001383 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001384 commonProperties := variantPropertiesFactory()
1385 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001386
Paul Duffinc097e362020-03-10 22:50:03 +00001387 // Create common value extractor that can be used to optimize the properties.
1388 commonValueExtractor := newCommonValueExtractor(commonProperties)
1389
Paul Duffina04c1072020-03-02 10:16:35 +00001390 // The list of property structures which are os type specific but common across
1391 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001392 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001393
1394 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001395 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001396 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001397 // Add the os specific properties to a list of os type specific yet architecture
1398 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001399 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001400
Paul Duffin00e46802020-03-12 20:40:35 +00001401 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001402 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001403 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001404
Paul Duffina04c1072020-03-02 10:16:35 +00001405 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001406 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001407
Paul Duffina04c1072020-03-02 10:16:35 +00001408 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001409 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001410
Paul Duffina04c1072020-03-02 10:16:35 +00001411 // Create a target property set into which target specific properties can be
1412 // added.
1413 targetPropertySet := bpModule.AddPropertySet("target")
1414
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001415 // If the member is host OS dependent and has host_supported then disable by
1416 // default and enable each host OS variant explicitly. This avoids problems
1417 // with implicitly enabled OS variants when the snapshot is used, which might
1418 // be different from this run (e.g. different build OS).
1419 if ctx.memberType.IsHostOsDependent() {
1420 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1421 if hostSupported {
1422 hostPropertySet := targetPropertySet.AddPropertySet("host")
1423 hostPropertySet.AddProperty("enabled", false)
1424 }
1425 }
1426
Paul Duffina04c1072020-03-02 10:16:35 +00001427 // Iterate over the os types in a fixed order.
1428 for _, osType := range s.getPossibleOsTypes() {
1429 osInfo := osTypeToInfo[osType]
1430 if osInfo == nil {
1431 continue
1432 }
1433
Paul Duffin3a4eb502020-03-19 16:11:18 +00001434 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001435 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001436}
1437
Paul Duffina04c1072020-03-02 10:16:35 +00001438// Compute the list of possible os types that this sdk could support.
1439func (s *sdk) getPossibleOsTypes() []android.OsType {
1440 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001441 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001442 if s.DeviceSupported() {
1443 if osType.Class == android.Device && osType != android.Fuchsia {
1444 osTypes = append(osTypes, osType)
1445 }
1446 }
1447 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001448 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001449 osTypes = append(osTypes, osType)
1450 }
1451 }
1452 }
1453 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1454 return osTypes
1455}
1456
Paul Duffinb28369a2020-05-04 15:39:59 +01001457// Given a set of properties (struct value), return the value of the field within that
1458// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001459type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1460
Paul Duffinc459f892020-04-30 18:08:29 +01001461// Checks the metadata to determine whether the property should be ignored for the
1462// purposes of common value extraction or not.
1463type extractorMetadataPredicate func(metadata propertiesContainer) bool
1464
1465// Indicates whether optimizable properties are provided by a host variant or
1466// not.
1467type isHostVariant interface {
1468 isHostVariant() bool
1469}
1470
Paul Duffinb28369a2020-05-04 15:39:59 +01001471// A property that can be optimized by the commonValueExtractor.
1472type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001473 // The name of the field for this property. It is a "."-separated path for
1474 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001475 name string
1476
Paul Duffinc459f892020-04-30 18:08:29 +01001477 // Filter that can use metadata associated with the properties being optimized
1478 // to determine whether the field should be ignored during common value
1479 // optimization.
1480 filter extractorMetadataPredicate
1481
Paul Duffinb28369a2020-05-04 15:39:59 +01001482 // Retrieves the value on which common value optimization will be performed.
1483 getter fieldAccessorFunc
1484
1485 // The empty value for the field.
1486 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001487
1488 // True if the property can support arch variants false otherwise.
1489 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001490}
1491
Paul Duffin4b8b7932020-05-06 12:35:38 +01001492func (p extractorProperty) String() string {
1493 return p.name
1494}
1495
Paul Duffinc097e362020-03-10 22:50:03 +00001496// Supports extracting common values from a number of instances of a properties
1497// structure into a separate common set of properties.
1498type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001499 // The properties that the extractor can optimize.
1500 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001501}
1502
1503// Create a new common value extractor for the structure type for the supplied
1504// properties struct.
1505//
1506// The returned extractor can be used on any properties structure of the same type
1507// as the supplied set of properties.
1508func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1509 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1510 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001511 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001512 return extractor
1513}
1514
1515// Gather the fields from the supplied structure type from which common values will
1516// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001517//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001518// This is recursive function. If it encounters a struct then it will recurse
1519// into it, passing in the accessor for the field and the struct name as prefix
1520// for the nested fields. That will then be used in the accessors for the fields
1521// in the embedded struct.
1522func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001523 for f := 0; f < structType.NumField(); f++ {
1524 field := structType.Field(f)
1525 if field.PkgPath != "" {
1526 // Ignore unexported fields.
1527 continue
1528 }
1529
Paul Duffinb07fa512020-03-10 22:17:04 +00001530 // Ignore fields whose value should be kept.
1531 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001532 continue
1533 }
1534
Paul Duffinc459f892020-04-30 18:08:29 +01001535 var filter extractorMetadataPredicate
1536
1537 // Add a filter
1538 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1539 filter = func(metadata propertiesContainer) bool {
1540 if m, ok := metadata.(isHostVariant); ok {
1541 if m.isHostVariant() {
1542 return false
1543 }
1544 }
1545 return true
1546 }
1547 }
1548
Paul Duffinc097e362020-03-10 22:50:03 +00001549 // Save a copy of the field index for use in the function.
1550 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001551
Martin Stjernholmb0249572020-09-15 02:32:35 +01001552 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001553
Paul Duffinc097e362020-03-10 22:50:03 +00001554 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001555 if containingStructAccessor != nil {
1556 // This is an embedded structure so first access the field for the embedded
1557 // structure.
1558 value = containingStructAccessor(value)
1559 }
1560
Paul Duffinc097e362020-03-10 22:50:03 +00001561 // Skip through interface and pointer values to find the structure.
1562 value = getStructValue(value)
1563
Paul Duffin4b8b7932020-05-06 12:35:38 +01001564 defer func() {
1565 if r := recover(); r != nil {
1566 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1567 }
1568 }()
1569
Paul Duffinc097e362020-03-10 22:50:03 +00001570 // Return the field.
1571 return value.Field(fieldIndex)
1572 }
1573
Martin Stjernholmb0249572020-09-15 02:32:35 +01001574 if field.Type.Kind() == reflect.Struct {
1575 // Gather fields from the nested or embedded structure.
1576 var subNamePrefix string
1577 if field.Anonymous {
1578 subNamePrefix = namePrefix
1579 } else {
1580 subNamePrefix = name + "."
1581 }
1582 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001583 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001584 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001585 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001586 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001587 fieldGetter,
1588 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001589 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001590 }
1591 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001592 }
Paul Duffinc097e362020-03-10 22:50:03 +00001593 }
1594}
1595
1596func getStructValue(value reflect.Value) reflect.Value {
1597foundStruct:
1598 for {
1599 kind := value.Kind()
1600 switch kind {
1601 case reflect.Interface, reflect.Ptr:
1602 value = value.Elem()
1603 case reflect.Struct:
1604 break foundStruct
1605 default:
1606 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1607 }
1608 }
1609 return value
1610}
1611
Paul Duffinf34f6d82020-04-30 15:48:31 +01001612// A container of properties to be optimized.
1613//
1614// Allows additional information to be associated with the properties, e.g. for
1615// filtering.
1616type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001617 fmt.Stringer
1618
Paul Duffinf34f6d82020-04-30 15:48:31 +01001619 // Get the properties that need optimizing.
1620 optimizableProperties() interface{}
1621}
1622
Paul Duffin2d1bb892021-04-24 11:32:59 +01001623// A wrapper for sdk variant related properties to allow them to be optimized.
1624type sdkVariantPropertiesContainer struct {
1625 sdkVariant *sdk
1626 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01001627}
1628
Paul Duffin2d1bb892021-04-24 11:32:59 +01001629func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
1630 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01001631}
1632
Paul Duffin2d1bb892021-04-24 11:32:59 +01001633func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001634 return c.sdkVariant.String()
1635}
1636
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001637// Extract common properties from a slice of property structures of the same type.
1638//
1639// All the property structures must be of the same type.
1640// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001641// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001642//
1643// Iterates over each exported field (capitalized name) and checks to see whether they
1644// have the same value (using DeepEquals) across all the input properties. If it does not then no
1645// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001646// and the field in each of the input properties structure is set to its default value. Nested
1647// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001648func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001649 commonPropertiesValue := reflect.ValueOf(commonProperties)
1650 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001651
Paul Duffinf34f6d82020-04-30 15:48:31 +01001652 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1653
Paul Duffinb28369a2020-05-04 15:39:59 +01001654 for _, property := range e.properties {
1655 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001656 filter := property.filter
1657 if filter == nil {
1658 filter = func(metadata propertiesContainer) bool {
1659 return true
1660 }
1661 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001662
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001663 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001664 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1665 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001666 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001667
Paul Duffin864e1b42020-05-06 10:23:19 +01001668 // Assume that all the values will be the same.
1669 //
1670 // While similar to this is not quite the same as commonValue == nil. If all the values
1671 // have been filtered out then this will be false but commonValue == nil will be true.
1672 valuesDiffer := false
1673
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001674 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001675 container := sliceValue.Index(i).Interface().(propertiesContainer)
1676 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001677 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001678
Paul Duffinc459f892020-04-30 18:08:29 +01001679 if !filter(container) {
1680 expectedValue := property.emptyValue.Interface()
1681 actualValue := fieldValue.Interface()
1682 if !reflect.DeepEqual(expectedValue, actualValue) {
1683 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1684 }
1685 continue
1686 }
1687
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001688 if commonValue == nil {
1689 // Use the first value as the commonProperties value.
1690 commonValue = &fieldValue
1691 } else {
1692 // If the value does not match the current common value then there is
1693 // no value in common so break out.
1694 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1695 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001696 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001697 break
1698 }
1699 }
1700 }
1701
Paul Duffin864e1b42020-05-06 10:23:19 +01001702 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001703 // and set the input struct's field to the empty value.
1704 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001705 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001706 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001707 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001708 container := sliceValue.Index(i).Interface().(propertiesContainer)
1709 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001710 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001711 fieldValue.Set(emptyValue)
1712 }
1713 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001714
1715 if valuesDiffer && !property.archVariant {
1716 // The values differ but the property does not support arch variants so it
1717 // is an error.
1718 var details strings.Builder
1719 for i := 0; i < sliceValue.Len(); i++ {
1720 container := sliceValue.Index(i).Interface().(propertiesContainer)
1721 itemValue := reflect.ValueOf(container.optimizableProperties())
1722 fieldValue := fieldGetter(itemValue)
1723
1724 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1725 }
1726
1727 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1728 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001729 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01001730
1731 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001732}