blob: 912218864b45b0867165e943a6e749b8653378a9 [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()
Pete Gillin230e2412020-01-21 13:41:17 +0000379 if targetSdkVersion == ctx.Config().PlatformSdkCodename() &&
380 ctx.Config().UnbundledBuild() &&
381 !ctx.Config().UnbundledBuildUsePrebuiltSdks() &&
382 ctx.Config().IsEnvTrue("UNBUNDLED_BUILD_TARGET_SDK_WITH_API_FINGERPRINT") {
383 apiFingerprint := java.ApiFingerprintPath(ctx)
384 targetSdkVersion += fmt.Sprintf(".$$(cat %s)", apiFingerprint.String())
385 implicitInputs = append(implicitInputs, apiFingerprint)
Jiyong Park09d77522019-11-18 11:16:27 +0900386 }
387 optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
388
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800389 noticeFile := a.buildNoticeFile(ctx, a.Name()+suffix)
Jiyong Park09d77522019-11-18 11:16:27 +0900390 if noticeFile.Valid() {
391 // If there's a NOTICE file, embed it as an asset file in the APEX.
392 implicitInputs = append(implicitInputs, noticeFile.Path())
393 optFlags = append(optFlags, "--assets_dir "+filepath.Dir(noticeFile.String()))
394 }
395
Nikita Ioffeb4b44c02020-01-02 23:01:39 +0000396 if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && ctx.ModuleDir() != "system/apex/shim/build" && a.testOnlyShouldSkipHashtreeGeneration() {
Nikita Ioffec72b5dd2019-12-07 17:30:22 +0000397 ctx.PropertyErrorf("test_only_no_hashtree", "not available")
398 return
399 }
Dario Frenie3546902020-01-14 23:50:25 +0000400 if !proptools.Bool(a.properties.Legacy_android10_support) || a.testOnlyShouldSkipHashtreeGeneration() {
Jiyong Park09d77522019-11-18 11:16:27 +0900401 // Apexes which are supposed to be installed in builtin dirs(/system, etc)
402 // don't need hashtree for activation. Therefore, by removing hashtree from
403 // apex bundle (filesystem image in it, to be specific), we can save storage.
404 optFlags = append(optFlags, "--no_hashtree")
405 }
406
407 if a.properties.Apex_name != nil {
408 // If apex_name is set, apexer can skip checking if key name matches with apex name.
409 // Note that apex_manifest is also mended.
410 optFlags = append(optFlags, "--do_not_check_keyname")
411 }
412
Jooyung Han214bf372019-11-12 13:03:50 +0900413 if proptools.Bool(a.properties.Legacy_android10_support) {
414 implicitInputs = append(implicitInputs, a.manifestJsonOut)
415 optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
416 }
417
Jiyong Park09d77522019-11-18 11:16:27 +0900418 ctx.Build(pctx, android.BuildParams{
419 Rule: apexRule,
420 Implicits: implicitInputs,
421 Output: unsignedOutputFile,
422 Description: "apex (" + apexType.name() + ")",
423 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900424 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900425 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900426 "copy_commands": strings.Join(copyCommands, " && "),
427 "manifest": a.manifestPbOut.String(),
428 "file_contexts": a.fileContexts.String(),
429 "canned_fs_config": cannedFsConfig.String(),
430 "key": a.private_key_file.String(),
431 "opt_flags": strings.Join(optFlags, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900432 },
433 })
434
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800435 apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
436 bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
Jiyong Park09d77522019-11-18 11:16:27 +0900437 a.bundleModuleFile = bundleModuleFile
438
439 ctx.Build(pctx, android.BuildParams{
440 Rule: apexProtoConvertRule,
441 Input: unsignedOutputFile,
442 Output: apexProtoFile,
443 Description: "apex proto convert",
444 })
445
446 ctx.Build(pctx, android.BuildParams{
447 Rule: apexBundleRule,
448 Input: apexProtoFile,
449 Output: a.bundleModuleFile,
450 Description: "apex bundle module",
451 Args: map[string]string{
452 "abi": strings.Join(abis, "."),
453 },
454 })
455 } else {
456 ctx.Build(pctx, android.BuildParams{
457 Rule: zipApexRule,
458 Implicits: implicitInputs,
459 Output: unsignedOutputFile,
460 Description: "apex (" + apexType.name() + ")",
461 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900462 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900463 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900464 "copy_commands": strings.Join(copyCommands, " && "),
465 "manifest": a.manifestPbOut.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900466 },
467 })
468 }
469
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800470 a.outputFile = android.PathForModuleOut(ctx, a.Name()+suffix)
Jiyong Park09d77522019-11-18 11:16:27 +0900471 ctx.Build(pctx, android.BuildParams{
472 Rule: java.Signapk,
473 Description: "signapk",
474 Output: a.outputFile,
475 Input: unsignedOutputFile,
476 Implicits: []android.Path{
477 a.container_certificate_file,
478 a.container_private_key_file,
479 },
480 Args: map[string]string{
481 "certificates": a.container_certificate_file.String() + " " + a.container_private_key_file.String(),
482 "flags": "-a 4096", //alignment
483 },
484 })
485
486 // Install to $OUT/soong/{target,host}/.../apex
487 if a.installable() {
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800488 ctx.InstallFile(a.installDir, a.Name()+suffix, a.outputFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900489 }
490 a.buildFilesInfo(ctx)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900491
492 // installed-files.txt is dist'ed
493 a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900494}
495
496func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
497 // Temporarily wrap the original `ctx` into a `flattenedApexContext` to have it
498 // reply true to `InstallBypassMake()` (thus making the call
499 // `android.PathForModuleInstall` below use `android.pathForInstallInMakeDir`
500 // instead of `android.PathForOutput`) to return the correct path to the flattened
501 // APEX (as its contents is installed by Make, not Soong).
502 factx := flattenedApexContext{ctx}
503 apexName := proptools.StringDefault(a.properties.Apex_name, ctx.ModuleName())
504 a.outputFile = android.PathForModuleInstall(&factx, "apex", apexName)
505
Jiyong Park317645e2019-12-05 13:20:58 +0900506 if a.installable() && a.GetOverriddenBy() == "" {
Jooyung Han54aca7b2019-11-20 02:26:02 +0900507 installPath := android.PathForModuleInstall(ctx, "apex", apexName)
508 devicePath := android.InstallPathToOnDevicePath(ctx, installPath)
509 addFlattenedFileContextsInfos(ctx, apexName+":"+devicePath+":"+a.fileContexts.String())
510 }
Jiyong Park09d77522019-11-18 11:16:27 +0900511 a.buildFilesInfo(ctx)
512}
513
514func (a *apexBundle) setCertificateAndPrivateKey(ctx android.ModuleContext) {
Jooyung Hanf121a652019-12-17 14:30:11 +0900515 if a.container_certificate_file == nil {
516 cert := String(a.properties.Certificate)
517 if cert == "" {
518 pem, key := ctx.Config().DefaultAppCertificate(ctx)
519 a.container_certificate_file = pem
520 a.container_private_key_file = key
521 } else {
522 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
523 a.container_certificate_file = defaultDir.Join(ctx, cert+".x509.pem")
524 a.container_private_key_file = defaultDir.Join(ctx, cert+".pk8")
525 }
Jiyong Park09d77522019-11-18 11:16:27 +0900526 }
527}
528
529func (a *apexBundle) buildFilesInfo(ctx android.ModuleContext) {
530 if a.installable() {
Jooyung Han214bf372019-11-12 13:03:50 +0900531 // 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 +0900532 // with other ordinary files.
Jiyong Park1833cef2019-12-13 13:28:36 +0900533 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 +0900534
535 // rename to apex_pubkey
536 copiedPubkey := android.PathForModuleOut(ctx, "apex_pubkey")
537 ctx.Build(pctx, android.BuildParams{
538 Rule: android.Cp,
539 Input: a.public_key_file,
540 Output: copiedPubkey,
541 })
Jiyong Park1833cef2019-12-13 13:28:36 +0900542 a.filesInfo = append(a.filesInfo, newApexFile(ctx, copiedPubkey, "apex_pubkey."+a.Name()+a.suffix, ".", etc, nil))
Jiyong Park09d77522019-11-18 11:16:27 +0900543
544 if a.properties.ApexType == flattenedApex {
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800545 apexName := proptools.StringDefault(a.properties.Apex_name, a.Name())
Jiyong Park09d77522019-11-18 11:16:27 +0900546 for _, fi := range a.filesInfo {
547 dir := filepath.Join("apex", apexName, fi.installDir)
548 target := ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.builtFile.Base(), fi.builtFile)
549 for _, sym := range fi.symlinks {
550 ctx.InstallSymlink(android.PathForModuleInstall(ctx, dir), sym, target)
551 }
552 }
553 }
554 }
555}
Jooyung Han27151d92019-12-16 17:45:32 +0900556
557func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
558 // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
559 // to see if it should be overridden because their <apex name> is dynamically generated
560 // according to its VNDK version.
561 if a.vndkApex {
562 overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
563 if overridden {
564 return strings.Replace(*a.properties.Apex_name, vndkApexName, overrideName, 1)
565 }
566 return ""
567 }
568 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(a.Name())
569 if overridden {
570 return manifestPackageName
571 }
572 return ""
573}
Jiyong Park83dc74b2020-01-14 18:38:44 +0900574
575func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
576 if !a.primaryApexType {
577 return
578 }
579
580 if a.properties.IsCoverageVariant {
581 // Otherwise, we will have duplicated rules for coverage and
582 // non-coverage variants of the same APEX
583 return
584 }
585
586 if ctx.Host() {
587 // No need to generate dependency info for host variant
588 return
589 }
590
591 internalDeps := a.internalDeps
592 externalDeps := a.externalDeps
593
594 internalDeps = android.SortedUniqueStrings(internalDeps)
595 externalDeps = android.SortedUniqueStrings(externalDeps)
596 externalDeps = android.RemoveListFromList(externalDeps, internalDeps)
597
598 var content strings.Builder
599 for _, name := range internalDeps {
600 fmt.Fprintf(&content, "internal %s\\n", name)
601 }
602 for _, name := range externalDeps {
603 fmt.Fprintf(&content, "external %s\\n", name)
604 }
605
606 depsInfoFile := android.PathForOutput(ctx, a.Name()+"-deps-info.txt")
607 ctx.Build(pctx, android.BuildParams{
608 Rule: android.WriteFile,
609 Description: "Dependency Info",
610 Output: depsInfoFile,
611 Args: map[string]string{
612 "content": content.String(),
613 },
614 })
615
616 ctx.Build(pctx, android.BuildParams{
617 Rule: android.Phony,
618 Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
619 Inputs: []android.Path{depsInfoFile},
620 })
621}