blob: 46207b21546d7bda37d400f33ab6888e0d707c8d [file] [log] [blame]
Jiyong Park48ca7dc2018-10-10 14:01:00 +09001// Copyright (C) 2018 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 apex
16
17import (
18 "fmt"
19 "io"
20 "path/filepath"
21 "runtime"
Jiyong Parkab3ceb32018-10-10 14:05:29 +090022 "sort"
Jiyong Park48ca7dc2018-10-10 14:01:00 +090023 "strings"
24
25 "android/soong/android"
26 "android/soong/cc"
27 "android/soong/java"
28
29 "github.com/google/blueprint"
30 "github.com/google/blueprint/proptools"
31)
32
33var (
34 pctx = android.NewPackageContext("android/apex")
35
36 // Create a canned fs config file where all files and directories are
37 // by default set to (uid/gid/mode) = (1000/1000/0644)
38 // TODO(b/113082813) make this configurable using config.fs syntax
39 generateFsConfig = pctx.StaticRule("generateFsConfig", blueprint.RuleParams{
Roland Levillain2b11f742018-11-02 11:50:42 +000040 Command: `echo '/ 1000 1000 0755' > ${out} && ` +
Dario Freni4abb1dc2018-11-20 18:04:58 +000041 `echo '/apex_manifest.json 1000 1000 0644' >> ${out} && ` +
Jiyong Park92905d62018-10-11 13:23:09 +090042 `echo ${ro_paths} | tr ' ' '\n' | awk '{print "/"$$1 " 1000 1000 0644"}' >> ${out} && ` +
43 `echo ${exec_paths} | tr ' ' '\n' | awk '{print "/"$$1 " 1000 1000 0755"}' >> ${out}`,
Jiyong Park48ca7dc2018-10-10 14:01:00 +090044 Description: "fs_config ${out}",
Jiyong Park92905d62018-10-11 13:23:09 +090045 }, "ro_paths", "exec_paths")
Jiyong Park48ca7dc2018-10-10 14:01:00 +090046
47 // TODO(b/113233103): make sure that file_contexts is sane, i.e., validate
48 // against the binary policy using sefcontext_compiler -p <policy>.
49
50 // TODO(b/114327326): automate the generation of file_contexts
51 apexRule = pctx.StaticRule("apexRule", blueprint.RuleParams{
52 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
53 `(${copy_commands}) && ` +
54 `APEXER_TOOL_PATH=${tool_path} ` +
Jiyong Park25560152018-11-20 09:57:52 +090055 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park48ca7dc2018-10-10 14:01:00 +090056 `--file_contexts ${file_contexts} ` +
57 `--canned_fs_config ${canned_fs_config} ` +
Alex Light5098a612018-11-29 17:12:15 -080058 `--payload_type image ` +
Jiyong Park48ca7dc2018-10-10 14:01:00 +090059 `--key ${key} ${image_dir} ${out} `,
60 CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
61 "${mke2fs}", "${resize2fs}", "${sefcontext_compile}",
62 "${soong_zip}", "${zipalign}", "${aapt2}"},
63 Description: "APEX ${image_dir} => ${out}",
64 }, "tool_path", "image_dir", "copy_commands", "manifest", "file_contexts", "canned_fs_config", "key")
Colin Crossa4925902018-11-16 11:36:28 -080065
Alex Light5098a612018-11-29 17:12:15 -080066 zipApexRule = pctx.StaticRule("zipApexRule", blueprint.RuleParams{
67 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
68 `(${copy_commands}) && ` +
69 `APEXER_TOOL_PATH=${tool_path} ` +
70 `${apexer} --force --manifest ${manifest} ` +
71 `--payload_type zip ` +
72 `${image_dir} ${out} `,
73 CommandDeps: []string{"${apexer}", "${merge_zips}", "${soong_zip}", "${zipalign}", "${aapt2}"},
74 Description: "ZipAPEX ${image_dir} => ${out}",
75 }, "tool_path", "image_dir", "copy_commands", "manifest")
76
Colin Crossa4925902018-11-16 11:36:28 -080077 apexProtoConvertRule = pctx.AndroidStaticRule("apexProtoConvertRule",
78 blueprint.RuleParams{
79 Command: `${aapt2} convert --output-format proto $in -o $out`,
80 CommandDeps: []string{"${aapt2}"},
81 })
82
83 apexBundleRule = pctx.StaticRule("apexBundleRule", blueprint.RuleParams{
Jiyong Park1ed0fc52018-11-23 13:22:21 +090084 Command: `${zip2zip} -i $in -o $out ` +
Dario Freni4abb1dc2018-11-20 18:04:58 +000085 `apex_payload.img:apex/${abi}.img ` +
86 `apex_manifest.json:root/apex_manifest.json ` +
Shahar Amitai328b0772018-11-26 14:12:02 +000087 `AndroidManifest.xml:manifest/AndroidManifest.xml`,
Colin Crossa4925902018-11-16 11:36:28 -080088 CommandDeps: []string{"${zip2zip}"},
89 Description: "app bundle",
90 }, "abi")
Jiyong Park48ca7dc2018-10-10 14:01:00 +090091)
92
Alex Light5098a612018-11-29 17:12:15 -080093var imageApexSuffix = ".apex"
94var zipApexSuffix = ".zipapex"
95
96var imageApexType = "image"
97var zipApexType = "zip"
Jiyong Park48ca7dc2018-10-10 14:01:00 +090098
99type dependencyTag struct {
100 blueprint.BaseDependencyTag
101 name string
102}
103
104var (
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900105 sharedLibTag = dependencyTag{name: "sharedLib"}
106 executableTag = dependencyTag{name: "executable"}
107 javaLibTag = dependencyTag{name: "javaLib"}
108 prebuiltTag = dependencyTag{name: "prebuilt"}
109 keyTag = dependencyTag{name: "key"}
110 certificateTag = dependencyTag{name: "certificate"}
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900111)
112
113func init() {
114 pctx.Import("android/soong/common")
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900115 pctx.Import("android/soong/java")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900116 pctx.HostBinToolVariable("apexer", "apexer")
Roland Levillain54bdfda2018-10-05 19:34:32 +0100117 // ART minimal builds (using the master-art manifest) do not have the "frameworks/base"
118 // projects, and hence cannot built 'aapt2'. Use the SDK prebuilt instead.
119 hostBinToolVariableWithPrebuilt := func(name, prebuiltDir, tool string) {
120 pctx.VariableFunc(name, func(ctx android.PackageVarContext) string {
121 if !android.ExistentPathForSource(ctx, "frameworks/base").Valid() {
122 return filepath.Join(prebuiltDir, runtime.GOOS, "bin", tool)
123 } else {
124 return pctx.HostBinToolPath(ctx, tool).String()
125 }
126 })
127 }
128 hostBinToolVariableWithPrebuilt("aapt2", "prebuilts/sdk/tools", "aapt2")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900129 pctx.HostBinToolVariable("avbtool", "avbtool")
130 pctx.HostBinToolVariable("e2fsdroid", "e2fsdroid")
131 pctx.HostBinToolVariable("merge_zips", "merge_zips")
132 pctx.HostBinToolVariable("mke2fs", "mke2fs")
133 pctx.HostBinToolVariable("resize2fs", "resize2fs")
134 pctx.HostBinToolVariable("sefcontext_compile", "sefcontext_compile")
135 pctx.HostBinToolVariable("soong_zip", "soong_zip")
Colin Crossa4925902018-11-16 11:36:28 -0800136 pctx.HostBinToolVariable("zip2zip", "zip2zip")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900137 pctx.HostBinToolVariable("zipalign", "zipalign")
138
Alex Lightee250722018-12-06 14:00:02 -0800139 android.RegisterModuleType("apex", ApexBundleFactory)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900140
141 android.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
142 ctx.TopDown("apex_deps", apexDepsMutator)
143 ctx.BottomUp("apex", apexMutator)
144 })
145}
146
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900147// Mark the direct and transitive dependencies of apex bundles so that they
148// can be built for the apex bundles.
149func apexDepsMutator(mctx android.TopDownMutatorContext) {
150 if _, ok := mctx.Module().(*apexBundle); ok {
Colin Crossa4925902018-11-16 11:36:28 -0800151 apexBundleName := mctx.ModuleName()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900152 mctx.WalkDeps(func(child, parent android.Module) bool {
Jiyong Park0ddfcd12018-12-11 01:35:25 +0900153 depName := mctx.OtherModuleName(child)
154 // If the parent is apexBundle, this child is directly depended.
155 _, directDep := parent.(*apexBundle)
156 android.UpdateApexDependency(apexBundleName, depName, directDep)
157
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900158 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() {
Jiyong Park0ddfcd12018-12-11 01:35:25 +0900159 am.BuildForApex(apexBundleName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900160 return true
161 } else {
162 return false
163 }
164 })
165 }
166}
167
168// Create apex variations if a module is included in APEX(s).
169func apexMutator(mctx android.BottomUpMutatorContext) {
170 if am, ok := mctx.Module().(android.ApexModule); ok && am.CanHaveApexVariants() {
Jiyong Park0ddfcd12018-12-11 01:35:25 +0900171 am.CreateApexVariations(mctx)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900172 } else if _, ok := mctx.Module().(*apexBundle); ok {
173 // apex bundle itself is mutated so that it and its modules have same
174 // apex variant.
175 apexBundleName := mctx.ModuleName()
176 mctx.CreateVariations(apexBundleName)
177 }
178}
179
180type apexBundleProperties struct {
181 // Json manifest file describing meta info of this APEX bundle. Default:
Dario Freni4abb1dc2018-11-20 18:04:58 +0000182 // "apex_manifest.json"
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900183 Manifest *string
184
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900185 // Determines the file contexts file for setting security context to each file in this APEX bundle.
186 // Specifically, when this is set to <value>, /system/sepolicy/apex/<value>_file_contexts file is
187 // used.
188 // Default: <name_of_this_module>
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900189 File_contexts *string
190
191 // List of native shared libs that are embedded inside this APEX bundle
192 Native_shared_libs []string
193
194 // List of native executables that are embedded inside this APEX bundle
195 Binaries []string
196
197 // List of java libraries that are embedded inside this APEX bundle
198 Java_libs []string
199
200 // List of prebuilt files that are embedded inside this APEX bundle
201 Prebuilts []string
Jiyong Parkff1458f2018-10-12 21:49:38 +0900202
203 // Name of the apex_key module that provides the private key to sign APEX
204 Key *string
Jiyong Park397e55e2018-10-24 21:09:55 +0900205
Alex Light5098a612018-11-29 17:12:15 -0800206 // The type of APEX to build. Controls what the APEX payload is. Either
207 // 'image', 'zip' or 'both'. Default: 'image'.
208 Payload_type *string
209
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900210 // The name of a certificate in the default certificate directory, blank to use the default product certificate,
211 // or an android_app_certificate module name in the form ":module".
212 Certificate *string
213
Jiyong Park397e55e2018-10-24 21:09:55 +0900214 Multilib struct {
215 First struct {
216 // List of native libraries whose compile_multilib is "first"
217 Native_shared_libs []string
218 // List of native executables whose compile_multilib is "first"
219 Binaries []string
220 }
221 Both struct {
222 // List of native libraries whose compile_multilib is "both"
223 Native_shared_libs []string
224 // List of native executables whose compile_multilib is "both"
225 Binaries []string
226 }
227 Prefer32 struct {
228 // List of native libraries whose compile_multilib is "prefer32"
229 Native_shared_libs []string
230 // List of native executables whose compile_multilib is "prefer32"
231 Binaries []string
232 }
233 Lib32 struct {
234 // List of native libraries whose compile_multilib is "32"
235 Native_shared_libs []string
236 // List of native executables whose compile_multilib is "32"
237 Binaries []string
238 }
239 Lib64 struct {
240 // List of native libraries whose compile_multilib is "64"
241 Native_shared_libs []string
242 // List of native executables whose compile_multilib is "64"
243 Binaries []string
244 }
245 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900246}
247
Jiyong Park8fd61922018-11-08 02:50:25 +0900248type apexFileClass int
249
250const (
251 etc apexFileClass = iota
252 nativeSharedLib
253 nativeExecutable
254 javaSharedLib
255)
256
Alex Light5098a612018-11-29 17:12:15 -0800257type apexPackaging int
258
259const (
260 imageApex apexPackaging = iota
261 zipApex
262 both
263)
264
265func (a apexPackaging) image() bool {
266 switch a {
267 case imageApex, both:
268 return true
269 }
270 return false
271}
272
273func (a apexPackaging) zip() bool {
274 switch a {
275 case zipApex, both:
276 return true
277 }
278 return false
279}
280
281func (a apexPackaging) suffix() string {
282 switch a {
283 case imageApex:
284 return imageApexSuffix
285 case zipApex:
286 return zipApexSuffix
287 case both:
288 panic(fmt.Errorf("must be either zip or image"))
289 default:
290 panic(fmt.Errorf("unkonwn APEX type %d", a))
291 }
292}
293
294func (a apexPackaging) name() string {
295 switch a {
296 case imageApex:
297 return imageApexType
298 case zipApex:
299 return zipApexType
300 case both:
301 panic(fmt.Errorf("must be either zip or image"))
302 default:
303 panic(fmt.Errorf("unkonwn APEX type %d", a))
304 }
305}
306
Jiyong Park8fd61922018-11-08 02:50:25 +0900307func (class apexFileClass) NameInMake() string {
308 switch class {
309 case etc:
310 return "ETC"
311 case nativeSharedLib:
312 return "SHARED_LIBRARIES"
313 case nativeExecutable:
314 return "EXECUTABLES"
315 case javaSharedLib:
316 return "JAVA_LIBRARIES"
317 default:
318 panic(fmt.Errorf("unkonwn class %d", class))
319 }
320}
321
322type apexFile struct {
323 builtFile android.Path
324 moduleName string
325 archType android.ArchType
326 installDir string
327 class apexFileClass
328}
329
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900330type apexBundle struct {
331 android.ModuleBase
332 android.DefaultableModuleBase
333
334 properties apexBundleProperties
335
Alex Light5098a612018-11-29 17:12:15 -0800336 apexTypes apexPackaging
337
Colin Crossa4925902018-11-16 11:36:28 -0800338 bundleModuleFile android.WritablePath
Alex Light5098a612018-11-29 17:12:15 -0800339 outputFiles map[apexPackaging]android.WritablePath
Colin Crossa4925902018-11-16 11:36:28 -0800340 installDir android.OutputPath
Jiyong Park8fd61922018-11-08 02:50:25 +0900341
342 // list of files to be included in this apex
343 filesInfo []apexFile
344
345 flattened bool
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900346}
347
Jiyong Park397e55e2018-10-24 21:09:55 +0900348func addDependenciesForNativeModules(ctx android.BottomUpMutatorContext,
349 native_shared_libs []string, binaries []string, arch string) {
350 // Use *FarVariation* to be able to depend on modules having
351 // conflicting variations with this module. This is required since
352 // arch variant of an APEX bundle is 'common' but it is 'arm' or 'arm64'
353 // for native shared libs.
354 ctx.AddFarVariationDependencies([]blueprint.Variation{
355 {Mutator: "arch", Variation: arch},
356 {Mutator: "image", Variation: "core"},
357 {Mutator: "link", Variation: "shared"},
Jiyong Park28d395a2018-12-07 22:42:47 +0900358 {Mutator: "version", Variation: ""}, // "" is the non-stub variant
Jiyong Park397e55e2018-10-24 21:09:55 +0900359 }, sharedLibTag, native_shared_libs...)
360
361 ctx.AddFarVariationDependencies([]blueprint.Variation{
362 {Mutator: "arch", Variation: arch},
363 {Mutator: "image", Variation: "core"},
364 }, executableTag, binaries...)
365}
366
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900367func (a *apexBundle) DepsMutator(ctx android.BottomUpMutatorContext) {
Jiyong Park397e55e2018-10-24 21:09:55 +0900368 targets := ctx.MultiTargets()
369 has32BitTarget := false
370 for _, target := range targets {
371 if target.Arch.ArchType.Multilib == "lib32" {
372 has32BitTarget = true
373 }
374 }
375 for i, target := range targets {
376 // When multilib.* is omitted for native_shared_libs, it implies
377 // multilib.both.
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900378 ctx.AddFarVariationDependencies([]blueprint.Variation{
Jiyong Park397e55e2018-10-24 21:09:55 +0900379 {Mutator: "arch", Variation: target.String()},
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900380 {Mutator: "image", Variation: "core"},
381 {Mutator: "link", Variation: "shared"},
382 }, sharedLibTag, a.properties.Native_shared_libs...)
383
Jiyong Park397e55e2018-10-24 21:09:55 +0900384 // Add native modules targetting both ABIs
385 addDependenciesForNativeModules(ctx,
386 a.properties.Multilib.Both.Native_shared_libs,
387 a.properties.Multilib.Both.Binaries, target.String())
388
389 if i == 0 {
390 // When multilib.* is omitted for binaries, it implies
391 // multilib.first.
392 ctx.AddFarVariationDependencies([]blueprint.Variation{
393 {Mutator: "arch", Variation: target.String()},
394 {Mutator: "image", Variation: "core"},
395 }, executableTag, a.properties.Binaries...)
396
397 // Add native modules targetting the first ABI
398 addDependenciesForNativeModules(ctx,
399 a.properties.Multilib.First.Native_shared_libs,
400 a.properties.Multilib.First.Binaries, target.String())
401 }
402
403 switch target.Arch.ArchType.Multilib {
404 case "lib32":
405 // Add native modules targetting 32-bit ABI
406 addDependenciesForNativeModules(ctx,
407 a.properties.Multilib.Lib32.Native_shared_libs,
408 a.properties.Multilib.Lib32.Binaries, target.String())
409
410 addDependenciesForNativeModules(ctx,
411 a.properties.Multilib.Prefer32.Native_shared_libs,
412 a.properties.Multilib.Prefer32.Binaries, target.String())
413 case "lib64":
414 // Add native modules targetting 64-bit ABI
415 addDependenciesForNativeModules(ctx,
416 a.properties.Multilib.Lib64.Native_shared_libs,
417 a.properties.Multilib.Lib64.Binaries, target.String())
418
419 if !has32BitTarget {
420 addDependenciesForNativeModules(ctx,
421 a.properties.Multilib.Prefer32.Native_shared_libs,
422 a.properties.Multilib.Prefer32.Binaries, target.String())
423 }
424 }
425
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900426 }
427
Jiyong Parkff1458f2018-10-12 21:49:38 +0900428 ctx.AddFarVariationDependencies([]blueprint.Variation{
429 {Mutator: "arch", Variation: "android_common"},
430 }, javaLibTag, a.properties.Java_libs...)
431
432 ctx.AddFarVariationDependencies([]blueprint.Variation{
433 {Mutator: "arch", Variation: "android_common"},
434 }, prebuiltTag, a.properties.Prebuilts...)
435
436 if String(a.properties.Key) == "" {
437 ctx.ModuleErrorf("key is missing")
438 return
439 }
440 ctx.AddDependency(ctx.Module(), keyTag, String(a.properties.Key))
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900441
442 cert := android.SrcIsModule(String(a.properties.Certificate))
443 if cert != "" {
444 ctx.AddDependency(ctx.Module(), certificateTag, cert)
445 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900446}
447
Jiyong Park74e240b2018-11-27 21:27:08 +0900448func (a *apexBundle) Srcs() android.Paths {
449 return android.Paths{a.outputFiles[imageApex]}
450}
451
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900452func getCopyManifestForNativeLibrary(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
453 // Decide the APEX-local directory by the multilib of the library
454 // In the future, we may query this to the module.
455 switch cc.Arch().ArchType.Multilib {
456 case "lib32":
457 dirInApex = "lib"
458 case "lib64":
459 dirInApex = "lib64"
460 }
461 if !cc.Arch().Native {
462 dirInApex = filepath.Join(dirInApex, cc.Arch().ArchType.String())
463 }
464
465 fileToCopy = cc.OutputFile().Path()
466 return
467}
468
469func getCopyManifestForExecutable(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
470 dirInApex = "bin"
471 fileToCopy = cc.OutputFile().Path()
472 return
473}
474
475func getCopyManifestForJavaLibrary(java *java.Library) (fileToCopy android.Path, dirInApex string) {
476 dirInApex = "javalib"
Jiyong Park8fd61922018-11-08 02:50:25 +0900477 fileToCopy = java.DexJarFile()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900478 return
479}
480
481func getCopyManifestForPrebuiltEtc(prebuilt *android.PrebuiltEtc) (fileToCopy android.Path, dirInApex string) {
482 dirInApex = filepath.Join("etc", prebuilt.SubDir())
483 fileToCopy = prebuilt.OutputFile()
484 return
485}
486
487func (a *apexBundle) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Park8fd61922018-11-08 02:50:25 +0900488 filesInfo := []apexFile{}
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900489
Jiyong Parkff1458f2018-10-12 21:49:38 +0900490 var keyFile android.Path
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900491 var certificate java.Certificate
Jiyong Parkff1458f2018-10-12 21:49:38 +0900492
Alex Light5098a612018-11-29 17:12:15 -0800493 if a.properties.Payload_type == nil || *a.properties.Payload_type == "image" {
494 a.apexTypes = imageApex
495 } else if *a.properties.Payload_type == "zip" {
496 a.apexTypes = zipApex
497 } else if *a.properties.Payload_type == "both" {
498 a.apexTypes = both
499 } else {
500 ctx.PropertyErrorf("type", "%q is not one of \"image\", \"zip\", or \"both\".", *a.properties.Payload_type)
501 return
502 }
503
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900504 ctx.WalkDeps(func(child, parent android.Module) bool {
505 if _, ok := parent.(*apexBundle); ok {
506 // direct dependencies
507 depTag := ctx.OtherModuleDependencyTag(child)
Jiyong Parkff1458f2018-10-12 21:49:38 +0900508 depName := ctx.OtherModuleName(child)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900509 switch depTag {
510 case sharedLibTag:
511 if cc, ok := child.(*cc.Module); ok {
512 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900513 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeSharedLib})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900514 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900515 } else {
516 ctx.PropertyErrorf("native_shared_libs", "%q is not a cc_library or cc_library_shared module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900517 }
518 case executableTag:
519 if cc, ok := child.(*cc.Module); ok {
520 fileToCopy, dirInApex := getCopyManifestForExecutable(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900521 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeExecutable})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900522 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900523 } else {
524 ctx.PropertyErrorf("binaries", "%q is not a cc_binary module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900525 }
526 case javaLibTag:
527 if java, ok := child.(*java.Library); ok {
528 fileToCopy, dirInApex := getCopyManifestForJavaLibrary(java)
Jiyong Park8fd61922018-11-08 02:50:25 +0900529 if fileToCopy == nil {
530 ctx.PropertyErrorf("java_libs", "%q is not configured to be compiled into dex", depName)
531 } else {
532 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, java.Arch().ArchType, dirInApex, javaSharedLib})
533 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900534 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900535 } else {
536 ctx.PropertyErrorf("java_libs", "%q is not a java_library module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900537 }
538 case prebuiltTag:
539 if prebuilt, ok := child.(*android.PrebuiltEtc); ok {
540 fileToCopy, dirInApex := getCopyManifestForPrebuiltEtc(prebuilt)
Jiyong Park8fd61922018-11-08 02:50:25 +0900541 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, prebuilt.Arch().ArchType, dirInApex, etc})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900542 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900543 } else {
544 ctx.PropertyErrorf("prebuilts", "%q is not a prebuilt_etc module", depName)
545 }
546 case keyTag:
547 if key, ok := child.(*apexKey); ok {
548 keyFile = key.private_key_file
549 return false
550 } else {
551 ctx.PropertyErrorf("key", "%q is not an apex_key module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900552 }
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900553 case certificateTag:
554 if dep, ok := child.(*java.AndroidAppCertificate); ok {
555 certificate = dep.Certificate
556 return false
557 } else {
558 ctx.ModuleErrorf("certificate dependency %q must be an android_app_certificate module", depName)
559 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900560 }
561 } else {
562 // indirect dependencies
563 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() && am.IsInstallableToApex() {
564 if cc, ok := child.(*cc.Module); ok {
Jiyong Park25fc6a92018-11-18 18:02:45 +0900565 if cc.IsStubs() || cc.HasStubsVariants() {
566 return false
567 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900568 depName := ctx.OtherModuleName(child)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900569 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900570 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeSharedLib})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900571 return true
572 }
573 }
574 }
575 return false
576 })
577
Jiyong Parkfa0a3732018-11-09 05:52:26 +0900578 if keyFile == nil {
579 ctx.PropertyErrorf("key", "private_key for %q could not be found", String(a.properties.Key))
580 return
581 }
582
Jiyong Park8fd61922018-11-08 02:50:25 +0900583 // remove duplicates in filesInfo
584 removeDup := func(filesInfo []apexFile) []apexFile {
585 encountered := make(map[android.Path]bool)
586 result := []apexFile{}
587 for _, f := range filesInfo {
588 if !encountered[f.builtFile] {
589 encountered[f.builtFile] = true
590 result = append(result, f)
591 }
592 }
593 return result
594 }
595 filesInfo = removeDup(filesInfo)
596
597 // to have consistent build rules
598 sort.Slice(filesInfo, func(i, j int) bool {
599 return filesInfo[i].builtFile.String() < filesInfo[j].builtFile.String()
600 })
601
602 // prepend the name of this APEX to the module names. These names will be the names of
603 // modules that will be defined if the APEX is flattened.
604 for i := range filesInfo {
605 filesInfo[i].moduleName = ctx.ModuleName() + "." + filesInfo[i].moduleName
606 }
607
Colin Crossa4925902018-11-16 11:36:28 -0800608 a.flattened = ctx.Config().FlattenApex() && !ctx.Config().UnbundledBuild()
Jiyong Park8fd61922018-11-08 02:50:25 +0900609 a.installDir = android.PathForModuleInstall(ctx, "apex")
610 a.filesInfo = filesInfo
Alex Light5098a612018-11-29 17:12:15 -0800611
612 if a.apexTypes.zip() {
613 a.buildUnflattenedApex(ctx, keyFile, certificate, zipApex)
614 }
615 if a.apexTypes.image() {
616 if ctx.Config().FlattenApex() {
617 a.buildFlattenedApex(ctx)
618 } else {
619 a.buildUnflattenedApex(ctx, keyFile, certificate, imageApex)
620 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900621 }
622}
623
Alex Light5098a612018-11-29 17:12:15 -0800624func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext, keyFile android.Path, certificate java.Certificate, apexType apexPackaging) {
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900625 cert := String(a.properties.Certificate)
626 if cert != "" && android.SrcIsModule(cert) == "" {
627 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
628 certificate = java.Certificate{
629 defaultDir.Join(ctx, cert+".x509.pem"),
630 defaultDir.Join(ctx, cert+".pk8"),
631 }
632 } else if cert == "" {
633 pem, key := ctx.Config().DefaultAppCertificate(ctx)
634 certificate = java.Certificate{pem, key}
635 }
636
Dario Freni4abb1dc2018-11-20 18:04:58 +0000637 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900638
Alex Light5098a612018-11-29 17:12:15 -0800639 var abis []string
640 for _, target := range ctx.MultiTargets() {
641 if len(target.Arch.Abi) > 0 {
642 abis = append(abis, target.Arch.Abi[0])
643 }
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900644 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900645
Alex Light5098a612018-11-29 17:12:15 -0800646 abis = android.FirstUniqueStrings(abis)
647
648 suffix := apexType.suffix()
649 unsignedOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+suffix+".unsigned")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900650
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900651 filesToCopy := []android.Path{}
Jiyong Park8fd61922018-11-08 02:50:25 +0900652 for _, f := range a.filesInfo {
653 filesToCopy = append(filesToCopy, f.builtFile)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900654 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900655
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900656 copyCommands := []string{}
Jiyong Park8fd61922018-11-08 02:50:25 +0900657 for i, src := range filesToCopy {
658 dest := filepath.Join(a.filesInfo[i].installDir, src.Base())
Alex Light5098a612018-11-29 17:12:15 -0800659 dest_path := filepath.Join(android.PathForModuleOut(ctx, "image"+suffix).String(), dest)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900660 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(dest_path))
661 copyCommands = append(copyCommands, "cp "+src.String()+" "+dest_path)
662 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900663 implicitInputs := append(android.Paths(nil), filesToCopy...)
Alex Light5098a612018-11-29 17:12:15 -0800664 implicitInputs = append(implicitInputs, manifest)
665
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900666 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
667 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900668
Alex Light5098a612018-11-29 17:12:15 -0800669 if apexType.image() {
670 // files and dirs that will be created in APEX
671 var readOnlyPaths []string
672 var executablePaths []string // this also includes dirs
673 for _, f := range a.filesInfo {
674 pathInApex := filepath.Join(f.installDir, f.builtFile.Base())
675 if f.installDir == "bin" {
676 executablePaths = append(executablePaths, pathInApex)
677 } else {
678 readOnlyPaths = append(readOnlyPaths, pathInApex)
679 }
Jiyong Park7c2ee712018-12-07 00:42:25 +0900680 dir := f.installDir
681 for !android.InList(dir, executablePaths) && dir != "" {
682 executablePaths = append(executablePaths, dir)
683 dir, _ = filepath.Split(dir) // move up to the parent
684 if len(dir) > 0 {
685 // remove trailing slash
686 dir = dir[:len(dir)-1]
687 }
Alex Light5098a612018-11-29 17:12:15 -0800688 }
689 }
690 sort.Strings(readOnlyPaths)
691 sort.Strings(executablePaths)
692 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
693 ctx.Build(pctx, android.BuildParams{
694 Rule: generateFsConfig,
695 Output: cannedFsConfig,
696 Description: "generate fs config",
697 Args: map[string]string{
698 "ro_paths": strings.Join(readOnlyPaths, " "),
699 "exec_paths": strings.Join(executablePaths, " "),
700 },
701 })
702
703 fcName := proptools.StringDefault(a.properties.File_contexts, ctx.ModuleName())
704 fileContextsPath := "system/sepolicy/apex/" + fcName + "-file_contexts"
705 fileContextsOptionalPath := android.ExistentPathForSource(ctx, fileContextsPath)
706 if !fileContextsOptionalPath.Valid() {
707 ctx.ModuleErrorf("Cannot find file_contexts file: %q", fileContextsPath)
708 return
709 }
710 fileContexts := fileContextsOptionalPath.Path()
711
712 // Additional implicit inputs.
713 implicitInputs = append(implicitInputs, cannedFsConfig, fileContexts, keyFile)
714
715 ctx.Build(pctx, android.BuildParams{
716 Rule: apexRule,
717 Implicits: implicitInputs,
718 Output: unsignedOutputFile,
719 Description: "apex (" + apexType.name() + ")",
720 Args: map[string]string{
721 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
722 "image_dir": android.PathForModuleOut(ctx, "image"+suffix).String(),
723 "copy_commands": strings.Join(copyCommands, " && "),
724 "manifest": manifest.String(),
725 "file_contexts": fileContexts.String(),
726 "canned_fs_config": cannedFsConfig.String(),
727 "key": keyFile.String(),
728 },
729 })
730
731 apexProtoFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".pb"+suffix)
732 bundleModuleFile := android.PathForModuleOut(ctx, ctx.ModuleName()+suffix+"-base.zip")
733 a.bundleModuleFile = bundleModuleFile
734
735 ctx.Build(pctx, android.BuildParams{
736 Rule: apexProtoConvertRule,
737 Input: unsignedOutputFile,
738 Output: apexProtoFile,
739 Description: "apex proto convert",
740 })
741
742 ctx.Build(pctx, android.BuildParams{
743 Rule: apexBundleRule,
744 Input: apexProtoFile,
745 Output: a.bundleModuleFile,
746 Description: "apex bundle module",
747 Args: map[string]string{
748 "abi": strings.Join(abis, "."),
749 },
750 })
751 } else {
752 ctx.Build(pctx, android.BuildParams{
753 Rule: zipApexRule,
754 Implicits: implicitInputs,
755 Output: unsignedOutputFile,
756 Description: "apex (" + apexType.name() + ")",
757 Args: map[string]string{
758 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
759 "image_dir": android.PathForModuleOut(ctx, "image"+suffix).String(),
760 "copy_commands": strings.Join(copyCommands, " && "),
761 "manifest": manifest.String(),
762 },
763 })
Colin Crossa4925902018-11-16 11:36:28 -0800764 }
Colin Crossa4925902018-11-16 11:36:28 -0800765
Alex Light5098a612018-11-29 17:12:15 -0800766 a.outputFiles[apexType] = android.PathForModuleOut(ctx, ctx.ModuleName()+suffix)
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900767 ctx.Build(pctx, android.BuildParams{
768 Rule: java.Signapk,
769 Description: "signapk",
Alex Light5098a612018-11-29 17:12:15 -0800770 Output: a.outputFiles[apexType],
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900771 Input: unsignedOutputFile,
772 Args: map[string]string{
773 "certificates": strings.Join([]string{certificate.Pem.String(), certificate.Key.String()}, " "),
Jiyong Parkbfe64a12018-11-22 02:51:54 +0900774 "flags": "-a 4096", //alignment
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900775 },
776 })
Alex Light5098a612018-11-29 17:12:15 -0800777
778 // Install to $OUT/soong/{target,host}/.../apex
779 ctx.InstallFile(android.PathForModuleInstall(ctx, "apex"), ctx.ModuleName()+suffix, a.outputFiles[apexType])
Jiyong Park8fd61922018-11-08 02:50:25 +0900780}
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900781
Jiyong Park8fd61922018-11-08 02:50:25 +0900782func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
Dario Freni4abb1dc2018-11-20 18:04:58 +0000783 // For flattened APEX, do nothing but make sure that apex_manifest.json file is also copied along
Jiyong Park8fd61922018-11-08 02:50:25 +0900784 // with other ordinary files.
Dario Freni4abb1dc2018-11-20 18:04:58 +0000785 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
786 a.filesInfo = append(a.filesInfo, apexFile{manifest, ctx.ModuleName() + ".apex_manifest.json", android.Common, ".", etc})
Jiyong Park8fd61922018-11-08 02:50:25 +0900787
788 for _, fi := range a.filesInfo {
Colin Crossa4925902018-11-16 11:36:28 -0800789 dir := filepath.Join("apex", ctx.ModuleName(), fi.installDir)
Jiyong Park8fd61922018-11-08 02:50:25 +0900790 ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.builtFile.Base(), fi.builtFile)
791 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900792}
793
794func (a *apexBundle) AndroidMk() android.AndroidMkData {
Alex Light5098a612018-11-29 17:12:15 -0800795 writers := []android.AndroidMkData{}
796 if a.apexTypes.image() {
797 writers = append(writers, a.androidMkForType(imageApex))
798 }
799 if a.apexTypes.zip() {
800 writers = append(writers, a.androidMkForType(zipApex))
801 }
802 return android.AndroidMkData{
803 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
804 for _, data := range writers {
805 data.Custom(w, name, prefix, moduleDir, data)
806 }
807 }}
808}
809
810func (a *apexBundle) androidMkForType(apexType apexPackaging) android.AndroidMkData {
811 // Only image APEXes can be flattened.
812 if a.flattened && apexType.image() {
Jiyong Park8fd61922018-11-08 02:50:25 +0900813 return android.AndroidMkData{
814 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
815 moduleNames := []string{}
816 for _, fi := range a.filesInfo {
817 if !android.InList(fi.moduleName, moduleNames) {
818 moduleNames = append(moduleNames, fi.moduleName)
819 }
820 }
821 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
822 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
823 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
824 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", strings.Join(moduleNames, " "))
825 fmt.Fprintln(w, "include $(BUILD_PHONY_PACKAGE)")
826
827 for _, fi := range a.filesInfo {
828 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
829 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
830 fmt.Fprintln(w, "LOCAL_MODULE :=", fi.moduleName)
831 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString(), name, fi.installDir))
832 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", fi.builtFile.Base())
833 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", fi.builtFile.String())
834 fmt.Fprintln(w, "LOCAL_MODULE_CLASS :=", fi.class.NameInMake())
835 archStr := fi.archType.String()
836 if archStr != "common" {
837 fmt.Fprintln(w, "LOCAL_MODULE_TARGET_ARCH :=", archStr)
838 }
839 if fi.class == javaSharedLib {
840 fmt.Fprintln(w, "LOCAL_SOONG_DEX_JAR :=", fi.builtFile.String())
841 fmt.Fprintln(w, "LOCAL_DEX_PREOPT := false")
842 fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_java_prebuilt.mk")
843 } else {
844 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
845 }
846 }
847 }}
848 } else {
849 return android.AndroidMkData{
850 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
Alex Light5098a612018-11-29 17:12:15 -0800851 // zip-apex is the less common type so have the name refer to the image-apex
852 // only and use {name}.zip if you want the zip-apex
853 if apexType == zipApex && a.apexTypes == both {
854 name = name + ".zip"
855 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900856 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
857 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
858 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
859 fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC") // do we need a new class?
Alex Light5098a612018-11-29 17:12:15 -0800860 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", a.outputFiles[apexType].String())
Jiyong Park8fd61922018-11-08 02:50:25 +0900861 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString()))
Alex Light5098a612018-11-29 17:12:15 -0800862 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", name+apexType.suffix())
Jiyong Park8fd61922018-11-08 02:50:25 +0900863 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", String(a.properties.Key))
864 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
Colin Crossa4925902018-11-16 11:36:28 -0800865
Alex Light5098a612018-11-29 17:12:15 -0800866 if apexType == imageApex {
867 fmt.Fprintln(w, "ALL_MODULES.$(LOCAL_MODULE).BUNDLE :=", a.bundleModuleFile.String())
868 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900869 }}
870 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900871}
872
Alex Lightee250722018-12-06 14:00:02 -0800873func ApexBundleFactory() android.Module {
Alex Light5098a612018-11-29 17:12:15 -0800874 module := &apexBundle{
875 outputFiles: map[apexPackaging]android.WritablePath{},
876 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900877 module.AddProperties(&module.properties)
Alex Light5098a612018-11-29 17:12:15 -0800878 module.Prefer32(func(ctx android.BaseModuleContext, base *android.ModuleBase, class android.OsClass) bool {
Jiyong Park397e55e2018-10-24 21:09:55 +0900879 return class == android.Device && ctx.Config().DevicePrefer32BitExecutables()
880 })
Alex Light5098a612018-11-29 17:12:15 -0800881 android.InitAndroidMultiTargetsArchModule(module, android.HostAndDeviceSupported, android.MultilibCommon)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900882 android.InitDefaultableModule(module)
883 return module
884}