blob: d25c256cfdeadf5e076aad47ebf1715f0a5119fc [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} && ` +
Jiyong Park805cbc32019-01-08 14:04:17 +090043 `echo ${exec_paths} | tr ' ' '\n' | awk '{print "/"$$1 " 0 2000 0755"}' >> ${out}`,
Jiyong Park48ca7dc2018-10-10 14:01:00 +090044 Description: "fs_config ${out}",
Jiyong Park92905d62018-10-11 13:23:09 +090045 }, "ro_paths", "exec_paths")
Jiyong Park48ca7dc2018-10-10 14:01:00 +090046
47 // TODO(b/113233103): make sure that file_contexts is sane, i.e., validate
48 // against the binary policy using sefcontext_compiler -p <policy>.
49
50 // TODO(b/114327326): automate the generation of file_contexts
51 apexRule = pctx.StaticRule("apexRule", blueprint.RuleParams{
52 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
53 `(${copy_commands}) && ` +
54 `APEXER_TOOL_PATH=${tool_path} ` +
Jiyong Park25560152018-11-20 09:57:52 +090055 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park48ca7dc2018-10-10 14:01:00 +090056 `--file_contexts ${file_contexts} ` +
57 `--canned_fs_config ${canned_fs_config} ` +
Alex Light5098a612018-11-29 17:12:15 -080058 `--payload_type image ` +
Jiyong Park835d82b2018-12-27 16:04:18 +090059 `--key ${key} ${opt_flags} ${image_dir} ${out} `,
Jiyong Park48ca7dc2018-10-10 14:01:00 +090060 CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
61 "${mke2fs}", "${resize2fs}", "${sefcontext_compile}",
62 "${soong_zip}", "${zipalign}", "${aapt2}"},
63 Description: "APEX ${image_dir} => ${out}",
Jiyong Park835d82b2018-12-27 16:04:18 +090064 }, "tool_path", "image_dir", "copy_commands", "manifest", "file_contexts", "canned_fs_config", "key", "opt_flags")
Colin Crossa4925902018-11-16 11:36:28 -080065
Alex Light5098a612018-11-29 17:12:15 -080066 zipApexRule = pctx.StaticRule("zipApexRule", blueprint.RuleParams{
67 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
68 `(${copy_commands}) && ` +
69 `APEXER_TOOL_PATH=${tool_path} ` +
70 `${apexer} --force --manifest ${manifest} ` +
71 `--payload_type zip ` +
72 `${image_dir} ${out} `,
73 CommandDeps: []string{"${apexer}", "${merge_zips}", "${soong_zip}", "${zipalign}", "${aapt2}"},
74 Description: "ZipAPEX ${image_dir} => ${out}",
75 }, "tool_path", "image_dir", "copy_commands", "manifest")
76
Colin Crossa4925902018-11-16 11:36:28 -080077 apexProtoConvertRule = pctx.AndroidStaticRule("apexProtoConvertRule",
78 blueprint.RuleParams{
79 Command: `${aapt2} convert --output-format proto $in -o $out`,
80 CommandDeps: []string{"${aapt2}"},
81 })
82
83 apexBundleRule = pctx.StaticRule("apexBundleRule", blueprint.RuleParams{
Jiyong Park1ed0fc52018-11-23 13:22:21 +090084 Command: `${zip2zip} -i $in -o $out ` +
Dario Freni4abb1dc2018-11-20 18:04:58 +000085 `apex_payload.img:apex/${abi}.img ` +
86 `apex_manifest.json:root/apex_manifest.json ` +
Shahar Amitai328b0772018-11-26 14:12:02 +000087 `AndroidManifest.xml:manifest/AndroidManifest.xml`,
Colin Crossa4925902018-11-16 11:36:28 -080088 CommandDeps: []string{"${zip2zip}"},
89 Description: "app bundle",
90 }, "abi")
Jiyong Park48ca7dc2018-10-10 14:01:00 +090091)
92
Alex Light5098a612018-11-29 17:12:15 -080093var imageApexSuffix = ".apex"
94var zipApexSuffix = ".zipapex"
95
96var imageApexType = "image"
97var zipApexType = "zip"
Jiyong Park48ca7dc2018-10-10 14:01:00 +090098
99type dependencyTag struct {
100 blueprint.BaseDependencyTag
101 name string
102}
103
104var (
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900105 sharedLibTag = dependencyTag{name: "sharedLib"}
106 executableTag = dependencyTag{name: "executable"}
107 javaLibTag = dependencyTag{name: "javaLib"}
108 prebuiltTag = dependencyTag{name: "prebuilt"}
109 keyTag = dependencyTag{name: "key"}
110 certificateTag = dependencyTag{name: "certificate"}
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900111)
112
113func init() {
114 pctx.Import("android/soong/common")
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900115 pctx.Import("android/soong/java")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900116 pctx.HostBinToolVariable("apexer", "apexer")
Roland Levillain54bdfda2018-10-05 19:34:32 +0100117 // ART minimal builds (using the master-art manifest) do not have the "frameworks/base"
118 // projects, and hence cannot built 'aapt2'. Use the SDK prebuilt instead.
119 hostBinToolVariableWithPrebuilt := func(name, prebuiltDir, tool string) {
120 pctx.VariableFunc(name, func(ctx android.PackageVarContext) string {
David Brazdil91b4e3e2019-01-23 21:04:05 +0000121 if !ctx.Config().FrameworksBaseDirExists(ctx) {
Roland Levillain54bdfda2018-10-05 19:34:32 +0100122 return filepath.Join(prebuiltDir, runtime.GOOS, "bin", tool)
123 } else {
124 return pctx.HostBinToolPath(ctx, tool).String()
125 }
126 })
127 }
128 hostBinToolVariableWithPrebuilt("aapt2", "prebuilts/sdk/tools", "aapt2")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900129 pctx.HostBinToolVariable("avbtool", "avbtool")
130 pctx.HostBinToolVariable("e2fsdroid", "e2fsdroid")
131 pctx.HostBinToolVariable("merge_zips", "merge_zips")
132 pctx.HostBinToolVariable("mke2fs", "mke2fs")
133 pctx.HostBinToolVariable("resize2fs", "resize2fs")
134 pctx.HostBinToolVariable("sefcontext_compile", "sefcontext_compile")
135 pctx.HostBinToolVariable("soong_zip", "soong_zip")
Colin Crossa4925902018-11-16 11:36:28 -0800136 pctx.HostBinToolVariable("zip2zip", "zip2zip")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900137 pctx.HostBinToolVariable("zipalign", "zipalign")
138
Alex Lightee250722018-12-06 14:00:02 -0800139 android.RegisterModuleType("apex", ApexBundleFactory)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900140
141 android.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
142 ctx.TopDown("apex_deps", apexDepsMutator)
143 ctx.BottomUp("apex", apexMutator)
144 })
145}
146
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900147// Mark the direct and transitive dependencies of apex bundles so that they
148// can be built for the apex bundles.
149func apexDepsMutator(mctx android.TopDownMutatorContext) {
150 if _, ok := mctx.Module().(*apexBundle); ok {
Colin Crossa4925902018-11-16 11:36:28 -0800151 apexBundleName := mctx.ModuleName()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900152 mctx.WalkDeps(func(child, parent android.Module) bool {
Jiyong Park0ddfcd12018-12-11 01:35:25 +0900153 depName := mctx.OtherModuleName(child)
154 // If the parent is apexBundle, this child is directly depended.
155 _, directDep := parent.(*apexBundle)
156 android.UpdateApexDependency(apexBundleName, depName, directDep)
157
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900158 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() {
Jiyong Park0ddfcd12018-12-11 01:35:25 +0900159 am.BuildForApex(apexBundleName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900160 return true
161 } else {
162 return false
163 }
164 })
165 }
166}
167
168// Create apex variations if a module is included in APEX(s).
169func apexMutator(mctx android.BottomUpMutatorContext) {
170 if am, ok := mctx.Module().(android.ApexModule); ok && am.CanHaveApexVariants() {
Jiyong Park0ddfcd12018-12-11 01:35:25 +0900171 am.CreateApexVariations(mctx)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900172 } else if _, ok := mctx.Module().(*apexBundle); ok {
173 // apex bundle itself is mutated so that it and its modules have same
174 // apex variant.
175 apexBundleName := mctx.ModuleName()
176 mctx.CreateVariations(apexBundleName)
177 }
178}
179
Alex Light9670d332019-01-29 18:07:33 -0800180type apexNativeDependencies struct {
181 // List of native libraries
182 Native_shared_libs []string
183 // List of native executables
184 Binaries []string
185}
186type apexMultilibProperties struct {
187 // Native dependencies whose compile_multilib is "first"
188 First apexNativeDependencies
189
190 // Native dependencies whose compile_multilib is "both"
191 Both apexNativeDependencies
192
193 // Native dependencies whose compile_multilib is "prefer32"
194 Prefer32 apexNativeDependencies
195
196 // Native dependencies whose compile_multilib is "32"
197 Lib32 apexNativeDependencies
198
199 // Native dependencies whose compile_multilib is "64"
200 Lib64 apexNativeDependencies
201}
202
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900203type apexBundleProperties struct {
204 // Json manifest file describing meta info of this APEX bundle. Default:
Dario Freni4abb1dc2018-11-20 18:04:58 +0000205 // "apex_manifest.json"
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900206 Manifest *string
207
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900208 // Determines the file contexts file for setting security context to each file in this APEX bundle.
209 // Specifically, when this is set to <value>, /system/sepolicy/apex/<value>_file_contexts file is
210 // used.
211 // Default: <name_of_this_module>
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900212 File_contexts *string
213
214 // List of native shared libs that are embedded inside this APEX bundle
215 Native_shared_libs []string
216
217 // List of native executables that are embedded inside this APEX bundle
218 Binaries []string
219
220 // List of java libraries that are embedded inside this APEX bundle
221 Java_libs []string
222
223 // List of prebuilt files that are embedded inside this APEX bundle
224 Prebuilts []string
Jiyong Parkff1458f2018-10-12 21:49:38 +0900225
226 // Name of the apex_key module that provides the private key to sign APEX
227 Key *string
Jiyong Park397e55e2018-10-24 21:09:55 +0900228
Alex Light5098a612018-11-29 17:12:15 -0800229 // The type of APEX to build. Controls what the APEX payload is. Either
230 // 'image', 'zip' or 'both'. Default: 'image'.
231 Payload_type *string
232
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900233 // The name of a certificate in the default certificate directory, blank to use the default product certificate,
234 // or an android_app_certificate module name in the form ":module".
235 Certificate *string
236
Jiyong Park92c0f9c2018-12-13 23:14:57 +0900237 // Whether this APEX is installable to one of the partitions. Default: true.
238 Installable *bool
239
Jiyong Parkda6eb592018-12-19 17:12:36 +0900240 // For native libraries and binaries, use the vendor variant instead of the core (platform) variant.
241 // Default is false.
242 Use_vendor *bool
243
Alex Lightfc0bd7c2019-01-29 18:31:59 -0800244 // For telling the apex to ignore special handling for system libraries such as bionic. Default is false.
245 Ignore_system_library_special_case *bool
246
Alex Light9670d332019-01-29 18:07:33 -0800247 Multilib apexMultilibProperties
248}
249
250type apexTargetBundleProperties struct {
251 Target struct {
252 // Multilib properties only for android.
253 Android struct {
254 Multilib apexMultilibProperties
Jiyong Park397e55e2018-10-24 21:09:55 +0900255 }
Alex Light9670d332019-01-29 18:07:33 -0800256 // Multilib properties only for host.
257 Host struct {
258 Multilib apexMultilibProperties
Jiyong Park397e55e2018-10-24 21:09:55 +0900259 }
Alex Light9670d332019-01-29 18:07:33 -0800260 // Multilib properties only for host linux_bionic.
261 Linux_bionic struct {
262 Multilib apexMultilibProperties
Jiyong Park397e55e2018-10-24 21:09:55 +0900263 }
Alex Light9670d332019-01-29 18:07:33 -0800264 // Multilib properties only for host linux_glibc.
265 Linux_glibc struct {
266 Multilib apexMultilibProperties
Jiyong Park397e55e2018-10-24 21:09:55 +0900267 }
268 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900269}
270
Jiyong Park8fd61922018-11-08 02:50:25 +0900271type apexFileClass int
272
273const (
274 etc apexFileClass = iota
275 nativeSharedLib
276 nativeExecutable
Jiyong Park04480cf2019-02-06 00:16:29 +0900277 shBinary
Jiyong Park8fd61922018-11-08 02:50:25 +0900278 javaSharedLib
279)
280
Alex Light5098a612018-11-29 17:12:15 -0800281type apexPackaging int
282
283const (
284 imageApex apexPackaging = iota
285 zipApex
286 both
287)
288
289func (a apexPackaging) image() bool {
290 switch a {
291 case imageApex, both:
292 return true
293 }
294 return false
295}
296
297func (a apexPackaging) zip() bool {
298 switch a {
299 case zipApex, both:
300 return true
301 }
302 return false
303}
304
305func (a apexPackaging) suffix() string {
306 switch a {
307 case imageApex:
308 return imageApexSuffix
309 case zipApex:
310 return zipApexSuffix
311 case both:
312 panic(fmt.Errorf("must be either zip or image"))
313 default:
314 panic(fmt.Errorf("unkonwn APEX type %d", a))
315 }
316}
317
318func (a apexPackaging) name() string {
319 switch a {
320 case imageApex:
321 return imageApexType
322 case zipApex:
323 return zipApexType
324 case both:
325 panic(fmt.Errorf("must be either zip or image"))
326 default:
327 panic(fmt.Errorf("unkonwn APEX type %d", a))
328 }
329}
330
Jiyong Park8fd61922018-11-08 02:50:25 +0900331func (class apexFileClass) NameInMake() string {
332 switch class {
333 case etc:
334 return "ETC"
335 case nativeSharedLib:
336 return "SHARED_LIBRARIES"
Jiyong Park04480cf2019-02-06 00:16:29 +0900337 case nativeExecutable, shBinary:
Jiyong Park8fd61922018-11-08 02:50:25 +0900338 return "EXECUTABLES"
339 case javaSharedLib:
340 return "JAVA_LIBRARIES"
341 default:
342 panic(fmt.Errorf("unkonwn class %d", class))
343 }
344}
345
346type apexFile struct {
347 builtFile android.Path
348 moduleName string
Jiyong Park8fd61922018-11-08 02:50:25 +0900349 installDir string
350 class apexFileClass
Jiyong Parka8894842018-12-19 17:36:39 +0900351 module android.Module
Alex Light3d673592019-01-18 14:37:31 -0800352 symlinks []string
Jiyong Park8fd61922018-11-08 02:50:25 +0900353}
354
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900355type apexBundle struct {
356 android.ModuleBase
357 android.DefaultableModuleBase
358
Alex Light9670d332019-01-29 18:07:33 -0800359 properties apexBundleProperties
360 targetProperties apexTargetBundleProperties
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900361
Alex Light5098a612018-11-29 17:12:15 -0800362 apexTypes apexPackaging
363
Colin Crossa4925902018-11-16 11:36:28 -0800364 bundleModuleFile android.WritablePath
Alex Light5098a612018-11-29 17:12:15 -0800365 outputFiles map[apexPackaging]android.WritablePath
Colin Crossa4925902018-11-16 11:36:28 -0800366 installDir android.OutputPath
Jiyong Park8fd61922018-11-08 02:50:25 +0900367
368 // list of files to be included in this apex
369 filesInfo []apexFile
370
371 flattened bool
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900372}
373
Jiyong Park397e55e2018-10-24 21:09:55 +0900374func addDependenciesForNativeModules(ctx android.BottomUpMutatorContext,
Jiyong Parkda6eb592018-12-19 17:12:36 +0900375 native_shared_libs []string, binaries []string, arch string, imageVariation string) {
Jiyong Park397e55e2018-10-24 21:09:55 +0900376 // Use *FarVariation* to be able to depend on modules having
377 // conflicting variations with this module. This is required since
378 // arch variant of an APEX bundle is 'common' but it is 'arm' or 'arm64'
379 // for native shared libs.
380 ctx.AddFarVariationDependencies([]blueprint.Variation{
381 {Mutator: "arch", Variation: arch},
Jiyong Parkda6eb592018-12-19 17:12:36 +0900382 {Mutator: "image", Variation: imageVariation},
Jiyong Park397e55e2018-10-24 21:09:55 +0900383 {Mutator: "link", Variation: "shared"},
Jiyong Park28d395a2018-12-07 22:42:47 +0900384 {Mutator: "version", Variation: ""}, // "" is the non-stub variant
Jiyong Park397e55e2018-10-24 21:09:55 +0900385 }, sharedLibTag, native_shared_libs...)
386
387 ctx.AddFarVariationDependencies([]blueprint.Variation{
388 {Mutator: "arch", Variation: arch},
Jiyong Parkda6eb592018-12-19 17:12:36 +0900389 {Mutator: "image", Variation: imageVariation},
Jiyong Park397e55e2018-10-24 21:09:55 +0900390 }, executableTag, binaries...)
391}
392
Alex Light9670d332019-01-29 18:07:33 -0800393func (a *apexBundle) combineProperties(ctx android.BottomUpMutatorContext) {
394 if ctx.Os().Class == android.Device {
395 proptools.AppendProperties(&a.properties.Multilib, &a.targetProperties.Target.Android.Multilib, nil)
396 } else {
397 proptools.AppendProperties(&a.properties.Multilib, &a.targetProperties.Target.Host.Multilib, nil)
398 if ctx.Os().Bionic() {
399 proptools.AppendProperties(&a.properties.Multilib, &a.targetProperties.Target.Linux_bionic.Multilib, nil)
400 } else {
401 proptools.AppendProperties(&a.properties.Multilib, &a.targetProperties.Target.Linux_glibc.Multilib, nil)
402 }
403 }
404}
405
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900406func (a *apexBundle) DepsMutator(ctx android.BottomUpMutatorContext) {
Alex Light9670d332019-01-29 18:07:33 -0800407
Jiyong Park397e55e2018-10-24 21:09:55 +0900408 targets := ctx.MultiTargets()
Jiyong Park7c1dc612019-01-05 11:15:24 +0900409 config := ctx.DeviceConfig()
Alex Light9670d332019-01-29 18:07:33 -0800410
411 a.combineProperties(ctx)
412
Jiyong Park397e55e2018-10-24 21:09:55 +0900413 has32BitTarget := false
414 for _, target := range targets {
415 if target.Arch.ArchType.Multilib == "lib32" {
416 has32BitTarget = true
417 }
418 }
419 for i, target := range targets {
420 // When multilib.* is omitted for native_shared_libs, it implies
421 // multilib.both.
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900422 ctx.AddFarVariationDependencies([]blueprint.Variation{
Jiyong Park397e55e2018-10-24 21:09:55 +0900423 {Mutator: "arch", Variation: target.String()},
Jiyong Park7c1dc612019-01-05 11:15:24 +0900424 {Mutator: "image", Variation: a.getImageVariation(config)},
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900425 {Mutator: "link", Variation: "shared"},
426 }, sharedLibTag, a.properties.Native_shared_libs...)
427
Jiyong Park397e55e2018-10-24 21:09:55 +0900428 // Add native modules targetting both ABIs
429 addDependenciesForNativeModules(ctx,
430 a.properties.Multilib.Both.Native_shared_libs,
Jiyong Parkda6eb592018-12-19 17:12:36 +0900431 a.properties.Multilib.Both.Binaries, target.String(),
Jiyong Park7c1dc612019-01-05 11:15:24 +0900432 a.getImageVariation(config))
Jiyong Park397e55e2018-10-24 21:09:55 +0900433
Alex Light3d673592019-01-18 14:37:31 -0800434 isPrimaryAbi := i == 0
435 if isPrimaryAbi {
Jiyong Park397e55e2018-10-24 21:09:55 +0900436 // When multilib.* is omitted for binaries, it implies
437 // multilib.first.
438 ctx.AddFarVariationDependencies([]blueprint.Variation{
439 {Mutator: "arch", Variation: target.String()},
Jiyong Park7c1dc612019-01-05 11:15:24 +0900440 {Mutator: "image", Variation: a.getImageVariation(config)},
Jiyong Park397e55e2018-10-24 21:09:55 +0900441 }, executableTag, a.properties.Binaries...)
442
443 // Add native modules targetting the first ABI
444 addDependenciesForNativeModules(ctx,
445 a.properties.Multilib.First.Native_shared_libs,
Jiyong Parkda6eb592018-12-19 17:12:36 +0900446 a.properties.Multilib.First.Binaries, target.String(),
Jiyong Park7c1dc612019-01-05 11:15:24 +0900447 a.getImageVariation(config))
Jaewoong Jungb9a11512019-01-15 10:47:05 -0800448
449 // When multilib.* is omitted for prebuilts, it implies multilib.first.
450 ctx.AddFarVariationDependencies([]blueprint.Variation{
451 {Mutator: "arch", Variation: target.String()},
452 }, prebuiltTag, a.properties.Prebuilts...)
Jiyong Park397e55e2018-10-24 21:09:55 +0900453 }
454
455 switch target.Arch.ArchType.Multilib {
456 case "lib32":
457 // Add native modules targetting 32-bit ABI
458 addDependenciesForNativeModules(ctx,
459 a.properties.Multilib.Lib32.Native_shared_libs,
Jiyong Parkda6eb592018-12-19 17:12:36 +0900460 a.properties.Multilib.Lib32.Binaries, target.String(),
Jiyong Park7c1dc612019-01-05 11:15:24 +0900461 a.getImageVariation(config))
Jiyong Park397e55e2018-10-24 21:09:55 +0900462
463 addDependenciesForNativeModules(ctx,
464 a.properties.Multilib.Prefer32.Native_shared_libs,
Jiyong Parkda6eb592018-12-19 17:12:36 +0900465 a.properties.Multilib.Prefer32.Binaries, target.String(),
Jiyong Park7c1dc612019-01-05 11:15:24 +0900466 a.getImageVariation(config))
Jiyong Park397e55e2018-10-24 21:09:55 +0900467 case "lib64":
468 // Add native modules targetting 64-bit ABI
469 addDependenciesForNativeModules(ctx,
470 a.properties.Multilib.Lib64.Native_shared_libs,
Jiyong Parkda6eb592018-12-19 17:12:36 +0900471 a.properties.Multilib.Lib64.Binaries, target.String(),
Jiyong Park7c1dc612019-01-05 11:15:24 +0900472 a.getImageVariation(config))
Jiyong Park397e55e2018-10-24 21:09:55 +0900473
474 if !has32BitTarget {
475 addDependenciesForNativeModules(ctx,
476 a.properties.Multilib.Prefer32.Native_shared_libs,
Jiyong Parkda6eb592018-12-19 17:12:36 +0900477 a.properties.Multilib.Prefer32.Binaries, target.String(),
Jiyong Park7c1dc612019-01-05 11:15:24 +0900478 a.getImageVariation(config))
Jiyong Park397e55e2018-10-24 21:09:55 +0900479 }
480 }
481
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900482 }
483
Jiyong Parkff1458f2018-10-12 21:49:38 +0900484 ctx.AddFarVariationDependencies([]blueprint.Variation{
485 {Mutator: "arch", Variation: "android_common"},
486 }, javaLibTag, a.properties.Java_libs...)
487
Jiyong Park23c52b02019-02-02 13:13:47 +0900488 if String(a.properties.Key) == "" {
489 ctx.ModuleErrorf("key is missing")
490 return
491 }
492 ctx.AddDependency(ctx.Module(), keyTag, String(a.properties.Key))
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900493
Jiyong Park23c52b02019-02-02 13:13:47 +0900494 cert := android.SrcIsModule(String(a.properties.Certificate))
495 if cert != "" {
496 ctx.AddDependency(ctx.Module(), certificateTag, cert)
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900497 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900498}
499
Jiyong Park74e240b2018-11-27 21:27:08 +0900500func (a *apexBundle) Srcs() android.Paths {
Jiyong Park5a832022018-12-20 09:54:35 +0900501 if file, ok := a.outputFiles[imageApex]; ok {
502 return android.Paths{file}
503 } else {
504 return nil
505 }
Jiyong Park74e240b2018-11-27 21:27:08 +0900506}
507
Jiyong Park92c0f9c2018-12-13 23:14:57 +0900508func (a *apexBundle) installable() bool {
509 return a.properties.Installable == nil || proptools.Bool(a.properties.Installable)
510}
511
Jiyong Park7c1dc612019-01-05 11:15:24 +0900512func (a *apexBundle) getImageVariation(config android.DeviceConfig) string {
513 if config.VndkVersion() != "" && proptools.Bool(a.properties.Use_vendor) {
Jiyong Parkda6eb592018-12-19 17:12:36 +0900514 return "vendor"
515 } else {
516 return "core"
517 }
518}
519
Jiyong Park388ef3f2019-01-28 19:47:32 +0900520func (a *apexBundle) IsSanitizerEnabled(ctx android.BaseModuleContext, sanitizerName string) bool {
521 globalSanitizerNames := []string{}
522 if a.Host() {
523 globalSanitizerNames = ctx.Config().SanitizeHost()
524 } else {
525 arches := ctx.Config().SanitizeDeviceArch()
526 if len(arches) == 0 || android.InList(a.Arch().ArchType.Name, arches) {
527 globalSanitizerNames = ctx.Config().SanitizeDevice()
528 }
529 }
530 return android.InList(sanitizerName, globalSanitizerNames)
Jiyong Park379de2f2018-12-19 02:47:14 +0900531}
532
Alex Lightfc0bd7c2019-01-29 18:31:59 -0800533func getCopyManifestForNativeLibrary(cc *cc.Module, handleSpecialLibs bool) (fileToCopy android.Path, dirInApex string) {
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900534 // Decide the APEX-local directory by the multilib of the library
535 // In the future, we may query this to the module.
536 switch cc.Arch().ArchType.Multilib {
537 case "lib32":
538 dirInApex = "lib"
539 case "lib64":
540 dirInApex = "lib64"
541 }
Jiyong Parkb7c24df2019-02-01 12:03:59 +0900542 dirInApex = filepath.Join(dirInApex, cc.RelativeInstallPath())
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900543 if !cc.Arch().Native {
544 dirInApex = filepath.Join(dirInApex, cc.Arch().ArchType.String())
545 }
Alex Lightfc0bd7c2019-01-29 18:31:59 -0800546 if handleSpecialLibs {
547 switch cc.Name() {
548 case "libc", "libm", "libdl":
549 // Special case for bionic libs. This is to prevent the bionic libs
550 // from being included in the search path /apex/com.android.apex/lib.
551 // This exclusion is required because bionic libs in the runtime APEX
552 // are available via the legacy paths /system/lib/libc.so, etc. By the
553 // init process, the bionic libs in the APEX are bind-mounted to the
554 // legacy paths and thus will be loaded into the default linker namespace.
555 // If the bionic libs are directly in /apex/com.android.apex/lib then
556 // the same libs will be again loaded to the runtime linker namespace,
557 // which will result double loading of bionic libs that isn't supported.
558 dirInApex = filepath.Join(dirInApex, "bionic")
559 }
Jiyong Parkb0788572018-12-20 22:10:17 +0900560 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900561
562 fileToCopy = cc.OutputFile().Path()
563 return
564}
565
566func getCopyManifestForExecutable(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
Jiyong Parkb7c24df2019-02-01 12:03:59 +0900567 // TODO(b/123721777) respect relative_install_path also for binaries
568 // dirInApex = filepath.Join("bin", cc.RelativeInstallPath())
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900569 dirInApex = "bin"
570 fileToCopy = cc.OutputFile().Path()
571 return
572}
573
Jiyong Park04480cf2019-02-06 00:16:29 +0900574func getCopyManifestForShBinary(sh *android.ShBinary) (fileToCopy android.Path, dirInApex string) {
575 dirInApex = filepath.Join("bin", sh.SubDir())
576 fileToCopy = sh.OutputFile()
577 return
578}
579
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900580func getCopyManifestForJavaLibrary(java *java.Library) (fileToCopy android.Path, dirInApex string) {
581 dirInApex = "javalib"
Jiyong Park8fd61922018-11-08 02:50:25 +0900582 fileToCopy = java.DexJarFile()
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900583 return
584}
585
586func getCopyManifestForPrebuiltEtc(prebuilt *android.PrebuiltEtc) (fileToCopy android.Path, dirInApex string) {
587 dirInApex = filepath.Join("etc", prebuilt.SubDir())
588 fileToCopy = prebuilt.OutputFile()
589 return
590}
591
592func (a *apexBundle) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Jiyong Park8fd61922018-11-08 02:50:25 +0900593 filesInfo := []apexFile{}
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900594
Jiyong Parkff1458f2018-10-12 21:49:38 +0900595 var keyFile android.Path
Jiyong Park835d82b2018-12-27 16:04:18 +0900596 var pubKeyFile android.Path
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900597 var certificate java.Certificate
Jiyong Parkff1458f2018-10-12 21:49:38 +0900598
Alex Light5098a612018-11-29 17:12:15 -0800599 if a.properties.Payload_type == nil || *a.properties.Payload_type == "image" {
600 a.apexTypes = imageApex
601 } else if *a.properties.Payload_type == "zip" {
602 a.apexTypes = zipApex
603 } else if *a.properties.Payload_type == "both" {
604 a.apexTypes = both
605 } else {
606 ctx.PropertyErrorf("type", "%q is not one of \"image\", \"zip\", or \"both\".", *a.properties.Payload_type)
607 return
608 }
609
Alex Lightfc0bd7c2019-01-29 18:31:59 -0800610 handleSpecialLibs := !android.Bool(a.properties.Ignore_system_library_special_case)
611
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900612 ctx.WalkDeps(func(child, parent android.Module) bool {
613 if _, ok := parent.(*apexBundle); ok {
614 // direct dependencies
615 depTag := ctx.OtherModuleDependencyTag(child)
Jiyong Parkff1458f2018-10-12 21:49:38 +0900616 depName := ctx.OtherModuleName(child)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900617 switch depTag {
618 case sharedLibTag:
619 if cc, ok := child.(*cc.Module); ok {
Alex Lightfc0bd7c2019-01-29 18:31:59 -0800620 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc, handleSpecialLibs)
Jiyong Park719b4462019-01-13 00:39:51 +0900621 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, dirInApex, nativeSharedLib, cc, nil})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900622 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900623 } else {
624 ctx.PropertyErrorf("native_shared_libs", "%q is not a cc_library or cc_library_shared module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900625 }
626 case executableTag:
627 if cc, ok := child.(*cc.Module); ok {
Alex Light16df4e82019-01-24 11:37:55 -0800628 if !cc.Arch().Native {
629 // There is only one 'bin' directory so we shouldn't bother copying in
630 // native-bridge'd binaries and only use main ones.
631 return true
632 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900633 fileToCopy, dirInApex := getCopyManifestForExecutable(cc)
Jiyong Park719b4462019-01-13 00:39:51 +0900634 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, dirInApex, nativeExecutable, cc, cc.Symlinks()})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900635 return true
Jiyong Park04480cf2019-02-06 00:16:29 +0900636 } else if sh, ok := child.(*android.ShBinary); ok {
637 fileToCopy, dirInApex := getCopyManifestForShBinary(sh)
638 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, dirInApex, shBinary, sh, nil})
Jiyong Parkff1458f2018-10-12 21:49:38 +0900639 } else {
Jiyong Park04480cf2019-02-06 00:16:29 +0900640 ctx.PropertyErrorf("binaries", "%q is neithher cc_binary nor sh_binary", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900641 }
642 case javaLibTag:
643 if java, ok := child.(*java.Library); ok {
644 fileToCopy, dirInApex := getCopyManifestForJavaLibrary(java)
Jiyong Park8fd61922018-11-08 02:50:25 +0900645 if fileToCopy == nil {
646 ctx.PropertyErrorf("java_libs", "%q is not configured to be compiled into dex", depName)
647 } else {
Jiyong Park719b4462019-01-13 00:39:51 +0900648 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, dirInApex, javaSharedLib, java, nil})
Jiyong Park8fd61922018-11-08 02:50:25 +0900649 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900650 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900651 } else {
652 ctx.PropertyErrorf("java_libs", "%q is not a java_library module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900653 }
654 case prebuiltTag:
655 if prebuilt, ok := child.(*android.PrebuiltEtc); ok {
656 fileToCopy, dirInApex := getCopyManifestForPrebuiltEtc(prebuilt)
Jiyong Park719b4462019-01-13 00:39:51 +0900657 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, dirInApex, etc, prebuilt, nil})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900658 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900659 } else {
660 ctx.PropertyErrorf("prebuilts", "%q is not a prebuilt_etc module", depName)
661 }
662 case keyTag:
663 if key, ok := child.(*apexKey); ok {
664 keyFile = key.private_key_file
Jiyong Park835d82b2018-12-27 16:04:18 +0900665 if !key.installable() && ctx.Config().Debuggable() {
666 // If the key is not installed, bundled it with the APEX.
667 // Note: this bundled key is valid only for non-production builds
668 // (eng/userdebug).
669 pubKeyFile = key.public_key_file
670 }
Jiyong Parkff1458f2018-10-12 21:49:38 +0900671 return false
672 } else {
673 ctx.PropertyErrorf("key", "%q is not an apex_key module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900674 }
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900675 case certificateTag:
676 if dep, ok := child.(*java.AndroidAppCertificate); ok {
677 certificate = dep.Certificate
678 return false
679 } else {
680 ctx.ModuleErrorf("certificate dependency %q must be an android_app_certificate module", depName)
681 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900682 }
683 } else {
684 // indirect dependencies
685 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() && am.IsInstallableToApex() {
686 if cc, ok := child.(*cc.Module); ok {
Jiyong Park25fc6a92018-11-18 18:02:45 +0900687 if cc.IsStubs() || cc.HasStubsVariants() {
688 return false
689 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900690 depName := ctx.OtherModuleName(child)
Alex Lightfc0bd7c2019-01-29 18:31:59 -0800691 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc, handleSpecialLibs)
Jiyong Park719b4462019-01-13 00:39:51 +0900692 filesInfo = append(filesInfo, apexFile{fileToCopy, depName, dirInApex, nativeSharedLib, cc, nil})
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900693 return true
694 }
695 }
696 }
697 return false
698 })
699
Jiyong Park9335a262018-12-24 11:31:58 +0900700 a.flattened = ctx.Config().FlattenApex() && !ctx.Config().UnbundledBuild()
Jiyong Park23c52b02019-02-02 13:13:47 +0900701 if keyFile == nil {
Jiyong Parkfa0a3732018-11-09 05:52:26 +0900702 ctx.PropertyErrorf("key", "private_key for %q could not be found", String(a.properties.Key))
703 return
704 }
705
Jiyong Park8fd61922018-11-08 02:50:25 +0900706 // remove duplicates in filesInfo
707 removeDup := func(filesInfo []apexFile) []apexFile {
708 encountered := make(map[android.Path]bool)
709 result := []apexFile{}
710 for _, f := range filesInfo {
711 if !encountered[f.builtFile] {
712 encountered[f.builtFile] = true
713 result = append(result, f)
714 }
715 }
716 return result
717 }
718 filesInfo = removeDup(filesInfo)
719
720 // to have consistent build rules
721 sort.Slice(filesInfo, func(i, j int) bool {
722 return filesInfo[i].builtFile.String() < filesInfo[j].builtFile.String()
723 })
724
725 // prepend the name of this APEX to the module names. These names will be the names of
726 // modules that will be defined if the APEX is flattened.
727 for i := range filesInfo {
728 filesInfo[i].moduleName = ctx.ModuleName() + "." + filesInfo[i].moduleName
729 }
730
Jiyong Park8fd61922018-11-08 02:50:25 +0900731 a.installDir = android.PathForModuleInstall(ctx, "apex")
732 a.filesInfo = filesInfo
Alex Light5098a612018-11-29 17:12:15 -0800733
734 if a.apexTypes.zip() {
Jiyong Park835d82b2018-12-27 16:04:18 +0900735 a.buildUnflattenedApex(ctx, keyFile, pubKeyFile, certificate, zipApex)
Alex Light5098a612018-11-29 17:12:15 -0800736 }
737 if a.apexTypes.image() {
Jiyong Park23c52b02019-02-02 13:13:47 +0900738 // Build rule for unflattened APEX is created even when ctx.Config().FlattenApex()
739 // is true. This is to support referencing APEX via ":<module_name" syntax
740 // in other modules. It is in AndroidMk where the selection of flattened
741 // or unflattened APEX is made.
742 a.buildUnflattenedApex(ctx, keyFile, pubKeyFile, certificate, imageApex)
743 a.buildFlattenedApex(ctx)
Jiyong Park8fd61922018-11-08 02:50:25 +0900744 }
745}
746
Jiyong Park835d82b2018-12-27 16:04:18 +0900747func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext, keyFile android.Path,
748 pubKeyFile android.Path, certificate java.Certificate, apexType apexPackaging) {
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900749 cert := String(a.properties.Certificate)
750 if cert != "" && android.SrcIsModule(cert) == "" {
751 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
752 certificate = java.Certificate{
753 defaultDir.Join(ctx, cert+".x509.pem"),
754 defaultDir.Join(ctx, cert+".pk8"),
755 }
756 } else if cert == "" {
757 pem, key := ctx.Config().DefaultAppCertificate(ctx)
758 certificate = java.Certificate{pem, key}
759 }
760
Dario Freni4abb1dc2018-11-20 18:04:58 +0000761 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900762
Alex Light5098a612018-11-29 17:12:15 -0800763 var abis []string
764 for _, target := range ctx.MultiTargets() {
765 if len(target.Arch.Abi) > 0 {
766 abis = append(abis, target.Arch.Abi[0])
767 }
Jiyong Parkd0a65ba2018-11-10 06:37:15 +0900768 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900769
Alex Light5098a612018-11-29 17:12:15 -0800770 abis = android.FirstUniqueStrings(abis)
771
772 suffix := apexType.suffix()
773 unsignedOutputFile := android.PathForModuleOut(ctx, ctx.ModuleName()+suffix+".unsigned")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900774
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900775 filesToCopy := []android.Path{}
Jiyong Park8fd61922018-11-08 02:50:25 +0900776 for _, f := range a.filesInfo {
777 filesToCopy = append(filesToCopy, f.builtFile)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900778 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900779
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900780 copyCommands := []string{}
Jiyong Park8fd61922018-11-08 02:50:25 +0900781 for i, src := range filesToCopy {
782 dest := filepath.Join(a.filesInfo[i].installDir, src.Base())
Alex Light5098a612018-11-29 17:12:15 -0800783 dest_path := filepath.Join(android.PathForModuleOut(ctx, "image"+suffix).String(), dest)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900784 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(dest_path))
785 copyCommands = append(copyCommands, "cp "+src.String()+" "+dest_path)
Alex Light3d673592019-01-18 14:37:31 -0800786 for _, sym := range a.filesInfo[i].symlinks {
787 symlinkDest := filepath.Join(filepath.Dir(dest_path), sym)
788 copyCommands = append(copyCommands, "ln -s "+filepath.Base(dest)+" "+symlinkDest)
789 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900790 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900791 implicitInputs := append(android.Paths(nil), filesToCopy...)
Alex Light5098a612018-11-29 17:12:15 -0800792 implicitInputs = append(implicitInputs, manifest)
793
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900794 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
795 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900796
Alex Light5098a612018-11-29 17:12:15 -0800797 if apexType.image() {
798 // files and dirs that will be created in APEX
799 var readOnlyPaths []string
800 var executablePaths []string // this also includes dirs
801 for _, f := range a.filesInfo {
802 pathInApex := filepath.Join(f.installDir, f.builtFile.Base())
803 if f.installDir == "bin" {
804 executablePaths = append(executablePaths, pathInApex)
Alex Light3d673592019-01-18 14:37:31 -0800805 for _, s := range f.symlinks {
806 executablePaths = append(executablePaths, filepath.Join("bin", s))
807 }
Alex Light5098a612018-11-29 17:12:15 -0800808 } else {
809 readOnlyPaths = append(readOnlyPaths, pathInApex)
810 }
Jiyong Park7c2ee712018-12-07 00:42:25 +0900811 dir := f.installDir
812 for !android.InList(dir, executablePaths) && dir != "" {
813 executablePaths = append(executablePaths, dir)
814 dir, _ = filepath.Split(dir) // move up to the parent
815 if len(dir) > 0 {
816 // remove trailing slash
817 dir = dir[:len(dir)-1]
818 }
Alex Light5098a612018-11-29 17:12:15 -0800819 }
820 }
821 sort.Strings(readOnlyPaths)
822 sort.Strings(executablePaths)
823 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
824 ctx.Build(pctx, android.BuildParams{
825 Rule: generateFsConfig,
826 Output: cannedFsConfig,
827 Description: "generate fs config",
828 Args: map[string]string{
829 "ro_paths": strings.Join(readOnlyPaths, " "),
830 "exec_paths": strings.Join(executablePaths, " "),
831 },
832 })
833
834 fcName := proptools.StringDefault(a.properties.File_contexts, ctx.ModuleName())
835 fileContextsPath := "system/sepolicy/apex/" + fcName + "-file_contexts"
836 fileContextsOptionalPath := android.ExistentPathForSource(ctx, fileContextsPath)
837 if !fileContextsOptionalPath.Valid() {
838 ctx.ModuleErrorf("Cannot find file_contexts file: %q", fileContextsPath)
839 return
840 }
841 fileContexts := fileContextsOptionalPath.Path()
842
Jiyong Park835d82b2018-12-27 16:04:18 +0900843 optFlags := []string{}
844
Alex Light5098a612018-11-29 17:12:15 -0800845 // Additional implicit inputs.
846 implicitInputs = append(implicitInputs, cannedFsConfig, fileContexts, keyFile)
Jiyong Park835d82b2018-12-27 16:04:18 +0900847 if pubKeyFile != nil {
848 implicitInputs = append(implicitInputs, pubKeyFile)
849 optFlags = append(optFlags, "--pubkey "+pubKeyFile.String())
850 }
Alex Light5098a612018-11-29 17:12:15 -0800851
Jiyong Park7f67f482019-01-05 12:57:48 +0900852 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
853 if overridden {
854 optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
855 }
856
Alex Light5098a612018-11-29 17:12:15 -0800857 ctx.Build(pctx, android.BuildParams{
858 Rule: apexRule,
859 Implicits: implicitInputs,
860 Output: unsignedOutputFile,
861 Description: "apex (" + apexType.name() + ")",
862 Args: map[string]string{
863 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
864 "image_dir": android.PathForModuleOut(ctx, "image"+suffix).String(),
865 "copy_commands": strings.Join(copyCommands, " && "),
866 "manifest": manifest.String(),
867 "file_contexts": fileContexts.String(),
868 "canned_fs_config": cannedFsConfig.String(),
869 "key": keyFile.String(),
Jiyong Park835d82b2018-12-27 16:04:18 +0900870 "opt_flags": strings.Join(optFlags, " "),
Alex Light5098a612018-11-29 17:12:15 -0800871 },
872 })
873
874 apexProtoFile := android.PathForModuleOut(ctx, ctx.ModuleName()+".pb"+suffix)
875 bundleModuleFile := android.PathForModuleOut(ctx, ctx.ModuleName()+suffix+"-base.zip")
876 a.bundleModuleFile = bundleModuleFile
877
878 ctx.Build(pctx, android.BuildParams{
879 Rule: apexProtoConvertRule,
880 Input: unsignedOutputFile,
881 Output: apexProtoFile,
882 Description: "apex proto convert",
883 })
884
885 ctx.Build(pctx, android.BuildParams{
886 Rule: apexBundleRule,
887 Input: apexProtoFile,
888 Output: a.bundleModuleFile,
889 Description: "apex bundle module",
890 Args: map[string]string{
891 "abi": strings.Join(abis, "."),
892 },
893 })
894 } else {
895 ctx.Build(pctx, android.BuildParams{
896 Rule: zipApexRule,
897 Implicits: implicitInputs,
898 Output: unsignedOutputFile,
899 Description: "apex (" + apexType.name() + ")",
900 Args: map[string]string{
901 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
902 "image_dir": android.PathForModuleOut(ctx, "image"+suffix).String(),
903 "copy_commands": strings.Join(copyCommands, " && "),
904 "manifest": manifest.String(),
905 },
906 })
Colin Crossa4925902018-11-16 11:36:28 -0800907 }
Colin Crossa4925902018-11-16 11:36:28 -0800908
Alex Light5098a612018-11-29 17:12:15 -0800909 a.outputFiles[apexType] = android.PathForModuleOut(ctx, ctx.ModuleName()+suffix)
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900910 ctx.Build(pctx, android.BuildParams{
911 Rule: java.Signapk,
912 Description: "signapk",
Alex Light5098a612018-11-29 17:12:15 -0800913 Output: a.outputFiles[apexType],
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900914 Input: unsignedOutputFile,
915 Args: map[string]string{
916 "certificates": strings.Join([]string{certificate.Pem.String(), certificate.Key.String()}, " "),
Jiyong Parkbfe64a12018-11-22 02:51:54 +0900917 "flags": "-a 4096", //alignment
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900918 },
919 })
Alex Light5098a612018-11-29 17:12:15 -0800920
921 // Install to $OUT/soong/{target,host}/.../apex
Jiyong Park23c52b02019-02-02 13:13:47 +0900922 if a.installable() && !ctx.Config().FlattenApex() {
Jiyong Park92c0f9c2018-12-13 23:14:57 +0900923 ctx.InstallFile(android.PathForModuleInstall(ctx, "apex"), ctx.ModuleName()+suffix, a.outputFiles[apexType])
924 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900925}
Jiyong Parkc00cbd92018-10-30 21:20:05 +0900926
Jiyong Park8fd61922018-11-08 02:50:25 +0900927func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
Jiyong Park92c0f9c2018-12-13 23:14:57 +0900928 if a.installable() {
929 // For flattened APEX, do nothing but make sure that apex_manifest.json file is also copied along
930 // with other ordinary files.
931 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
Jiyong Parkd699cb92019-01-10 00:23:16 +0900932
933 // rename to apex_manifest.json
934 copiedManifest := android.PathForModuleOut(ctx, "apex_manifest.json")
935 ctx.Build(pctx, android.BuildParams{
936 Rule: android.Cp,
937 Input: manifest,
938 Output: copiedManifest,
939 })
Jiyong Park719b4462019-01-13 00:39:51 +0900940 a.filesInfo = append(a.filesInfo, apexFile{copiedManifest, ctx.ModuleName() + ".apex_manifest.json", ".", etc, nil, nil})
Jiyong Park8fd61922018-11-08 02:50:25 +0900941
Jiyong Park23c52b02019-02-02 13:13:47 +0900942 if ctx.Config().FlattenApex() {
943 for _, fi := range a.filesInfo {
944 dir := filepath.Join("apex", ctx.ModuleName(), fi.installDir)
945 ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.builtFile.Base(), fi.builtFile)
946 }
Jiyong Park92c0f9c2018-12-13 23:14:57 +0900947 }
Jiyong Park8fd61922018-11-08 02:50:25 +0900948 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900949}
950
951func (a *apexBundle) AndroidMk() android.AndroidMkData {
Alex Light5098a612018-11-29 17:12:15 -0800952 writers := []android.AndroidMkData{}
953 if a.apexTypes.image() {
954 writers = append(writers, a.androidMkForType(imageApex))
955 }
956 if a.apexTypes.zip() {
957 writers = append(writers, a.androidMkForType(zipApex))
958 }
959 return android.AndroidMkData{
960 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
961 for _, data := range writers {
962 data.Custom(w, name, prefix, moduleDir, data)
963 }
964 }}
965}
966
Jiyong Park94427262019-02-05 23:18:47 +0900967func (a *apexBundle) androidMkForFiles(w io.Writer, name, moduleDir string) []string {
968 moduleNames := []string{}
969
970 for _, fi := range a.filesInfo {
971 if cc, ok := fi.module.(*cc.Module); ok && cc.Properties.HideFromMake {
972 continue
973 }
974 if !android.InList(fi.moduleName, moduleNames) {
975 moduleNames = append(moduleNames, fi.moduleName)
976 }
977 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
978 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
979 fmt.Fprintln(w, "LOCAL_MODULE :=", fi.moduleName)
980 if a.flattened {
981 // /system/apex/<name>/{lib|framework|...}
982 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)",
983 a.installDir.RelPathString(), name, fi.installDir))
984 } else {
985 // /apex/<name>/{lib|framework|...}
986 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(PRODUCT_OUT)",
987 "apex", name, fi.installDir))
988 }
989 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", fi.builtFile.String())
990 fmt.Fprintln(w, "LOCAL_MODULE_CLASS :=", fi.class.NameInMake())
991 if fi.module != nil {
992 archStr := fi.module.Target().Arch.ArchType.String()
993 host := false
994 switch fi.module.Target().Os.Class {
995 case android.Host:
996 if archStr != "common" {
997 fmt.Fprintln(w, "LOCAL_MODULE_HOST_ARCH :=", archStr)
998 }
999 host = true
1000 case android.HostCross:
1001 if archStr != "common" {
1002 fmt.Fprintln(w, "LOCAL_MODULE_HOST_CROSS_ARCH :=", archStr)
1003 }
1004 host = true
1005 case android.Device:
1006 if archStr != "common" {
1007 fmt.Fprintln(w, "LOCAL_MODULE_TARGET_ARCH :=", archStr)
1008 }
1009 }
1010 if host {
1011 makeOs := fi.module.Target().Os.String()
1012 if fi.module.Target().Os == android.Linux || fi.module.Target().Os == android.LinuxBionic {
1013 makeOs = "linux"
1014 }
1015 fmt.Fprintln(w, "LOCAL_MODULE_HOST_OS :=", makeOs)
1016 fmt.Fprintln(w, "LOCAL_IS_HOST_MODULE := true")
1017 }
1018 }
1019 if fi.class == javaSharedLib {
1020 javaModule := fi.module.(*java.Library)
1021 // soong_java_prebuilt.mk sets LOCAL_MODULE_SUFFIX := .jar Therefore
1022 // we need to remove the suffix from LOCAL_MODULE_STEM, otherwise
1023 // we will have foo.jar.jar
1024 fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", strings.TrimSuffix(fi.builtFile.Base(), ".jar"))
1025 fmt.Fprintln(w, "LOCAL_SOONG_CLASSES_JAR :=", javaModule.ImplementationAndResourcesJars()[0].String())
1026 fmt.Fprintln(w, "LOCAL_SOONG_HEADER_JAR :=", javaModule.HeaderJars()[0].String())
1027 fmt.Fprintln(w, "LOCAL_SOONG_DEX_JAR :=", fi.builtFile.String())
1028 fmt.Fprintln(w, "LOCAL_DEX_PREOPT := false")
1029 fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_java_prebuilt.mk")
1030 } else if fi.class == nativeSharedLib || fi.class == nativeExecutable {
1031 fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", fi.builtFile.Base())
1032 if cc, ok := fi.module.(*cc.Module); ok && cc.UnstrippedOutputFile() != nil {
1033 fmt.Fprintln(w, "LOCAL_SOONG_UNSTRIPPED_BINARY :=", cc.UnstrippedOutputFile().String())
1034 }
1035 fmt.Fprintln(w, "include $(BUILD_SYSTEM)/soong_cc_prebuilt.mk")
1036 } else {
1037 fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", fi.builtFile.Base())
1038 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
1039 }
1040 }
1041 return moduleNames
1042}
1043
Alex Light5098a612018-11-29 17:12:15 -08001044func (a *apexBundle) androidMkForType(apexType apexPackaging) android.AndroidMkData {
Jiyong Park719b4462019-01-13 00:39:51 +09001045 return android.AndroidMkData{
1046 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
1047 moduleNames := []string{}
Jiyong Park94427262019-02-05 23:18:47 +09001048 if a.installable() {
Jiyong Park41229f52019-02-07 16:46:59 +09001049 moduleNames = a.androidMkForFiles(w, name, moduleDir)
Jiyong Park719b4462019-01-13 00:39:51 +09001050 }
1051
Jiyong Park719b4462019-01-13 00:39:51 +09001052 if a.flattened && apexType.image() {
1053 // Only image APEXes can be flattened.
Jiyong Park8fd61922018-11-08 02:50:25 +09001054 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
1055 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
1056 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
Jiyong Park94427262019-02-05 23:18:47 +09001057 if len(moduleNames) > 0 {
1058 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", strings.Join(moduleNames, " "))
1059 }
Jiyong Park8fd61922018-11-08 02:50:25 +09001060 fmt.Fprintln(w, "include $(BUILD_PHONY_PACKAGE)")
Jiyong Park719b4462019-01-13 00:39:51 +09001061 } else {
Alex Light5098a612018-11-29 17:12:15 -08001062 // zip-apex is the less common type so have the name refer to the image-apex
1063 // only and use {name}.zip if you want the zip-apex
1064 if apexType == zipApex && a.apexTypes == both {
1065 name = name + ".zip"
1066 }
Jiyong Park8fd61922018-11-08 02:50:25 +09001067 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
1068 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
1069 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
1070 fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC") // do we need a new class?
Alex Light5098a612018-11-29 17:12:15 -08001071 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", a.outputFiles[apexType].String())
Jiyong Park8fd61922018-11-08 02:50:25 +09001072 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString()))
Colin Cross189ff982019-01-02 22:32:27 -08001073 fmt.Fprintln(w, "LOCAL_MODULE_STEM :=", name+apexType.suffix())
Jiyong Park92c0f9c2018-12-13 23:14:57 +09001074 fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE :=", !a.installable())
Jiyong Park8fd61922018-11-08 02:50:25 +09001075 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", String(a.properties.Key))
Jiyong Park94427262019-02-05 23:18:47 +09001076 if len(moduleNames) > 0 {
1077 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES +=", strings.Join(moduleNames, " "))
1078 }
Jiyong Park8fd61922018-11-08 02:50:25 +09001079 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
Colin Crossa4925902018-11-16 11:36:28 -08001080
Alex Light5098a612018-11-29 17:12:15 -08001081 if apexType == imageApex {
1082 fmt.Fprintln(w, "ALL_MODULES.$(LOCAL_MODULE).BUNDLE :=", a.bundleModuleFile.String())
1083 }
Jiyong Park719b4462019-01-13 00:39:51 +09001084 }
1085 }}
Jiyong Park48ca7dc2018-10-10 14:01:00 +09001086}
1087
Alex Lightee250722018-12-06 14:00:02 -08001088func ApexBundleFactory() android.Module {
Alex Light5098a612018-11-29 17:12:15 -08001089 module := &apexBundle{
1090 outputFiles: map[apexPackaging]android.WritablePath{},
1091 }
Jiyong Park48ca7dc2018-10-10 14:01:00 +09001092 module.AddProperties(&module.properties)
Alex Light9670d332019-01-29 18:07:33 -08001093 module.AddProperties(&module.targetProperties)
Alex Light5098a612018-11-29 17:12:15 -08001094 module.Prefer32(func(ctx android.BaseModuleContext, base *android.ModuleBase, class android.OsClass) bool {
Jiyong Park397e55e2018-10-24 21:09:55 +09001095 return class == android.Device && ctx.Config().DevicePrefer32BitExecutables()
1096 })
Alex Light5098a612018-11-29 17:12:15 -08001097 android.InitAndroidMultiTargetsArchModule(module, android.HostAndDeviceSupported, android.MultilibCommon)
Jiyong Park48ca7dc2018-10-10 14:01:00 +09001098 android.InitDefaultableModule(module)
1099 return module
1100}