blob: c0dfdd836c6e270ffc03ebdb2dadd8fda9283f6b [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} && ` +
Jiyong Park48ca7dc2018-10-10 14:01:00 +090041 `echo '/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} ` +
58 `--key ${key} ${image_dir} ${out} `,
59 CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
60 "${mke2fs}", "${resize2fs}", "${sefcontext_compile}",
61 "${soong_zip}", "${zipalign}", "${aapt2}"},
62 Description: "APEX ${image_dir} => ${out}",
63 }, "tool_path", "image_dir", "copy_commands", "manifest", "file_contexts", "canned_fs_config", "key")
Colin Crossa4925902018-11-16 11:36:28 -080064
65 apexProtoConvertRule = pctx.AndroidStaticRule("apexProtoConvertRule",
66 blueprint.RuleParams{
67 Command: `${aapt2} convert --output-format proto $in -o $out`,
68 CommandDeps: []string{"${aapt2}"},
69 })
70
71 apexBundleRule = pctx.StaticRule("apexBundleRule", blueprint.RuleParams{
Jiyong Park1ed0fc52018-11-23 13:22:21 +090072 Command: `${zip2zip} -i $in -o $out ` +
73 `image.img:apex/${abi}.img ` +
74 `manifest.json:root/manifest.json ` +
75 `AndroidManifest.xml:manifest/AndroidManifest.xml ` +
76 `resources.pb`,
Colin Crossa4925902018-11-16 11:36:28 -080077 CommandDeps: []string{"${zip2zip}"},
78 Description: "app bundle",
79 }, "abi")
Jiyong Park48ca7dc2018-10-10 14:01:00 +090080)
81
82var apexSuffix = ".apex"
83
84type dependencyTag struct {
85 blueprint.BaseDependencyTag
86 name string
87}
88
89var (
Jiyong Parkc00cbd92018-10-30 21:20:05 +090090 sharedLibTag = dependencyTag{name: "sharedLib"}
91 executableTag = dependencyTag{name: "executable"}
92 javaLibTag = dependencyTag{name: "javaLib"}
93 prebuiltTag = dependencyTag{name: "prebuilt"}
94 keyTag = dependencyTag{name: "key"}
95 certificateTag = dependencyTag{name: "certificate"}
Jiyong Park48ca7dc2018-10-10 14:01:00 +090096)
97
98func init() {
99 pctx.Import("android/soong/common")
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900100 pctx.Import("android/soong/java")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900101 pctx.HostBinToolVariable("apexer", "apexer")
Roland Levillain54bdfda2018-10-05 19:34:32 +0100102 // ART minimal builds (using the master-art manifest) do not have the "frameworks/base"
103 // projects, and hence cannot built 'aapt2'. Use the SDK prebuilt instead.
104 hostBinToolVariableWithPrebuilt := func(name, prebuiltDir, tool string) {
105 pctx.VariableFunc(name, func(ctx android.PackageVarContext) string {
106 if !android.ExistentPathForSource(ctx, "frameworks/base").Valid() {
107 return filepath.Join(prebuiltDir, runtime.GOOS, "bin", tool)
108 } else {
109 return pctx.HostBinToolPath(ctx, tool).String()
110 }
111 })
112 }
113 hostBinToolVariableWithPrebuilt("aapt2", "prebuilts/sdk/tools", "aapt2")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900114 pctx.HostBinToolVariable("avbtool", "avbtool")
115 pctx.HostBinToolVariable("e2fsdroid", "e2fsdroid")
116 pctx.HostBinToolVariable("merge_zips", "merge_zips")
117 pctx.HostBinToolVariable("mke2fs", "mke2fs")
118 pctx.HostBinToolVariable("resize2fs", "resize2fs")
119 pctx.HostBinToolVariable("sefcontext_compile", "sefcontext_compile")
120 pctx.HostBinToolVariable("soong_zip", "soong_zip")
Colin Crossa4925902018-11-16 11:36:28 -0800121 pctx.HostBinToolVariable("zip2zip", "zip2zip")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900122 pctx.HostBinToolVariable("zipalign", "zipalign")
123
124 android.RegisterModuleType("apex", apexBundleFactory)
125
126 android.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
127 ctx.TopDown("apex_deps", apexDepsMutator)
128 ctx.BottomUp("apex", apexMutator)
129 })
130}
131
132// maps a module name to set of apex bundle names that the module should be built for
133func apexBundleNamesFor(config android.Config) map[string]map[string]bool {
134 return config.Once("apexBundleNames", func() interface{} {
135 return make(map[string]map[string]bool)
136 }).(map[string]map[string]bool)
137}
138
139// Mark the direct and transitive dependencies of apex bundles so that they
140// can be built for the apex bundles.
141func apexDepsMutator(mctx android.TopDownMutatorContext) {
142 if _, ok := mctx.Module().(*apexBundle); ok {
Colin Crossa4925902018-11-16 11:36:28 -0800143 apexBundleName := mctx.ModuleName()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900144 mctx.WalkDeps(func(child, parent android.Module) bool {
145 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() {
Colin Crossa4925902018-11-16 11:36:28 -0800146 moduleName := mctx.OtherModuleName(am) + "-" + am.Target().String()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900147 bundleNames, ok := apexBundleNamesFor(mctx.Config())[moduleName]
148 if !ok {
149 bundleNames = make(map[string]bool)
150 apexBundleNamesFor(mctx.Config())[moduleName] = bundleNames
151 }
152 bundleNames[apexBundleName] = true
153 return true
154 } else {
155 return false
156 }
157 })
158 }
159}
160
161// Create apex variations if a module is included in APEX(s).
162func apexMutator(mctx android.BottomUpMutatorContext) {
163 if am, ok := mctx.Module().(android.ApexModule); ok && am.CanHaveApexVariants() {
Colin Crossa4925902018-11-16 11:36:28 -0800164 moduleName := mctx.ModuleName() + "-" + am.Target().String()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900165 if bundleNames, ok := apexBundleNamesFor(mctx.Config())[moduleName]; ok {
166 variations := []string{"platform"}
167 for bn := range bundleNames {
168 variations = append(variations, bn)
169 }
170 modules := mctx.CreateVariations(variations...)
171 for i, m := range modules {
172 if i == 0 {
173 continue // platform
174 }
175 m.(android.ApexModule).BuildForApex(variations[i])
176 }
177 }
178 } else if _, ok := mctx.Module().(*apexBundle); ok {
179 // apex bundle itself is mutated so that it and its modules have same
180 // apex variant.
181 apexBundleName := mctx.ModuleName()
182 mctx.CreateVariations(apexBundleName)
183 }
184}
185
186type apexBundleProperties struct {
187 // Json manifest file describing meta info of this APEX bundle. Default:
188 // "manifest.json"
189 Manifest *string
190
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900191 // Determines the file contexts file for setting security context to each file in this APEX bundle.
192 // Specifically, when this is set to <value>, /system/sepolicy/apex/<value>_file_contexts file is
193 // used.
194 // Default: <name_of_this_module>
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900195 File_contexts *string
196
197 // List of native shared libs that are embedded inside this APEX bundle
198 Native_shared_libs []string
199
200 // List of native executables that are embedded inside this APEX bundle
201 Binaries []string
202
203 // List of java libraries that are embedded inside this APEX bundle
204 Java_libs []string
205
206 // List of prebuilt files that are embedded inside this APEX bundle
207 Prebuilts []string
Jiyong Parkff1458f2018-10-12 21:49:38 +0900208
209 // Name of the apex_key module that provides the private key to sign APEX
210 Key *string
Jiyong Park397e55e2018-10-24 21:09:55 +0900211
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900212 // The name of a certificate in the default certificate directory, blank to use the default product certificate,
213 // or an android_app_certificate module name in the form ":module".
214 Certificate *string
215
Jiyong Park397e55e2018-10-24 21:09:55 +0900216 Multilib struct {
217 First struct {
218 // List of native libraries whose compile_multilib is "first"
219 Native_shared_libs []string
220 // List of native executables whose compile_multilib is "first"
221 Binaries []string
222 }
223 Both struct {
224 // List of native libraries whose compile_multilib is "both"
225 Native_shared_libs []string
226 // List of native executables whose compile_multilib is "both"
227 Binaries []string
228 }
229 Prefer32 struct {
230 // List of native libraries whose compile_multilib is "prefer32"
231 Native_shared_libs []string
232 // List of native executables whose compile_multilib is "prefer32"
233 Binaries []string
234 }
235 Lib32 struct {
236 // List of native libraries whose compile_multilib is "32"
237 Native_shared_libs []string
238 // List of native executables whose compile_multilib is "32"
239 Binaries []string
240 }
241 Lib64 struct {
242 // List of native libraries whose compile_multilib is "64"
243 Native_shared_libs []string
244 // List of native executables whose compile_multilib is "64"
245 Binaries []string
246 }
247 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900248}
249
Jiyong Park8fd61922018-11-08 02:50:25 +0900250type apexFileClass int
251
252const (
253 etc apexFileClass = iota
254 nativeSharedLib
255 nativeExecutable
256 javaSharedLib
257)
258
259func (class apexFileClass) NameInMake() string {
260 switch class {
261 case etc:
262 return "ETC"
263 case nativeSharedLib:
264 return "SHARED_LIBRARIES"
265 case nativeExecutable:
266 return "EXECUTABLES"
267 case javaSharedLib:
268 return "JAVA_LIBRARIES"
269 default:
270 panic(fmt.Errorf("unkonwn class %d", class))
271 }
272}
273
274type apexFile struct {
275 builtFile android.Path
276 moduleName string
277 archType android.ArchType
278 installDir string
279 class apexFileClass
280}
281
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900282type apexBundle struct {
283 android.ModuleBase
284 android.DefaultableModuleBase
285
286 properties apexBundleProperties
287
Colin Crossa4925902018-11-16 11:36:28 -0800288 bundleModuleFile android.WritablePath
289 outputFile android.WritablePath
290 installDir android.OutputPath
Jiyong Park8fd61922018-11-08 02:50:25 +0900291
292 // list of files to be included in this apex
293 filesInfo []apexFile
294
295 flattened bool
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900296}
297
Jiyong Park397e55e2018-10-24 21:09:55 +0900298func addDependenciesForNativeModules(ctx android.BottomUpMutatorContext,
299 native_shared_libs []string, binaries []string, arch string) {
300 // Use *FarVariation* to be able to depend on modules having
301 // conflicting variations with this module. This is required since
302 // arch variant of an APEX bundle is 'common' but it is 'arm' or 'arm64'
303 // for native shared libs.
304 ctx.AddFarVariationDependencies([]blueprint.Variation{
305 {Mutator: "arch", Variation: arch},
306 {Mutator: "image", Variation: "core"},
307 {Mutator: "link", Variation: "shared"},
308 }, sharedLibTag, native_shared_libs...)
309
310 ctx.AddFarVariationDependencies([]blueprint.Variation{
311 {Mutator: "arch", Variation: arch},
312 {Mutator: "image", Variation: "core"},
313 }, executableTag, binaries...)
314}
315
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900316func (a *apexBundle) DepsMutator(ctx android.BottomUpMutatorContext) {
Jiyong Park397e55e2018-10-24 21:09:55 +0900317 targets := ctx.MultiTargets()
318 has32BitTarget := false
319 for _, target := range targets {
320 if target.Arch.ArchType.Multilib == "lib32" {
321 has32BitTarget = true
322 }
323 }
324 for i, target := range targets {
325 // When multilib.* is omitted for native_shared_libs, it implies
326 // multilib.both.
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900327 ctx.AddFarVariationDependencies([]blueprint.Variation{
Jiyong Park397e55e2018-10-24 21:09:55 +0900328 {Mutator: "arch", Variation: target.String()},
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900329 {Mutator: "image", Variation: "core"},
330 {Mutator: "link", Variation: "shared"},
331 }, sharedLibTag, a.properties.Native_shared_libs...)
332
Jiyong Park397e55e2018-10-24 21:09:55 +0900333 // Add native modules targetting both ABIs
334 addDependenciesForNativeModules(ctx,
335 a.properties.Multilib.Both.Native_shared_libs,
336 a.properties.Multilib.Both.Binaries, target.String())
337
338 if i == 0 {
339 // When multilib.* is omitted for binaries, it implies
340 // multilib.first.
341 ctx.AddFarVariationDependencies([]blueprint.Variation{
342 {Mutator: "arch", Variation: target.String()},
343 {Mutator: "image", Variation: "core"},
344 }, executableTag, a.properties.Binaries...)
345
346 // Add native modules targetting the first ABI
347 addDependenciesForNativeModules(ctx,
348 a.properties.Multilib.First.Native_shared_libs,
349 a.properties.Multilib.First.Binaries, target.String())
350 }
351
352 switch target.Arch.ArchType.Multilib {
353 case "lib32":
354 // Add native modules targetting 32-bit ABI
355 addDependenciesForNativeModules(ctx,
356 a.properties.Multilib.Lib32.Native_shared_libs,
357 a.properties.Multilib.Lib32.Binaries, target.String())
358
359 addDependenciesForNativeModules(ctx,
360 a.properties.Multilib.Prefer32.Native_shared_libs,
361 a.properties.Multilib.Prefer32.Binaries, target.String())
362 case "lib64":
363 // Add native modules targetting 64-bit ABI
364 addDependenciesForNativeModules(ctx,
365 a.properties.Multilib.Lib64.Native_shared_libs,
366 a.properties.Multilib.Lib64.Binaries, target.String())
367
368 if !has32BitTarget {
369 addDependenciesForNativeModules(ctx,
370 a.properties.Multilib.Prefer32.Native_shared_libs,
371 a.properties.Multilib.Prefer32.Binaries, target.String())
372 }
373 }
374
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900375 }
376
Jiyong Parkff1458f2018-10-12 21:49:38 +0900377 ctx.AddFarVariationDependencies([]blueprint.Variation{
378 {Mutator: "arch", Variation: "android_common"},
379 }, javaLibTag, a.properties.Java_libs...)
380
381 ctx.AddFarVariationDependencies([]blueprint.Variation{
382 {Mutator: "arch", Variation: "android_common"},
383 }, prebuiltTag, a.properties.Prebuilts...)
384
385 if String(a.properties.Key) == "" {
386 ctx.ModuleErrorf("key is missing")
387 return
388 }
389 ctx.AddDependency(ctx.Module(), keyTag, String(a.properties.Key))
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900390
391 cert := android.SrcIsModule(String(a.properties.Certificate))
392 if cert != "" {
393 ctx.AddDependency(ctx.Module(), certificateTag, cert)
394 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900395}
396
397func getCopyManifestForNativeLibrary(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
398 // Decide the APEX-local directory by the multilib of the library
399 // In the future, we may query this to the module.
400 switch cc.Arch().ArchType.Multilib {
401 case "lib32":
402 dirInApex = "lib"
403 case "lib64":
404 dirInApex = "lib64"
405 }
406 if !cc.Arch().Native {
407 dirInApex = filepath.Join(dirInApex, cc.Arch().ArchType.String())
408 }
409
410 fileToCopy = cc.OutputFile().Path()
411 return
412}
413
414func getCopyManifestForExecutable(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
415 dirInApex = "bin"
416 fileToCopy = cc.OutputFile().Path()
417 return
418}
419
420func getCopyManifestForJavaLibrary(java *java.Library) (fileToCopy android.Path, dirInApex string) {
421 dirInApex = "javalib"
Jiyong Park8fd61922018-11-08 02:50:25 +0900422 fileToCopy = java.DexJarFile()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900423 return
424}
425
426func getCopyManifestForPrebuiltEtc(prebuilt *android.PrebuiltEtc) (fileToCopy android.Path, dirInApex string) {
427 dirInApex = filepath.Join("etc", prebuilt.SubDir())
428 fileToCopy = prebuilt.OutputFile()
429 return
430}
431
432func (a *apexBundle) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Park8fd61922018-11-08 02:50:25 +0900433 filesInfo := []apexFile{}
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900434
Jiyong Parkff1458f2018-10-12 21:49:38 +0900435 var keyFile android.Path
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900436 var certificate java.Certificate
Jiyong Parkff1458f2018-10-12 21:49:38 +0900437
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900438 ctx.WalkDeps(func(child, parent android.Module) bool {
439 if _, ok := parent.(*apexBundle); ok {
440 // direct dependencies
441 depTag := ctx.OtherModuleDependencyTag(child)
Jiyong Parkff1458f2018-10-12 21:49:38 +0900442 depName := ctx.OtherModuleName(child)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900443 switch depTag {
444 case sharedLibTag:
445 if cc, ok := child.(*cc.Module); ok {
446 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900447 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeSharedLib})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900448 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900449 } else {
450 ctx.PropertyErrorf("native_shared_libs", "%q is not a cc_library or cc_library_shared module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900451 }
452 case executableTag:
453 if cc, ok := child.(*cc.Module); ok {
454 fileToCopy, dirInApex := getCopyManifestForExecutable(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900455 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeExecutable})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900456 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900457 } else {
458 ctx.PropertyErrorf("binaries", "%q is not a cc_binary module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900459 }
460 case javaLibTag:
461 if java, ok := child.(*java.Library); ok {
462 fileToCopy, dirInApex := getCopyManifestForJavaLibrary(java)
Jiyong Park8fd61922018-11-08 02:50:25 +0900463 if fileToCopy == nil {
464 ctx.PropertyErrorf("java_libs", "%q is not configured to be compiled into dex", depName)
465 } else {
466 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, java.Arch().ArchType, dirInApex, javaSharedLib})
467 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900468 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900469 } else {
470 ctx.PropertyErrorf("java_libs", "%q is not a java_library module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900471 }
472 case prebuiltTag:
473 if prebuilt, ok := child.(*android.PrebuiltEtc); ok {
474 fileToCopy, dirInApex := getCopyManifestForPrebuiltEtc(prebuilt)
Jiyong Park8fd61922018-11-08 02:50:25 +0900475 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, prebuilt.Arch().ArchType, dirInApex, etc})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900476 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900477 } else {
478 ctx.PropertyErrorf("prebuilts", "%q is not a prebuilt_etc module", depName)
479 }
480 case keyTag:
481 if key, ok := child.(*apexKey); ok {
482 keyFile = key.private_key_file
483 return false
484 } else {
485 ctx.PropertyErrorf("key", "%q is not an apex_key module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900486 }
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900487 case certificateTag:
488 if dep, ok := child.(*java.AndroidAppCertificate); ok {
489 certificate = dep.Certificate
490 return false
491 } else {
492 ctx.ModuleErrorf("certificate dependency %q must be an android_app_certificate module", depName)
493 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900494 }
495 } else {
496 // indirect dependencies
497 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() && am.IsInstallableToApex() {
498 if cc, ok := child.(*cc.Module); ok {
Jiyong Park8fd61922018-11-08 02:50:25 +0900499 depName := ctx.OtherModuleName(child)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900500 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900501 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeSharedLib})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900502 return true
503 }
504 }
505 }
506 return false
507 })
508
Jiyong Parkfa0a3732018-11-09 05:52:26 +0900509 if keyFile == nil {
510 ctx.PropertyErrorf("key", "private_key for %q could not be found", String(a.properties.Key))
511 return
512 }
513
Jiyong Park8fd61922018-11-08 02:50:25 +0900514 // remove duplicates in filesInfo
515 removeDup := func(filesInfo []apexFile) []apexFile {
516 encountered := make(map[android.Path]bool)
517 result := []apexFile{}
518 for _, f := range filesInfo {
519 if !encountered[f.builtFile] {
520 encountered[f.builtFile] = true
521 result = append(result, f)
522 }
523 }
524 return result
525 }
526 filesInfo = removeDup(filesInfo)
527
528 // to have consistent build rules
529 sort.Slice(filesInfo, func(i, j int) bool {
530 return filesInfo[i].builtFile.String() < filesInfo[j].builtFile.String()
531 })
532
533 // prepend the name of this APEX to the module names. These names will be the names of
534 // modules that will be defined if the APEX is flattened.
535 for i := range filesInfo {
536 filesInfo[i].moduleName = ctx.ModuleName() + "." + filesInfo[i].moduleName
537 }
538
Colin Crossa4925902018-11-16 11:36:28 -0800539 a.flattened = ctx.Config().FlattenApex() && !ctx.Config().UnbundledBuild()
Jiyong Park8fd61922018-11-08 02:50:25 +0900540 a.installDir = android.PathForModuleInstall(ctx, "apex")
541 a.filesInfo = filesInfo
542 if ctx.Config().FlattenApex() {
543 a.buildFlattenedApex(ctx)
544 } else {
545 a.buildUnflattenedApex(ctx, keyFile, certificate)
546 }
547}
548
549func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext, keyFile android.Path, certificate java.Certificate) {
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900550 cert := String(a.properties.Certificate)
551 if cert != "" && android.SrcIsModule(cert) == "" {
552 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
553 certificate = java.Certificate{
554 defaultDir.Join(ctx, cert+".x509.pem"),
555 defaultDir.Join(ctx, cert+".pk8"),
556 }
557 } else if cert == "" {
558 pem, key := ctx.Config().DefaultAppCertificate(ctx)
559 certificate = java.Certificate{pem, key}
560 }
561
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900562 // files and dirs that will be created in apex
Jiyong Park92905d62018-10-11 13:23:09 +0900563 var readOnlyPaths []string
564 var executablePaths []string // this also includes dirs
Jiyong Park8fd61922018-11-08 02:50:25 +0900565 for _, f := range a.filesInfo {
566 pathInApex := filepath.Join(f.installDir, f.builtFile.Base())
567 if f.installDir == "bin" {
Jiyong Park92905d62018-10-11 13:23:09 +0900568 executablePaths = append(executablePaths, pathInApex)
569 } else {
570 readOnlyPaths = append(readOnlyPaths, pathInApex)
571 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900572 if !android.InList(f.installDir, executablePaths) {
573 executablePaths = append(executablePaths, f.installDir)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900574 }
575 }
Jiyong Park92905d62018-10-11 13:23:09 +0900576 sort.Strings(readOnlyPaths)
577 sort.Strings(executablePaths)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900578 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
Colin Crossa4925902018-11-16 11:36:28 -0800579 ctx.Build(pctx, android.BuildParams{
580 Rule: generateFsConfig,
581 Output: cannedFsConfig,
582 Description: "generate fs config",
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900583 Args: map[string]string{
Jiyong Park92905d62018-10-11 13:23:09 +0900584 "ro_paths": strings.Join(readOnlyPaths, " "),
585 "exec_paths": strings.Join(executablePaths, " "),
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900586 },
587 })
588
589 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "manifest.json"))
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900590
Colin Crossa4925902018-11-16 11:36:28 -0800591 fcName := proptools.StringDefault(a.properties.File_contexts, ctx.ModuleName())
Jiyong Park02196572018-11-14 13:54:14 +0900592 fileContextsPath := "system/sepolicy/apex/" + fcName + "-file_contexts"
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900593 fileContextsOptionalPath := android.ExistentPathForSource(ctx, fileContextsPath)
594 if !fileContextsOptionalPath.Valid() {
595 ctx.ModuleErrorf("Cannot find file_contexts file: %q", fileContextsPath)
596 return
597 }
598 fileContexts := fileContextsOptionalPath.Path()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900599
Colin Crossa4925902018-11-16 11:36:28 -0800600 unsignedOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+apexSuffix+".unsigned")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900601
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900602 filesToCopy := []android.Path{}
Jiyong Park8fd61922018-11-08 02:50:25 +0900603 for _, f := range a.filesInfo {
604 filesToCopy = append(filesToCopy, f.builtFile)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900605 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900606
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900607 copyCommands := []string{}
Jiyong Park8fd61922018-11-08 02:50:25 +0900608 for i, src := range filesToCopy {
609 dest := filepath.Join(a.filesInfo[i].installDir, src.Base())
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900610 dest_path := filepath.Join(android.PathForModuleOut(ctx, "image").String(), dest)
611 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(dest_path))
612 copyCommands = append(copyCommands, "cp "+src.String()+" "+dest_path)
613 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900614 implicitInputs := append(android.Paths(nil), filesToCopy...)
Jiyong Parkff1458f2018-10-12 21:49:38 +0900615 implicitInputs = append(implicitInputs, cannedFsConfig, manifest, fileContexts, keyFile)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900616 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
617 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
Colin Crossa4925902018-11-16 11:36:28 -0800618 ctx.Build(pctx, android.BuildParams{
619 Rule: apexRule,
620 Implicits: implicitInputs,
621 Output: unsignedOutputFile,
622 Description: "apex",
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900623 Args: map[string]string{
624 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
625 "image_dir": android.PathForModuleOut(ctx, "image").String(),
626 "copy_commands": strings.Join(copyCommands, " && "),
627 "manifest": manifest.String(),
628 "file_contexts": fileContexts.String(),
629 "canned_fs_config": cannedFsConfig.String(),
Jiyong Parkff1458f2018-10-12 21:49:38 +0900630 "key": keyFile.String(),
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900631 },
632 })
633
Colin Crossa4925902018-11-16 11:36:28 -0800634 var abis []string
635 for _, target := range ctx.MultiTargets() {
636 abis = append(abis, target.Arch.Abi[0])
637 }
638 abis = android.FirstUniqueStrings(abis)
639
640 apexProtoFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".pb"+apexSuffix)
641 bundleModuleFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-base.zip")
642 a.bundleModuleFile = bundleModuleFile
643
644 ctx.Build(pctx, android.BuildParams{
645 Rule: apexProtoConvertRule,
646 Input: unsignedOutputFile,
647 Output: apexProtoFile,
648 Description: "apex proto convert",
649 })
650
651 ctx.Build(pctx, android.BuildParams{
652 Rule: apexBundleRule,
653 Input: apexProtoFile,
654 Output: bundleModuleFile,
655 Description: "apex bundle module",
656 Args: map[string]string{
657 "abi": strings.Join(abis, "."),
658 },
659 })
660
661 a.outputFile = android.PathForModuleOut(ctx, ctx.ModuleName()+apexSuffix)
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900662 ctx.Build(pctx, android.BuildParams{
663 Rule: java.Signapk,
664 Description: "signapk",
665 Output: a.outputFile,
666 Input: unsignedOutputFile,
667 Args: map[string]string{
668 "certificates": strings.Join([]string{certificate.Pem.String(), certificate.Key.String()}, " "),
Jiyong Parkbfe64a12018-11-22 02:51:54 +0900669 "flags": "-a 4096", //alignment
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900670 },
671 })
Jiyong Park8fd61922018-11-08 02:50:25 +0900672}
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900673
Jiyong Park8fd61922018-11-08 02:50:25 +0900674func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
675 // For flattened APEX, do nothing but make sure that manifest.json file is also copied along
676 // with other ordinary files.
677 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "manifest.json"))
Colin Crossa4925902018-11-16 11:36:28 -0800678 a.filesInfo = append(a.filesInfo, apexFile{manifest, ctx.ModuleName() + ".manifest.json", android.Common, ".", etc})
Jiyong Park8fd61922018-11-08 02:50:25 +0900679
680 for _, fi := range a.filesInfo {
Colin Crossa4925902018-11-16 11:36:28 -0800681 dir := filepath.Join("apex", ctx.ModuleName(), fi.installDir)
Jiyong Park8fd61922018-11-08 02:50:25 +0900682 ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.builtFile.Base(), fi.builtFile)
683 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900684}
685
686func (a *apexBundle) AndroidMk() android.AndroidMkData {
Jiyong Park8fd61922018-11-08 02:50:25 +0900687 if a.flattened {
688 return android.AndroidMkData{
689 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
690 moduleNames := []string{}
691 for _, fi := range a.filesInfo {
692 if !android.InList(fi.moduleName, moduleNames) {
693 moduleNames = append(moduleNames, fi.moduleName)
694 }
695 }
696 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
697 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
698 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
699 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", strings.Join(moduleNames, " "))
700 fmt.Fprintln(w, "include $(BUILD_PHONY_PACKAGE)")
701
702 for _, fi := range a.filesInfo {
703 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
704 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
705 fmt.Fprintln(w, "LOCAL_MODULE :=", fi.moduleName)
706 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString(), name, fi.installDir))
707 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", fi.builtFile.Base())
708 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", fi.builtFile.String())
709 fmt.Fprintln(w, "LOCAL_MODULE_CLASS :=", fi.class.NameInMake())
710 archStr := fi.archType.String()
711 if archStr != "common" {
712 fmt.Fprintln(w, "LOCAL_MODULE_TARGET_ARCH :=", archStr)
713 }
714 if fi.class == javaSharedLib {
715 fmt.Fprintln(w, "LOCAL_SOONG_DEX_JAR :=", fi.builtFile.String())
716 fmt.Fprintln(w, "LOCAL_DEX_PREOPT := false")
717 fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_java_prebuilt.mk")
718 } else {
719 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
720 }
721 }
722 }}
723 } else {
724 return android.AndroidMkData{
725 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
726 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
727 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
728 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
729 fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC") // do we need a new class?
730 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", a.outputFile.String())
731 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString()))
732 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", name+apexSuffix)
733 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", String(a.properties.Key))
734 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
Colin Crossa4925902018-11-16 11:36:28 -0800735
736 fmt.Fprintln(w, "ALL_MODULES.$(LOCAL_MODULE).BUNDLE :=", a.bundleModuleFile.String())
Jiyong Park8fd61922018-11-08 02:50:25 +0900737 }}
738 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900739}
740
741func apexBundleFactory() android.Module {
742 module := &apexBundle{}
743 module.AddProperties(&module.properties)
Jiyong Park397e55e2018-10-24 21:09:55 +0900744 module.Prefer32(func(ctx android.BaseModuleContext, base *android.ModuleBase,
745 class android.OsClass) bool {
746 return class == android.Device && ctx.Config().DevicePrefer32BitExecutables()
747 })
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900748 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
749 android.InitDefaultableModule(module)
750 return module
751}