blob: 8a652db0548b4ce8fd7b19ea016aa68d77b8a8f1 [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} ` +
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 ` +
Dario Freni4abb1dc2018-11-20 18:04:58 +000073 `apex_payload.img:apex/${abi}.img ` +
74 `apex_manifest.json:root/apex_manifest.json ` +
Shahar Amitai328b0772018-11-26 14:12:02 +000075 `AndroidManifest.xml:manifest/AndroidManifest.xml`,
Colin Crossa4925902018-11-16 11:36:28 -080076 CommandDeps: []string{"${zip2zip}"},
77 Description: "app bundle",
78 }, "abi")
Jiyong Park48ca7dc2018-10-10 14:01:00 +090079)
80
81var apexSuffix = ".apex"
82
83type dependencyTag struct {
84 blueprint.BaseDependencyTag
85 name string
86}
87
88var (
Jiyong Parkc00cbd92018-10-30 21:20:05 +090089 sharedLibTag = dependencyTag{name: "sharedLib"}
90 executableTag = dependencyTag{name: "executable"}
91 javaLibTag = dependencyTag{name: "javaLib"}
92 prebuiltTag = dependencyTag{name: "prebuilt"}
93 keyTag = dependencyTag{name: "key"}
94 certificateTag = dependencyTag{name: "certificate"}
Jiyong Park48ca7dc2018-10-10 14:01:00 +090095)
96
97func init() {
98 pctx.Import("android/soong/common")
Jiyong Parkc00cbd92018-10-30 21:20:05 +090099 pctx.Import("android/soong/java")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900100 pctx.HostBinToolVariable("apexer", "apexer")
Roland Levillain54bdfda2018-10-05 19:34:32 +0100101 // ART minimal builds (using the master-art manifest) do not have the "frameworks/base"
102 // projects, and hence cannot built 'aapt2'. Use the SDK prebuilt instead.
103 hostBinToolVariableWithPrebuilt := func(name, prebuiltDir, tool string) {
104 pctx.VariableFunc(name, func(ctx android.PackageVarContext) string {
105 if !android.ExistentPathForSource(ctx, "frameworks/base").Valid() {
106 return filepath.Join(prebuiltDir, runtime.GOOS, "bin", tool)
107 } else {
108 return pctx.HostBinToolPath(ctx, tool).String()
109 }
110 })
111 }
112 hostBinToolVariableWithPrebuilt("aapt2", "prebuilts/sdk/tools", "aapt2")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900113 pctx.HostBinToolVariable("avbtool", "avbtool")
114 pctx.HostBinToolVariable("e2fsdroid", "e2fsdroid")
115 pctx.HostBinToolVariable("merge_zips", "merge_zips")
116 pctx.HostBinToolVariable("mke2fs", "mke2fs")
117 pctx.HostBinToolVariable("resize2fs", "resize2fs")
118 pctx.HostBinToolVariable("sefcontext_compile", "sefcontext_compile")
119 pctx.HostBinToolVariable("soong_zip", "soong_zip")
Colin Crossa4925902018-11-16 11:36:28 -0800120 pctx.HostBinToolVariable("zip2zip", "zip2zip")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900121 pctx.HostBinToolVariable("zipalign", "zipalign")
122
123 android.RegisterModuleType("apex", apexBundleFactory)
124
125 android.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
126 ctx.TopDown("apex_deps", apexDepsMutator)
127 ctx.BottomUp("apex", apexMutator)
128 })
129}
130
131// maps a module name to set of apex bundle names that the module should be built for
132func apexBundleNamesFor(config android.Config) map[string]map[string]bool {
133 return config.Once("apexBundleNames", func() interface{} {
134 return make(map[string]map[string]bool)
135 }).(map[string]map[string]bool)
136}
137
138// Mark the direct and transitive dependencies of apex bundles so that they
139// can be built for the apex bundles.
140func apexDepsMutator(mctx android.TopDownMutatorContext) {
141 if _, ok := mctx.Module().(*apexBundle); ok {
Colin Crossa4925902018-11-16 11:36:28 -0800142 apexBundleName := mctx.ModuleName()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900143 mctx.WalkDeps(func(child, parent android.Module) bool {
144 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() {
Colin Crossa4925902018-11-16 11:36:28 -0800145 moduleName := mctx.OtherModuleName(am) + "-" + am.Target().String()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900146 bundleNames, ok := apexBundleNamesFor(mctx.Config())[moduleName]
147 if !ok {
148 bundleNames = make(map[string]bool)
149 apexBundleNamesFor(mctx.Config())[moduleName] = bundleNames
150 }
151 bundleNames[apexBundleName] = true
152 return true
153 } else {
154 return false
155 }
156 })
157 }
158}
159
160// Create apex variations if a module is included in APEX(s).
161func apexMutator(mctx android.BottomUpMutatorContext) {
162 if am, ok := mctx.Module().(android.ApexModule); ok && am.CanHaveApexVariants() {
Colin Crossa4925902018-11-16 11:36:28 -0800163 moduleName := mctx.ModuleName() + "-" + am.Target().String()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900164 if bundleNames, ok := apexBundleNamesFor(mctx.Config())[moduleName]; ok {
165 variations := []string{"platform"}
166 for bn := range bundleNames {
167 variations = append(variations, bn)
168 }
169 modules := mctx.CreateVariations(variations...)
170 for i, m := range modules {
171 if i == 0 {
172 continue // platform
173 }
174 m.(android.ApexModule).BuildForApex(variations[i])
175 }
176 }
177 } else if _, ok := mctx.Module().(*apexBundle); ok {
178 // apex bundle itself is mutated so that it and its modules have same
179 // apex variant.
180 apexBundleName := mctx.ModuleName()
181 mctx.CreateVariations(apexBundleName)
182 }
183}
184
185type apexBundleProperties struct {
186 // Json manifest file describing meta info of this APEX bundle. Default:
Dario Freni4abb1dc2018-11-20 18:04:58 +0000187 // "apex_manifest.json"
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900188 Manifest *string
189
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900190 // Determines the file contexts file for setting security context to each file in this APEX bundle.
191 // Specifically, when this is set to <value>, /system/sepolicy/apex/<value>_file_contexts file is
192 // used.
193 // Default: <name_of_this_module>
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900194 File_contexts *string
195
196 // List of native shared libs that are embedded inside this APEX bundle
197 Native_shared_libs []string
198
199 // List of native executables that are embedded inside this APEX bundle
200 Binaries []string
201
202 // List of java libraries that are embedded inside this APEX bundle
203 Java_libs []string
204
205 // List of prebuilt files that are embedded inside this APEX bundle
206 Prebuilts []string
Jiyong Parkff1458f2018-10-12 21:49:38 +0900207
208 // Name of the apex_key module that provides the private key to sign APEX
209 Key *string
Jiyong Park397e55e2018-10-24 21:09:55 +0900210
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900211 // The name of a certificate in the default certificate directory, blank to use the default product certificate,
212 // or an android_app_certificate module name in the form ":module".
213 Certificate *string
214
Jiyong Park397e55e2018-10-24 21:09:55 +0900215 Multilib struct {
216 First struct {
217 // List of native libraries whose compile_multilib is "first"
218 Native_shared_libs []string
219 // List of native executables whose compile_multilib is "first"
220 Binaries []string
221 }
222 Both struct {
223 // List of native libraries whose compile_multilib is "both"
224 Native_shared_libs []string
225 // List of native executables whose compile_multilib is "both"
226 Binaries []string
227 }
228 Prefer32 struct {
229 // List of native libraries whose compile_multilib is "prefer32"
230 Native_shared_libs []string
231 // List of native executables whose compile_multilib is "prefer32"
232 Binaries []string
233 }
234 Lib32 struct {
235 // List of native libraries whose compile_multilib is "32"
236 Native_shared_libs []string
237 // List of native executables whose compile_multilib is "32"
238 Binaries []string
239 }
240 Lib64 struct {
241 // List of native libraries whose compile_multilib is "64"
242 Native_shared_libs []string
243 // List of native executables whose compile_multilib is "64"
244 Binaries []string
245 }
246 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900247}
248
Jiyong Park8fd61922018-11-08 02:50:25 +0900249type apexFileClass int
250
251const (
252 etc apexFileClass = iota
253 nativeSharedLib
254 nativeExecutable
255 javaSharedLib
256)
257
258func (class apexFileClass) NameInMake() string {
259 switch class {
260 case etc:
261 return "ETC"
262 case nativeSharedLib:
263 return "SHARED_LIBRARIES"
264 case nativeExecutable:
265 return "EXECUTABLES"
266 case javaSharedLib:
267 return "JAVA_LIBRARIES"
268 default:
269 panic(fmt.Errorf("unkonwn class %d", class))
270 }
271}
272
273type apexFile struct {
274 builtFile android.Path
275 moduleName string
276 archType android.ArchType
277 installDir string
278 class apexFileClass
279}
280
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900281type apexBundle struct {
282 android.ModuleBase
283 android.DefaultableModuleBase
284
285 properties apexBundleProperties
286
Colin Crossa4925902018-11-16 11:36:28 -0800287 bundleModuleFile android.WritablePath
288 outputFile android.WritablePath
289 installDir android.OutputPath
Jiyong Park8fd61922018-11-08 02:50:25 +0900290
291 // list of files to be included in this apex
292 filesInfo []apexFile
293
294 flattened bool
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900295}
296
Jiyong Park397e55e2018-10-24 21:09:55 +0900297func addDependenciesForNativeModules(ctx android.BottomUpMutatorContext,
298 native_shared_libs []string, binaries []string, arch string) {
299 // Use *FarVariation* to be able to depend on modules having
300 // conflicting variations with this module. This is required since
301 // arch variant of an APEX bundle is 'common' but it is 'arm' or 'arm64'
302 // for native shared libs.
303 ctx.AddFarVariationDependencies([]blueprint.Variation{
304 {Mutator: "arch", Variation: arch},
305 {Mutator: "image", Variation: "core"},
306 {Mutator: "link", Variation: "shared"},
307 }, sharedLibTag, native_shared_libs...)
308
309 ctx.AddFarVariationDependencies([]blueprint.Variation{
310 {Mutator: "arch", Variation: arch},
311 {Mutator: "image", Variation: "core"},
312 }, executableTag, binaries...)
313}
314
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900315func (a *apexBundle) DepsMutator(ctx android.BottomUpMutatorContext) {
Jiyong Park397e55e2018-10-24 21:09:55 +0900316 targets := ctx.MultiTargets()
317 has32BitTarget := false
318 for _, target := range targets {
319 if target.Arch.ArchType.Multilib == "lib32" {
320 has32BitTarget = true
321 }
322 }
323 for i, target := range targets {
324 // When multilib.* is omitted for native_shared_libs, it implies
325 // multilib.both.
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900326 ctx.AddFarVariationDependencies([]blueprint.Variation{
Jiyong Park397e55e2018-10-24 21:09:55 +0900327 {Mutator: "arch", Variation: target.String()},
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900328 {Mutator: "image", Variation: "core"},
329 {Mutator: "link", Variation: "shared"},
330 }, sharedLibTag, a.properties.Native_shared_libs...)
331
Jiyong Park397e55e2018-10-24 21:09:55 +0900332 // Add native modules targetting both ABIs
333 addDependenciesForNativeModules(ctx,
334 a.properties.Multilib.Both.Native_shared_libs,
335 a.properties.Multilib.Both.Binaries, target.String())
336
337 if i == 0 {
338 // When multilib.* is omitted for binaries, it implies
339 // multilib.first.
340 ctx.AddFarVariationDependencies([]blueprint.Variation{
341 {Mutator: "arch", Variation: target.String()},
342 {Mutator: "image", Variation: "core"},
343 }, executableTag, a.properties.Binaries...)
344
345 // Add native modules targetting the first ABI
346 addDependenciesForNativeModules(ctx,
347 a.properties.Multilib.First.Native_shared_libs,
348 a.properties.Multilib.First.Binaries, target.String())
349 }
350
351 switch target.Arch.ArchType.Multilib {
352 case "lib32":
353 // Add native modules targetting 32-bit ABI
354 addDependenciesForNativeModules(ctx,
355 a.properties.Multilib.Lib32.Native_shared_libs,
356 a.properties.Multilib.Lib32.Binaries, target.String())
357
358 addDependenciesForNativeModules(ctx,
359 a.properties.Multilib.Prefer32.Native_shared_libs,
360 a.properties.Multilib.Prefer32.Binaries, target.String())
361 case "lib64":
362 // Add native modules targetting 64-bit ABI
363 addDependenciesForNativeModules(ctx,
364 a.properties.Multilib.Lib64.Native_shared_libs,
365 a.properties.Multilib.Lib64.Binaries, target.String())
366
367 if !has32BitTarget {
368 addDependenciesForNativeModules(ctx,
369 a.properties.Multilib.Prefer32.Native_shared_libs,
370 a.properties.Multilib.Prefer32.Binaries, target.String())
371 }
372 }
373
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900374 }
375
Jiyong Parkff1458f2018-10-12 21:49:38 +0900376 ctx.AddFarVariationDependencies([]blueprint.Variation{
377 {Mutator: "arch", Variation: "android_common"},
378 }, javaLibTag, a.properties.Java_libs...)
379
380 ctx.AddFarVariationDependencies([]blueprint.Variation{
381 {Mutator: "arch", Variation: "android_common"},
382 }, prebuiltTag, a.properties.Prebuilts...)
383
384 if String(a.properties.Key) == "" {
385 ctx.ModuleErrorf("key is missing")
386 return
387 }
388 ctx.AddDependency(ctx.Module(), keyTag, String(a.properties.Key))
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900389
390 cert := android.SrcIsModule(String(a.properties.Certificate))
391 if cert != "" {
392 ctx.AddDependency(ctx.Module(), certificateTag, cert)
393 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900394}
395
396func getCopyManifestForNativeLibrary(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
397 // Decide the APEX-local directory by the multilib of the library
398 // In the future, we may query this to the module.
399 switch cc.Arch().ArchType.Multilib {
400 case "lib32":
401 dirInApex = "lib"
402 case "lib64":
403 dirInApex = "lib64"
404 }
405 if !cc.Arch().Native {
406 dirInApex = filepath.Join(dirInApex, cc.Arch().ArchType.String())
407 }
408
409 fileToCopy = cc.OutputFile().Path()
410 return
411}
412
413func getCopyManifestForExecutable(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
414 dirInApex = "bin"
415 fileToCopy = cc.OutputFile().Path()
416 return
417}
418
419func getCopyManifestForJavaLibrary(java *java.Library) (fileToCopy android.Path, dirInApex string) {
420 dirInApex = "javalib"
Jiyong Park8fd61922018-11-08 02:50:25 +0900421 fileToCopy = java.DexJarFile()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900422 return
423}
424
425func getCopyManifestForPrebuiltEtc(prebuilt *android.PrebuiltEtc) (fileToCopy android.Path, dirInApex string) {
426 dirInApex = filepath.Join("etc", prebuilt.SubDir())
427 fileToCopy = prebuilt.OutputFile()
428 return
429}
430
431func (a *apexBundle) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Park8fd61922018-11-08 02:50:25 +0900432 filesInfo := []apexFile{}
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900433
Jiyong Parkff1458f2018-10-12 21:49:38 +0900434 var keyFile android.Path
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900435 var certificate java.Certificate
Jiyong Parkff1458f2018-10-12 21:49:38 +0900436
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900437 ctx.WalkDeps(func(child, parent android.Module) bool {
438 if _, ok := parent.(*apexBundle); ok {
439 // direct dependencies
440 depTag := ctx.OtherModuleDependencyTag(child)
Jiyong Parkff1458f2018-10-12 21:49:38 +0900441 depName := ctx.OtherModuleName(child)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900442 switch depTag {
443 case sharedLibTag:
444 if cc, ok := child.(*cc.Module); ok {
445 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900446 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeSharedLib})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900447 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900448 } else {
449 ctx.PropertyErrorf("native_shared_libs", "%q is not a cc_library or cc_library_shared module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900450 }
451 case executableTag:
452 if cc, ok := child.(*cc.Module); ok {
453 fileToCopy, dirInApex := getCopyManifestForExecutable(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900454 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeExecutable})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900455 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900456 } else {
457 ctx.PropertyErrorf("binaries", "%q is not a cc_binary module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900458 }
459 case javaLibTag:
460 if java, ok := child.(*java.Library); ok {
461 fileToCopy, dirInApex := getCopyManifestForJavaLibrary(java)
Jiyong Park8fd61922018-11-08 02:50:25 +0900462 if fileToCopy == nil {
463 ctx.PropertyErrorf("java_libs", "%q is not configured to be compiled into dex", depName)
464 } else {
465 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, java.Arch().ArchType, dirInApex, javaSharedLib})
466 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900467 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900468 } else {
469 ctx.PropertyErrorf("java_libs", "%q is not a java_library module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900470 }
471 case prebuiltTag:
472 if prebuilt, ok := child.(*android.PrebuiltEtc); ok {
473 fileToCopy, dirInApex := getCopyManifestForPrebuiltEtc(prebuilt)
Jiyong Park8fd61922018-11-08 02:50:25 +0900474 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, prebuilt.Arch().ArchType, dirInApex, etc})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900475 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900476 } else {
477 ctx.PropertyErrorf("prebuilts", "%q is not a prebuilt_etc module", depName)
478 }
479 case keyTag:
480 if key, ok := child.(*apexKey); ok {
481 keyFile = key.private_key_file
482 return false
483 } else {
484 ctx.PropertyErrorf("key", "%q is not an apex_key module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900485 }
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900486 case certificateTag:
487 if dep, ok := child.(*java.AndroidAppCertificate); ok {
488 certificate = dep.Certificate
489 return false
490 } else {
491 ctx.ModuleErrorf("certificate dependency %q must be an android_app_certificate module", depName)
492 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900493 }
494 } else {
495 // indirect dependencies
496 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() && am.IsInstallableToApex() {
497 if cc, ok := child.(*cc.Module); ok {
Jiyong Park8fd61922018-11-08 02:50:25 +0900498 depName := ctx.OtherModuleName(child)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900499 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900500 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeSharedLib})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900501 return true
502 }
503 }
504 }
505 return false
506 })
507
Jiyong Parkfa0a3732018-11-09 05:52:26 +0900508 if keyFile == nil {
509 ctx.PropertyErrorf("key", "private_key for %q could not be found", String(a.properties.Key))
510 return
511 }
512
Jiyong Park8fd61922018-11-08 02:50:25 +0900513 // remove duplicates in filesInfo
514 removeDup := func(filesInfo []apexFile) []apexFile {
515 encountered := make(map[android.Path]bool)
516 result := []apexFile{}
517 for _, f := range filesInfo {
518 if !encountered[f.builtFile] {
519 encountered[f.builtFile] = true
520 result = append(result, f)
521 }
522 }
523 return result
524 }
525 filesInfo = removeDup(filesInfo)
526
527 // to have consistent build rules
528 sort.Slice(filesInfo, func(i, j int) bool {
529 return filesInfo[i].builtFile.String() < filesInfo[j].builtFile.String()
530 })
531
532 // prepend the name of this APEX to the module names. These names will be the names of
533 // modules that will be defined if the APEX is flattened.
534 for i := range filesInfo {
535 filesInfo[i].moduleName = ctx.ModuleName() + "." + filesInfo[i].moduleName
536 }
537
Colin Crossa4925902018-11-16 11:36:28 -0800538 a.flattened = ctx.Config().FlattenApex() && !ctx.Config().UnbundledBuild()
Jiyong Park8fd61922018-11-08 02:50:25 +0900539 a.installDir = android.PathForModuleInstall(ctx, "apex")
540 a.filesInfo = filesInfo
541 if ctx.Config().FlattenApex() {
542 a.buildFlattenedApex(ctx)
543 } else {
544 a.buildUnflattenedApex(ctx, keyFile, certificate)
545 }
546}
547
548func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext, keyFile android.Path, certificate java.Certificate) {
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900549 cert := String(a.properties.Certificate)
550 if cert != "" && android.SrcIsModule(cert) == "" {
551 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
552 certificate = java.Certificate{
553 defaultDir.Join(ctx, cert+".x509.pem"),
554 defaultDir.Join(ctx, cert+".pk8"),
555 }
556 } else if cert == "" {
557 pem, key := ctx.Config().DefaultAppCertificate(ctx)
558 certificate = java.Certificate{pem, key}
559 }
560
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900561 // files and dirs that will be created in apex
Jiyong Park92905d62018-10-11 13:23:09 +0900562 var readOnlyPaths []string
563 var executablePaths []string // this also includes dirs
Jiyong Park8fd61922018-11-08 02:50:25 +0900564 for _, f := range a.filesInfo {
565 pathInApex := filepath.Join(f.installDir, f.builtFile.Base())
566 if f.installDir == "bin" {
Jiyong Park92905d62018-10-11 13:23:09 +0900567 executablePaths = append(executablePaths, pathInApex)
568 } else {
569 readOnlyPaths = append(readOnlyPaths, pathInApex)
570 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900571 if !android.InList(f.installDir, executablePaths) {
572 executablePaths = append(executablePaths, f.installDir)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900573 }
574 }
Jiyong Park92905d62018-10-11 13:23:09 +0900575 sort.Strings(readOnlyPaths)
576 sort.Strings(executablePaths)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900577 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
Colin Crossa4925902018-11-16 11:36:28 -0800578 ctx.Build(pctx, android.BuildParams{
579 Rule: generateFsConfig,
580 Output: cannedFsConfig,
581 Description: "generate fs config",
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900582 Args: map[string]string{
Jiyong Park92905d62018-10-11 13:23:09 +0900583 "ro_paths": strings.Join(readOnlyPaths, " "),
584 "exec_paths": strings.Join(executablePaths, " "),
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900585 },
586 })
587
Dario Freni4abb1dc2018-11-20 18:04:58 +0000588 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900589
Colin Crossa4925902018-11-16 11:36:28 -0800590 fcName := proptools.StringDefault(a.properties.File_contexts, ctx.ModuleName())
Jiyong Park02196572018-11-14 13:54:14 +0900591 fileContextsPath := "system/sepolicy/apex/" + fcName + "-file_contexts"
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900592 fileContextsOptionalPath := android.ExistentPathForSource(ctx, fileContextsPath)
593 if !fileContextsOptionalPath.Valid() {
594 ctx.ModuleErrorf("Cannot find file_contexts file: %q", fileContextsPath)
595 return
596 }
597 fileContexts := fileContextsOptionalPath.Path()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900598
Colin Crossa4925902018-11-16 11:36:28 -0800599 unsignedOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+apexSuffix+".unsigned")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900600
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900601 filesToCopy := []android.Path{}
Jiyong Park8fd61922018-11-08 02:50:25 +0900602 for _, f := range a.filesInfo {
603 filesToCopy = append(filesToCopy, f.builtFile)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900604 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900605
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900606 copyCommands := []string{}
Jiyong Park8fd61922018-11-08 02:50:25 +0900607 for i, src := range filesToCopy {
608 dest := filepath.Join(a.filesInfo[i].installDir, src.Base())
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900609 dest_path := filepath.Join(android.PathForModuleOut(ctx, "image").String(), dest)
610 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(dest_path))
611 copyCommands = append(copyCommands, "cp "+src.String()+" "+dest_path)
612 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900613 implicitInputs := append(android.Paths(nil), filesToCopy...)
Jiyong Parkff1458f2018-10-12 21:49:38 +0900614 implicitInputs = append(implicitInputs, cannedFsConfig, manifest, fileContexts, keyFile)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900615 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
616 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
Colin Crossa4925902018-11-16 11:36:28 -0800617 ctx.Build(pctx, android.BuildParams{
618 Rule: apexRule,
619 Implicits: implicitInputs,
620 Output: unsignedOutputFile,
621 Description: "apex",
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900622 Args: map[string]string{
623 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
624 "image_dir": android.PathForModuleOut(ctx, "image").String(),
625 "copy_commands": strings.Join(copyCommands, " && "),
626 "manifest": manifest.String(),
627 "file_contexts": fileContexts.String(),
628 "canned_fs_config": cannedFsConfig.String(),
Jiyong Parkff1458f2018-10-12 21:49:38 +0900629 "key": keyFile.String(),
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900630 },
631 })
632
Colin Crossa4925902018-11-16 11:36:28 -0800633 var abis []string
634 for _, target := range ctx.MultiTargets() {
635 abis = append(abis, target.Arch.Abi[0])
636 }
637 abis = android.FirstUniqueStrings(abis)
638
639 apexProtoFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".pb"+apexSuffix)
640 bundleModuleFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-base.zip")
641 a.bundleModuleFile = bundleModuleFile
642
643 ctx.Build(pctx, android.BuildParams{
644 Rule: apexProtoConvertRule,
645 Input: unsignedOutputFile,
646 Output: apexProtoFile,
647 Description: "apex proto convert",
648 })
649
650 ctx.Build(pctx, android.BuildParams{
651 Rule: apexBundleRule,
652 Input: apexProtoFile,
653 Output: bundleModuleFile,
654 Description: "apex bundle module",
655 Args: map[string]string{
656 "abi": strings.Join(abis, "."),
657 },
658 })
659
660 a.outputFile = android.PathForModuleOut(ctx, ctx.ModuleName()+apexSuffix)
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900661 ctx.Build(pctx, android.BuildParams{
662 Rule: java.Signapk,
663 Description: "signapk",
664 Output: a.outputFile,
665 Input: unsignedOutputFile,
666 Args: map[string]string{
667 "certificates": strings.Join([]string{certificate.Pem.String(), certificate.Key.String()}, " "),
Jiyong Parkbfe64a12018-11-22 02:51:54 +0900668 "flags": "-a 4096", //alignment
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900669 },
670 })
Jiyong Park8fd61922018-11-08 02:50:25 +0900671}
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900672
Jiyong Park8fd61922018-11-08 02:50:25 +0900673func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
Dario Freni4abb1dc2018-11-20 18:04:58 +0000674 // For flattened APEX, do nothing but make sure that apex_manifest.json file is also copied along
Jiyong Park8fd61922018-11-08 02:50:25 +0900675 // with other ordinary files.
Dario Freni4abb1dc2018-11-20 18:04:58 +0000676 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
677 a.filesInfo = append(a.filesInfo, apexFile{manifest, ctx.ModuleName() + ".apex_manifest.json", android.Common, ".", etc})
Jiyong Park8fd61922018-11-08 02:50:25 +0900678
679 for _, fi := range a.filesInfo {
Colin Crossa4925902018-11-16 11:36:28 -0800680 dir := filepath.Join("apex", ctx.ModuleName(), fi.installDir)
Jiyong Park8fd61922018-11-08 02:50:25 +0900681 ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.builtFile.Base(), fi.builtFile)
682 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900683}
684
685func (a *apexBundle) AndroidMk() android.AndroidMkData {
Jiyong Park8fd61922018-11-08 02:50:25 +0900686 if a.flattened {
687 return android.AndroidMkData{
688 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
689 moduleNames := []string{}
690 for _, fi := range a.filesInfo {
691 if !android.InList(fi.moduleName, moduleNames) {
692 moduleNames = append(moduleNames, fi.moduleName)
693 }
694 }
695 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
696 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
697 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
698 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", strings.Join(moduleNames, " "))
699 fmt.Fprintln(w, "include $(BUILD_PHONY_PACKAGE)")
700
701 for _, fi := range a.filesInfo {
702 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
703 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
704 fmt.Fprintln(w, "LOCAL_MODULE :=", fi.moduleName)
705 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString(), name, fi.installDir))
706 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", fi.builtFile.Base())
707 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", fi.builtFile.String())
708 fmt.Fprintln(w, "LOCAL_MODULE_CLASS :=", fi.class.NameInMake())
709 archStr := fi.archType.String()
710 if archStr != "common" {
711 fmt.Fprintln(w, "LOCAL_MODULE_TARGET_ARCH :=", archStr)
712 }
713 if fi.class == javaSharedLib {
714 fmt.Fprintln(w, "LOCAL_SOONG_DEX_JAR :=", fi.builtFile.String())
715 fmt.Fprintln(w, "LOCAL_DEX_PREOPT := false")
716 fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_java_prebuilt.mk")
717 } else {
718 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
719 }
720 }
721 }}
722 } else {
723 return android.AndroidMkData{
724 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
725 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
726 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
727 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
728 fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC") // do we need a new class?
729 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", a.outputFile.String())
730 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString()))
731 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", name+apexSuffix)
732 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", String(a.properties.Key))
733 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
Colin Crossa4925902018-11-16 11:36:28 -0800734
735 fmt.Fprintln(w, "ALL_MODULES.$(LOCAL_MODULE).BUNDLE :=", a.bundleModuleFile.String())
Jiyong Park8fd61922018-11-08 02:50:25 +0900736 }}
737 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900738}
739
740func apexBundleFactory() android.Module {
741 module := &apexBundle{}
742 module.AddProperties(&module.properties)
Jiyong Park397e55e2018-10-24 21:09:55 +0900743 module.Prefer32(func(ctx android.BaseModuleContext, base *android.ModuleBase,
744 class android.OsClass) bool {
745 return class == android.Device && ctx.Config().DevicePrefer32BitExecutables()
746 })
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900747 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
748 android.InitDefaultableModule(module)
749 return module
750}