blob: dda342f82d73930705fe12c51e3983d78ab08ae1 [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 (
Jiyong Parkbd159612020-02-28 15:22:21 +090018 "encoding/json"
Jiyong Park09d77522019-11-18 11:16:27 +090019 "fmt"
20 "path/filepath"
21 "runtime"
22 "sort"
Nikita Ioffe5335bc42020-10-20 00:02:15 +010023 "strconv"
Jiyong Park09d77522019-11-18 11:16:27 +090024 "strings"
25
26 "android/soong/android"
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
37func init() {
38 pctx.Import("android/soong/android")
sophiezc80a2b32020-11-12 16:39:19 +000039 pctx.Import("android/soong/cc/config")
Jiyong Park09d77522019-11-18 11:16:27 +090040 pctx.Import("android/soong/java")
41 pctx.HostBinToolVariable("apexer", "apexer")
42 // ART minimal builds (using the master-art manifest) do not have the "frameworks/base"
Jiyong Parkb81b9902020-11-24 19:51:18 +090043 // projects, and hence cannot build 'aapt2'. Use the SDK prebuilt instead.
Jiyong Park09d77522019-11-18 11:16:27 +090044 hostBinToolVariableWithPrebuilt := func(name, prebuiltDir, tool string) {
45 pctx.VariableFunc(name, func(ctx android.PackageVarContext) string {
46 if !ctx.Config().FrameworksBaseDirExists(ctx) {
47 return filepath.Join(prebuiltDir, runtime.GOOS, "bin", tool)
48 } else {
Martin Stjernholm7260d062019-12-09 21:47:14 +000049 return ctx.Config().HostToolPath(ctx, tool).String()
Jiyong Park09d77522019-11-18 11:16:27 +090050 }
51 })
52 }
53 hostBinToolVariableWithPrebuilt("aapt2", "prebuilts/sdk/tools", "aapt2")
54 pctx.HostBinToolVariable("avbtool", "avbtool")
55 pctx.HostBinToolVariable("e2fsdroid", "e2fsdroid")
56 pctx.HostBinToolVariable("merge_zips", "merge_zips")
57 pctx.HostBinToolVariable("mke2fs", "mke2fs")
58 pctx.HostBinToolVariable("resize2fs", "resize2fs")
59 pctx.HostBinToolVariable("sefcontext_compile", "sefcontext_compile")
60 pctx.HostBinToolVariable("soong_zip", "soong_zip")
61 pctx.HostBinToolVariable("zip2zip", "zip2zip")
62 pctx.HostBinToolVariable("zipalign", "zipalign")
63 pctx.HostBinToolVariable("jsonmodify", "jsonmodify")
64 pctx.HostBinToolVariable("conv_apex_manifest", "conv_apex_manifest")
Jaewoong Jungfa00c062020-05-14 14:15:24 -070065 pctx.HostBinToolVariable("extract_apks", "extract_apks")
Theotime Combes4ba38c12020-06-12 12:46:59 +000066 pctx.HostBinToolVariable("make_f2fs", "make_f2fs")
67 pctx.HostBinToolVariable("sload_f2fs", "sload_f2fs")
Huang Jianan13cac632021-08-02 15:02:17 +080068 pctx.HostBinToolVariable("make_erofs", "make_erofs")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +000069 pctx.HostBinToolVariable("apex_compression_tool", "apex_compression_tool")
sophiez02347372021-11-02 17:58:02 -070070 pctx.HostBinToolVariable("dexdeps", "dexdeps")
sophiezc80a2b32020-11-12 16:39:19 +000071 pctx.SourcePathVariable("genNdkUsedbyApexPath", "build/soong/scripts/gen_ndk_usedby_apex.sh")
Jiyong Park09d77522019-11-18 11:16:27 +090072}
73
74var (
Jiyong Park09d77522019-11-18 11:16:27 +090075 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
Alexei Nicoaraee4b6332022-06-30 16:34:28 +010085 stripCommentsApexManifestRule = pctx.StaticRule("stripCommentsApexManifestRule", blueprint.RuleParams{
86 Command: `sed '/^\s*\/\//d' $in > $out`,
87 Description: "strip lines starting with // ${in}=>${out}",
88 })
89
Jiyong Park09d77522019-11-18 11:16:27 +090090 stripApexManifestRule = pctx.StaticRule("stripApexManifestRule", blueprint.RuleParams{
91 Command: `rm -f $out && ${conv_apex_manifest} strip $in -o $out`,
92 CommandDeps: []string{"${conv_apex_manifest}"},
93 Description: "strip ${in}=>${out}",
94 })
95
Alexei Nicoarae922d212022-07-08 15:24:41 +010096 setVersionApexManifestRule = pctx.StaticRule("setVersionApexManifestRule", blueprint.RuleParams{
97 Command: `sed 's/\"version\":\s*0\([^0-9]*\)$$/\"version\":\ ${default_version}\1/' $in > $out`,
98 Description: "Replace 'version: 0' with the correct version // ${in}=>${out}",
99 }, "default_version")
100
Jiyong Park09d77522019-11-18 11:16:27 +0900101 pbApexManifestRule = pctx.StaticRule("pbApexManifestRule", blueprint.RuleParams{
102 Command: `rm -f $out && ${conv_apex_manifest} proto $in -o $out`,
103 CommandDeps: []string{"${conv_apex_manifest}"},
104 Description: "convert ${in}=>${out}",
105 })
106
Joe Onoratob4638c12021-10-27 15:47:06 -0700107 // TODO(b/113233103): make sure that file_contexts is as expected, i.e., validate
Jiyong Park09d77522019-11-18 11:16:27 +0900108 // against the binary policy using sefcontext_compiler -p <policy>.
109
110 // TODO(b/114327326): automate the generation of file_contexts
111 apexRule = pctx.StaticRule("apexRule", blueprint.RuleParams{
112 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
113 `(. ${out}.copy_commands) && ` +
114 `APEXER_TOOL_PATH=${tool_path} ` +
115 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900116 `--file_contexts ${file_contexts} ` +
117 `--canned_fs_config ${canned_fs_config} ` +
Dario Freni0f4ae072020-01-02 15:24:12 +0000118 `--include_build_info ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900119 `--payload_type image ` +
Alexei Nicoarac939b012022-07-06 12:03:11 +0100120 `--apex_version ${apex_version} ` +
Oriol Prieto Gasco17e22902022-05-05 13:52:25 +0000121 `--key ${key} ${opt_flags} ${image_dir} ${out} `,
Jiyong Park09d77522019-11-18 11:16:27 +0900122 CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
Huang Jianan13cac632021-08-02 15:02:17 +0800123 "${mke2fs}", "${resize2fs}", "${sefcontext_compile}", "${make_f2fs}", "${sload_f2fs}", "${make_erofs}",
Jiyong Park09d77522019-11-18 11:16:27 +0900124 "${soong_zip}", "${zipalign}", "${aapt2}", "prebuilts/sdk/current/public/android.jar"},
125 Rspfile: "${out}.copy_commands",
126 RspfileContent: "${copy_commands}",
127 Description: "APEX ${image_dir} => ${out}",
Alexei Nicoarac939b012022-07-06 12:03:11 +0100128 }, "tool_path", "image_dir", "copy_commands", "file_contexts", "canned_fs_config", "key", "opt_flags", "manifest", "payload_fs_type", "apex_version")
Jiyong Park09d77522019-11-18 11:16:27 +0900129
130 zipApexRule = pctx.StaticRule("zipApexRule", blueprint.RuleParams{
131 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
132 `(. ${out}.copy_commands) && ` +
133 `APEXER_TOOL_PATH=${tool_path} ` +
Jooyung Han214bf372019-11-12 13:03:50 +0900134 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900135 `--payload_type zip ` +
Alexei Nicoarac939b012022-07-06 12:03:11 +0100136 `--apex_version ${apex_version} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900137 `${image_dir} ${out} `,
138 CommandDeps: []string{"${apexer}", "${merge_zips}", "${soong_zip}", "${zipalign}", "${aapt2}"},
139 Rspfile: "${out}.copy_commands",
140 RspfileContent: "${copy_commands}",
141 Description: "ZipAPEX ${image_dir} => ${out}",
Alexei Nicoarac939b012022-07-06 12:03:11 +0100142 }, "tool_path", "image_dir", "copy_commands", "manifest", "apex_version")
Jiyong Park09d77522019-11-18 11:16:27 +0900143
144 apexProtoConvertRule = pctx.AndroidStaticRule("apexProtoConvertRule",
145 blueprint.RuleParams{
146 Command: `${aapt2} convert --output-format proto $in -o $out`,
147 CommandDeps: []string{"${aapt2}"},
148 })
149
150 apexBundleRule = pctx.StaticRule("apexBundleRule", blueprint.RuleParams{
Jiyong Parkbd159612020-02-28 15:22:21 +0900151 Command: `${zip2zip} -i $in -o $out.base ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900152 `apex_payload.img:apex/${abi}.img ` +
Dario Frenida1aefe2020-03-02 21:47:09 +0000153 `apex_build_info.pb:apex/${abi}.build_info.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900154 `apex_manifest.json:root/apex_manifest.json ` +
Jiyong Park53ae3342019-12-08 02:06:24 +0900155 `apex_manifest.pb:root/apex_manifest.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900156 `AndroidManifest.xml:manifest/AndroidManifest.xml ` +
Jiyong Parkbd159612020-02-28 15:22:21 +0900157 `assets/NOTICE.html.gz:assets/NOTICE.html.gz &&` +
158 `${soong_zip} -o $out.config -C $$(dirname ${config}) -f ${config} && ` +
159 `${merge_zips} $out $out.base $out.config`,
160 CommandDeps: []string{"${zip2zip}", "${soong_zip}", "${merge_zips}"},
Jiyong Park09d77522019-11-18 11:16:27 +0900161 Description: "app bundle",
Jiyong Parkbd159612020-02-28 15:22:21 +0900162 }, "abi", "config")
Jiyong Park09d77522019-11-18 11:16:27 +0900163
164 emitApexContentRule = pctx.StaticRule("emitApexContentRule", blueprint.RuleParams{
165 Command: `rm -f ${out} && touch ${out} && (. ${out}.emit_commands)`,
166 Rspfile: "${out}.emit_commands",
167 RspfileContent: "${emit_commands}",
168 Description: "Emit APEX image content",
169 }, "emit_commands")
170
171 diffApexContentRule = pctx.StaticRule("diffApexContentRule", blueprint.RuleParams{
172 Command: `diff --unchanged-group-format='' \` +
173 `--changed-group-format='%<' \` +
Colin Cross440e0d02020-06-11 11:32:11 -0700174 `${image_content_file} ${allowed_files_file} || (` +
Jiyong Park09d77522019-11-18 11:16:27 +0900175 `echo -e "New unexpected files were added to ${apex_module_name}." ` +
176 ` "To fix the build run following command:" && ` +
Colin Cross440e0d02020-06-11 11:32:11 -0700177 `echo "system/apex/tools/update_allowed_list.sh ${allowed_files_file} ${image_content_file}" && ` +
Dan Willemsen81e43c52020-01-28 15:40:19 -0800178 `exit 1); touch ${out}`,
Colin Cross440e0d02020-06-11 11:32:11 -0700179 Description: "Diff ${image_content_file} and ${allowed_files_file}",
180 }, "image_content_file", "allowed_files_file", "apex_module_name")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900181
sophiezc80a2b32020-11-12 16:39:19 +0000182 generateAPIsUsedbyApexRule = pctx.StaticRule("generateAPIsUsedbyApexRule", blueprint.RuleParams{
183 Command: "$genNdkUsedbyApexPath ${image_dir} ${readelf} ${out}",
184 CommandDeps: []string{"${genNdkUsedbyApexPath}"},
185 Description: "Generate symbol list used by Apex",
186 }, "image_dir", "readelf")
187
Jiyong Parkb81b9902020-11-24 19:51:18 +0900188 // Don't add more rules here. Consider using android.NewRuleBuilder instead.
Jiyong Park09d77522019-11-18 11:16:27 +0900189)
190
Jiyong Parkb81b9902020-11-24 19:51:18 +0900191// buildManifest creates buile rules to modify the input apex_manifest.json to add information
192// gathered by the build system such as provided/required native libraries. Two output files having
193// different formats are generated. a.manifestJsonOut is JSON format for Q devices, and
194// a.manifest.PbOut is protobuf format for R+ devices.
195// TODO(jiyong): make this to return paths instead of directly storing the paths to apexBundle
Jiyong Park09d77522019-11-18 11:16:27 +0900196func (a *apexBundle) buildManifest(ctx android.ModuleContext, provideNativeLibs, requireNativeLibs []string) {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900197 src := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
Jiyong Park09d77522019-11-18 11:16:27 +0900198
Jiyong Parkb81b9902020-11-24 19:51:18 +0900199 // Put dependency({provide|require}NativeLibs) in apex_manifest.json
Jiyong Park09d77522019-11-18 11:16:27 +0900200 provideNativeLibs = android.SortedUniqueStrings(provideNativeLibs)
201 requireNativeLibs = android.SortedUniqueStrings(android.RemoveListFromList(requireNativeLibs, provideNativeLibs))
202
Jiyong Parkb81b9902020-11-24 19:51:18 +0900203 // APEX name can be overridden
Jiyong Park09d77522019-11-18 11:16:27 +0900204 optCommands := []string{}
205 if a.properties.Apex_name != nil {
206 optCommands = append(optCommands, "-v name "+*a.properties.Apex_name)
207 }
208
Jiyong Parkb81b9902020-11-24 19:51:18 +0900209 // Collect jniLibs. Notice that a.filesInfo is already sorted
Jooyung Han643adc42020-02-27 13:50:06 +0900210 var jniLibs []string
211 for _, fi := range a.filesInfo {
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900212 if fi.isJniLib && !android.InList(fi.stem(), jniLibs) {
213 jniLibs = append(jniLibs, fi.stem())
Jooyung Han643adc42020-02-27 13:50:06 +0900214 }
215 }
216 if len(jniLibs) > 0 {
217 optCommands = append(optCommands, "-a jniLibs "+strings.Join(jniLibs, " "))
218 }
219
Alexei Nicoaraee4b6332022-06-30 16:34:28 +0100220 manifestJsonCommentsStripped := android.PathForModuleOut(ctx, "apex_manifest_comments_stripped.json")
221 ctx.Build(pctx, android.BuildParams{
222 Rule: stripCommentsApexManifestRule,
223 Input: src,
224 Output: manifestJsonCommentsStripped,
225 })
226
Alexei Nicoarae922d212022-07-08 15:24:41 +0100227 manifestJsonVersionChanged := android.PathForModuleOut(ctx, "apex_manifest_version_changed.json")
228 ctx.Build(pctx, android.BuildParams{
229 Rule: setVersionApexManifestRule,
230 Input: manifestJsonCommentsStripped,
231 Output: manifestJsonVersionChanged,
232 Args: map[string]string{
233 "default_version": defaultManifestVersion,
234 },
235 })
236
Jiyong Parkb81b9902020-11-24 19:51:18 +0900237 manifestJsonFullOut := android.PathForModuleOut(ctx, "apex_manifest_full.json")
Jiyong Park09d77522019-11-18 11:16:27 +0900238 ctx.Build(pctx, android.BuildParams{
239 Rule: apexManifestRule,
Alexei Nicoarae922d212022-07-08 15:24:41 +0100240 Input: manifestJsonVersionChanged,
Jooyung Han214bf372019-11-12 13:03:50 +0900241 Output: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900242 Args: map[string]string{
243 "provideNativeLibs": strings.Join(provideNativeLibs, " "),
244 "requireNativeLibs": strings.Join(requireNativeLibs, " "),
245 "opt": strings.Join(optCommands, " "),
246 },
247 })
248
Jiyong Parkb81b9902020-11-24 19:51:18 +0900249 // b/143654022 Q apexd can't understand newly added keys in apex_manifest.json prepare
250 // stripped-down version so that APEX modules built from R+ can be installed to Q
Dan Albertc8060532020-07-22 22:32:17 -0700251 minSdkVersion := a.minSdkVersion(ctx)
252 if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
Jooyung Han214bf372019-11-12 13:03:50 +0900253 a.manifestJsonOut = android.PathForModuleOut(ctx, "apex_manifest.json")
254 ctx.Build(pctx, android.BuildParams{
255 Rule: stripApexManifestRule,
256 Input: manifestJsonFullOut,
257 Output: a.manifestJsonOut,
258 })
259 }
Jiyong Park09d77522019-11-18 11:16:27 +0900260
Jiyong Parkb81b9902020-11-24 19:51:18 +0900261 // From R+, protobuf binary format (.pb) is the standard format for apex_manifest
Jiyong Park09d77522019-11-18 11:16:27 +0900262 a.manifestPbOut = android.PathForModuleOut(ctx, "apex_manifest.pb")
263 ctx.Build(pctx, android.BuildParams{
264 Rule: pbApexManifestRule,
Jooyung Han214bf372019-11-12 13:03:50 +0900265 Input: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900266 Output: a.manifestPbOut,
267 })
268}
269
Jiyong Parkb81b9902020-11-24 19:51:18 +0900270// buildFileContexts create build rules to append an entry for apex_manifest.pb to the file_contexts
271// file for this APEX which is either from /systme/sepolicy/apex/<apexname>-file_contexts or from
272// the file_contexts property of this APEX. This is to make sure that the manifest file is correctly
273// labeled as system_file.
274func (a *apexBundle) buildFileContexts(ctx android.ModuleContext) android.OutputPath {
Jooyung Han580eb4f2020-06-24 19:33:06 +0900275 var fileContexts android.Path
Liz Kammer37997c42021-09-14 17:53:38 -0400276 var fileContextsDir string
Jooyung Han580eb4f2020-06-24 19:33:06 +0900277 if a.properties.File_contexts == nil {
278 fileContexts = android.PathForSource(ctx, "system/sepolicy/apex", ctx.ModuleName()+"-file_contexts")
279 } else {
Liz Kammer37997c42021-09-14 17:53:38 -0400280 if m, t := android.SrcIsModuleWithTag(*a.properties.File_contexts); m != "" {
281 otherModule := android.GetModuleFromPathDep(ctx, m, t)
282 fileContextsDir = ctx.OtherModuleDir(otherModule)
283 }
Jooyung Han580eb4f2020-06-24 19:33:06 +0900284 fileContexts = android.PathForModuleSrc(ctx, *a.properties.File_contexts)
285 }
Liz Kammer37997c42021-09-14 17:53:38 -0400286 if fileContextsDir == "" {
287 fileContextsDir = filepath.Dir(fileContexts.String())
288 }
289 fileContextsDir += string(filepath.Separator)
290
Jooyung Han580eb4f2020-06-24 19:33:06 +0900291 if a.Platform() {
Liz Kammer37997c42021-09-14 17:53:38 -0400292 if !strings.HasPrefix(fileContextsDir, "system/sepolicy/") {
293 ctx.PropertyErrorf("file_contexts", "should be under system/sepolicy, but found in %q", fileContextsDir)
Jooyung Han580eb4f2020-06-24 19:33:06 +0900294 }
295 }
296 if !android.ExistentPathForSource(ctx, fileContexts.String()).Valid() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900297 ctx.PropertyErrorf("file_contexts", "cannot find file_contexts file: %q", fileContexts.String())
Jooyung Han580eb4f2020-06-24 19:33:06 +0900298 }
299
300 output := android.PathForModuleOut(ctx, "file_contexts")
Colin Crossf1a035e2020-11-16 17:32:30 -0800301 rule := android.NewRuleBuilder(pctx, ctx)
Jooyung Han7f146c02020-09-23 19:15:55 +0900302
Jiyong Parkb81b9902020-11-24 19:51:18 +0900303 switch a.properties.ApexType {
304 case imageApex:
Jooyung Han7f146c02020-09-23 19:15:55 +0900305 // remove old file
306 rule.Command().Text("rm").FlagWithOutput("-f ", output)
307 // copy file_contexts
308 rule.Command().Text("cat").Input(fileContexts).Text(">>").Output(output)
309 // new line
310 rule.Command().Text("echo").Text(">>").Output(output)
311 // force-label /apex_manifest.pb and / as system_file so that apexd can read them
312 rule.Command().Text("echo").Flag("/apex_manifest\\\\.pb u:object_r:system_file:s0").Text(">>").Output(output)
313 rule.Command().Text("echo").Flag("/ u:object_r:system_file:s0").Text(">>").Output(output)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900314 case flattenedApex:
Jooyung Han7f146c02020-09-23 19:15:55 +0900315 // For flattened apexes, install path should be prepended.
316 // File_contexts file should be emiited to make via LOCAL_FILE_CONTEXTS
317 // so that it can be merged into file_contexts.bin
318 apexPath := android.InstallPathToOnDevicePath(ctx, a.installDir.Join(ctx, a.Name()))
319 apexPath = strings.ReplaceAll(apexPath, ".", `\\.`)
320 // remove old file
321 rule.Command().Text("rm").FlagWithOutput("-f ", output)
322 // copy file_contexts
323 rule.Command().Text("awk").Text(`'/object_r/{printf("` + apexPath + `%s\n", $0)}'`).Input(fileContexts).Text(">").Output(output)
324 // new line
325 rule.Command().Text("echo").Text(">>").Output(output)
326 // force-label /apex_manifest.pb and / as system_file so that apexd can read them
327 rule.Command().Text("echo").Flag(apexPath + `/apex_manifest\\.pb u:object_r:system_file:s0`).Text(">>").Output(output)
328 rule.Command().Text("echo").Flag(apexPath + "/ u:object_r:system_file:s0").Text(">>").Output(output)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900329 default:
330 panic(fmt.Errorf("unsupported type %v", a.properties.ApexType))
Jooyung Han7f146c02020-09-23 19:15:55 +0900331 }
332
Colin Crossf1a035e2020-11-16 17:32:30 -0800333 rule.Build("file_contexts."+a.Name(), "Generate file_contexts")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900334 return output.OutputPath
Jooyung Han580eb4f2020-06-24 19:33:06 +0900335}
336
Jiyong Parkb81b9902020-11-24 19:51:18 +0900337// buildInstalledFilesFile creates a build rule for the installed-files.txt file where the list of
338// files included in this APEX is shown. The text file is dist'ed so that people can see what's
339// included in the APEX without actually downloading and extracting it.
Jiyong Park3a1602e2020-01-14 14:39:19 +0900340func (a *apexBundle) buildInstalledFilesFile(ctx android.ModuleContext, builtApex android.Path, imageDir android.Path) android.OutputPath {
341 output := android.PathForModuleOut(ctx, "installed-files.txt")
Colin Crossf1a035e2020-11-16 17:32:30 -0800342 rule := android.NewRuleBuilder(pctx, ctx)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900343 rule.Command().
344 Implicit(builtApex).
345 Text("(cd " + imageDir.String() + " ; ").
Jiyong Parkbd63a102020-02-08 12:40:05 +0900346 Text("find . \\( -type f -o -type l \\) -printf \"%s %p\\n\") ").
Jiyong Park3a1602e2020-01-14 14:39:19 +0900347 Text(" | sort -nr > ").
348 Output(output)
Colin Crossf1a035e2020-11-16 17:32:30 -0800349 rule.Build("installed-files."+a.Name(), "Installed files")
Jiyong Park3a1602e2020-01-14 14:39:19 +0900350 return output.OutputPath
351}
352
Jiyong Parkb81b9902020-11-24 19:51:18 +0900353// buildBundleConfig creates a build rule for the bundle config file that will control the bundle
354// creation process.
Jiyong Parkbd159612020-02-28 15:22:21 +0900355func (a *apexBundle) buildBundleConfig(ctx android.ModuleContext) android.OutputPath {
356 output := android.PathForModuleOut(ctx, "bundle_config.json")
357
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900358 type ApkConfig struct {
359 Package_name string `json:"package_name"`
360 Apk_path string `json:"path"`
361 }
Jiyong Parkbd159612020-02-28 15:22:21 +0900362 config := struct {
363 Compression struct {
364 Uncompressed_glob []string `json:"uncompressed_glob"`
365 } `json:"compression"`
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900366 Apex_config struct {
367 Apex_embedded_apk_config []ApkConfig `json:"apex_embedded_apk_config,omitempty"`
368 } `json:"apex_config,omitempty"`
Jiyong Parkbd159612020-02-28 15:22:21 +0900369 }{}
370
371 config.Compression.Uncompressed_glob = []string{
372 "apex_payload.img",
373 "apex_manifest.*",
374 }
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900375
Jiyong Parkb81b9902020-11-24 19:51:18 +0900376 // Collect the manifest names and paths of android apps if their manifest names are
377 // overridden.
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900378 for _, fi := range a.filesInfo {
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700379 if fi.class != app && fi.class != appSet {
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900380 continue
381 }
382 packageName := fi.overriddenPackageName
383 if packageName != "" {
384 config.Apex_config.Apex_embedded_apk_config = append(
385 config.Apex_config.Apex_embedded_apk_config,
386 ApkConfig{
387 Package_name: packageName,
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900388 Apk_path: fi.path(),
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900389 })
390 }
391 }
392
Jiyong Parkbd159612020-02-28 15:22:21 +0900393 j, err := json.Marshal(config)
394 if err != nil {
395 panic(fmt.Errorf("error while marshalling to %q: %#v", output, err))
396 }
397
Colin Crosscf371cc2020-11-13 11:48:42 -0800398 android.WriteFileRule(ctx, output, string(j))
Jiyong Parkbd159612020-02-28 15:22:21 +0900399
400 return output.OutputPath
401}
402
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000403func markManifestTestOnly(ctx android.ModuleContext, androidManifestFile android.Path) android.Path {
Gurpreet Singh7deabfa2022-02-10 13:28:35 +0000404 return java.ManifestFixer(ctx, androidManifestFile, java.ManifestFixerParams{
405 TestOnly: true,
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000406 })
407}
408
Jiyong Parkb81b9902020-11-24 19:51:18 +0900409// buildUnflattendApex creates build rules to build an APEX using apexer.
Jiyong Park09d77522019-11-18 11:16:27 +0900410func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext) {
Jiyong Park09d77522019-11-18 11:16:27 +0900411 apexType := a.properties.ApexType
412 suffix := apexType.suffix()
Colin Cross6340ea52021-11-04 12:01:18 -0700413 apexName := proptools.StringDefault(a.properties.Apex_name, a.BaseModuleName())
Jiyong Park09d77522019-11-18 11:16:27 +0900414
Jiyong Parkb81b9902020-11-24 19:51:18 +0900415 ////////////////////////////////////////////////////////////////////////////////////////////
416 // Step 1: copy built files to appropriate directories under the image directory
417
418 imageDir := android.PathForModuleOut(ctx, "image"+suffix)
419
Colin Cross02730b92022-04-18 17:42:27 -0700420 installSymbolFiles := (!ctx.Config().KatiEnabled() || a.ExportedToMake()) && a.installable()
Colin Cross6340ea52021-11-04 12:01:18 -0700421
422 // b/140136207. When there are overriding APEXes for a VNDK APEX, the symbols file for the overridden
423 // APEX and the overriding APEX will have the same installation paths at /apex/com.android.vndk.v<ver>
424 // as their apexName will be the same. To avoid the path conflicts, skip installing the symbol files
425 // for the overriding VNDK APEXes.
426 if a.vndkApex && len(a.overridableProperties.Overrides) > 0 {
427 installSymbolFiles = false
428 }
429
430 // Avoid creating duplicate build rules for multi-installed APEXes.
431 if proptools.BoolDefault(a.properties.Multi_install_skip_symbol_files, false) {
432 installSymbolFiles = false
Colin Cross4acaea92021-12-10 23:05:02 +0000433
Colin Cross6340ea52021-11-04 12:01:18 -0700434 }
Colin Cross4acaea92021-12-10 23:05:02 +0000435 // set of dependency module:location mappings
436 installMapSet := make(map[string]bool)
Colin Cross6340ea52021-11-04 12:01:18 -0700437
Jiyong Parkb81b9902020-11-24 19:51:18 +0900438 // TODO(jiyong): use the RuleBuilder
Jiyong Park7cd10e32020-01-14 09:22:18 +0900439 var copyCommands []string
Jiyong Parkb81b9902020-11-24 19:51:18 +0900440 var implicitInputs []android.Path
Colin Cross6340ea52021-11-04 12:01:18 -0700441 pathWhenActivated := android.PathForModuleInPartitionInstall(ctx, "apex", apexName)
Jiyong Park7cd10e32020-01-14 09:22:18 +0900442 for _, fi := range a.filesInfo {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900443 destPath := imageDir.Join(ctx, fi.path()).String()
Jiyong Parkb81b9902020-11-24 19:51:18 +0900444 // Prepare the destination path
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700445 destPathDir := filepath.Dir(destPath)
446 if fi.class == appSet {
447 copyCommands = append(copyCommands, "rm -rf "+destPathDir)
448 }
449 copyCommands = append(copyCommands, "mkdir -p "+destPathDir)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900450
Colin Cross4acaea92021-12-10 23:05:02 +0000451 installMapPath := fi.builtFile
452
Jiyong Parkb81b9902020-11-24 19:51:18 +0900453 // Copy the built file to the directory. But if the symlink optimization is turned
454 // on, place a symlink to the corresponding file in /system partition instead.
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900455 if a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform() {
Jiyong Park7cd10e32020-01-14 09:22:18 +0900456 // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900457 pathOnDevice := filepath.Join("/system", fi.path())
Jiyong Park7cd10e32020-01-14 09:22:18 +0900458 copyCommands = append(copyCommands, "ln -sfn "+pathOnDevice+" "+destPath)
459 } else {
Colin Cross4acaea92021-12-10 23:05:02 +0000460 var installedPath android.InstallPath
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700461 if fi.class == appSet {
462 copyCommands = append(copyCommands,
Colin Crossffbcd1d2021-11-12 12:19:42 -0800463 fmt.Sprintf("unzip -qDD -d %s %s", destPathDir,
464 fi.module.(*java.AndroidAppSet).PackedAdditionalOutputs().String()))
Colin Cross6340ea52021-11-04 12:01:18 -0700465 if installSymbolFiles {
466 installedPath = ctx.InstallFileWithExtraFilesZip(pathWhenActivated.Join(ctx, fi.installDir),
467 fi.stem(), fi.builtFile, fi.module.(*java.AndroidAppSet).PackedAdditionalOutputs())
468 }
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700469 } else {
470 copyCommands = append(copyCommands, "cp -f "+fi.builtFile.String()+" "+destPath)
Colin Cross6340ea52021-11-04 12:01:18 -0700471 if installSymbolFiles {
472 installedPath = ctx.InstallFile(pathWhenActivated.Join(ctx, fi.installDir), fi.stem(), fi.builtFile)
473 }
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700474 }
Jiyong Park7cd10e32020-01-14 09:22:18 +0900475 implicitInputs = append(implicitInputs, fi.builtFile)
Colin Cross6340ea52021-11-04 12:01:18 -0700476 if installSymbolFiles {
477 implicitInputs = append(implicitInputs, installedPath)
478 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900479
Colin Cross4acaea92021-12-10 23:05:02 +0000480 // Create additional symlinks pointing the file inside the APEX (if any). Note that
481 // this is independent from the symlink optimization.
482 for _, symlinkPath := range fi.symlinkPaths() {
483 symlinkDest := imageDir.Join(ctx, symlinkPath).String()
484 copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
485 if installSymbolFiles {
486 installedSymlink := ctx.InstallSymlink(pathWhenActivated.Join(ctx, filepath.Dir(symlinkPath)), filepath.Base(symlinkPath), installedPath)
487 implicitInputs = append(implicitInputs, installedSymlink)
488 }
Colin Cross6340ea52021-11-04 12:01:18 -0700489 }
Colin Cross4acaea92021-12-10 23:05:02 +0000490
491 installMapPath = installedPath
Jiyong Park7cd10e32020-01-14 09:22:18 +0900492 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900493
494 // Copy the test files (if any)
Liz Kammer1c14a212020-05-12 15:26:55 -0700495 for _, d := range fi.dataPaths {
496 // TODO(eakammer): This is now the third repetition of ~this logic for test paths, refactoring should be possible
Chris Parsons216e10a2020-07-09 17:12:52 -0400497 relPath := d.SrcPath.Rel()
498 dataPath := d.SrcPath.String()
Liz Kammer1c14a212020-05-12 15:26:55 -0700499 if !strings.HasSuffix(dataPath, relPath) {
500 panic(fmt.Errorf("path %q does not end with %q", dataPath, relPath))
501 }
502
Jiyong Parkb81b9902020-11-24 19:51:18 +0900503 dataDest := imageDir.Join(ctx, fi.apexRelativePath(relPath), d.RelativeInstallPath).String()
Liz Kammer1c14a212020-05-12 15:26:55 -0700504
Chris Parsons216e10a2020-07-09 17:12:52 -0400505 copyCommands = append(copyCommands, "cp -f "+d.SrcPath.String()+" "+dataDest)
506 implicitInputs = append(implicitInputs, d.SrcPath)
Liz Kammer1c14a212020-05-12 15:26:55 -0700507 }
Colin Cross4acaea92021-12-10 23:05:02 +0000508
509 installMapSet[installMapPath.String()+":"+fi.installDir+"/"+fi.builtFile.Base()] = true
Jiyong Park09d77522019-11-18 11:16:27 +0900510 }
Jooyung Han214bf372019-11-12 13:03:50 +0900511 implicitInputs = append(implicitInputs, a.manifestPbOut)
Colin Cross6340ea52021-11-04 12:01:18 -0700512 if installSymbolFiles {
513 installedManifest := ctx.InstallFile(pathWhenActivated, "apex_manifest.pb", a.manifestPbOut)
514 installedKey := ctx.InstallFile(pathWhenActivated, "apex_pubkey", a.publicKeyFile)
515 implicitInputs = append(implicitInputs, installedManifest, installedKey)
516 }
Jiyong Park09d77522019-11-18 11:16:27 +0900517
Colin Cross4acaea92021-12-10 23:05:02 +0000518 if len(installMapSet) > 0 {
519 var installs []string
520 installs = append(installs, android.SortedStringKeys(installMapSet)...)
521 a.SetLicenseInstallMap(installs)
522 }
523
Jiyong Parkb81b9902020-11-24 19:51:18 +0900524 ////////////////////////////////////////////////////////////////////////////////////////////
525 // Step 1.a: Write the list of files in this APEX to a txt file and compare it against
526 // the allowed list given via the allowed_files property. Build fails when the two lists
527 // differ.
528 //
529 // TODO(jiyong): consider removing this. Nobody other than com.android.apex.cts.shim.* seems
530 // to be using this at this moment. Furthermore, this looks very similar to what
531 // buildInstalledFilesFile does. At least, move this to somewhere else so that this doesn't
532 // hurt readability.
533 // TODO(jiyong): use RuleBuilder
Jooyung Han938b5932020-06-20 12:47:47 +0900534 if a.overridableProperties.Allowed_files != nil {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900535 // Build content.txt
536 var emitCommands []string
537 imageContentFile := android.PathForModuleOut(ctx, "content.txt")
538 emitCommands = append(emitCommands, "echo ./apex_manifest.pb >> "+imageContentFile.String())
539 minSdkVersion := a.minSdkVersion(ctx)
540 if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
541 emitCommands = append(emitCommands, "echo ./apex_manifest.json >> "+imageContentFile.String())
542 }
543 for _, fi := range a.filesInfo {
544 emitCommands = append(emitCommands, "echo './"+fi.path()+"' >> "+imageContentFile.String())
545 }
546 emitCommands = append(emitCommands, "sort -o "+imageContentFile.String()+" "+imageContentFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900547 ctx.Build(pctx, android.BuildParams{
548 Rule: emitApexContentRule,
549 Implicits: implicitInputs,
550 Output: imageContentFile,
551 Description: "emit apex image content",
552 Args: map[string]string{
553 "emit_commands": strings.Join(emitCommands, " && "),
554 },
555 })
556 implicitInputs = append(implicitInputs, imageContentFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900557
Jiyong Parkb81b9902020-11-24 19:51:18 +0900558 // Compare content.txt against allowed_files.
559 allowedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.overridableProperties.Allowed_files))
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800560 phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
Jiyong Park09d77522019-11-18 11:16:27 +0900561 ctx.Build(pctx, android.BuildParams{
562 Rule: diffApexContentRule,
563 Implicits: implicitInputs,
564 Output: phonyOutput,
565 Description: "diff apex image content",
566 Args: map[string]string{
Colin Cross440e0d02020-06-11 11:32:11 -0700567 "allowed_files_file": allowedFilesFile.String(),
568 "image_content_file": imageContentFile.String(),
569 "apex_module_name": a.Name(),
Jiyong Park09d77522019-11-18 11:16:27 +0900570 },
571 })
Jiyong Park09d77522019-11-18 11:16:27 +0900572 implicitInputs = append(implicitInputs, phonyOutput)
573 }
574
Jiyong Parkb81b9902020-11-24 19:51:18 +0900575 unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
Colin Cross790ef352021-10-25 19:15:55 -0700576 outHostBinDir := ctx.Config().HostToolPath(ctx, "").String()
Jiyong Park09d77522019-11-18 11:16:27 +0900577 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
578
Oriol Prieto Gascoa07099d2021-10-14 15:33:41 -0400579 // Figure out if we need to compress the apex.
580 compressionEnabled := ctx.Config().CompressedApex() && proptools.BoolDefault(a.overridableProperties.Compressible, false) && !a.testApex && !ctx.Config().UnbundledBuildApps()
Jiyong Park09d77522019-11-18 11:16:27 +0900581 if apexType == imageApex {
Jiyong Park1b0893e2021-12-13 23:40:17 +0900582
Jiyong Parkb81b9902020-11-24 19:51:18 +0900583 ////////////////////////////////////////////////////////////////////////////////////
584 // Step 2: create canned_fs_config which encodes filemode,uid,gid of each files
585 // in this APEX. The file will be used by apexer in later steps.
Jiyong Park1b0893e2021-12-13 23:40:17 +0900586 cannedFsConfig := a.buildCannedFsConfig(ctx)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900587 implicitInputs = append(implicitInputs, cannedFsConfig)
Jiyong Park09d77522019-11-18 11:16:27 +0900588
Jiyong Parkb81b9902020-11-24 19:51:18 +0900589 ////////////////////////////////////////////////////////////////////////////////////
590 // Step 3: Prepare option flags for apexer and invoke it to create an unsigned APEX.
591 // TODO(jiyong): use the RuleBuilder
Jiyong Park09d77522019-11-18 11:16:27 +0900592 optFlags := []string{}
593
Jiyong Parkb81b9902020-11-24 19:51:18 +0900594 fileContexts := a.buildFileContexts(ctx)
595 implicitInputs = append(implicitInputs, fileContexts)
596
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800597 implicitInputs = append(implicitInputs, a.privateKeyFile, a.publicKeyFile)
598 optFlags = append(optFlags, "--pubkey "+a.publicKeyFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900599
Jooyung Han27151d92019-12-16 17:45:32 +0900600 manifestPackageName := a.getOverrideManifestPackageName(ctx)
601 if manifestPackageName != "" {
Jiyong Park09d77522019-11-18 11:16:27 +0900602 optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
603 }
604
605 if a.properties.AndroidManifest != nil {
606 androidManifestFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.AndroidManifest))
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000607
608 if a.testApex {
609 androidManifestFile = markManifestTestOnly(ctx, androidManifestFile)
610 }
611
Jiyong Park09d77522019-11-18 11:16:27 +0900612 implicitInputs = append(implicitInputs, androidManifestFile)
613 optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
Gurpreet Singha76f8742022-02-03 21:01:51 +0000614 } else if a.testApex {
615 optFlags = append(optFlags, "--test_only")
Jiyong Park09d77522019-11-18 11:16:27 +0900616 }
617
Jiyong Parkb81b9902020-11-24 19:51:18 +0900618 // Determine target/min sdk version from the context
619 // TODO(jiyong): make this as a function
Dan Albertc8060532020-07-22 22:32:17 -0700620 moduleMinSdkVersion := a.minSdkVersion(ctx)
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100621 minSdkVersion := moduleMinSdkVersion.String()
622
Jiyong Parkb81b9902020-11-24 19:51:18 +0900623 // bundletool doesn't understand what "current" is. We need to transform it to
624 // codename
Jooyung Haned124c32021-01-26 11:43:46 +0900625 if moduleMinSdkVersion.IsCurrent() || moduleMinSdkVersion.IsNone() {
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100626 minSdkVersion = ctx.Config().DefaultAppTargetSdk(ctx).String()
Liz Kammer4854a7d2021-05-27 14:28:27 -0400627
628 if java.UseApiFingerprint(ctx) {
629 minSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
630 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
631 }
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000632 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900633 // apex module doesn't have a concept of target_sdk_version, hence for the time
634 // being targetSdkVersion == default targetSdkVersion of the branch.
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100635 targetSdkVersion := strconv.Itoa(ctx.Config().DefaultAppTargetSdk(ctx).FinalOrFutureInt())
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000636
Nikita Ioffe1f4f3452020-03-02 16:58:11 +0000637 if java.UseApiFingerprint(ctx) {
638 targetSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
Baligh Uddinf6201372020-01-24 23:15:44 +0000639 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
640 }
Jiyong Park09d77522019-11-18 11:16:27 +0900641 optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
Baligh Uddinf6201372020-01-24 23:15:44 +0000642 optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
Jiyong Park09d77522019-11-18 11:16:27 +0900643
Baligh Uddin004d7172020-02-19 21:29:28 -0800644 if a.overridableProperties.Logging_parent != "" {
645 optFlags = append(optFlags, "--logging_parent ", a.overridableProperties.Logging_parent)
646 }
647
Bob Badourde6a0872022-04-01 18:00:00 +0000648 // Create a NOTICE file, and embed it as an asset file in the APEX.
Bob Badour2c8888e2022-04-04 16:12:21 -0700649 a.htmlGzNotice = android.PathForModuleOut(ctx, "NOTICE.html.gz")
Bob Badourc6ec9fb2022-06-08 15:59:35 -0700650 android.BuildNoticeHtmlOutputFromLicenseMetadata(
651 ctx, a.htmlGzNotice, "", "",
652 []string{
653 android.PathForModuleInstall(ctx).String() + "/",
654 android.PathForModuleInPartitionInstall(ctx, "apex").String() + "/",
655 })
Bob Badour2c8888e2022-04-04 16:12:21 -0700656 noticeAssetPath := android.PathForModuleOut(ctx, "NOTICE", "NOTICE.html.gz")
657 builder := android.NewRuleBuilder(pctx, ctx)
658 builder.Command().Text("cp").
659 Input(a.htmlGzNotice).
660 Output(noticeAssetPath)
661 builder.Build("notice_dir", "Building notice dir")
662 implicitInputs = append(implicitInputs, noticeAssetPath)
663 optFlags = append(optFlags, "--assets_dir "+filepath.Dir(noticeAssetPath.String()))
Jiyong Park09d77522019-11-18 11:16:27 +0900664
Nikita Ioffe9d9960f2021-06-09 19:43:46 +0100665 if (moduleMinSdkVersion.GreaterThan(android.SdkVersion_Android10) && !a.shouldGenerateHashtree()) && !compressionEnabled {
Jiyong Park09d77522019-11-18 11:16:27 +0900666 // Apexes which are supposed to be installed in builtin dirs(/system, etc)
667 // don't need hashtree for activation. Therefore, by removing hashtree from
668 // apex bundle (filesystem image in it, to be specific), we can save storage.
669 optFlags = append(optFlags, "--no_hashtree")
670 }
671
Dario Frenica913392020-04-27 18:21:11 +0100672 if a.testOnlyShouldSkipPayloadSign() {
673 optFlags = append(optFlags, "--unsigned_payload")
674 }
675
Jiyong Park09d77522019-11-18 11:16:27 +0900676 if a.properties.Apex_name != nil {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900677 // If apex_name is set, apexer can skip checking if key name matches with
678 // apex name. Note that apex_manifest is also mended.
Jiyong Park09d77522019-11-18 11:16:27 +0900679 optFlags = append(optFlags, "--do_not_check_keyname")
680 }
681
Dan Albertc8060532020-07-22 22:32:17 -0700682 if moduleMinSdkVersion == android.SdkVersion_Android10 {
Jooyung Han214bf372019-11-12 13:03:50 +0900683 implicitInputs = append(implicitInputs, a.manifestJsonOut)
684 optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
685 }
686
Theotime Combes4ba38c12020-06-12 12:46:59 +0000687 optFlags = append(optFlags, "--payload_fs_type "+a.payloadFsType.string())
688
Jiyong Park09d77522019-11-18 11:16:27 +0900689 ctx.Build(pctx, android.BuildParams{
690 Rule: apexRule,
691 Implicits: implicitInputs,
692 Output: unsignedOutputFile,
693 Description: "apex (" + apexType.name() + ")",
694 Args: map[string]string{
Oriol Prieto Gasco17e22902022-05-05 13:52:25 +0000695 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
696 "image_dir": imageDir.String(),
697 "copy_commands": strings.Join(copyCommands, " && "),
698 "manifest": a.manifestPbOut.String(),
699 "file_contexts": fileContexts.String(),
700 "canned_fs_config": cannedFsConfig.String(),
701 "key": a.privateKeyFile.String(),
Alexei Nicoarac939b012022-07-06 12:03:11 +0100702 "apex_version": defaultManifestVersion,
Oriol Prieto Gasco17e22902022-05-05 13:52:25 +0000703 "opt_flags": strings.Join(optFlags, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900704 },
705 })
706
Jiyong Parkb81b9902020-11-24 19:51:18 +0900707 // TODO(jiyong): make the two rules below as separate functions
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800708 apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
709 bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
Jiyong Park09d77522019-11-18 11:16:27 +0900710 a.bundleModuleFile = bundleModuleFile
711
712 ctx.Build(pctx, android.BuildParams{
713 Rule: apexProtoConvertRule,
714 Input: unsignedOutputFile,
715 Output: apexProtoFile,
716 Description: "apex proto convert",
717 })
718
sophiezc80a2b32020-11-12 16:39:19 +0000719 implicitInputs = append(implicitInputs, unsignedOutputFile)
720
721 // Run coverage analysis
sophiez6bde0b52021-01-09 01:03:42 +0000722 apisUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.txt")
sophiezc80a2b32020-11-12 16:39:19 +0000723 ctx.Build(pctx, android.BuildParams{
724 Rule: generateAPIsUsedbyApexRule,
725 Implicits: implicitInputs,
726 Description: "coverage",
727 Output: apisUsedbyOutputFile,
728 Args: map[string]string{
729 "image_dir": imageDir.String(),
730 "readelf": "${config.ClangBin}/llvm-readelf",
731 },
732 })
sophiez02347372021-11-02 17:58:02 -0700733 a.nativeApisUsedByModuleFile = apisUsedbyOutputFile
sophiez6bde0b52021-01-09 01:03:42 +0000734
sophiez02347372021-11-02 17:58:02 -0700735 var nativeLibNames []string
Colin Cross69f0a242021-02-08 16:49:57 -0800736 for _, f := range a.filesInfo {
737 if f.class == nativeSharedLib {
sophiez02347372021-11-02 17:58:02 -0700738 nativeLibNames = append(nativeLibNames, f.stem())
Colin Cross69f0a242021-02-08 16:49:57 -0800739 }
740 }
sophiez6bde0b52021-01-09 01:03:42 +0000741 apisBackedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_backing.txt")
sophiez6bde0b52021-01-09 01:03:42 +0000742 rule := android.NewRuleBuilder(pctx, ctx)
743 rule.Command().
744 Tool(android.PathForSource(ctx, "build/soong/scripts/gen_ndk_backedby_apex.sh")).
sophiez6bde0b52021-01-09 01:03:42 +0000745 Output(apisBackedbyOutputFile).
sophiez02347372021-11-02 17:58:02 -0700746 Flags(nativeLibNames)
sophiez6bde0b52021-01-09 01:03:42 +0000747 rule.Build("ndk_backedby_list", "Generate API libraries backed by Apex")
sophiez02347372021-11-02 17:58:02 -0700748 a.nativeApisBackedByModuleFile = apisBackedbyOutputFile
749
750 var javaLibOrApkPath []android.Path
751 for _, f := range a.filesInfo {
752 if f.class == javaSharedLib || f.class == app {
753 javaLibOrApkPath = append(javaLibOrApkPath, f.builtFile)
754 }
755 }
756 javaApiUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.xml")
757 javaUsedByRule := android.NewRuleBuilder(pctx, ctx)
758 javaUsedByRule.Command().
759 Tool(android.PathForSource(ctx, "build/soong/scripts/gen_java_usedby_apex.sh")).
760 BuiltTool("dexdeps").
761 Output(javaApiUsedbyOutputFile).
762 Inputs(javaLibOrApkPath)
763 javaUsedByRule.Build("java_usedby_list", "Generate Java APIs used by Apex")
764 a.javaApisUsedByModuleFile = javaApiUsedbyOutputFile
sophiezc80a2b32020-11-12 16:39:19 +0000765
Jiyong Parkbd159612020-02-28 15:22:21 +0900766 bundleConfig := a.buildBundleConfig(ctx)
767
Jiyong Parkb81b9902020-11-24 19:51:18 +0900768 var abis []string
769 for _, target := range ctx.MultiTargets() {
770 if len(target.Arch.Abi) > 0 {
771 abis = append(abis, target.Arch.Abi[0])
772 }
773 }
774
775 abis = android.FirstUniqueStrings(abis)
776
Jiyong Park09d77522019-11-18 11:16:27 +0900777 ctx.Build(pctx, android.BuildParams{
778 Rule: apexBundleRule,
779 Input: apexProtoFile,
Jiyong Parkbd159612020-02-28 15:22:21 +0900780 Implicit: bundleConfig,
Jiyong Park09d77522019-11-18 11:16:27 +0900781 Output: a.bundleModuleFile,
782 Description: "apex bundle module",
783 Args: map[string]string{
Jiyong Parkbd159612020-02-28 15:22:21 +0900784 "abi": strings.Join(abis, "."),
785 "config": bundleConfig.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900786 },
787 })
Jiyong Parkb81b9902020-11-24 19:51:18 +0900788 } else { // zipApex
Jiyong Park09d77522019-11-18 11:16:27 +0900789 ctx.Build(pctx, android.BuildParams{
790 Rule: zipApexRule,
791 Implicits: implicitInputs,
792 Output: unsignedOutputFile,
793 Description: "apex (" + apexType.name() + ")",
794 Args: map[string]string{
Oriol Prieto Gasco17e22902022-05-05 13:52:25 +0000795 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
796 "image_dir": imageDir.String(),
797 "copy_commands": strings.Join(copyCommands, " && "),
798 "manifest": a.manifestPbOut.String(),
Alexei Nicoarac939b012022-07-06 12:03:11 +0100799 "apex_version": defaultManifestVersion,
Jiyong Park09d77522019-11-18 11:16:27 +0900800 },
801 })
802 }
803
Jiyong Parkb81b9902020-11-24 19:51:18 +0900804 ////////////////////////////////////////////////////////////////////////////////////
805 // Step 4: Sign the APEX using signapk
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000806 signedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900807
808 pem, key := a.getCertificateAndPrivateKey(ctx)
Kousik Kumar309b1c02020-05-28 06:13:33 -0700809 rule := java.Signapk
810 args := map[string]string{
Jiyong Parkb81b9902020-11-24 19:51:18 +0900811 "certificates": pem.String() + " " + key.String(),
Jooyung Han5d00f502021-07-11 07:26:22 +0900812 "flags": "-a 4096 --align-file-size", //alignment
Kousik Kumar309b1c02020-05-28 06:13:33 -0700813 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900814 implicits := android.Paths{pem, key}
Ramy Medhat16f23a42020-09-03 01:29:49 -0400815 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
Kousik Kumar309b1c02020-05-28 06:13:33 -0700816 rule = java.SignapkRE
817 args["implicits"] = strings.Join(implicits.Strings(), ",")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000818 args["outCommaList"] = signedOutputFile.String()
Kousik Kumar309b1c02020-05-28 06:13:33 -0700819 }
Jiyong Park09d77522019-11-18 11:16:27 +0900820 ctx.Build(pctx, android.BuildParams{
Kousik Kumar309b1c02020-05-28 06:13:33 -0700821 Rule: rule,
Jiyong Park09d77522019-11-18 11:16:27 +0900822 Description: "signapk",
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000823 Output: signedOutputFile,
Jiyong Park09d77522019-11-18 11:16:27 +0900824 Input: unsignedOutputFile,
Kousik Kumar309b1c02020-05-28 06:13:33 -0700825 Implicits: implicits,
826 Args: args,
Jiyong Park09d77522019-11-18 11:16:27 +0900827 })
Jooyung Hana6d36672022-02-24 13:58:07 +0900828 if suffix == imageApexSuffix {
829 a.outputApexFile = signedOutputFile
830 }
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000831 a.outputFile = signedOutputFile
832
Mohammad Samiul Islama8008f92020-12-22 10:47:50 +0000833 if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && a.testOnlyShouldForceCompression() {
834 ctx.PropertyErrorf("test_only_force_compression", "not available")
835 return
836 }
Nikita Ioffebc035882021-04-14 21:35:24 +0100837
Mohammad Samiul Islama8008f92020-12-22 10:47:50 +0000838 if apexType == imageApex && (compressionEnabled || a.testOnlyShouldForceCompression()) {
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000839 a.isCompressed = true
Samiul Islam7c02e262021-09-08 17:48:28 +0100840 unsignedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix+".unsigned")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000841
842 compressRule := android.NewRuleBuilder(pctx, ctx)
843 compressRule.Command().
844 Text("rm").
845 FlagWithOutput("-f ", unsignedCompressedOutputFile)
846 compressRule.Command().
847 BuiltTool("apex_compression_tool").
848 Flag("compress").
849 FlagWithArg("--apex_compression_tool ", outHostBinDir+":"+prebuiltSdkToolsBinDir).
850 FlagWithInput("--input ", signedOutputFile).
851 FlagWithOutput("--output ", unsignedCompressedOutputFile)
852 compressRule.Build("compressRule", "Generate unsigned compressed APEX file")
853
Samiul Islam7c02e262021-09-08 17:48:28 +0100854 signedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix)
Mohammad Samiul Islam9ac0e322021-01-19 11:32:29 +0000855 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
856 args["outCommaList"] = signedCompressedOutputFile.String()
857 }
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000858 ctx.Build(pctx, android.BuildParams{
859 Rule: rule,
860 Description: "sign compressedApex",
861 Output: signedCompressedOutputFile,
862 Input: unsignedCompressedOutputFile,
863 Implicits: implicits,
864 Args: args,
865 })
866 a.outputFile = signedCompressedOutputFile
867 }
Jiyong Park09d77522019-11-18 11:16:27 +0900868
Colin Cross6340ea52021-11-04 12:01:18 -0700869 installSuffix := suffix
870 if a.isCompressed {
871 installSuffix = imageCapexSuffix
872 }
873
Colin Crossd9ccb6a2022-03-07 18:38:34 -0800874 if !a.installable() {
875 a.SkipInstall()
876 }
877
Jiyong Park17ff2832021-09-27 12:50:30 +0900878 // Install to $OUT/soong/{target,host}/.../apex.
Colin Cross6340ea52021-11-04 12:01:18 -0700879 a.installedFile = ctx.InstallFile(a.installDir, a.Name()+installSuffix, a.outputFile,
880 a.compatSymlinks.Paths()...)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900881
882 // installed-files.txt is dist'ed
883 a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900884}
885
Jiyong Parkb81b9902020-11-24 19:51:18 +0900886// buildFlattenedApex creates rules for a flattened APEX. Flattened APEX actually doesn't have a
887// single output file. It is a phony target for all the files under /system/apex/<name> directory.
888// This function creates the installation rules for the files.
Jiyong Park09d77522019-11-18 11:16:27 +0900889func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900890 bundleName := a.Name()
Colin Cross6340ea52021-11-04 12:01:18 -0700891 installedSymlinks := append(android.InstallPaths(nil), a.compatSymlinks...)
Jiyong Park09d77522019-11-18 11:16:27 +0900892 if a.installable() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900893 for _, fi := range a.filesInfo {
894 dir := filepath.Join("apex", bundleName, fi.installDir)
Colin Cross6340ea52021-11-04 12:01:18 -0700895 installDir := android.PathForModuleInstall(ctx, dir)
896 if a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform() {
897 // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
898 pathOnDevice := filepath.Join("/system", fi.path())
899 installedSymlinks = append(installedSymlinks,
900 ctx.InstallAbsoluteSymlink(installDir, fi.stem(), pathOnDevice))
901 } else {
902 target := ctx.InstallFile(installDir, fi.stem(), fi.builtFile)
903 for _, sym := range fi.symlinks {
904 installedSymlinks = append(installedSymlinks,
905 ctx.InstallSymlink(installDir, sym, target))
906 }
Jiyong Park09d77522019-11-18 11:16:27 +0900907 }
908 }
Colin Cross6340ea52021-11-04 12:01:18 -0700909
910 // Create install rules for the files added in GenerateAndroidBuildActions after
911 // buildFlattenedApex is called. Add the links to system libs (if any) as dependencies
912 // of the apex_manifest.pb file since it is always present.
913 dir := filepath.Join("apex", bundleName)
914 installDir := android.PathForModuleInstall(ctx, dir)
915 ctx.InstallFile(installDir, "apex_manifest.pb", a.manifestPbOut, installedSymlinks.Paths()...)
916 ctx.InstallFile(installDir, "apex_pubkey", a.publicKeyFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900917 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900918
919 a.fileContexts = a.buildFileContexts(ctx)
920
Colin Cross6340ea52021-11-04 12:01:18 -0700921 a.outputFile = android.PathForModuleInstall(ctx, "apex", bundleName)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900922}
923
924// getCertificateAndPrivateKey retrieves the cert and the private key that will be used to sign
925// the zip container of this APEX. See the description of the 'certificate' property for how
926// the cert and the private key are found.
927func (a *apexBundle) getCertificateAndPrivateKey(ctx android.PathContext) (pem, key android.Path) {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800928 if a.containerCertificateFile != nil {
929 return a.containerCertificateFile, a.containerPrivateKeyFile
Jiyong Parkb81b9902020-11-24 19:51:18 +0900930 }
931
Jaewoong Jung4cfdf7d2021-04-20 16:21:24 -0700932 cert := String(a.overridableProperties.Certificate)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900933 if cert == "" {
934 return ctx.Config().DefaultAppCertificate(ctx)
935 }
936
937 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
938 pem = defaultDir.Join(ctx, cert+".x509.pem")
939 key = defaultDir.Join(ctx, cert+".pk8")
940 return pem, key
Jiyong Park09d77522019-11-18 11:16:27 +0900941}
Jooyung Han27151d92019-12-16 17:45:32 +0900942
943func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
944 // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
945 // to see if it should be overridden because their <apex name> is dynamically generated
946 // according to its VNDK version.
947 if a.vndkApex {
948 overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
949 if overridden {
950 return strings.Replace(*a.properties.Apex_name, vndkApexName, overrideName, 1)
951 }
952 return ""
953 }
Baligh Uddin5b57dba2020-03-15 13:01:05 -0700954 if a.overridableProperties.Package_name != "" {
955 return a.overridableProperties.Package_name
956 }
Jiyong Park20bacab2020-03-03 11:45:41 +0900957 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jooyung Han27151d92019-12-16 17:45:32 +0900958 if overridden {
959 return manifestPackageName
960 }
961 return ""
962}
Jiyong Park83dc74b2020-01-14 18:38:44 +0900963
964func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
965 if !a.primaryApexType {
966 return
967 }
968
969 if a.properties.IsCoverageVariant {
970 // Otherwise, we will have duplicated rules for coverage and
971 // non-coverage variants of the same APEX
972 return
973 }
974
975 if ctx.Host() {
976 // No need to generate dependency info for host variant
977 return
978 }
979
Artur Satayev872a1442020-04-27 17:08:37 +0100980 depInfos := android.DepNameToDepInfoMap{}
Jooyung Han749dc692020-04-15 11:03:39 +0900981 a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
Artur Satayev872a1442020-04-27 17:08:37 +0100982 if from.Name() == to.Name() {
983 // This can happen for cc.reuseObjTag. We are not interested in tracking this.
984 // As soon as the dependency graph crosses the APEX boundary, don't go further.
985 return !externalDep
Jiyong Park678c8812020-02-07 17:25:49 +0900986 }
Jiyong Park83dc74b2020-01-14 18:38:44 +0900987
Artur Satayev533b98c2021-03-11 18:03:42 +0000988 // Skip dependencies that are only available to APEXes; they are developed with updatability
989 // in mind and don't need manual approval.
990 if to.(android.ApexModule).NotAvailableForPlatform() {
991 return !externalDep
992 }
993
Cindy Zhou18417cb2020-12-10 07:12:38 -0800994 depTag := ctx.OtherModuleDependencyTag(to)
Artur Satayev533b98c2021-03-11 18:03:42 +0000995 // Check to see if dependency been marked to skip the dependency check
Cindy Zhou18417cb2020-12-10 07:12:38 -0800996 if skipDepCheck, ok := depTag.(android.SkipApexAllowedDependenciesCheck); ok && skipDepCheck.SkipApexAllowedDependenciesCheck() {
Cindy Zhou18417cb2020-12-10 07:12:38 -0800997 return !externalDep
998 }
999
Artur Satayev872a1442020-04-27 17:08:37 +01001000 if info, exists := depInfos[to.Name()]; exists {
1001 if !android.InList(from.Name(), info.From) {
1002 info.From = append(info.From, from.Name())
1003 }
1004 info.IsExternal = info.IsExternal && externalDep
1005 depInfos[to.Name()] = info
1006 } else {
Artur Satayev480e25b2020-04-27 18:53:18 +01001007 toMinSdkVersion := "(no version)"
Jiyong Park92315372021-04-02 08:45:46 +09001008 if m, ok := to.(interface {
1009 MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec
1010 }); ok {
1011 if v := m.MinSdkVersion(ctx); !v.ApiLevel.IsNone() {
1012 toMinSdkVersion = v.ApiLevel.String()
1013 }
1014 } else if m, ok := to.(interface{ MinSdkVersion() string }); ok {
1015 // TODO(b/175678607) eliminate the use of MinSdkVersion returning
1016 // string
Artur Satayev480e25b2020-04-27 18:53:18 +01001017 if v := m.MinSdkVersion(); v != "" {
1018 toMinSdkVersion = v
1019 }
1020 }
Artur Satayev872a1442020-04-27 17:08:37 +01001021 depInfos[to.Name()] = android.ApexModuleDepInfo{
Artur Satayev480e25b2020-04-27 18:53:18 +01001022 To: to.Name(),
1023 From: []string{from.Name()},
1024 IsExternal: externalDep,
1025 MinSdkVersion: toMinSdkVersion,
Artur Satayev872a1442020-04-27 17:08:37 +01001026 }
1027 }
1028
1029 // As soon as the dependency graph crosses the APEX boundary, don't go further.
1030 return !externalDep
Jiyong Park83dc74b2020-01-14 18:38:44 +09001031 })
1032
Albert Martineefabcf2022-03-21 20:11:16 +00001033 a.ApexBundleDepsInfo.BuildDepsInfoLists(ctx, a.MinSdkVersion(ctx).Raw, depInfos)
Artur Satayev872a1442020-04-27 17:08:37 +01001034
Jiyong Park83dc74b2020-01-14 18:38:44 +09001035 ctx.Build(pctx, android.BuildParams{
1036 Rule: android.Phony,
1037 Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
Artur Satayeva8bd1132020-04-27 18:07:06 +01001038 Inputs: []android.Path{
1039 a.ApexBundleDepsInfo.FullListPath(),
1040 a.ApexBundleDepsInfo.FlatListPath(),
1041 },
Jiyong Park83dc74b2020-01-14 18:38:44 +09001042 })
1043}
Colin Cross08dca382020-07-21 20:31:17 -07001044
1045func (a *apexBundle) buildLintReports(ctx android.ModuleContext) {
1046 depSetsBuilder := java.NewLintDepSetBuilder()
1047 for _, fi := range a.filesInfo {
1048 depSetsBuilder.Transitive(fi.lintDepSets)
1049 }
1050
1051 a.lintReports = java.BuildModuleLintReportZips(ctx, depSetsBuilder.Build())
1052}
Jiyong Park1b0893e2021-12-13 23:40:17 +09001053
1054func (a *apexBundle) buildCannedFsConfig(ctx android.ModuleContext) android.OutputPath {
1055 var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
1056 var executablePaths []string // this also includes dirs
1057 var appSetDirs []string
1058 appSetFiles := make(map[string]android.Path)
1059 for _, f := range a.filesInfo {
1060 pathInApex := f.path()
1061 if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
1062 executablePaths = append(executablePaths, pathInApex)
1063 for _, d := range f.dataPaths {
1064 readOnlyPaths = append(readOnlyPaths, filepath.Join(f.installDir, d.RelativeInstallPath, d.SrcPath.Rel()))
1065 }
1066 for _, s := range f.symlinks {
1067 executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
1068 }
1069 } else if f.class == appSet {
1070 appSetDirs = append(appSetDirs, f.installDir)
1071 appSetFiles[f.installDir] = f.builtFile
1072 } else {
1073 readOnlyPaths = append(readOnlyPaths, pathInApex)
1074 }
1075 dir := f.installDir
1076 for !android.InList(dir, executablePaths) && dir != "" {
1077 executablePaths = append(executablePaths, dir)
1078 dir, _ = filepath.Split(dir) // move up to the parent
1079 if len(dir) > 0 {
1080 // remove trailing slash
1081 dir = dir[:len(dir)-1]
1082 }
1083 }
1084 }
1085 sort.Strings(readOnlyPaths)
1086 sort.Strings(executablePaths)
1087 sort.Strings(appSetDirs)
1088
1089 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
1090 builder := android.NewRuleBuilder(pctx, ctx)
1091 cmd := builder.Command()
1092 cmd.Text("(")
1093 cmd.Text("echo '/ 1000 1000 0755';")
1094 for _, p := range readOnlyPaths {
1095 cmd.Textf("echo '/%s 1000 1000 0644';", p)
1096 }
1097 for _, p := range executablePaths {
1098 cmd.Textf("echo '/%s 0 2000 0755';", p)
1099 }
1100 for _, dir := range appSetDirs {
1101 cmd.Textf("echo '/%s 0 2000 0755';", dir)
1102 file := appSetFiles[dir]
1103 cmd.Text("zipinfo -1").Input(file).Textf(`| sed "s:\(.*\):/%s/\1 1000 1000 0644:";`, dir)
1104 }
Jiyong Park038e8522021-12-13 23:56:35 +09001105 // Custom fs_config is "appended" to the last so that entries from the file are preferred
1106 // over default ones set above.
1107 if a.properties.Canned_fs_config != nil {
1108 cmd.Text("cat").Input(android.PathForModuleSrc(ctx, *a.properties.Canned_fs_config))
1109 }
Jiyong Park1b0893e2021-12-13 23:40:17 +09001110 cmd.Text(")").FlagWithOutput("> ", cannedFsConfig)
1111 builder.Build("generateFsConfig", fmt.Sprintf("Generating canned fs config for %s", a.BaseModuleName()))
1112
1113 return cannedFsConfig.OutputPath
1114}