blob: 43ec9266232141eac8d7b0b10324f7d896105537 [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()
134 s.memberVariantDeps = append(s.memberVariantDeps, sdkMemberVariantDep{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 Duffin2d1bb892021-04-24 11:32:59 +0100371 combinedPropertiesList := s.collateSnapshotModuleInfo(sdkVariants)
372 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.
479func (s *sdk) collateSnapshotModuleInfo(sdkVariants []*sdk) []*combinedSnapshotModuleProperties {
480 var list []*combinedSnapshotModuleProperties
481 for _, sdkVariant := range sdkVariants {
482 staticProperties := &snapshotModuleStaticProperties{
483 Compile_multilib: sdkVariant.multilibUsages.String(),
484 }
485 dynamicProperties := sdkVariant.dynamicMemberTypeListProperties
486
487 list = append(list, &combinedSnapshotModuleProperties{
488 sdkVariant: sdkVariant,
489 staticProperties: staticProperties,
490 dynamicProperties: dynamicProperties,
491 })
492 }
493 return list
494}
495
496func (s *sdk) optimizeSnapshotModuleProperties(ctx android.ModuleContext, list []*combinedSnapshotModuleProperties) *combinedSnapshotModuleProperties {
497
498 // Extract the dynamic properties and add them to a list of propertiesContainer.
499 propertyContainers := []propertiesContainer{}
500 for _, i := range list {
501 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
502 sdkVariant: i.sdkVariant,
503 properties: i.dynamicProperties,
504 })
505 }
506
507 // Extract the common members, removing them from the original properties.
508 commonDynamicProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
509 extractor := newCommonValueExtractor(commonDynamicProperties)
510 extractCommonProperties(ctx, extractor, commonDynamicProperties, propertyContainers)
511
512 // Extract the static properties and add them to a list of propertiesContainer.
513 propertyContainers = []propertiesContainer{}
514 for _, i := range list {
515 propertyContainers = append(propertyContainers, sdkVariantPropertiesContainer{
516 sdkVariant: i.sdkVariant,
517 properties: i.staticProperties,
518 })
519 }
520
521 commonStaticProperties := &snapshotModuleStaticProperties{}
522 extractor = newCommonValueExtractor(commonStaticProperties)
523 extractCommonProperties(ctx, extractor, &commonStaticProperties, propertyContainers)
524
525 return &combinedSnapshotModuleProperties{
526 sdkVariant: nil,
527 staticProperties: commonStaticProperties,
528 dynamicProperties: commonDynamicProperties,
529 }
530}
531
532func (s *sdk) addSnapshotPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, combined *combinedSnapshotModuleProperties) {
533 staticProperties := combined.staticProperties
Paul Duffinfbe470e2021-04-24 12:37:13 +0100534 multilib := staticProperties.Compile_multilib
535 if multilib != "" && multilib != "both" {
536 // Compile_multilib defaults to both so only needs to be set when it's specified and not both.
537 propertySet.AddProperty("compile_multilib", multilib)
538 }
539
Paul Duffin2d1bb892021-04-24 11:32:59 +0100540 dynamicMemberTypeListProperties := combined.dynamicProperties
Paul Duffin865171e2020-03-02 18:38:15 +0000541 for _, memberListProperty := range s.memberListProperties() {
542 names := memberListProperty.getter(dynamicMemberTypeListProperties)
543 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000544 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000545 }
546 }
547}
548
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000549type propertyTag struct {
550 name string
551}
552
Paul Duffin0cb37b92020-03-04 14:52:46 +0000553// A BpPropertyTag to add to a property that contains references to other sdk members.
554//
555// This will cause the references to be rewritten to a versioned reference in the version
556// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000557var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000558var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000559
Paul Duffin0cb37b92020-03-04 14:52:46 +0000560// A BpPropertyTag that indicates the property should only be present in the versioned
561// module.
562//
563// This will cause the property to be removed from the unversioned instance of a
564// snapshot module.
565var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
566
Paul Duffine6c0d842020-01-15 14:08:51 +0000567type unversionedToVersionedTransformation struct {
568 identityTransformation
569 builder *snapshotBuilder
570}
571
Paul Duffine6c0d842020-01-15 14:08:51 +0000572func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
573 // Use a versioned name for the module but remember the original name for the
574 // snapshot.
575 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000576 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000577 module.insertAfter("name", "sdk_member_name", name)
578 return module
579}
580
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000581func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000582 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
583 required := tag == requiredSdkMemberReferencePropertyTag
584 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000585 } else {
586 return value, tag
587 }
588}
589
Paul Duffin72910952020-01-20 18:16:30 +0000590type unversionedTransformation struct {
591 identityTransformation
592 builder *snapshotBuilder
593}
594
595func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
596 // If the module is an internal member then use a unique name for it.
597 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000598 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000599
600 // Set prefer: false - this is not strictly required as that is the default.
601 module.insertAfter("name", "prefer", false)
602
603 return module
604}
605
606func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000607 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
608 required := tag == requiredSdkMemberReferencePropertyTag
609 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000610 } else if tag == sdkVersionedOnlyPropertyTag {
611 // The property is not allowed in the unversioned module so remove it.
612 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000613 } else {
614 return value, tag
615 }
616}
617
Paul Duffina78f3a72020-02-21 16:29:35 +0000618type pruneEmptySetTransformer struct {
619 identityTransformation
620}
621
622var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
623
624func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
625 if len(propertySet.properties) == 0 {
626 return nil, nil
627 } else {
628 return propertySet, tag
629 }
630}
631
Paul Duffinb645ec82019-11-27 17:43:54 +0000632func generateBpContents(contents *generatedContents, bpFile *bpFile) {
Paul Duffind0759072021-02-17 11:23:00 +0000633 generateFilteredBpContents(contents, bpFile, func(*bpModule) bool {
634 return true
635 })
636}
637
638func generateFilteredBpContents(contents *generatedContents, bpFile *bpFile, moduleFilter func(module *bpModule) bool) {
Paul Duffinb645ec82019-11-27 17:43:54 +0000639 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
640 for _, bpModule := range bpFile.order {
Paul Duffind0759072021-02-17 11:23:00 +0000641 if moduleFilter(bpModule) {
642 contents.Printfln("")
643 contents.Printfln("%s {", bpModule.moduleType)
644 outputPropertySet(contents, bpModule.bpPropertySet)
645 contents.Printfln("}")
646 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000647 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000648}
649
650func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
651 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000652
653 // Output the properties first, followed by the nested sets. This ensures a
654 // consistent output irrespective of whether property sets are created before
655 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000656 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000657 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000658
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000659 switch v := value.(type) {
660 case []string:
661 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000662 if length > 1 {
663 contents.Printfln("%s: [", name)
664 contents.Indent()
665 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000666 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000667 }
668 contents.Dedent()
669 contents.Printfln("],")
670 } else if length == 0 {
671 contents.Printfln("%s: [],", name)
672 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000673 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000674 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000675
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000676 case bool:
677 contents.Printfln("%s: %t,", name, v)
678
679 case *bpPropertySet:
680 // Do not write property sets in the properties phase.
Paul Duffinb645ec82019-11-27 17:43:54 +0000681
682 default:
683 contents.Printfln("%s: %q,", name, value)
684 }
685 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000686
687 for _, name := range set.order {
688 value := set.getValue(name)
689
690 // Only write property sets in the sets phase.
691 switch v := value.(type) {
692 case *bpPropertySet:
693 contents.Printfln("%s: {", name)
694 outputPropertySet(contents, v)
695 contents.Printfln("},")
696 }
697 }
698
Paul Duffinb645ec82019-11-27 17:43:54 +0000699 contents.Dedent()
700}
701
Paul Duffinac37c502019-11-26 18:02:20 +0000702func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000703 contents := &generatedContents{}
704 generateBpContents(contents, s.builderForTests.bpFile)
705 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000706}
707
Paul Duffind0759072021-02-17 11:23:00 +0000708func (s *sdk) GetUnversionedAndroidBpContentsForTests() string {
709 contents := &generatedContents{}
710 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
711 return !strings.Contains(module.properties["name"].(string), "@")
712 })
713 return contents.content.String()
714}
715
716func (s *sdk) GetVersionedAndroidBpContentsForTests() string {
717 contents := &generatedContents{}
718 generateFilteredBpContents(contents, s.builderForTests.bpFile, func(module *bpModule) bool {
719 return strings.Contains(module.properties["name"].(string), "@")
720 })
721 return contents.content.String()
722}
723
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000724type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000725 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000726 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000727 version string
728 snapshotDir android.OutputPath
729 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000730
731 // Map from destination to source of each copy - used to eliminate duplicates and
732 // detect conflicts.
733 copies map[string]string
734
Paul Duffinb645ec82019-11-27 17:43:54 +0000735 filesToZip android.Paths
736 zipsToMerge android.Paths
737
738 prebuiltModules map[string]*bpModule
739 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000740
741 // The set of all members by name.
742 allMembersByName map[string]struct{}
743
744 // The set of exported members by name.
745 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000746}
747
748func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000749 if existing, ok := s.copies[dest]; ok {
750 if existing != src.String() {
751 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
752 return
753 }
754 } else {
755 path := s.snapshotDir.Join(s.ctx, dest)
756 s.ctx.Build(pctx, android.BuildParams{
757 Rule: android.Cp,
758 Input: src,
759 Output: path,
760 })
761 s.filesToZip = append(s.filesToZip, path)
762
763 s.copies[dest] = src.String()
764 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000765}
766
Paul Duffin91547182019-11-12 19:39:36 +0000767func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
768 ctx := s.ctx
769
770 // Repackage the zip file so that the entries are in the destDir directory.
771 // This will allow the zip file to be merged into the snapshot.
772 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000773
774 ctx.Build(pctx, android.BuildParams{
775 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
776 Rule: repackageZip,
777 Input: zipPath,
778 Output: tmpZipPath,
779 Args: map[string]string{
780 "destdir": destDir,
781 },
782 })
Paul Duffin91547182019-11-12 19:39:36 +0000783
784 // Add the repackaged zip file to the files to merge.
785 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
786}
787
Paul Duffin9d8d6092019-12-05 18:19:29 +0000788func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
789 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000790 if s.prebuiltModules[name] != nil {
791 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
792 }
793
794 m := s.bpFile.newModule(moduleType)
795 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000796
Paul Duffinbefa4b92020-03-04 14:22:45 +0000797 variant := member.Variants()[0]
798
Paul Duffin13f02712020-03-06 12:30:43 +0000799 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000800 // An internal member is only referenced from the sdk snapshot which is in the
801 // same package so can be marked as private.
802 m.AddProperty("visibility", []string{"//visibility:private"})
803 } else {
804 // Extract visibility information from a member variant. All variants have the same
805 // visibility so it doesn't matter which one is used.
Paul Duffin157f40f2020-09-29 16:01:08 +0100806 visibilityRules := android.EffectiveVisibilityRules(s.ctx, variant)
807
808 // Add any additional visibility rules needed for the prebuilts to reference each other.
809 err := visibilityRules.Widen(s.sdk.properties.Prebuilt_visibility)
810 if err != nil {
811 s.ctx.PropertyErrorf("prebuilt_visibility", "%s", err)
812 }
813
814 visibility := visibilityRules.Strings()
Paul Duffin72910952020-01-20 18:16:30 +0000815 if len(visibility) != 0 {
816 m.AddProperty("visibility", visibility)
817 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000818 }
819
Martin Stjernholm1e041092020-11-03 00:11:09 +0000820 // Where available copy apex_available properties from the member.
821 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
822 apexAvailable := apexAware.ApexAvailable()
823 if len(apexAvailable) == 0 {
824 // //apex_available:platform is the default.
825 apexAvailable = []string{android.AvailableToPlatform}
826 }
827
828 // Add in any baseline apex available settings.
829 apexAvailable = append(apexAvailable, apex.BaselineApexAvailable(member.Name())...)
830
831 // Remove duplicates and sort.
832 apexAvailable = android.FirstUniqueStrings(apexAvailable)
833 sort.Strings(apexAvailable)
834
835 m.AddProperty("apex_available", apexAvailable)
836 }
837
Paul Duffin865171e2020-03-02 18:38:15 +0000838 deviceSupported := false
839 hostSupported := false
840
841 for _, variant := range member.Variants() {
842 osClass := variant.Target().Os.Class
Jiyong Park1613e552020-09-14 19:43:17 +0900843 if osClass == android.Host {
Paul Duffin865171e2020-03-02 18:38:15 +0000844 hostSupported = true
845 } else if osClass == android.Device {
846 deviceSupported = true
847 }
848 }
849
850 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000851
Paul Duffin0cb37b92020-03-04 14:52:46 +0000852 // Disable installation in the versioned module of those modules that are ever installable.
853 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
854 if installable.EverInstallable() {
855 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
856 }
857 }
858
Paul Duffinb645ec82019-11-27 17:43:54 +0000859 s.prebuiltModules[name] = m
860 s.prebuiltOrder = append(s.prebuiltOrder, m)
861 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000862}
863
Paul Duffin865171e2020-03-02 18:38:15 +0000864func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
865 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000866 bpModule.AddProperty("device_supported", false)
867 }
Paul Duffin865171e2020-03-02 18:38:15 +0000868 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000869 bpModule.AddProperty("host_supported", true)
870 }
871}
872
Paul Duffin13f02712020-03-06 12:30:43 +0000873func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
874 if required {
875 return requiredSdkMemberReferencePropertyTag
876 } else {
877 return optionalSdkMemberReferencePropertyTag
878 }
879}
880
881func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
882 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000883}
884
Paul Duffinb645ec82019-11-27 17:43:54 +0000885// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +0000886func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
887 if _, ok := s.allMembersByName[unversionedName]; !ok {
888 if required {
889 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
890 }
891 return unversionedName
892 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000893 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
894}
Paul Duffinb645ec82019-11-27 17:43:54 +0000895
Paul Duffin13f02712020-03-06 12:30:43 +0000896func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000897 var references []string = nil
898 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000899 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000900 }
901 return references
902}
Paul Duffin13879572019-11-28 14:31:38 +0000903
Paul Duffin72910952020-01-20 18:16:30 +0000904// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +0000905func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
906 if _, ok := s.allMembersByName[unversionedName]; !ok {
907 if required {
908 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
909 }
910 return unversionedName
911 }
912
913 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +0000914 return s.ctx.ModuleName() + "_" + unversionedName
915 } else {
916 return unversionedName
917 }
918}
919
Paul Duffin13f02712020-03-06 12:30:43 +0000920func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +0000921 var references []string = nil
922 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000923 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +0000924 }
925 return references
926}
927
Paul Duffin13f02712020-03-06 12:30:43 +0000928func (s *snapshotBuilder) isInternalMember(memberName string) bool {
929 _, ok := s.exportedMembersByName[memberName]
930 return !ok
931}
932
Martin Stjernholm89238f42020-07-10 00:14:03 +0100933// Add the properties from the given SdkMemberProperties to the blueprint
934// property set. This handles common properties in SdkMemberPropertiesBase and
935// calls the member-specific AddToPropertySet for the rest.
936func addSdkMemberPropertiesToSet(ctx *memberContext, memberProperties android.SdkMemberProperties, targetPropertySet android.BpPropertySet) {
937 if memberProperties.Base().Compile_multilib != "" {
938 targetPropertySet.AddProperty("compile_multilib", memberProperties.Base().Compile_multilib)
939 }
940
941 memberProperties.AddToPropertySet(ctx, targetPropertySet)
942}
943
Paul Duffin21827262021-04-24 12:16:36 +0100944// sdkMemberVariantDep represents a dependency from an sdk variant onto a member variant.
945type sdkMemberVariantDep struct {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000946 memberType android.SdkMemberType
947 variant android.SdkAware
Paul Duffina7208112021-04-23 21:20:20 +0100948 export bool
Paul Duffin1356d8c2020-02-25 19:26:33 +0000949}
950
Paul Duffin13879572019-11-28 14:31:38 +0000951var _ android.SdkMember = (*sdkMember)(nil)
952
Paul Duffin21827262021-04-24 12:16:36 +0100953// sdkMember groups all the variants of a specific member module together along with the name of the
954// module and the member type. This is used to generate the prebuilt modules for a specific member.
Paul Duffin13879572019-11-28 14:31:38 +0000955type sdkMember struct {
956 memberType android.SdkMemberType
957 name string
958 variants []android.SdkAware
959}
960
961func (m *sdkMember) Name() string {
962 return m.name
963}
964
965func (m *sdkMember) Variants() []android.SdkAware {
966 return m.variants
967}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000968
Paul Duffin9c3760e2020-03-16 19:52:08 +0000969// Track usages of multilib variants.
970type multilibUsage int
971
972const (
973 multilibNone multilibUsage = 0
974 multilib32 multilibUsage = 1
975 multilib64 multilibUsage = 2
976 multilibBoth = multilib32 | multilib64
977)
978
979// Add the multilib that is used in the arch type.
980func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
981 multilib := archType.Multilib
982 switch multilib {
983 case "":
984 return m
985 case "lib32":
986 return m | multilib32
987 case "lib64":
988 return m | multilib64
989 default:
990 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
991 }
992}
993
994func (m multilibUsage) String() string {
995 switch m {
996 case multilibNone:
997 return ""
998 case multilib32:
999 return "32"
1000 case multilib64:
1001 return "64"
1002 case multilibBoth:
1003 return "both"
1004 default:
1005 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
1006 m, multilibNone, multilib32, multilib64, multilibBoth))
1007 }
1008}
1009
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001010type baseInfo struct {
1011 Properties android.SdkMemberProperties
1012}
1013
Paul Duffinf34f6d82020-04-30 15:48:31 +01001014func (b *baseInfo) optimizableProperties() interface{} {
1015 return b.Properties
1016}
1017
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001018type osTypeSpecificInfo struct {
1019 baseInfo
1020
Paul Duffin00e46802020-03-12 20:40:35 +00001021 osType android.OsType
1022
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001023 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001024 //
1025 // Nil if there is one variant whose arch type is common
1026 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001027}
1028
Paul Duffin4b8b7932020-05-06 12:35:38 +01001029var _ propertiesContainer = (*osTypeSpecificInfo)(nil)
1030
Paul Duffinfc8dd232020-03-17 12:51:37 +00001031type variantPropertiesFactoryFunc func() android.SdkMemberProperties
1032
Paul Duffin00e46802020-03-12 20:40:35 +00001033// Create a new osTypeSpecificInfo for the specified os type and its properties
1034// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001035func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +00001036 osInfo := &osTypeSpecificInfo{
1037 osType: osType,
1038 }
1039
1040 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
1041 properties := variantPropertiesFactory()
1042 properties.Base().Os = osType
1043 return properties
1044 }
1045
1046 // Create a structure into which properties common across the architectures in
1047 // this os type will be stored.
1048 osInfo.Properties = osSpecificVariantPropertiesFactory()
1049
1050 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001051 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +00001052 var archTypes []android.ArchType
1053 for _, variant := range osTypeVariants {
1054 archType := variant.Target().Arch.ArchType
1055 archTypeName := archType.Name
1056 if _, ok := variantsByArchName[archTypeName]; !ok {
1057 archTypes = append(archTypes, archType)
1058 }
1059
1060 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
1061 }
1062
1063 if commonVariants, ok := variantsByArchName["common"]; ok {
1064 if len(osTypeVariants) != 1 {
Colin Crossafa6a772020-07-06 17:41:08 -07001065 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 +00001066 }
1067
1068 // A common arch type only has one variant and its properties should be treated
1069 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001070 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +00001071 } else {
1072 // Create an arch specific info for each supported architecture type.
1073 for _, archType := range archTypes {
1074 archTypeName := archType.Name
1075
1076 archVariants := variantsByArchName[archTypeName]
Jiyong Park8fe14e62020-10-19 22:47:34 +09001077 archInfo := newArchSpecificInfo(ctx, archType, osType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +00001078
1079 osInfo.archInfos = append(osInfo.archInfos, archInfo)
1080 }
1081 }
1082
1083 return osInfo
1084}
1085
1086// Optimize the properties by extracting common properties from arch type specific
1087// properties into os type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001088func (osInfo *osTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin00e46802020-03-12 20:40:35 +00001089 // Nothing to do if there is only a single common architecture.
1090 if len(osInfo.archInfos) == 0 {
1091 return
1092 }
1093
Paul Duffin9c3760e2020-03-16 19:52:08 +00001094 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +00001095 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +00001096 multilib = multilib.addArchType(archInfo.archType)
1097
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001098 // Optimize the arch properties first.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001099 archInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +00001100 }
1101
Paul Duffin4b8b7932020-05-06 12:35:38 +01001102 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +00001103
1104 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +00001105 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +00001106}
1107
1108// Add the properties for an os to a property set.
1109//
1110// Maps the properties related to the os variants through to an appropriate
1111// module structure that will produce equivalent set of variants when it is
1112// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001113func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +00001114
1115 var osPropertySet android.BpPropertySet
1116 var archPropertySet android.BpPropertySet
1117 var archOsPrefix string
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001118 if osInfo.Properties.Base().Os_count == 1 &&
1119 (osInfo.osType.Class == android.Device || !ctx.memberType.IsHostOsDependent()) {
1120 // There is only one OS type present in the variants and it shouldn't have a
1121 // variant-specific target. The latter is the case if it's either for device
1122 // where there is only one OS (android), or for host and the member type
1123 // isn't host OS dependent.
Paul Duffin00e46802020-03-12 20:40:35 +00001124
1125 // Create a structure that looks like:
1126 // module_type {
1127 // name: "...",
1128 // ...
1129 // <common properties>
1130 // ...
1131 // <single os type specific properties>
1132 //
1133 // arch: {
1134 // <arch specific sections>
1135 // }
1136 //
1137 osPropertySet = bpModule
1138 archPropertySet = osPropertySet.AddPropertySet("arch")
1139
1140 // Arch specific properties need to be added to an arch specific section
1141 // within arch.
1142 archOsPrefix = ""
1143 } else {
1144 // Create a structure that looks like:
1145 // module_type {
1146 // name: "...",
1147 // ...
1148 // <common properties>
1149 // ...
1150 // target: {
1151 // <arch independent os specific sections, e.g. android>
1152 // ...
1153 // <arch and os specific sections, e.g. android_x86>
1154 // }
1155 //
1156 osType := osInfo.osType
1157 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
1158 archPropertySet = targetPropertySet
1159
1160 // Arch specific properties need to be added to an os and arch specific
1161 // section prefixed with <os>_.
1162 archOsPrefix = osType.Name + "_"
1163 }
1164
1165 // Add the os specific but arch independent properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001166 addSdkMemberPropertiesToSet(ctx, osInfo.Properties, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +00001167
1168 // Add arch (and possibly os) specific sections for each set of arch (and possibly
1169 // os) specific properties.
1170 //
1171 // The archInfos list will be empty if the os contains variants for the common
1172 // architecture.
1173 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001174 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +00001175 }
1176}
1177
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001178func (osInfo *osTypeSpecificInfo) isHostVariant() bool {
1179 osClass := osInfo.osType.Class
Jiyong Park1613e552020-09-14 19:43:17 +09001180 return osClass == android.Host
Paul Duffin7a1f7f32020-05-04 15:32:08 +01001181}
1182
1183var _ isHostVariant = (*osTypeSpecificInfo)(nil)
1184
Paul Duffin4b8b7932020-05-06 12:35:38 +01001185func (osInfo *osTypeSpecificInfo) String() string {
1186 return fmt.Sprintf("OsType{%s}", osInfo.osType)
1187}
1188
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001189type archTypeSpecificInfo struct {
1190 baseInfo
1191
1192 archType android.ArchType
Jiyong Park8fe14e62020-10-19 22:47:34 +09001193 osType android.OsType
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001194
1195 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001196}
1197
Paul Duffin4b8b7932020-05-06 12:35:38 +01001198var _ propertiesContainer = (*archTypeSpecificInfo)(nil)
1199
Paul Duffinfc8dd232020-03-17 12:51:37 +00001200// Create a new archTypeSpecificInfo for the specified arch type and its properties
1201// structures populated with information from the variants.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001202func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001203
Paul Duffinfc8dd232020-03-17 12:51:37 +00001204 // Create an arch specific info into which the variant properties can be copied.
Jiyong Park8fe14e62020-10-19 22:47:34 +09001205 archInfo := &archTypeSpecificInfo{archType: archType, osType: osType}
Paul Duffinfc8dd232020-03-17 12:51:37 +00001206
1207 // Create the properties into which the arch type specific properties will be
1208 // added.
1209 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001210
1211 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001212 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001213 } else {
1214 // There is more than one variant for this arch type which must be differentiated
1215 // by link type.
1216 for _, linkVariant := range archVariants {
1217 linkType := getLinkType(linkVariant)
1218 if linkType == "" {
1219 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1220 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001221 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001222
1223 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1224 }
1225 }
1226 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001227
1228 return archInfo
1229}
1230
Paul Duffinf34f6d82020-04-30 15:48:31 +01001231func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1232 return archInfo.Properties
1233}
1234
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001235// Get the link type of the variant
1236//
1237// If the variant is not differentiated by link type then it returns "",
1238// otherwise it returns one of "static" or "shared".
1239func getLinkType(variant android.Module) string {
1240 linkType := ""
1241 if linkable, ok := variant.(cc.LinkableInterface); ok {
1242 if linkable.Shared() && linkable.Static() {
1243 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1244 } else if linkable.Shared() {
1245 linkType = "shared"
1246 } else if linkable.Static() {
1247 linkType = "static"
1248 } else {
1249 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1250 }
1251 }
1252 return linkType
1253}
1254
1255// Optimize the properties by extracting common properties from link type specific
1256// properties into arch type specific properties.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001257func (archInfo *archTypeSpecificInfo) optimizeProperties(ctx *memberContext, commonValueExtractor *commonValueExtractor) {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001258 if len(archInfo.linkInfos) == 0 {
1259 return
1260 }
1261
Paul Duffin4b8b7932020-05-06 12:35:38 +01001262 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001263}
1264
Paul Duffinfc8dd232020-03-17 12:51:37 +00001265// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001266func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001267 archTypeName := archInfo.archType.Name
1268 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Jiyong Park8fe14e62020-10-19 22:47:34 +09001269 // Enable the <os>_<arch> variant explicitly when we've disabled it by default on host.
1270 if ctx.memberType.IsHostOsDependent() && archInfo.osType.Class == android.Host {
1271 archTypePropertySet.AddProperty("enabled", true)
1272 }
Martin Stjernholm89238f42020-07-10 00:14:03 +01001273 addSdkMemberPropertiesToSet(ctx, archInfo.Properties, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001274
1275 for _, linkInfo := range archInfo.linkInfos {
1276 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Martin Stjernholm89238f42020-07-10 00:14:03 +01001277 addSdkMemberPropertiesToSet(ctx, linkInfo.Properties, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001278 }
1279}
1280
Paul Duffin4b8b7932020-05-06 12:35:38 +01001281func (archInfo *archTypeSpecificInfo) String() string {
1282 return fmt.Sprintf("ArchType{%s}", archInfo.archType)
1283}
1284
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001285type linkTypeSpecificInfo struct {
1286 baseInfo
1287
1288 linkType string
1289}
1290
Paul Duffin4b8b7932020-05-06 12:35:38 +01001291var _ propertiesContainer = (*linkTypeSpecificInfo)(nil)
1292
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001293// Create a new linkTypeSpecificInfo for the specified link type and its properties
1294// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001295func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001296 linkInfo := &linkTypeSpecificInfo{
1297 baseInfo: baseInfo{
1298 // Create the properties into which the link type specific properties will be
1299 // added.
1300 Properties: variantPropertiesFactory(),
1301 },
1302 linkType: linkType,
1303 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001304 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001305 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001306}
1307
Paul Duffin4b8b7932020-05-06 12:35:38 +01001308func (l *linkTypeSpecificInfo) String() string {
1309 return fmt.Sprintf("LinkType{%s}", l.linkType)
1310}
1311
Paul Duffin3a4eb502020-03-19 16:11:18 +00001312type memberContext struct {
1313 sdkMemberContext android.ModuleContext
1314 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001315 memberType android.SdkMemberType
1316 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001317}
1318
1319func (m *memberContext) SdkModuleContext() android.ModuleContext {
1320 return m.sdkMemberContext
1321}
1322
1323func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1324 return m.builder
1325}
1326
Paul Duffina551a1c2020-03-17 21:04:24 +00001327func (m *memberContext) MemberType() android.SdkMemberType {
1328 return m.memberType
1329}
1330
1331func (m *memberContext) Name() string {
1332 return m.name
1333}
1334
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001335func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule *bpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001336
1337 memberType := member.memberType
1338
Paul Duffina04c1072020-03-02 10:16:35 +00001339 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001340 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001341 variants := member.Variants()
1342 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001343 osType := variant.Target().Os
1344 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001345 }
1346
Paul Duffina04c1072020-03-02 10:16:35 +00001347 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001348 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001349 properties := memberType.CreateVariantPropertiesStruct()
1350 base := properties.Base()
1351 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001352 return properties
1353 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001354
Paul Duffina04c1072020-03-02 10:16:35 +00001355 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001356
Paul Duffina04c1072020-03-02 10:16:35 +00001357 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001358 commonProperties := variantPropertiesFactory()
1359 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001360
Paul Duffinc097e362020-03-10 22:50:03 +00001361 // Create common value extractor that can be used to optimize the properties.
1362 commonValueExtractor := newCommonValueExtractor(commonProperties)
1363
Paul Duffina04c1072020-03-02 10:16:35 +00001364 // The list of property structures which are os type specific but common across
1365 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001366 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001367
1368 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001369 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001370 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001371 // Add the os specific properties to a list of os type specific yet architecture
1372 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001373 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001374
Paul Duffin00e46802020-03-12 20:40:35 +00001375 // Optimize the properties across all the variants for a specific os type.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001376 osInfo.optimizeProperties(ctx, commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001377 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001378
Paul Duffina04c1072020-03-02 10:16:35 +00001379 // Extract properties which are common across all architectures and os types.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001380 extractCommonProperties(ctx.sdkMemberContext, commonValueExtractor, commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001381
Paul Duffina04c1072020-03-02 10:16:35 +00001382 // Add the common properties to the module.
Martin Stjernholm89238f42020-07-10 00:14:03 +01001383 addSdkMemberPropertiesToSet(ctx, commonProperties, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001384
Paul Duffina04c1072020-03-02 10:16:35 +00001385 // Create a target property set into which target specific properties can be
1386 // added.
1387 targetPropertySet := bpModule.AddPropertySet("target")
1388
Martin Stjernholmcaa47d72020-07-11 04:52:24 +01001389 // If the member is host OS dependent and has host_supported then disable by
1390 // default and enable each host OS variant explicitly. This avoids problems
1391 // with implicitly enabled OS variants when the snapshot is used, which might
1392 // be different from this run (e.g. different build OS).
1393 if ctx.memberType.IsHostOsDependent() {
1394 hostSupported := bpModule.getValue("host_supported") == true // Missing means false.
1395 if hostSupported {
1396 hostPropertySet := targetPropertySet.AddPropertySet("host")
1397 hostPropertySet.AddProperty("enabled", false)
1398 }
1399 }
1400
Paul Duffina04c1072020-03-02 10:16:35 +00001401 // Iterate over the os types in a fixed order.
1402 for _, osType := range s.getPossibleOsTypes() {
1403 osInfo := osTypeToInfo[osType]
1404 if osInfo == nil {
1405 continue
1406 }
1407
Paul Duffin3a4eb502020-03-19 16:11:18 +00001408 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001409 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001410}
1411
Paul Duffina04c1072020-03-02 10:16:35 +00001412// Compute the list of possible os types that this sdk could support.
1413func (s *sdk) getPossibleOsTypes() []android.OsType {
1414 var osTypes []android.OsType
Jingwen Chen2f6a21e2021-04-05 07:33:05 +00001415 for _, osType := range android.OsTypeList() {
Paul Duffina04c1072020-03-02 10:16:35 +00001416 if s.DeviceSupported() {
1417 if osType.Class == android.Device && osType != android.Fuchsia {
1418 osTypes = append(osTypes, osType)
1419 }
1420 }
1421 if s.HostSupported() {
Jiyong Park1613e552020-09-14 19:43:17 +09001422 if osType.Class == android.Host {
Paul Duffina04c1072020-03-02 10:16:35 +00001423 osTypes = append(osTypes, osType)
1424 }
1425 }
1426 }
1427 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1428 return osTypes
1429}
1430
Paul Duffinb28369a2020-05-04 15:39:59 +01001431// Given a set of properties (struct value), return the value of the field within that
1432// struct (or one of its embedded structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001433type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1434
Paul Duffinc459f892020-04-30 18:08:29 +01001435// Checks the metadata to determine whether the property should be ignored for the
1436// purposes of common value extraction or not.
1437type extractorMetadataPredicate func(metadata propertiesContainer) bool
1438
1439// Indicates whether optimizable properties are provided by a host variant or
1440// not.
1441type isHostVariant interface {
1442 isHostVariant() bool
1443}
1444
Paul Duffinb28369a2020-05-04 15:39:59 +01001445// A property that can be optimized by the commonValueExtractor.
1446type extractorProperty struct {
Martin Stjernholmb0249572020-09-15 02:32:35 +01001447 // The name of the field for this property. It is a "."-separated path for
1448 // fields in non-anonymous substructs.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001449 name string
1450
Paul Duffinc459f892020-04-30 18:08:29 +01001451 // Filter that can use metadata associated with the properties being optimized
1452 // to determine whether the field should be ignored during common value
1453 // optimization.
1454 filter extractorMetadataPredicate
1455
Paul Duffinb28369a2020-05-04 15:39:59 +01001456 // Retrieves the value on which common value optimization will be performed.
1457 getter fieldAccessorFunc
1458
1459 // The empty value for the field.
1460 emptyValue reflect.Value
Paul Duffin864e1b42020-05-06 10:23:19 +01001461
1462 // True if the property can support arch variants false otherwise.
1463 archVariant bool
Paul Duffinb28369a2020-05-04 15:39:59 +01001464}
1465
Paul Duffin4b8b7932020-05-06 12:35:38 +01001466func (p extractorProperty) String() string {
1467 return p.name
1468}
1469
Paul Duffinc097e362020-03-10 22:50:03 +00001470// Supports extracting common values from a number of instances of a properties
1471// structure into a separate common set of properties.
1472type commonValueExtractor struct {
Paul Duffinb28369a2020-05-04 15:39:59 +01001473 // The properties that the extractor can optimize.
1474 properties []extractorProperty
Paul Duffinc097e362020-03-10 22:50:03 +00001475}
1476
1477// Create a new common value extractor for the structure type for the supplied
1478// properties struct.
1479//
1480// The returned extractor can be used on any properties structure of the same type
1481// as the supplied set of properties.
1482func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1483 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1484 extractor := &commonValueExtractor{}
Martin Stjernholmb0249572020-09-15 02:32:35 +01001485 extractor.gatherFields(structType, nil, "")
Paul Duffinc097e362020-03-10 22:50:03 +00001486 return extractor
1487}
1488
1489// Gather the fields from the supplied structure type from which common values will
1490// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001491//
Martin Stjernholmb0249572020-09-15 02:32:35 +01001492// This is recursive function. If it encounters a struct then it will recurse
1493// into it, passing in the accessor for the field and the struct name as prefix
1494// for the nested fields. That will then be used in the accessors for the fields
1495// in the embedded struct.
1496func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc, namePrefix string) {
Paul Duffinc097e362020-03-10 22:50:03 +00001497 for f := 0; f < structType.NumField(); f++ {
1498 field := structType.Field(f)
1499 if field.PkgPath != "" {
1500 // Ignore unexported fields.
1501 continue
1502 }
1503
Paul Duffinb07fa512020-03-10 22:17:04 +00001504 // Ignore fields whose value should be kept.
1505 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001506 continue
1507 }
1508
Paul Duffinc459f892020-04-30 18:08:29 +01001509 var filter extractorMetadataPredicate
1510
1511 // Add a filter
1512 if proptools.HasTag(field, "sdk", "ignored-on-host") {
1513 filter = func(metadata propertiesContainer) bool {
1514 if m, ok := metadata.(isHostVariant); ok {
1515 if m.isHostVariant() {
1516 return false
1517 }
1518 }
1519 return true
1520 }
1521 }
1522
Paul Duffinc097e362020-03-10 22:50:03 +00001523 // Save a copy of the field index for use in the function.
1524 fieldIndex := f
Paul Duffin4b8b7932020-05-06 12:35:38 +01001525
Martin Stjernholmb0249572020-09-15 02:32:35 +01001526 name := namePrefix + field.Name
Paul Duffin4b8b7932020-05-06 12:35:38 +01001527
Paul Duffinc097e362020-03-10 22:50:03 +00001528 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001529 if containingStructAccessor != nil {
1530 // This is an embedded structure so first access the field for the embedded
1531 // structure.
1532 value = containingStructAccessor(value)
1533 }
1534
Paul Duffinc097e362020-03-10 22:50:03 +00001535 // Skip through interface and pointer values to find the structure.
1536 value = getStructValue(value)
1537
Paul Duffin4b8b7932020-05-06 12:35:38 +01001538 defer func() {
1539 if r := recover(); r != nil {
1540 panic(fmt.Errorf("%s for fieldIndex %d of field %s of value %#v", r, fieldIndex, name, value.Interface()))
1541 }
1542 }()
1543
Paul Duffinc097e362020-03-10 22:50:03 +00001544 // Return the field.
1545 return value.Field(fieldIndex)
1546 }
1547
Martin Stjernholmb0249572020-09-15 02:32:35 +01001548 if field.Type.Kind() == reflect.Struct {
1549 // Gather fields from the nested or embedded structure.
1550 var subNamePrefix string
1551 if field.Anonymous {
1552 subNamePrefix = namePrefix
1553 } else {
1554 subNamePrefix = name + "."
1555 }
1556 e.gatherFields(field.Type, fieldGetter, subNamePrefix)
Paul Duffinb07fa512020-03-10 22:17:04 +00001557 } else {
Paul Duffinb28369a2020-05-04 15:39:59 +01001558 property := extractorProperty{
Paul Duffin4b8b7932020-05-06 12:35:38 +01001559 name,
Paul Duffinc459f892020-04-30 18:08:29 +01001560 filter,
Paul Duffinb28369a2020-05-04 15:39:59 +01001561 fieldGetter,
1562 reflect.Zero(field.Type),
Paul Duffin864e1b42020-05-06 10:23:19 +01001563 proptools.HasTag(field, "android", "arch_variant"),
Paul Duffinb28369a2020-05-04 15:39:59 +01001564 }
1565 e.properties = append(e.properties, property)
Paul Duffinb07fa512020-03-10 22:17:04 +00001566 }
Paul Duffinc097e362020-03-10 22:50:03 +00001567 }
1568}
1569
1570func getStructValue(value reflect.Value) reflect.Value {
1571foundStruct:
1572 for {
1573 kind := value.Kind()
1574 switch kind {
1575 case reflect.Interface, reflect.Ptr:
1576 value = value.Elem()
1577 case reflect.Struct:
1578 break foundStruct
1579 default:
1580 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1581 }
1582 }
1583 return value
1584}
1585
Paul Duffinf34f6d82020-04-30 15:48:31 +01001586// A container of properties to be optimized.
1587//
1588// Allows additional information to be associated with the properties, e.g. for
1589// filtering.
1590type propertiesContainer interface {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001591 fmt.Stringer
1592
Paul Duffinf34f6d82020-04-30 15:48:31 +01001593 // Get the properties that need optimizing.
1594 optimizableProperties() interface{}
1595}
1596
Paul Duffin2d1bb892021-04-24 11:32:59 +01001597// A wrapper for sdk variant related properties to allow them to be optimized.
1598type sdkVariantPropertiesContainer struct {
1599 sdkVariant *sdk
1600 properties interface{}
Paul Duffinf34f6d82020-04-30 15:48:31 +01001601}
1602
Paul Duffin2d1bb892021-04-24 11:32:59 +01001603func (c sdkVariantPropertiesContainer) optimizableProperties() interface{} {
1604 return c.properties
Paul Duffinf34f6d82020-04-30 15:48:31 +01001605}
1606
Paul Duffin2d1bb892021-04-24 11:32:59 +01001607func (c sdkVariantPropertiesContainer) String() string {
Paul Duffin4b8b7932020-05-06 12:35:38 +01001608 return c.sdkVariant.String()
1609}
1610
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001611// Extract common properties from a slice of property structures of the same type.
1612//
1613// All the property structures must be of the same type.
1614// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001615// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001616//
1617// Iterates over each exported field (capitalized name) and checks to see whether they
1618// have the same value (using DeepEquals) across all the input properties. If it does not then no
1619// change is made. Otherwise, the common value is stored in the field in the commonProperties
Martin Stjernholmb0249572020-09-15 02:32:35 +01001620// and the field in each of the input properties structure is set to its default value. Nested
1621// structs are visited recursively and their non-struct fields are compared.
Paul Duffin4b8b7932020-05-06 12:35:38 +01001622func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) error {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001623 commonPropertiesValue := reflect.ValueOf(commonProperties)
1624 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001625
Paul Duffinf34f6d82020-04-30 15:48:31 +01001626 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1627
Paul Duffinb28369a2020-05-04 15:39:59 +01001628 for _, property := range e.properties {
1629 fieldGetter := property.getter
Paul Duffinc459f892020-04-30 18:08:29 +01001630 filter := property.filter
1631 if filter == nil {
1632 filter = func(metadata propertiesContainer) bool {
1633 return true
1634 }
1635 }
Paul Duffinb28369a2020-05-04 15:39:59 +01001636
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001637 // Check to see if all the structures have the same value for the field. The commonValue
Paul Duffin864e1b42020-05-06 10:23:19 +01001638 // is nil on entry to the loop and if it is nil on exit then there is no common value or
1639 // all the values have been filtered out, otherwise it points to the common value.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001640 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001641
Paul Duffin864e1b42020-05-06 10:23:19 +01001642 // Assume that all the values will be the same.
1643 //
1644 // While similar to this is not quite the same as commonValue == nil. If all the values
1645 // have been filtered out then this will be false but commonValue == nil will be true.
1646 valuesDiffer := false
1647
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001648 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001649 container := sliceValue.Index(i).Interface().(propertiesContainer)
1650 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001651 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001652
Paul Duffinc459f892020-04-30 18:08:29 +01001653 if !filter(container) {
1654 expectedValue := property.emptyValue.Interface()
1655 actualValue := fieldValue.Interface()
1656 if !reflect.DeepEqual(expectedValue, actualValue) {
1657 return fmt.Errorf("field %q is supposed to be ignored for %q but is set to %#v instead of %#v", property, container, actualValue, expectedValue)
1658 }
1659 continue
1660 }
1661
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001662 if commonValue == nil {
1663 // Use the first value as the commonProperties value.
1664 commonValue = &fieldValue
1665 } else {
1666 // If the value does not match the current common value then there is
1667 // no value in common so break out.
1668 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1669 commonValue = nil
Paul Duffin864e1b42020-05-06 10:23:19 +01001670 valuesDiffer = true
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001671 break
1672 }
1673 }
1674 }
1675
Paul Duffin864e1b42020-05-06 10:23:19 +01001676 // If the fields all have common value then store it in the common struct field
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001677 // and set the input struct's field to the empty value.
1678 if commonValue != nil {
Paul Duffinb28369a2020-05-04 15:39:59 +01001679 emptyValue := property.emptyValue
Paul Duffinc097e362020-03-10 22:50:03 +00001680 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001681 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001682 container := sliceValue.Index(i).Interface().(propertiesContainer)
1683 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001684 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001685 fieldValue.Set(emptyValue)
1686 }
1687 }
Paul Duffin864e1b42020-05-06 10:23:19 +01001688
1689 if valuesDiffer && !property.archVariant {
1690 // The values differ but the property does not support arch variants so it
1691 // is an error.
1692 var details strings.Builder
1693 for i := 0; i < sliceValue.Len(); i++ {
1694 container := sliceValue.Index(i).Interface().(propertiesContainer)
1695 itemValue := reflect.ValueOf(container.optimizableProperties())
1696 fieldValue := fieldGetter(itemValue)
1697
1698 _, _ = fmt.Fprintf(&details, "\n %q has value %q", container.String(), fieldValue.Interface())
1699 }
1700
1701 return fmt.Errorf("field %q is not tagged as \"arch_variant\" but has arch specific properties:%s", property.String(), details.String())
1702 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001703 }
Paul Duffin4b8b7932020-05-06 12:35:38 +01001704
1705 return nil
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001706}