blob: cd7599a027dd5638a48101af866468c5c469a952 [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")
Dennis Shenaf41bc12022-08-03 16:46:43 +000042 pctx.HostBinToolVariable("apexer_with_DCLA_preprocessing", "apexer_with_DCLA_preprocessing")
Dennis Shene2ed70c2023-01-11 14:15:43 +000043 pctx.HostBinToolVariable("apexer_with_trim_preprocessing", "apexer_with_trim_preprocessing")
44
Jiyong Park09d77522019-11-18 11:16:27 +090045 // ART minimal builds (using the master-art manifest) do not have the "frameworks/base"
Jiyong Parkb81b9902020-11-24 19:51:18 +090046 // projects, and hence cannot build 'aapt2'. Use the SDK prebuilt instead.
Jiyong Park09d77522019-11-18 11:16:27 +090047 hostBinToolVariableWithPrebuilt := func(name, prebuiltDir, tool string) {
48 pctx.VariableFunc(name, func(ctx android.PackageVarContext) string {
49 if !ctx.Config().FrameworksBaseDirExists(ctx) {
50 return filepath.Join(prebuiltDir, runtime.GOOS, "bin", tool)
51 } else {
Martin Stjernholm7260d062019-12-09 21:47:14 +000052 return ctx.Config().HostToolPath(ctx, tool).String()
Jiyong Park09d77522019-11-18 11:16:27 +090053 }
54 })
55 }
56 hostBinToolVariableWithPrebuilt("aapt2", "prebuilts/sdk/tools", "aapt2")
57 pctx.HostBinToolVariable("avbtool", "avbtool")
58 pctx.HostBinToolVariable("e2fsdroid", "e2fsdroid")
59 pctx.HostBinToolVariable("merge_zips", "merge_zips")
60 pctx.HostBinToolVariable("mke2fs", "mke2fs")
61 pctx.HostBinToolVariable("resize2fs", "resize2fs")
62 pctx.HostBinToolVariable("sefcontext_compile", "sefcontext_compile")
63 pctx.HostBinToolVariable("soong_zip", "soong_zip")
64 pctx.HostBinToolVariable("zip2zip", "zip2zip")
65 pctx.HostBinToolVariable("zipalign", "zipalign")
66 pctx.HostBinToolVariable("jsonmodify", "jsonmodify")
67 pctx.HostBinToolVariable("conv_apex_manifest", "conv_apex_manifest")
Jaewoong Jungfa00c062020-05-14 14:15:24 -070068 pctx.HostBinToolVariable("extract_apks", "extract_apks")
Theotime Combes4ba38c12020-06-12 12:46:59 +000069 pctx.HostBinToolVariable("make_f2fs", "make_f2fs")
70 pctx.HostBinToolVariable("sload_f2fs", "sload_f2fs")
Huang Jianan13cac632021-08-02 15:02:17 +080071 pctx.HostBinToolVariable("make_erofs", "make_erofs")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +000072 pctx.HostBinToolVariable("apex_compression_tool", "apex_compression_tool")
sophiez02347372021-11-02 17:58:02 -070073 pctx.HostBinToolVariable("dexdeps", "dexdeps")
Jooyung Han01f5d652023-04-05 16:29:26 +090074 pctx.HostBinToolVariable("apex_sepolicy_tests", "apex_sepolicy_tests")
75 pctx.HostBinToolVariable("deapexer", "deapexer")
76 pctx.HostBinToolVariable("debugfs_static", "debugfs_static")
sophiezc80a2b32020-11-12 16:39:19 +000077 pctx.SourcePathVariable("genNdkUsedbyApexPath", "build/soong/scripts/gen_ndk_usedby_apex.sh")
Jooyung Han4bc10262023-09-08 11:51:45 +090078 pctx.HostBinToolVariable("conv_linker_config", "conv_linker_config")
Jiyong Park09d77522019-11-18 11:16:27 +090079}
80
81var (
Jiyong Park09d77522019-11-18 11:16:27 +090082 apexManifestRule = pctx.StaticRule("apexManifestRule", blueprint.RuleParams{
83 Command: `rm -f $out && ${jsonmodify} $in ` +
84 `-a provideNativeLibs ${provideNativeLibs} ` +
85 `-a requireNativeLibs ${requireNativeLibs} ` +
Alexei Nicoarad887e242022-07-11 14:16:28 +010086 `-se version 0 ${default_version} ` +
Jiyong Park09d77522019-11-18 11:16:27 +090087 `${opt} ` +
88 `-o $out`,
89 CommandDeps: []string{"${jsonmodify}"},
90 Description: "prepare ${out}",
Alexei Nicoarad887e242022-07-11 14:16:28 +010091 }, "provideNativeLibs", "requireNativeLibs", "default_version", "opt")
Jiyong Park09d77522019-11-18 11:16:27 +090092
93 stripApexManifestRule = pctx.StaticRule("stripApexManifestRule", blueprint.RuleParams{
94 Command: `rm -f $out && ${conv_apex_manifest} strip $in -o $out`,
95 CommandDeps: []string{"${conv_apex_manifest}"},
96 Description: "strip ${in}=>${out}",
97 })
98
99 pbApexManifestRule = pctx.StaticRule("pbApexManifestRule", blueprint.RuleParams{
100 Command: `rm -f $out && ${conv_apex_manifest} proto $in -o $out`,
101 CommandDeps: []string{"${conv_apex_manifest}"},
102 Description: "convert ${in}=>${out}",
103 })
104
Joe Onoratob4638c12021-10-27 15:47:06 -0700105 // TODO(b/113233103): make sure that file_contexts is as expected, i.e., validate
Jiyong Park09d77522019-11-18 11:16:27 +0900106 // against the binary policy using sefcontext_compiler -p <policy>.
107
108 // TODO(b/114327326): automate the generation of file_contexts
109 apexRule = pctx.StaticRule("apexRule", blueprint.RuleParams{
110 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
111 `(. ${out}.copy_commands) && ` +
112 `APEXER_TOOL_PATH=${tool_path} ` +
113 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900114 `--file_contexts ${file_contexts} ` +
115 `--canned_fs_config ${canned_fs_config} ` +
Dario Freni0f4ae072020-01-02 15:24:12 +0000116 `--include_build_info ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900117 `--payload_type image ` +
Oriol Prieto Gasco17e22902022-05-05 13:52:25 +0000118 `--key ${key} ${opt_flags} ${image_dir} ${out} `,
Jiyong Park09d77522019-11-18 11:16:27 +0900119 CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
Huang Jianan13cac632021-08-02 15:02:17 +0800120 "${mke2fs}", "${resize2fs}", "${sefcontext_compile}", "${make_f2fs}", "${sload_f2fs}", "${make_erofs}",
Jiyong Park09d77522019-11-18 11:16:27 +0900121 "${soong_zip}", "${zipalign}", "${aapt2}", "prebuilts/sdk/current/public/android.jar"},
122 Rspfile: "${out}.copy_commands",
123 RspfileContent: "${copy_commands}",
124 Description: "APEX ${image_dir} => ${out}",
Dennis Shenaf41bc12022-08-03 16:46:43 +0000125 }, "tool_path", "image_dir", "copy_commands", "file_contexts", "canned_fs_config", "key",
126 "opt_flags", "manifest")
127
128 DCLAApexRule = pctx.StaticRule("DCLAApexRule", blueprint.RuleParams{
129 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
130 `(. ${out}.copy_commands) && ` +
131 `APEXER_TOOL_PATH=${tool_path} ` +
132 `${apexer_with_DCLA_preprocessing} ` +
133 `--apexer ${apexer} ` +
134 `--canned_fs_config ${canned_fs_config} ` +
135 `${image_dir} ` +
136 `${out} ` +
137 `-- ` +
138 `--include_build_info ` +
139 `--force ` +
140 `--payload_type image ` +
141 `--key ${key} ` +
142 `--file_contexts ${file_contexts} ` +
143 `--manifest ${manifest} ` +
144 `${opt_flags} `,
145 CommandDeps: []string{"${apexer_with_DCLA_preprocessing}", "${apexer}", "${avbtool}", "${e2fsdroid}",
146 "${merge_zips}", "${mke2fs}", "${resize2fs}", "${sefcontext_compile}", "${make_f2fs}",
147 "${sload_f2fs}", "${make_erofs}", "${soong_zip}", "${zipalign}", "${aapt2}",
148 "prebuilts/sdk/current/public/android.jar"},
149 Rspfile: "${out}.copy_commands",
150 RspfileContent: "${copy_commands}",
151 Description: "APEX ${image_dir} => ${out}",
152 }, "tool_path", "image_dir", "copy_commands", "file_contexts", "canned_fs_config", "key",
153 "opt_flags", "manifest", "is_DCLA")
Jiyong Park09d77522019-11-18 11:16:27 +0900154
Dennis Shene2ed70c2023-01-11 14:15:43 +0000155 TrimmedApexRule = pctx.StaticRule("TrimmedApexRule", blueprint.RuleParams{
156 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
157 `(. ${out}.copy_commands) && ` +
158 `APEXER_TOOL_PATH=${tool_path} ` +
159 `${apexer_with_trim_preprocessing} ` +
160 `--apexer ${apexer} ` +
161 `--canned_fs_config ${canned_fs_config} ` +
162 `--manifest ${manifest} ` +
163 `--libs_to_trim ${libs_to_trim} ` +
164 `${image_dir} ` +
165 `${out} ` +
166 `-- ` +
167 `--include_build_info ` +
168 `--force ` +
169 `--payload_type image ` +
170 `--key ${key} ` +
171 `--file_contexts ${file_contexts} ` +
172 `${opt_flags} `,
173 CommandDeps: []string{"${apexer_with_trim_preprocessing}", "${apexer}", "${avbtool}", "${e2fsdroid}",
174 "${merge_zips}", "${mke2fs}", "${resize2fs}", "${sefcontext_compile}", "${make_f2fs}",
175 "${sload_f2fs}", "${make_erofs}", "${soong_zip}", "${zipalign}", "${aapt2}",
176 "prebuilts/sdk/current/public/android.jar"},
177 Rspfile: "${out}.copy_commands",
178 RspfileContent: "${copy_commands}",
179 Description: "APEX ${image_dir} => ${out}",
180 }, "tool_path", "image_dir", "copy_commands", "file_contexts", "canned_fs_config", "key",
181 "opt_flags", "manifest", "libs_to_trim")
182
Jiyong Park09d77522019-11-18 11:16:27 +0900183 apexProtoConvertRule = pctx.AndroidStaticRule("apexProtoConvertRule",
184 blueprint.RuleParams{
185 Command: `${aapt2} convert --output-format proto $in -o $out`,
186 CommandDeps: []string{"${aapt2}"},
187 })
188
189 apexBundleRule = pctx.StaticRule("apexBundleRule", blueprint.RuleParams{
Jiyong Parkbd159612020-02-28 15:22:21 +0900190 Command: `${zip2zip} -i $in -o $out.base ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900191 `apex_payload.img:apex/${abi}.img ` +
Dario Frenida1aefe2020-03-02 21:47:09 +0000192 `apex_build_info.pb:apex/${abi}.build_info.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900193 `apex_manifest.json:root/apex_manifest.json ` +
Jiyong Park53ae3342019-12-08 02:06:24 +0900194 `apex_manifest.pb:root/apex_manifest.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900195 `AndroidManifest.xml:manifest/AndroidManifest.xml ` +
Jiyong Parkbd159612020-02-28 15:22:21 +0900196 `assets/NOTICE.html.gz:assets/NOTICE.html.gz &&` +
197 `${soong_zip} -o $out.config -C $$(dirname ${config}) -f ${config} && ` +
198 `${merge_zips} $out $out.base $out.config`,
199 CommandDeps: []string{"${zip2zip}", "${soong_zip}", "${merge_zips}"},
Jiyong Park09d77522019-11-18 11:16:27 +0900200 Description: "app bundle",
Jiyong Parkbd159612020-02-28 15:22:21 +0900201 }, "abi", "config")
Jiyong Park09d77522019-11-18 11:16:27 +0900202
Jiyong Park09d77522019-11-18 11:16:27 +0900203 diffApexContentRule = pctx.StaticRule("diffApexContentRule", blueprint.RuleParams{
204 Command: `diff --unchanged-group-format='' \` +
205 `--changed-group-format='%<' \` +
Colin Cross440e0d02020-06-11 11:32:11 -0700206 `${image_content_file} ${allowed_files_file} || (` +
Jiyong Park09d77522019-11-18 11:16:27 +0900207 `echo -e "New unexpected files were added to ${apex_module_name}." ` +
208 ` "To fix the build run following command:" && ` +
Colin Cross440e0d02020-06-11 11:32:11 -0700209 `echo "system/apex/tools/update_allowed_list.sh ${allowed_files_file} ${image_content_file}" && ` +
Dan Willemsen81e43c52020-01-28 15:40:19 -0800210 `exit 1); touch ${out}`,
Colin Cross440e0d02020-06-11 11:32:11 -0700211 Description: "Diff ${image_content_file} and ${allowed_files_file}",
212 }, "image_content_file", "allowed_files_file", "apex_module_name")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900213
sophiezc80a2b32020-11-12 16:39:19 +0000214 generateAPIsUsedbyApexRule = pctx.StaticRule("generateAPIsUsedbyApexRule", blueprint.RuleParams{
215 Command: "$genNdkUsedbyApexPath ${image_dir} ${readelf} ${out}",
216 CommandDeps: []string{"${genNdkUsedbyApexPath}"},
217 Description: "Generate symbol list used by Apex",
218 }, "image_dir", "readelf")
219
Jooyung Han01f5d652023-04-05 16:29:26 +0900220 apexSepolicyTestsRule = pctx.StaticRule("apexSepolicyTestsRule", blueprint.RuleParams{
221 Command: `${deapexer} --debugfs_path ${debugfs_static} list -Z ${in} > ${out}.fc` +
Jooyung Hanb7cdbba2023-04-26 14:42:50 +0900222 ` && ${apex_sepolicy_tests} -f ${out}.fc && touch ${out}`,
Jooyung Han01f5d652023-04-05 16:29:26 +0900223 CommandDeps: []string{"${apex_sepolicy_tests}", "${deapexer}", "${debugfs_static}"},
224 Description: "run apex_sepolicy_tests",
225 })
Jooyung Han4bc10262023-09-08 11:51:45 +0900226
227 apexLinkerconfigValidationRule = pctx.StaticRule("apexLinkerconfigValidationRule", blueprint.RuleParams{
228 Command: `${conv_linker_config} validate --type apex ${image_dir} && touch ${out}`,
229 CommandDeps: []string{"${conv_linker_config}"},
230 Description: "run apex_linkerconfig_validation",
231 }, "image_dir")
Jiyong Park09d77522019-11-18 11:16:27 +0900232)
233
Jiyong Parkb81b9902020-11-24 19:51:18 +0900234// buildManifest creates buile rules to modify the input apex_manifest.json to add information
235// gathered by the build system such as provided/required native libraries. Two output files having
236// different formats are generated. a.manifestJsonOut is JSON format for Q devices, and
237// a.manifest.PbOut is protobuf format for R+ devices.
238// TODO(jiyong): make this to return paths instead of directly storing the paths to apexBundle
Jiyong Park09d77522019-11-18 11:16:27 +0900239func (a *apexBundle) buildManifest(ctx android.ModuleContext, provideNativeLibs, requireNativeLibs []string) {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900240 src := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
Jiyong Park09d77522019-11-18 11:16:27 +0900241
Jiyong Parkb81b9902020-11-24 19:51:18 +0900242 // Put dependency({provide|require}NativeLibs) in apex_manifest.json
Jiyong Park09d77522019-11-18 11:16:27 +0900243 provideNativeLibs = android.SortedUniqueStrings(provideNativeLibs)
244 requireNativeLibs = android.SortedUniqueStrings(android.RemoveListFromList(requireNativeLibs, provideNativeLibs))
245
Jooyung Han2cd2f9a2023-02-06 18:29:08 +0900246 // VNDK APEX name is determined at runtime, so update "name" in apex_manifest
Jiyong Park09d77522019-11-18 11:16:27 +0900247 optCommands := []string{}
Jooyung Han2cd2f9a2023-02-06 18:29:08 +0900248 if a.vndkApex {
249 apexName := vndkApexNamePrefix + a.vndkVersion(ctx.DeviceConfig())
250 optCommands = append(optCommands, "-v name "+apexName)
Jiyong Park09d77522019-11-18 11:16:27 +0900251 }
252
Jiyong Parkb81b9902020-11-24 19:51:18 +0900253 // Collect jniLibs. Notice that a.filesInfo is already sorted
Jooyung Han643adc42020-02-27 13:50:06 +0900254 var jniLibs []string
255 for _, fi := range a.filesInfo {
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900256 if fi.isJniLib && !android.InList(fi.stem(), jniLibs) {
257 jniLibs = append(jniLibs, fi.stem())
Jooyung Han643adc42020-02-27 13:50:06 +0900258 }
259 }
260 if len(jniLibs) > 0 {
261 optCommands = append(optCommands, "-a jniLibs "+strings.Join(jniLibs, " "))
262 }
263
Jooyung Hand045ebc2022-12-06 15:23:57 +0900264 if android.InList(":vndk", requireNativeLibs) {
265 if _, vndkVersion := a.getImageVariationPair(ctx.DeviceConfig()); vndkVersion != "" {
266 optCommands = append(optCommands, "-v vndkVersion "+vndkVersion)
267 }
268 }
269
Jiyong Parkb81b9902020-11-24 19:51:18 +0900270 manifestJsonFullOut := android.PathForModuleOut(ctx, "apex_manifest_full.json")
Sahana Rao16ebdfd2022-12-02 17:00:22 +0000271 defaultVersion := android.DefaultUpdatableModuleVersion
Sam Delmerico6d65a0f2023-06-05 15:55:57 -0400272 if a.properties.Variant_version != nil {
273 defaultVersionInt, err := strconv.Atoi(defaultVersion)
274 if err != nil {
275 ctx.ModuleErrorf("expected DefaultUpdatableModuleVersion to be an int, but got %s", defaultVersion)
276 }
277 if defaultVersionInt%10 != 0 {
278 ctx.ModuleErrorf("expected DefaultUpdatableModuleVersion to end in a zero, but got %s", defaultVersion)
279 }
280 variantVersion := []rune(*a.properties.Variant_version)
281 if len(variantVersion) != 1 || variantVersion[0] < '0' || variantVersion[0] > '9' {
282 ctx.PropertyErrorf("variant_version", "expected an integer between 0-9; got %s", *a.properties.Variant_version)
283 }
284 defaultVersionRunes := []rune(defaultVersion)
285 defaultVersionRunes[len(defaultVersion)-1] = []rune(variantVersion)[0]
286 defaultVersion = string(defaultVersionRunes)
287 }
Sahana Rao16ebdfd2022-12-02 17:00:22 +0000288 if override := ctx.Config().Getenv("OVERRIDE_APEX_MANIFEST_DEFAULT_VERSION"); override != "" {
289 defaultVersion = override
290 }
Jiyong Park09d77522019-11-18 11:16:27 +0900291 ctx.Build(pctx, android.BuildParams{
292 Rule: apexManifestRule,
Alexei Nicoara0a389202022-07-12 14:35:39 +0100293 Input: src,
Jooyung Han214bf372019-11-12 13:03:50 +0900294 Output: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900295 Args: map[string]string{
296 "provideNativeLibs": strings.Join(provideNativeLibs, " "),
297 "requireNativeLibs": strings.Join(requireNativeLibs, " "),
Sahana Rao16ebdfd2022-12-02 17:00:22 +0000298 "default_version": defaultVersion,
Jiyong Park09d77522019-11-18 11:16:27 +0900299 "opt": strings.Join(optCommands, " "),
300 },
301 })
302
Jiyong Parkb81b9902020-11-24 19:51:18 +0900303 // b/143654022 Q apexd can't understand newly added keys in apex_manifest.json prepare
304 // stripped-down version so that APEX modules built from R+ can be installed to Q
Dan Albertc8060532020-07-22 22:32:17 -0700305 minSdkVersion := a.minSdkVersion(ctx)
306 if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
Jooyung Han214bf372019-11-12 13:03:50 +0900307 a.manifestJsonOut = android.PathForModuleOut(ctx, "apex_manifest.json")
308 ctx.Build(pctx, android.BuildParams{
309 Rule: stripApexManifestRule,
310 Input: manifestJsonFullOut,
311 Output: a.manifestJsonOut,
312 })
313 }
Jiyong Park09d77522019-11-18 11:16:27 +0900314
Jiyong Parkb81b9902020-11-24 19:51:18 +0900315 // From R+, protobuf binary format (.pb) is the standard format for apex_manifest
Jiyong Park09d77522019-11-18 11:16:27 +0900316 a.manifestPbOut = android.PathForModuleOut(ctx, "apex_manifest.pb")
317 ctx.Build(pctx, android.BuildParams{
318 Rule: pbApexManifestRule,
Jooyung Han214bf372019-11-12 13:03:50 +0900319 Input: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900320 Output: a.manifestPbOut,
321 })
322}
323
Jiyong Parkb81b9902020-11-24 19:51:18 +0900324// buildFileContexts create build rules to append an entry for apex_manifest.pb to the file_contexts
325// file for this APEX which is either from /systme/sepolicy/apex/<apexname>-file_contexts or from
326// the file_contexts property of this APEX. This is to make sure that the manifest file is correctly
Jooyung Hanbe953902023-05-31 16:42:16 +0900327// labeled as system_file or vendor_apex_metadata_file.
Jiyong Parkb81b9902020-11-24 19:51:18 +0900328func (a *apexBundle) buildFileContexts(ctx android.ModuleContext) android.OutputPath {
Jooyung Han580eb4f2020-06-24 19:33:06 +0900329 var fileContexts android.Path
Liz Kammer37997c42021-09-14 17:53:38 -0400330 var fileContextsDir string
Jooyung Han580eb4f2020-06-24 19:33:06 +0900331 if a.properties.File_contexts == nil {
332 fileContexts = android.PathForSource(ctx, "system/sepolicy/apex", ctx.ModuleName()+"-file_contexts")
333 } else {
Liz Kammer37997c42021-09-14 17:53:38 -0400334 if m, t := android.SrcIsModuleWithTag(*a.properties.File_contexts); m != "" {
335 otherModule := android.GetModuleFromPathDep(ctx, m, t)
336 fileContextsDir = ctx.OtherModuleDir(otherModule)
337 }
Jooyung Han580eb4f2020-06-24 19:33:06 +0900338 fileContexts = android.PathForModuleSrc(ctx, *a.properties.File_contexts)
339 }
Liz Kammer37997c42021-09-14 17:53:38 -0400340 if fileContextsDir == "" {
341 fileContextsDir = filepath.Dir(fileContexts.String())
342 }
343 fileContextsDir += string(filepath.Separator)
344
Jooyung Han580eb4f2020-06-24 19:33:06 +0900345 if a.Platform() {
Liz Kammer37997c42021-09-14 17:53:38 -0400346 if !strings.HasPrefix(fileContextsDir, "system/sepolicy/") {
347 ctx.PropertyErrorf("file_contexts", "should be under system/sepolicy, but found in %q", fileContextsDir)
Jooyung Han580eb4f2020-06-24 19:33:06 +0900348 }
349 }
350 if !android.ExistentPathForSource(ctx, fileContexts.String()).Valid() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900351 ctx.PropertyErrorf("file_contexts", "cannot find file_contexts file: %q", fileContexts.String())
Jooyung Han580eb4f2020-06-24 19:33:06 +0900352 }
353
Jooyung Hanaf730952023-02-28 14:13:38 +0900354 useFileContextsAsIs := proptools.Bool(a.properties.Use_file_contexts_as_is)
355
Jooyung Han580eb4f2020-06-24 19:33:06 +0900356 output := android.PathForModuleOut(ctx, "file_contexts")
Colin Crossf1a035e2020-11-16 17:32:30 -0800357 rule := android.NewRuleBuilder(pctx, ctx)
Jooyung Han7f146c02020-09-23 19:15:55 +0900358
Jooyung Hanbe953902023-05-31 16:42:16 +0900359 forceLabel := "u:object_r:system_file:s0"
360 if a.SocSpecific() && !a.vndkApex {
361 // APEX on /vendor should label ./ and ./apex_manifest.pb as vendor_apex_metadata_file.
362 // The reason why we skip VNDK APEX is that aosp_{pixel device} targets install VNDK APEX on /vendor
363 // even though VNDK APEX is supposed to be installed on /system. (See com.android.vndk.current.on_vendor)
364 forceLabel = "u:object_r:vendor_apex_metadata_file:s0"
365 }
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900366 // remove old file
367 rule.Command().Text("rm").FlagWithOutput("-f ", output)
368 // copy file_contexts
369 rule.Command().Text("cat").Input(fileContexts).Text(">>").Output(output)
370 // new line
371 rule.Command().Text("echo").Text(">>").Output(output)
372 if !useFileContextsAsIs {
373 // force-label /apex_manifest.pb and /
374 rule.Command().Text("echo").Text("/apex_manifest\\\\.pb").Text(forceLabel).Text(">>").Output(output)
375 rule.Command().Text("echo").Text("/").Text(forceLabel).Text(">>").Output(output)
Jooyung Han7f146c02020-09-23 19:15:55 +0900376 }
377
Colin Crossf1a035e2020-11-16 17:32:30 -0800378 rule.Build("file_contexts."+a.Name(), "Generate file_contexts")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900379 return output.OutputPath
Jooyung Han580eb4f2020-06-24 19:33:06 +0900380}
381
Jiyong Parkb81b9902020-11-24 19:51:18 +0900382// buildInstalledFilesFile creates a build rule for the installed-files.txt file where the list of
383// files included in this APEX is shown. The text file is dist'ed so that people can see what's
384// included in the APEX without actually downloading and extracting it.
Jiyong Park3a1602e2020-01-14 14:39:19 +0900385func (a *apexBundle) buildInstalledFilesFile(ctx android.ModuleContext, builtApex android.Path, imageDir android.Path) android.OutputPath {
386 output := android.PathForModuleOut(ctx, "installed-files.txt")
Colin Crossf1a035e2020-11-16 17:32:30 -0800387 rule := android.NewRuleBuilder(pctx, ctx)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900388 rule.Command().
389 Implicit(builtApex).
390 Text("(cd " + imageDir.String() + " ; ").
Jiyong Parkbd63a102020-02-08 12:40:05 +0900391 Text("find . \\( -type f -o -type l \\) -printf \"%s %p\\n\") ").
Jiyong Park3a1602e2020-01-14 14:39:19 +0900392 Text(" | sort -nr > ").
393 Output(output)
Colin Crossf1a035e2020-11-16 17:32:30 -0800394 rule.Build("installed-files."+a.Name(), "Installed files")
Jiyong Park3a1602e2020-01-14 14:39:19 +0900395 return output.OutputPath
396}
397
Jiyong Parkb81b9902020-11-24 19:51:18 +0900398// buildBundleConfig creates a build rule for the bundle config file that will control the bundle
399// creation process.
Jiyong Parkbd159612020-02-28 15:22:21 +0900400func (a *apexBundle) buildBundleConfig(ctx android.ModuleContext) android.OutputPath {
401 output := android.PathForModuleOut(ctx, "bundle_config.json")
402
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900403 type ApkConfig struct {
404 Package_name string `json:"package_name"`
405 Apk_path string `json:"path"`
406 }
Jiyong Parkbd159612020-02-28 15:22:21 +0900407 config := struct {
408 Compression struct {
409 Uncompressed_glob []string `json:"uncompressed_glob"`
410 } `json:"compression"`
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900411 Apex_config struct {
412 Apex_embedded_apk_config []ApkConfig `json:"apex_embedded_apk_config,omitempty"`
413 } `json:"apex_config,omitempty"`
Jiyong Parkbd159612020-02-28 15:22:21 +0900414 }{}
415
416 config.Compression.Uncompressed_glob = []string{
417 "apex_payload.img",
418 "apex_manifest.*",
419 }
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900420
Jiyong Parkb81b9902020-11-24 19:51:18 +0900421 // Collect the manifest names and paths of android apps if their manifest names are
422 // overridden.
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900423 for _, fi := range a.filesInfo {
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700424 if fi.class != app && fi.class != appSet {
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900425 continue
426 }
427 packageName := fi.overriddenPackageName
428 if packageName != "" {
429 config.Apex_config.Apex_embedded_apk_config = append(
430 config.Apex_config.Apex_embedded_apk_config,
431 ApkConfig{
432 Package_name: packageName,
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900433 Apk_path: fi.path(),
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900434 })
435 }
436 }
437
Jiyong Parkbd159612020-02-28 15:22:21 +0900438 j, err := json.Marshal(config)
439 if err != nil {
440 panic(fmt.Errorf("error while marshalling to %q: %#v", output, err))
441 }
442
Colin Crosscf371cc2020-11-13 11:48:42 -0800443 android.WriteFileRule(ctx, output, string(j))
Jiyong Parkbd159612020-02-28 15:22:21 +0900444
445 return output.OutputPath
446}
447
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000448func markManifestTestOnly(ctx android.ModuleContext, androidManifestFile android.Path) android.Path {
Gurpreet Singh7deabfa2022-02-10 13:28:35 +0000449 return java.ManifestFixer(ctx, androidManifestFile, java.ManifestFixerParams{
450 TestOnly: true,
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000451 })
452}
453
Jooyung Haneec1b3f2023-06-20 16:25:59 +0900454// buildApex creates build rules to build an APEX using apexer.
455func (a *apexBundle) buildApex(ctx android.ModuleContext) {
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900456 suffix := imageApexSuffix
Jooyung Han63dff462023-02-09 00:11:27 +0000457 apexName := a.BaseModuleName()
Jiyong Park09d77522019-11-18 11:16:27 +0900458
Jiyong Parkb81b9902020-11-24 19:51:18 +0900459 ////////////////////////////////////////////////////////////////////////////////////////////
460 // Step 1: copy built files to appropriate directories under the image directory
461
462 imageDir := android.PathForModuleOut(ctx, "image"+suffix)
463
Colin Cross02730b92022-04-18 17:42:27 -0700464 installSymbolFiles := (!ctx.Config().KatiEnabled() || a.ExportedToMake()) && a.installable()
Colin Cross6340ea52021-11-04 12:01:18 -0700465
Colin Cross4acaea92021-12-10 23:05:02 +0000466 // set of dependency module:location mappings
467 installMapSet := make(map[string]bool)
Colin Cross6340ea52021-11-04 12:01:18 -0700468
Jiyong Parkb81b9902020-11-24 19:51:18 +0900469 // TODO(jiyong): use the RuleBuilder
Jiyong Park7cd10e32020-01-14 09:22:18 +0900470 var copyCommands []string
Jiyong Parkb81b9902020-11-24 19:51:18 +0900471 var implicitInputs []android.Path
Jooyung Han63dff462023-02-09 00:11:27 +0000472 apexDir := android.PathForModuleInPartitionInstall(ctx, "apex", apexName)
Jiyong Park7cd10e32020-01-14 09:22:18 +0900473 for _, fi := range a.filesInfo {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900474 destPath := imageDir.Join(ctx, fi.path()).String()
Jiyong Parkb81b9902020-11-24 19:51:18 +0900475 // Prepare the destination path
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700476 destPathDir := filepath.Dir(destPath)
477 if fi.class == appSet {
478 copyCommands = append(copyCommands, "rm -rf "+destPathDir)
479 }
480 copyCommands = append(copyCommands, "mkdir -p "+destPathDir)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900481
Colin Cross4acaea92021-12-10 23:05:02 +0000482 installMapPath := fi.builtFile
483
Jiyong Parkb81b9902020-11-24 19:51:18 +0900484 // Copy the built file to the directory. But if the symlink optimization is turned
485 // on, place a symlink to the corresponding file in /system partition instead.
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900486 if a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform() {
Jiyong Parkce243632023-02-17 18:22:25 +0900487 pathOnDevice := filepath.Join("/", fi.partition, fi.path())
Jiyong Park7cd10e32020-01-14 09:22:18 +0900488 copyCommands = append(copyCommands, "ln -sfn "+pathOnDevice+" "+destPath)
489 } else {
Jiyong Park4169a252022-09-29 21:30:25 +0900490 // Copy the file into APEX
491 copyCommands = append(copyCommands, "cp -f "+fi.builtFile.String()+" "+destPath)
492
Colin Cross4acaea92021-12-10 23:05:02 +0000493 var installedPath android.InstallPath
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700494 if fi.class == appSet {
Jiyong Park4169a252022-09-29 21:30:25 +0900495 // In case of AppSet, we need to copy additional APKs as well. They
496 // are zipped. So we need to unzip them.
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700497 copyCommands = append(copyCommands,
Colin Crossffbcd1d2021-11-12 12:19:42 -0800498 fmt.Sprintf("unzip -qDD -d %s %s", destPathDir,
499 fi.module.(*java.AndroidAppSet).PackedAdditionalOutputs().String()))
Colin Cross6340ea52021-11-04 12:01:18 -0700500 if installSymbolFiles {
Jooyung Han63dff462023-02-09 00:11:27 +0000501 installedPath = ctx.InstallFileWithExtraFilesZip(apexDir.Join(ctx, fi.installDir),
Colin Cross6340ea52021-11-04 12:01:18 -0700502 fi.stem(), fi.builtFile, fi.module.(*java.AndroidAppSet).PackedAdditionalOutputs())
503 }
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700504 } else {
Colin Cross6340ea52021-11-04 12:01:18 -0700505 if installSymbolFiles {
Jooyung Han63dff462023-02-09 00:11:27 +0000506 installedPath = ctx.InstallFile(apexDir.Join(ctx, fi.installDir), fi.stem(), fi.builtFile)
Colin Cross6340ea52021-11-04 12:01:18 -0700507 }
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700508 }
Jiyong Park7cd10e32020-01-14 09:22:18 +0900509 implicitInputs = append(implicitInputs, fi.builtFile)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900510
Colin Cross4acaea92021-12-10 23:05:02 +0000511 // Create additional symlinks pointing the file inside the APEX (if any). Note that
512 // this is independent from the symlink optimization.
513 for _, symlinkPath := range fi.symlinkPaths() {
514 symlinkDest := imageDir.Join(ctx, symlinkPath).String()
515 copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
516 if installSymbolFiles {
Inseob Kim5bedfee2023-04-20 10:16:14 +0900517 ctx.InstallSymlink(apexDir.Join(ctx, filepath.Dir(symlinkPath)), filepath.Base(symlinkPath), installedPath)
Colin Cross4acaea92021-12-10 23:05:02 +0000518 }
Colin Cross6340ea52021-11-04 12:01:18 -0700519 }
Colin Cross4acaea92021-12-10 23:05:02 +0000520
521 installMapPath = installedPath
Jiyong Park7cd10e32020-01-14 09:22:18 +0900522 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900523
524 // Copy the test files (if any)
Liz Kammer1c14a212020-05-12 15:26:55 -0700525 for _, d := range fi.dataPaths {
526 // 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 -0400527 relPath := d.SrcPath.Rel()
528 dataPath := d.SrcPath.String()
Liz Kammer1c14a212020-05-12 15:26:55 -0700529 if !strings.HasSuffix(dataPath, relPath) {
530 panic(fmt.Errorf("path %q does not end with %q", dataPath, relPath))
531 }
532
Jiyong Parkb81b9902020-11-24 19:51:18 +0900533 dataDest := imageDir.Join(ctx, fi.apexRelativePath(relPath), d.RelativeInstallPath).String()
Liz Kammer1c14a212020-05-12 15:26:55 -0700534
Chris Parsons216e10a2020-07-09 17:12:52 -0400535 copyCommands = append(copyCommands, "cp -f "+d.SrcPath.String()+" "+dataDest)
536 implicitInputs = append(implicitInputs, d.SrcPath)
Liz Kammer1c14a212020-05-12 15:26:55 -0700537 }
Colin Cross4acaea92021-12-10 23:05:02 +0000538
539 installMapSet[installMapPath.String()+":"+fi.installDir+"/"+fi.builtFile.Base()] = true
Jiyong Park09d77522019-11-18 11:16:27 +0900540 }
Jooyung Han214bf372019-11-12 13:03:50 +0900541 implicitInputs = append(implicitInputs, a.manifestPbOut)
Jiyong Park09d77522019-11-18 11:16:27 +0900542
Colin Cross4acaea92021-12-10 23:05:02 +0000543 if len(installMapSet) > 0 {
544 var installs []string
Cole Faust18994c72023-02-28 16:02:16 -0800545 installs = append(installs, android.SortedKeys(installMapSet)...)
Colin Cross4acaea92021-12-10 23:05:02 +0000546 a.SetLicenseInstallMap(installs)
547 }
548
Jiyong Parkb81b9902020-11-24 19:51:18 +0900549 ////////////////////////////////////////////////////////////////////////////////////////////
550 // Step 1.a: Write the list of files in this APEX to a txt file and compare it against
551 // the allowed list given via the allowed_files property. Build fails when the two lists
552 // differ.
553 //
554 // TODO(jiyong): consider removing this. Nobody other than com.android.apex.cts.shim.* seems
555 // to be using this at this moment. Furthermore, this looks very similar to what
556 // buildInstalledFilesFile does. At least, move this to somewhere else so that this doesn't
557 // hurt readability.
Jooyung Han938b5932020-06-20 12:47:47 +0900558 if a.overridableProperties.Allowed_files != nil {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900559 // Build content.txt
Cole Fausta7347492022-12-16 10:56:24 -0800560 var contentLines []string
Jiyong Parkb81b9902020-11-24 19:51:18 +0900561 imageContentFile := android.PathForModuleOut(ctx, "content.txt")
Cole Fausta7347492022-12-16 10:56:24 -0800562 contentLines = append(contentLines, "./apex_manifest.pb")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900563 minSdkVersion := a.minSdkVersion(ctx)
564 if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
Cole Fausta7347492022-12-16 10:56:24 -0800565 contentLines = append(contentLines, "./apex_manifest.json")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900566 }
567 for _, fi := range a.filesInfo {
Cole Fausta7347492022-12-16 10:56:24 -0800568 contentLines = append(contentLines, "./"+fi.path())
Jiyong Parkb81b9902020-11-24 19:51:18 +0900569 }
Cole Fausta7347492022-12-16 10:56:24 -0800570 sort.Strings(contentLines)
571 android.WriteFileRule(ctx, imageContentFile, strings.Join(contentLines, "\n"))
Jiyong Park09d77522019-11-18 11:16:27 +0900572 implicitInputs = append(implicitInputs, imageContentFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900573
Jiyong Parkb81b9902020-11-24 19:51:18 +0900574 // Compare content.txt against allowed_files.
575 allowedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.overridableProperties.Allowed_files))
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800576 phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
Jiyong Park09d77522019-11-18 11:16:27 +0900577 ctx.Build(pctx, android.BuildParams{
578 Rule: diffApexContentRule,
579 Implicits: implicitInputs,
580 Output: phonyOutput,
581 Description: "diff apex image content",
582 Args: map[string]string{
Colin Cross440e0d02020-06-11 11:32:11 -0700583 "allowed_files_file": allowedFilesFile.String(),
584 "image_content_file": imageContentFile.String(),
585 "apex_module_name": a.Name(),
Jiyong Park09d77522019-11-18 11:16:27 +0900586 },
587 })
Jiyong Park09d77522019-11-18 11:16:27 +0900588 implicitInputs = append(implicitInputs, phonyOutput)
589 }
590
Jiyong Parkb81b9902020-11-24 19:51:18 +0900591 unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
Colin Cross790ef352021-10-25 19:15:55 -0700592 outHostBinDir := ctx.Config().HostToolPath(ctx, "").String()
Jiyong Park09d77522019-11-18 11:16:27 +0900593 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
594
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900595 ////////////////////////////////////////////////////////////////////////////////////
596 // Step 2: create canned_fs_config which encodes filemode,uid,gid of each files
597 // in this APEX. The file will be used by apexer in later steps.
598 cannedFsConfig := a.buildCannedFsConfig(ctx)
599 implicitInputs = append(implicitInputs, cannedFsConfig)
Jiyong Park1b0893e2021-12-13 23:40:17 +0900600
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900601 ////////////////////////////////////////////////////////////////////////////////////
602 // Step 3: Prepare option flags for apexer and invoke it to create an unsigned APEX.
603 // TODO(jiyong): use the RuleBuilder
604 optFlags := []string{}
Jiyong Park09d77522019-11-18 11:16:27 +0900605
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900606 fileContexts := a.buildFileContexts(ctx)
607 implicitInputs = append(implicitInputs, fileContexts)
Jiyong Park09d77522019-11-18 11:16:27 +0900608
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900609 implicitInputs = append(implicitInputs, a.privateKeyFile, a.publicKeyFile)
610 optFlags = append(optFlags, "--pubkey "+a.publicKeyFile.String())
Jiyong Parkb81b9902020-11-24 19:51:18 +0900611
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900612 manifestPackageName := a.getOverrideManifestPackageName(ctx)
613 if manifestPackageName != "" {
614 optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
615 }
Jiyong Park09d77522019-11-18 11:16:27 +0900616
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900617 if a.properties.AndroidManifest != nil {
618 androidManifestFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.AndroidManifest))
619
620 if a.testApex {
621 androidManifestFile = markManifestTestOnly(ctx, androidManifestFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900622 }
623
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900624 implicitInputs = append(implicitInputs, androidManifestFile)
625 optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
626 } else if a.testApex {
627 optFlags = append(optFlags, "--test_only")
628 }
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000629
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900630 // Determine target/min sdk version from the context
631 // TODO(jiyong): make this as a function
632 moduleMinSdkVersion := a.minSdkVersion(ctx)
633 minSdkVersion := moduleMinSdkVersion.String()
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000634
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900635 // bundletool doesn't understand what "current" is. We need to transform it to
636 // codename
637 if moduleMinSdkVersion.IsCurrent() || moduleMinSdkVersion.IsNone() {
638 minSdkVersion = ctx.Config().DefaultAppTargetSdk(ctx).String()
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000639
Nikita Ioffe1f4f3452020-03-02 16:58:11 +0000640 if java.UseApiFingerprint(ctx) {
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900641 minSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
Baligh Uddinf6201372020-01-24 23:15:44 +0000642 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
643 }
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900644 }
645 // apex module doesn't have a concept of target_sdk_version, hence for the time
646 // being targetSdkVersion == default targetSdkVersion of the branch.
647 targetSdkVersion := strconv.Itoa(ctx.Config().DefaultAppTargetSdk(ctx).FinalOrFutureInt())
Jiyong Park09d77522019-11-18 11:16:27 +0900648
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900649 if java.UseApiFingerprint(ctx) {
650 targetSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
651 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
652 }
653 optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
654 optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
Baligh Uddin004d7172020-02-19 21:29:28 -0800655
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900656 if a.overridableProperties.Logging_parent != "" {
657 optFlags = append(optFlags, "--logging_parent ", a.overridableProperties.Logging_parent)
658 }
Jiyong Park09d77522019-11-18 11:16:27 +0900659
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900660 // Create a NOTICE file, and embed it as an asset file in the APEX.
661 htmlGzNotice := android.PathForModuleOut(ctx, "NOTICE.html.gz")
662 android.BuildNoticeHtmlOutputFromLicenseMetadata(
663 ctx, htmlGzNotice, "", "",
664 []string{
665 android.PathForModuleInstall(ctx).String() + "/",
666 android.PathForModuleInPartitionInstall(ctx, "apex").String() + "/",
Jiyong Park09d77522019-11-18 11:16:27 +0900667 })
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900668 noticeAssetPath := android.PathForModuleOut(ctx, "NOTICE", "NOTICE.html.gz")
669 builder := android.NewRuleBuilder(pctx, ctx)
670 builder.Command().Text("cp").
671 Input(htmlGzNotice).
672 Output(noticeAssetPath)
673 builder.Build("notice_dir", "Building notice dir")
674 implicitInputs = append(implicitInputs, noticeAssetPath)
675 optFlags = append(optFlags, "--assets_dir "+filepath.Dir(noticeAssetPath.String()))
Jiyong Park09d77522019-11-18 11:16:27 +0900676
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900677 // Apexes which are supposed to be installed in builtin dirs(/system, etc)
678 // don't need hashtree for activation. Therefore, by removing hashtree from
679 // apex bundle (filesystem image in it, to be specific), we can save storage.
680 needHashTree := moduleMinSdkVersion.LessThanOrEqualTo(android.SdkVersion_Android10) ||
681 a.shouldGenerateHashtree()
682 if ctx.Config().ApexCompressionEnabled() && a.isCompressable() {
683 needHashTree = true
684 }
685 if !needHashTree {
686 optFlags = append(optFlags, "--no_hashtree")
687 }
sophiezc80a2b32020-11-12 16:39:19 +0000688
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900689 if a.testOnlyShouldSkipPayloadSign() {
690 optFlags = append(optFlags, "--unsigned_payload")
691 }
692
693 if moduleMinSdkVersion == android.SdkVersion_Android10 {
694 implicitInputs = append(implicitInputs, a.manifestJsonOut)
695 optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
696 }
697
698 optFlags = append(optFlags, "--payload_fs_type "+a.payloadFsType.string())
699
700 if a.dynamic_common_lib_apex() {
sophiezc80a2b32020-11-12 16:39:19 +0000701 ctx.Build(pctx, android.BuildParams{
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900702 Rule: DCLAApexRule,
Jiyong Park09d77522019-11-18 11:16:27 +0900703 Implicits: implicitInputs,
704 Output: unsignedOutputFile,
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900705 Description: "apex",
Jiyong Park09d77522019-11-18 11:16:27 +0900706 Args: map[string]string{
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900707 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
708 "image_dir": imageDir.String(),
709 "copy_commands": strings.Join(copyCommands, " && "),
710 "manifest": a.manifestPbOut.String(),
711 "file_contexts": fileContexts.String(),
712 "canned_fs_config": cannedFsConfig.String(),
713 "key": a.privateKeyFile.String(),
714 "opt_flags": strings.Join(optFlags, " "),
715 },
716 })
717 } else if ctx.Config().ApexTrimEnabled() && len(a.libs_to_trim(ctx)) > 0 {
718 ctx.Build(pctx, android.BuildParams{
719 Rule: TrimmedApexRule,
720 Implicits: implicitInputs,
721 Output: unsignedOutputFile,
722 Description: "apex",
723 Args: map[string]string{
724 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
725 "image_dir": imageDir.String(),
726 "copy_commands": strings.Join(copyCommands, " && "),
727 "manifest": a.manifestPbOut.String(),
728 "file_contexts": fileContexts.String(),
729 "canned_fs_config": cannedFsConfig.String(),
730 "key": a.privateKeyFile.String(),
731 "opt_flags": strings.Join(optFlags, " "),
732 "libs_to_trim": strings.Join(a.libs_to_trim(ctx), ","),
733 },
734 })
735 } else {
736 ctx.Build(pctx, android.BuildParams{
737 Rule: apexRule,
738 Implicits: implicitInputs,
739 Output: unsignedOutputFile,
740 Description: "apex",
741 Args: map[string]string{
742 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
743 "image_dir": imageDir.String(),
744 "copy_commands": strings.Join(copyCommands, " && "),
745 "manifest": a.manifestPbOut.String(),
746 "file_contexts": fileContexts.String(),
747 "canned_fs_config": cannedFsConfig.String(),
748 "key": a.privateKeyFile.String(),
749 "opt_flags": strings.Join(optFlags, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900750 },
751 })
752 }
753
Jooyung Han06a8a1c2023-08-23 11:11:43 +0900754 // TODO(jiyong): make the two rules below as separate functions
755 apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
756 bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
757 a.bundleModuleFile = bundleModuleFile
758
759 ctx.Build(pctx, android.BuildParams{
760 Rule: apexProtoConvertRule,
761 Input: unsignedOutputFile,
762 Output: apexProtoFile,
763 Description: "apex proto convert",
764 })
765
766 implicitInputs = append(implicitInputs, unsignedOutputFile)
767
768 // Run coverage analysis
769 apisUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.txt")
770 ctx.Build(pctx, android.BuildParams{
771 Rule: generateAPIsUsedbyApexRule,
772 Implicits: implicitInputs,
773 Description: "coverage",
774 Output: apisUsedbyOutputFile,
775 Args: map[string]string{
776 "image_dir": imageDir.String(),
777 "readelf": "${config.ClangBin}/llvm-readelf",
778 },
779 })
780 a.nativeApisUsedByModuleFile = apisUsedbyOutputFile
781
782 var nativeLibNames []string
783 for _, f := range a.filesInfo {
784 if f.class == nativeSharedLib {
785 nativeLibNames = append(nativeLibNames, f.stem())
786 }
787 }
788 apisBackedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_backing.txt")
789 rb := android.NewRuleBuilder(pctx, ctx)
790 rb.Command().
791 Tool(android.PathForSource(ctx, "build/soong/scripts/gen_ndk_backedby_apex.sh")).
792 Output(apisBackedbyOutputFile).
793 Flags(nativeLibNames)
794 rb.Build("ndk_backedby_list", "Generate API libraries backed by Apex")
795 a.nativeApisBackedByModuleFile = apisBackedbyOutputFile
796
797 var javaLibOrApkPath []android.Path
798 for _, f := range a.filesInfo {
799 if f.class == javaSharedLib || f.class == app {
800 javaLibOrApkPath = append(javaLibOrApkPath, f.builtFile)
801 }
802 }
803 javaApiUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.xml")
804 javaUsedByRule := android.NewRuleBuilder(pctx, ctx)
805 javaUsedByRule.Command().
806 Tool(android.PathForSource(ctx, "build/soong/scripts/gen_java_usedby_apex.sh")).
807 BuiltTool("dexdeps").
808 Output(javaApiUsedbyOutputFile).
809 Inputs(javaLibOrApkPath)
810 javaUsedByRule.Build("java_usedby_list", "Generate Java APIs used by Apex")
811 a.javaApisUsedByModuleFile = javaApiUsedbyOutputFile
812
813 bundleConfig := a.buildBundleConfig(ctx)
814
815 var abis []string
816 for _, target := range ctx.MultiTargets() {
817 if len(target.Arch.Abi) > 0 {
818 abis = append(abis, target.Arch.Abi[0])
819 }
820 }
821
822 abis = android.FirstUniqueStrings(abis)
823
824 ctx.Build(pctx, android.BuildParams{
825 Rule: apexBundleRule,
826 Input: apexProtoFile,
827 Implicit: bundleConfig,
828 Output: a.bundleModuleFile,
829 Description: "apex bundle module",
830 Args: map[string]string{
831 "abi": strings.Join(abis, "."),
832 "config": bundleConfig.String(),
833 },
834 })
835
Jiyong Parkb81b9902020-11-24 19:51:18 +0900836 ////////////////////////////////////////////////////////////////////////////////////
837 // Step 4: Sign the APEX using signapk
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000838 signedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900839
840 pem, key := a.getCertificateAndPrivateKey(ctx)
Kousik Kumar309b1c02020-05-28 06:13:33 -0700841 rule := java.Signapk
842 args := map[string]string{
Jiyong Parkb81b9902020-11-24 19:51:18 +0900843 "certificates": pem.String() + " " + key.String(),
Jooyung Han5d00f502021-07-11 07:26:22 +0900844 "flags": "-a 4096 --align-file-size", //alignment
Kousik Kumar309b1c02020-05-28 06:13:33 -0700845 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900846 implicits := android.Paths{pem, key}
Ramy Medhat16f23a42020-09-03 01:29:49 -0400847 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
Kousik Kumar309b1c02020-05-28 06:13:33 -0700848 rule = java.SignapkRE
849 args["implicits"] = strings.Join(implicits.Strings(), ",")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000850 args["outCommaList"] = signedOutputFile.String()
Kousik Kumar309b1c02020-05-28 06:13:33 -0700851 }
Jooyung Han01f5d652023-04-05 16:29:26 +0900852 var validations android.Paths
Jooyung Han4bc10262023-09-08 11:51:45 +0900853 validations = append(validations, runApexLinkerconfigValidation(ctx, unsignedOutputFile.OutputPath, imageDir.OutputPath))
Jooyung Hanb7cdbba2023-04-26 14:42:50 +0900854 // TODO(b/279688635) deapexer supports [ext4]
855 if suffix == imageApexSuffix && ext4 == a.payloadFsType {
Jooyung Han01f5d652023-04-05 16:29:26 +0900856 validations = append(validations, runApexSepolicyTests(ctx, unsignedOutputFile.OutputPath))
857 }
Jiyong Park09d77522019-11-18 11:16:27 +0900858 ctx.Build(pctx, android.BuildParams{
Kousik Kumar309b1c02020-05-28 06:13:33 -0700859 Rule: rule,
Jiyong Park09d77522019-11-18 11:16:27 +0900860 Description: "signapk",
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000861 Output: signedOutputFile,
Jiyong Park09d77522019-11-18 11:16:27 +0900862 Input: unsignedOutputFile,
Kousik Kumar309b1c02020-05-28 06:13:33 -0700863 Implicits: implicits,
864 Args: args,
Jooyung Han01f5d652023-04-05 16:29:26 +0900865 Validations: validations,
Jiyong Park09d77522019-11-18 11:16:27 +0900866 })
Jooyung Hana6d36672022-02-24 13:58:07 +0900867 if suffix == imageApexSuffix {
868 a.outputApexFile = signedOutputFile
869 }
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000870 a.outputFile = signedOutputFile
871
Mohammad Samiul Islama8008f92020-12-22 10:47:50 +0000872 if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && a.testOnlyShouldForceCompression() {
873 ctx.PropertyErrorf("test_only_force_compression", "not available")
874 return
875 }
Nikita Ioffebc035882021-04-14 21:35:24 +0100876
Sasha Smundakfe9a5b82022-07-27 14:51:45 -0700877 installSuffix := suffix
878 a.setCompression(ctx)
879 if a.isCompressed {
Samiul Islam7c02e262021-09-08 17:48:28 +0100880 unsignedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix+".unsigned")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000881
882 compressRule := android.NewRuleBuilder(pctx, ctx)
883 compressRule.Command().
884 Text("rm").
885 FlagWithOutput("-f ", unsignedCompressedOutputFile)
886 compressRule.Command().
887 BuiltTool("apex_compression_tool").
888 Flag("compress").
889 FlagWithArg("--apex_compression_tool ", outHostBinDir+":"+prebuiltSdkToolsBinDir).
890 FlagWithInput("--input ", signedOutputFile).
891 FlagWithOutput("--output ", unsignedCompressedOutputFile)
892 compressRule.Build("compressRule", "Generate unsigned compressed APEX file")
893
Samiul Islam7c02e262021-09-08 17:48:28 +0100894 signedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix)
Mohammad Samiul Islam9ac0e322021-01-19 11:32:29 +0000895 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
896 args["outCommaList"] = signedCompressedOutputFile.String()
897 }
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000898 ctx.Build(pctx, android.BuildParams{
899 Rule: rule,
900 Description: "sign compressedApex",
901 Output: signedCompressedOutputFile,
902 Input: unsignedCompressedOutputFile,
903 Implicits: implicits,
904 Args: args,
905 })
906 a.outputFile = signedCompressedOutputFile
Martin Stjernholm8a3c9142022-07-26 09:35:39 +0000907 installSuffix = imageCapexSuffix
908 }
909
Colin Crossd9ccb6a2022-03-07 18:38:34 -0800910 if !a.installable() {
911 a.SkipInstall()
912 }
913
Jiyong Park17ff2832021-09-27 12:50:30 +0900914 // Install to $OUT/soong/{target,host}/.../apex.
Martin Stjernholm8a3c9142022-07-26 09:35:39 +0000915 a.installedFile = ctx.InstallFile(a.installDir, a.Name()+installSuffix, a.outputFile,
Colin Cross6340ea52021-11-04 12:01:18 -0700916 a.compatSymlinks.Paths()...)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900917
918 // installed-files.txt is dist'ed
919 a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900920}
921
Jiyong Parkb81b9902020-11-24 19:51:18 +0900922// getCertificateAndPrivateKey retrieves the cert and the private key that will be used to sign
923// the zip container of this APEX. See the description of the 'certificate' property for how
924// the cert and the private key are found.
925func (a *apexBundle) getCertificateAndPrivateKey(ctx android.PathContext) (pem, key android.Path) {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800926 if a.containerCertificateFile != nil {
927 return a.containerCertificateFile, a.containerPrivateKeyFile
Jiyong Parkb81b9902020-11-24 19:51:18 +0900928 }
929
Jaewoong Jung4cfdf7d2021-04-20 16:21:24 -0700930 cert := String(a.overridableProperties.Certificate)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900931 if cert == "" {
932 return ctx.Config().DefaultAppCertificate(ctx)
933 }
934
935 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
936 pem = defaultDir.Join(ctx, cert+".x509.pem")
937 key = defaultDir.Join(ctx, cert+".pk8")
938 return pem, key
Jiyong Park09d77522019-11-18 11:16:27 +0900939}
Jooyung Han27151d92019-12-16 17:45:32 +0900940
941func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
942 // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
943 // to see if it should be overridden because their <apex name> is dynamically generated
944 // according to its VNDK version.
945 if a.vndkApex {
946 overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
947 if overridden {
Jooyung Han2cd2f9a2023-02-06 18:29:08 +0900948 return overrideName + ".v" + a.vndkVersion(ctx.DeviceConfig())
Jooyung Han27151d92019-12-16 17:45:32 +0900949 }
950 return ""
951 }
Baligh Uddin5b57dba2020-03-15 13:01:05 -0700952 if a.overridableProperties.Package_name != "" {
953 return a.overridableProperties.Package_name
954 }
Jiyong Park20bacab2020-03-03 11:45:41 +0900955 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jooyung Han27151d92019-12-16 17:45:32 +0900956 if overridden {
957 return manifestPackageName
958 }
959 return ""
960}
Jiyong Park83dc74b2020-01-14 18:38:44 +0900961
962func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
Jiyong Park83dc74b2020-01-14 18:38:44 +0900963 if a.properties.IsCoverageVariant {
964 // Otherwise, we will have duplicated rules for coverage and
965 // non-coverage variants of the same APEX
966 return
967 }
968
Artur Satayev872a1442020-04-27 17:08:37 +0100969 depInfos := android.DepNameToDepInfoMap{}
Jooyung Han749dc692020-04-15 11:03:39 +0900970 a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
Artur Satayev872a1442020-04-27 17:08:37 +0100971 if from.Name() == to.Name() {
972 // This can happen for cc.reuseObjTag. We are not interested in tracking this.
973 // As soon as the dependency graph crosses the APEX boundary, don't go further.
974 return !externalDep
Jiyong Park678c8812020-02-07 17:25:49 +0900975 }
Jiyong Park83dc74b2020-01-14 18:38:44 +0900976
Artur Satayev533b98c2021-03-11 18:03:42 +0000977 // Skip dependencies that are only available to APEXes; they are developed with updatability
978 // in mind and don't need manual approval.
979 if to.(android.ApexModule).NotAvailableForPlatform() {
980 return !externalDep
981 }
982
Cindy Zhou18417cb2020-12-10 07:12:38 -0800983 depTag := ctx.OtherModuleDependencyTag(to)
Artur Satayev533b98c2021-03-11 18:03:42 +0000984 // Check to see if dependency been marked to skip the dependency check
Cindy Zhou18417cb2020-12-10 07:12:38 -0800985 if skipDepCheck, ok := depTag.(android.SkipApexAllowedDependenciesCheck); ok && skipDepCheck.SkipApexAllowedDependenciesCheck() {
Cindy Zhou18417cb2020-12-10 07:12:38 -0800986 return !externalDep
987 }
988
Artur Satayev872a1442020-04-27 17:08:37 +0100989 if info, exists := depInfos[to.Name()]; exists {
990 if !android.InList(from.Name(), info.From) {
991 info.From = append(info.From, from.Name())
992 }
993 info.IsExternal = info.IsExternal && externalDep
994 depInfos[to.Name()] = info
995 } else {
Artur Satayev480e25b2020-04-27 18:53:18 +0100996 toMinSdkVersion := "(no version)"
Jiyong Park92315372021-04-02 08:45:46 +0900997 if m, ok := to.(interface {
Spandan Das8c9ae7e2023-03-03 21:20:36 +0000998 MinSdkVersion(ctx android.EarlyModuleContext) android.ApiLevel
Jiyong Park92315372021-04-02 08:45:46 +0900999 }); ok {
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001000 if v := m.MinSdkVersion(ctx); !v.IsNone() {
1001 toMinSdkVersion = v.String()
Jiyong Park92315372021-04-02 08:45:46 +09001002 }
1003 } else if m, ok := to.(interface{ MinSdkVersion() string }); ok {
1004 // TODO(b/175678607) eliminate the use of MinSdkVersion returning
1005 // string
Artur Satayev480e25b2020-04-27 18:53:18 +01001006 if v := m.MinSdkVersion(); v != "" {
1007 toMinSdkVersion = v
1008 }
1009 }
Artur Satayev872a1442020-04-27 17:08:37 +01001010 depInfos[to.Name()] = android.ApexModuleDepInfo{
Artur Satayev480e25b2020-04-27 18:53:18 +01001011 To: to.Name(),
1012 From: []string{from.Name()},
1013 IsExternal: externalDep,
1014 MinSdkVersion: toMinSdkVersion,
Artur Satayev872a1442020-04-27 17:08:37 +01001015 }
1016 }
1017
1018 // As soon as the dependency graph crosses the APEX boundary, don't go further.
1019 return !externalDep
Jiyong Park83dc74b2020-01-14 18:38:44 +09001020 })
1021
Spandan Das8c9ae7e2023-03-03 21:20:36 +00001022 a.ApexBundleDepsInfo.BuildDepsInfoLists(ctx, a.MinSdkVersion(ctx).String(), depInfos)
Artur Satayev872a1442020-04-27 17:08:37 +01001023
Jiyong Park83dc74b2020-01-14 18:38:44 +09001024 ctx.Build(pctx, android.BuildParams{
1025 Rule: android.Phony,
1026 Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
Artur Satayeva8bd1132020-04-27 18:07:06 +01001027 Inputs: []android.Path{
1028 a.ApexBundleDepsInfo.FullListPath(),
1029 a.ApexBundleDepsInfo.FlatListPath(),
1030 },
Jiyong Park83dc74b2020-01-14 18:38:44 +09001031 })
1032}
Colin Cross08dca382020-07-21 20:31:17 -07001033
1034func (a *apexBundle) buildLintReports(ctx android.ModuleContext) {
1035 depSetsBuilder := java.NewLintDepSetBuilder()
1036 for _, fi := range a.filesInfo {
1037 depSetsBuilder.Transitive(fi.lintDepSets)
1038 }
1039
1040 a.lintReports = java.BuildModuleLintReportZips(ctx, depSetsBuilder.Build())
1041}
Jiyong Park1b0893e2021-12-13 23:40:17 +09001042
1043func (a *apexBundle) buildCannedFsConfig(ctx android.ModuleContext) android.OutputPath {
1044 var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
1045 var executablePaths []string // this also includes dirs
1046 var appSetDirs []string
1047 appSetFiles := make(map[string]android.Path)
1048 for _, f := range a.filesInfo {
1049 pathInApex := f.path()
1050 if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
1051 executablePaths = append(executablePaths, pathInApex)
1052 for _, d := range f.dataPaths {
1053 readOnlyPaths = append(readOnlyPaths, filepath.Join(f.installDir, d.RelativeInstallPath, d.SrcPath.Rel()))
1054 }
1055 for _, s := range f.symlinks {
1056 executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
1057 }
1058 } else if f.class == appSet {
Jiyong Park4169a252022-09-29 21:30:25 +09001059 // base APK
1060 readOnlyPaths = append(readOnlyPaths, pathInApex)
1061 // Additional APKs
Jiyong Park1b0893e2021-12-13 23:40:17 +09001062 appSetDirs = append(appSetDirs, f.installDir)
Jiyong Parke1b69142022-09-26 14:48:56 +09001063 appSetFiles[f.installDir] = f.module.(*java.AndroidAppSet).PackedAdditionalOutputs()
Jiyong Park1b0893e2021-12-13 23:40:17 +09001064 } else {
1065 readOnlyPaths = append(readOnlyPaths, pathInApex)
1066 }
1067 dir := f.installDir
1068 for !android.InList(dir, executablePaths) && dir != "" {
1069 executablePaths = append(executablePaths, dir)
1070 dir, _ = filepath.Split(dir) // move up to the parent
1071 if len(dir) > 0 {
1072 // remove trailing slash
1073 dir = dir[:len(dir)-1]
1074 }
1075 }
1076 }
1077 sort.Strings(readOnlyPaths)
1078 sort.Strings(executablePaths)
1079 sort.Strings(appSetDirs)
1080
1081 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
1082 builder := android.NewRuleBuilder(pctx, ctx)
1083 cmd := builder.Command()
1084 cmd.Text("(")
1085 cmd.Text("echo '/ 1000 1000 0755';")
1086 for _, p := range readOnlyPaths {
1087 cmd.Textf("echo '/%s 1000 1000 0644';", p)
1088 }
1089 for _, p := range executablePaths {
1090 cmd.Textf("echo '/%s 0 2000 0755';", p)
1091 }
1092 for _, dir := range appSetDirs {
1093 cmd.Textf("echo '/%s 0 2000 0755';", dir)
1094 file := appSetFiles[dir]
1095 cmd.Text("zipinfo -1").Input(file).Textf(`| sed "s:\(.*\):/%s/\1 1000 1000 0644:";`, dir)
1096 }
Jiyong Park038e8522021-12-13 23:56:35 +09001097 // Custom fs_config is "appended" to the last so that entries from the file are preferred
1098 // over default ones set above.
1099 if a.properties.Canned_fs_config != nil {
1100 cmd.Text("cat").Input(android.PathForModuleSrc(ctx, *a.properties.Canned_fs_config))
1101 }
Maciej Żenczykowski67e2f792023-03-27 07:03:43 +00001102 cmd.Text(")").FlagWithOutput("> ", cannedFsConfig)
Jiyong Park1b0893e2021-12-13 23:40:17 +09001103 builder.Build("generateFsConfig", fmt.Sprintf("Generating canned fs config for %s", a.BaseModuleName()))
1104
1105 return cannedFsConfig.OutputPath
1106}
Jooyung Han01f5d652023-04-05 16:29:26 +09001107
Jooyung Han4bc10262023-09-08 11:51:45 +09001108func runApexLinkerconfigValidation(ctx android.ModuleContext, apexFile android.OutputPath, imageDir android.OutputPath) android.Path {
1109 timestamp := android.PathForModuleOut(ctx, "apex_linkerconfig_validation.timestamp")
1110 ctx.Build(pctx, android.BuildParams{
1111 Rule: apexLinkerconfigValidationRule,
1112 Input: apexFile,
1113 Output: timestamp,
1114 Args: map[string]string{
1115 "image_dir": imageDir.String(),
1116 },
1117 })
1118 return timestamp
1119}
1120
Jooyung Han01f5d652023-04-05 16:29:26 +09001121// Runs apex_sepolicy_tests
1122//
1123// $ deapexer list -Z {apex_file} > {file_contexts}
1124// $ apex_sepolicy_tests -f {file_contexts}
1125func runApexSepolicyTests(ctx android.ModuleContext, apexFile android.OutputPath) android.Path {
1126 timestamp := android.PathForModuleOut(ctx, "sepolicy_tests.timestamp")
1127 ctx.Build(pctx, android.BuildParams{
1128 Rule: apexSepolicyTestsRule,
1129 Input: apexFile,
1130 Output: timestamp,
1131 })
1132 return timestamp
1133}