blob: 88c7098e6415e797a1472ee36dec06dd5f7c4a3a [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}" && ` +
Dan Willemsen81e43c52020-01-28 15:40:19 -0800163 `exit 1); touch ${out}`,
Jiyong Park09d77522019-11-18 11:16:27 +0900164 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
Jiyong Park19972c72020-01-28 20:05:29 +0900214func (a *apexBundle) buildNoticeFiles(ctx android.ModuleContext, apexFileName string) android.NoticeOutputs {
Jiyong Park09d77522019-11-18 11:16:27 +0900215 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 {
Jiyong Park19972c72020-01-28 20:05:29 +0900230 return android.NoticeOutputs{}
Jiyong Park09d77522019-11-18 11:16:27 +0900231 }
232
Jiyong Park19972c72020-01-28 20:05:29 +0900233 return android.BuildNoticeOutput(ctx, a.installDir, apexFileName, android.FirstUniquePaths(noticeFiles))
Jiyong Park09d77522019-11-18 11:16:27 +0900234}
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() + " ; ").
Jiyong Parkbd63a102020-02-08 12:40:05 +0900242 Text("find . \\( -type f -o -type l \\) -printf \"%s %p\\n\") ").
Jiyong Park3a1602e2020-01-14 14:39:19 +0900243 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()
Jiyong Park7cd10e32020-01-14 09:22:18 +0900261 var implicitInputs []android.Path
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800262 unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
Jiyong Park09d77522019-11-18 11:16:27 +0900263
Jiyong Park7cd10e32020-01-14 09:22:18 +0900264 // TODO(jiyong): construct the copy rules using RuleBuilder
265 var copyCommands []string
266 for _, fi := range a.filesInfo {
267 destPath := android.PathForModuleOut(ctx, "image"+suffix, fi.Path()).String()
268 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(destPath))
269 if a.linkToSystemLib && fi.transitiveDep && fi.AvailableToPlatform() {
270 // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
271 pathOnDevice := filepath.Join("/system", fi.Path())
272 copyCommands = append(copyCommands, "ln -sfn "+pathOnDevice+" "+destPath)
273 } else {
274 copyCommands = append(copyCommands, "cp -f "+fi.builtFile.String()+" "+destPath)
275 implicitInputs = append(implicitInputs, fi.builtFile)
276 }
277 // create additional symlinks pointing the file inside the APEX
278 for _, symlinkPath := range fi.SymlinkPaths() {
279 symlinkDest := android.PathForModuleOut(ctx, "image"+suffix, symlinkPath).String()
280 copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
281 }
Jiyong Park09d77522019-11-18 11:16:27 +0900282 }
283
Jiyong Park7cd10e32020-01-14 09:22:18 +0900284 // TODO(jiyong): use RuleBuilder
285 var emitCommands []string
286 imageContentFile := android.PathForModuleOut(ctx, "content.txt")
Jooyung Han214bf372019-11-12 13:03:50 +0900287 emitCommands = append(emitCommands, "echo ./apex_manifest.pb >> "+imageContentFile.String())
288 if proptools.Bool(a.properties.Legacy_android10_support) {
289 emitCommands = append(emitCommands, "echo ./apex_manifest.json >> "+imageContentFile.String())
290 }
Jiyong Park7cd10e32020-01-14 09:22:18 +0900291 for _, fi := range a.filesInfo {
292 emitCommands = append(emitCommands, "echo './"+fi.Path()+"' >> "+imageContentFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900293 }
294 emitCommands = append(emitCommands, "sort -o "+imageContentFile.String()+" "+imageContentFile.String())
Jooyung Han214bf372019-11-12 13:03:50 +0900295 implicitInputs = append(implicitInputs, a.manifestPbOut)
Jiyong Park09d77522019-11-18 11:16:27 +0900296
297 if a.properties.Whitelisted_files != nil {
298 ctx.Build(pctx, android.BuildParams{
299 Rule: emitApexContentRule,
300 Implicits: implicitInputs,
301 Output: imageContentFile,
302 Description: "emit apex image content",
303 Args: map[string]string{
304 "emit_commands": strings.Join(emitCommands, " && "),
305 },
306 })
307 implicitInputs = append(implicitInputs, imageContentFile)
308 whitelistedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.Whitelisted_files))
309
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800310 phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
Jiyong Park09d77522019-11-18 11:16:27 +0900311 ctx.Build(pctx, android.BuildParams{
312 Rule: diffApexContentRule,
313 Implicits: implicitInputs,
314 Output: phonyOutput,
315 Description: "diff apex image content",
316 Args: map[string]string{
317 "whitelisted_files_file": whitelistedFilesFile.String(),
318 "image_content_file": imageContentFile.String(),
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800319 "apex_module_name": a.Name(),
Jiyong Park09d77522019-11-18 11:16:27 +0900320 },
321 })
322
323 implicitInputs = append(implicitInputs, phonyOutput)
324 }
325
326 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
327 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
328
Jiyong Park3a1602e2020-01-14 14:39:19 +0900329 imageDir := android.PathForModuleOut(ctx, "image"+suffix)
Jiyong Park09d77522019-11-18 11:16:27 +0900330 if apexType == imageApex {
331 // files and dirs that will be created in APEX
332 var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
333 var executablePaths []string // this also includes dirs
334 for _, f := range a.filesInfo {
335 pathInApex := filepath.Join(f.installDir, f.builtFile.Base())
336 if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
337 executablePaths = append(executablePaths, pathInApex)
338 for _, s := range f.symlinks {
339 executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
340 }
341 } else {
342 readOnlyPaths = append(readOnlyPaths, pathInApex)
343 }
344 dir := f.installDir
345 for !android.InList(dir, executablePaths) && dir != "" {
346 executablePaths = append(executablePaths, dir)
347 dir, _ = filepath.Split(dir) // move up to the parent
348 if len(dir) > 0 {
349 // remove trailing slash
350 dir = dir[:len(dir)-1]
351 }
352 }
353 }
354 sort.Strings(readOnlyPaths)
355 sort.Strings(executablePaths)
356 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
357 ctx.Build(pctx, android.BuildParams{
358 Rule: generateFsConfig,
359 Output: cannedFsConfig,
360 Description: "generate fs config",
361 Args: map[string]string{
362 "ro_paths": strings.Join(readOnlyPaths, " "),
363 "exec_paths": strings.Join(executablePaths, " "),
364 },
365 })
366
Jiyong Park09d77522019-11-18 11:16:27 +0900367 optFlags := []string{}
368
369 // Additional implicit inputs.
Jooyung Han54aca7b2019-11-20 02:26:02 +0900370 implicitInputs = append(implicitInputs, cannedFsConfig, a.fileContexts, a.private_key_file, a.public_key_file)
Jiyong Park09d77522019-11-18 11:16:27 +0900371 optFlags = append(optFlags, "--pubkey "+a.public_key_file.String())
372
Jooyung Han27151d92019-12-16 17:45:32 +0900373 manifestPackageName := a.getOverrideManifestPackageName(ctx)
374 if manifestPackageName != "" {
Jiyong Park09d77522019-11-18 11:16:27 +0900375 optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
376 }
377
378 if a.properties.AndroidManifest != nil {
379 androidManifestFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.AndroidManifest))
380 implicitInputs = append(implicitInputs, androidManifestFile)
381 optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
382 }
383
384 targetSdkVersion := ctx.Config().DefaultAppTargetSdk()
Baligh Uddinf6201372020-01-24 23:15:44 +0000385 minSdkVersion := ctx.Config().DefaultAppTargetSdk()
386 if java.UseApiFingerprint(ctx, targetSdkVersion) {
387 targetSdkVersion += fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
388 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
389 }
390 if java.UseApiFingerprint(ctx, minSdkVersion) {
391 minSdkVersion += fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
392 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
Jiyong Park09d77522019-11-18 11:16:27 +0900393 }
394 optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
Baligh Uddinf6201372020-01-24 23:15:44 +0000395 optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
Jiyong Park09d77522019-11-18 11:16:27 +0900396
Baligh Uddin004d7172020-02-19 21:29:28 -0800397 if a.overridableProperties.Logging_parent != "" {
398 optFlags = append(optFlags, "--logging_parent ", a.overridableProperties.Logging_parent)
399 }
400
Jiyong Park19972c72020-01-28 20:05:29 +0900401 a.mergedNotices = a.buildNoticeFiles(ctx, a.Name()+suffix)
402 if a.mergedNotices.HtmlGzOutput.Valid() {
Jiyong Park09d77522019-11-18 11:16:27 +0900403 // If there's a NOTICE file, embed it as an asset file in the APEX.
Jiyong Park19972c72020-01-28 20:05:29 +0900404 implicitInputs = append(implicitInputs, a.mergedNotices.HtmlGzOutput.Path())
405 optFlags = append(optFlags, "--assets_dir "+filepath.Dir(a.mergedNotices.HtmlGzOutput.String()))
Jiyong Park09d77522019-11-18 11:16:27 +0900406 }
407
Nikita Ioffeb4b44c02020-01-02 23:01:39 +0000408 if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && ctx.ModuleDir() != "system/apex/shim/build" && a.testOnlyShouldSkipHashtreeGeneration() {
Nikita Ioffec72b5dd2019-12-07 17:30:22 +0000409 ctx.PropertyErrorf("test_only_no_hashtree", "not available")
410 return
411 }
Dario Frenie3546902020-01-14 23:50:25 +0000412 if !proptools.Bool(a.properties.Legacy_android10_support) || a.testOnlyShouldSkipHashtreeGeneration() {
Jiyong Park09d77522019-11-18 11:16:27 +0900413 // Apexes which are supposed to be installed in builtin dirs(/system, etc)
414 // don't need hashtree for activation. Therefore, by removing hashtree from
415 // apex bundle (filesystem image in it, to be specific), we can save storage.
416 optFlags = append(optFlags, "--no_hashtree")
417 }
418
419 if a.properties.Apex_name != nil {
420 // If apex_name is set, apexer can skip checking if key name matches with apex name.
421 // Note that apex_manifest is also mended.
422 optFlags = append(optFlags, "--do_not_check_keyname")
423 }
424
Jooyung Han214bf372019-11-12 13:03:50 +0900425 if proptools.Bool(a.properties.Legacy_android10_support) {
426 implicitInputs = append(implicitInputs, a.manifestJsonOut)
427 optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
428 }
429
Jiyong Park09d77522019-11-18 11:16:27 +0900430 ctx.Build(pctx, android.BuildParams{
431 Rule: apexRule,
432 Implicits: implicitInputs,
433 Output: unsignedOutputFile,
434 Description: "apex (" + apexType.name() + ")",
435 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900436 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900437 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900438 "copy_commands": strings.Join(copyCommands, " && "),
439 "manifest": a.manifestPbOut.String(),
440 "file_contexts": a.fileContexts.String(),
441 "canned_fs_config": cannedFsConfig.String(),
442 "key": a.private_key_file.String(),
443 "opt_flags": strings.Join(optFlags, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900444 },
445 })
446
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800447 apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
448 bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
Jiyong Park09d77522019-11-18 11:16:27 +0900449 a.bundleModuleFile = bundleModuleFile
450
451 ctx.Build(pctx, android.BuildParams{
452 Rule: apexProtoConvertRule,
453 Input: unsignedOutputFile,
454 Output: apexProtoFile,
455 Description: "apex proto convert",
456 })
457
458 ctx.Build(pctx, android.BuildParams{
459 Rule: apexBundleRule,
460 Input: apexProtoFile,
461 Output: a.bundleModuleFile,
462 Description: "apex bundle module",
463 Args: map[string]string{
464 "abi": strings.Join(abis, "."),
465 },
466 })
467 } else {
468 ctx.Build(pctx, android.BuildParams{
469 Rule: zipApexRule,
470 Implicits: implicitInputs,
471 Output: unsignedOutputFile,
472 Description: "apex (" + apexType.name() + ")",
473 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900474 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900475 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900476 "copy_commands": strings.Join(copyCommands, " && "),
477 "manifest": a.manifestPbOut.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900478 },
479 })
480 }
481
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800482 a.outputFile = android.PathForModuleOut(ctx, a.Name()+suffix)
Jiyong Park09d77522019-11-18 11:16:27 +0900483 ctx.Build(pctx, android.BuildParams{
484 Rule: java.Signapk,
485 Description: "signapk",
486 Output: a.outputFile,
487 Input: unsignedOutputFile,
488 Implicits: []android.Path{
489 a.container_certificate_file,
490 a.container_private_key_file,
491 },
492 Args: map[string]string{
493 "certificates": a.container_certificate_file.String() + " " + a.container_private_key_file.String(),
494 "flags": "-a 4096", //alignment
495 },
496 })
497
498 // Install to $OUT/soong/{target,host}/.../apex
499 if a.installable() {
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800500 ctx.InstallFile(a.installDir, a.Name()+suffix, a.outputFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900501 }
502 a.buildFilesInfo(ctx)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900503
504 // installed-files.txt is dist'ed
505 a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900506}
507
508func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
509 // Temporarily wrap the original `ctx` into a `flattenedApexContext` to have it
510 // reply true to `InstallBypassMake()` (thus making the call
511 // `android.PathForModuleInstall` below use `android.pathForInstallInMakeDir`
512 // instead of `android.PathForOutput`) to return the correct path to the flattened
513 // APEX (as its contents is installed by Make, not Soong).
514 factx := flattenedApexContext{ctx}
Jiyong Parka5948012020-02-07 10:15:14 +0900515 apexBundleName := a.Name()
516 a.outputFile = android.PathForModuleInstall(&factx, "apex", apexBundleName)
Jiyong Park09d77522019-11-18 11:16:27 +0900517
Jiyong Park317645e2019-12-05 13:20:58 +0900518 if a.installable() && a.GetOverriddenBy() == "" {
Jiyong Parka5948012020-02-07 10:15:14 +0900519 installPath := android.PathForModuleInstall(ctx, "apex", apexBundleName)
Jooyung Han54aca7b2019-11-20 02:26:02 +0900520 devicePath := android.InstallPathToOnDevicePath(ctx, installPath)
Jiyong Parka5948012020-02-07 10:15:14 +0900521 addFlattenedFileContextsInfos(ctx, apexBundleName+":"+devicePath+":"+a.fileContexts.String())
Jooyung Han54aca7b2019-11-20 02:26:02 +0900522 }
Jiyong Park09d77522019-11-18 11:16:27 +0900523 a.buildFilesInfo(ctx)
524}
525
526func (a *apexBundle) setCertificateAndPrivateKey(ctx android.ModuleContext) {
Jooyung Hanf121a652019-12-17 14:30:11 +0900527 if a.container_certificate_file == nil {
528 cert := String(a.properties.Certificate)
529 if cert == "" {
530 pem, key := ctx.Config().DefaultAppCertificate(ctx)
531 a.container_certificate_file = pem
532 a.container_private_key_file = key
533 } else {
534 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
535 a.container_certificate_file = defaultDir.Join(ctx, cert+".x509.pem")
536 a.container_private_key_file = defaultDir.Join(ctx, cert+".pk8")
537 }
Jiyong Park09d77522019-11-18 11:16:27 +0900538 }
539}
540
541func (a *apexBundle) buildFilesInfo(ctx android.ModuleContext) {
542 if a.installable() {
Jooyung Han214bf372019-11-12 13:03:50 +0900543 // 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 +0900544 // with other ordinary files.
Jiyong Park7cd10e32020-01-14 09:22:18 +0900545 a.filesInfo = append(a.filesInfo, newApexFile(ctx, a.manifestPbOut, "apex_manifest.pb", ".", etc, nil))
Jiyong Park09d77522019-11-18 11:16:27 +0900546
547 // rename to apex_pubkey
548 copiedPubkey := android.PathForModuleOut(ctx, "apex_pubkey")
549 ctx.Build(pctx, android.BuildParams{
550 Rule: android.Cp,
551 Input: a.public_key_file,
552 Output: copiedPubkey,
553 })
Jiyong Park7cd10e32020-01-14 09:22:18 +0900554 a.filesInfo = append(a.filesInfo, newApexFile(ctx, copiedPubkey, "apex_pubkey", ".", etc, nil))
Jiyong Park09d77522019-11-18 11:16:27 +0900555
556 if a.properties.ApexType == flattenedApex {
Jiyong Parka5948012020-02-07 10:15:14 +0900557 apexBundleName := a.Name()
Jiyong Park09d77522019-11-18 11:16:27 +0900558 for _, fi := range a.filesInfo {
Jiyong Parka5948012020-02-07 10:15:14 +0900559 dir := filepath.Join("apex", apexBundleName, fi.installDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900560 target := ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.builtFile.Base(), fi.builtFile)
561 for _, sym := range fi.symlinks {
562 ctx.InstallSymlink(android.PathForModuleInstall(ctx, dir), sym, target)
563 }
564 }
565 }
566 }
567}
Jooyung Han27151d92019-12-16 17:45:32 +0900568
569func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
570 // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
571 // to see if it should be overridden because their <apex name> is dynamically generated
572 // according to its VNDK version.
573 if a.vndkApex {
574 overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
575 if overridden {
576 return strings.Replace(*a.properties.Apex_name, vndkApexName, overrideName, 1)
577 }
578 return ""
579 }
580 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(a.Name())
581 if overridden {
582 return manifestPackageName
583 }
584 return ""
585}
Jiyong Park83dc74b2020-01-14 18:38:44 +0900586
587func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
588 if !a.primaryApexType {
589 return
590 }
591
592 if a.properties.IsCoverageVariant {
593 // Otherwise, we will have duplicated rules for coverage and
594 // non-coverage variants of the same APEX
595 return
596 }
597
598 if ctx.Host() {
599 // No need to generate dependency info for host variant
600 return
601 }
602
Jiyong Park83dc74b2020-01-14 18:38:44 +0900603 var content strings.Builder
Jiyong Park678c8812020-02-07 17:25:49 +0900604 for _, key := range android.SortedStringKeys(a.depInfos) {
605 info := a.depInfos[key]
606 toName := info.to
607 if info.isExternal {
608 toName = toName + " (external)"
609 }
610 fmt.Fprintf(&content, "%s <- %s\\n", toName, strings.Join(android.SortedUniqueStrings(info.from), ", "))
Jiyong Park83dc74b2020-01-14 18:38:44 +0900611 }
612
613 depsInfoFile := android.PathForOutput(ctx, a.Name()+"-deps-info.txt")
614 ctx.Build(pctx, android.BuildParams{
615 Rule: android.WriteFile,
616 Description: "Dependency Info",
617 Output: depsInfoFile,
618 Args: map[string]string{
619 "content": content.String(),
620 },
621 })
622
623 ctx.Build(pctx, android.BuildParams{
624 Rule: android.Phony,
625 Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
626 Inputs: []android.Path{depsInfoFile},
627 })
628}