blob: 52fa561da92d3c7c408b5d31b41adf6ecd392255 [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
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900131// Mark the direct and transitive dependencies of apex bundles so that they
132// can be built for the apex bundles.
133func apexDepsMutator(mctx android.TopDownMutatorContext) {
134 if _, ok := mctx.Module().(*apexBundle); ok {
Colin Crossa4925902018-11-16 11:36:28 -0800135 apexBundleName := mctx.ModuleName()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900136 mctx.WalkDeps(func(child, parent android.Module) bool {
137 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() {
Colin Crossa4925902018-11-16 11:36:28 -0800138 moduleName := mctx.OtherModuleName(am) + "-" + am.Target().String()
Jiyong Park25fc6a92018-11-18 18:02:45 +0900139 // If the parent is apexBundle, this child is directly depended.
140 _, directDep := parent.(*apexBundle)
141 android.BuildModuleForApexBundle(mctx, moduleName, apexBundleName, directDep)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900142 return true
143 } else {
144 return false
145 }
146 })
147 }
148}
149
150// Create apex variations if a module is included in APEX(s).
151func apexMutator(mctx android.BottomUpMutatorContext) {
152 if am, ok := mctx.Module().(android.ApexModule); ok && am.CanHaveApexVariants() {
Colin Crossa4925902018-11-16 11:36:28 -0800153 moduleName := mctx.ModuleName() + "-" + am.Target().String()
Jiyong Park25fc6a92018-11-18 18:02:45 +0900154 bundleNames := android.GetApexBundlesForModule(mctx, moduleName)
155 if len(bundleNames) > 0 {
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900156 variations := []string{"platform"}
157 for bn := range bundleNames {
158 variations = append(variations, bn)
159 }
160 modules := mctx.CreateVariations(variations...)
161 for i, m := range modules {
162 if i == 0 {
163 continue // platform
164 }
165 m.(android.ApexModule).BuildForApex(variations[i])
166 }
167 }
168 } else if _, ok := mctx.Module().(*apexBundle); ok {
169 // apex bundle itself is mutated so that it and its modules have same
170 // apex variant.
171 apexBundleName := mctx.ModuleName()
172 mctx.CreateVariations(apexBundleName)
173 }
174}
175
176type apexBundleProperties struct {
177 // Json manifest file describing meta info of this APEX bundle. Default:
Dario Freni4abb1dc2018-11-20 18:04:58 +0000178 // "apex_manifest.json"
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900179 Manifest *string
180
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900181 // Determines the file contexts file for setting security context to each file in this APEX bundle.
182 // Specifically, when this is set to <value>, /system/sepolicy/apex/<value>_file_contexts file is
183 // used.
184 // Default: <name_of_this_module>
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900185 File_contexts *string
186
187 // List of native shared libs that are embedded inside this APEX bundle
188 Native_shared_libs []string
189
190 // List of native executables that are embedded inside this APEX bundle
191 Binaries []string
192
193 // List of java libraries that are embedded inside this APEX bundle
194 Java_libs []string
195
196 // List of prebuilt files that are embedded inside this APEX bundle
197 Prebuilts []string
Jiyong Parkff1458f2018-10-12 21:49:38 +0900198
199 // Name of the apex_key module that provides the private key to sign APEX
200 Key *string
Jiyong Park397e55e2018-10-24 21:09:55 +0900201
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900202 // The name of a certificate in the default certificate directory, blank to use the default product certificate,
203 // or an android_app_certificate module name in the form ":module".
204 Certificate *string
205
Jiyong Park397e55e2018-10-24 21:09:55 +0900206 Multilib struct {
207 First struct {
208 // List of native libraries whose compile_multilib is "first"
209 Native_shared_libs []string
210 // List of native executables whose compile_multilib is "first"
211 Binaries []string
212 }
213 Both struct {
214 // List of native libraries whose compile_multilib is "both"
215 Native_shared_libs []string
216 // List of native executables whose compile_multilib is "both"
217 Binaries []string
218 }
219 Prefer32 struct {
220 // List of native libraries whose compile_multilib is "prefer32"
221 Native_shared_libs []string
222 // List of native executables whose compile_multilib is "prefer32"
223 Binaries []string
224 }
225 Lib32 struct {
226 // List of native libraries whose compile_multilib is "32"
227 Native_shared_libs []string
228 // List of native executables whose compile_multilib is "32"
229 Binaries []string
230 }
231 Lib64 struct {
232 // List of native libraries whose compile_multilib is "64"
233 Native_shared_libs []string
234 // List of native executables whose compile_multilib is "64"
235 Binaries []string
236 }
237 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900238}
239
Jiyong Park8fd61922018-11-08 02:50:25 +0900240type apexFileClass int
241
242const (
243 etc apexFileClass = iota
244 nativeSharedLib
245 nativeExecutable
246 javaSharedLib
247)
248
249func (class apexFileClass) NameInMake() string {
250 switch class {
251 case etc:
252 return "ETC"
253 case nativeSharedLib:
254 return "SHARED_LIBRARIES"
255 case nativeExecutable:
256 return "EXECUTABLES"
257 case javaSharedLib:
258 return "JAVA_LIBRARIES"
259 default:
260 panic(fmt.Errorf("unkonwn class %d", class))
261 }
262}
263
264type apexFile struct {
265 builtFile android.Path
266 moduleName string
267 archType android.ArchType
268 installDir string
269 class apexFileClass
270}
271
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900272type apexBundle struct {
273 android.ModuleBase
274 android.DefaultableModuleBase
275
276 properties apexBundleProperties
277
Colin Crossa4925902018-11-16 11:36:28 -0800278 bundleModuleFile android.WritablePath
279 outputFile android.WritablePath
280 installDir android.OutputPath
Jiyong Park8fd61922018-11-08 02:50:25 +0900281
282 // list of files to be included in this apex
283 filesInfo []apexFile
284
285 flattened bool
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900286}
287
Jiyong Park397e55e2018-10-24 21:09:55 +0900288func addDependenciesForNativeModules(ctx android.BottomUpMutatorContext,
289 native_shared_libs []string, binaries []string, arch string) {
290 // Use *FarVariation* to be able to depend on modules having
291 // conflicting variations with this module. This is required since
292 // arch variant of an APEX bundle is 'common' but it is 'arm' or 'arm64'
293 // for native shared libs.
294 ctx.AddFarVariationDependencies([]blueprint.Variation{
295 {Mutator: "arch", Variation: arch},
296 {Mutator: "image", Variation: "core"},
297 {Mutator: "link", Variation: "shared"},
298 }, sharedLibTag, native_shared_libs...)
299
300 ctx.AddFarVariationDependencies([]blueprint.Variation{
301 {Mutator: "arch", Variation: arch},
302 {Mutator: "image", Variation: "core"},
303 }, executableTag, binaries...)
304}
305
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900306func (a *apexBundle) DepsMutator(ctx android.BottomUpMutatorContext) {
Jiyong Park397e55e2018-10-24 21:09:55 +0900307 targets := ctx.MultiTargets()
308 has32BitTarget := false
309 for _, target := range targets {
310 if target.Arch.ArchType.Multilib == "lib32" {
311 has32BitTarget = true
312 }
313 }
314 for i, target := range targets {
315 // When multilib.* is omitted for native_shared_libs, it implies
316 // multilib.both.
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900317 ctx.AddFarVariationDependencies([]blueprint.Variation{
Jiyong Park397e55e2018-10-24 21:09:55 +0900318 {Mutator: "arch", Variation: target.String()},
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900319 {Mutator: "image", Variation: "core"},
320 {Mutator: "link", Variation: "shared"},
321 }, sharedLibTag, a.properties.Native_shared_libs...)
322
Jiyong Park397e55e2018-10-24 21:09:55 +0900323 // Add native modules targetting both ABIs
324 addDependenciesForNativeModules(ctx,
325 a.properties.Multilib.Both.Native_shared_libs,
326 a.properties.Multilib.Both.Binaries, target.String())
327
328 if i == 0 {
329 // When multilib.* is omitted for binaries, it implies
330 // multilib.first.
331 ctx.AddFarVariationDependencies([]blueprint.Variation{
332 {Mutator: "arch", Variation: target.String()},
333 {Mutator: "image", Variation: "core"},
334 }, executableTag, a.properties.Binaries...)
335
336 // Add native modules targetting the first ABI
337 addDependenciesForNativeModules(ctx,
338 a.properties.Multilib.First.Native_shared_libs,
339 a.properties.Multilib.First.Binaries, target.String())
340 }
341
342 switch target.Arch.ArchType.Multilib {
343 case "lib32":
344 // Add native modules targetting 32-bit ABI
345 addDependenciesForNativeModules(ctx,
346 a.properties.Multilib.Lib32.Native_shared_libs,
347 a.properties.Multilib.Lib32.Binaries, target.String())
348
349 addDependenciesForNativeModules(ctx,
350 a.properties.Multilib.Prefer32.Native_shared_libs,
351 a.properties.Multilib.Prefer32.Binaries, target.String())
352 case "lib64":
353 // Add native modules targetting 64-bit ABI
354 addDependenciesForNativeModules(ctx,
355 a.properties.Multilib.Lib64.Native_shared_libs,
356 a.properties.Multilib.Lib64.Binaries, target.String())
357
358 if !has32BitTarget {
359 addDependenciesForNativeModules(ctx,
360 a.properties.Multilib.Prefer32.Native_shared_libs,
361 a.properties.Multilib.Prefer32.Binaries, target.String())
362 }
363 }
364
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900365 }
366
Jiyong Parkff1458f2018-10-12 21:49:38 +0900367 ctx.AddFarVariationDependencies([]blueprint.Variation{
368 {Mutator: "arch", Variation: "android_common"},
369 }, javaLibTag, a.properties.Java_libs...)
370
371 ctx.AddFarVariationDependencies([]blueprint.Variation{
372 {Mutator: "arch", Variation: "android_common"},
373 }, prebuiltTag, a.properties.Prebuilts...)
374
375 if String(a.properties.Key) == "" {
376 ctx.ModuleErrorf("key is missing")
377 return
378 }
379 ctx.AddDependency(ctx.Module(), keyTag, String(a.properties.Key))
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900380
381 cert := android.SrcIsModule(String(a.properties.Certificate))
382 if cert != "" {
383 ctx.AddDependency(ctx.Module(), certificateTag, cert)
384 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900385}
386
387func getCopyManifestForNativeLibrary(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
388 // Decide the APEX-local directory by the multilib of the library
389 // In the future, we may query this to the module.
390 switch cc.Arch().ArchType.Multilib {
391 case "lib32":
392 dirInApex = "lib"
393 case "lib64":
394 dirInApex = "lib64"
395 }
396 if !cc.Arch().Native {
397 dirInApex = filepath.Join(dirInApex, cc.Arch().ArchType.String())
398 }
399
400 fileToCopy = cc.OutputFile().Path()
401 return
402}
403
404func getCopyManifestForExecutable(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
405 dirInApex = "bin"
406 fileToCopy = cc.OutputFile().Path()
407 return
408}
409
410func getCopyManifestForJavaLibrary(java *java.Library) (fileToCopy android.Path, dirInApex string) {
411 dirInApex = "javalib"
Jiyong Park8fd61922018-11-08 02:50:25 +0900412 fileToCopy = java.DexJarFile()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900413 return
414}
415
416func getCopyManifestForPrebuiltEtc(prebuilt *android.PrebuiltEtc) (fileToCopy android.Path, dirInApex string) {
417 dirInApex = filepath.Join("etc", prebuilt.SubDir())
418 fileToCopy = prebuilt.OutputFile()
419 return
420}
421
422func (a *apexBundle) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Park8fd61922018-11-08 02:50:25 +0900423 filesInfo := []apexFile{}
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900424
Jiyong Parkff1458f2018-10-12 21:49:38 +0900425 var keyFile android.Path
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900426 var certificate java.Certificate
Jiyong Parkff1458f2018-10-12 21:49:38 +0900427
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900428 ctx.WalkDeps(func(child, parent android.Module) bool {
429 if _, ok := parent.(*apexBundle); ok {
430 // direct dependencies
431 depTag := ctx.OtherModuleDependencyTag(child)
Jiyong Parkff1458f2018-10-12 21:49:38 +0900432 depName := ctx.OtherModuleName(child)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900433 switch depTag {
434 case sharedLibTag:
435 if cc, ok := child.(*cc.Module); ok {
436 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900437 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeSharedLib})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900438 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900439 } else {
440 ctx.PropertyErrorf("native_shared_libs", "%q is not a cc_library or cc_library_shared module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900441 }
442 case executableTag:
443 if cc, ok := child.(*cc.Module); ok {
444 fileToCopy, dirInApex := getCopyManifestForExecutable(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900445 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeExecutable})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900446 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900447 } else {
448 ctx.PropertyErrorf("binaries", "%q is not a cc_binary module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900449 }
450 case javaLibTag:
451 if java, ok := child.(*java.Library); ok {
452 fileToCopy, dirInApex := getCopyManifestForJavaLibrary(java)
Jiyong Park8fd61922018-11-08 02:50:25 +0900453 if fileToCopy == nil {
454 ctx.PropertyErrorf("java_libs", "%q is not configured to be compiled into dex", depName)
455 } else {
456 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, java.Arch().ArchType, dirInApex, javaSharedLib})
457 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900458 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900459 } else {
460 ctx.PropertyErrorf("java_libs", "%q is not a java_library module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900461 }
462 case prebuiltTag:
463 if prebuilt, ok := child.(*android.PrebuiltEtc); ok {
464 fileToCopy, dirInApex := getCopyManifestForPrebuiltEtc(prebuilt)
Jiyong Park8fd61922018-11-08 02:50:25 +0900465 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, prebuilt.Arch().ArchType, dirInApex, etc})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900466 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900467 } else {
468 ctx.PropertyErrorf("prebuilts", "%q is not a prebuilt_etc module", depName)
469 }
470 case keyTag:
471 if key, ok := child.(*apexKey); ok {
472 keyFile = key.private_key_file
473 return false
474 } else {
475 ctx.PropertyErrorf("key", "%q is not an apex_key module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900476 }
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900477 case certificateTag:
478 if dep, ok := child.(*java.AndroidAppCertificate); ok {
479 certificate = dep.Certificate
480 return false
481 } else {
482 ctx.ModuleErrorf("certificate dependency %q must be an android_app_certificate module", depName)
483 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900484 }
485 } else {
486 // indirect dependencies
487 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() && am.IsInstallableToApex() {
488 if cc, ok := child.(*cc.Module); ok {
Jiyong Park25fc6a92018-11-18 18:02:45 +0900489 if cc.IsStubs() || cc.HasStubsVariants() {
490 return false
491 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900492 depName := ctx.OtherModuleName(child)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900493 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
Jiyong Park8fd61922018-11-08 02:50:25 +0900494 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, cc.Arch().ArchType, dirInApex, nativeSharedLib})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900495 return true
496 }
497 }
498 }
499 return false
500 })
501
Jiyong Parkfa0a3732018-11-09 05:52:26 +0900502 if keyFile == nil {
503 ctx.PropertyErrorf("key", "private_key for %q could not be found", String(a.properties.Key))
504 return
505 }
506
Jiyong Park8fd61922018-11-08 02:50:25 +0900507 // remove duplicates in filesInfo
508 removeDup := func(filesInfo []apexFile) []apexFile {
509 encountered := make(map[android.Path]bool)
510 result := []apexFile{}
511 for _, f := range filesInfo {
512 if !encountered[f.builtFile] {
513 encountered[f.builtFile] = true
514 result = append(result, f)
515 }
516 }
517 return result
518 }
519 filesInfo = removeDup(filesInfo)
520
521 // to have consistent build rules
522 sort.Slice(filesInfo, func(i, j int) bool {
523 return filesInfo[i].builtFile.String() < filesInfo[j].builtFile.String()
524 })
525
526 // prepend the name of this APEX to the module names. These names will be the names of
527 // modules that will be defined if the APEX is flattened.
528 for i := range filesInfo {
529 filesInfo[i].moduleName = ctx.ModuleName() + "." + filesInfo[i].moduleName
530 }
531
Colin Crossa4925902018-11-16 11:36:28 -0800532 a.flattened = ctx.Config().FlattenApex() && !ctx.Config().UnbundledBuild()
Jiyong Park8fd61922018-11-08 02:50:25 +0900533 a.installDir = android.PathForModuleInstall(ctx, "apex")
534 a.filesInfo = filesInfo
535 if ctx.Config().FlattenApex() {
536 a.buildFlattenedApex(ctx)
537 } else {
538 a.buildUnflattenedApex(ctx, keyFile, certificate)
539 }
540}
541
542func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext, keyFile android.Path, certificate java.Certificate) {
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900543 cert := String(a.properties.Certificate)
544 if cert != "" && android.SrcIsModule(cert) == "" {
545 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
546 certificate = java.Certificate{
547 defaultDir.Join(ctx, cert+".x509.pem"),
548 defaultDir.Join(ctx, cert+".pk8"),
549 }
550 } else if cert == "" {
551 pem, key := ctx.Config().DefaultAppCertificate(ctx)
552 certificate = java.Certificate{pem, key}
553 }
554
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900555 // files and dirs that will be created in apex
Jiyong Park92905d62018-10-11 13:23:09 +0900556 var readOnlyPaths []string
557 var executablePaths []string // this also includes dirs
Jiyong Park8fd61922018-11-08 02:50:25 +0900558 for _, f := range a.filesInfo {
559 pathInApex := filepath.Join(f.installDir, f.builtFile.Base())
560 if f.installDir == "bin" {
Jiyong Park92905d62018-10-11 13:23:09 +0900561 executablePaths = append(executablePaths, pathInApex)
562 } else {
563 readOnlyPaths = append(readOnlyPaths, pathInApex)
564 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900565 if !android.InList(f.installDir, executablePaths) {
566 executablePaths = append(executablePaths, f.installDir)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900567 }
568 }
Jiyong Park92905d62018-10-11 13:23:09 +0900569 sort.Strings(readOnlyPaths)
570 sort.Strings(executablePaths)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900571 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
Colin Crossa4925902018-11-16 11:36:28 -0800572 ctx.Build(pctx, android.BuildParams{
573 Rule: generateFsConfig,
574 Output: cannedFsConfig,
575 Description: "generate fs config",
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900576 Args: map[string]string{
Jiyong Park92905d62018-10-11 13:23:09 +0900577 "ro_paths": strings.Join(readOnlyPaths, " "),
578 "exec_paths": strings.Join(executablePaths, " "),
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900579 },
580 })
581
Dario Freni4abb1dc2018-11-20 18:04:58 +0000582 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900583
Colin Crossa4925902018-11-16 11:36:28 -0800584 fcName := proptools.StringDefault(a.properties.File_contexts, ctx.ModuleName())
Jiyong Park02196572018-11-14 13:54:14 +0900585 fileContextsPath := "system/sepolicy/apex/" + fcName + "-file_contexts"
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900586 fileContextsOptionalPath := android.ExistentPathForSource(ctx, fileContextsPath)
587 if !fileContextsOptionalPath.Valid() {
588 ctx.ModuleErrorf("Cannot find file_contexts file: %q", fileContextsPath)
589 return
590 }
591 fileContexts := fileContextsOptionalPath.Path()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900592
Colin Crossa4925902018-11-16 11:36:28 -0800593 unsignedOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+apexSuffix+".unsigned")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900594
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900595 filesToCopy := []android.Path{}
Jiyong Park8fd61922018-11-08 02:50:25 +0900596 for _, f := range a.filesInfo {
597 filesToCopy = append(filesToCopy, f.builtFile)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900598 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900599
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900600 copyCommands := []string{}
Jiyong Park8fd61922018-11-08 02:50:25 +0900601 for i, src := range filesToCopy {
602 dest := filepath.Join(a.filesInfo[i].installDir, src.Base())
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900603 dest_path := filepath.Join(android.PathForModuleOut(ctx, "image").String(), dest)
604 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(dest_path))
605 copyCommands = append(copyCommands, "cp "+src.String()+" "+dest_path)
606 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900607 implicitInputs := append(android.Paths(nil), filesToCopy...)
Jiyong Parkff1458f2018-10-12 21:49:38 +0900608 implicitInputs = append(implicitInputs, cannedFsConfig, manifest, fileContexts, keyFile)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900609 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
610 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
Colin Crossa4925902018-11-16 11:36:28 -0800611 ctx.Build(pctx, android.BuildParams{
612 Rule: apexRule,
613 Implicits: implicitInputs,
614 Output: unsignedOutputFile,
615 Description: "apex",
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900616 Args: map[string]string{
617 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
618 "image_dir": android.PathForModuleOut(ctx, "image").String(),
619 "copy_commands": strings.Join(copyCommands, " && "),
620 "manifest": manifest.String(),
621 "file_contexts": fileContexts.String(),
622 "canned_fs_config": cannedFsConfig.String(),
Jiyong Parkff1458f2018-10-12 21:49:38 +0900623 "key": keyFile.String(),
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900624 },
625 })
626
Colin Crossa4925902018-11-16 11:36:28 -0800627 var abis []string
628 for _, target := range ctx.MultiTargets() {
629 abis = append(abis, target.Arch.Abi[0])
630 }
631 abis = android.FirstUniqueStrings(abis)
632
633 apexProtoFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".pb"+apexSuffix)
634 bundleModuleFile := android.PathForModuleOut(ctx, ctx.ModuleName()+"-base.zip")
635 a.bundleModuleFile = bundleModuleFile
636
637 ctx.Build(pctx, android.BuildParams{
638 Rule: apexProtoConvertRule,
639 Input: unsignedOutputFile,
640 Output: apexProtoFile,
641 Description: "apex proto convert",
642 })
643
644 ctx.Build(pctx, android.BuildParams{
645 Rule: apexBundleRule,
646 Input: apexProtoFile,
647 Output: bundleModuleFile,
648 Description: "apex bundle module",
649 Args: map[string]string{
650 "abi": strings.Join(abis, "."),
651 },
652 })
653
654 a.outputFile = android.PathForModuleOut(ctx, ctx.ModuleName()+apexSuffix)
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900655 ctx.Build(pctx, android.BuildParams{
656 Rule: java.Signapk,
657 Description: "signapk",
658 Output: a.outputFile,
659 Input: unsignedOutputFile,
660 Args: map[string]string{
661 "certificates": strings.Join([]string{certificate.Pem.String(), certificate.Key.String()}, " "),
Jiyong Parkbfe64a12018-11-22 02:51:54 +0900662 "flags": "-a 4096", //alignment
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900663 },
664 })
Jiyong Park8fd61922018-11-08 02:50:25 +0900665}
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900666
Jiyong Park8fd61922018-11-08 02:50:25 +0900667func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
Dario Freni4abb1dc2018-11-20 18:04:58 +0000668 // For flattened APEX, do nothing but make sure that apex_manifest.json file is also copied along
Jiyong Park8fd61922018-11-08 02:50:25 +0900669 // with other ordinary files.
Dario Freni4abb1dc2018-11-20 18:04:58 +0000670 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
671 a.filesInfo = append(a.filesInfo, apexFile{manifest, ctx.ModuleName() + ".apex_manifest.json", android.Common, ".", etc})
Jiyong Park8fd61922018-11-08 02:50:25 +0900672
673 for _, fi := range a.filesInfo {
Colin Crossa4925902018-11-16 11:36:28 -0800674 dir := filepath.Join("apex", ctx.ModuleName(), fi.installDir)
Jiyong Park8fd61922018-11-08 02:50:25 +0900675 ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.builtFile.Base(), fi.builtFile)
676 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900677}
678
679func (a *apexBundle) AndroidMk() android.AndroidMkData {
Jiyong Park8fd61922018-11-08 02:50:25 +0900680 if a.flattened {
681 return android.AndroidMkData{
682 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
683 moduleNames := []string{}
684 for _, fi := range a.filesInfo {
685 if !android.InList(fi.moduleName, moduleNames) {
686 moduleNames = append(moduleNames, fi.moduleName)
687 }
688 }
689 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
690 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
691 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
692 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", strings.Join(moduleNames, " "))
693 fmt.Fprintln(w, "include $(BUILD_PHONY_PACKAGE)")
694
695 for _, fi := range a.filesInfo {
696 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
697 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
698 fmt.Fprintln(w, "LOCAL_MODULE :=", fi.moduleName)
699 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString(), name, fi.installDir))
700 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", fi.builtFile.Base())
701 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", fi.builtFile.String())
702 fmt.Fprintln(w, "LOCAL_MODULE_CLASS :=", fi.class.NameInMake())
703 archStr := fi.archType.String()
704 if archStr != "common" {
705 fmt.Fprintln(w, "LOCAL_MODULE_TARGET_ARCH :=", archStr)
706 }
707 if fi.class == javaSharedLib {
708 fmt.Fprintln(w, "LOCAL_SOONG_DEX_JAR :=", fi.builtFile.String())
709 fmt.Fprintln(w, "LOCAL_DEX_PREOPT := false")
710 fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_java_prebuilt.mk")
711 } else {
712 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
713 }
714 }
715 }}
716 } else {
717 return android.AndroidMkData{
718 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
719 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
720 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
721 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
722 fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC") // do we need a new class?
723 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", a.outputFile.String())
724 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString()))
725 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", name+apexSuffix)
726 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", String(a.properties.Key))
727 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
Colin Crossa4925902018-11-16 11:36:28 -0800728
729 fmt.Fprintln(w, "ALL_MODULES.$(LOCAL_MODULE).BUNDLE :=", a.bundleModuleFile.String())
Jiyong Park8fd61922018-11-08 02:50:25 +0900730 }}
731 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900732}
733
734func apexBundleFactory() android.Module {
735 module := &apexBundle{}
736 module.AddProperties(&module.properties)
Jiyong Park397e55e2018-10-24 21:09:55 +0900737 module.Prefer32(func(ctx android.BaseModuleContext, base *android.ModuleBase,
738 class android.OsClass) bool {
739 return class == android.Device && ctx.Config().DevicePrefer32BitExecutables()
740 })
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900741 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
742 android.InitDefaultableModule(module)
743 return module
744}