blob: 33143d6e0e78c50685ea7f84cc67aa795b389865 [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} ` +
55 `${apexer} --verbose --force --manifest ${manifest} ` +
56 `--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{
72 Command: `${zip2zip} -i $in -o $out image.img:apex/${abi}.img manifest.json:root/manifest.json AndroidManifest.xml:manifest/AndroidManifest.xml`,
73 CommandDeps: []string{"${zip2zip}"},
74 Description: "app bundle",
75 }, "abi")
Jiyong Park48ca7dc2018-10-10 14:01:00 +090076)
77
78var apexSuffix = ".apex"
79
80type dependencyTag struct {
81 blueprint.BaseDependencyTag
82 name string
83}
84
85var (
Jiyong Parkc00cbd92018-10-30 21:20:05 +090086 sharedLibTag = dependencyTag{name: "sharedLib"}
87 executableTag = dependencyTag{name: "executable"}
88 javaLibTag = dependencyTag{name: "javaLib"}
89 prebuiltTag = dependencyTag{name: "prebuilt"}
90 keyTag = dependencyTag{name: "key"}
91 certificateTag = dependencyTag{name: "certificate"}
Jiyong Park48ca7dc2018-10-10 14:01:00 +090092)
93
94func init() {
95 pctx.Import("android/soong/common")
Jiyong Parkc00cbd92018-10-30 21:20:05 +090096 pctx.Import("android/soong/java")
Jiyong Park48ca7dc2018-10-10 14:01:00 +090097 pctx.HostBinToolVariable("apexer", "apexer")
Roland Levillain54bdfda2018-10-05 19:34:32 +010098 // ART minimal builds (using the master-art manifest) do not have the "frameworks/base"
99 // projects, and hence cannot built 'aapt2'. Use the SDK prebuilt instead.
100 hostBinToolVariableWithPrebuilt := func(name, prebuiltDir, tool string) {
101 pctx.VariableFunc(name, func(ctx android.PackageVarContext) string {
102 if !android.ExistentPathForSource(ctx, "frameworks/base").Valid() {
103 return filepath.Join(prebuiltDir, runtime.GOOS, "bin", tool)
104 } else {
105 return pctx.HostBinToolPath(ctx, tool).String()
106 }
107 })
108 }
109 hostBinToolVariableWithPrebuilt("aapt2", "prebuilts/sdk/tools", "aapt2")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900110 pctx.HostBinToolVariable("avbtool", "avbtool")
111 pctx.HostBinToolVariable("e2fsdroid", "e2fsdroid")
112 pctx.HostBinToolVariable("merge_zips", "merge_zips")
113 pctx.HostBinToolVariable("mke2fs", "mke2fs")
114 pctx.HostBinToolVariable("resize2fs", "resize2fs")
115 pctx.HostBinToolVariable("sefcontext_compile", "sefcontext_compile")
116 pctx.HostBinToolVariable("soong_zip", "soong_zip")
Colin Crossa4925902018-11-16 11:36:28 -0800117 pctx.HostBinToolVariable("zip2zip", "zip2zip")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900118 pctx.HostBinToolVariable("zipalign", "zipalign")
119
120 android.RegisterModuleType("apex", apexBundleFactory)
121
122 android.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
123 ctx.TopDown("apex_deps", apexDepsMutator)
124 ctx.BottomUp("apex", apexMutator)
125 })
126}
127
128// maps a module name to set of apex bundle names that the module should be built for
129func apexBundleNamesFor(config android.Config) map[string]map[string]bool {
130 return config.Once("apexBundleNames", func() interface{} {
131 return make(map[string]map[string]bool)
132 }).(map[string]map[string]bool)
133}
134
135// Mark the direct and transitive dependencies of apex bundles so that they
136// can be built for the apex bundles.
137func apexDepsMutator(mctx android.TopDownMutatorContext) {
138 if _, ok := mctx.Module().(*apexBundle); ok {
Colin Crossa4925902018-11-16 11:36:28 -0800139 apexBundleName := mctx.ModuleName()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900140 mctx.WalkDeps(func(child, parent android.Module) bool {
141 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() {
Colin Crossa4925902018-11-16 11:36:28 -0800142 moduleName := mctx.OtherModuleName(am) + "-" + am.Target().String()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900143 bundleNames, ok := apexBundleNamesFor(mctx.Config())[moduleName]
144 if !ok {
145 bundleNames = make(map[string]bool)
146 apexBundleNamesFor(mctx.Config())[moduleName] = bundleNames
147 }
148 bundleNames[apexBundleName] = true
149 return true
150 } else {
151 return false
152 }
153 })
154 }
155}
156
157// Create apex variations if a module is included in APEX(s).
158func apexMutator(mctx android.BottomUpMutatorContext) {
159 if am, ok := mctx.Module().(android.ApexModule); ok && am.CanHaveApexVariants() {
Colin Crossa4925902018-11-16 11:36:28 -0800160 moduleName := mctx.ModuleName() + "-" + am.Target().String()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900161 if bundleNames, ok := apexBundleNamesFor(mctx.Config())[moduleName]; ok {
162 variations := []string{"platform"}
163 for bn := range bundleNames {
164 variations = append(variations, bn)
165 }
166 modules := mctx.CreateVariations(variations...)
167 for i, m := range modules {
168 if i == 0 {
169 continue // platform
170 }
171 m.(android.ApexModule).BuildForApex(variations[i])
172 }
173 }
174 } else if _, ok := mctx.Module().(*apexBundle); ok {
175 // apex bundle itself is mutated so that it and its modules have same
176 // apex variant.
177 apexBundleName := mctx.ModuleName()
178 mctx.CreateVariations(apexBundleName)
179 }
180}
181
182type apexBundleProperties struct {
183 // Json manifest file describing meta info of this APEX bundle. Default:
184 // "manifest.json"
185 Manifest *string
186
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900187 // Determines the file contexts file for setting security context to each file in this APEX bundle.
188 // Specifically, when this is set to <value>, /system/sepolicy/apex/<value>_file_contexts file is
189 // used.
190 // Default: <name_of_this_module>
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900191 File_contexts *string
192
193 // List of native shared libs that are embedded inside this APEX bundle
194 Native_shared_libs []string
195
196 // List of native executables that are embedded inside this APEX bundle
197 Binaries []string
198
199 // List of java libraries that are embedded inside this APEX bundle
200 Java_libs []string
201
202 // List of prebuilt files that are embedded inside this APEX bundle
203 Prebuilts []string
Jiyong Parkff1458f2018-10-12 21:49:38 +0900204
205 // Name of the apex_key module that provides the private key to sign APEX
206 Key *string
Jiyong Park397e55e2018-10-24 21:09:55 +0900207
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900208 // The name of a certificate in the default certificate directory, blank to use the default product certificate,
209 // or an android_app_certificate module name in the form ":module".
210 Certificate *string
211
Jiyong Park397e55e2018-10-24 21:09:55 +0900212 Multilib struct {
213 First struct {
214 // List of native libraries whose compile_multilib is "first"
215 Native_shared_libs []string
216 // List of native executables whose compile_multilib is "first"
217 Binaries []string
218 }
219 Both struct {
220 // List of native libraries whose compile_multilib is "both"
221 Native_shared_libs []string
222 // List of native executables whose compile_multilib is "both"
223 Binaries []string
224 }
225 Prefer32 struct {
226 // List of native libraries whose compile_multilib is "prefer32"
227 Native_shared_libs []string
228 // List of native executables whose compile_multilib is "prefer32"
229 Binaries []string
230 }
231 Lib32 struct {
232 // List of native libraries whose compile_multilib is "32"
233 Native_shared_libs []string
234 // List of native executables whose compile_multilib is "32"
235 Binaries []string
236 }
237 Lib64 struct {
238 // List of native libraries whose compile_multilib is "64"
239 Native_shared_libs []string
240 // List of native executables whose compile_multilib is "64"
241 Binaries []string
242 }
243 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900244}
245
Jiyong Park8fd61922018-11-08 02:50:25 +0900246type apexFileClass int
247
248const (
249 etc apexFileClass = iota
250 nativeSharedLib
251 nativeExecutable
252 javaSharedLib
253)
254
255func (class apexFileClass) NameInMake() string {
256 switch class {
257 case etc:
258 return "ETC"
259 case nativeSharedLib:
260 return "SHARED_LIBRARIES"
261 case nativeExecutable:
262 return "EXECUTABLES"
263 case javaSharedLib:
264 return "JAVA_LIBRARIES"
265 default:
266 panic(fmt.Errorf("unkonwn class %d", class))
267 }
268}
269
270type apexFile struct {
271 builtFile android.Path
272 moduleName string
273 archType android.ArchType
274 installDir string
275 class apexFileClass
276}
277
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900278type apexBundle struct {
279 android.ModuleBase
280 android.DefaultableModuleBase
281
282 properties apexBundleProperties
283
Colin Crossa4925902018-11-16 11:36:28 -0800284 bundleModuleFile android.WritablePath
285 outputFile android.WritablePath
286 installDir android.OutputPath
Jiyong Park8fd61922018-11-08 02:50:25 +0900287
288 // list of files to be included in this apex
289 filesInfo []apexFile
290
291 flattened bool
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900292}
293
Jiyong Park397e55e2018-10-24 21:09:55 +0900294func addDependenciesForNativeModules(ctx android.BottomUpMutatorContext,
295 native_shared_libs []string, binaries []string, arch string) {
296 // Use *FarVariation* to be able to depend on modules having
297 // conflicting variations with this module. This is required since
298 // arch variant of an APEX bundle is 'common' but it is 'arm' or 'arm64'
299 // for native shared libs.
300 ctx.AddFarVariationDependencies([]blueprint.Variation{
301 {Mutator: "arch", Variation: arch},
302 {Mutator: "image", Variation: "core"},
303 {Mutator: "link", Variation: "shared"},
304 }, sharedLibTag, native_shared_libs...)
305
306 ctx.AddFarVariationDependencies([]blueprint.Variation{
307 {Mutator: "arch", Variation: arch},
308 {Mutator: "image", Variation: "core"},
309 }, executableTag, binaries...)
310}
311
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900312func (a *apexBundle) DepsMutator(ctx android.BottomUpMutatorContext) {
Jiyong Park397e55e2018-10-24 21:09:55 +0900313 targets := ctx.MultiTargets()
314 has32BitTarget := false
315 for _, target := range targets {
316 if target.Arch.ArchType.Multilib == "lib32" {
317 has32BitTarget = true
318 }
319 }
320 for i, target := range targets {
321 // When multilib.* is omitted for native_shared_libs, it implies
322 // multilib.both.
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900323 ctx.AddFarVariationDependencies([]blueprint.Variation{
Jiyong Park397e55e2018-10-24 21:09:55 +0900324 {Mutator: "arch", Variation: target.String()},
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900325 {Mutator: "image", Variation: "core"},
326 {Mutator: "link", Variation: "shared"},
327 }, sharedLibTag, a.properties.Native_shared_libs...)
328
Jiyong Park397e55e2018-10-24 21:09:55 +0900329 // Add native modules targetting both ABIs
330 addDependenciesForNativeModules(ctx,
331 a.properties.Multilib.Both.Native_shared_libs,
332 a.properties.Multilib.Both.Binaries, target.String())
333
334 if i == 0 {
335 // When multilib.* is omitted for binaries, it implies
336 // multilib.first.
337 ctx.AddFarVariationDependencies([]blueprint.Variation{
338 {Mutator: "arch", Variation: target.String()},
339 {Mutator: "image", Variation: "core"},
340 }, executableTag, a.properties.Binaries...)
341
342 // Add native modules targetting the first ABI
343 addDependenciesForNativeModules(ctx,
344 a.properties.Multilib.First.Native_shared_libs,
345 a.properties.Multilib.First.Binaries, target.String())
346 }
347
348 switch target.Arch.ArchType.Multilib {
349 case "lib32":
350 // Add native modules targetting 32-bit ABI
351 addDependenciesForNativeModules(ctx,
352 a.properties.Multilib.Lib32.Native_shared_libs,
353 a.properties.Multilib.Lib32.Binaries, target.String())
354
355 addDependenciesForNativeModules(ctx,
356 a.properties.Multilib.Prefer32.Native_shared_libs,
357 a.properties.Multilib.Prefer32.Binaries, target.String())
358 case "lib64":
359 // Add native modules targetting 64-bit ABI
360 addDependenciesForNativeModules(ctx,
361 a.properties.Multilib.Lib64.Native_shared_libs,
362 a.properties.Multilib.Lib64.Binaries, target.String())
363
364 if !has32BitTarget {
365 addDependenciesForNativeModules(ctx,
366 a.properties.Multilib.Prefer32.Native_shared_libs,
367 a.properties.Multilib.Prefer32.Binaries, target.String())
368 }
369 }
370
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900371 }
372
Jiyong Parkff1458f2018-10-12 21:49:38 +0900373 ctx.AddFarVariationDependencies([]blueprint.Variation{
374 {Mutator: "arch", Variation: "android_common"},
375 }, javaLibTag, a.properties.Java_libs...)
376
377 ctx.AddFarVariationDependencies([]blueprint.Variation{
378 {Mutator: "arch", Variation: "android_common"},
379 }, prebuiltTag, a.properties.Prebuilts...)
380
381 if String(a.properties.Key) == "" {
382 ctx.ModuleErrorf("key is missing")
383 return
384 }
385 ctx.AddDependency(ctx.Module(), keyTag, String(a.properties.Key))
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900386
387 cert := android.SrcIsModule(String(a.properties.Certificate))
388 if cert != "" {
389 ctx.AddDependency(ctx.Module(), certificateTag, cert)
390 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900391}
392
393func getCopyManifestForNativeLibrary(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
394 // Decide the APEX-local directory by the multilib of the library
395 // In the future, we may query this to the module.
396 switch cc.Arch().ArchType.Multilib {
397 case "lib32":
398 dirInApex = "lib"
399 case "lib64":
400 dirInApex = "lib64"
401 }
402 if !cc.Arch().Native {
403 dirInApex = filepath.Join(dirInApex, cc.Arch().ArchType.String())
404 }
405
406 fileToCopy = cc.OutputFile().Path()
407 return
408}
409
410func getCopyManifestForExecutable(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
411 dirInApex = "bin"
412 fileToCopy = cc.OutputFile().Path()
413 return
414}
415
416func getCopyManifestForJavaLibrary(java *java.Library) (fileToCopy android.Path, dirInApex string) {
417 dirInApex = "javalib"
Jiyong Park8fd61922018-11-08 02:50:25 +0900418 fileToCopy = java.DexJarFile()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900419 return
420}
421
422func getCopyManifestForPrebuiltEtc(prebuilt *android.PrebuiltEtc) (fileToCopy android.Path, dirInApex string) {
423 dirInApex = filepath.Join("etc", prebuilt.SubDir())
424 fileToCopy = prebuilt.OutputFile()
425 return
426}
427
428func (a *apexBundle) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Park8fd61922018-11-08 02:50:25 +0900429 filesInfo := []apexFile{}
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900430
Jiyong Parkff1458f2018-10-12 21:49:38 +0900431 var keyFile android.Path
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900432 var certificate java.Certificate
Jiyong Parkff1458f2018-10-12 21:49:38 +0900433
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900434 ctx.WalkDeps(func(child, parent android.Module) bool {
435 if _, ok := parent.(*apexBundle); ok {
436 // direct dependencies
437 depTag := ctx.OtherModuleDependencyTag(child)
Jiyong Parkff1458f2018-10-12 21:49:38 +0900438 depName := ctx.OtherModuleName(child)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900439 switch depTag {
440 case sharedLibTag:
441 if cc, ok := child.(*cc.Module); ok {
442 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900443 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeSharedLib})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900444 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900445 } else {
446 ctx.PropertyErrorf("native_shared_libs", "%q is not a cc_library or cc_library_shared module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900447 }
448 case executableTag:
449 if cc, ok := child.(*cc.Module); ok {
450 fileToCopy, dirInApex := getCopyManifestForExecutable(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900451 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeExecutable})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900452 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900453 } else {
454 ctx.PropertyErrorf("binaries", "%q is not a cc_binary module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900455 }
456 case javaLibTag:
457 if java, ok := child.(*java.Library); ok {
458 fileToCopy, dirInApex := getCopyManifestForJavaLibrary(java)
Jiyong Park8fd61922018-11-08 02:50:25 +0900459 if fileToCopy == nil {
460 ctx.PropertyErrorf("java_libs", "%q is not configured to be compiled into dex", depName)
461 } else {
462 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, java.Arch().ArchType, dirInApex, javaSharedLib})
463 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900464 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900465 } else {
466 ctx.PropertyErrorf("java_libs", "%q is not a java_library module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900467 }
468 case prebuiltTag:
469 if prebuilt, ok := child.(*android.PrebuiltEtc); ok {
470 fileToCopy, dirInApex := getCopyManifestForPrebuiltEtc(prebuilt)
Jiyong Park8fd61922018-11-08 02:50:25 +0900471 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, prebuilt.Arch().ArchType, dirInApex, etc})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900472 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900473 } else {
474 ctx.PropertyErrorf("prebuilts", "%q is not a prebuilt_etc module", depName)
475 }
476 case keyTag:
477 if key, ok := child.(*apexKey); ok {
478 keyFile = key.private_key_file
479 return false
480 } else {
481 ctx.PropertyErrorf("key", "%q is not an apex_key module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900482 }
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900483 case certificateTag:
484 if dep, ok := child.(*java.AndroidAppCertificate); ok {
485 certificate = dep.Certificate
486 return false
487 } else {
488 ctx.ModuleErrorf("certificate dependency %q must be an android_app_certificate module", depName)
489 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900490 }
491 } else {
492 // indirect dependencies
493 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() && am.IsInstallableToApex() {
494 if cc, ok := child.(*cc.Module); ok {
Jiyong Park8fd61922018-11-08 02:50:25 +0900495 depName := ctx.OtherModuleName(child)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900496 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900497 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeSharedLib})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900498 return true
499 }
500 }
501 }
502 return false
503 })
504
Jiyong Parkfa0a3732018-11-09 05:52:26 +0900505 if keyFile == nil {
506 ctx.PropertyErrorf("key", "private_key for %q could not be found", String(a.properties.Key))
507 return
508 }
509
Jiyong Park8fd61922018-11-08 02:50:25 +0900510 // remove duplicates in filesInfo
511 removeDup := func(filesInfo []apexFile) []apexFile {
512 encountered := make(map[android.Path]bool)
513 result := []apexFile{}
514 for _, f := range filesInfo {
515 if !encountered[f.builtFile] {
516 encountered[f.builtFile] = true
517 result = append(result, f)
518 }
519 }
520 return result
521 }
522 filesInfo = removeDup(filesInfo)
523
524 // to have consistent build rules
525 sort.Slice(filesInfo, func(i, j int) bool {
526 return filesInfo[i].builtFile.String() < filesInfo[j].builtFile.String()
527 })
528
529 // prepend the name of this APEX to the module names. These names will be the names of
530 // modules that will be defined if the APEX is flattened.
531 for i := range filesInfo {
532 filesInfo[i].moduleName = ctx.ModuleName() + "." + filesInfo[i].moduleName
533 }
534
Colin Crossa4925902018-11-16 11:36:28 -0800535 a.flattened = ctx.Config().FlattenApex() && !ctx.Config().UnbundledBuild()
Jiyong Park8fd61922018-11-08 02:50:25 +0900536 a.installDir = android.PathForModuleInstall(ctx, "apex")
537 a.filesInfo = filesInfo
538 if ctx.Config().FlattenApex() {
539 a.buildFlattenedApex(ctx)
540 } else {
541 a.buildUnflattenedApex(ctx, keyFile, certificate)
542 }
543}
544
545func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext, keyFile android.Path, certificate java.Certificate) {
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900546 cert := String(a.properties.Certificate)
547 if cert != "" && android.SrcIsModule(cert) == "" {
548 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
549 certificate = java.Certificate{
550 defaultDir.Join(ctx, cert+".x509.pem"),
551 defaultDir.Join(ctx, cert+".pk8"),
552 }
553 } else if cert == "" {
554 pem, key := ctx.Config().DefaultAppCertificate(ctx)
555 certificate = java.Certificate{pem, key}
556 }
557
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900558 // files and dirs that will be created in apex
Jiyong Park92905d62018-10-11 13:23:09 +0900559 var readOnlyPaths []string
560 var executablePaths []string // this also includes dirs
Jiyong Park8fd61922018-11-08 02:50:25 +0900561 for _, f := range a.filesInfo {
562 pathInApex := filepath.Join(f.installDir, f.builtFile.Base())
563 if f.installDir == "bin" {
Jiyong Park92905d62018-10-11 13:23:09 +0900564 executablePaths = append(executablePaths, pathInApex)
565 } else {
566 readOnlyPaths = append(readOnlyPaths, pathInApex)
567 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900568 if !android.InList(f.installDir, executablePaths) {
569 executablePaths = append(executablePaths, f.installDir)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900570 }
571 }
Jiyong Park92905d62018-10-11 13:23:09 +0900572 sort.Strings(readOnlyPaths)
573 sort.Strings(executablePaths)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900574 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
Colin Crossa4925902018-11-16 11:36:28 -0800575 ctx.Build(pctx, android.BuildParams{
576 Rule: generateFsConfig,
577 Output: cannedFsConfig,
578 Description: "generate fs config",
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900579 Args: map[string]string{
Jiyong Park92905d62018-10-11 13:23:09 +0900580 "ro_paths": strings.Join(readOnlyPaths, " "),
581 "exec_paths": strings.Join(executablePaths, " "),
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900582 },
583 })
584
585 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "manifest.json"))
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900586
Colin Crossa4925902018-11-16 11:36:28 -0800587 fcName := proptools.StringDefault(a.properties.File_contexts, ctx.ModuleName())
Jiyong Park02196572018-11-14 13:54:14 +0900588 fileContextsPath := "system/sepolicy/apex/" + fcName + "-file_contexts"
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900589 fileContextsOptionalPath := android.ExistentPathForSource(ctx, fileContextsPath)
590 if !fileContextsOptionalPath.Valid() {
591 ctx.ModuleErrorf("Cannot find file_contexts file: %q", fileContextsPath)
592 return
593 }
594 fileContexts := fileContextsOptionalPath.Path()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900595
Colin Crossa4925902018-11-16 11:36:28 -0800596 unsignedOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+apexSuffix+".unsigned")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900597
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900598 filesToCopy := []android.Path{}
Jiyong Park8fd61922018-11-08 02:50:25 +0900599 for _, f := range a.filesInfo {
600 filesToCopy = append(filesToCopy, f.builtFile)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900601 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900602
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900603 copyCommands := []string{}
Jiyong Park8fd61922018-11-08 02:50:25 +0900604 for i, src := range filesToCopy {
605 dest := filepath.Join(a.filesInfo[i].installDir, src.Base())
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900606 dest_path := filepath.Join(android.PathForModuleOut(ctx, "image").String(), dest)
607 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(dest_path))
608 copyCommands = append(copyCommands, "cp "+src.String()+" "+dest_path)
609 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900610 implicitInputs := append(android.Paths(nil), filesToCopy...)
Jiyong Parkff1458f2018-10-12 21:49:38 +0900611 implicitInputs = append(implicitInputs, cannedFsConfig, manifest, fileContexts, keyFile)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900612 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
613 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
Colin Crossa4925902018-11-16 11:36:28 -0800614 ctx.Build(pctx, android.BuildParams{
615 Rule: apexRule,
616 Implicits: implicitInputs,
617 Output: unsignedOutputFile,
618 Description: "apex",
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900619 Args: map[string]string{
620 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
621 "image_dir": android.PathForModuleOut(ctx, "image").String(),
622 "copy_commands": strings.Join(copyCommands, " && "),
623 "manifest": manifest.String(),
624 "file_contexts": fileContexts.String(),
625 "canned_fs_config": cannedFsConfig.String(),
Jiyong Parkff1458f2018-10-12 21:49:38 +0900626 "key": keyFile.String(),
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900627 },
628 })
629
Colin Crossa4925902018-11-16 11:36:28 -0800630 var abis []string
631 for _, target := range ctx.MultiTargets() {
632 abis = append(abis, target.Arch.Abi[0])
633 }
634 abis = android.FirstUniqueStrings(abis)
635
636 apexProtoFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".pb"+apexSuffix)
637 bundleModuleFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-base.zip")
638 a.bundleModuleFile = bundleModuleFile
639
640 ctx.Build(pctx, android.BuildParams{
641 Rule: apexProtoConvertRule,
642 Input: unsignedOutputFile,
643 Output: apexProtoFile,
644 Description: "apex proto convert",
645 })
646
647 ctx.Build(pctx, android.BuildParams{
648 Rule: apexBundleRule,
649 Input: apexProtoFile,
650 Output: bundleModuleFile,
651 Description: "apex bundle module",
652 Args: map[string]string{
653 "abi": strings.Join(abis, "."),
654 },
655 })
656
657 a.outputFile = android.PathForModuleOut(ctx, ctx.ModuleName()+apexSuffix)
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900658 ctx.Build(pctx, android.BuildParams{
659 Rule: java.Signapk,
660 Description: "signapk",
661 Output: a.outputFile,
662 Input: unsignedOutputFile,
663 Args: map[string]string{
664 "certificates": strings.Join([]string{certificate.Pem.String(), certificate.Key.String()}, " "),
665 },
666 })
Jiyong Park8fd61922018-11-08 02:50:25 +0900667}
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900668
Jiyong Park8fd61922018-11-08 02:50:25 +0900669func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
670 // For flattened APEX, do nothing but make sure that manifest.json file is also copied along
671 // with other ordinary files.
672 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "manifest.json"))
Colin Crossa4925902018-11-16 11:36:28 -0800673 a.filesInfo = append(a.filesInfo, apexFile{manifest, ctx.ModuleName() + ".manifest.json", android.Common, ".", etc})
Jiyong Park8fd61922018-11-08 02:50:25 +0900674
675 for _, fi := range a.filesInfo {
Colin Crossa4925902018-11-16 11:36:28 -0800676 dir := filepath.Join("apex", ctx.ModuleName(), fi.installDir)
Jiyong Park8fd61922018-11-08 02:50:25 +0900677 ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.builtFile.Base(), fi.builtFile)
678 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900679}
680
681func (a *apexBundle) AndroidMk() android.AndroidMkData {
Jiyong Park8fd61922018-11-08 02:50:25 +0900682 if a.flattened {
683 return android.AndroidMkData{
684 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
685 moduleNames := []string{}
686 for _, fi := range a.filesInfo {
687 if !android.InList(fi.moduleName, moduleNames) {
688 moduleNames = append(moduleNames, fi.moduleName)
689 }
690 }
691 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
692 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
693 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
694 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", strings.Join(moduleNames, " "))
695 fmt.Fprintln(w, "include $(BUILD_PHONY_PACKAGE)")
696
697 for _, fi := range a.filesInfo {
698 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
699 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
700 fmt.Fprintln(w, "LOCAL_MODULE :=", fi.moduleName)
701 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString(), name, fi.installDir))
702 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", fi.builtFile.Base())
703 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", fi.builtFile.String())
704 fmt.Fprintln(w, "LOCAL_MODULE_CLASS :=", fi.class.NameInMake())
705 archStr := fi.archType.String()
706 if archStr != "common" {
707 fmt.Fprintln(w, "LOCAL_MODULE_TARGET_ARCH :=", archStr)
708 }
709 if fi.class == javaSharedLib {
710 fmt.Fprintln(w, "LOCAL_SOONG_DEX_JAR :=", fi.builtFile.String())
711 fmt.Fprintln(w, "LOCAL_DEX_PREOPT := false")
712 fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_java_prebuilt.mk")
713 } else {
714 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
715 }
716 }
717 }}
718 } else {
719 return android.AndroidMkData{
720 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
721 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
722 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
723 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
724 fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC") // do we need a new class?
725 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", a.outputFile.String())
726 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString()))
727 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", name+apexSuffix)
728 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", String(a.properties.Key))
729 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
Colin Crossa4925902018-11-16 11:36:28 -0800730
731 fmt.Fprintln(w, "ALL_MODULES.$(LOCAL_MODULE).BUNDLE :=", a.bundleModuleFile.String())
Jiyong Park8fd61922018-11-08 02:50:25 +0900732 }}
733 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900734}
735
736func apexBundleFactory() android.Module {
737 module := &apexBundle{}
738 module.AddProperties(&module.properties)
Jiyong Park397e55e2018-10-24 21:09:55 +0900739 module.Prefer32(func(ctx android.BaseModuleContext, base *android.ModuleBase,
740 class android.OsClass) bool {
741 return class == android.Device && ctx.Config().DevicePrefer32BitExecutables()
742 })
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900743 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
744 android.InitDefaultableModule(module)
745 return module
746}