blob: 3ff0c1d1cd4f4153237344749edf69491f58adce [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 Duffin1356d8c2020-02-25 19:26:33 +0000110// Returns a list containing type (extracted from the dependency tag) and the variant.
111func (s *sdk) collectMembers(ctx android.ModuleContext) []sdkMemberRef {
112 var memberRefs []sdkMemberRef
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000113 ctx.WalkDeps(func(child android.Module, parent android.Module) bool {
114 tag := ctx.OtherModuleDependencyTag(child)
Paul Duffinf8539922019-11-19 19:44:10 +0000115 if memberTag, ok := tag.(android.SdkMemberTypeDependencyTag); ok {
116 memberType := memberTag.SdkMemberType()
Jiyong Park9b409bc2019-10-11 14:59:13 +0900117
Paul Duffin13879572019-11-28 14:31:38 +0000118 // Make sure that the resolved module is allowed in the member list property.
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000119 if !memberType.IsInstance(child) {
120 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(child), memberType.SdkPropertyName())
Jiyong Park73c54ee2019-10-22 20:31:18 +0900121 }
Paul Duffin13879572019-11-28 14:31:38 +0000122
Paul Duffin1356d8c2020-02-25 19:26:33 +0000123 memberRefs = append(memberRefs, sdkMemberRef{memberType, child.(android.SdkAware)})
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000124
125 // If the member type supports transitive sdk members then recurse down into
126 // its dependencies, otherwise exit traversal.
127 return memberType.HasTransitiveSdkMembers()
Jiyong Park73c54ee2019-10-22 20:31:18 +0900128 }
Paul Duffinf4ae4f12020-01-13 20:58:25 +0000129
130 return false
Paul Duffin13879572019-11-28 14:31:38 +0000131 })
132
Paul Duffin1356d8c2020-02-25 19:26:33 +0000133 return memberRefs
134}
135
136// Organize the members.
137//
138// The members are first grouped by type and then grouped by name. The order of
139// the types is the order they are referenced in android.SdkMemberTypesRegistry.
140// The names are in the order in which the dependencies were added.
141//
142// Returns the members as well as the multilib setting to use.
143func (s *sdk) organizeMembers(ctx android.ModuleContext, memberRefs []sdkMemberRef) ([]*sdkMember, string) {
144 byType := make(map[android.SdkMemberType][]*sdkMember)
145 byName := make(map[string]*sdkMember)
146
Paul Duffin9c3760e2020-03-16 19:52:08 +0000147 multilib := multilibNone
Paul Duffin1356d8c2020-02-25 19:26:33 +0000148
149 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 Duffin9c3760e2020-03-16 19:52:08 +0000161 multilib = multilib.addArchType(variant.Target().Arch.ArchType)
Paul Duffin1356d8c2020-02-25 19:26:33 +0000162
163 // Only append new variants to the list. This is needed because a member can be both
164 // exported by the sdk and also be a transitive sdk member.
165 member.variants = appendUniqueVariants(member.variants, variant)
166 }
167
Paul Duffin13879572019-11-28 14:31:38 +0000168 var members []*sdkMember
Paul Duffin72910952020-01-20 18:16:30 +0000169 for _, memberListProperty := range s.memberListProperties() {
Paul Duffin13879572019-11-28 14:31:38 +0000170 membersOfType := byType[memberListProperty.memberType]
171 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900172 }
173
Paul Duffin9c3760e2020-03-16 19:52:08 +0000174 return members, multilib.String()
Jiyong Park73c54ee2019-10-22 20:31:18 +0900175}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900176
Paul Duffin72910952020-01-20 18:16:30 +0000177func appendUniqueVariants(variants []android.SdkAware, newVariant android.SdkAware) []android.SdkAware {
178 for _, v := range variants {
179 if v == newVariant {
180 return variants
181 }
182 }
183 return append(variants, newVariant)
184}
185
Jiyong Park73c54ee2019-10-22 20:31:18 +0900186// SDK directory structure
187// <sdk_root>/
188// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
189// <api_ver>/ : below this directory are all auto-generated
190// Android.bp : definition of 'sdk_snapshot' module is here
191// aidl/
192// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
193// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900194// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900195// include/
196// bionic/libc/include/stdlib.h : an exported header file
197// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900198// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900199// <arch>/include/ : arch-specific exported headers
200// <arch>/include_gen/ : arch-specific generated headers
201// <arch>/lib/
202// libFoo.so : a stub library
203
Jiyong Park232e7852019-11-04 12:23:40 +0900204// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900205// This isn't visible to users, so could be changed in future.
206func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
207 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
208}
209
Jiyong Park232e7852019-11-04 12:23:40 +0900210// buildSnapshot is the main function in this source file. It creates rules to copy
211// the contents (header files, stub libraries, etc) into the zip file.
Paul Duffin1356d8c2020-02-25 19:26:33 +0000212func (s *sdk) buildSnapshot(ctx android.ModuleContext, sdkVariants []*sdk) android.OutputPath {
213
Paul Duffin13f02712020-03-06 12:30:43 +0000214 allMembersByName := make(map[string]struct{})
215 exportedMembersByName := make(map[string]struct{})
Paul Duffin1356d8c2020-02-25 19:26:33 +0000216 var memberRefs []sdkMemberRef
217 for _, sdkVariant := range sdkVariants {
218 memberRefs = append(memberRefs, sdkVariant.memberRefs...)
Paul Duffin865171e2020-03-02 18:38:15 +0000219
Paul Duffin13f02712020-03-06 12:30:43 +0000220 // Record the names of all the members, both explicitly specified and implicitly
221 // included.
222 for _, memberRef := range sdkVariant.memberRefs {
223 allMembersByName[memberRef.variant.Name()] = struct{}{}
224 }
225
Paul Duffin865171e2020-03-02 18:38:15 +0000226 // Merge the exported member sets from all sdk variants.
227 for key, _ := range sdkVariant.getExportedMembers() {
Paul Duffin13f02712020-03-06 12:30:43 +0000228 exportedMembersByName[key] = struct{}{}
Paul Duffin865171e2020-03-02 18:38:15 +0000229 }
Paul Duffin1356d8c2020-02-25 19:26:33 +0000230 }
231
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000232 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900233
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000234 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000235
236 bpFile := &bpFile{
237 modules: make(map[string]*bpModule),
238 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000239
240 builder := &snapshotBuilder{
Paul Duffin13f02712020-03-06 12:30:43 +0000241 ctx: ctx,
242 sdk: s,
243 version: "current",
244 snapshotDir: snapshotDir.OutputPath,
245 copies: make(map[string]string),
246 filesToZip: []android.Path{bp.path},
247 bpFile: bpFile,
248 prebuiltModules: make(map[string]*bpModule),
249 allMembersByName: allMembersByName,
250 exportedMembersByName: exportedMembersByName,
Jiyong Park73c54ee2019-10-22 20:31:18 +0900251 }
Paul Duffinac37c502019-11-26 18:02:20 +0000252 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900253
Paul Duffin1356d8c2020-02-25 19:26:33 +0000254 members, multilib := s.organizeMembers(ctx, memberRefs)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000255 for _, member := range members {
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000256 memberType := member.memberType
Paul Duffin3a4eb502020-03-19 16:11:18 +0000257
Paul Duffina551a1c2020-03-17 21:04:24 +0000258 memberCtx := &memberContext{ctx, builder, memberType, member.name}
Paul Duffin3a4eb502020-03-19 16:11:18 +0000259
260 prebuiltModule := memberType.AddPrebuiltModule(memberCtx, member)
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000261 if prebuiltModule == nil {
262 // Fall back to legacy method of building a snapshot
263 memberType.BuildSnapshot(ctx, builder, member)
264 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +0000265 s.createMemberSnapshot(memberCtx, member, prebuiltModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000266 }
Jiyong Park73c54ee2019-10-22 20:31:18 +0900267 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900268
Paul Duffine6c0d842020-01-15 14:08:51 +0000269 // Create a transformer that will transform an unversioned module into a versioned module.
270 unversionedToVersionedTransformer := unversionedToVersionedTransformation{builder: builder}
271
Paul Duffin72910952020-01-20 18:16:30 +0000272 // Create a transformer that will transform an unversioned module by replacing any references
273 // to internal members with a unique module name and setting prefer: false.
274 unversionedTransformer := unversionedTransformation{builder: builder}
275
Paul Duffinb645ec82019-11-27 17:43:54 +0000276 for _, unversioned := range builder.prebuiltOrder {
Paul Duffina78f3a72020-02-21 16:29:35 +0000277 // Prune any empty property sets.
278 unversioned = unversioned.transform(pruneEmptySetTransformer{})
279
Paul Duffinb645ec82019-11-27 17:43:54 +0000280 // Copy the unversioned module so it can be modified to make it versioned.
Paul Duffincc72e982020-01-14 15:53:11 +0000281 versioned := unversioned.deepCopy()
Paul Duffine6c0d842020-01-15 14:08:51 +0000282
283 // Transform the unversioned module into a versioned one.
284 versioned.transform(unversionedToVersionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000285 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000286
Paul Duffin72910952020-01-20 18:16:30 +0000287 // Transform the unversioned module to make it suitable for use in the snapshot.
288 unversioned.transform(unversionedTransformer)
Paul Duffinb645ec82019-11-27 17:43:54 +0000289 bpFile.AddModule(unversioned)
290 }
291
292 // Create the snapshot module.
293 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
Paul Duffin8150da62019-12-16 17:21:27 +0000294 var snapshotModuleType string
295 if s.properties.Module_exports {
296 snapshotModuleType = "module_exports_snapshot"
297 } else {
298 snapshotModuleType = "sdk_snapshot"
299 }
300 snapshotModule := bpFile.newModule(snapshotModuleType)
Paul Duffinb645ec82019-11-27 17:43:54 +0000301 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000302
303 // Make sure that the snapshot has the same visibility as the sdk.
304 visibility := android.EffectiveVisibilityRules(ctx, s)
305 if len(visibility) != 0 {
306 snapshotModule.AddProperty("visibility", visibility)
307 }
308
Paul Duffin865171e2020-03-02 18:38:15 +0000309 addHostDeviceSupportedProperties(s.ModuleBase.DeviceSupported(), s.ModuleBase.HostSupported(), snapshotModule)
Paul Duffin13ad94f2020-02-19 16:19:27 +0000310
311 // Compile_multilib defaults to both and must always be set to both on the
312 // device and so only needs to be set when targeted at the host and is neither
313 // unspecified or both.
Paul Duffin865171e2020-03-02 18:38:15 +0000314 targetPropertySet := snapshotModule.AddPropertySet("target")
Paul Duffin13ad94f2020-02-19 16:19:27 +0000315 if s.HostSupported() && multilib != "" && multilib != "both" {
Paul Duffin865171e2020-03-02 18:38:15 +0000316 hostSet := targetPropertySet.AddPropertySet("host")
Paul Duffin13ad94f2020-02-19 16:19:27 +0000317 hostSet.AddProperty("compile_multilib", multilib)
318 }
319
Paul Duffin865171e2020-03-02 18:38:15 +0000320 var dynamicMemberPropertiesList []interface{}
321 osTypeToMemberProperties := make(map[android.OsType]*sdk)
322 for _, sdkVariant := range sdkVariants {
323 properties := sdkVariant.dynamicMemberTypeListProperties
324 osTypeToMemberProperties[sdkVariant.Target().Os] = sdkVariant
325 dynamicMemberPropertiesList = append(dynamicMemberPropertiesList, properties)
326 }
327
328 // Extract the common lists of members into a separate struct.
329 commonDynamicMemberProperties := s.dynamicSdkMemberTypes.createMemberListProperties()
Paul Duffinc097e362020-03-10 22:50:03 +0000330 extractor := newCommonValueExtractor(commonDynamicMemberProperties)
331 extractor.extractCommonProperties(commonDynamicMemberProperties, dynamicMemberPropertiesList)
Paul Duffin865171e2020-03-02 18:38:15 +0000332
333 // Add properties common to all os types.
334 s.addMemberPropertiesToPropertySet(builder, snapshotModule, commonDynamicMemberProperties)
335
336 // Iterate over the os types in a fixed order.
337 for _, osType := range s.getPossibleOsTypes() {
338 if sdkVariant, ok := osTypeToMemberProperties[osType]; ok {
339 osPropertySet := targetPropertySet.AddPropertySet(sdkVariant.Target().Os.Name)
340 s.addMemberPropertiesToPropertySet(builder, osPropertySet, sdkVariant.dynamicMemberTypeListProperties)
Paul Duffin13879572019-11-28 14:31:38 +0000341 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000342 }
Paul Duffin865171e2020-03-02 18:38:15 +0000343
344 // Prune any empty property sets.
345 snapshotModule.transform(pruneEmptySetTransformer{})
346
Paul Duffinb645ec82019-11-27 17:43:54 +0000347 bpFile.AddModule(snapshotModule)
348
349 // generate Android.bp
350 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
351 generateBpContents(&bp.generatedContents, bpFile)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000352
353 bp.build(pctx, ctx, nil)
354
355 filesToZip := builder.filesToZip
Jiyong Park9b409bc2019-10-11 14:59:13 +0900356
Jiyong Park232e7852019-11-04 12:23:40 +0900357 // zip them all
Paul Duffin91547182019-11-12 19:39:36 +0000358 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000359 outputDesc := "Building snapshot for " + ctx.ModuleName()
360
361 // If there are no zips to merge then generate the output zip directly.
362 // Otherwise, generate an intermediate zip file into which other zips can be
363 // merged.
364 var zipFile android.OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000365 var desc string
366 if len(builder.zipsToMerge) == 0 {
367 zipFile = outputZipFile
Paul Duffin91547182019-11-12 19:39:36 +0000368 desc = outputDesc
369 } else {
370 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000371 desc = "Building intermediate snapshot for " + ctx.ModuleName()
372 }
373
Paul Duffin375058f2019-11-29 20:17:53 +0000374 ctx.Build(pctx, android.BuildParams{
375 Description: desc,
376 Rule: zipFiles,
377 Inputs: filesToZip,
378 Output: zipFile,
379 Args: map[string]string{
380 "basedir": builder.snapshotDir.String(),
381 },
382 })
Jiyong Park9b409bc2019-10-11 14:59:13 +0900383
Paul Duffin91547182019-11-12 19:39:36 +0000384 if len(builder.zipsToMerge) != 0 {
Paul Duffin375058f2019-11-29 20:17:53 +0000385 ctx.Build(pctx, android.BuildParams{
386 Description: outputDesc,
387 Rule: mergeZips,
388 Input: zipFile,
389 Inputs: builder.zipsToMerge,
390 Output: outputZipFile,
391 })
Paul Duffin91547182019-11-12 19:39:36 +0000392 }
393
394 return outputZipFile
Jiyong Park9b409bc2019-10-11 14:59:13 +0900395}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000396
Paul Duffin865171e2020-03-02 18:38:15 +0000397func (s *sdk) addMemberPropertiesToPropertySet(builder *snapshotBuilder, propertySet android.BpPropertySet, dynamicMemberTypeListProperties interface{}) {
398 for _, memberListProperty := range s.memberListProperties() {
399 names := memberListProperty.getter(dynamicMemberTypeListProperties)
400 if len(names) > 0 {
Paul Duffin13f02712020-03-06 12:30:43 +0000401 propertySet.AddProperty(memberListProperty.propertyName(), builder.versionedSdkMemberNames(names, false))
Paul Duffin865171e2020-03-02 18:38:15 +0000402 }
403 }
404}
405
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000406type propertyTag struct {
407 name string
408}
409
Paul Duffin0cb37b92020-03-04 14:52:46 +0000410// A BpPropertyTag to add to a property that contains references to other sdk members.
411//
412// This will cause the references to be rewritten to a versioned reference in the version
413// specific instance of a snapshot module.
Paul Duffin13f02712020-03-06 12:30:43 +0000414var requiredSdkMemberReferencePropertyTag = propertyTag{"requiredSdkMemberReferencePropertyTag"}
Paul Duffin13f02712020-03-06 12:30:43 +0000415var optionalSdkMemberReferencePropertyTag = propertyTag{"optionalSdkMemberReferencePropertyTag"}
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000416
Paul Duffin0cb37b92020-03-04 14:52:46 +0000417// A BpPropertyTag that indicates the property should only be present in the versioned
418// module.
419//
420// This will cause the property to be removed from the unversioned instance of a
421// snapshot module.
422var sdkVersionedOnlyPropertyTag = propertyTag{"sdkVersionedOnlyPropertyTag"}
423
Paul Duffine6c0d842020-01-15 14:08:51 +0000424type unversionedToVersionedTransformation struct {
425 identityTransformation
426 builder *snapshotBuilder
427}
428
Paul Duffine6c0d842020-01-15 14:08:51 +0000429func (t unversionedToVersionedTransformation) transformModule(module *bpModule) *bpModule {
430 // Use a versioned name for the module but remember the original name for the
431 // snapshot.
432 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000433 module.setProperty("name", t.builder.versionedSdkMemberName(name, true))
Paul Duffine6c0d842020-01-15 14:08:51 +0000434 module.insertAfter("name", "sdk_member_name", name)
435 return module
436}
437
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000438func (t unversionedToVersionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000439 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
440 required := tag == requiredSdkMemberReferencePropertyTag
441 return t.builder.versionedSdkMemberNames(value.([]string), required), tag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000442 } else {
443 return value, tag
444 }
445}
446
Paul Duffin72910952020-01-20 18:16:30 +0000447type unversionedTransformation struct {
448 identityTransformation
449 builder *snapshotBuilder
450}
451
452func (t unversionedTransformation) transformModule(module *bpModule) *bpModule {
453 // If the module is an internal member then use a unique name for it.
454 name := module.getValue("name").(string)
Paul Duffin13f02712020-03-06 12:30:43 +0000455 module.setProperty("name", t.builder.unversionedSdkMemberName(name, true))
Paul Duffin72910952020-01-20 18:16:30 +0000456
457 // Set prefer: false - this is not strictly required as that is the default.
458 module.insertAfter("name", "prefer", false)
459
460 return module
461}
462
463func (t unversionedTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) {
Paul Duffin13f02712020-03-06 12:30:43 +0000464 if tag == requiredSdkMemberReferencePropertyTag || tag == optionalSdkMemberReferencePropertyTag {
465 required := tag == requiredSdkMemberReferencePropertyTag
466 return t.builder.unversionedSdkMemberNames(value.([]string), required), tag
Paul Duffin0cb37b92020-03-04 14:52:46 +0000467 } else if tag == sdkVersionedOnlyPropertyTag {
468 // The property is not allowed in the unversioned module so remove it.
469 return nil, nil
Paul Duffin72910952020-01-20 18:16:30 +0000470 } else {
471 return value, tag
472 }
473}
474
Paul Duffina78f3a72020-02-21 16:29:35 +0000475type pruneEmptySetTransformer struct {
476 identityTransformation
477}
478
479var _ bpTransformer = (*pruneEmptySetTransformer)(nil)
480
481func (t pruneEmptySetTransformer) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) {
482 if len(propertySet.properties) == 0 {
483 return nil, nil
484 } else {
485 return propertySet, tag
486 }
487}
488
Paul Duffinb645ec82019-11-27 17:43:54 +0000489func generateBpContents(contents *generatedContents, bpFile *bpFile) {
490 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
491 for _, bpModule := range bpFile.order {
492 contents.Printfln("")
493 contents.Printfln("%s {", bpModule.moduleType)
Paul Duffincc72e982020-01-14 15:53:11 +0000494 outputPropertySet(contents, bpModule.bpPropertySet)
Paul Duffinb645ec82019-11-27 17:43:54 +0000495 contents.Printfln("}")
496 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000497}
498
499func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
500 contents.Indent()
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000501
502 // Output the properties first, followed by the nested sets. This ensures a
503 // consistent output irrespective of whether property sets are created before
504 // or after the properties. This simplifies the creation of the module.
Paul Duffinb645ec82019-11-27 17:43:54 +0000505 for _, name := range set.order {
Paul Duffin5b511a22020-01-15 14:23:52 +0000506 value := set.getValue(name)
Paul Duffinb645ec82019-11-27 17:43:54 +0000507
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000508 switch v := value.(type) {
509 case []string:
510 length := len(v)
Paul Duffinb645ec82019-11-27 17:43:54 +0000511 if length > 1 {
512 contents.Printfln("%s: [", name)
513 contents.Indent()
514 for i := 0; i < length; i = i + 1 {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000515 contents.Printfln("%q,", v[i])
Paul Duffinb645ec82019-11-27 17:43:54 +0000516 }
517 contents.Dedent()
518 contents.Printfln("],")
519 } else if length == 0 {
520 contents.Printfln("%s: [],", name)
521 } else {
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000522 contents.Printfln("%s: [%q],", name, v[0])
Paul Duffinb645ec82019-11-27 17:43:54 +0000523 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000524
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000525 case bool:
526 contents.Printfln("%s: %t,", name, v)
527
528 case *bpPropertySet:
529 // Do not write property sets in the properties phase.
Paul Duffinb645ec82019-11-27 17:43:54 +0000530
531 default:
532 contents.Printfln("%s: %q,", name, value)
533 }
534 }
Paul Duffin07ef3cb2020-03-11 18:17:42 +0000535
536 for _, name := range set.order {
537 value := set.getValue(name)
538
539 // Only write property sets in the sets phase.
540 switch v := value.(type) {
541 case *bpPropertySet:
542 contents.Printfln("%s: {", name)
543 outputPropertySet(contents, v)
544 contents.Printfln("},")
545 }
546 }
547
Paul Duffinb645ec82019-11-27 17:43:54 +0000548 contents.Dedent()
549}
550
Paul Duffinac37c502019-11-26 18:02:20 +0000551func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000552 contents := &generatedContents{}
553 generateBpContents(contents, s.builderForTests.bpFile)
554 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000555}
556
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000557type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000558 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000559 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000560 version string
561 snapshotDir android.OutputPath
562 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000563
564 // Map from destination to source of each copy - used to eliminate duplicates and
565 // detect conflicts.
566 copies map[string]string
567
Paul Duffinb645ec82019-11-27 17:43:54 +0000568 filesToZip android.Paths
569 zipsToMerge android.Paths
570
571 prebuiltModules map[string]*bpModule
572 prebuiltOrder []*bpModule
Paul Duffin13f02712020-03-06 12:30:43 +0000573
574 // The set of all members by name.
575 allMembersByName map[string]struct{}
576
577 // The set of exported members by name.
578 exportedMembersByName map[string]struct{}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000579}
580
581func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000582 if existing, ok := s.copies[dest]; ok {
583 if existing != src.String() {
584 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
585 return
586 }
587 } else {
588 path := s.snapshotDir.Join(s.ctx, dest)
589 s.ctx.Build(pctx, android.BuildParams{
590 Rule: android.Cp,
591 Input: src,
592 Output: path,
593 })
594 s.filesToZip = append(s.filesToZip, path)
595
596 s.copies[dest] = src.String()
597 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000598}
599
Paul Duffin91547182019-11-12 19:39:36 +0000600func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
601 ctx := s.ctx
602
603 // Repackage the zip file so that the entries are in the destDir directory.
604 // This will allow the zip file to be merged into the snapshot.
605 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000606
607 ctx.Build(pctx, android.BuildParams{
608 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
609 Rule: repackageZip,
610 Input: zipPath,
611 Output: tmpZipPath,
612 Args: map[string]string{
613 "destdir": destDir,
614 },
615 })
Paul Duffin91547182019-11-12 19:39:36 +0000616
617 // Add the repackaged zip file to the files to merge.
618 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
619}
620
Paul Duffin9d8d6092019-12-05 18:19:29 +0000621func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
622 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000623 if s.prebuiltModules[name] != nil {
624 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
625 }
626
627 m := s.bpFile.newModule(moduleType)
628 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000629
Paul Duffinbefa4b92020-03-04 14:22:45 +0000630 variant := member.Variants()[0]
631
Paul Duffin13f02712020-03-06 12:30:43 +0000632 if s.isInternalMember(name) {
Paul Duffin72910952020-01-20 18:16:30 +0000633 // An internal member is only referenced from the sdk snapshot which is in the
634 // same package so can be marked as private.
635 m.AddProperty("visibility", []string{"//visibility:private"})
636 } else {
637 // Extract visibility information from a member variant. All variants have the same
638 // visibility so it doesn't matter which one is used.
Paul Duffinbefa4b92020-03-04 14:22:45 +0000639 visibility := android.EffectiveVisibilityRules(s.ctx, variant)
Paul Duffin72910952020-01-20 18:16:30 +0000640 if len(visibility) != 0 {
641 m.AddProperty("visibility", visibility)
642 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000643 }
644
Paul Duffin865171e2020-03-02 18:38:15 +0000645 deviceSupported := false
646 hostSupported := false
647
648 for _, variant := range member.Variants() {
649 osClass := variant.Target().Os.Class
650 if osClass == android.Host || osClass == android.HostCross {
651 hostSupported = true
652 } else if osClass == android.Device {
653 deviceSupported = true
654 }
655 }
656
657 addHostDeviceSupportedProperties(deviceSupported, hostSupported, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000658
Paul Duffinbefa4b92020-03-04 14:22:45 +0000659 // Where available copy apex_available properties from the member.
660 if apexAware, ok := variant.(interface{ ApexAvailable() []string }); ok {
661 apexAvailable := apexAware.ApexAvailable()
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000662
663 // Add in any white listed apex available settings.
664 apexAvailable = append(apexAvailable, apex.WhitelistedApexAvailable(member.Name())...)
665
Paul Duffinbefa4b92020-03-04 14:22:45 +0000666 if len(apexAvailable) > 0 {
Paul Duffin7d74e7b2020-03-06 12:30:13 +0000667 // Remove duplicates and sort.
668 apexAvailable = android.FirstUniqueStrings(apexAvailable)
669 sort.Strings(apexAvailable)
670
Paul Duffinbefa4b92020-03-04 14:22:45 +0000671 m.AddProperty("apex_available", apexAvailable)
672 }
673 }
674
Paul Duffin0cb37b92020-03-04 14:52:46 +0000675 // Disable installation in the versioned module of those modules that are ever installable.
676 if installable, ok := variant.(interface{ EverInstallable() bool }); ok {
677 if installable.EverInstallable() {
678 m.AddPropertyWithTag("installable", false, sdkVersionedOnlyPropertyTag)
679 }
680 }
681
Paul Duffinb645ec82019-11-27 17:43:54 +0000682 s.prebuiltModules[name] = m
683 s.prebuiltOrder = append(s.prebuiltOrder, m)
684 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000685}
686
Paul Duffin865171e2020-03-02 18:38:15 +0000687func addHostDeviceSupportedProperties(deviceSupported bool, hostSupported bool, bpModule *bpModule) {
688 if !deviceSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000689 bpModule.AddProperty("device_supported", false)
690 }
Paul Duffin865171e2020-03-02 18:38:15 +0000691 if hostSupported {
Paul Duffine44358f2019-11-26 18:04:12 +0000692 bpModule.AddProperty("host_supported", true)
693 }
694}
695
Paul Duffin13f02712020-03-06 12:30:43 +0000696func (s *snapshotBuilder) SdkMemberReferencePropertyTag(required bool) android.BpPropertyTag {
697 if required {
698 return requiredSdkMemberReferencePropertyTag
699 } else {
700 return optionalSdkMemberReferencePropertyTag
701 }
702}
703
704func (s *snapshotBuilder) OptionalSdkMemberReferencePropertyTag() android.BpPropertyTag {
705 return optionalSdkMemberReferencePropertyTag
Paul Duffin7b81f5e2020-01-13 21:03:22 +0000706}
707
Paul Duffinb645ec82019-11-27 17:43:54 +0000708// Get a versioned name appropriate for the SDK snapshot version being taken.
Paul Duffin13f02712020-03-06 12:30:43 +0000709func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string, required bool) string {
710 if _, ok := s.allMembersByName[unversionedName]; !ok {
711 if required {
712 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
713 }
714 return unversionedName
715 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000716 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
717}
Paul Duffinb645ec82019-11-27 17:43:54 +0000718
Paul Duffin13f02712020-03-06 12:30:43 +0000719func (s *snapshotBuilder) versionedSdkMemberNames(members []string, required bool) []string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000720 var references []string = nil
721 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000722 references = append(references, s.versionedSdkMemberName(m, required))
Paul Duffinb645ec82019-11-27 17:43:54 +0000723 }
724 return references
725}
Paul Duffin13879572019-11-28 14:31:38 +0000726
Paul Duffin72910952020-01-20 18:16:30 +0000727// Get an internal name unique to the sdk.
Paul Duffin13f02712020-03-06 12:30:43 +0000728func (s *snapshotBuilder) unversionedSdkMemberName(unversionedName string, required bool) string {
729 if _, ok := s.allMembersByName[unversionedName]; !ok {
730 if required {
731 s.ctx.ModuleErrorf("Required member reference %s is not a member of the sdk", unversionedName)
732 }
733 return unversionedName
734 }
735
736 if s.isInternalMember(unversionedName) {
Paul Duffin72910952020-01-20 18:16:30 +0000737 return s.ctx.ModuleName() + "_" + unversionedName
738 } else {
739 return unversionedName
740 }
741}
742
Paul Duffin13f02712020-03-06 12:30:43 +0000743func (s *snapshotBuilder) unversionedSdkMemberNames(members []string, required bool) []string {
Paul Duffin72910952020-01-20 18:16:30 +0000744 var references []string = nil
745 for _, m := range members {
Paul Duffin13f02712020-03-06 12:30:43 +0000746 references = append(references, s.unversionedSdkMemberName(m, required))
Paul Duffin72910952020-01-20 18:16:30 +0000747 }
748 return references
749}
750
Paul Duffin13f02712020-03-06 12:30:43 +0000751func (s *snapshotBuilder) isInternalMember(memberName string) bool {
752 _, ok := s.exportedMembersByName[memberName]
753 return !ok
754}
755
Paul Duffin1356d8c2020-02-25 19:26:33 +0000756type sdkMemberRef struct {
757 memberType android.SdkMemberType
758 variant android.SdkAware
759}
760
Paul Duffin13879572019-11-28 14:31:38 +0000761var _ android.SdkMember = (*sdkMember)(nil)
762
763type sdkMember struct {
764 memberType android.SdkMemberType
765 name string
766 variants []android.SdkAware
767}
768
769func (m *sdkMember) Name() string {
770 return m.name
771}
772
773func (m *sdkMember) Variants() []android.SdkAware {
774 return m.variants
775}
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000776
Paul Duffin9c3760e2020-03-16 19:52:08 +0000777// Track usages of multilib variants.
778type multilibUsage int
779
780const (
781 multilibNone multilibUsage = 0
782 multilib32 multilibUsage = 1
783 multilib64 multilibUsage = 2
784 multilibBoth = multilib32 | multilib64
785)
786
787// Add the multilib that is used in the arch type.
788func (m multilibUsage) addArchType(archType android.ArchType) multilibUsage {
789 multilib := archType.Multilib
790 switch multilib {
791 case "":
792 return m
793 case "lib32":
794 return m | multilib32
795 case "lib64":
796 return m | multilib64
797 default:
798 panic(fmt.Errorf("Unknown Multilib field in ArchType, expected 'lib32' or 'lib64', found %q", multilib))
799 }
800}
801
802func (m multilibUsage) String() string {
803 switch m {
804 case multilibNone:
805 return ""
806 case multilib32:
807 return "32"
808 case multilib64:
809 return "64"
810 case multilibBoth:
811 return "both"
812 default:
813 panic(fmt.Errorf("Unknown multilib value, found %b, expected one of %b, %b, %b or %b",
814 m, multilibNone, multilib32, multilib64, multilibBoth))
815 }
816}
817
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000818type baseInfo struct {
819 Properties android.SdkMemberProperties
820}
821
822type osTypeSpecificInfo struct {
823 baseInfo
824
Paul Duffin00e46802020-03-12 20:40:35 +0000825 osType android.OsType
826
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000827 // The list of arch type specific info for this os type.
Paul Duffinb44b33a2020-03-17 10:58:23 +0000828 //
829 // Nil if there is one variant whose arch type is common
830 archInfos []*archTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000831}
832
Paul Duffinfc8dd232020-03-17 12:51:37 +0000833type variantPropertiesFactoryFunc func() android.SdkMemberProperties
834
Paul Duffin00e46802020-03-12 20:40:35 +0000835// Create a new osTypeSpecificInfo for the specified os type and its properties
836// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000837func newOsTypeSpecificInfo(ctx android.SdkMemberContext, osType android.OsType, variantPropertiesFactory variantPropertiesFactoryFunc, osTypeVariants []android.Module) *osTypeSpecificInfo {
Paul Duffin00e46802020-03-12 20:40:35 +0000838 osInfo := &osTypeSpecificInfo{
839 osType: osType,
840 }
841
842 osSpecificVariantPropertiesFactory := func() android.SdkMemberProperties {
843 properties := variantPropertiesFactory()
844 properties.Base().Os = osType
845 return properties
846 }
847
848 // Create a structure into which properties common across the architectures in
849 // this os type will be stored.
850 osInfo.Properties = osSpecificVariantPropertiesFactory()
851
852 // Group the variants by arch type.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000853 var variantsByArchName = make(map[string][]android.Module)
Paul Duffin00e46802020-03-12 20:40:35 +0000854 var archTypes []android.ArchType
855 for _, variant := range osTypeVariants {
856 archType := variant.Target().Arch.ArchType
857 archTypeName := archType.Name
858 if _, ok := variantsByArchName[archTypeName]; !ok {
859 archTypes = append(archTypes, archType)
860 }
861
862 variantsByArchName[archTypeName] = append(variantsByArchName[archTypeName], variant)
863 }
864
865 if commonVariants, ok := variantsByArchName["common"]; ok {
866 if len(osTypeVariants) != 1 {
867 panic("Expected to only have 1 variant when arch type is common but found " + string(len(osTypeVariants)))
868 }
869
870 // A common arch type only has one variant and its properties should be treated
871 // as common to the os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000872 osInfo.Properties.PopulateFromVariant(ctx, commonVariants[0])
Paul Duffin00e46802020-03-12 20:40:35 +0000873 } else {
874 // Create an arch specific info for each supported architecture type.
875 for _, archType := range archTypes {
876 archTypeName := archType.Name
877
878 archVariants := variantsByArchName[archTypeName]
Paul Duffin3a4eb502020-03-19 16:11:18 +0000879 archInfo := newArchSpecificInfo(ctx, archType, osSpecificVariantPropertiesFactory, archVariants)
Paul Duffin00e46802020-03-12 20:40:35 +0000880
881 osInfo.archInfos = append(osInfo.archInfos, archInfo)
882 }
883 }
884
885 return osInfo
886}
887
888// Optimize the properties by extracting common properties from arch type specific
889// properties into os type specific properties.
890func (osInfo *osTypeSpecificInfo) optimizeProperties(commonValueExtractor *commonValueExtractor) {
891 // Nothing to do if there is only a single common architecture.
892 if len(osInfo.archInfos) == 0 {
893 return
894 }
895
Paul Duffin9c3760e2020-03-16 19:52:08 +0000896 multilib := multilibNone
Paul Duffin00e46802020-03-12 20:40:35 +0000897 var archPropertiesList []android.SdkMemberProperties
898 for _, archInfo := range osInfo.archInfos {
Paul Duffin9c3760e2020-03-16 19:52:08 +0000899 multilib = multilib.addArchType(archInfo.archType)
900
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000901 // Optimize the arch properties first.
902 archInfo.optimizeProperties(commonValueExtractor)
903
Paul Duffin00e46802020-03-12 20:40:35 +0000904 archPropertiesList = append(archPropertiesList, archInfo.Properties)
905 }
906
907 commonValueExtractor.extractCommonProperties(osInfo.Properties, archPropertiesList)
908
909 // Choose setting for compile_multilib that is appropriate for the arch variants supplied.
Paul Duffin9c3760e2020-03-16 19:52:08 +0000910 osInfo.Properties.Base().Compile_multilib = multilib.String()
Paul Duffin00e46802020-03-12 20:40:35 +0000911}
912
913// Add the properties for an os to a property set.
914//
915// Maps the properties related to the os variants through to an appropriate
916// module structure that will produce equivalent set of variants when it is
917// processed in a build.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000918func (osInfo *osTypeSpecificInfo) addToPropertySet(ctx *memberContext, bpModule android.BpModule, targetPropertySet android.BpPropertySet) {
Paul Duffin00e46802020-03-12 20:40:35 +0000919
920 var osPropertySet android.BpPropertySet
921 var archPropertySet android.BpPropertySet
922 var archOsPrefix string
923 if osInfo.Properties.Base().Os_count == 1 {
924 // There is only one os type present in the variants so don't bother
925 // with adding target specific properties.
926
927 // Create a structure that looks like:
928 // module_type {
929 // name: "...",
930 // ...
931 // <common properties>
932 // ...
933 // <single os type specific properties>
934 //
935 // arch: {
936 // <arch specific sections>
937 // }
938 //
939 osPropertySet = bpModule
940 archPropertySet = osPropertySet.AddPropertySet("arch")
941
942 // Arch specific properties need to be added to an arch specific section
943 // within arch.
944 archOsPrefix = ""
945 } else {
946 // Create a structure that looks like:
947 // module_type {
948 // name: "...",
949 // ...
950 // <common properties>
951 // ...
952 // target: {
953 // <arch independent os specific sections, e.g. android>
954 // ...
955 // <arch and os specific sections, e.g. android_x86>
956 // }
957 //
958 osType := osInfo.osType
959 osPropertySet = targetPropertySet.AddPropertySet(osType.Name)
960 archPropertySet = targetPropertySet
961
962 // Arch specific properties need to be added to an os and arch specific
963 // section prefixed with <os>_.
964 archOsPrefix = osType.Name + "_"
965 }
966
967 // Add the os specific but arch independent properties to the module.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000968 osInfo.Properties.AddToPropertySet(ctx, osPropertySet)
Paul Duffin00e46802020-03-12 20:40:35 +0000969
970 // Add arch (and possibly os) specific sections for each set of arch (and possibly
971 // os) specific properties.
972 //
973 // The archInfos list will be empty if the os contains variants for the common
974 // architecture.
975 for _, archInfo := range osInfo.archInfos {
Paul Duffin3a4eb502020-03-19 16:11:18 +0000976 archInfo.addToPropertySet(ctx, archPropertySet, archOsPrefix)
Paul Duffin00e46802020-03-12 20:40:35 +0000977 }
978}
979
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000980type archTypeSpecificInfo struct {
981 baseInfo
982
983 archType android.ArchType
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000984
985 linkInfos []*linkTypeSpecificInfo
Paul Duffin88f2fbe2020-02-27 16:00:53 +0000986}
987
Paul Duffinfc8dd232020-03-17 12:51:37 +0000988// Create a new archTypeSpecificInfo for the specified arch type and its properties
989// structures populated with information from the variants.
Paul Duffin3a4eb502020-03-19 16:11:18 +0000990func newArchSpecificInfo(ctx android.SdkMemberContext, archType android.ArchType, variantPropertiesFactory variantPropertiesFactoryFunc, archVariants []android.Module) *archTypeSpecificInfo {
Paul Duffinfc8dd232020-03-17 12:51:37 +0000991
Paul Duffinfc8dd232020-03-17 12:51:37 +0000992 // Create an arch specific info into which the variant properties can be copied.
993 archInfo := &archTypeSpecificInfo{archType: archType}
994
995 // Create the properties into which the arch type specific properties will be
996 // added.
997 archInfo.Properties = variantPropertiesFactory()
Paul Duffin9b76c0b2020-03-12 10:24:35 +0000998
999 if len(archVariants) == 1 {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001000 archInfo.Properties.PopulateFromVariant(ctx, archVariants[0])
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001001 } else {
1002 // There is more than one variant for this arch type which must be differentiated
1003 // by link type.
1004 for _, linkVariant := range archVariants {
1005 linkType := getLinkType(linkVariant)
1006 if linkType == "" {
1007 panic(fmt.Errorf("expected one arch specific variant as it is not identified by link type but found %d", len(archVariants)))
1008 } else {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001009 linkInfo := newLinkSpecificInfo(ctx, linkType, variantPropertiesFactory, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001010
1011 archInfo.linkInfos = append(archInfo.linkInfos, linkInfo)
1012 }
1013 }
1014 }
Paul Duffinfc8dd232020-03-17 12:51:37 +00001015
1016 return archInfo
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
1046 var propertiesList []android.SdkMemberProperties
1047 for _, linkInfo := range archInfo.linkInfos {
1048 propertiesList = append(propertiesList, linkInfo.Properties)
1049 }
1050
1051 commonValueExtractor.extractCommonProperties(archInfo.Properties, propertiesList)
1052}
1053
Paul Duffinfc8dd232020-03-17 12:51:37 +00001054// Add the properties for an arch type to a property set.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001055func (archInfo *archTypeSpecificInfo) addToPropertySet(ctx *memberContext, archPropertySet android.BpPropertySet, archOsPrefix string) {
Paul Duffinfc8dd232020-03-17 12:51:37 +00001056 archTypeName := archInfo.archType.Name
1057 archTypePropertySet := archPropertySet.AddPropertySet(archOsPrefix + archTypeName)
Paul Duffin3a4eb502020-03-19 16:11:18 +00001058 archInfo.Properties.AddToPropertySet(ctx, archTypePropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001059
1060 for _, linkInfo := range archInfo.linkInfos {
1061 linkPropertySet := archTypePropertySet.AddPropertySet(linkInfo.linkType)
Paul Duffin3a4eb502020-03-19 16:11:18 +00001062 linkInfo.Properties.AddToPropertySet(ctx, linkPropertySet)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001063 }
1064}
1065
1066type linkTypeSpecificInfo struct {
1067 baseInfo
1068
1069 linkType string
1070}
1071
1072// Create a new linkTypeSpecificInfo for the specified link type and its properties
1073// structures populated with information from the variant.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001074func newLinkSpecificInfo(ctx android.SdkMemberContext, linkType string, variantPropertiesFactory variantPropertiesFactoryFunc, linkVariant android.Module) *linkTypeSpecificInfo {
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001075 linkInfo := &linkTypeSpecificInfo{
1076 baseInfo: baseInfo{
1077 // Create the properties into which the link type specific properties will be
1078 // added.
1079 Properties: variantPropertiesFactory(),
1080 },
1081 linkType: linkType,
1082 }
Paul Duffin3a4eb502020-03-19 16:11:18 +00001083 linkInfo.Properties.PopulateFromVariant(ctx, linkVariant)
Paul Duffin9b76c0b2020-03-12 10:24:35 +00001084 return linkInfo
Paul Duffinfc8dd232020-03-17 12:51:37 +00001085}
1086
Paul Duffin3a4eb502020-03-19 16:11:18 +00001087type memberContext struct {
1088 sdkMemberContext android.ModuleContext
1089 builder *snapshotBuilder
Paul Duffina551a1c2020-03-17 21:04:24 +00001090 memberType android.SdkMemberType
1091 name string
Paul Duffin3a4eb502020-03-19 16:11:18 +00001092}
1093
1094func (m *memberContext) SdkModuleContext() android.ModuleContext {
1095 return m.sdkMemberContext
1096}
1097
1098func (m *memberContext) SnapshotBuilder() android.SnapshotBuilder {
1099 return m.builder
1100}
1101
Paul Duffina551a1c2020-03-17 21:04:24 +00001102func (m *memberContext) MemberType() android.SdkMemberType {
1103 return m.memberType
1104}
1105
1106func (m *memberContext) Name() string {
1107 return m.name
1108}
1109
Paul Duffin3a4eb502020-03-19 16:11:18 +00001110func (s *sdk) createMemberSnapshot(ctx *memberContext, member *sdkMember, bpModule android.BpModule) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001111
1112 memberType := member.memberType
1113
Paul Duffina04c1072020-03-02 10:16:35 +00001114 // Group the variants by os type.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001115 variantsByOsType := make(map[android.OsType][]android.Module)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001116 variants := member.Variants()
1117 for _, variant := range variants {
Paul Duffina04c1072020-03-02 10:16:35 +00001118 osType := variant.Target().Os
1119 variantsByOsType[osType] = append(variantsByOsType[osType], variant)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001120 }
1121
Paul Duffina04c1072020-03-02 10:16:35 +00001122 osCount := len(variantsByOsType)
Paul Duffinb44b33a2020-03-17 10:58:23 +00001123 variantPropertiesFactory := func() android.SdkMemberProperties {
Paul Duffina04c1072020-03-02 10:16:35 +00001124 properties := memberType.CreateVariantPropertiesStruct()
1125 base := properties.Base()
1126 base.Os_count = osCount
Paul Duffina04c1072020-03-02 10:16:35 +00001127 return properties
1128 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001129
Paul Duffina04c1072020-03-02 10:16:35 +00001130 osTypeToInfo := make(map[android.OsType]*osTypeSpecificInfo)
Paul Duffin14eb4672020-03-02 11:33:02 +00001131
Paul Duffina04c1072020-03-02 10:16:35 +00001132 // The set of properties that are common across all architectures and os types.
Paul Duffinb44b33a2020-03-17 10:58:23 +00001133 commonProperties := variantPropertiesFactory()
1134 commonProperties.Base().Os = android.CommonOS
Paul Duffina04c1072020-03-02 10:16:35 +00001135
Paul Duffinc097e362020-03-10 22:50:03 +00001136 // Create common value extractor that can be used to optimize the properties.
1137 commonValueExtractor := newCommonValueExtractor(commonProperties)
1138
Paul Duffina04c1072020-03-02 10:16:35 +00001139 // The list of property structures which are os type specific but common across
1140 // architectures within that os type.
1141 var osSpecificPropertiesList []android.SdkMemberProperties
1142
1143 for osType, osTypeVariants := range variantsByOsType {
Paul Duffin3a4eb502020-03-19 16:11:18 +00001144 osInfo := newOsTypeSpecificInfo(ctx, osType, variantPropertiesFactory, osTypeVariants)
Paul Duffina04c1072020-03-02 10:16:35 +00001145 osTypeToInfo[osType] = osInfo
Paul Duffinb44b33a2020-03-17 10:58:23 +00001146 // Add the os specific properties to a list of os type specific yet architecture
1147 // independent properties structs.
Paul Duffina04c1072020-03-02 10:16:35 +00001148 osSpecificPropertiesList = append(osSpecificPropertiesList, osInfo.Properties)
1149
Paul Duffin00e46802020-03-12 20:40:35 +00001150 // Optimize the properties across all the variants for a specific os type.
1151 osInfo.optimizeProperties(commonValueExtractor)
Paul Duffin14eb4672020-03-02 11:33:02 +00001152 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001153
Paul Duffina04c1072020-03-02 10:16:35 +00001154 // Extract properties which are common across all architectures and os types.
Paul Duffinc097e362020-03-10 22:50:03 +00001155 commonValueExtractor.extractCommonProperties(commonProperties, osSpecificPropertiesList)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001156
Paul Duffina04c1072020-03-02 10:16:35 +00001157 // Add the common properties to the module.
Paul Duffin3a4eb502020-03-19 16:11:18 +00001158 commonProperties.AddToPropertySet(ctx, bpModule)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001159
Paul Duffina04c1072020-03-02 10:16:35 +00001160 // Create a target property set into which target specific properties can be
1161 // added.
1162 targetPropertySet := bpModule.AddPropertySet("target")
1163
1164 // Iterate over the os types in a fixed order.
1165 for _, osType := range s.getPossibleOsTypes() {
1166 osInfo := osTypeToInfo[osType]
1167 if osInfo == nil {
1168 continue
1169 }
1170
Paul Duffin3a4eb502020-03-19 16:11:18 +00001171 osInfo.addToPropertySet(ctx, bpModule, targetPropertySet)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001172 }
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001173}
1174
Paul Duffina04c1072020-03-02 10:16:35 +00001175// Compute the list of possible os types that this sdk could support.
1176func (s *sdk) getPossibleOsTypes() []android.OsType {
1177 var osTypes []android.OsType
1178 for _, osType := range android.OsTypeList {
1179 if s.DeviceSupported() {
1180 if osType.Class == android.Device && osType != android.Fuchsia {
1181 osTypes = append(osTypes, osType)
1182 }
1183 }
1184 if s.HostSupported() {
1185 if osType.Class == android.Host || osType.Class == android.HostCross {
1186 osTypes = append(osTypes, osType)
1187 }
1188 }
1189 }
1190 sort.SliceStable(osTypes, func(i, j int) bool { return osTypes[i].Name < osTypes[j].Name })
1191 return osTypes
1192}
1193
Paul Duffinb07fa512020-03-10 22:17:04 +00001194// Given a struct value, access a field within that struct (or one of its embedded
1195// structs).
Paul Duffinc097e362020-03-10 22:50:03 +00001196type fieldAccessorFunc func(structValue reflect.Value) reflect.Value
1197
1198// Supports extracting common values from a number of instances of a properties
1199// structure into a separate common set of properties.
1200type commonValueExtractor struct {
1201 // The getters for every field from which common values can be extracted.
1202 fieldGetters []fieldAccessorFunc
1203}
1204
1205// Create a new common value extractor for the structure type for the supplied
1206// properties struct.
1207//
1208// The returned extractor can be used on any properties structure of the same type
1209// as the supplied set of properties.
1210func newCommonValueExtractor(propertiesStruct interface{}) *commonValueExtractor {
1211 structType := getStructValue(reflect.ValueOf(propertiesStruct)).Type()
1212 extractor := &commonValueExtractor{}
Paul Duffinb07fa512020-03-10 22:17:04 +00001213 extractor.gatherFields(structType, nil)
Paul Duffinc097e362020-03-10 22:50:03 +00001214 return extractor
1215}
1216
1217// Gather the fields from the supplied structure type from which common values will
1218// be extracted.
Paul Duffinb07fa512020-03-10 22:17:04 +00001219//
1220// This is recursive function. If it encounters an embedded field (no field name)
1221// that is a struct then it will recurse into that struct passing in the accessor
1222// for the field. That will then be used in the accessors for the fields in the
1223// embedded struct.
1224func (e *commonValueExtractor) gatherFields(structType reflect.Type, containingStructAccessor fieldAccessorFunc) {
Paul Duffinc097e362020-03-10 22:50:03 +00001225 for f := 0; f < structType.NumField(); f++ {
1226 field := structType.Field(f)
1227 if field.PkgPath != "" {
1228 // Ignore unexported fields.
1229 continue
1230 }
1231
Paul Duffinb07fa512020-03-10 22:17:04 +00001232 // Ignore fields whose value should be kept.
1233 if proptools.HasTag(field, "sdk", "keep") {
Paul Duffinc097e362020-03-10 22:50:03 +00001234 continue
1235 }
1236
1237 // Save a copy of the field index for use in the function.
1238 fieldIndex := f
1239 fieldGetter := func(value reflect.Value) reflect.Value {
Paul Duffinb07fa512020-03-10 22:17:04 +00001240 if containingStructAccessor != nil {
1241 // This is an embedded structure so first access the field for the embedded
1242 // structure.
1243 value = containingStructAccessor(value)
1244 }
1245
Paul Duffinc097e362020-03-10 22:50:03 +00001246 // Skip through interface and pointer values to find the structure.
1247 value = getStructValue(value)
1248
1249 // Return the field.
1250 return value.Field(fieldIndex)
1251 }
1252
Paul Duffinb07fa512020-03-10 22:17:04 +00001253 if field.Type.Kind() == reflect.Struct && field.Anonymous {
1254 // Gather fields from the embedded structure.
1255 e.gatherFields(field.Type, fieldGetter)
1256 } else {
1257 e.fieldGetters = append(e.fieldGetters, fieldGetter)
1258 }
Paul Duffinc097e362020-03-10 22:50:03 +00001259 }
1260}
1261
1262func getStructValue(value reflect.Value) reflect.Value {
1263foundStruct:
1264 for {
1265 kind := value.Kind()
1266 switch kind {
1267 case reflect.Interface, reflect.Ptr:
1268 value = value.Elem()
1269 case reflect.Struct:
1270 break foundStruct
1271 default:
1272 panic(fmt.Errorf("expecting struct, interface or pointer, found %v of kind %s", value, kind))
1273 }
1274 }
1275 return value
1276}
1277
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001278// Extract common properties from a slice of property structures of the same type.
1279//
1280// All the property structures must be of the same type.
1281// commonProperties - must be a pointer to the structure into which common properties will be added.
1282// inputPropertiesSlice - must be a slice of input properties structures.
1283//
1284// Iterates over each exported field (capitalized name) and checks to see whether they
1285// have the same value (using DeepEquals) across all the input properties. If it does not then no
1286// change is made. Otherwise, the common value is stored in the field in the commonProperties
1287// and the field in each of the input properties structure is set to its default value.
Paul Duffinc097e362020-03-10 22:50:03 +00001288func (e *commonValueExtractor) extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001289 commonPropertiesValue := reflect.ValueOf(commonProperties)
1290 commonStructValue := commonPropertiesValue.Elem()
1291 propertiesStructType := commonStructValue.Type()
1292
1293 // Create an empty structure from which default values for the field can be copied.
1294 emptyStructValue := reflect.New(propertiesStructType).Elem()
1295
Paul Duffinc097e362020-03-10 22:50:03 +00001296 for _, fieldGetter := range e.fieldGetters {
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001297 // Check to see if all the structures have the same value for the field. The commonValue
1298 // is nil on entry to the loop and if it is nil on exit then there is no common value,
1299 // otherwise it points to the common value.
1300 var commonValue *reflect.Value
1301 sliceValue := reflect.ValueOf(inputPropertiesSlice)
1302
1303 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinc097e362020-03-10 22:50:03 +00001304 itemValue := sliceValue.Index(i)
1305 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001306
1307 if commonValue == nil {
1308 // Use the first value as the commonProperties value.
1309 commonValue = &fieldValue
1310 } else {
1311 // If the value does not match the current common value then there is
1312 // no value in common so break out.
1313 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
1314 commonValue = nil
1315 break
1316 }
1317 }
1318 }
1319
1320 // If the fields all have a common value then store it in the common struct field
1321 // and set the input struct's field to the empty value.
1322 if commonValue != nil {
Paul Duffinc097e362020-03-10 22:50:03 +00001323 emptyValue := fieldGetter(emptyStructValue)
1324 fieldGetter(commonStructValue).Set(*commonValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001325 for i := 0; i < sliceValue.Len(); i++ {
Paul Duffinc097e362020-03-10 22:50:03 +00001326 itemValue := sliceValue.Index(i)
1327 fieldValue := fieldGetter(itemValue)
Paul Duffin88f2fbe2020-02-27 16:00:53 +00001328 fieldValue.Set(emptyValue)
1329 }
1330 }
1331 }
1332}