blob: 290c1ea90b5d620861613e50e4c1a098d2b879e7 [file] [log] [blame]
Jiyong Park09d77522019-11-18 11:16:27 +09001// Copyright (C) 2019 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 "path/filepath"
20 "runtime"
21 "sort"
22 "strings"
23
24 "android/soong/android"
25 "android/soong/java"
26
27 "github.com/google/blueprint"
28 "github.com/google/blueprint/proptools"
29)
30
31var (
32 pctx = android.NewPackageContext("android/apex")
33)
34
35func init() {
36 pctx.Import("android/soong/android")
37 pctx.Import("android/soong/java")
38 pctx.HostBinToolVariable("apexer", "apexer")
39 // ART minimal builds (using the master-art manifest) do not have the "frameworks/base"
40 // projects, and hence cannot built 'aapt2'. Use the SDK prebuilt instead.
41 hostBinToolVariableWithPrebuilt := func(name, prebuiltDir, tool string) {
42 pctx.VariableFunc(name, func(ctx android.PackageVarContext) string {
43 if !ctx.Config().FrameworksBaseDirExists(ctx) {
44 return filepath.Join(prebuiltDir, runtime.GOOS, "bin", tool)
45 } else {
Martin Stjernholm7260d062019-12-09 21:47:14 +000046 return ctx.Config().HostToolPath(ctx, tool).String()
Jiyong Park09d77522019-11-18 11:16:27 +090047 }
48 })
49 }
50 hostBinToolVariableWithPrebuilt("aapt2", "prebuilts/sdk/tools", "aapt2")
51 pctx.HostBinToolVariable("avbtool", "avbtool")
52 pctx.HostBinToolVariable("e2fsdroid", "e2fsdroid")
53 pctx.HostBinToolVariable("merge_zips", "merge_zips")
54 pctx.HostBinToolVariable("mke2fs", "mke2fs")
55 pctx.HostBinToolVariable("resize2fs", "resize2fs")
56 pctx.HostBinToolVariable("sefcontext_compile", "sefcontext_compile")
57 pctx.HostBinToolVariable("soong_zip", "soong_zip")
58 pctx.HostBinToolVariable("zip2zip", "zip2zip")
59 pctx.HostBinToolVariable("zipalign", "zipalign")
60 pctx.HostBinToolVariable("jsonmodify", "jsonmodify")
61 pctx.HostBinToolVariable("conv_apex_manifest", "conv_apex_manifest")
62}
63
64var (
65 // Create a canned fs config file where all files and directories are
66 // by default set to (uid/gid/mode) = (1000/1000/0644)
67 // TODO(b/113082813) make this configurable using config.fs syntax
68 generateFsConfig = pctx.StaticRule("generateFsConfig", blueprint.RuleParams{
69 Command: `echo '/ 1000 1000 0755' > ${out} && ` +
70 `echo ${ro_paths} | tr ' ' '\n' | awk '{print "/"$$1 " 1000 1000 0644"}' >> ${out} && ` +
71 `echo ${exec_paths} | tr ' ' '\n' | awk '{print "/"$$1 " 0 2000 0755"}' >> ${out}`,
72 Description: "fs_config ${out}",
73 }, "ro_paths", "exec_paths")
74
75 apexManifestRule = pctx.StaticRule("apexManifestRule", blueprint.RuleParams{
76 Command: `rm -f $out && ${jsonmodify} $in ` +
77 `-a provideNativeLibs ${provideNativeLibs} ` +
78 `-a requireNativeLibs ${requireNativeLibs} ` +
79 `${opt} ` +
80 `-o $out`,
81 CommandDeps: []string{"${jsonmodify}"},
82 Description: "prepare ${out}",
83 }, "provideNativeLibs", "requireNativeLibs", "opt")
84
85 stripApexManifestRule = pctx.StaticRule("stripApexManifestRule", blueprint.RuleParams{
86 Command: `rm -f $out && ${conv_apex_manifest} strip $in -o $out`,
87 CommandDeps: []string{"${conv_apex_manifest}"},
88 Description: "strip ${in}=>${out}",
89 })
90
91 pbApexManifestRule = pctx.StaticRule("pbApexManifestRule", blueprint.RuleParams{
92 Command: `rm -f $out && ${conv_apex_manifest} proto $in -o $out`,
93 CommandDeps: []string{"${conv_apex_manifest}"},
94 Description: "convert ${in}=>${out}",
95 })
96
97 // TODO(b/113233103): make sure that file_contexts is sane, i.e., validate
98 // against the binary policy using sefcontext_compiler -p <policy>.
99
100 // TODO(b/114327326): automate the generation of file_contexts
101 apexRule = pctx.StaticRule("apexRule", blueprint.RuleParams{
102 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
103 `(. ${out}.copy_commands) && ` +
104 `APEXER_TOOL_PATH=${tool_path} ` +
105 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900106 `--file_contexts ${file_contexts} ` +
107 `--canned_fs_config ${canned_fs_config} ` +
Dario Freni0f4ae072020-01-02 15:24:12 +0000108 `--include_build_info ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900109 `--payload_type image ` +
110 `--key ${key} ${opt_flags} ${image_dir} ${out} `,
111 CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
112 "${mke2fs}", "${resize2fs}", "${sefcontext_compile}",
113 "${soong_zip}", "${zipalign}", "${aapt2}", "prebuilts/sdk/current/public/android.jar"},
114 Rspfile: "${out}.copy_commands",
115 RspfileContent: "${copy_commands}",
116 Description: "APEX ${image_dir} => ${out}",
Jooyung Han214bf372019-11-12 13:03:50 +0900117 }, "tool_path", "image_dir", "copy_commands", "file_contexts", "canned_fs_config", "key", "opt_flags", "manifest")
Jiyong Park09d77522019-11-18 11:16:27 +0900118
119 zipApexRule = pctx.StaticRule("zipApexRule", blueprint.RuleParams{
120 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
121 `(. ${out}.copy_commands) && ` +
122 `APEXER_TOOL_PATH=${tool_path} ` +
Jooyung Han214bf372019-11-12 13:03:50 +0900123 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900124 `--payload_type zip ` +
125 `${image_dir} ${out} `,
126 CommandDeps: []string{"${apexer}", "${merge_zips}", "${soong_zip}", "${zipalign}", "${aapt2}"},
127 Rspfile: "${out}.copy_commands",
128 RspfileContent: "${copy_commands}",
129 Description: "ZipAPEX ${image_dir} => ${out}",
Jooyung Han214bf372019-11-12 13:03:50 +0900130 }, "tool_path", "image_dir", "copy_commands", "manifest")
Jiyong Park09d77522019-11-18 11:16:27 +0900131
132 apexProtoConvertRule = pctx.AndroidStaticRule("apexProtoConvertRule",
133 blueprint.RuleParams{
134 Command: `${aapt2} convert --output-format proto $in -o $out`,
135 CommandDeps: []string{"${aapt2}"},
136 })
137
138 apexBundleRule = pctx.StaticRule("apexBundleRule", blueprint.RuleParams{
139 Command: `${zip2zip} -i $in -o $out ` +
140 `apex_payload.img:apex/${abi}.img ` +
141 `apex_manifest.json:root/apex_manifest.json ` +
Jiyong Park53ae3342019-12-08 02:06:24 +0900142 `apex_manifest.pb:root/apex_manifest.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900143 `AndroidManifest.xml:manifest/AndroidManifest.xml ` +
144 `assets/NOTICE.html.gz:assets/NOTICE.html.gz`,
145 CommandDeps: []string{"${zip2zip}"},
146 Description: "app bundle",
147 }, "abi")
148
149 emitApexContentRule = pctx.StaticRule("emitApexContentRule", blueprint.RuleParams{
150 Command: `rm -f ${out} && touch ${out} && (. ${out}.emit_commands)`,
151 Rspfile: "${out}.emit_commands",
152 RspfileContent: "${emit_commands}",
153 Description: "Emit APEX image content",
154 }, "emit_commands")
155
156 diffApexContentRule = pctx.StaticRule("diffApexContentRule", blueprint.RuleParams{
157 Command: `diff --unchanged-group-format='' \` +
158 `--changed-group-format='%<' \` +
159 `${image_content_file} ${whitelisted_files_file} || (` +
160 `echo -e "New unexpected files were added to ${apex_module_name}." ` +
161 ` "To fix the build run following command:" && ` +
162 `echo "system/apex/tools/update_whitelist.sh ${whitelisted_files_file} ${image_content_file}" && ` +
163 `exit 1)`,
164 Description: "Diff ${image_content_file} and ${whitelisted_files_file}",
165 }, "image_content_file", "whitelisted_files_file", "apex_module_name")
166)
167
168func (a *apexBundle) buildManifest(ctx android.ModuleContext, provideNativeLibs, requireNativeLibs []string) {
169 manifestSrc := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
170
Jooyung Han214bf372019-11-12 13:03:50 +0900171 manifestJsonFullOut := android.PathForModuleOut(ctx, "apex_manifest_full.json")
Jiyong Park09d77522019-11-18 11:16:27 +0900172
173 // put dependency({provide|require}NativeLibs) in apex_manifest.json
174 provideNativeLibs = android.SortedUniqueStrings(provideNativeLibs)
175 requireNativeLibs = android.SortedUniqueStrings(android.RemoveListFromList(requireNativeLibs, provideNativeLibs))
176
177 // apex name can be overridden
178 optCommands := []string{}
179 if a.properties.Apex_name != nil {
180 optCommands = append(optCommands, "-v name "+*a.properties.Apex_name)
181 }
182
183 ctx.Build(pctx, android.BuildParams{
184 Rule: apexManifestRule,
185 Input: manifestSrc,
Jooyung Han214bf372019-11-12 13:03:50 +0900186 Output: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900187 Args: map[string]string{
188 "provideNativeLibs": strings.Join(provideNativeLibs, " "),
189 "requireNativeLibs": strings.Join(requireNativeLibs, " "),
190 "opt": strings.Join(optCommands, " "),
191 },
192 })
193
Jooyung Han214bf372019-11-12 13:03:50 +0900194 if proptools.Bool(a.properties.Legacy_android10_support) {
195 // b/143654022 Q apexd can't understand newly added keys in apex_manifest.json
196 // prepare stripped-down version so that APEX modules built from R+ can be installed to Q
197 a.manifestJsonOut = android.PathForModuleOut(ctx, "apex_manifest.json")
198 ctx.Build(pctx, android.BuildParams{
199 Rule: stripApexManifestRule,
200 Input: manifestJsonFullOut,
201 Output: a.manifestJsonOut,
202 })
203 }
Jiyong Park09d77522019-11-18 11:16:27 +0900204
205 // from R+, protobuf binary format (.pb) is the standard format for apex_manifest
206 a.manifestPbOut = android.PathForModuleOut(ctx, "apex_manifest.pb")
207 ctx.Build(pctx, android.BuildParams{
208 Rule: pbApexManifestRule,
Jooyung Han214bf372019-11-12 13:03:50 +0900209 Input: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900210 Output: a.manifestPbOut,
211 })
212}
213
214func (a *apexBundle) buildNoticeFile(ctx android.ModuleContext, apexFileName string) android.OptionalPath {
215 noticeFiles := []android.Path{}
216 for _, f := range a.filesInfo {
217 if f.module != nil {
218 notice := f.module.NoticeFile()
219 if notice.Valid() {
220 noticeFiles = append(noticeFiles, notice.Path())
221 }
222 }
223 }
224 // append the notice file specified in the apex module itself
225 if a.NoticeFile().Valid() {
226 noticeFiles = append(noticeFiles, a.NoticeFile().Path())
227 }
228
229 if len(noticeFiles) == 0 {
230 return android.OptionalPath{}
231 }
232
233 return android.BuildNoticeOutput(ctx, a.installDir, apexFileName, android.FirstUniquePaths(noticeFiles)).HtmlGzOutput
234}
235
Jiyong Park3a1602e2020-01-14 14:39:19 +0900236func (a *apexBundle) buildInstalledFilesFile(ctx android.ModuleContext, builtApex android.Path, imageDir android.Path) android.OutputPath {
237 output := android.PathForModuleOut(ctx, "installed-files.txt")
238 rule := android.NewRuleBuilder()
239 rule.Command().
240 Implicit(builtApex).
241 Text("(cd " + imageDir.String() + " ; ").
242 Text("find . -type f -printf \"%s %p\\n\") ").
243 Text(" | sort -nr > ").
244 Output(output)
245 rule.Build(pctx, ctx, "installed-files."+a.Name(), "Installed files")
246 return output.OutputPath
247}
248
Jiyong Park09d77522019-11-18 11:16:27 +0900249func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext) {
250 var abis []string
251 for _, target := range ctx.MultiTargets() {
252 if len(target.Arch.Abi) > 0 {
253 abis = append(abis, target.Arch.Abi[0])
254 }
255 }
256
257 abis = android.FirstUniqueStrings(abis)
258
259 apexType := a.properties.ApexType
260 suffix := apexType.suffix()
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800261 unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
Jiyong Park09d77522019-11-18 11:16:27 +0900262
263 filesToCopy := []android.Path{}
264 for _, f := range a.filesInfo {
265 filesToCopy = append(filesToCopy, f.builtFile)
266 }
267
268 copyCommands := []string{}
269 emitCommands := []string{}
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800270 imageContentFile := android.PathForModuleOut(ctx, a.Name()+"-content.txt")
Jooyung Han214bf372019-11-12 13:03:50 +0900271 emitCommands = append(emitCommands, "echo ./apex_manifest.pb >> "+imageContentFile.String())
272 if proptools.Bool(a.properties.Legacy_android10_support) {
273 emitCommands = append(emitCommands, "echo ./apex_manifest.json >> "+imageContentFile.String())
274 }
Jiyong Park09d77522019-11-18 11:16:27 +0900275 for i, src := range filesToCopy {
276 dest := filepath.Join(a.filesInfo[i].installDir, src.Base())
277 emitCommands = append(emitCommands, "echo './"+dest+"' >> "+imageContentFile.String())
278 dest_path := filepath.Join(android.PathForModuleOut(ctx, "image"+suffix).String(), dest)
279 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(dest_path))
280 copyCommands = append(copyCommands, "cp "+src.String()+" "+dest_path)
281 for _, sym := range a.filesInfo[i].symlinks {
282 symlinkDest := filepath.Join(filepath.Dir(dest_path), sym)
283 copyCommands = append(copyCommands, "ln -s "+filepath.Base(dest)+" "+symlinkDest)
284 }
285 }
286 emitCommands = append(emitCommands, "sort -o "+imageContentFile.String()+" "+imageContentFile.String())
287
288 implicitInputs := append(android.Paths(nil), filesToCopy...)
Jooyung Han214bf372019-11-12 13:03:50 +0900289 implicitInputs = append(implicitInputs, a.manifestPbOut)
Jiyong Park09d77522019-11-18 11:16:27 +0900290
291 if a.properties.Whitelisted_files != nil {
292 ctx.Build(pctx, android.BuildParams{
293 Rule: emitApexContentRule,
294 Implicits: implicitInputs,
295 Output: imageContentFile,
296 Description: "emit apex image content",
297 Args: map[string]string{
298 "emit_commands": strings.Join(emitCommands, " && "),
299 },
300 })
301 implicitInputs = append(implicitInputs, imageContentFile)
302 whitelistedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.Whitelisted_files))
303
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800304 phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
Jiyong Park09d77522019-11-18 11:16:27 +0900305 ctx.Build(pctx, android.BuildParams{
306 Rule: diffApexContentRule,
307 Implicits: implicitInputs,
308 Output: phonyOutput,
309 Description: "diff apex image content",
310 Args: map[string]string{
311 "whitelisted_files_file": whitelistedFilesFile.String(),
312 "image_content_file": imageContentFile.String(),
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800313 "apex_module_name": a.Name(),
Jiyong Park09d77522019-11-18 11:16:27 +0900314 },
315 })
316
317 implicitInputs = append(implicitInputs, phonyOutput)
318 }
319
320 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
321 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
322
Jiyong Park3a1602e2020-01-14 14:39:19 +0900323 imageDir := android.PathForModuleOut(ctx, "image"+suffix)
Jiyong Park09d77522019-11-18 11:16:27 +0900324 if apexType == imageApex {
325 // files and dirs that will be created in APEX
326 var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
327 var executablePaths []string // this also includes dirs
328 for _, f := range a.filesInfo {
329 pathInApex := filepath.Join(f.installDir, f.builtFile.Base())
330 if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
331 executablePaths = append(executablePaths, pathInApex)
332 for _, s := range f.symlinks {
333 executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
334 }
335 } else {
336 readOnlyPaths = append(readOnlyPaths, pathInApex)
337 }
338 dir := f.installDir
339 for !android.InList(dir, executablePaths) && dir != "" {
340 executablePaths = append(executablePaths, dir)
341 dir, _ = filepath.Split(dir) // move up to the parent
342 if len(dir) > 0 {
343 // remove trailing slash
344 dir = dir[:len(dir)-1]
345 }
346 }
347 }
348 sort.Strings(readOnlyPaths)
349 sort.Strings(executablePaths)
350 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
351 ctx.Build(pctx, android.BuildParams{
352 Rule: generateFsConfig,
353 Output: cannedFsConfig,
354 Description: "generate fs config",
355 Args: map[string]string{
356 "ro_paths": strings.Join(readOnlyPaths, " "),
357 "exec_paths": strings.Join(executablePaths, " "),
358 },
359 })
360
Jiyong Park09d77522019-11-18 11:16:27 +0900361 optFlags := []string{}
362
363 // Additional implicit inputs.
Jooyung Han54aca7b2019-11-20 02:26:02 +0900364 implicitInputs = append(implicitInputs, cannedFsConfig, a.fileContexts, a.private_key_file, a.public_key_file)
Jiyong Park09d77522019-11-18 11:16:27 +0900365 optFlags = append(optFlags, "--pubkey "+a.public_key_file.String())
366
Jooyung Han27151d92019-12-16 17:45:32 +0900367 manifestPackageName := a.getOverrideManifestPackageName(ctx)
368 if manifestPackageName != "" {
Jiyong Park09d77522019-11-18 11:16:27 +0900369 optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
370 }
371
372 if a.properties.AndroidManifest != nil {
373 androidManifestFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.AndroidManifest))
374 implicitInputs = append(implicitInputs, androidManifestFile)
375 optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
376 }
377
378 targetSdkVersion := ctx.Config().DefaultAppTargetSdk()
Baligh Uddinf6201372020-01-24 23:15:44 +0000379 minSdkVersion := ctx.Config().DefaultAppTargetSdk()
380 if java.UseApiFingerprint(ctx, targetSdkVersion) {
381 targetSdkVersion += fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
382 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
383 }
384 if java.UseApiFingerprint(ctx, minSdkVersion) {
385 minSdkVersion += fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
386 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
Jiyong Park09d77522019-11-18 11:16:27 +0900387 }
388 optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
Baligh Uddinf6201372020-01-24 23:15:44 +0000389 optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
Jiyong Park09d77522019-11-18 11:16:27 +0900390
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800391 noticeFile := a.buildNoticeFile(ctx, a.Name()+suffix)
Jiyong Park09d77522019-11-18 11:16:27 +0900392 if noticeFile.Valid() {
393 // If there's a NOTICE file, embed it as an asset file in the APEX.
394 implicitInputs = append(implicitInputs, noticeFile.Path())
395 optFlags = append(optFlags, "--assets_dir "+filepath.Dir(noticeFile.String()))
396 }
397
Nikita Ioffeb4b44c02020-01-02 23:01:39 +0000398 if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && ctx.ModuleDir() != "system/apex/shim/build" && a.testOnlyShouldSkipHashtreeGeneration() {
Nikita Ioffec72b5dd2019-12-07 17:30:22 +0000399 ctx.PropertyErrorf("test_only_no_hashtree", "not available")
400 return
401 }
Dario Frenie3546902020-01-14 23:50:25 +0000402 if !proptools.Bool(a.properties.Legacy_android10_support) || a.testOnlyShouldSkipHashtreeGeneration() {
Jiyong Park09d77522019-11-18 11:16:27 +0900403 // Apexes which are supposed to be installed in builtin dirs(/system, etc)
404 // don't need hashtree for activation. Therefore, by removing hashtree from
405 // apex bundle (filesystem image in it, to be specific), we can save storage.
406 optFlags = append(optFlags, "--no_hashtree")
407 }
408
409 if a.properties.Apex_name != nil {
410 // If apex_name is set, apexer can skip checking if key name matches with apex name.
411 // Note that apex_manifest is also mended.
412 optFlags = append(optFlags, "--do_not_check_keyname")
413 }
414
Jooyung Han214bf372019-11-12 13:03:50 +0900415 if proptools.Bool(a.properties.Legacy_android10_support) {
416 implicitInputs = append(implicitInputs, a.manifestJsonOut)
417 optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
418 }
419
Jiyong Park09d77522019-11-18 11:16:27 +0900420 ctx.Build(pctx, android.BuildParams{
421 Rule: apexRule,
422 Implicits: implicitInputs,
423 Output: unsignedOutputFile,
424 Description: "apex (" + apexType.name() + ")",
425 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900426 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900427 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900428 "copy_commands": strings.Join(copyCommands, " && "),
429 "manifest": a.manifestPbOut.String(),
430 "file_contexts": a.fileContexts.String(),
431 "canned_fs_config": cannedFsConfig.String(),
432 "key": a.private_key_file.String(),
433 "opt_flags": strings.Join(optFlags, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900434 },
435 })
436
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800437 apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
438 bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
Jiyong Park09d77522019-11-18 11:16:27 +0900439 a.bundleModuleFile = bundleModuleFile
440
441 ctx.Build(pctx, android.BuildParams{
442 Rule: apexProtoConvertRule,
443 Input: unsignedOutputFile,
444 Output: apexProtoFile,
445 Description: "apex proto convert",
446 })
447
448 ctx.Build(pctx, android.BuildParams{
449 Rule: apexBundleRule,
450 Input: apexProtoFile,
451 Output: a.bundleModuleFile,
452 Description: "apex bundle module",
453 Args: map[string]string{
454 "abi": strings.Join(abis, "."),
455 },
456 })
457 } else {
458 ctx.Build(pctx, android.BuildParams{
459 Rule: zipApexRule,
460 Implicits: implicitInputs,
461 Output: unsignedOutputFile,
462 Description: "apex (" + apexType.name() + ")",
463 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900464 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900465 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900466 "copy_commands": strings.Join(copyCommands, " && "),
467 "manifest": a.manifestPbOut.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900468 },
469 })
470 }
471
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800472 a.outputFile = android.PathForModuleOut(ctx, a.Name()+suffix)
Jiyong Park09d77522019-11-18 11:16:27 +0900473 ctx.Build(pctx, android.BuildParams{
474 Rule: java.Signapk,
475 Description: "signapk",
476 Output: a.outputFile,
477 Input: unsignedOutputFile,
478 Implicits: []android.Path{
479 a.container_certificate_file,
480 a.container_private_key_file,
481 },
482 Args: map[string]string{
483 "certificates": a.container_certificate_file.String() + " " + a.container_private_key_file.String(),
484 "flags": "-a 4096", //alignment
485 },
486 })
487
488 // Install to $OUT/soong/{target,host}/.../apex
489 if a.installable() {
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800490 ctx.InstallFile(a.installDir, a.Name()+suffix, a.outputFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900491 }
492 a.buildFilesInfo(ctx)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900493
494 // installed-files.txt is dist'ed
495 a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900496}
497
498func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
499 // Temporarily wrap the original `ctx` into a `flattenedApexContext` to have it
500 // reply true to `InstallBypassMake()` (thus making the call
501 // `android.PathForModuleInstall` below use `android.pathForInstallInMakeDir`
502 // instead of `android.PathForOutput`) to return the correct path to the flattened
503 // APEX (as its contents is installed by Make, not Soong).
504 factx := flattenedApexContext{ctx}
505 apexName := proptools.StringDefault(a.properties.Apex_name, ctx.ModuleName())
506 a.outputFile = android.PathForModuleInstall(&factx, "apex", apexName)
507
Jiyong Park317645e2019-12-05 13:20:58 +0900508 if a.installable() && a.GetOverriddenBy() == "" {
Jooyung Han54aca7b2019-11-20 02:26:02 +0900509 installPath := android.PathForModuleInstall(ctx, "apex", apexName)
510 devicePath := android.InstallPathToOnDevicePath(ctx, installPath)
511 addFlattenedFileContextsInfos(ctx, apexName+":"+devicePath+":"+a.fileContexts.String())
512 }
Jiyong Park09d77522019-11-18 11:16:27 +0900513 a.buildFilesInfo(ctx)
514}
515
516func (a *apexBundle) setCertificateAndPrivateKey(ctx android.ModuleContext) {
Jooyung Hanf121a652019-12-17 14:30:11 +0900517 if a.container_certificate_file == nil {
518 cert := String(a.properties.Certificate)
519 if cert == "" {
520 pem, key := ctx.Config().DefaultAppCertificate(ctx)
521 a.container_certificate_file = pem
522 a.container_private_key_file = key
523 } else {
524 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
525 a.container_certificate_file = defaultDir.Join(ctx, cert+".x509.pem")
526 a.container_private_key_file = defaultDir.Join(ctx, cert+".pk8")
527 }
Jiyong Park09d77522019-11-18 11:16:27 +0900528 }
529}
530
531func (a *apexBundle) buildFilesInfo(ctx android.ModuleContext) {
532 if a.installable() {
Jooyung Han214bf372019-11-12 13:03:50 +0900533 // For flattened APEX, do nothing but make sure that APEX manifest and apex_pubkey are also copied along
Jiyong Park09d77522019-11-18 11:16:27 +0900534 // with other ordinary files.
Jiyong Park1833cef2019-12-13 13:28:36 +0900535 a.filesInfo = append(a.filesInfo, newApexFile(ctx, a.manifestPbOut, "apex_manifest.pb."+a.Name()+a.suffix, ".", etc, nil))
Jiyong Park09d77522019-11-18 11:16:27 +0900536
537 // rename to apex_pubkey
538 copiedPubkey := android.PathForModuleOut(ctx, "apex_pubkey")
539 ctx.Build(pctx, android.BuildParams{
540 Rule: android.Cp,
541 Input: a.public_key_file,
542 Output: copiedPubkey,
543 })
Jiyong Park1833cef2019-12-13 13:28:36 +0900544 a.filesInfo = append(a.filesInfo, newApexFile(ctx, copiedPubkey, "apex_pubkey."+a.Name()+a.suffix, ".", etc, nil))
Jiyong Park09d77522019-11-18 11:16:27 +0900545
546 if a.properties.ApexType == flattenedApex {
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800547 apexName := proptools.StringDefault(a.properties.Apex_name, a.Name())
Jiyong Park09d77522019-11-18 11:16:27 +0900548 for _, fi := range a.filesInfo {
549 dir := filepath.Join("apex", apexName, fi.installDir)
550 target := ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.builtFile.Base(), fi.builtFile)
551 for _, sym := range fi.symlinks {
552 ctx.InstallSymlink(android.PathForModuleInstall(ctx, dir), sym, target)
553 }
554 }
555 }
556 }
557}
Jooyung Han27151d92019-12-16 17:45:32 +0900558
559func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
560 // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
561 // to see if it should be overridden because their <apex name> is dynamically generated
562 // according to its VNDK version.
563 if a.vndkApex {
564 overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
565 if overridden {
566 return strings.Replace(*a.properties.Apex_name, vndkApexName, overrideName, 1)
567 }
568 return ""
569 }
570 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(a.Name())
571 if overridden {
572 return manifestPackageName
573 }
574 return ""
575}
Jiyong Park83dc74b2020-01-14 18:38:44 +0900576
577func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
578 if !a.primaryApexType {
579 return
580 }
581
582 if a.properties.IsCoverageVariant {
583 // Otherwise, we will have duplicated rules for coverage and
584 // non-coverage variants of the same APEX
585 return
586 }
587
588 if ctx.Host() {
589 // No need to generate dependency info for host variant
590 return
591 }
592
593 internalDeps := a.internalDeps
594 externalDeps := a.externalDeps
595
596 internalDeps = android.SortedUniqueStrings(internalDeps)
597 externalDeps = android.SortedUniqueStrings(externalDeps)
598 externalDeps = android.RemoveListFromList(externalDeps, internalDeps)
599
600 var content strings.Builder
601 for _, name := range internalDeps {
602 fmt.Fprintf(&content, "internal %s\\n", name)
603 }
604 for _, name := range externalDeps {
605 fmt.Fprintf(&content, "external %s\\n", name)
606 }
607
608 depsInfoFile := android.PathForOutput(ctx, a.Name()+"-deps-info.txt")
609 ctx.Build(pctx, android.BuildParams{
610 Rule: android.WriteFile,
611 Description: "Dependency Info",
612 Output: depsInfoFile,
613 Args: map[string]string{
614 "content": content.String(),
615 },
616 })
617
618 ctx.Build(pctx, android.BuildParams{
619 Rule: android.Phony,
620 Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
621 Inputs: []android.Path{depsInfoFile},
622 })
623}