blob: e26849917638a12594474ca95909435758e0ff5c [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"},
Jiyong Park28d395a2018-12-07 22:42:47 +0900370 {Mutator: "version", Variation: ""}, // "" is the non-stub variant
Jiyong Park397e55e2018-10-24 21:09:55 +0900371 }, sharedLibTag, native_shared_libs...)
372
373 ctx.AddFarVariationDependencies([]blueprint.Variation{
374 {Mutator: "arch", Variation: arch},
375 {Mutator: "image", Variation: "core"},
376 }, executableTag, binaries...)
377}
378
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900379func (a *apexBundle) DepsMutator(ctx android.BottomUpMutatorContext) {
Jiyong Park397e55e2018-10-24 21:09:55 +0900380 targets := ctx.MultiTargets()
381 has32BitTarget := false
382 for _, target := range targets {
383 if target.Arch.ArchType.Multilib == "lib32" {
384 has32BitTarget = true
385 }
386 }
387 for i, target := range targets {
388 // When multilib.* is omitted for native_shared_libs, it implies
389 // multilib.both.
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900390 ctx.AddFarVariationDependencies([]blueprint.Variation{
Jiyong Park397e55e2018-10-24 21:09:55 +0900391 {Mutator: "arch", Variation: target.String()},
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900392 {Mutator: "image", Variation: "core"},
393 {Mutator: "link", Variation: "shared"},
394 }, sharedLibTag, a.properties.Native_shared_libs...)
395
Jiyong Park397e55e2018-10-24 21:09:55 +0900396 // Add native modules targetting both ABIs
397 addDependenciesForNativeModules(ctx,
398 a.properties.Multilib.Both.Native_shared_libs,
399 a.properties.Multilib.Both.Binaries, target.String())
400
401 if i == 0 {
402 // When multilib.* is omitted for binaries, it implies
403 // multilib.first.
404 ctx.AddFarVariationDependencies([]blueprint.Variation{
405 {Mutator: "arch", Variation: target.String()},
406 {Mutator: "image", Variation: "core"},
407 }, executableTag, a.properties.Binaries...)
408
409 // Add native modules targetting the first ABI
410 addDependenciesForNativeModules(ctx,
411 a.properties.Multilib.First.Native_shared_libs,
412 a.properties.Multilib.First.Binaries, target.String())
413 }
414
415 switch target.Arch.ArchType.Multilib {
416 case "lib32":
417 // Add native modules targetting 32-bit ABI
418 addDependenciesForNativeModules(ctx,
419 a.properties.Multilib.Lib32.Native_shared_libs,
420 a.properties.Multilib.Lib32.Binaries, target.String())
421
422 addDependenciesForNativeModules(ctx,
423 a.properties.Multilib.Prefer32.Native_shared_libs,
424 a.properties.Multilib.Prefer32.Binaries, target.String())
425 case "lib64":
426 // Add native modules targetting 64-bit ABI
427 addDependenciesForNativeModules(ctx,
428 a.properties.Multilib.Lib64.Native_shared_libs,
429 a.properties.Multilib.Lib64.Binaries, target.String())
430
431 if !has32BitTarget {
432 addDependenciesForNativeModules(ctx,
433 a.properties.Multilib.Prefer32.Native_shared_libs,
434 a.properties.Multilib.Prefer32.Binaries, target.String())
435 }
436 }
437
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900438 }
439
Jiyong Parkff1458f2018-10-12 21:49:38 +0900440 ctx.AddFarVariationDependencies([]blueprint.Variation{
441 {Mutator: "arch", Variation: "android_common"},
442 }, javaLibTag, a.properties.Java_libs...)
443
444 ctx.AddFarVariationDependencies([]blueprint.Variation{
445 {Mutator: "arch", Variation: "android_common"},
446 }, prebuiltTag, a.properties.Prebuilts...)
447
448 if String(a.properties.Key) == "" {
449 ctx.ModuleErrorf("key is missing")
450 return
451 }
452 ctx.AddDependency(ctx.Module(), keyTag, String(a.properties.Key))
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900453
454 cert := android.SrcIsModule(String(a.properties.Certificate))
455 if cert != "" {
456 ctx.AddDependency(ctx.Module(), certificateTag, cert)
457 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900458}
459
460func getCopyManifestForNativeLibrary(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
461 // Decide the APEX-local directory by the multilib of the library
462 // In the future, we may query this to the module.
463 switch cc.Arch().ArchType.Multilib {
464 case "lib32":
465 dirInApex = "lib"
466 case "lib64":
467 dirInApex = "lib64"
468 }
469 if !cc.Arch().Native {
470 dirInApex = filepath.Join(dirInApex, cc.Arch().ArchType.String())
471 }
472
473 fileToCopy = cc.OutputFile().Path()
474 return
475}
476
477func getCopyManifestForExecutable(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
478 dirInApex = "bin"
479 fileToCopy = cc.OutputFile().Path()
480 return
481}
482
483func getCopyManifestForJavaLibrary(java *java.Library) (fileToCopy android.Path, dirInApex string) {
484 dirInApex = "javalib"
Jiyong Park8fd61922018-11-08 02:50:25 +0900485 fileToCopy = java.DexJarFile()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900486 return
487}
488
489func getCopyManifestForPrebuiltEtc(prebuilt *android.PrebuiltEtc) (fileToCopy android.Path, dirInApex string) {
490 dirInApex = filepath.Join("etc", prebuilt.SubDir())
491 fileToCopy = prebuilt.OutputFile()
492 return
493}
494
495func (a *apexBundle) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Park8fd61922018-11-08 02:50:25 +0900496 filesInfo := []apexFile{}
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900497
Jiyong Parkff1458f2018-10-12 21:49:38 +0900498 var keyFile android.Path
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900499 var certificate java.Certificate
Jiyong Parkff1458f2018-10-12 21:49:38 +0900500
Alex Light5098a612018-11-29 17:12:15 -0800501 if a.properties.Payload_type == nil || *a.properties.Payload_type == "image" {
502 a.apexTypes = imageApex
503 } else if *a.properties.Payload_type == "zip" {
504 a.apexTypes = zipApex
505 } else if *a.properties.Payload_type == "both" {
506 a.apexTypes = both
507 } else {
508 ctx.PropertyErrorf("type", "%q is not one of \"image\", \"zip\", or \"both\".", *a.properties.Payload_type)
509 return
510 }
511
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900512 ctx.WalkDeps(func(child, parent android.Module) bool {
513 if _, ok := parent.(*apexBundle); ok {
514 // direct dependencies
515 depTag := ctx.OtherModuleDependencyTag(child)
Jiyong Parkff1458f2018-10-12 21:49:38 +0900516 depName := ctx.OtherModuleName(child)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900517 switch depTag {
518 case sharedLibTag:
519 if cc, ok := child.(*cc.Module); ok {
520 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900521 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeSharedLib})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900522 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900523 } else {
524 ctx.PropertyErrorf("native_shared_libs", "%q is not a cc_library or cc_library_shared module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900525 }
526 case executableTag:
527 if cc, ok := child.(*cc.Module); ok {
528 fileToCopy, dirInApex := getCopyManifestForExecutable(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900529 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeExecutable})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900530 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900531 } else {
532 ctx.PropertyErrorf("binaries", "%q is not a cc_binary module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900533 }
534 case javaLibTag:
535 if java, ok := child.(*java.Library); ok {
536 fileToCopy, dirInApex := getCopyManifestForJavaLibrary(java)
Jiyong Park8fd61922018-11-08 02:50:25 +0900537 if fileToCopy == nil {
538 ctx.PropertyErrorf("java_libs", "%q is not configured to be compiled into dex", depName)
539 } else {
540 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, java.Arch().ArchType, dirInApex, javaSharedLib})
541 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900542 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900543 } else {
544 ctx.PropertyErrorf("java_libs", "%q is not a java_library module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900545 }
546 case prebuiltTag:
547 if prebuilt, ok := child.(*android.PrebuiltEtc); ok {
548 fileToCopy, dirInApex := getCopyManifestForPrebuiltEtc(prebuilt)
Jiyong Park8fd61922018-11-08 02:50:25 +0900549 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, prebuilt.Arch().ArchType, dirInApex, etc})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900550 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900551 } else {
552 ctx.PropertyErrorf("prebuilts", "%q is not a prebuilt_etc module", depName)
553 }
554 case keyTag:
555 if key, ok := child.(*apexKey); ok {
556 keyFile = key.private_key_file
557 return false
558 } else {
559 ctx.PropertyErrorf("key", "%q is not an apex_key module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900560 }
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900561 case certificateTag:
562 if dep, ok := child.(*java.AndroidAppCertificate); ok {
563 certificate = dep.Certificate
564 return false
565 } else {
566 ctx.ModuleErrorf("certificate dependency %q must be an android_app_certificate module", depName)
567 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900568 }
569 } else {
570 // indirect dependencies
571 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() && am.IsInstallableToApex() {
572 if cc, ok := child.(*cc.Module); ok {
Jiyong Park25fc6a92018-11-18 18:02:45 +0900573 if cc.IsStubs() || cc.HasStubsVariants() {
574 return false
575 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900576 depName := ctx.OtherModuleName(child)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900577 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900578 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeSharedLib})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900579 return true
580 }
581 }
582 }
583 return false
584 })
585
Jiyong Parkfa0a3732018-11-09 05:52:26 +0900586 if keyFile == nil {
587 ctx.PropertyErrorf("key", "private_key for %q could not be found", String(a.properties.Key))
588 return
589 }
590
Jiyong Park8fd61922018-11-08 02:50:25 +0900591 // remove duplicates in filesInfo
592 removeDup := func(filesInfo []apexFile) []apexFile {
593 encountered := make(map[android.Path]bool)
594 result := []apexFile{}
595 for _, f := range filesInfo {
596 if !encountered[f.builtFile] {
597 encountered[f.builtFile] = true
598 result = append(result, f)
599 }
600 }
601 return result
602 }
603 filesInfo = removeDup(filesInfo)
604
605 // to have consistent build rules
606 sort.Slice(filesInfo, func(i, j int) bool {
607 return filesInfo[i].builtFile.String() < filesInfo[j].builtFile.String()
608 })
609
610 // prepend the name of this APEX to the module names. These names will be the names of
611 // modules that will be defined if the APEX is flattened.
612 for i := range filesInfo {
613 filesInfo[i].moduleName = ctx.ModuleName() + "." + filesInfo[i].moduleName
614 }
615
Colin Crossa4925902018-11-16 11:36:28 -0800616 a.flattened = ctx.Config().FlattenApex() && !ctx.Config().UnbundledBuild()
Jiyong Park8fd61922018-11-08 02:50:25 +0900617 a.installDir = android.PathForModuleInstall(ctx, "apex")
618 a.filesInfo = filesInfo
Alex Light5098a612018-11-29 17:12:15 -0800619
620 if a.apexTypes.zip() {
621 a.buildUnflattenedApex(ctx, keyFile, certificate, zipApex)
622 }
623 if a.apexTypes.image() {
624 if ctx.Config().FlattenApex() {
625 a.buildFlattenedApex(ctx)
626 } else {
627 a.buildUnflattenedApex(ctx, keyFile, certificate, imageApex)
628 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900629 }
630}
631
Alex Light5098a612018-11-29 17:12:15 -0800632func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext, keyFile android.Path, certificate java.Certificate, apexType apexPackaging) {
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900633 cert := String(a.properties.Certificate)
634 if cert != "" && android.SrcIsModule(cert) == "" {
635 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
636 certificate = java.Certificate{
637 defaultDir.Join(ctx, cert+".x509.pem"),
638 defaultDir.Join(ctx, cert+".pk8"),
639 }
640 } else if cert == "" {
641 pem, key := ctx.Config().DefaultAppCertificate(ctx)
642 certificate = java.Certificate{pem, key}
643 }
644
Dario Freni4abb1dc2018-11-20 18:04:58 +0000645 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900646
Alex Light5098a612018-11-29 17:12:15 -0800647 var abis []string
648 for _, target := range ctx.MultiTargets() {
649 if len(target.Arch.Abi) > 0 {
650 abis = append(abis, target.Arch.Abi[0])
651 }
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900652 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900653
Alex Light5098a612018-11-29 17:12:15 -0800654 abis = android.FirstUniqueStrings(abis)
655
656 suffix := apexType.suffix()
657 unsignedOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+suffix+".unsigned")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900658
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900659 filesToCopy := []android.Path{}
Jiyong Park8fd61922018-11-08 02:50:25 +0900660 for _, f := range a.filesInfo {
661 filesToCopy = append(filesToCopy, f.builtFile)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900662 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900663
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900664 copyCommands := []string{}
Jiyong Park8fd61922018-11-08 02:50:25 +0900665 for i, src := range filesToCopy {
666 dest := filepath.Join(a.filesInfo[i].installDir, src.Base())
Alex Light5098a612018-11-29 17:12:15 -0800667 dest_path := filepath.Join(android.PathForModuleOut(ctx, "image"+suffix).String(), dest)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900668 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(dest_path))
669 copyCommands = append(copyCommands, "cp "+src.String()+" "+dest_path)
670 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900671 implicitInputs := append(android.Paths(nil), filesToCopy...)
Alex Light5098a612018-11-29 17:12:15 -0800672 implicitInputs = append(implicitInputs, manifest)
673
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900674 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
675 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900676
Alex Light5098a612018-11-29 17:12:15 -0800677 if apexType.image() {
678 // files and dirs that will be created in APEX
679 var readOnlyPaths []string
680 var executablePaths []string // this also includes dirs
681 for _, f := range a.filesInfo {
682 pathInApex := filepath.Join(f.installDir, f.builtFile.Base())
683 if f.installDir == "bin" {
684 executablePaths = append(executablePaths, pathInApex)
685 } else {
686 readOnlyPaths = append(readOnlyPaths, pathInApex)
687 }
Jiyong Park7c2ee712018-12-07 00:42:25 +0900688 dir := f.installDir
689 for !android.InList(dir, executablePaths) && dir != "" {
690 executablePaths = append(executablePaths, dir)
691 dir, _ = filepath.Split(dir) // move up to the parent
692 if len(dir) > 0 {
693 // remove trailing slash
694 dir = dir[:len(dir)-1]
695 }
Alex Light5098a612018-11-29 17:12:15 -0800696 }
697 }
698 sort.Strings(readOnlyPaths)
699 sort.Strings(executablePaths)
700 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
701 ctx.Build(pctx, android.BuildParams{
702 Rule: generateFsConfig,
703 Output: cannedFsConfig,
704 Description: "generate fs config",
705 Args: map[string]string{
706 "ro_paths": strings.Join(readOnlyPaths, " "),
707 "exec_paths": strings.Join(executablePaths, " "),
708 },
709 })
710
711 fcName := proptools.StringDefault(a.properties.File_contexts, ctx.ModuleName())
712 fileContextsPath := "system/sepolicy/apex/" + fcName + "-file_contexts"
713 fileContextsOptionalPath := android.ExistentPathForSource(ctx, fileContextsPath)
714 if !fileContextsOptionalPath.Valid() {
715 ctx.ModuleErrorf("Cannot find file_contexts file: %q", fileContextsPath)
716 return
717 }
718 fileContexts := fileContextsOptionalPath.Path()
719
720 // Additional implicit inputs.
721 implicitInputs = append(implicitInputs, cannedFsConfig, fileContexts, keyFile)
722
723 ctx.Build(pctx, android.BuildParams{
724 Rule: apexRule,
725 Implicits: implicitInputs,
726 Output: unsignedOutputFile,
727 Description: "apex (" + apexType.name() + ")",
728 Args: map[string]string{
729 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
730 "image_dir": android.PathForModuleOut(ctx, "image"+suffix).String(),
731 "copy_commands": strings.Join(copyCommands, " && "),
732 "manifest": manifest.String(),
733 "file_contexts": fileContexts.String(),
734 "canned_fs_config": cannedFsConfig.String(),
735 "key": keyFile.String(),
736 },
737 })
738
739 apexProtoFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".pb"+suffix)
740 bundleModuleFile := android.PathForModuleOut(ctx, ctx.ModuleName()+suffix+"-base.zip")
741 a.bundleModuleFile = bundleModuleFile
742
743 ctx.Build(pctx, android.BuildParams{
744 Rule: apexProtoConvertRule,
745 Input: unsignedOutputFile,
746 Output: apexProtoFile,
747 Description: "apex proto convert",
748 })
749
750 ctx.Build(pctx, android.BuildParams{
751 Rule: apexBundleRule,
752 Input: apexProtoFile,
753 Output: a.bundleModuleFile,
754 Description: "apex bundle module",
755 Args: map[string]string{
756 "abi": strings.Join(abis, "."),
757 },
758 })
759 } else {
760 ctx.Build(pctx, android.BuildParams{
761 Rule: zipApexRule,
762 Implicits: implicitInputs,
763 Output: unsignedOutputFile,
764 Description: "apex (" + apexType.name() + ")",
765 Args: map[string]string{
766 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
767 "image_dir": android.PathForModuleOut(ctx, "image"+suffix).String(),
768 "copy_commands": strings.Join(copyCommands, " && "),
769 "manifest": manifest.String(),
770 },
771 })
Colin Crossa4925902018-11-16 11:36:28 -0800772 }
Colin Crossa4925902018-11-16 11:36:28 -0800773
Alex Light5098a612018-11-29 17:12:15 -0800774 a.outputFiles[apexType] = android.PathForModuleOut(ctx, ctx.ModuleName()+suffix)
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900775 ctx.Build(pctx, android.BuildParams{
776 Rule: java.Signapk,
777 Description: "signapk",
Alex Light5098a612018-11-29 17:12:15 -0800778 Output: a.outputFiles[apexType],
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900779 Input: unsignedOutputFile,
780 Args: map[string]string{
781 "certificates": strings.Join([]string{certificate.Pem.String(), certificate.Key.String()}, " "),
Jiyong Parkbfe64a12018-11-22 02:51:54 +0900782 "flags": "-a 4096", //alignment
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900783 },
784 })
Alex Light5098a612018-11-29 17:12:15 -0800785
786 // Install to $OUT/soong/{target,host}/.../apex
787 ctx.InstallFile(android.PathForModuleInstall(ctx, "apex"), ctx.ModuleName()+suffix, a.outputFiles[apexType])
Jiyong Park8fd61922018-11-08 02:50:25 +0900788}
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900789
Jiyong Park8fd61922018-11-08 02:50:25 +0900790func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
Dario Freni4abb1dc2018-11-20 18:04:58 +0000791 // For flattened APEX, do nothing but make sure that apex_manifest.json file is also copied along
Jiyong Park8fd61922018-11-08 02:50:25 +0900792 // with other ordinary files.
Dario Freni4abb1dc2018-11-20 18:04:58 +0000793 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
794 a.filesInfo = append(a.filesInfo, apexFile{manifest, ctx.ModuleName() + ".apex_manifest.json", android.Common, ".", etc})
Jiyong Park8fd61922018-11-08 02:50:25 +0900795
796 for _, fi := range a.filesInfo {
Colin Crossa4925902018-11-16 11:36:28 -0800797 dir := filepath.Join("apex", ctx.ModuleName(), fi.installDir)
Jiyong Park8fd61922018-11-08 02:50:25 +0900798 ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.builtFile.Base(), fi.builtFile)
799 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900800}
801
802func (a *apexBundle) AndroidMk() android.AndroidMkData {
Alex Light5098a612018-11-29 17:12:15 -0800803 writers := []android.AndroidMkData{}
804 if a.apexTypes.image() {
805 writers = append(writers, a.androidMkForType(imageApex))
806 }
807 if a.apexTypes.zip() {
808 writers = append(writers, a.androidMkForType(zipApex))
809 }
810 return android.AndroidMkData{
811 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
812 for _, data := range writers {
813 data.Custom(w, name, prefix, moduleDir, data)
814 }
815 }}
816}
817
818func (a *apexBundle) androidMkForType(apexType apexPackaging) android.AndroidMkData {
819 // Only image APEXes can be flattened.
820 if a.flattened && apexType.image() {
Jiyong Park8fd61922018-11-08 02:50:25 +0900821 return android.AndroidMkData{
822 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
823 moduleNames := []string{}
824 for _, fi := range a.filesInfo {
825 if !android.InList(fi.moduleName, moduleNames) {
826 moduleNames = append(moduleNames, fi.moduleName)
827 }
828 }
829 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
830 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
831 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
832 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", strings.Join(moduleNames, " "))
833 fmt.Fprintln(w, "include $(BUILD_PHONY_PACKAGE)")
834
835 for _, fi := range a.filesInfo {
836 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
837 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
838 fmt.Fprintln(w, "LOCAL_MODULE :=", fi.moduleName)
839 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString(), name, fi.installDir))
840 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", fi.builtFile.Base())
841 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", fi.builtFile.String())
842 fmt.Fprintln(w, "LOCAL_MODULE_CLASS :=", fi.class.NameInMake())
843 archStr := fi.archType.String()
844 if archStr != "common" {
845 fmt.Fprintln(w, "LOCAL_MODULE_TARGET_ARCH :=", archStr)
846 }
847 if fi.class == javaSharedLib {
848 fmt.Fprintln(w, "LOCAL_SOONG_DEX_JAR :=", fi.builtFile.String())
849 fmt.Fprintln(w, "LOCAL_DEX_PREOPT := false")
850 fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_java_prebuilt.mk")
851 } else {
852 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
853 }
854 }
855 }}
856 } else {
857 return android.AndroidMkData{
858 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
Alex Light5098a612018-11-29 17:12:15 -0800859 // zip-apex is the less common type so have the name refer to the image-apex
860 // only and use {name}.zip if you want the zip-apex
861 if apexType == zipApex && a.apexTypes == both {
862 name = name + ".zip"
863 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900864 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
865 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
866 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
867 fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC") // do we need a new class?
Alex Light5098a612018-11-29 17:12:15 -0800868 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", a.outputFiles[apexType].String())
Jiyong Park8fd61922018-11-08 02:50:25 +0900869 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString()))
Alex Light5098a612018-11-29 17:12:15 -0800870 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", name+apexType.suffix())
Jiyong Park8fd61922018-11-08 02:50:25 +0900871 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", String(a.properties.Key))
872 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
Colin Crossa4925902018-11-16 11:36:28 -0800873
Alex Light5098a612018-11-29 17:12:15 -0800874 if apexType == imageApex {
875 fmt.Fprintln(w, "ALL_MODULES.$(LOCAL_MODULE).BUNDLE :=", a.bundleModuleFile.String())
876 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900877 }}
878 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900879}
880
Alex Lightee250722018-12-06 14:00:02 -0800881func ApexBundleFactory() android.Module {
Alex Light5098a612018-11-29 17:12:15 -0800882 module := &apexBundle{
883 outputFiles: map[apexPackaging]android.WritablePath{},
884 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900885 module.AddProperties(&module.properties)
Alex Light5098a612018-11-29 17:12:15 -0800886 module.Prefer32(func(ctx android.BaseModuleContext, base *android.ModuleBase, class android.OsClass) bool {
Jiyong Park397e55e2018-10-24 21:09:55 +0900887 return class == android.Device && ctx.Config().DevicePrefer32BitExecutables()
888 })
Alex Light5098a612018-11-29 17:12:15 -0800889 android.InitAndroidMultiTargetsArchModule(module, android.HostAndDeviceSupported, android.MultilibCommon)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900890 android.InitDefaultableModule(module)
891 return module
892}