blob: 75da2dd3cc4d9d9a2bf375ff9736e81b7b84af14 [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"
Paul Duffin375058f2019-11-29 20:17:53 +000025 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090026 "github.com/google/blueprint/proptools"
27
28 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090029)
30
31var pctx = android.NewPackageContext("android/soong/sdk")
32
Paul Duffin375058f2019-11-29 20:17:53 +000033var (
34 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
35 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000036 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000037 CommandDeps: []string{
38 "${config.Zip2ZipCmd}",
39 },
40 },
41 "destdir")
42
43 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
44 blueprint.RuleParams{
45 Command: `${config.SoongZipCmd} -C $basedir -l $out.rsp -o $out`,
46 CommandDeps: []string{
47 "${config.SoongZipCmd}",
48 },
49 Rspfile: "$out.rsp",
50 RspfileContent: "$in",
51 },
52 "basedir")
53
54 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
55 blueprint.RuleParams{
56 Command: `${config.MergeZipsCmd} $out $in`,
57 CommandDeps: []string{
58 "${config.MergeZipsCmd}",
59 },
60 })
61)
62
Paul Duffinb645ec82019-11-27 17:43:54 +000063type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090064 content strings.Builder
65 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090066}
67
Paul Duffinb645ec82019-11-27 17:43:54 +000068// generatedFile abstracts operations for writing contents into a file and emit a build rule
69// for the file.
70type generatedFile struct {
71 generatedContents
72 path android.OutputPath
73}
74
Jiyong Park232e7852019-11-04 12:23:40 +090075func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +090076 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +000077 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +090078 }
79}
80
Paul Duffinb645ec82019-11-27 17:43:54 +000081func (gc *generatedContents) Indent() {
82 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +090083}
84
Paul Duffinb645ec82019-11-27 17:43:54 +000085func (gc *generatedContents) Dedent() {
86 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +090087}
88
Paul Duffinb645ec82019-11-27 17:43:54 +000089func (gc *generatedContents) Printfln(format string, args ...interface{}) {
Jiyong Park9b409bc2019-10-11 14:59:13 +090090 // ninja consumes newline characters in rspfile_content. Prevent it by
Paul Duffin0e0cf1d2019-11-12 19:39:25 +000091 // escaping the backslash in the newline character. The extra backslash
Jiyong Park9b409bc2019-10-11 14:59:13 +090092 // is removed when the rspfile is written to the actual script file
Paul Duffinb645ec82019-11-27 17:43:54 +000093 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format+"\\n", args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +090094}
95
96func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
97 rb := android.NewRuleBuilder()
98 // convert \\n to \n
99 rb.Command().
100 Implicits(implicits).
101 Text("echo").Text(proptools.ShellEscape(gf.content.String())).
102 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
103 rb.Command().
104 Text("chmod a+x").Output(gf.path)
105 rb.Build(pctx, ctx, gf.path.Base(), "Build "+gf.path.Base())
106}
107
Paul Duffin13879572019-11-28 14:31:38 +0000108// Collect all the members.
109//
Paul Duffin6a7e9532020-03-20 17:50:07 +0000110// Returns a list containing type (extracted from the dependency tag) and the variant
111// plus the multilib usages.
112func (s *sdk) collectMembers(ctx android.ModuleContext) {
113 s.multilibUsages = multilibNone
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000114 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
115 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000116 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
117 memberType := memberTag.SdkMemberType()
Jiyong Park9b409bc2019-10-11 14:59:13 +0900118
Paul Duffin13879572019-11-28 14:31:38 +0000119 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000120 if !memberType.IsInstance(child) {
121 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900122 }
Paul Duffin13879572019-11-28 14:31:38 +0000123
Paul Duffin6a7e9532020-03-20 17:50:07 +0000124 // Keep track of which multilib variants are used by the sdk.
125 s.multilibUsages = s.multilibUsages.addArchType(child.Target().Arch.ArchType)
126
127 s.memberRefs = append(s.memberRefs, sdkMemberRef{memberType, child.(android.SdkAware)})
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000128
129 // If the member type supports transitive sdk members then recurse down into
130 // its dependencies, otherwise exit traversal.
131 return memberType.HasTransitiveSdkMembers()
Jiyong Park73c54ee2019-10-22 20:31:18 +0900132 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000133
134 return false
Paul Duffin13879572019-11-28 14:31:38 +0000135 })
Paul Duffin1356d8c2020-02-25 19:26:33 +0000136}
137
138// Organize the members.
139//
140// The members are first grouped by type and then grouped by name. The order of
141// the types is the order they are referenced in android.SdkMemberTypesRegistry.
142// The names are in the order in which the dependencies were added.
143//
144// Returns the members as well as the multilib setting to use.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000145func (s *sdk) organizeMembers(ctx android.ModuleContext, memberRefs []sdkMemberRef) []*sdkMember {
Paul Duffin1356d8c2020-02-25 19:26:33 +0000146 byType := make(map[android.SdkMemberType][]*sdkMember)
147 byName := make(map[string]*sdkMember)
148
Paul Duffin1356d8c2020-02-25 19:26:33 +0000149 for _, memberRef := range memberRefs {
150 memberType := memberRef.memberType
151 variant := memberRef.variant
152
153 name := ctx.OtherModuleName(variant)
154 member := byName[name]
155 if member == nil {
156 member = &sdkMember{memberType: memberType, name: name}
157 byName[name] = member
158 byType[memberType] = append(byType[memberType], member)
159 }
160
Paul Duffin1356d8c2020-02-25 19:26:33 +0000161 // Only append new variants to the list. This is needed because a member can be both
162 // exported by the sdk and also be a transitive sdk member.
163 member.variants = appendUniqueVariants(member.variants, variant)
164 }
165
Paul Duffin13879572019-11-28 14:31:38 +0000166 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000167 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000168 membersOfType := byType[memberListProperty.memberType]
169 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900170 }
171
Paul Duffin6a7e9532020-03-20 17:50:07 +0000172 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900173}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900174
Paul Duffin72910952020-01-20 18:16:30 +0000175func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
176 for _, v := range variants {
177 if v == newVariant {
178 return variants
179 }
180 }
181 return append(variants, newVariant)
182}
183
Jiyong Park73c54ee2019-10-22 20:31:18 +0900184// SDK directory structure
185// <sdk_root>/
186// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
187// <api_ver>/ : below this directory are all auto-generated
188// Android.bp : definition of 'sdk_snapshot' module is here
189// aidl/
190// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
191// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900192// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900193// include/
194// bionic/libc/include/stdlib.h : an exported header file
195// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900196// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900197// <arch>/include/ : arch-specific exported headers
198// <arch>/include_gen/ : arch-specific generated headers
199// <arch>/lib/
200// libFoo.so : a stub library
201
Jiyong Park232e7852019-11-04 12:23:40 +0900202// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900203// This isn't visible to users, so could be changed in future.
204func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
205 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
206}
207
Jiyong Park232e7852019-11-04 12:23:40 +0900208// buildSnapshot is the main function in this source file. It creates rules to copy
209// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000210func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
211
Paul Duffin13f02712020-03-06 12:30:43 +0000212 allMembersByName := make(map[string]struct{})
213 exportedMembersByName := make(map[string]struct{})
Paul Duffin1356d8c2020-02-25 19:26:33 +0000214 var memberRefs []sdkMemberRef
215 for _, sdkVariant := range sdkVariants {
216 memberRefs = append(memberRefs, sdkVariant.memberRefs...)
Paul Duffin865171e2020-03-02 18:38:15 +0000217
Paul Duffin13f02712020-03-06 12:30:43 +0000218 // Record the names of all the members, both explicitly specified and implicitly
219 // included.
220 for _, memberRef := range sdkVariant.memberRefs {
221 allMembersByName[memberRef.variant.Name()] = struct{}{}
222 }
223
Paul Duffin865171e2020-03-02 18:38:15 +0000224 // Merge the exported member sets from all sdk variants.
225 for key, _ := range sdkVariant.getExportedMembers() {
Paul Duffin13f02712020-03-06 12:30:43 +0000226 exportedMembersByName[key] = struct{}{}
Paul Duffin865171e2020-03-02 18:38:15 +0000227 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000228 }
229
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000230 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900231
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000232 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000233
234 bpFile := &bpFile{
235 modules: make(map[string]*bpModule),
236 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000237
238 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000239 ctx: ctx,
240 sdk: s,
241 version: "current",
242 snapshotDir: snapshotDir.OutputPath,
243 copies: make(map[string]string),
244 filesToZip: []android.Path{bp.path},
245 bpFile: bpFile,
246 prebuiltModules: make(map[string]*bpModule),
247 allMembersByName: allMembersByName,
248 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900249 }
Paul Duffinac37c502019-11-26 18:02:20 +0000250 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900251
Paul Duffin6a7e9532020-03-20 17:50:07 +0000252 members := s.organizeMembers(ctx, memberRefs)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000253 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000254 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000255
Paul Duffina551a1c2020-03-17 21:04:24 +0000256 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000257
258 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Paul Duffin495ffb92020-03-20 13:35:40 +0000259 s.createMemberSnapshot(memberCtx, member, prebuiltModule)
Jiyong Park73c54ee2019-10-22 20:31:18 +0900260 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900261
Paul Duffine6c0d842020-01-15 14:08:51 +0000262 // Create a transformer that will transform an unversioned module into a versioned module.
263 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
264
Paul Duffin72910952020-01-20 18:16:30 +0000265 // Create a transformer that will transform an unversioned module by replacing any references
266 // to internal members with a unique module name and setting prefer: false.
267 unversionedTransformer := unversionedTransformation{builder: builder}
268
Paul Duffinb645ec82019-11-27 17:43:54 +0000269 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000270 // Prune any empty property sets.
271 unversioned = unversioned.transform(pruneEmptySetTransformer{})
272
Paul Duffinb645ec82019-11-27 17:43:54 +0000273 // Copy the unversioned module so it can be modified to make it versioned.
Paul Duffincc72e982020-01-14 15:53:11 +0000274 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000275
276 // Transform the unversioned module into a versioned one.
277 versioned.transform(unversionedToVersionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000278 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000279
Paul Duffin72910952020-01-20 18:16:30 +0000280 // Transform the unversioned module to make it suitable for use in the snapshot.
281 unversioned.transform(unversionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000282 bpFile.AddModule(unversioned)
283 }
284
285 // Create the snapshot module.
286 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000287 var snapshotModuleType string
288 if s.properties.Module_exports {
289 snapshotModuleType = "module_exports_snapshot"
290 } else {
291 snapshotModuleType = "sdk_snapshot"
292 }
293 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000294 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000295
296 // Make sure that the snapshot has the same visibility as the sdk.
297 visibility := android.EffectiveVisibilityRules(ctx, s)
298 if len(visibility) != 0 {
299 snapshotModule.AddProperty("visibility", visibility)
300 }
301
Paul Duffin865171e2020-03-02 18:38:15 +0000302 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000303
Paul Duffinf34f6d82020-04-30 15:48:31 +0100304 var dynamicMemberPropertiesContainers []propertiesContainer
Paul Duffin865171e2020-03-02 18:38:15 +0000305 osTypeToMemberProperties := make(map[android.OsType]*sdk)
306 for _, sdkVariant := range sdkVariants {
307 properties := sdkVariant.dynamicMemberTypeListProperties
308 osTypeToMemberProperties[sdkVariant.Target().Os] = sdkVariant
Paul Duffinf34f6d82020-04-30 15:48:31 +0100309 dynamicMemberPropertiesContainers = append(dynamicMemberPropertiesContainers, &dynamicMemberPropertiesContainer{properties})
Paul Duffin865171e2020-03-02 18:38:15 +0000310 }
311
312 // Extract the common lists of members into a separate struct.
313 commonDynamicMemberProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffinc097e362020-03-10 22:50:03 +0000314 extractor := newCommonValueExtractor(commonDynamicMemberProperties)
Paul Duffinf34f6d82020-04-30 15:48:31 +0100315 extractor.extractCommonProperties(commonDynamicMemberProperties, dynamicMemberPropertiesContainers)
Paul Duffin865171e2020-03-02 18:38:15 +0000316
317 // Add properties common to all os types.
318 s.addMemberPropertiesToPropertySet(builder, snapshotModule, commonDynamicMemberProperties)
319
320 // Iterate over the os types in a fixed order.
Paul Duffin6a7e9532020-03-20 17:50:07 +0000321 targetPropertySet := snapshotModule.AddPropertySet("target")
Paul Duffin865171e2020-03-02 18:38:15 +0000322 for _, osType := range s.getPossibleOsTypes() {
323 if sdkVariant, ok := osTypeToMemberProperties[osType]; ok {
324 osPropertySet := targetPropertySet.AddPropertySet(sdkVariant.Target().Os.Name)
Paul Duffin6a7e9532020-03-20 17:50:07 +0000325
326 // Compile_multilib defaults to both and must always be set to both on the
327 // device and so only needs to be set when targeted at the host and is neither
328 // unspecified or both.
329 multilib := sdkVariant.multilibUsages
330 if (osType.Class == android.Host || osType.Class == android.HostCross) &&
331 multilib != multilibNone && multilib != multilibBoth {
332 osPropertySet.AddProperty("compile_multilib", multilib.String())
333 }
334
Paul Duffin865171e2020-03-02 18:38:15 +0000335 s.addMemberPropertiesToPropertySet(builder, osPropertySet, sdkVariant.dynamicMemberTypeListProperties)
Paul Duffin13879572019-11-28 14:31:38 +0000336 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000337 }
Paul Duffin865171e2020-03-02 18:38:15 +0000338
339 // Prune any empty property sets.
340 snapshotModule.transform(pruneEmptySetTransformer{})
341
Paul Duffinb645ec82019-11-27 17:43:54 +0000342 bpFile.AddModule(snapshotModule)
343
344 // generate Android.bp
345 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
346 generateBpContents(&bp.generatedContents, bpFile)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000347
348 bp.build(pctx, ctx, nil)
349
350 filesToZip := builder.filesToZip
Jiyong Park9b409bc2019-10-11 14:59:13 +0900351
Jiyong Park232e7852019-11-04 12:23:40 +0900352 // zip them all
Paul Duffin91547182019-11-12 19:39:36 +0000353 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000354 outputDesc := "Building snapshot for " + ctx.ModuleName()
355
356 // If there are no zips to merge then generate the output zip directly.
357 // Otherwise, generate an intermediate zip file into which other zips can be
358 // merged.
359 var zipFile android.OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000360 var desc string
361 if len(builder.zipsToMerge) == 0 {
362 zipFile = outputZipFile
Paul Duffin91547182019-11-12 19:39:36 +0000363 desc = outputDesc
364 } else {
365 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000366 desc = "Building intermediate snapshot for " + ctx.ModuleName()
367 }
368
Paul Duffin375058f2019-11-29 20:17:53 +0000369 ctx.Build(pctx, android.BuildParams{
370 Description: desc,
371 Rule: zipFiles,
372 Inputs: filesToZip,
373 Output: zipFile,
374 Args: map[string]string{
375 "basedir": builder.snapshotDir.String(),
376 },
377 })
Jiyong Park9b409bc2019-10-11 14:59:13 +0900378
Paul Duffin91547182019-11-12 19:39:36 +0000379 if len(builder.zipsToMerge) != 0 {
Paul Duffin375058f2019-11-29 20:17:53 +0000380 ctx.Build(pctx, android.BuildParams{
381 Description: outputDesc,
382 Rule: mergeZips,
383 Input: zipFile,
384 Inputs: builder.zipsToMerge,
385 Output: outputZipFile,
386 })
Paul Duffin91547182019-11-12 19:39:36 +0000387 }
388
389 return outputZipFile
Jiyong Park9b409bc2019-10-11 14:59:13 +0900390}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000391
Paul Duffin865171e2020-03-02 18:38:15 +0000392func (s *sdk) addMemberPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, dynamicMemberTypeListProperties interface{}) {
393 for _, memberListProperty := range s.memberListProperties() {
394 names := memberListProperty.getter(dynamicMemberTypeListProperties)
395 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000396 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000397 }
398 }
399}
400
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000401type propertyTag struct {
402 name string
403}
404
Paul Duffin0cb37b92020-03-04 14:52:46 +0000405// A BpPropertyTag to add to a property that contains references to other sdk members.
406//
407// This will cause the references to be rewritten to a versioned reference in the version
408// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000409var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000410var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000411
Paul Duffin0cb37b92020-03-04 14:52:46 +0000412// A BpPropertyTag that indicates the property should only be present in the versioned
413// module.
414//
415// This will cause the property to be removed from the unversioned instance of a
416// snapshot module.
417var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
418
Paul Duffine6c0d842020-01-15 14:08:51 +0000419type unversionedToVersionedTransformation struct {
420 identityTransformation
421 builder *snapshotBuilder
422}
423
Paul Duffine6c0d842020-01-15 14:08:51 +0000424func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
425 // Use a versioned name for the module but remember the original name for the
426 // snapshot.
427 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000428 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000429 module.insertAfter("name", "sdk_member_name", name)
430 return module
431}
432
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000433func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000434 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
435 required := tag == requiredSdkMemberReferencePropertyTag
436 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000437 } else {
438 return value, tag
439 }
440}
441
Paul Duffin72910952020-01-20 18:16:30 +0000442type unversionedTransformation struct {
443 identityTransformation
444 builder *snapshotBuilder
445}
446
447func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
448 // If the module is an internal member then use a unique name for it.
449 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000450 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000451
452 // Set prefer: false - this is not strictly required as that is the default.
453 module.insertAfter("name", "prefer", false)
454
455 return module
456}
457
458func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000459 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
460 required := tag == requiredSdkMemberReferencePropertyTag
461 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000462 } else if tag == sdkVersionedOnlyPropertyTag {
463 // The property is not allowed in the unversioned module so remove it.
464 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000465 } else {
466 return value, tag
467 }
468}
469
Paul Duffina78f3a72020-02-21 16:29:35 +0000470type pruneEmptySetTransformer struct {
471 identityTransformation
472}
473
474var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
475
476func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
477 if len(propertySet.properties) == 0 {
478 return nil, nil
479 } else {
480 return propertySet, tag
481 }
482}
483
Paul Duffinb645ec82019-11-27 17:43:54 +0000484func generateBpContents(contents *generatedContents, bpFile *bpFile) {
485 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
486 for _, bpModule := range bpFile.order {
487 contents.Printfln("")
488 contents.Printfln("%s {", bpModule.moduleType)
Paul Duffincc72e982020-01-14 15:53:11 +0000489 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffinb645ec82019-11-27 17:43:54 +0000490 contents.Printfln("}")
491 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000492}
493
494func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
495 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000496
497 // Output the properties first, followed by the nested sets. This ensures a
498 // consistent output irrespective of whether property sets are created before
499 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000500 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000501 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000502
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000503 switch v := value.(type) {
504 case []string:
505 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000506 if length > 1 {
507 contents.Printfln("%s: [", name)
508 contents.Indent()
509 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000510 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000511 }
512 contents.Dedent()
513 contents.Printfln("],")
514 } else if length == 0 {
515 contents.Printfln("%s: [],", name)
516 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000517 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000518 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000519
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000520 case bool:
521 contents.Printfln("%s: %t,", name, v)
522
523 case *bpPropertySet:
524 // Do not write property sets in the properties phase.
Paul Duffinb645ec82019-11-27 17:43:54 +0000525
526 default:
527 contents.Printfln("%s: %q,", name, value)
528 }
529 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000530
531 for _, name := range set.order {
532 value := set.getValue(name)
533
534 // Only write property sets in the sets phase.
535 switch v := value.(type) {
536 case *bpPropertySet:
537 contents.Printfln("%s: {", name)
538 outputPropertySet(contents, v)
539 contents.Printfln("},")
540 }
541 }
542
Paul Duffinb645ec82019-11-27 17:43:54 +0000543 contents.Dedent()
544}
545
Paul Duffinac37c502019-11-26 18:02:20 +0000546func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000547 contents := &generatedContents{}
548 generateBpContents(contents, s.builderForTests.bpFile)
549 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000550}
551
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000552type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000553 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000554 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000555 version string
556 snapshotDir android.OutputPath
557 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000558
559 // Map from destination to source of each copy - used to eliminate duplicates and
560 // detect conflicts.
561 copies map[string]string
562
Paul Duffinb645ec82019-11-27 17:43:54 +0000563 filesToZip android.Paths
564 zipsToMerge android.Paths
565
566 prebuiltModules map[string]*bpModule
567 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000568
569 // The set of all members by name.
570 allMembersByName map[string]struct{}
571
572 // The set of exported members by name.
573 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000574}
575
576func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000577 if existing, ok := s.copies[dest]; ok {
578 if existing != src.String() {
579 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
580 return
581 }
582 } else {
583 path := s.snapshotDir.Join(s.ctx, dest)
584 s.ctx.Build(pctx, android.BuildParams{
585 Rule: android.Cp,
586 Input: src,
587 Output: path,
588 })
589 s.filesToZip = append(s.filesToZip, path)
590
591 s.copies[dest] = src.String()
592 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000593}
594
Paul Duffin91547182019-11-12 19:39:36 +0000595func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
596 ctx := s.ctx
597
598 // Repackage the zip file so that the entries are in the destDir directory.
599 // This will allow the zip file to be merged into the snapshot.
600 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000601
602 ctx.Build(pctx, android.BuildParams{
603 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
604 Rule: repackageZip,
605 Input: zipPath,
606 Output: tmpZipPath,
607 Args: map[string]string{
608 "destdir": destDir,
609 },
610 })
Paul Duffin91547182019-11-12 19:39:36 +0000611
612 // Add the repackaged zip file to the files to merge.
613 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
614}
615
Paul Duffin9d8d6092019-12-05 18:19:29 +0000616func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
617 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000618 if s.prebuiltModules[name] != nil {
619 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
620 }
621
622 m := s.bpFile.newModule(moduleType)
623 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000624
Paul Duffinbefa4b92020-03-04 14:22:45 +0000625 variant := member.Variants()[0]
626
Paul Duffin13f02712020-03-06 12:30:43 +0000627 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000628 // An internal member is only referenced from the sdk snapshot which is in the
629 // same package so can be marked as private.
630 m.AddProperty("visibility", []string{"//visibility:private"})
631 } else {
632 // Extract visibility information from a member variant. All variants have the same
633 // visibility so it doesn't matter which one is used.
Paul Duffinbefa4b92020-03-04 14:22:45 +0000634 visibility := android.EffectiveVisibilityRules(s.ctx, variant)
Paul Duffin72910952020-01-20 18:16:30 +0000635 if len(visibility) != 0 {
636 m.AddProperty("visibility", visibility)
637 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000638 }
639
Paul Duffin865171e2020-03-02 18:38:15 +0000640 deviceSupported := false
641 hostSupported := false
642
643 for _, variant := range member.Variants() {
644 osClass := variant.Target().Os.Class
645 if osClass == android.Host || osClass == android.HostCross {
646 hostSupported = true
647 } else if osClass == android.Device {
648 deviceSupported = true
649 }
650 }
651
652 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000653
Paul Duffinbefa4b92020-03-04 14:22:45 +0000654 // Where available copy apex_available properties from the member.
655 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
656 apexAvailable := apexAware.ApexAvailable()
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000657
658 // Add in any white listed apex available settings.
659 apexAvailable = append(apexAvailable, apex.WhitelistedApexAvailable(member.Name())...)
660
Paul Duffinbefa4b92020-03-04 14:22:45 +0000661 if len(apexAvailable) > 0 {
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000662 // Remove duplicates and sort.
663 apexAvailable = android.FirstUniqueStrings(apexAvailable)
664 sort.Strings(apexAvailable)
665
Paul Duffinbefa4b92020-03-04 14:22:45 +0000666 m.AddProperty("apex_available", apexAvailable)
667 }
668 }
669
Paul Duffin0cb37b92020-03-04 14:52:46 +0000670 // Disable installation in the versioned module of those modules that are ever installable.
671 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
672 if installable.EverInstallable() {
673 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
674 }
675 }
676
Paul Duffinb645ec82019-11-27 17:43:54 +0000677 s.prebuiltModules[name] = m
678 s.prebuiltOrder = append(s.prebuiltOrder, m)
679 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000680}
681
Paul Duffin865171e2020-03-02 18:38:15 +0000682func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
683 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000684 bpModule.AddProperty("device_supported", false)
685 }
Paul Duffin865171e2020-03-02 18:38:15 +0000686 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000687 bpModule.AddProperty("host_supported", true)
688 }
689}
690
Paul Duffin13f02712020-03-06 12:30:43 +0000691func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
692 if required {
693 return requiredSdkMemberReferencePropertyTag
694 } else {
695 return optionalSdkMemberReferencePropertyTag
696 }
697}
698
699func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
700 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000701}
702
Paul Duffinb645ec82019-11-27 17:43:54 +0000703// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +0000704func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
705 if _, ok := s.allMembersByName[unversionedName]; !ok {
706 if required {
707 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
708 }
709 return unversionedName
710 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000711 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
712}
Paul Duffinb645ec82019-11-27 17:43:54 +0000713
Paul Duffin13f02712020-03-06 12:30:43 +0000714func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000715 var references []string = nil
716 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000717 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000718 }
719 return references
720}
Paul Duffin13879572019-11-28 14:31:38 +0000721
Paul Duffin72910952020-01-20 18:16:30 +0000722// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +0000723func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
724 if _, ok := s.allMembersByName[unversionedName]; !ok {
725 if required {
726 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
727 }
728 return unversionedName
729 }
730
731 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +0000732 return s.ctx.ModuleName() + "_" + unversionedName
733 } else {
734 return unversionedName
735 }
736}
737
Paul Duffin13f02712020-03-06 12:30:43 +0000738func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +0000739 var references []string = nil
740 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000741 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +0000742 }
743 return references
744}
745
Paul Duffin13f02712020-03-06 12:30:43 +0000746func (s *snapshotBuilder) isInternalMember(memberName string) bool {
747 _, ok := s.exportedMembersByName[memberName]
748 return !ok
749}
750
Paul Duffin1356d8c2020-02-25 19:26:33 +0000751type sdkMemberRef struct {
752 memberType android.SdkMemberType
753 variant android.SdkAware
754}
755
Paul Duffin13879572019-11-28 14:31:38 +0000756var _ android.SdkMember = (*sdkMember)(nil)
757
758type sdkMember struct {
759 memberType android.SdkMemberType
760 name string
761 variants []android.SdkAware
762}
763
764func (m *sdkMember) Name() string {
765 return m.name
766}
767
768func (m *sdkMember) Variants() []android.SdkAware {
769 return m.variants
770}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000771
Paul Duffin9c3760e2020-03-16 19:52:08 +0000772// Track usages of multilib variants.
773type multilibUsage int
774
775const (
776 multilibNone multilibUsage = 0
777 multilib32 multilibUsage = 1
778 multilib64 multilibUsage = 2
779 multilibBoth = multilib32 | multilib64
780)
781
782// Add the multilib that is used in the arch type.
783func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
784 multilib := archType.Multilib
785 switch multilib {
786 case "":
787 return m
788 case "lib32":
789 return m | multilib32
790 case "lib64":
791 return m | multilib64
792 default:
793 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
794 }
795}
796
797func (m multilibUsage) String() string {
798 switch m {
799 case multilibNone:
800 return ""
801 case multilib32:
802 return "32"
803 case multilib64:
804 return "64"
805 case multilibBoth:
806 return "both"
807 default:
808 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
809 m, multilibNone, multilib32, multilib64, multilibBoth))
810 }
811}
812
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000813type baseInfo struct {
814 Properties android.SdkMemberProperties
815}
816
Paul Duffinf34f6d82020-04-30 15:48:31 +0100817func (b *baseInfo) optimizableProperties() interface{} {
818 return b.Properties
819}
820
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000821type osTypeSpecificInfo struct {
822 baseInfo
823
Paul Duffin00e46802020-03-12 20:40:35 +0000824 osType android.OsType
825
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000826 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +0000827 //
828 // Nil if there is one variant whose arch type is common
829 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000830}
831
Paul Duffinfc8dd232020-03-17 12:51:37 +0000832type variantPropertiesFactoryFunc func() android.SdkMemberProperties
833
Paul Duffin00e46802020-03-12 20:40:35 +0000834// Create a new osTypeSpecificInfo for the specified os type and its properties
835// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000836func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +0000837 osInfo := &osTypeSpecificInfo{
838 osType: osType,
839 }
840
841 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
842 properties := variantPropertiesFactory()
843 properties.Base().Os = osType
844 return properties
845 }
846
847 // Create a structure into which properties common across the architectures in
848 // this os type will be stored.
849 osInfo.Properties = osSpecificVariantPropertiesFactory()
850
851 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000852 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +0000853 var archTypes []android.ArchType
854 for _, variant := range osTypeVariants {
855 archType := variant.Target().Arch.ArchType
856 archTypeName := archType.Name
857 if _, ok := variantsByArchName[archTypeName]; !ok {
858 archTypes = append(archTypes, archType)
859 }
860
861 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
862 }
863
864 if commonVariants, ok := variantsByArchName["common"]; ok {
865 if len(osTypeVariants) != 1 {
866 panic("Expected to only have 1 variant when arch type is common but found " + string(len(osTypeVariants)))
867 }
868
869 // A common arch type only has one variant and its properties should be treated
870 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000871 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +0000872 } else {
873 // Create an arch specific info for each supported architecture type.
874 for _, archType := range archTypes {
875 archTypeName := archType.Name
876
877 archVariants := variantsByArchName[archTypeName]
Paul Duffin3a4eb502020-03-19 16:11:18 +0000878 archInfo := newArchSpecificInfo(ctx, archType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +0000879
880 osInfo.archInfos = append(osInfo.archInfos, archInfo)
881 }
882 }
883
884 return osInfo
885}
886
887// Optimize the properties by extracting common properties from arch type specific
888// properties into os type specific properties.
889func (osInfo *osTypeSpecificInfo) optimizeProperties(commonValueExtractor *commonValueExtractor) {
890 // Nothing to do if there is only a single common architecture.
891 if len(osInfo.archInfos) == 0 {
892 return
893 }
894
Paul Duffin9c3760e2020-03-16 19:52:08 +0000895 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +0000896 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +0000897 multilib = multilib.addArchType(archInfo.archType)
898
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000899 // Optimize the arch properties first.
900 archInfo.optimizeProperties(commonValueExtractor)
Paul Duffin00e46802020-03-12 20:40:35 +0000901 }
902
Paul Duffinf34f6d82020-04-30 15:48:31 +0100903 commonValueExtractor.extractCommonProperties(osInfo.Properties, osInfo.archInfos)
Paul Duffin00e46802020-03-12 20:40:35 +0000904
905 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +0000906 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +0000907}
908
909// Add the properties for an os to a property set.
910//
911// Maps the properties related to the os variants through to an appropriate
912// module structure that will produce equivalent set of variants when it is
913// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000914func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +0000915
916 var osPropertySet android.BpPropertySet
917 var archPropertySet android.BpPropertySet
918 var archOsPrefix string
919 if osInfo.Properties.Base().Os_count == 1 {
920 // There is only one os type present in the variants so don't bother
921 // with adding target specific properties.
922
923 // Create a structure that looks like:
924 // module_type {
925 // name: "...",
926 // ...
927 // <common properties>
928 // ...
929 // <single os type specific properties>
930 //
931 // arch: {
932 // <arch specific sections>
933 // }
934 //
935 osPropertySet = bpModule
936 archPropertySet = osPropertySet.AddPropertySet("arch")
937
938 // Arch specific properties need to be added to an arch specific section
939 // within arch.
940 archOsPrefix = ""
941 } else {
942 // Create a structure that looks like:
943 // module_type {
944 // name: "...",
945 // ...
946 // <common properties>
947 // ...
948 // target: {
949 // <arch independent os specific sections, e.g. android>
950 // ...
951 // <arch and os specific sections, e.g. android_x86>
952 // }
953 //
954 osType := osInfo.osType
955 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
956 archPropertySet = targetPropertySet
957
958 // Arch specific properties need to be added to an os and arch specific
959 // section prefixed with <os>_.
960 archOsPrefix = osType.Name + "_"
961 }
962
963 // Add the os specific but arch independent properties to the module.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000964 osInfo.Properties.AddToPropertySet(ctx, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +0000965
966 // Add arch (and possibly os) specific sections for each set of arch (and possibly
967 // os) specific properties.
968 //
969 // The archInfos list will be empty if the os contains variants for the common
970 // architecture.
971 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +0000972 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +0000973 }
974}
975
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000976type archTypeSpecificInfo struct {
977 baseInfo
978
979 archType android.ArchType
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000980
981 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000982}
983
Paul Duffinfc8dd232020-03-17 12:51:37 +0000984// Create a new archTypeSpecificInfo for the specified arch type and its properties
985// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000986func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +0000987
Paul Duffinfc8dd232020-03-17 12:51:37 +0000988 // Create an arch specific info into which the variant properties can be copied.
989 archInfo := &archTypeSpecificInfo{archType: archType}
990
991 // Create the properties into which the arch type specific properties will be
992 // added.
993 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000994
995 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +0000996 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000997 } else {
998 // There is more than one variant for this arch type which must be differentiated
999 // by link type.
1000 for _, linkVariant := range archVariants {
1001 linkType := getLinkType(linkVariant)
1002 if linkType == "" {
1003 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1004 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001005 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001006
1007 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1008 }
1009 }
1010 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001011
1012 return archInfo
1013}
1014
Paul Duffinf34f6d82020-04-30 15:48:31 +01001015func (archInfo *archTypeSpecificInfo) optimizableProperties() interface{} {
1016 return archInfo.Properties
1017}
1018
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001019// Get the link type of the variant
1020//
1021// If the variant is not differentiated by link type then it returns "",
1022// otherwise it returns one of "static" or "shared".
1023func getLinkType(variant android.Module) string {
1024 linkType := ""
1025 if linkable, ok := variant.(cc.LinkableInterface); ok {
1026 if linkable.Shared() && linkable.Static() {
1027 panic(fmt.Errorf("expected variant %q to be either static or shared but was both", variant.String()))
1028 } else if linkable.Shared() {
1029 linkType = "shared"
1030 } else if linkable.Static() {
1031 linkType = "static"
1032 } else {
1033 panic(fmt.Errorf("expected variant %q to be either static or shared but was neither", variant.String()))
1034 }
1035 }
1036 return linkType
1037}
1038
1039// Optimize the properties by extracting common properties from link type specific
1040// properties into arch type specific properties.
1041func (archInfo *archTypeSpecificInfo) optimizeProperties(commonValueExtractor *commonValueExtractor) {
1042 if len(archInfo.linkInfos) == 0 {
1043 return
1044 }
1045
Paul Duffinf34f6d82020-04-30 15:48:31 +01001046 commonValueExtractor.extractCommonProperties(archInfo.Properties, archInfo.linkInfos)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001047}
1048
Paul Duffinfc8dd232020-03-17 12:51:37 +00001049// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001050func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001051 archTypeName := archInfo.archType.Name
1052 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Paul Duffin3a4eb502020-03-19 16:11:18 +00001053 archInfo.Properties.AddToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001054
1055 for _, linkInfo := range archInfo.linkInfos {
1056 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Paul Duffin3a4eb502020-03-19 16:11:18 +00001057 linkInfo.Properties.AddToPropertySet(ctx, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001058 }
1059}
1060
1061type linkTypeSpecificInfo struct {
1062 baseInfo
1063
1064 linkType string
1065}
1066
1067// Create a new linkTypeSpecificInfo for the specified link type and its properties
1068// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001069func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001070 linkInfo := &linkTypeSpecificInfo{
1071 baseInfo: baseInfo{
1072 // Create the properties into which the link type specific properties will be
1073 // added.
1074 Properties: variantPropertiesFactory(),
1075 },
1076 linkType: linkType,
1077 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001078 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001079 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001080}
1081
Paul Duffin3a4eb502020-03-19 16:11:18 +00001082type memberContext struct {
1083 sdkMemberContext android.ModuleContext
1084 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001085 memberType android.SdkMemberType
1086 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001087}
1088
1089func (m *memberContext) SdkModuleContext() android.ModuleContext {
1090 return m.sdkMemberContext
1091}
1092
1093func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1094 return m.builder
1095}
1096
Paul Duffina551a1c2020-03-17 21:04:24 +00001097func (m *memberContext) MemberType() android.SdkMemberType {
1098 return m.memberType
1099}
1100
1101func (m *memberContext) Name() string {
1102 return m.name
1103}
1104
Paul Duffin3a4eb502020-03-19 16:11:18 +00001105func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule android.BpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001106
1107 memberType := member.memberType
1108
Paul Duffina04c1072020-03-02 10:16:35 +00001109 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001110 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001111 variants := member.Variants()
1112 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001113 osType := variant.Target().Os
1114 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001115 }
1116
Paul Duffina04c1072020-03-02 10:16:35 +00001117 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001118 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001119 properties := memberType.CreateVariantPropertiesStruct()
1120 base := properties.Base()
1121 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001122 return properties
1123 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001124
Paul Duffina04c1072020-03-02 10:16:35 +00001125 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001126
Paul Duffina04c1072020-03-02 10:16:35 +00001127 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001128 commonProperties := variantPropertiesFactory()
1129 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001130
Paul Duffinc097e362020-03-10 22:50:03 +00001131 // Create common value extractor that can be used to optimize the properties.
1132 commonValueExtractor := newCommonValueExtractor(commonProperties)
1133
Paul Duffina04c1072020-03-02 10:16:35 +00001134 // The list of property structures which are os type specific but common across
1135 // architectures within that os type.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001136 var osSpecificPropertiesContainers []*osTypeSpecificInfo
Paul Duffina04c1072020-03-02 10:16:35 +00001137
1138 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001139 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001140 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001141 // Add the os specific properties to a list of os type specific yet architecture
1142 // independent properties structs.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001143 osSpecificPropertiesContainers = append(osSpecificPropertiesContainers, osInfo)
Paul Duffina04c1072020-03-02 10:16:35 +00001144
Paul Duffin00e46802020-03-12 20:40:35 +00001145 // Optimize the properties across all the variants for a specific os type.
1146 osInfo.optimizeProperties(commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001147 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001148
Paul Duffina04c1072020-03-02 10:16:35 +00001149 // Extract properties which are common across all architectures and os types.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001150 commonValueExtractor.extractCommonProperties(commonProperties, osSpecificPropertiesContainers)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001151
Paul Duffina04c1072020-03-02 10:16:35 +00001152 // Add the common properties to the module.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001153 commonProperties.AddToPropertySet(ctx, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001154
Paul Duffina04c1072020-03-02 10:16:35 +00001155 // Create a target property set into which target specific properties can be
1156 // added.
1157 targetPropertySet := bpModule.AddPropertySet("target")
1158
1159 // Iterate over the os types in a fixed order.
1160 for _, osType := range s.getPossibleOsTypes() {
1161 osInfo := osTypeToInfo[osType]
1162 if osInfo == nil {
1163 continue
1164 }
1165
Paul Duffin3a4eb502020-03-19 16:11:18 +00001166 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001167 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001168}
1169
Paul Duffina04c1072020-03-02 10:16:35 +00001170// Compute the list of possible os types that this sdk could support.
1171func (s *sdk) getPossibleOsTypes() []android.OsType {
1172 var osTypes []android.OsType
1173 for _, osType := range android.OsTypeList {
1174 if s.DeviceSupported() {
1175 if osType.Class == android.Device && osType != android.Fuchsia {
1176 osTypes = append(osTypes, osType)
1177 }
1178 }
1179 if s.HostSupported() {
1180 if osType.Class == android.Host || osType.Class == android.HostCross {
1181 osTypes = append(osTypes, osType)
1182 }
1183 }
1184 }
1185 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1186 return osTypes
1187}
1188
Paul Duffinb07fa512020-03-10 22:17:04 +00001189// Given a struct value, access a field within that struct (or one of its embedded
1190// structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001191type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1192
1193// Supports extracting common values from a number of instances of a properties
1194// structure into a separate common set of properties.
1195type commonValueExtractor struct {
1196 // The getters for every field from which common values can be extracted.
1197 fieldGetters []fieldAccessorFunc
1198}
1199
1200// Create a new common value extractor for the structure type for the supplied
1201// properties struct.
1202//
1203// The returned extractor can be used on any properties structure of the same type
1204// as the supplied set of properties.
1205func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1206 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1207 extractor := &commonValueExtractor{}
Paul Duffinb07fa512020-03-10 22:17:04 +00001208 extractor.gatherFields(structType, nil)
Paul Duffinc097e362020-03-10 22:50:03 +00001209 return extractor
1210}
1211
1212// Gather the fields from the supplied structure type from which common values will
1213// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001214//
1215// This is recursive function. If it encounters an embedded field (no field name)
1216// that is a struct then it will recurse into that struct passing in the accessor
1217// for the field. That will then be used in the accessors for the fields in the
1218// embedded struct.
1219func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc) {
Paul Duffinc097e362020-03-10 22:50:03 +00001220 for f := 0; f < structType.NumField(); f++ {
1221 field := structType.Field(f)
1222 if field.PkgPath != "" {
1223 // Ignore unexported fields.
1224 continue
1225 }
1226
Paul Duffinb07fa512020-03-10 22:17:04 +00001227 // Ignore fields whose value should be kept.
1228 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001229 continue
1230 }
1231
1232 // Save a copy of the field index for use in the function.
1233 fieldIndex := f
1234 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001235 if containingStructAccessor != nil {
1236 // This is an embedded structure so first access the field for the embedded
1237 // structure.
1238 value = containingStructAccessor(value)
1239 }
1240
Paul Duffinc097e362020-03-10 22:50:03 +00001241 // Skip through interface and pointer values to find the structure.
1242 value = getStructValue(value)
1243
1244 // Return the field.
1245 return value.Field(fieldIndex)
1246 }
1247
Paul Duffinb07fa512020-03-10 22:17:04 +00001248 if field.Type.Kind() == reflect.Struct && field.Anonymous {
1249 // Gather fields from the embedded structure.
1250 e.gatherFields(field.Type, fieldGetter)
1251 } else {
1252 e.fieldGetters = append(e.fieldGetters, fieldGetter)
1253 }
Paul Duffinc097e362020-03-10 22:50:03 +00001254 }
1255}
1256
1257func getStructValue(value reflect.Value) reflect.Value {
1258foundStruct:
1259 for {
1260 kind := value.Kind()
1261 switch kind {
1262 case reflect.Interface, reflect.Ptr:
1263 value = value.Elem()
1264 case reflect.Struct:
1265 break foundStruct
1266 default:
1267 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1268 }
1269 }
1270 return value
1271}
1272
Paul Duffinf34f6d82020-04-30 15:48:31 +01001273// A container of properties to be optimized.
1274//
1275// Allows additional information to be associated with the properties, e.g. for
1276// filtering.
1277type propertiesContainer interface {
1278 // Get the properties that need optimizing.
1279 optimizableProperties() interface{}
1280}
1281
1282// A wrapper for dynamic member properties to allow them to be optimized.
1283type dynamicMemberPropertiesContainer struct {
1284 dynamicMemberProperties interface{}
1285}
1286
1287func (c dynamicMemberPropertiesContainer) optimizableProperties() interface{} {
1288 return c.dynamicMemberProperties
1289}
1290
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001291// Extract common properties from a slice of property structures of the same type.
1292//
1293// All the property structures must be of the same type.
1294// commonProperties - must be a pointer to the structure into which common properties will be added.
Paul Duffinf34f6d82020-04-30 15:48:31 +01001295// inputPropertiesSlice - must be a slice of propertiesContainer interfaces.
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001296//
1297// Iterates over each exported field (capitalized name) and checks to see whether they
1298// have the same value (using DeepEquals) across all the input properties. If it does not then no
1299// change is made. Otherwise, the common value is stored in the field in the commonProperties
1300// and the field in each of the input properties structure is set to its default value.
Paul Duffinc097e362020-03-10 22:50:03 +00001301func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001302 commonPropertiesValue := reflect.ValueOf(commonProperties)
1303 commonStructValue := commonPropertiesValue.Elem()
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001304
Paul Duffinf34f6d82020-04-30 15:48:31 +01001305 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1306
Paul Duffinc097e362020-03-10 22:50:03 +00001307 for _, fieldGetter := range e.fieldGetters {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001308 // Check to see if all the structures have the same value for the field. The commonValue
1309 // is nil on entry to the loop and if it is nil on exit then there is no common value,
1310 // otherwise it points to the common value.
1311 var commonValue *reflect.Value
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001312
1313 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001314 container := sliceValue.Index(i).Interface().(propertiesContainer)
1315 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001316 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001317
1318 if commonValue == nil {
1319 // Use the first value as the commonProperties value.
1320 commonValue = &fieldValue
1321 } else {
1322 // If the value does not match the current common value then there is
1323 // no value in common so break out.
1324 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1325 commonValue = nil
1326 break
1327 }
1328 }
1329 }
1330
1331 // If the fields all have a common value then store it in the common struct field
1332 // and set the input struct's field to the empty value.
1333 if commonValue != nil {
Paul Duffin7b5f1a62020-03-20 20:45:04 +00001334 emptyValue := reflect.Zero(commonValue.Type())
Paul Duffinc097e362020-03-10 22:50:03 +00001335 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001336 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinf34f6d82020-04-30 15:48:31 +01001337 container := sliceValue.Index(i).Interface().(propertiesContainer)
1338 itemValue := reflect.ValueOf(container.optimizableProperties())
Paul Duffinc097e362020-03-10 22:50:03 +00001339 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001340 fieldValue.Set(emptyValue)
1341 }
1342 }
1343 }
1344}