blob: 5ce0e0573410db8dbf894bd2554c0e2e6f2d8b48 [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 {
153 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() {
Colin Crossa4925902018-11-16 11:36:28 -0800154 moduleName := mctx.OtherModuleName(am) + "-" + am.Target().String()
Jiyong Park25fc6a92018-11-18 18:02:45 +0900155 // If the parent is apexBundle, this child is directly depended.
156 _, directDep := parent.(*apexBundle)
157 android.BuildModuleForApexBundle(mctx, moduleName, apexBundleName, directDep)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900158 return true
159 } else {
160 return false
161 }
162 })
163 }
164}
165
166// Create apex variations if a module is included in APEX(s).
167func apexMutator(mctx android.BottomUpMutatorContext) {
168 if am, ok := mctx.Module().(android.ApexModule); ok && am.CanHaveApexVariants() {
Colin Crossa4925902018-11-16 11:36:28 -0800169 moduleName := mctx.ModuleName() + "-" + am.Target().String()
Jiyong Park25fc6a92018-11-18 18:02:45 +0900170 bundleNames := android.GetApexBundlesForModule(mctx, moduleName)
171 if len(bundleNames) > 0 {
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900172 variations := []string{"platform"}
173 for bn := range bundleNames {
174 variations = append(variations, bn)
175 }
176 modules := mctx.CreateVariations(variations...)
177 for i, m := range modules {
178 if i == 0 {
179 continue // platform
180 }
181 m.(android.ApexModule).BuildForApex(variations[i])
182 }
183 }
184 } else if _, ok := mctx.Module().(*apexBundle); ok {
185 // apex bundle itself is mutated so that it and its modules have same
186 // apex variant.
187 apexBundleName := mctx.ModuleName()
188 mctx.CreateVariations(apexBundleName)
189 }
190}
191
192type apexBundleProperties struct {
193 // Json manifest file describing meta info of this APEX bundle. Default:
Dario Freni4abb1dc2018-11-20 18:04:58 +0000194 // "apex_manifest.json"
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900195 Manifest *string
196
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900197 // Determines the file contexts file for setting security context to each file in this APEX bundle.
198 // Specifically, when this is set to <value>, /system/sepolicy/apex/<value>_file_contexts file is
199 // used.
200 // Default: <name_of_this_module>
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900201 File_contexts *string
202
203 // List of native shared libs that are embedded inside this APEX bundle
204 Native_shared_libs []string
205
206 // List of native executables that are embedded inside this APEX bundle
207 Binaries []string
208
209 // List of java libraries that are embedded inside this APEX bundle
210 Java_libs []string
211
212 // List of prebuilt files that are embedded inside this APEX bundle
213 Prebuilts []string
Jiyong Parkff1458f2018-10-12 21:49:38 +0900214
215 // Name of the apex_key module that provides the private key to sign APEX
216 Key *string
Jiyong Park397e55e2018-10-24 21:09:55 +0900217
Alex Light5098a612018-11-29 17:12:15 -0800218 // The type of APEX to build. Controls what the APEX payload is. Either
219 // 'image', 'zip' or 'both'. Default: 'image'.
220 Payload_type *string
221
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900222 // The name of a certificate in the default certificate directory, blank to use the default product certificate,
223 // or an android_app_certificate module name in the form ":module".
224 Certificate *string
225
Jiyong Park397e55e2018-10-24 21:09:55 +0900226 Multilib struct {
227 First struct {
228 // List of native libraries whose compile_multilib is "first"
229 Native_shared_libs []string
230 // List of native executables whose compile_multilib is "first"
231 Binaries []string
232 }
233 Both struct {
234 // List of native libraries whose compile_multilib is "both"
235 Native_shared_libs []string
236 // List of native executables whose compile_multilib is "both"
237 Binaries []string
238 }
239 Prefer32 struct {
240 // List of native libraries whose compile_multilib is "prefer32"
241 Native_shared_libs []string
242 // List of native executables whose compile_multilib is "prefer32"
243 Binaries []string
244 }
245 Lib32 struct {
246 // List of native libraries whose compile_multilib is "32"
247 Native_shared_libs []string
248 // List of native executables whose compile_multilib is "32"
249 Binaries []string
250 }
251 Lib64 struct {
252 // List of native libraries whose compile_multilib is "64"
253 Native_shared_libs []string
254 // List of native executables whose compile_multilib is "64"
255 Binaries []string
256 }
257 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900258}
259
Jiyong Park8fd61922018-11-08 02:50:25 +0900260type apexFileClass int
261
262const (
263 etc apexFileClass = iota
264 nativeSharedLib
265 nativeExecutable
266 javaSharedLib
267)
268
Alex Light5098a612018-11-29 17:12:15 -0800269type apexPackaging int
270
271const (
272 imageApex apexPackaging = iota
273 zipApex
274 both
275)
276
277func (a apexPackaging) image() bool {
278 switch a {
279 case imageApex, both:
280 return true
281 }
282 return false
283}
284
285func (a apexPackaging) zip() bool {
286 switch a {
287 case zipApex, both:
288 return true
289 }
290 return false
291}
292
293func (a apexPackaging) suffix() string {
294 switch a {
295 case imageApex:
296 return imageApexSuffix
297 case zipApex:
298 return zipApexSuffix
299 case both:
300 panic(fmt.Errorf("must be either zip or image"))
301 default:
302 panic(fmt.Errorf("unkonwn APEX type %d", a))
303 }
304}
305
306func (a apexPackaging) name() string {
307 switch a {
308 case imageApex:
309 return imageApexType
310 case zipApex:
311 return zipApexType
312 case both:
313 panic(fmt.Errorf("must be either zip or image"))
314 default:
315 panic(fmt.Errorf("unkonwn APEX type %d", a))
316 }
317}
318
Jiyong Park8fd61922018-11-08 02:50:25 +0900319func (class apexFileClass) NameInMake() string {
320 switch class {
321 case etc:
322 return "ETC"
323 case nativeSharedLib:
324 return "SHARED_LIBRARIES"
325 case nativeExecutable:
326 return "EXECUTABLES"
327 case javaSharedLib:
328 return "JAVA_LIBRARIES"
329 default:
330 panic(fmt.Errorf("unkonwn class %d", class))
331 }
332}
333
334type apexFile struct {
335 builtFile android.Path
336 moduleName string
337 archType android.ArchType
338 installDir string
339 class apexFileClass
340}
341
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900342type apexBundle struct {
343 android.ModuleBase
344 android.DefaultableModuleBase
345
346 properties apexBundleProperties
347
Alex Light5098a612018-11-29 17:12:15 -0800348 apexTypes apexPackaging
349
Colin Crossa4925902018-11-16 11:36:28 -0800350 bundleModuleFile android.WritablePath
Alex Light5098a612018-11-29 17:12:15 -0800351 outputFiles map[apexPackaging]android.WritablePath
Colin Crossa4925902018-11-16 11:36:28 -0800352 installDir android.OutputPath
Jiyong Park8fd61922018-11-08 02:50:25 +0900353
354 // list of files to be included in this apex
355 filesInfo []apexFile
356
357 flattened bool
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900358}
359
Jiyong Park397e55e2018-10-24 21:09:55 +0900360func addDependenciesForNativeModules(ctx android.BottomUpMutatorContext,
361 native_shared_libs []string, binaries []string, arch string) {
362 // Use *FarVariation* to be able to depend on modules having
363 // conflicting variations with this module. This is required since
364 // arch variant of an APEX bundle is 'common' but it is 'arm' or 'arm64'
365 // for native shared libs.
366 ctx.AddFarVariationDependencies([]blueprint.Variation{
367 {Mutator: "arch", Variation: arch},
368 {Mutator: "image", Variation: "core"},
369 {Mutator: "link", Variation: "shared"},
370 }, sharedLibTag, native_shared_libs...)
371
372 ctx.AddFarVariationDependencies([]blueprint.Variation{
373 {Mutator: "arch", Variation: arch},
374 {Mutator: "image", Variation: "core"},
375 }, executableTag, binaries...)
376}
377
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900378func (a *apexBundle) DepsMutator(ctx android.BottomUpMutatorContext) {
Jiyong Park397e55e2018-10-24 21:09:55 +0900379 targets := ctx.MultiTargets()
380 has32BitTarget := false
381 for _, target := range targets {
382 if target.Arch.ArchType.Multilib == "lib32" {
383 has32BitTarget = true
384 }
385 }
386 for i, target := range targets {
387 // When multilib.* is omitted for native_shared_libs, it implies
388 // multilib.both.
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900389 ctx.AddFarVariationDependencies([]blueprint.Variation{
Jiyong Park397e55e2018-10-24 21:09:55 +0900390 {Mutator: "arch", Variation: target.String()},
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900391 {Mutator: "image", Variation: "core"},
392 {Mutator: "link", Variation: "shared"},
393 }, sharedLibTag, a.properties.Native_shared_libs...)
394
Jiyong Park397e55e2018-10-24 21:09:55 +0900395 // Add native modules targetting both ABIs
396 addDependenciesForNativeModules(ctx,
397 a.properties.Multilib.Both.Native_shared_libs,
398 a.properties.Multilib.Both.Binaries, target.String())
399
400 if i == 0 {
401 // When multilib.* is omitted for binaries, it implies
402 // multilib.first.
403 ctx.AddFarVariationDependencies([]blueprint.Variation{
404 {Mutator: "arch", Variation: target.String()},
405 {Mutator: "image", Variation: "core"},
406 }, executableTag, a.properties.Binaries...)
407
408 // Add native modules targetting the first ABI
409 addDependenciesForNativeModules(ctx,
410 a.properties.Multilib.First.Native_shared_libs,
411 a.properties.Multilib.First.Binaries, target.String())
412 }
413
414 switch target.Arch.ArchType.Multilib {
415 case "lib32":
416 // Add native modules targetting 32-bit ABI
417 addDependenciesForNativeModules(ctx,
418 a.properties.Multilib.Lib32.Native_shared_libs,
419 a.properties.Multilib.Lib32.Binaries, target.String())
420
421 addDependenciesForNativeModules(ctx,
422 a.properties.Multilib.Prefer32.Native_shared_libs,
423 a.properties.Multilib.Prefer32.Binaries, target.String())
424 case "lib64":
425 // Add native modules targetting 64-bit ABI
426 addDependenciesForNativeModules(ctx,
427 a.properties.Multilib.Lib64.Native_shared_libs,
428 a.properties.Multilib.Lib64.Binaries, target.String())
429
430 if !has32BitTarget {
431 addDependenciesForNativeModules(ctx,
432 a.properties.Multilib.Prefer32.Native_shared_libs,
433 a.properties.Multilib.Prefer32.Binaries, target.String())
434 }
435 }
436
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900437 }
438
Jiyong Parkff1458f2018-10-12 21:49:38 +0900439 ctx.AddFarVariationDependencies([]blueprint.Variation{
440 {Mutator: "arch", Variation: "android_common"},
441 }, javaLibTag, a.properties.Java_libs...)
442
443 ctx.AddFarVariationDependencies([]blueprint.Variation{
444 {Mutator: "arch", Variation: "android_common"},
445 }, prebuiltTag, a.properties.Prebuilts...)
446
447 if String(a.properties.Key) == "" {
448 ctx.ModuleErrorf("key is missing")
449 return
450 }
451 ctx.AddDependency(ctx.Module(), keyTag, String(a.properties.Key))
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900452
453 cert := android.SrcIsModule(String(a.properties.Certificate))
454 if cert != "" {
455 ctx.AddDependency(ctx.Module(), certificateTag, cert)
456 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900457}
458
459func getCopyManifestForNativeLibrary(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
460 // Decide the APEX-local directory by the multilib of the library
461 // In the future, we may query this to the module.
462 switch cc.Arch().ArchType.Multilib {
463 case "lib32":
464 dirInApex = "lib"
465 case "lib64":
466 dirInApex = "lib64"
467 }
468 if !cc.Arch().Native {
469 dirInApex = filepath.Join(dirInApex, cc.Arch().ArchType.String())
470 }
471
472 fileToCopy = cc.OutputFile().Path()
473 return
474}
475
476func getCopyManifestForExecutable(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
477 dirInApex = "bin"
478 fileToCopy = cc.OutputFile().Path()
479 return
480}
481
482func getCopyManifestForJavaLibrary(java *java.Library) (fileToCopy android.Path, dirInApex string) {
483 dirInApex = "javalib"
Jiyong Park8fd61922018-11-08 02:50:25 +0900484 fileToCopy = java.DexJarFile()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900485 return
486}
487
488func getCopyManifestForPrebuiltEtc(prebuilt *android.PrebuiltEtc) (fileToCopy android.Path, dirInApex string) {
489 dirInApex = filepath.Join("etc", prebuilt.SubDir())
490 fileToCopy = prebuilt.OutputFile()
491 return
492}
493
494func (a *apexBundle) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Park8fd61922018-11-08 02:50:25 +0900495 filesInfo := []apexFile{}
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900496
Jiyong Parkff1458f2018-10-12 21:49:38 +0900497 var keyFile android.Path
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900498 var certificate java.Certificate
Jiyong Parkff1458f2018-10-12 21:49:38 +0900499
Alex Light5098a612018-11-29 17:12:15 -0800500 if a.properties.Payload_type == nil || *a.properties.Payload_type == "image" {
501 a.apexTypes = imageApex
502 } else if *a.properties.Payload_type == "zip" {
503 a.apexTypes = zipApex
504 } else if *a.properties.Payload_type == "both" {
505 a.apexTypes = both
506 } else {
507 ctx.PropertyErrorf("type", "%q is not one of \"image\", \"zip\", or \"both\".", *a.properties.Payload_type)
508 return
509 }
510
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900511 ctx.WalkDeps(func(child, parent android.Module) bool {
512 if _, ok := parent.(*apexBundle); ok {
513 // direct dependencies
514 depTag := ctx.OtherModuleDependencyTag(child)
Jiyong Parkff1458f2018-10-12 21:49:38 +0900515 depName := ctx.OtherModuleName(child)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900516 switch depTag {
517 case sharedLibTag:
518 if cc, ok := child.(*cc.Module); ok {
519 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900520 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeSharedLib})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900521 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900522 } else {
523 ctx.PropertyErrorf("native_shared_libs", "%q is not a cc_library or cc_library_shared module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900524 }
525 case executableTag:
526 if cc, ok := child.(*cc.Module); ok {
527 fileToCopy, dirInApex := getCopyManifestForExecutable(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900528 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeExecutable})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900529 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900530 } else {
531 ctx.PropertyErrorf("binaries", "%q is not a cc_binary module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900532 }
533 case javaLibTag:
534 if java, ok := child.(*java.Library); ok {
535 fileToCopy, dirInApex := getCopyManifestForJavaLibrary(java)
Jiyong Park8fd61922018-11-08 02:50:25 +0900536 if fileToCopy == nil {
537 ctx.PropertyErrorf("java_libs", "%q is not configured to be compiled into dex", depName)
538 } else {
539 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, java.Arch().ArchType, dirInApex, javaSharedLib})
540 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900541 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900542 } else {
543 ctx.PropertyErrorf("java_libs", "%q is not a java_library module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900544 }
545 case prebuiltTag:
546 if prebuilt, ok := child.(*android.PrebuiltEtc); ok {
547 fileToCopy, dirInApex := getCopyManifestForPrebuiltEtc(prebuilt)
Jiyong Park8fd61922018-11-08 02:50:25 +0900548 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, prebuilt.Arch().ArchType, dirInApex, etc})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900549 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900550 } else {
551 ctx.PropertyErrorf("prebuilts", "%q is not a prebuilt_etc module", depName)
552 }
553 case keyTag:
554 if key, ok := child.(*apexKey); ok {
555 keyFile = key.private_key_file
556 return false
557 } else {
558 ctx.PropertyErrorf("key", "%q is not an apex_key module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900559 }
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900560 case certificateTag:
561 if dep, ok := child.(*java.AndroidAppCertificate); ok {
562 certificate = dep.Certificate
563 return false
564 } else {
565 ctx.ModuleErrorf("certificate dependency %q must be an android_app_certificate module", depName)
566 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900567 }
568 } else {
569 // indirect dependencies
570 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() && am.IsInstallableToApex() {
571 if cc, ok := child.(*cc.Module); ok {
Jiyong Park25fc6a92018-11-18 18:02:45 +0900572 if cc.IsStubs() || cc.HasStubsVariants() {
573 return false
574 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900575 depName := ctx.OtherModuleName(child)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900576 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900577 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeSharedLib})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900578 return true
579 }
580 }
581 }
582 return false
583 })
584
Jiyong Parkfa0a3732018-11-09 05:52:26 +0900585 if keyFile == nil {
586 ctx.PropertyErrorf("key", "private_key for %q could not be found", String(a.properties.Key))
587 return
588 }
589
Jiyong Park8fd61922018-11-08 02:50:25 +0900590 // remove duplicates in filesInfo
591 removeDup := func(filesInfo []apexFile) []apexFile {
592 encountered := make(map[android.Path]bool)
593 result := []apexFile{}
594 for _, f := range filesInfo {
595 if !encountered[f.builtFile] {
596 encountered[f.builtFile] = true
597 result = append(result, f)
598 }
599 }
600 return result
601 }
602 filesInfo = removeDup(filesInfo)
603
604 // to have consistent build rules
605 sort.Slice(filesInfo, func(i, j int) bool {
606 return filesInfo[i].builtFile.String() < filesInfo[j].builtFile.String()
607 })
608
609 // prepend the name of this APEX to the module names. These names will be the names of
610 // modules that will be defined if the APEX is flattened.
611 for i := range filesInfo {
612 filesInfo[i].moduleName = ctx.ModuleName() + "." + filesInfo[i].moduleName
613 }
614
Colin Crossa4925902018-11-16 11:36:28 -0800615 a.flattened = ctx.Config().FlattenApex() && !ctx.Config().UnbundledBuild()
Jiyong Park8fd61922018-11-08 02:50:25 +0900616 a.installDir = android.PathForModuleInstall(ctx, "apex")
617 a.filesInfo = filesInfo
Alex Light5098a612018-11-29 17:12:15 -0800618
619 if a.apexTypes.zip() {
620 a.buildUnflattenedApex(ctx, keyFile, certificate, zipApex)
621 }
622 if a.apexTypes.image() {
623 if ctx.Config().FlattenApex() {
624 a.buildFlattenedApex(ctx)
625 } else {
626 a.buildUnflattenedApex(ctx, keyFile, certificate, imageApex)
627 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900628 }
629}
630
Alex Light5098a612018-11-29 17:12:15 -0800631func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext, keyFile android.Path, certificate java.Certificate, apexType apexPackaging) {
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900632 cert := String(a.properties.Certificate)
633 if cert != "" && android.SrcIsModule(cert) == "" {
634 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
635 certificate = java.Certificate{
636 defaultDir.Join(ctx, cert+".x509.pem"),
637 defaultDir.Join(ctx, cert+".pk8"),
638 }
639 } else if cert == "" {
640 pem, key := ctx.Config().DefaultAppCertificate(ctx)
641 certificate = java.Certificate{pem, key}
642 }
643
Dario Freni4abb1dc2018-11-20 18:04:58 +0000644 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900645
Alex Light5098a612018-11-29 17:12:15 -0800646 var abis []string
647 for _, target := range ctx.MultiTargets() {
648 if len(target.Arch.Abi) > 0 {
649 abis = append(abis, target.Arch.Abi[0])
650 }
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900651 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900652
Alex Light5098a612018-11-29 17:12:15 -0800653 abis = android.FirstUniqueStrings(abis)
654
655 suffix := apexType.suffix()
656 unsignedOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+suffix+".unsigned")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900657
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900658 filesToCopy := []android.Path{}
Jiyong Park8fd61922018-11-08 02:50:25 +0900659 for _, f := range a.filesInfo {
660 filesToCopy = append(filesToCopy, f.builtFile)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900661 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900662
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900663 copyCommands := []string{}
Jiyong Park8fd61922018-11-08 02:50:25 +0900664 for i, src := range filesToCopy {
665 dest := filepath.Join(a.filesInfo[i].installDir, src.Base())
Alex Light5098a612018-11-29 17:12:15 -0800666 dest_path := filepath.Join(android.PathForModuleOut(ctx, "image"+suffix).String(), dest)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900667 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(dest_path))
668 copyCommands = append(copyCommands, "cp "+src.String()+" "+dest_path)
669 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900670 implicitInputs := append(android.Paths(nil), filesToCopy...)
Alex Light5098a612018-11-29 17:12:15 -0800671 implicitInputs = append(implicitInputs, manifest)
672
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900673 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
674 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900675
Alex Light5098a612018-11-29 17:12:15 -0800676 if apexType.image() {
677 // files and dirs that will be created in APEX
678 var readOnlyPaths []string
679 var executablePaths []string // this also includes dirs
680 for _, f := range a.filesInfo {
681 pathInApex := filepath.Join(f.installDir, f.builtFile.Base())
682 if f.installDir == "bin" {
683 executablePaths = append(executablePaths, pathInApex)
684 } else {
685 readOnlyPaths = append(readOnlyPaths, pathInApex)
686 }
Jiyong Park7c2ee712018-12-07 00:42:25 +0900687 dir := f.installDir
688 for !android.InList(dir, executablePaths) && dir != "" {
689 executablePaths = append(executablePaths, dir)
690 dir, _ = filepath.Split(dir) // move up to the parent
691 if len(dir) > 0 {
692 // remove trailing slash
693 dir = dir[:len(dir)-1]
694 }
Alex Light5098a612018-11-29 17:12:15 -0800695 }
696 }
697 sort.Strings(readOnlyPaths)
698 sort.Strings(executablePaths)
699 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
700 ctx.Build(pctx, android.BuildParams{
701 Rule: generateFsConfig,
702 Output: cannedFsConfig,
703 Description: "generate fs config",
704 Args: map[string]string{
705 "ro_paths": strings.Join(readOnlyPaths, " "),
706 "exec_paths": strings.Join(executablePaths, " "),
707 },
708 })
709
710 fcName := proptools.StringDefault(a.properties.File_contexts, ctx.ModuleName())
711 fileContextsPath := "system/sepolicy/apex/" + fcName + "-file_contexts"
712 fileContextsOptionalPath := android.ExistentPathForSource(ctx, fileContextsPath)
713 if !fileContextsOptionalPath.Valid() {
714 ctx.ModuleErrorf("Cannot find file_contexts file: %q", fileContextsPath)
715 return
716 }
717 fileContexts := fileContextsOptionalPath.Path()
718
719 // Additional implicit inputs.
720 implicitInputs = append(implicitInputs, cannedFsConfig, fileContexts, keyFile)
721
722 ctx.Build(pctx, android.BuildParams{
723 Rule: apexRule,
724 Implicits: implicitInputs,
725 Output: unsignedOutputFile,
726 Description: "apex (" + apexType.name() + ")",
727 Args: map[string]string{
728 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
729 "image_dir": android.PathForModuleOut(ctx, "image"+suffix).String(),
730 "copy_commands": strings.Join(copyCommands, " && "),
731 "manifest": manifest.String(),
732 "file_contexts": fileContexts.String(),
733 "canned_fs_config": cannedFsConfig.String(),
734 "key": keyFile.String(),
735 },
736 })
737
738 apexProtoFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".pb"+suffix)
739 bundleModuleFile := android.PathForModuleOut(ctx, ctx.ModuleName()+suffix+"-base.zip")
740 a.bundleModuleFile = bundleModuleFile
741
742 ctx.Build(pctx, android.BuildParams{
743 Rule: apexProtoConvertRule,
744 Input: unsignedOutputFile,
745 Output: apexProtoFile,
746 Description: "apex proto convert",
747 })
748
749 ctx.Build(pctx, android.BuildParams{
750 Rule: apexBundleRule,
751 Input: apexProtoFile,
752 Output: a.bundleModuleFile,
753 Description: "apex bundle module",
754 Args: map[string]string{
755 "abi": strings.Join(abis, "."),
756 },
757 })
758 } else {
759 ctx.Build(pctx, android.BuildParams{
760 Rule: zipApexRule,
761 Implicits: implicitInputs,
762 Output: unsignedOutputFile,
763 Description: "apex (" + apexType.name() + ")",
764 Args: map[string]string{
765 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
766 "image_dir": android.PathForModuleOut(ctx, "image"+suffix).String(),
767 "copy_commands": strings.Join(copyCommands, " && "),
768 "manifest": manifest.String(),
769 },
770 })
Colin Crossa4925902018-11-16 11:36:28 -0800771 }
Colin Crossa4925902018-11-16 11:36:28 -0800772
Alex Light5098a612018-11-29 17:12:15 -0800773 a.outputFiles[apexType] = android.PathForModuleOut(ctx, ctx.ModuleName()+suffix)
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900774 ctx.Build(pctx, android.BuildParams{
775 Rule: java.Signapk,
776 Description: "signapk",
Alex Light5098a612018-11-29 17:12:15 -0800777 Output: a.outputFiles[apexType],
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900778 Input: unsignedOutputFile,
779 Args: map[string]string{
780 "certificates": strings.Join([]string{certificate.Pem.String(), certificate.Key.String()}, " "),
Jiyong Parkbfe64a12018-11-22 02:51:54 +0900781 "flags": "-a 4096", //alignment
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900782 },
783 })
Alex Light5098a612018-11-29 17:12:15 -0800784
785 // Install to $OUT/soong/{target,host}/.../apex
786 ctx.InstallFile(android.PathForModuleInstall(ctx, "apex"), ctx.ModuleName()+suffix, a.outputFiles[apexType])
Jiyong Park8fd61922018-11-08 02:50:25 +0900787}
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900788
Jiyong Park8fd61922018-11-08 02:50:25 +0900789func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
Dario Freni4abb1dc2018-11-20 18:04:58 +0000790 // For flattened APEX, do nothing but make sure that apex_manifest.json file is also copied along
Jiyong Park8fd61922018-11-08 02:50:25 +0900791 // with other ordinary files.
Dario Freni4abb1dc2018-11-20 18:04:58 +0000792 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
793 a.filesInfo = append(a.filesInfo, apexFile{manifest, ctx.ModuleName() + ".apex_manifest.json", android.Common, ".", etc})
Jiyong Park8fd61922018-11-08 02:50:25 +0900794
795 for _, fi := range a.filesInfo {
Colin Crossa4925902018-11-16 11:36:28 -0800796 dir := filepath.Join("apex", ctx.ModuleName(), fi.installDir)
Jiyong Park8fd61922018-11-08 02:50:25 +0900797 ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.builtFile.Base(), fi.builtFile)
798 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900799}
800
801func (a *apexBundle) AndroidMk() android.AndroidMkData {
Alex Light5098a612018-11-29 17:12:15 -0800802 writers := []android.AndroidMkData{}
803 if a.apexTypes.image() {
804 writers = append(writers, a.androidMkForType(imageApex))
805 }
806 if a.apexTypes.zip() {
807 writers = append(writers, a.androidMkForType(zipApex))
808 }
809 return android.AndroidMkData{
810 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
811 for _, data := range writers {
812 data.Custom(w, name, prefix, moduleDir, data)
813 }
814 }}
815}
816
817func (a *apexBundle) androidMkForType(apexType apexPackaging) android.AndroidMkData {
818 // Only image APEXes can be flattened.
819 if a.flattened && apexType.image() {
Jiyong Park8fd61922018-11-08 02:50:25 +0900820 return android.AndroidMkData{
821 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
822 moduleNames := []string{}
823 for _, fi := range a.filesInfo {
824 if !android.InList(fi.moduleName, moduleNames) {
825 moduleNames = append(moduleNames, fi.moduleName)
826 }
827 }
828 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
829 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
830 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
831 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", strings.Join(moduleNames, " "))
832 fmt.Fprintln(w, "include $(BUILD_PHONY_PACKAGE)")
833
834 for _, fi := range a.filesInfo {
835 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
836 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
837 fmt.Fprintln(w, "LOCAL_MODULE :=", fi.moduleName)
838 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString(), name, fi.installDir))
839 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", fi.builtFile.Base())
840 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", fi.builtFile.String())
841 fmt.Fprintln(w, "LOCAL_MODULE_CLASS :=", fi.class.NameInMake())
842 archStr := fi.archType.String()
843 if archStr != "common" {
844 fmt.Fprintln(w, "LOCAL_MODULE_TARGET_ARCH :=", archStr)
845 }
846 if fi.class == javaSharedLib {
847 fmt.Fprintln(w, "LOCAL_SOONG_DEX_JAR :=", fi.builtFile.String())
848 fmt.Fprintln(w, "LOCAL_DEX_PREOPT := false")
849 fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_java_prebuilt.mk")
850 } else {
851 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
852 }
853 }
854 }}
855 } else {
856 return android.AndroidMkData{
857 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
Alex Light5098a612018-11-29 17:12:15 -0800858 // zip-apex is the less common type so have the name refer to the image-apex
859 // only and use {name}.zip if you want the zip-apex
860 if apexType == zipApex && a.apexTypes == both {
861 name = name + ".zip"
862 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900863 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
864 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
865 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
866 fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC") // do we need a new class?
Alex Light5098a612018-11-29 17:12:15 -0800867 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", a.outputFiles[apexType].String())
Jiyong Park8fd61922018-11-08 02:50:25 +0900868 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString()))
Alex Light5098a612018-11-29 17:12:15 -0800869 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", name+apexType.suffix())
Jiyong Park8fd61922018-11-08 02:50:25 +0900870 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", String(a.properties.Key))
871 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
Colin Crossa4925902018-11-16 11:36:28 -0800872
Alex Light5098a612018-11-29 17:12:15 -0800873 if apexType == imageApex {
874 fmt.Fprintln(w, "ALL_MODULES.$(LOCAL_MODULE).BUNDLE :=", a.bundleModuleFile.String())
875 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900876 }}
877 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900878}
879
Alex Lightee250722018-12-06 14:00:02 -0800880func ApexBundleFactory() android.Module {
Alex Light5098a612018-11-29 17:12:15 -0800881 module := &apexBundle{
882 outputFiles: map[apexPackaging]android.WritablePath{},
883 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900884 module.AddProperties(&module.properties)
Alex Light5098a612018-11-29 17:12:15 -0800885 module.Prefer32(func(ctx android.BaseModuleContext, base *android.ModuleBase, class android.OsClass) bool {
Jiyong Park397e55e2018-10-24 21:09:55 +0900886 return class == android.Device && ctx.Config().DevicePrefer32BitExecutables()
887 })
Alex Light5098a612018-11-29 17:12:15 -0800888 android.InitAndroidMultiTargetsArchModule(module, android.HostAndDeviceSupported, android.MultilibCommon)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900889 android.InitDefaultableModule(module)
890 return module
891}