blob: 52d21eda678292ef8659281eb79ae00df38a2177 [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"
Jiyong Park9b409bc2019-10-11 14:59:13 +090020 "strings"
21
Paul Duffin375058f2019-11-29 20:17:53 +000022 "github.com/google/blueprint"
Jiyong Park9b409bc2019-10-11 14:59:13 +090023 "github.com/google/blueprint/proptools"
24
25 "android/soong/android"
Jiyong Park9b409bc2019-10-11 14:59:13 +090026)
27
28var pctx = android.NewPackageContext("android/soong/sdk")
29
Paul Duffin375058f2019-11-29 20:17:53 +000030var (
31 repackageZip = pctx.AndroidStaticRule("SnapshotRepackageZip",
32 blueprint.RuleParams{
Paul Duffince482dc2019-12-09 19:58:17 +000033 Command: `${config.Zip2ZipCmd} -i $in -o $out -x META-INF/**/* "**/*:$destdir"`,
Paul Duffin375058f2019-11-29 20:17:53 +000034 CommandDeps: []string{
35 "${config.Zip2ZipCmd}",
36 },
37 },
38 "destdir")
39
40 zipFiles = pctx.AndroidStaticRule("SnapshotZipFiles",
41 blueprint.RuleParams{
42 Command: `${config.SoongZipCmd} -C $basedir -l $out.rsp -o $out`,
43 CommandDeps: []string{
44 "${config.SoongZipCmd}",
45 },
46 Rspfile: "$out.rsp",
47 RspfileContent: "$in",
48 },
49 "basedir")
50
51 mergeZips = pctx.AndroidStaticRule("SnapshotMergeZips",
52 blueprint.RuleParams{
53 Command: `${config.MergeZipsCmd} $out $in`,
54 CommandDeps: []string{
55 "${config.MergeZipsCmd}",
56 },
57 })
58)
59
Paul Duffinb645ec82019-11-27 17:43:54 +000060type generatedContents struct {
Jiyong Park73c54ee2019-10-22 20:31:18 +090061 content strings.Builder
62 indentLevel int
Jiyong Park9b409bc2019-10-11 14:59:13 +090063}
64
Paul Duffinb645ec82019-11-27 17:43:54 +000065// generatedFile abstracts operations for writing contents into a file and emit a build rule
66// for the file.
67type generatedFile struct {
68 generatedContents
69 path android.OutputPath
70}
71
Jiyong Park232e7852019-11-04 12:23:40 +090072func newGeneratedFile(ctx android.ModuleContext, path ...string) *generatedFile {
Jiyong Park9b409bc2019-10-11 14:59:13 +090073 return &generatedFile{
Paul Duffinb645ec82019-11-27 17:43:54 +000074 path: android.PathForModuleOut(ctx, path...).OutputPath,
Jiyong Park9b409bc2019-10-11 14:59:13 +090075 }
76}
77
Paul Duffinb645ec82019-11-27 17:43:54 +000078func (gc *generatedContents) Indent() {
79 gc.indentLevel++
Jiyong Park73c54ee2019-10-22 20:31:18 +090080}
81
Paul Duffinb645ec82019-11-27 17:43:54 +000082func (gc *generatedContents) Dedent() {
83 gc.indentLevel--
Jiyong Park73c54ee2019-10-22 20:31:18 +090084}
85
Paul Duffinb645ec82019-11-27 17:43:54 +000086func (gc *generatedContents) Printfln(format string, args ...interface{}) {
Jiyong Park9b409bc2019-10-11 14:59:13 +090087 // ninja consumes newline characters in rspfile_content. Prevent it by
Paul Duffin0e0cf1d2019-11-12 19:39:25 +000088 // escaping the backslash in the newline character. The extra backslash
Jiyong Park9b409bc2019-10-11 14:59:13 +090089 // is removed when the rspfile is written to the actual script file
Paul Duffinb645ec82019-11-27 17:43:54 +000090 fmt.Fprintf(&(gc.content), strings.Repeat(" ", gc.indentLevel)+format+"\\n", args...)
Jiyong Park9b409bc2019-10-11 14:59:13 +090091}
92
93func (gf *generatedFile) build(pctx android.PackageContext, ctx android.BuilderContext, implicits android.Paths) {
94 rb := android.NewRuleBuilder()
95 // convert \\n to \n
96 rb.Command().
97 Implicits(implicits).
98 Text("echo").Text(proptools.ShellEscape(gf.content.String())).
99 Text("| sed 's/\\\\n/\\n/g' >").Output(gf.path)
100 rb.Command().
101 Text("chmod a+x").Output(gf.path)
102 rb.Build(pctx, ctx, gf.path.Base(), "Build "+gf.path.Base())
103}
104
Paul Duffin13879572019-11-28 14:31:38 +0000105// Collect all the members.
106//
107// The members are first grouped by type and then grouped by name. The order of
108// the types is the order they are referenced in sdkMemberListProperties. The
109// names are in order in which the dependencies were added.
110func collectMembers(ctx android.ModuleContext) []*sdkMember {
111 byType := make(map[android.SdkMemberType][]*sdkMember)
112 byName := make(map[string]*sdkMember)
113
Jiyong Park9b409bc2019-10-11 14:59:13 +0900114 ctx.VisitDirectDeps(func(m android.Module) {
Paul Duffin13879572019-11-28 14:31:38 +0000115 tag := ctx.OtherModuleDependencyTag(m)
116 if memberTag, ok := tag.(*sdkMemberDependencyTag); ok {
117 memberListProperty := memberTag.memberListProperty
118 memberType := memberListProperty.memberType
Jiyong Park9b409bc2019-10-11 14:59:13 +0900119
Paul Duffin13879572019-11-28 14:31:38 +0000120 // Make sure that the resolved module is allowed in the member list property.
121 if !memberType.IsInstance(m) {
122 ctx.ModuleErrorf("module %q is not valid in property %s", ctx.OtherModuleName(m), memberListProperty.name)
Jiyong Park73c54ee2019-10-22 20:31:18 +0900123 }
Paul Duffin13879572019-11-28 14:31:38 +0000124
125 name := ctx.OtherModuleName(m)
126
127 member := byName[name]
128 if member == nil {
129 member = &sdkMember{memberType: memberType, name: name}
130 byName[name] = member
131 byType[memberType] = append(byType[memberType], member)
Jiyong Park73c54ee2019-10-22 20:31:18 +0900132 }
Paul Duffin13879572019-11-28 14:31:38 +0000133
134 member.variants = append(member.variants, m.(android.SdkAware))
Jiyong Park73c54ee2019-10-22 20:31:18 +0900135 }
Paul Duffin13879572019-11-28 14:31:38 +0000136 })
137
138 var members []*sdkMember
139 for _, memberListProperty := range sdkMemberListProperties {
140 membersOfType := byType[memberListProperty.memberType]
141 members = append(members, membersOfType...)
Jiyong Park9b409bc2019-10-11 14:59:13 +0900142 }
143
Paul Duffin13879572019-11-28 14:31:38 +0000144 return members
Jiyong Park73c54ee2019-10-22 20:31:18 +0900145}
Jiyong Park9b409bc2019-10-11 14:59:13 +0900146
Jiyong Park73c54ee2019-10-22 20:31:18 +0900147// SDK directory structure
148// <sdk_root>/
149// Android.bp : definition of a 'sdk' module is here. This is a hand-made one.
150// <api_ver>/ : below this directory are all auto-generated
151// Android.bp : definition of 'sdk_snapshot' module is here
152// aidl/
153// frameworks/base/core/..../IFoo.aidl : an exported AIDL file
154// java/
Jiyong Park232e7852019-11-04 12:23:40 +0900155// <module_name>.jar : the stub jar for a java library 'module_name'
Jiyong Park73c54ee2019-10-22 20:31:18 +0900156// include/
157// bionic/libc/include/stdlib.h : an exported header file
158// include_gen/
Jiyong Park232e7852019-11-04 12:23:40 +0900159// <module_name>/com/android/.../IFoo.h : a generated header file
Jiyong Park73c54ee2019-10-22 20:31:18 +0900160// <arch>/include/ : arch-specific exported headers
161// <arch>/include_gen/ : arch-specific generated headers
162// <arch>/lib/
163// libFoo.so : a stub library
164
Jiyong Park232e7852019-11-04 12:23:40 +0900165// A name that uniquely identifies a prebuilt SDK member for a version of SDK snapshot
Jiyong Park73c54ee2019-10-22 20:31:18 +0900166// This isn't visible to users, so could be changed in future.
167func versionedSdkMemberName(ctx android.ModuleContext, memberName string, version string) string {
168 return ctx.ModuleName() + "_" + memberName + string(android.SdkVersionSeparator) + version
169}
170
Jiyong Park232e7852019-11-04 12:23:40 +0900171// buildSnapshot is the main function in this source file. It creates rules to copy
172// the contents (header files, stub libraries, etc) into the zip file.
173func (s *sdk) buildSnapshot(ctx android.ModuleContext) android.OutputPath {
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000174 snapshotDir := android.PathForModuleOut(ctx, "snapshot")
Jiyong Park9b409bc2019-10-11 14:59:13 +0900175
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000176 bp := newGeneratedFile(ctx, "snapshot", "Android.bp")
Paul Duffinb645ec82019-11-27 17:43:54 +0000177
178 bpFile := &bpFile{
179 modules: make(map[string]*bpModule),
180 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000181
182 builder := &snapshotBuilder{
Paul Duffinb645ec82019-11-27 17:43:54 +0000183 ctx: ctx,
Paul Duffine44358f2019-11-26 18:04:12 +0000184 sdk: s,
Paul Duffinb645ec82019-11-27 17:43:54 +0000185 version: "current",
186 snapshotDir: snapshotDir.OutputPath,
Paul Duffinc62a5102019-12-11 18:34:15 +0000187 copies: make(map[string]string),
Paul Duffinb645ec82019-11-27 17:43:54 +0000188 filesToZip: []android.Path{bp.path},
189 bpFile: bpFile,
190 prebuiltModules: make(map[string]*bpModule),
Jiyong Park73c54ee2019-10-22 20:31:18 +0900191 }
Paul Duffinac37c502019-11-26 18:02:20 +0000192 s.builderForTests = builder
Jiyong Park9b409bc2019-10-11 14:59:13 +0900193
Paul Duffin13879572019-11-28 14:31:38 +0000194 for _, member := range collectMembers(ctx) {
195 member.memberType.BuildSnapshot(ctx, builder, member)
Jiyong Park73c54ee2019-10-22 20:31:18 +0900196 }
Jiyong Park9b409bc2019-10-11 14:59:13 +0900197
Paul Duffinb645ec82019-11-27 17:43:54 +0000198 for _, unversioned := range builder.prebuiltOrder {
199 // Copy the unversioned module so it can be modified to make it versioned.
200 versioned := unversioned.copy()
201 name := versioned.properties["name"].(string)
202 versioned.setProperty("name", builder.versionedSdkMemberName(name))
203 versioned.insertAfter("name", "sdk_member_name", name)
204 bpFile.AddModule(versioned)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000205
Paul Duffinb645ec82019-11-27 17:43:54 +0000206 // Set prefer: false - this is not strictly required as that is the default.
207 unversioned.insertAfter("name", "prefer", false)
208 bpFile.AddModule(unversioned)
209 }
210
211 // Create the snapshot module.
212 snapshotName := ctx.ModuleName() + string(android.SdkVersionSeparator) + builder.version
213 snapshotModule := bpFile.newModule("sdk_snapshot")
214 snapshotModule.AddProperty("name", snapshotName)
Paul Duffin593b3c92019-12-05 14:31:48 +0000215
216 // Make sure that the snapshot has the same visibility as the sdk.
217 visibility := android.EffectiveVisibilityRules(ctx, s)
218 if len(visibility) != 0 {
219 snapshotModule.AddProperty("visibility", visibility)
220 }
221
Paul Duffine44358f2019-11-26 18:04:12 +0000222 addHostDeviceSupportedProperties(&s.ModuleBase, snapshotModule)
Paul Duffin13879572019-11-28 14:31:38 +0000223 for _, memberListProperty := range sdkMemberListProperties {
224 names := memberListProperty.getter(&s.properties)
225 if len(names) > 0 {
226 snapshotModule.AddProperty(memberListProperty.name, builder.versionedSdkMemberNames(names))
227 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000228 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000229 bpFile.AddModule(snapshotModule)
230
231 // generate Android.bp
232 bp = newGeneratedFile(ctx, "snapshot", "Android.bp")
233 generateBpContents(&bp.generatedContents, bpFile)
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000234
235 bp.build(pctx, ctx, nil)
236
237 filesToZip := builder.filesToZip
Jiyong Park9b409bc2019-10-11 14:59:13 +0900238
Jiyong Park232e7852019-11-04 12:23:40 +0900239 // zip them all
Paul Duffin91547182019-11-12 19:39:36 +0000240 outputZipFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000241 outputDesc := "Building snapshot for " + ctx.ModuleName()
242
243 // If there are no zips to merge then generate the output zip directly.
244 // Otherwise, generate an intermediate zip file into which other zips can be
245 // merged.
246 var zipFile android.OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000247 var desc string
248 if len(builder.zipsToMerge) == 0 {
249 zipFile = outputZipFile
Paul Duffin91547182019-11-12 19:39:36 +0000250 desc = outputDesc
251 } else {
252 zipFile = android.PathForModuleOut(ctx, ctx.ModuleName()+"-current.unmerged.zip").OutputPath
Paul Duffin91547182019-11-12 19:39:36 +0000253 desc = "Building intermediate snapshot for " + ctx.ModuleName()
254 }
255
Paul Duffin375058f2019-11-29 20:17:53 +0000256 ctx.Build(pctx, android.BuildParams{
257 Description: desc,
258 Rule: zipFiles,
259 Inputs: filesToZip,
260 Output: zipFile,
261 Args: map[string]string{
262 "basedir": builder.snapshotDir.String(),
263 },
264 })
Jiyong Park9b409bc2019-10-11 14:59:13 +0900265
Paul Duffin91547182019-11-12 19:39:36 +0000266 if len(builder.zipsToMerge) != 0 {
Paul Duffin375058f2019-11-29 20:17:53 +0000267 ctx.Build(pctx, android.BuildParams{
268 Description: outputDesc,
269 Rule: mergeZips,
270 Input: zipFile,
271 Inputs: builder.zipsToMerge,
272 Output: outputZipFile,
273 })
Paul Duffin91547182019-11-12 19:39:36 +0000274 }
275
276 return outputZipFile
Jiyong Park9b409bc2019-10-11 14:59:13 +0900277}
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000278
Paul Duffinb645ec82019-11-27 17:43:54 +0000279func generateBpContents(contents *generatedContents, bpFile *bpFile) {
280 contents.Printfln("// This is auto-generated. DO NOT EDIT.")
281 for _, bpModule := range bpFile.order {
282 contents.Printfln("")
283 contents.Printfln("%s {", bpModule.moduleType)
284 outputPropertySet(contents, &bpModule.bpPropertySet)
285 contents.Printfln("}")
286 }
Paul Duffinb645ec82019-11-27 17:43:54 +0000287}
288
289func outputPropertySet(contents *generatedContents, set *bpPropertySet) {
290 contents.Indent()
291 for _, name := range set.order {
292 value := set.properties[name]
293
294 reflectedValue := reflect.ValueOf(value)
295 t := reflectedValue.Type()
296
297 kind := t.Kind()
298 switch kind {
299 case reflect.Slice:
300 length := reflectedValue.Len()
301 if length > 1 {
302 contents.Printfln("%s: [", name)
303 contents.Indent()
304 for i := 0; i < length; i = i + 1 {
305 contents.Printfln("%q,", reflectedValue.Index(i).Interface())
306 }
307 contents.Dedent()
308 contents.Printfln("],")
309 } else if length == 0 {
310 contents.Printfln("%s: [],", name)
311 } else {
312 contents.Printfln("%s: [%q],", name, reflectedValue.Index(0).Interface())
313 }
314 case reflect.Bool:
315 contents.Printfln("%s: %t,", name, reflectedValue.Bool())
316
317 case reflect.Ptr:
318 contents.Printfln("%s: {", name)
319 outputPropertySet(contents, reflectedValue.Interface().(*bpPropertySet))
320 contents.Printfln("},")
321
322 default:
323 contents.Printfln("%s: %q,", name, value)
324 }
325 }
326 contents.Dedent()
327}
328
Paul Duffinac37c502019-11-26 18:02:20 +0000329func (s *sdk) GetAndroidBpContentsForTests() string {
Paul Duffinb645ec82019-11-27 17:43:54 +0000330 contents := &generatedContents{}
331 generateBpContents(contents, s.builderForTests.bpFile)
332 return contents.content.String()
Paul Duffinac37c502019-11-26 18:02:20 +0000333}
334
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000335type snapshotBuilder struct {
Paul Duffinb645ec82019-11-27 17:43:54 +0000336 ctx android.ModuleContext
Paul Duffine44358f2019-11-26 18:04:12 +0000337 sdk *sdk
Paul Duffinb645ec82019-11-27 17:43:54 +0000338 version string
339 snapshotDir android.OutputPath
340 bpFile *bpFile
Paul Duffinc62a5102019-12-11 18:34:15 +0000341
342 // Map from destination to source of each copy - used to eliminate duplicates and
343 // detect conflicts.
344 copies map[string]string
345
Paul Duffinb645ec82019-11-27 17:43:54 +0000346 filesToZip android.Paths
347 zipsToMerge android.Paths
348
349 prebuiltModules map[string]*bpModule
350 prebuiltOrder []*bpModule
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000351}
352
353func (s *snapshotBuilder) CopyToSnapshot(src android.Path, dest string) {
Paul Duffinc62a5102019-12-11 18:34:15 +0000354 if existing, ok := s.copies[dest]; ok {
355 if existing != src.String() {
356 s.ctx.ModuleErrorf("conflicting copy, %s copied from both %s and %s", dest, existing, src)
357 return
358 }
359 } else {
360 path := s.snapshotDir.Join(s.ctx, dest)
361 s.ctx.Build(pctx, android.BuildParams{
362 Rule: android.Cp,
363 Input: src,
364 Output: path,
365 })
366 s.filesToZip = append(s.filesToZip, path)
367
368 s.copies[dest] = src.String()
369 }
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000370}
371
Paul Duffin91547182019-11-12 19:39:36 +0000372func (s *snapshotBuilder) UnzipToSnapshot(zipPath android.Path, destDir string) {
373 ctx := s.ctx
374
375 // Repackage the zip file so that the entries are in the destDir directory.
376 // This will allow the zip file to be merged into the snapshot.
377 tmpZipPath := android.PathForModuleOut(ctx, "tmp", destDir+".zip").OutputPath
Paul Duffin375058f2019-11-29 20:17:53 +0000378
379 ctx.Build(pctx, android.BuildParams{
380 Description: "Repackaging zip file " + destDir + " for snapshot " + ctx.ModuleName(),
381 Rule: repackageZip,
382 Input: zipPath,
383 Output: tmpZipPath,
384 Args: map[string]string{
385 "destdir": destDir,
386 },
387 })
Paul Duffin91547182019-11-12 19:39:36 +0000388
389 // Add the repackaged zip file to the files to merge.
390 s.zipsToMerge = append(s.zipsToMerge, tmpZipPath)
391}
392
Paul Duffin9d8d6092019-12-05 18:19:29 +0000393func (s *snapshotBuilder) AddPrebuiltModule(member android.SdkMember, moduleType string) android.BpModule {
394 name := member.Name()
Paul Duffinb645ec82019-11-27 17:43:54 +0000395 if s.prebuiltModules[name] != nil {
396 panic(fmt.Sprintf("Duplicate module detected, module %s has already been added", name))
397 }
398
399 m := s.bpFile.newModule(moduleType)
400 m.AddProperty("name", name)
Paul Duffin593b3c92019-12-05 14:31:48 +0000401
402 // Extract visibility information from a member variant. All variants have the same
403 // visibility so it doesn't matter which one is used.
404 visibility := android.EffectiveVisibilityRules(s.ctx, member.Variants()[0])
405 if len(visibility) != 0 {
406 m.AddProperty("visibility", visibility)
407 }
408
Paul Duffine44358f2019-11-26 18:04:12 +0000409 addHostDeviceSupportedProperties(&s.sdk.ModuleBase, m)
Paul Duffinb645ec82019-11-27 17:43:54 +0000410
411 s.prebuiltModules[name] = m
412 s.prebuiltOrder = append(s.prebuiltOrder, m)
413 return m
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000414}
415
Paul Duffine44358f2019-11-26 18:04:12 +0000416func addHostDeviceSupportedProperties(module *android.ModuleBase, bpModule *bpModule) {
417 if !module.DeviceSupported() {
418 bpModule.AddProperty("device_supported", false)
419 }
420 if module.HostSupported() {
421 bpModule.AddProperty("host_supported", true)
422 }
423}
424
Paul Duffinb645ec82019-11-27 17:43:54 +0000425// Get a versioned name appropriate for the SDK snapshot version being taken.
426func (s *snapshotBuilder) versionedSdkMemberName(unversionedName string) string {
Paul Duffin0e0cf1d2019-11-12 19:39:25 +0000427 return versionedSdkMemberName(s.ctx, unversionedName, s.version)
428}
Paul Duffinb645ec82019-11-27 17:43:54 +0000429
430func (s *snapshotBuilder) versionedSdkMemberNames(members []string) []string {
431 var references []string = nil
432 for _, m := range members {
433 references = append(references, s.versionedSdkMemberName(m))
434 }
435 return references
436}
Paul Duffin13879572019-11-28 14:31:38 +0000437
438var _ android.SdkMember = (*sdkMember)(nil)
439
440type sdkMember struct {
441 memberType android.SdkMemberType
442 name string
443 variants []android.SdkAware
444}
445
446func (m *sdkMember) Name() string {
447 return m.name
448}
449
450func (m *sdkMember) Variants() []android.SdkAware {
451 return m.variants
452}