blob: 7e2b924c7ec547c680663ce5cf6e924fc2fe1f33 [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
96 pbApexManifestRule = pctx.StaticRule("pbApexManifestRule", blueprint.RuleParams{
97 Command: `rm -f $out && ${conv_apex_manifest} proto $in -o $out`,
98 CommandDeps: []string{"${conv_apex_manifest}"},
99 Description: "convert ${in}=>${out}",
100 })
101
Joe Onoratob4638c12021-10-27 15:47:06 -0700102 // TODO(b/113233103): make sure that file_contexts is as expected, i.e., validate
Jiyong Park09d77522019-11-18 11:16:27 +0900103 // against the binary policy using sefcontext_compiler -p <policy>.
104
105 // TODO(b/114327326): automate the generation of file_contexts
106 apexRule = pctx.StaticRule("apexRule", blueprint.RuleParams{
107 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
108 `(. ${out}.copy_commands) && ` +
109 `APEXER_TOOL_PATH=${tool_path} ` +
110 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900111 `--file_contexts ${file_contexts} ` +
112 `--canned_fs_config ${canned_fs_config} ` +
Dario Freni0f4ae072020-01-02 15:24:12 +0000113 `--include_build_info ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900114 `--payload_type image ` +
Oriol Prieto Gasco17e22902022-05-05 13:52:25 +0000115 `--key ${key} ${opt_flags} ${image_dir} ${out} `,
Jiyong Park09d77522019-11-18 11:16:27 +0900116 CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
Huang Jianan13cac632021-08-02 15:02:17 +0800117 "${mke2fs}", "${resize2fs}", "${sefcontext_compile}", "${make_f2fs}", "${sload_f2fs}", "${make_erofs}",
Jiyong Park09d77522019-11-18 11:16:27 +0900118 "${soong_zip}", "${zipalign}", "${aapt2}", "prebuilts/sdk/current/public/android.jar"},
119 Rspfile: "${out}.copy_commands",
120 RspfileContent: "${copy_commands}",
121 Description: "APEX ${image_dir} => ${out}",
Oriol Prieto Gasco17e22902022-05-05 13:52:25 +0000122 }, "tool_path", "image_dir", "copy_commands", "file_contexts", "canned_fs_config", "key", "opt_flags", "manifest", "payload_fs_type")
Jiyong Park09d77522019-11-18 11:16:27 +0900123
124 zipApexRule = pctx.StaticRule("zipApexRule", blueprint.RuleParams{
125 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
126 `(. ${out}.copy_commands) && ` +
127 `APEXER_TOOL_PATH=${tool_path} ` +
Jooyung Han214bf372019-11-12 13:03:50 +0900128 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900129 `--payload_type zip ` +
130 `${image_dir} ${out} `,
131 CommandDeps: []string{"${apexer}", "${merge_zips}", "${soong_zip}", "${zipalign}", "${aapt2}"},
132 Rspfile: "${out}.copy_commands",
133 RspfileContent: "${copy_commands}",
134 Description: "ZipAPEX ${image_dir} => ${out}",
Oriol Prieto Gasco17e22902022-05-05 13:52:25 +0000135 }, "tool_path", "image_dir", "copy_commands", "manifest")
Jiyong Park09d77522019-11-18 11:16:27 +0900136
137 apexProtoConvertRule = pctx.AndroidStaticRule("apexProtoConvertRule",
138 blueprint.RuleParams{
139 Command: `${aapt2} convert --output-format proto $in -o $out`,
140 CommandDeps: []string{"${aapt2}"},
141 })
142
143 apexBundleRule = pctx.StaticRule("apexBundleRule", blueprint.RuleParams{
Jiyong Parkbd159612020-02-28 15:22:21 +0900144 Command: `${zip2zip} -i $in -o $out.base ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900145 `apex_payload.img:apex/${abi}.img ` +
Dario Frenida1aefe2020-03-02 21:47:09 +0000146 `apex_build_info.pb:apex/${abi}.build_info.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900147 `apex_manifest.json:root/apex_manifest.json ` +
Jiyong Park53ae3342019-12-08 02:06:24 +0900148 `apex_manifest.pb:root/apex_manifest.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900149 `AndroidManifest.xml:manifest/AndroidManifest.xml ` +
Jiyong Parkbd159612020-02-28 15:22:21 +0900150 `assets/NOTICE.html.gz:assets/NOTICE.html.gz &&` +
151 `${soong_zip} -o $out.config -C $$(dirname ${config}) -f ${config} && ` +
152 `${merge_zips} $out $out.base $out.config`,
153 CommandDeps: []string{"${zip2zip}", "${soong_zip}", "${merge_zips}"},
Jiyong Park09d77522019-11-18 11:16:27 +0900154 Description: "app bundle",
Jiyong Parkbd159612020-02-28 15:22:21 +0900155 }, "abi", "config")
Jiyong Park09d77522019-11-18 11:16:27 +0900156
157 emitApexContentRule = pctx.StaticRule("emitApexContentRule", blueprint.RuleParams{
158 Command: `rm -f ${out} && touch ${out} && (. ${out}.emit_commands)`,
159 Rspfile: "${out}.emit_commands",
160 RspfileContent: "${emit_commands}",
161 Description: "Emit APEX image content",
162 }, "emit_commands")
163
164 diffApexContentRule = pctx.StaticRule("diffApexContentRule", blueprint.RuleParams{
165 Command: `diff --unchanged-group-format='' \` +
166 `--changed-group-format='%<' \` +
Colin Cross440e0d02020-06-11 11:32:11 -0700167 `${image_content_file} ${allowed_files_file} || (` +
Jiyong Park09d77522019-11-18 11:16:27 +0900168 `echo -e "New unexpected files were added to ${apex_module_name}." ` +
169 ` "To fix the build run following command:" && ` +
Colin Cross440e0d02020-06-11 11:32:11 -0700170 `echo "system/apex/tools/update_allowed_list.sh ${allowed_files_file} ${image_content_file}" && ` +
Dan Willemsen81e43c52020-01-28 15:40:19 -0800171 `exit 1); touch ${out}`,
Colin Cross440e0d02020-06-11 11:32:11 -0700172 Description: "Diff ${image_content_file} and ${allowed_files_file}",
173 }, "image_content_file", "allowed_files_file", "apex_module_name")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900174
sophiezc80a2b32020-11-12 16:39:19 +0000175 generateAPIsUsedbyApexRule = pctx.StaticRule("generateAPIsUsedbyApexRule", blueprint.RuleParams{
176 Command: "$genNdkUsedbyApexPath ${image_dir} ${readelf} ${out}",
177 CommandDeps: []string{"${genNdkUsedbyApexPath}"},
178 Description: "Generate symbol list used by Apex",
179 }, "image_dir", "readelf")
180
Jiyong Parkb81b9902020-11-24 19:51:18 +0900181 // Don't add more rules here. Consider using android.NewRuleBuilder instead.
Jiyong Park09d77522019-11-18 11:16:27 +0900182)
183
Jiyong Parkb81b9902020-11-24 19:51:18 +0900184// buildManifest creates buile rules to modify the input apex_manifest.json to add information
185// gathered by the build system such as provided/required native libraries. Two output files having
186// different formats are generated. a.manifestJsonOut is JSON format for Q devices, and
187// a.manifest.PbOut is protobuf format for R+ devices.
188// TODO(jiyong): make this to return paths instead of directly storing the paths to apexBundle
Jiyong Park09d77522019-11-18 11:16:27 +0900189func (a *apexBundle) buildManifest(ctx android.ModuleContext, provideNativeLibs, requireNativeLibs []string) {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900190 src := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
Jiyong Park09d77522019-11-18 11:16:27 +0900191
Jiyong Parkb81b9902020-11-24 19:51:18 +0900192 // Put dependency({provide|require}NativeLibs) in apex_manifest.json
Jiyong Park09d77522019-11-18 11:16:27 +0900193 provideNativeLibs = android.SortedUniqueStrings(provideNativeLibs)
194 requireNativeLibs = android.SortedUniqueStrings(android.RemoveListFromList(requireNativeLibs, provideNativeLibs))
195
Jiyong Parkb81b9902020-11-24 19:51:18 +0900196 // APEX name can be overridden
Jiyong Park09d77522019-11-18 11:16:27 +0900197 optCommands := []string{}
198 if a.properties.Apex_name != nil {
199 optCommands = append(optCommands, "-v name "+*a.properties.Apex_name)
200 }
201
Jiyong Parkb81b9902020-11-24 19:51:18 +0900202 // Collect jniLibs. Notice that a.filesInfo is already sorted
Jooyung Han643adc42020-02-27 13:50:06 +0900203 var jniLibs []string
204 for _, fi := range a.filesInfo {
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900205 if fi.isJniLib && !android.InList(fi.stem(), jniLibs) {
206 jniLibs = append(jniLibs, fi.stem())
Jooyung Han643adc42020-02-27 13:50:06 +0900207 }
208 }
209 if len(jniLibs) > 0 {
210 optCommands = append(optCommands, "-a jniLibs "+strings.Join(jniLibs, " "))
211 }
212
Alexei Nicoaraee4b6332022-06-30 16:34:28 +0100213 manifestJsonCommentsStripped := android.PathForModuleOut(ctx, "apex_manifest_comments_stripped.json")
214 ctx.Build(pctx, android.BuildParams{
215 Rule: stripCommentsApexManifestRule,
216 Input: src,
217 Output: manifestJsonCommentsStripped,
218 })
219
Jiyong Parkb81b9902020-11-24 19:51:18 +0900220 manifestJsonFullOut := android.PathForModuleOut(ctx, "apex_manifest_full.json")
Jiyong Park09d77522019-11-18 11:16:27 +0900221 ctx.Build(pctx, android.BuildParams{
222 Rule: apexManifestRule,
Alexei Nicoaraee4b6332022-06-30 16:34:28 +0100223 Input: manifestJsonCommentsStripped,
Jooyung Han214bf372019-11-12 13:03:50 +0900224 Output: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900225 Args: map[string]string{
226 "provideNativeLibs": strings.Join(provideNativeLibs, " "),
227 "requireNativeLibs": strings.Join(requireNativeLibs, " "),
228 "opt": strings.Join(optCommands, " "),
229 },
230 })
231
Jiyong Parkb81b9902020-11-24 19:51:18 +0900232 // b/143654022 Q apexd can't understand newly added keys in apex_manifest.json prepare
233 // stripped-down version so that APEX modules built from R+ can be installed to Q
Dan Albertc8060532020-07-22 22:32:17 -0700234 minSdkVersion := a.minSdkVersion(ctx)
235 if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
Jooyung Han214bf372019-11-12 13:03:50 +0900236 a.manifestJsonOut = android.PathForModuleOut(ctx, "apex_manifest.json")
237 ctx.Build(pctx, android.BuildParams{
238 Rule: stripApexManifestRule,
239 Input: manifestJsonFullOut,
240 Output: a.manifestJsonOut,
241 })
242 }
Jiyong Park09d77522019-11-18 11:16:27 +0900243
Jiyong Parkb81b9902020-11-24 19:51:18 +0900244 // From R+, protobuf binary format (.pb) is the standard format for apex_manifest
Jiyong Park09d77522019-11-18 11:16:27 +0900245 a.manifestPbOut = android.PathForModuleOut(ctx, "apex_manifest.pb")
246 ctx.Build(pctx, android.BuildParams{
247 Rule: pbApexManifestRule,
Jooyung Han214bf372019-11-12 13:03:50 +0900248 Input: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900249 Output: a.manifestPbOut,
250 })
251}
252
Jiyong Parkb81b9902020-11-24 19:51:18 +0900253// buildFileContexts create build rules to append an entry for apex_manifest.pb to the file_contexts
254// file for this APEX which is either from /systme/sepolicy/apex/<apexname>-file_contexts or from
255// the file_contexts property of this APEX. This is to make sure that the manifest file is correctly
256// labeled as system_file.
257func (a *apexBundle) buildFileContexts(ctx android.ModuleContext) android.OutputPath {
Jooyung Han580eb4f2020-06-24 19:33:06 +0900258 var fileContexts android.Path
Liz Kammer37997c42021-09-14 17:53:38 -0400259 var fileContextsDir string
Jooyung Han580eb4f2020-06-24 19:33:06 +0900260 if a.properties.File_contexts == nil {
261 fileContexts = android.PathForSource(ctx, "system/sepolicy/apex", ctx.ModuleName()+"-file_contexts")
262 } else {
Liz Kammer37997c42021-09-14 17:53:38 -0400263 if m, t := android.SrcIsModuleWithTag(*a.properties.File_contexts); m != "" {
264 otherModule := android.GetModuleFromPathDep(ctx, m, t)
265 fileContextsDir = ctx.OtherModuleDir(otherModule)
266 }
Jooyung Han580eb4f2020-06-24 19:33:06 +0900267 fileContexts = android.PathForModuleSrc(ctx, *a.properties.File_contexts)
268 }
Liz Kammer37997c42021-09-14 17:53:38 -0400269 if fileContextsDir == "" {
270 fileContextsDir = filepath.Dir(fileContexts.String())
271 }
272 fileContextsDir += string(filepath.Separator)
273
Jooyung Han580eb4f2020-06-24 19:33:06 +0900274 if a.Platform() {
Liz Kammer37997c42021-09-14 17:53:38 -0400275 if !strings.HasPrefix(fileContextsDir, "system/sepolicy/") {
276 ctx.PropertyErrorf("file_contexts", "should be under system/sepolicy, but found in %q", fileContextsDir)
Jooyung Han580eb4f2020-06-24 19:33:06 +0900277 }
278 }
279 if !android.ExistentPathForSource(ctx, fileContexts.String()).Valid() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900280 ctx.PropertyErrorf("file_contexts", "cannot find file_contexts file: %q", fileContexts.String())
Jooyung Han580eb4f2020-06-24 19:33:06 +0900281 }
282
283 output := android.PathForModuleOut(ctx, "file_contexts")
Colin Crossf1a035e2020-11-16 17:32:30 -0800284 rule := android.NewRuleBuilder(pctx, ctx)
Jooyung Han7f146c02020-09-23 19:15:55 +0900285
Jiyong Parkb81b9902020-11-24 19:51:18 +0900286 switch a.properties.ApexType {
287 case imageApex:
Jooyung Han7f146c02020-09-23 19:15:55 +0900288 // remove old file
289 rule.Command().Text("rm").FlagWithOutput("-f ", output)
290 // copy file_contexts
291 rule.Command().Text("cat").Input(fileContexts).Text(">>").Output(output)
292 // new line
293 rule.Command().Text("echo").Text(">>").Output(output)
294 // force-label /apex_manifest.pb and / as system_file so that apexd can read them
295 rule.Command().Text("echo").Flag("/apex_manifest\\\\.pb u:object_r:system_file:s0").Text(">>").Output(output)
296 rule.Command().Text("echo").Flag("/ u:object_r:system_file:s0").Text(">>").Output(output)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900297 case flattenedApex:
Jooyung Han7f146c02020-09-23 19:15:55 +0900298 // For flattened apexes, install path should be prepended.
299 // File_contexts file should be emiited to make via LOCAL_FILE_CONTEXTS
300 // so that it can be merged into file_contexts.bin
301 apexPath := android.InstallPathToOnDevicePath(ctx, a.installDir.Join(ctx, a.Name()))
302 apexPath = strings.ReplaceAll(apexPath, ".", `\\.`)
303 // remove old file
304 rule.Command().Text("rm").FlagWithOutput("-f ", output)
305 // copy file_contexts
306 rule.Command().Text("awk").Text(`'/object_r/{printf("` + apexPath + `%s\n", $0)}'`).Input(fileContexts).Text(">").Output(output)
307 // new line
308 rule.Command().Text("echo").Text(">>").Output(output)
309 // force-label /apex_manifest.pb and / as system_file so that apexd can read them
310 rule.Command().Text("echo").Flag(apexPath + `/apex_manifest\\.pb u:object_r:system_file:s0`).Text(">>").Output(output)
311 rule.Command().Text("echo").Flag(apexPath + "/ u:object_r:system_file:s0").Text(">>").Output(output)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900312 default:
313 panic(fmt.Errorf("unsupported type %v", a.properties.ApexType))
Jooyung Han7f146c02020-09-23 19:15:55 +0900314 }
315
Colin Crossf1a035e2020-11-16 17:32:30 -0800316 rule.Build("file_contexts."+a.Name(), "Generate file_contexts")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900317 return output.OutputPath
Jooyung Han580eb4f2020-06-24 19:33:06 +0900318}
319
Jiyong Parkb81b9902020-11-24 19:51:18 +0900320// buildInstalledFilesFile creates a build rule for the installed-files.txt file where the list of
321// files included in this APEX is shown. The text file is dist'ed so that people can see what's
322// included in the APEX without actually downloading and extracting it.
Jiyong Park3a1602e2020-01-14 14:39:19 +0900323func (a *apexBundle) buildInstalledFilesFile(ctx android.ModuleContext, builtApex android.Path, imageDir android.Path) android.OutputPath {
324 output := android.PathForModuleOut(ctx, "installed-files.txt")
Colin Crossf1a035e2020-11-16 17:32:30 -0800325 rule := android.NewRuleBuilder(pctx, ctx)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900326 rule.Command().
327 Implicit(builtApex).
328 Text("(cd " + imageDir.String() + " ; ").
Jiyong Parkbd63a102020-02-08 12:40:05 +0900329 Text("find . \\( -type f -o -type l \\) -printf \"%s %p\\n\") ").
Jiyong Park3a1602e2020-01-14 14:39:19 +0900330 Text(" | sort -nr > ").
331 Output(output)
Colin Crossf1a035e2020-11-16 17:32:30 -0800332 rule.Build("installed-files."+a.Name(), "Installed files")
Jiyong Park3a1602e2020-01-14 14:39:19 +0900333 return output.OutputPath
334}
335
Jiyong Parkb81b9902020-11-24 19:51:18 +0900336// buildBundleConfig creates a build rule for the bundle config file that will control the bundle
337// creation process.
Jiyong Parkbd159612020-02-28 15:22:21 +0900338func (a *apexBundle) buildBundleConfig(ctx android.ModuleContext) android.OutputPath {
339 output := android.PathForModuleOut(ctx, "bundle_config.json")
340
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900341 type ApkConfig struct {
342 Package_name string `json:"package_name"`
343 Apk_path string `json:"path"`
344 }
Jiyong Parkbd159612020-02-28 15:22:21 +0900345 config := struct {
346 Compression struct {
347 Uncompressed_glob []string `json:"uncompressed_glob"`
348 } `json:"compression"`
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900349 Apex_config struct {
350 Apex_embedded_apk_config []ApkConfig `json:"apex_embedded_apk_config,omitempty"`
351 } `json:"apex_config,omitempty"`
Jiyong Parkbd159612020-02-28 15:22:21 +0900352 }{}
353
354 config.Compression.Uncompressed_glob = []string{
355 "apex_payload.img",
356 "apex_manifest.*",
357 }
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900358
Jiyong Parkb81b9902020-11-24 19:51:18 +0900359 // Collect the manifest names and paths of android apps if their manifest names are
360 // overridden.
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900361 for _, fi := range a.filesInfo {
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700362 if fi.class != app && fi.class != appSet {
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900363 continue
364 }
365 packageName := fi.overriddenPackageName
366 if packageName != "" {
367 config.Apex_config.Apex_embedded_apk_config = append(
368 config.Apex_config.Apex_embedded_apk_config,
369 ApkConfig{
370 Package_name: packageName,
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900371 Apk_path: fi.path(),
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900372 })
373 }
374 }
375
Jiyong Parkbd159612020-02-28 15:22:21 +0900376 j, err := json.Marshal(config)
377 if err != nil {
378 panic(fmt.Errorf("error while marshalling to %q: %#v", output, err))
379 }
380
Colin Crosscf371cc2020-11-13 11:48:42 -0800381 android.WriteFileRule(ctx, output, string(j))
Jiyong Parkbd159612020-02-28 15:22:21 +0900382
383 return output.OutputPath
384}
385
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000386func markManifestTestOnly(ctx android.ModuleContext, androidManifestFile android.Path) android.Path {
Gurpreet Singh7deabfa2022-02-10 13:28:35 +0000387 return java.ManifestFixer(ctx, androidManifestFile, java.ManifestFixerParams{
388 TestOnly: true,
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000389 })
390}
391
Jiyong Parkb81b9902020-11-24 19:51:18 +0900392// buildUnflattendApex creates build rules to build an APEX using apexer.
Jiyong Park09d77522019-11-18 11:16:27 +0900393func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext) {
Jiyong Park09d77522019-11-18 11:16:27 +0900394 apexType := a.properties.ApexType
395 suffix := apexType.suffix()
Colin Cross6340ea52021-11-04 12:01:18 -0700396 apexName := proptools.StringDefault(a.properties.Apex_name, a.BaseModuleName())
Jiyong Park09d77522019-11-18 11:16:27 +0900397
Jiyong Parkb81b9902020-11-24 19:51:18 +0900398 ////////////////////////////////////////////////////////////////////////////////////////////
399 // Step 1: copy built files to appropriate directories under the image directory
400
401 imageDir := android.PathForModuleOut(ctx, "image"+suffix)
402
Colin Cross02730b92022-04-18 17:42:27 -0700403 installSymbolFiles := (!ctx.Config().KatiEnabled() || a.ExportedToMake()) && a.installable()
Colin Cross6340ea52021-11-04 12:01:18 -0700404
405 // b/140136207. When there are overriding APEXes for a VNDK APEX, the symbols file for the overridden
406 // APEX and the overriding APEX will have the same installation paths at /apex/com.android.vndk.v<ver>
407 // as their apexName will be the same. To avoid the path conflicts, skip installing the symbol files
408 // for the overriding VNDK APEXes.
409 if a.vndkApex && len(a.overridableProperties.Overrides) > 0 {
410 installSymbolFiles = false
411 }
412
413 // Avoid creating duplicate build rules for multi-installed APEXes.
414 if proptools.BoolDefault(a.properties.Multi_install_skip_symbol_files, false) {
415 installSymbolFiles = false
Colin Cross4acaea92021-12-10 23:05:02 +0000416
Colin Cross6340ea52021-11-04 12:01:18 -0700417 }
Colin Cross4acaea92021-12-10 23:05:02 +0000418 // set of dependency module:location mappings
419 installMapSet := make(map[string]bool)
Colin Cross6340ea52021-11-04 12:01:18 -0700420
Jiyong Parkb81b9902020-11-24 19:51:18 +0900421 // TODO(jiyong): use the RuleBuilder
Jiyong Park7cd10e32020-01-14 09:22:18 +0900422 var copyCommands []string
Jiyong Parkb81b9902020-11-24 19:51:18 +0900423 var implicitInputs []android.Path
Colin Cross6340ea52021-11-04 12:01:18 -0700424 pathWhenActivated := android.PathForModuleInPartitionInstall(ctx, "apex", apexName)
Jiyong Park7cd10e32020-01-14 09:22:18 +0900425 for _, fi := range a.filesInfo {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900426 destPath := imageDir.Join(ctx, fi.path()).String()
Jiyong Parkb81b9902020-11-24 19:51:18 +0900427 // Prepare the destination path
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700428 destPathDir := filepath.Dir(destPath)
429 if fi.class == appSet {
430 copyCommands = append(copyCommands, "rm -rf "+destPathDir)
431 }
432 copyCommands = append(copyCommands, "mkdir -p "+destPathDir)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900433
Colin Cross4acaea92021-12-10 23:05:02 +0000434 installMapPath := fi.builtFile
435
Jiyong Parkb81b9902020-11-24 19:51:18 +0900436 // Copy the built file to the directory. But if the symlink optimization is turned
437 // on, place a symlink to the corresponding file in /system partition instead.
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900438 if a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform() {
Jiyong Park7cd10e32020-01-14 09:22:18 +0900439 // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900440 pathOnDevice := filepath.Join("/system", fi.path())
Jiyong Park7cd10e32020-01-14 09:22:18 +0900441 copyCommands = append(copyCommands, "ln -sfn "+pathOnDevice+" "+destPath)
442 } else {
Colin Cross4acaea92021-12-10 23:05:02 +0000443 var installedPath android.InstallPath
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700444 if fi.class == appSet {
445 copyCommands = append(copyCommands,
Colin Crossffbcd1d2021-11-12 12:19:42 -0800446 fmt.Sprintf("unzip -qDD -d %s %s", destPathDir,
447 fi.module.(*java.AndroidAppSet).PackedAdditionalOutputs().String()))
Colin Cross6340ea52021-11-04 12:01:18 -0700448 if installSymbolFiles {
449 installedPath = ctx.InstallFileWithExtraFilesZip(pathWhenActivated.Join(ctx, fi.installDir),
450 fi.stem(), fi.builtFile, fi.module.(*java.AndroidAppSet).PackedAdditionalOutputs())
451 }
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700452 } else {
453 copyCommands = append(copyCommands, "cp -f "+fi.builtFile.String()+" "+destPath)
Colin Cross6340ea52021-11-04 12:01:18 -0700454 if installSymbolFiles {
455 installedPath = ctx.InstallFile(pathWhenActivated.Join(ctx, fi.installDir), fi.stem(), fi.builtFile)
456 }
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700457 }
Jiyong Park7cd10e32020-01-14 09:22:18 +0900458 implicitInputs = append(implicitInputs, fi.builtFile)
Colin Cross6340ea52021-11-04 12:01:18 -0700459 if installSymbolFiles {
460 implicitInputs = append(implicitInputs, installedPath)
461 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900462
Colin Cross4acaea92021-12-10 23:05:02 +0000463 // Create additional symlinks pointing the file inside the APEX (if any). Note that
464 // this is independent from the symlink optimization.
465 for _, symlinkPath := range fi.symlinkPaths() {
466 symlinkDest := imageDir.Join(ctx, symlinkPath).String()
467 copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
468 if installSymbolFiles {
469 installedSymlink := ctx.InstallSymlink(pathWhenActivated.Join(ctx, filepath.Dir(symlinkPath)), filepath.Base(symlinkPath), installedPath)
470 implicitInputs = append(implicitInputs, installedSymlink)
471 }
Colin Cross6340ea52021-11-04 12:01:18 -0700472 }
Colin Cross4acaea92021-12-10 23:05:02 +0000473
474 installMapPath = installedPath
Jiyong Park7cd10e32020-01-14 09:22:18 +0900475 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900476
477 // Copy the test files (if any)
Liz Kammer1c14a212020-05-12 15:26:55 -0700478 for _, d := range fi.dataPaths {
479 // 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 -0400480 relPath := d.SrcPath.Rel()
481 dataPath := d.SrcPath.String()
Liz Kammer1c14a212020-05-12 15:26:55 -0700482 if !strings.HasSuffix(dataPath, relPath) {
483 panic(fmt.Errorf("path %q does not end with %q", dataPath, relPath))
484 }
485
Jiyong Parkb81b9902020-11-24 19:51:18 +0900486 dataDest := imageDir.Join(ctx, fi.apexRelativePath(relPath), d.RelativeInstallPath).String()
Liz Kammer1c14a212020-05-12 15:26:55 -0700487
Chris Parsons216e10a2020-07-09 17:12:52 -0400488 copyCommands = append(copyCommands, "cp -f "+d.SrcPath.String()+" "+dataDest)
489 implicitInputs = append(implicitInputs, d.SrcPath)
Liz Kammer1c14a212020-05-12 15:26:55 -0700490 }
Colin Cross4acaea92021-12-10 23:05:02 +0000491
492 installMapSet[installMapPath.String()+":"+fi.installDir+"/"+fi.builtFile.Base()] = true
Jiyong Park09d77522019-11-18 11:16:27 +0900493 }
Jooyung Han214bf372019-11-12 13:03:50 +0900494 implicitInputs = append(implicitInputs, a.manifestPbOut)
Colin Cross6340ea52021-11-04 12:01:18 -0700495 if installSymbolFiles {
496 installedManifest := ctx.InstallFile(pathWhenActivated, "apex_manifest.pb", a.manifestPbOut)
497 installedKey := ctx.InstallFile(pathWhenActivated, "apex_pubkey", a.publicKeyFile)
498 implicitInputs = append(implicitInputs, installedManifest, installedKey)
499 }
Jiyong Park09d77522019-11-18 11:16:27 +0900500
Colin Cross4acaea92021-12-10 23:05:02 +0000501 if len(installMapSet) > 0 {
502 var installs []string
503 installs = append(installs, android.SortedStringKeys(installMapSet)...)
504 a.SetLicenseInstallMap(installs)
505 }
506
Jiyong Parkb81b9902020-11-24 19:51:18 +0900507 ////////////////////////////////////////////////////////////////////////////////////////////
508 // Step 1.a: Write the list of files in this APEX to a txt file and compare it against
509 // the allowed list given via the allowed_files property. Build fails when the two lists
510 // differ.
511 //
512 // TODO(jiyong): consider removing this. Nobody other than com.android.apex.cts.shim.* seems
513 // to be using this at this moment. Furthermore, this looks very similar to what
514 // buildInstalledFilesFile does. At least, move this to somewhere else so that this doesn't
515 // hurt readability.
516 // TODO(jiyong): use RuleBuilder
Jooyung Han938b5932020-06-20 12:47:47 +0900517 if a.overridableProperties.Allowed_files != nil {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900518 // Build content.txt
519 var emitCommands []string
520 imageContentFile := android.PathForModuleOut(ctx, "content.txt")
521 emitCommands = append(emitCommands, "echo ./apex_manifest.pb >> "+imageContentFile.String())
522 minSdkVersion := a.minSdkVersion(ctx)
523 if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
524 emitCommands = append(emitCommands, "echo ./apex_manifest.json >> "+imageContentFile.String())
525 }
526 for _, fi := range a.filesInfo {
527 emitCommands = append(emitCommands, "echo './"+fi.path()+"' >> "+imageContentFile.String())
528 }
529 emitCommands = append(emitCommands, "sort -o "+imageContentFile.String()+" "+imageContentFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900530 ctx.Build(pctx, android.BuildParams{
531 Rule: emitApexContentRule,
532 Implicits: implicitInputs,
533 Output: imageContentFile,
534 Description: "emit apex image content",
535 Args: map[string]string{
536 "emit_commands": strings.Join(emitCommands, " && "),
537 },
538 })
539 implicitInputs = append(implicitInputs, imageContentFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900540
Jiyong Parkb81b9902020-11-24 19:51:18 +0900541 // Compare content.txt against allowed_files.
542 allowedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.overridableProperties.Allowed_files))
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800543 phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
Jiyong Park09d77522019-11-18 11:16:27 +0900544 ctx.Build(pctx, android.BuildParams{
545 Rule: diffApexContentRule,
546 Implicits: implicitInputs,
547 Output: phonyOutput,
548 Description: "diff apex image content",
549 Args: map[string]string{
Colin Cross440e0d02020-06-11 11:32:11 -0700550 "allowed_files_file": allowedFilesFile.String(),
551 "image_content_file": imageContentFile.String(),
552 "apex_module_name": a.Name(),
Jiyong Park09d77522019-11-18 11:16:27 +0900553 },
554 })
Jiyong Park09d77522019-11-18 11:16:27 +0900555 implicitInputs = append(implicitInputs, phonyOutput)
556 }
557
Jiyong Parkb81b9902020-11-24 19:51:18 +0900558 unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
Colin Cross790ef352021-10-25 19:15:55 -0700559 outHostBinDir := ctx.Config().HostToolPath(ctx, "").String()
Jiyong Park09d77522019-11-18 11:16:27 +0900560 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
561
Oriol Prieto Gascoa07099d2021-10-14 15:33:41 -0400562 // Figure out if we need to compress the apex.
563 compressionEnabled := ctx.Config().CompressedApex() && proptools.BoolDefault(a.overridableProperties.Compressible, false) && !a.testApex && !ctx.Config().UnbundledBuildApps()
Jiyong Park09d77522019-11-18 11:16:27 +0900564 if apexType == imageApex {
Jiyong Park1b0893e2021-12-13 23:40:17 +0900565
Jiyong Parkb81b9902020-11-24 19:51:18 +0900566 ////////////////////////////////////////////////////////////////////////////////////
567 // Step 2: create canned_fs_config which encodes filemode,uid,gid of each files
568 // in this APEX. The file will be used by apexer in later steps.
Jiyong Park1b0893e2021-12-13 23:40:17 +0900569 cannedFsConfig := a.buildCannedFsConfig(ctx)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900570 implicitInputs = append(implicitInputs, cannedFsConfig)
Jiyong Park09d77522019-11-18 11:16:27 +0900571
Jiyong Parkb81b9902020-11-24 19:51:18 +0900572 ////////////////////////////////////////////////////////////////////////////////////
573 // Step 3: Prepare option flags for apexer and invoke it to create an unsigned APEX.
574 // TODO(jiyong): use the RuleBuilder
Jiyong Park09d77522019-11-18 11:16:27 +0900575 optFlags := []string{}
576
Jiyong Parkb81b9902020-11-24 19:51:18 +0900577 fileContexts := a.buildFileContexts(ctx)
578 implicitInputs = append(implicitInputs, fileContexts)
579
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800580 implicitInputs = append(implicitInputs, a.privateKeyFile, a.publicKeyFile)
581 optFlags = append(optFlags, "--pubkey "+a.publicKeyFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900582
Jooyung Han27151d92019-12-16 17:45:32 +0900583 manifestPackageName := a.getOverrideManifestPackageName(ctx)
584 if manifestPackageName != "" {
Jiyong Park09d77522019-11-18 11:16:27 +0900585 optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
586 }
587
588 if a.properties.AndroidManifest != nil {
589 androidManifestFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.AndroidManifest))
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000590
591 if a.testApex {
592 androidManifestFile = markManifestTestOnly(ctx, androidManifestFile)
593 }
594
Jiyong Park09d77522019-11-18 11:16:27 +0900595 implicitInputs = append(implicitInputs, androidManifestFile)
596 optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
Gurpreet Singha76f8742022-02-03 21:01:51 +0000597 } else if a.testApex {
598 optFlags = append(optFlags, "--test_only")
Jiyong Park09d77522019-11-18 11:16:27 +0900599 }
600
Jiyong Parkb81b9902020-11-24 19:51:18 +0900601 // Determine target/min sdk version from the context
602 // TODO(jiyong): make this as a function
Dan Albertc8060532020-07-22 22:32:17 -0700603 moduleMinSdkVersion := a.minSdkVersion(ctx)
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100604 minSdkVersion := moduleMinSdkVersion.String()
605
Jiyong Parkb81b9902020-11-24 19:51:18 +0900606 // bundletool doesn't understand what "current" is. We need to transform it to
607 // codename
Jooyung Haned124c32021-01-26 11:43:46 +0900608 if moduleMinSdkVersion.IsCurrent() || moduleMinSdkVersion.IsNone() {
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100609 minSdkVersion = ctx.Config().DefaultAppTargetSdk(ctx).String()
Liz Kammer4854a7d2021-05-27 14:28:27 -0400610
611 if java.UseApiFingerprint(ctx) {
612 minSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
613 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
614 }
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000615 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900616 // apex module doesn't have a concept of target_sdk_version, hence for the time
617 // being targetSdkVersion == default targetSdkVersion of the branch.
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100618 targetSdkVersion := strconv.Itoa(ctx.Config().DefaultAppTargetSdk(ctx).FinalOrFutureInt())
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000619
Nikita Ioffe1f4f3452020-03-02 16:58:11 +0000620 if java.UseApiFingerprint(ctx) {
621 targetSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
Baligh Uddinf6201372020-01-24 23:15:44 +0000622 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
623 }
Jiyong Park09d77522019-11-18 11:16:27 +0900624 optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
Baligh Uddinf6201372020-01-24 23:15:44 +0000625 optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
Jiyong Park09d77522019-11-18 11:16:27 +0900626
Baligh Uddin004d7172020-02-19 21:29:28 -0800627 if a.overridableProperties.Logging_parent != "" {
628 optFlags = append(optFlags, "--logging_parent ", a.overridableProperties.Logging_parent)
629 }
630
Bob Badourde6a0872022-04-01 18:00:00 +0000631 // Create a NOTICE file, and embed it as an asset file in the APEX.
Bob Badour2c8888e2022-04-04 16:12:21 -0700632 a.htmlGzNotice = android.PathForModuleOut(ctx, "NOTICE.html.gz")
Bob Badourc6ec9fb2022-06-08 15:59:35 -0700633 android.BuildNoticeHtmlOutputFromLicenseMetadata(
634 ctx, a.htmlGzNotice, "", "",
635 []string{
636 android.PathForModuleInstall(ctx).String() + "/",
637 android.PathForModuleInPartitionInstall(ctx, "apex").String() + "/",
638 })
Bob Badour2c8888e2022-04-04 16:12:21 -0700639 noticeAssetPath := android.PathForModuleOut(ctx, "NOTICE", "NOTICE.html.gz")
640 builder := android.NewRuleBuilder(pctx, ctx)
641 builder.Command().Text("cp").
642 Input(a.htmlGzNotice).
643 Output(noticeAssetPath)
644 builder.Build("notice_dir", "Building notice dir")
645 implicitInputs = append(implicitInputs, noticeAssetPath)
646 optFlags = append(optFlags, "--assets_dir "+filepath.Dir(noticeAssetPath.String()))
Jiyong Park09d77522019-11-18 11:16:27 +0900647
Nikita Ioffe9d9960f2021-06-09 19:43:46 +0100648 if (moduleMinSdkVersion.GreaterThan(android.SdkVersion_Android10) && !a.shouldGenerateHashtree()) && !compressionEnabled {
Jiyong Park09d77522019-11-18 11:16:27 +0900649 // Apexes which are supposed to be installed in builtin dirs(/system, etc)
650 // don't need hashtree for activation. Therefore, by removing hashtree from
651 // apex bundle (filesystem image in it, to be specific), we can save storage.
652 optFlags = append(optFlags, "--no_hashtree")
653 }
654
Dario Frenica913392020-04-27 18:21:11 +0100655 if a.testOnlyShouldSkipPayloadSign() {
656 optFlags = append(optFlags, "--unsigned_payload")
657 }
658
Jiyong Park09d77522019-11-18 11:16:27 +0900659 if a.properties.Apex_name != nil {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900660 // If apex_name is set, apexer can skip checking if key name matches with
661 // apex name. Note that apex_manifest is also mended.
Jiyong Park09d77522019-11-18 11:16:27 +0900662 optFlags = append(optFlags, "--do_not_check_keyname")
663 }
664
Dan Albertc8060532020-07-22 22:32:17 -0700665 if moduleMinSdkVersion == android.SdkVersion_Android10 {
Jooyung Han214bf372019-11-12 13:03:50 +0900666 implicitInputs = append(implicitInputs, a.manifestJsonOut)
667 optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
668 }
669
Alexei Nicoara3f8cbcb2022-05-24 16:16:22 +0100670 optFlags = append(optFlags, "--apex_version "+defaultManifestVersion)
671
Theotime Combes4ba38c12020-06-12 12:46:59 +0000672 optFlags = append(optFlags, "--payload_fs_type "+a.payloadFsType.string())
673
Jiyong Park09d77522019-11-18 11:16:27 +0900674 ctx.Build(pctx, android.BuildParams{
675 Rule: apexRule,
676 Implicits: implicitInputs,
677 Output: unsignedOutputFile,
678 Description: "apex (" + apexType.name() + ")",
679 Args: map[string]string{
Oriol Prieto Gasco17e22902022-05-05 13:52:25 +0000680 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
681 "image_dir": imageDir.String(),
682 "copy_commands": strings.Join(copyCommands, " && "),
683 "manifest": a.manifestPbOut.String(),
684 "file_contexts": fileContexts.String(),
685 "canned_fs_config": cannedFsConfig.String(),
686 "key": a.privateKeyFile.String(),
687 "opt_flags": strings.Join(optFlags, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900688 },
689 })
690
Jiyong Parkb81b9902020-11-24 19:51:18 +0900691 // TODO(jiyong): make the two rules below as separate functions
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800692 apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
693 bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
Jiyong Park09d77522019-11-18 11:16:27 +0900694 a.bundleModuleFile = bundleModuleFile
695
696 ctx.Build(pctx, android.BuildParams{
697 Rule: apexProtoConvertRule,
698 Input: unsignedOutputFile,
699 Output: apexProtoFile,
700 Description: "apex proto convert",
701 })
702
sophiezc80a2b32020-11-12 16:39:19 +0000703 implicitInputs = append(implicitInputs, unsignedOutputFile)
704
705 // Run coverage analysis
sophiez6bde0b52021-01-09 01:03:42 +0000706 apisUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.txt")
sophiezc80a2b32020-11-12 16:39:19 +0000707 ctx.Build(pctx, android.BuildParams{
708 Rule: generateAPIsUsedbyApexRule,
709 Implicits: implicitInputs,
710 Description: "coverage",
711 Output: apisUsedbyOutputFile,
712 Args: map[string]string{
713 "image_dir": imageDir.String(),
714 "readelf": "${config.ClangBin}/llvm-readelf",
715 },
716 })
sophiez02347372021-11-02 17:58:02 -0700717 a.nativeApisUsedByModuleFile = apisUsedbyOutputFile
sophiez6bde0b52021-01-09 01:03:42 +0000718
sophiez02347372021-11-02 17:58:02 -0700719 var nativeLibNames []string
Colin Cross69f0a242021-02-08 16:49:57 -0800720 for _, f := range a.filesInfo {
721 if f.class == nativeSharedLib {
sophiez02347372021-11-02 17:58:02 -0700722 nativeLibNames = append(nativeLibNames, f.stem())
Colin Cross69f0a242021-02-08 16:49:57 -0800723 }
724 }
sophiez6bde0b52021-01-09 01:03:42 +0000725 apisBackedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_backing.txt")
sophiez6bde0b52021-01-09 01:03:42 +0000726 rule := android.NewRuleBuilder(pctx, ctx)
727 rule.Command().
728 Tool(android.PathForSource(ctx, "build/soong/scripts/gen_ndk_backedby_apex.sh")).
sophiez6bde0b52021-01-09 01:03:42 +0000729 Output(apisBackedbyOutputFile).
sophiez02347372021-11-02 17:58:02 -0700730 Flags(nativeLibNames)
sophiez6bde0b52021-01-09 01:03:42 +0000731 rule.Build("ndk_backedby_list", "Generate API libraries backed by Apex")
sophiez02347372021-11-02 17:58:02 -0700732 a.nativeApisBackedByModuleFile = apisBackedbyOutputFile
733
734 var javaLibOrApkPath []android.Path
735 for _, f := range a.filesInfo {
736 if f.class == javaSharedLib || f.class == app {
737 javaLibOrApkPath = append(javaLibOrApkPath, f.builtFile)
738 }
739 }
740 javaApiUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.xml")
741 javaUsedByRule := android.NewRuleBuilder(pctx, ctx)
742 javaUsedByRule.Command().
743 Tool(android.PathForSource(ctx, "build/soong/scripts/gen_java_usedby_apex.sh")).
744 BuiltTool("dexdeps").
745 Output(javaApiUsedbyOutputFile).
746 Inputs(javaLibOrApkPath)
747 javaUsedByRule.Build("java_usedby_list", "Generate Java APIs used by Apex")
748 a.javaApisUsedByModuleFile = javaApiUsedbyOutputFile
sophiezc80a2b32020-11-12 16:39:19 +0000749
Jiyong Parkbd159612020-02-28 15:22:21 +0900750 bundleConfig := a.buildBundleConfig(ctx)
751
Jiyong Parkb81b9902020-11-24 19:51:18 +0900752 var abis []string
753 for _, target := range ctx.MultiTargets() {
754 if len(target.Arch.Abi) > 0 {
755 abis = append(abis, target.Arch.Abi[0])
756 }
757 }
758
759 abis = android.FirstUniqueStrings(abis)
760
Jiyong Park09d77522019-11-18 11:16:27 +0900761 ctx.Build(pctx, android.BuildParams{
762 Rule: apexBundleRule,
763 Input: apexProtoFile,
Jiyong Parkbd159612020-02-28 15:22:21 +0900764 Implicit: bundleConfig,
Jiyong Park09d77522019-11-18 11:16:27 +0900765 Output: a.bundleModuleFile,
766 Description: "apex bundle module",
767 Args: map[string]string{
Jiyong Parkbd159612020-02-28 15:22:21 +0900768 "abi": strings.Join(abis, "."),
769 "config": bundleConfig.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900770 },
771 })
Jiyong Parkb81b9902020-11-24 19:51:18 +0900772 } else { // zipApex
Jiyong Park09d77522019-11-18 11:16:27 +0900773 ctx.Build(pctx, android.BuildParams{
774 Rule: zipApexRule,
775 Implicits: implicitInputs,
776 Output: unsignedOutputFile,
777 Description: "apex (" + apexType.name() + ")",
778 Args: map[string]string{
Oriol Prieto Gasco17e22902022-05-05 13:52:25 +0000779 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
780 "image_dir": imageDir.String(),
781 "copy_commands": strings.Join(copyCommands, " && "),
782 "manifest": a.manifestPbOut.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900783 },
784 })
785 }
786
Jiyong Parkb81b9902020-11-24 19:51:18 +0900787 ////////////////////////////////////////////////////////////////////////////////////
788 // Step 4: Sign the APEX using signapk
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000789 signedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900790
791 pem, key := a.getCertificateAndPrivateKey(ctx)
Kousik Kumar309b1c02020-05-28 06:13:33 -0700792 rule := java.Signapk
793 args := map[string]string{
Jiyong Parkb81b9902020-11-24 19:51:18 +0900794 "certificates": pem.String() + " " + key.String(),
Jooyung Han5d00f502021-07-11 07:26:22 +0900795 "flags": "-a 4096 --align-file-size", //alignment
Kousik Kumar309b1c02020-05-28 06:13:33 -0700796 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900797 implicits := android.Paths{pem, key}
Ramy Medhat16f23a42020-09-03 01:29:49 -0400798 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
Kousik Kumar309b1c02020-05-28 06:13:33 -0700799 rule = java.SignapkRE
800 args["implicits"] = strings.Join(implicits.Strings(), ",")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000801 args["outCommaList"] = signedOutputFile.String()
Kousik Kumar309b1c02020-05-28 06:13:33 -0700802 }
Jiyong Park09d77522019-11-18 11:16:27 +0900803 ctx.Build(pctx, android.BuildParams{
Kousik Kumar309b1c02020-05-28 06:13:33 -0700804 Rule: rule,
Jiyong Park09d77522019-11-18 11:16:27 +0900805 Description: "signapk",
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000806 Output: signedOutputFile,
Jiyong Park09d77522019-11-18 11:16:27 +0900807 Input: unsignedOutputFile,
Kousik Kumar309b1c02020-05-28 06:13:33 -0700808 Implicits: implicits,
809 Args: args,
Jiyong Park09d77522019-11-18 11:16:27 +0900810 })
Jooyung Hana6d36672022-02-24 13:58:07 +0900811 if suffix == imageApexSuffix {
812 a.outputApexFile = signedOutputFile
813 }
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000814 a.outputFile = signedOutputFile
815
Mohammad Samiul Islama8008f92020-12-22 10:47:50 +0000816 if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && a.testOnlyShouldForceCompression() {
817 ctx.PropertyErrorf("test_only_force_compression", "not available")
818 return
819 }
Nikita Ioffebc035882021-04-14 21:35:24 +0100820
Mohammad Samiul Islama8008f92020-12-22 10:47:50 +0000821 if apexType == imageApex && (compressionEnabled || a.testOnlyShouldForceCompression()) {
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000822 a.isCompressed = true
Samiul Islam7c02e262021-09-08 17:48:28 +0100823 unsignedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix+".unsigned")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000824
825 compressRule := android.NewRuleBuilder(pctx, ctx)
826 compressRule.Command().
827 Text("rm").
828 FlagWithOutput("-f ", unsignedCompressedOutputFile)
829 compressRule.Command().
830 BuiltTool("apex_compression_tool").
831 Flag("compress").
832 FlagWithArg("--apex_compression_tool ", outHostBinDir+":"+prebuiltSdkToolsBinDir).
833 FlagWithInput("--input ", signedOutputFile).
834 FlagWithOutput("--output ", unsignedCompressedOutputFile)
835 compressRule.Build("compressRule", "Generate unsigned compressed APEX file")
836
Samiul Islam7c02e262021-09-08 17:48:28 +0100837 signedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix)
Mohammad Samiul Islam9ac0e322021-01-19 11:32:29 +0000838 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
839 args["outCommaList"] = signedCompressedOutputFile.String()
840 }
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000841 ctx.Build(pctx, android.BuildParams{
842 Rule: rule,
843 Description: "sign compressedApex",
844 Output: signedCompressedOutputFile,
845 Input: unsignedCompressedOutputFile,
846 Implicits: implicits,
847 Args: args,
848 })
849 a.outputFile = signedCompressedOutputFile
850 }
Jiyong Park09d77522019-11-18 11:16:27 +0900851
Colin Cross6340ea52021-11-04 12:01:18 -0700852 installSuffix := suffix
853 if a.isCompressed {
854 installSuffix = imageCapexSuffix
855 }
856
Colin Crossd9ccb6a2022-03-07 18:38:34 -0800857 if !a.installable() {
858 a.SkipInstall()
859 }
860
Jiyong Park17ff2832021-09-27 12:50:30 +0900861 // Install to $OUT/soong/{target,host}/.../apex.
Colin Cross6340ea52021-11-04 12:01:18 -0700862 a.installedFile = ctx.InstallFile(a.installDir, a.Name()+installSuffix, a.outputFile,
863 a.compatSymlinks.Paths()...)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900864
865 // installed-files.txt is dist'ed
866 a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900867}
868
Jiyong Parkb81b9902020-11-24 19:51:18 +0900869// buildFlattenedApex creates rules for a flattened APEX. Flattened APEX actually doesn't have a
870// single output file. It is a phony target for all the files under /system/apex/<name> directory.
871// This function creates the installation rules for the files.
Jiyong Park09d77522019-11-18 11:16:27 +0900872func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900873 bundleName := a.Name()
Colin Cross6340ea52021-11-04 12:01:18 -0700874 installedSymlinks := append(android.InstallPaths(nil), a.compatSymlinks...)
Jiyong Park09d77522019-11-18 11:16:27 +0900875 if a.installable() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900876 for _, fi := range a.filesInfo {
877 dir := filepath.Join("apex", bundleName, fi.installDir)
Colin Cross6340ea52021-11-04 12:01:18 -0700878 installDir := android.PathForModuleInstall(ctx, dir)
879 if a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform() {
880 // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
881 pathOnDevice := filepath.Join("/system", fi.path())
882 installedSymlinks = append(installedSymlinks,
883 ctx.InstallAbsoluteSymlink(installDir, fi.stem(), pathOnDevice))
884 } else {
885 target := ctx.InstallFile(installDir, fi.stem(), fi.builtFile)
886 for _, sym := range fi.symlinks {
887 installedSymlinks = append(installedSymlinks,
888 ctx.InstallSymlink(installDir, sym, target))
889 }
Jiyong Park09d77522019-11-18 11:16:27 +0900890 }
891 }
Colin Cross6340ea52021-11-04 12:01:18 -0700892
893 // Create install rules for the files added in GenerateAndroidBuildActions after
894 // buildFlattenedApex is called. Add the links to system libs (if any) as dependencies
895 // of the apex_manifest.pb file since it is always present.
896 dir := filepath.Join("apex", bundleName)
897 installDir := android.PathForModuleInstall(ctx, dir)
898 ctx.InstallFile(installDir, "apex_manifest.pb", a.manifestPbOut, installedSymlinks.Paths()...)
899 ctx.InstallFile(installDir, "apex_pubkey", a.publicKeyFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900900 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900901
902 a.fileContexts = a.buildFileContexts(ctx)
903
Colin Cross6340ea52021-11-04 12:01:18 -0700904 a.outputFile = android.PathForModuleInstall(ctx, "apex", bundleName)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900905}
906
907// getCertificateAndPrivateKey retrieves the cert and the private key that will be used to sign
908// the zip container of this APEX. See the description of the 'certificate' property for how
909// the cert and the private key are found.
910func (a *apexBundle) getCertificateAndPrivateKey(ctx android.PathContext) (pem, key android.Path) {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800911 if a.containerCertificateFile != nil {
912 return a.containerCertificateFile, a.containerPrivateKeyFile
Jiyong Parkb81b9902020-11-24 19:51:18 +0900913 }
914
Jaewoong Jung4cfdf7d2021-04-20 16:21:24 -0700915 cert := String(a.overridableProperties.Certificate)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900916 if cert == "" {
917 return ctx.Config().DefaultAppCertificate(ctx)
918 }
919
920 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
921 pem = defaultDir.Join(ctx, cert+".x509.pem")
922 key = defaultDir.Join(ctx, cert+".pk8")
923 return pem, key
Jiyong Park09d77522019-11-18 11:16:27 +0900924}
Jooyung Han27151d92019-12-16 17:45:32 +0900925
926func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
927 // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
928 // to see if it should be overridden because their <apex name> is dynamically generated
929 // according to its VNDK version.
930 if a.vndkApex {
931 overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
932 if overridden {
933 return strings.Replace(*a.properties.Apex_name, vndkApexName, overrideName, 1)
934 }
935 return ""
936 }
Baligh Uddin5b57dba2020-03-15 13:01:05 -0700937 if a.overridableProperties.Package_name != "" {
938 return a.overridableProperties.Package_name
939 }
Jiyong Park20bacab2020-03-03 11:45:41 +0900940 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jooyung Han27151d92019-12-16 17:45:32 +0900941 if overridden {
942 return manifestPackageName
943 }
944 return ""
945}
Jiyong Park83dc74b2020-01-14 18:38:44 +0900946
947func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
948 if !a.primaryApexType {
949 return
950 }
951
952 if a.properties.IsCoverageVariant {
953 // Otherwise, we will have duplicated rules for coverage and
954 // non-coverage variants of the same APEX
955 return
956 }
957
958 if ctx.Host() {
959 // No need to generate dependency info for host variant
960 return
961 }
962
Artur Satayev872a1442020-04-27 17:08:37 +0100963 depInfos := android.DepNameToDepInfoMap{}
Jooyung Han749dc692020-04-15 11:03:39 +0900964 a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
Artur Satayev872a1442020-04-27 17:08:37 +0100965 if from.Name() == to.Name() {
966 // This can happen for cc.reuseObjTag. We are not interested in tracking this.
967 // As soon as the dependency graph crosses the APEX boundary, don't go further.
968 return !externalDep
Jiyong Park678c8812020-02-07 17:25:49 +0900969 }
Jiyong Park83dc74b2020-01-14 18:38:44 +0900970
Artur Satayev533b98c2021-03-11 18:03:42 +0000971 // Skip dependencies that are only available to APEXes; they are developed with updatability
972 // in mind and don't need manual approval.
973 if to.(android.ApexModule).NotAvailableForPlatform() {
974 return !externalDep
975 }
976
Cindy Zhou18417cb2020-12-10 07:12:38 -0800977 depTag := ctx.OtherModuleDependencyTag(to)
Artur Satayev533b98c2021-03-11 18:03:42 +0000978 // Check to see if dependency been marked to skip the dependency check
Cindy Zhou18417cb2020-12-10 07:12:38 -0800979 if skipDepCheck, ok := depTag.(android.SkipApexAllowedDependenciesCheck); ok && skipDepCheck.SkipApexAllowedDependenciesCheck() {
Cindy Zhou18417cb2020-12-10 07:12:38 -0800980 return !externalDep
981 }
982
Artur Satayev872a1442020-04-27 17:08:37 +0100983 if info, exists := depInfos[to.Name()]; exists {
984 if !android.InList(from.Name(), info.From) {
985 info.From = append(info.From, from.Name())
986 }
987 info.IsExternal = info.IsExternal && externalDep
988 depInfos[to.Name()] = info
989 } else {
Artur Satayev480e25b2020-04-27 18:53:18 +0100990 toMinSdkVersion := "(no version)"
Jiyong Park92315372021-04-02 08:45:46 +0900991 if m, ok := to.(interface {
992 MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec
993 }); ok {
994 if v := m.MinSdkVersion(ctx); !v.ApiLevel.IsNone() {
995 toMinSdkVersion = v.ApiLevel.String()
996 }
997 } else if m, ok := to.(interface{ MinSdkVersion() string }); ok {
998 // TODO(b/175678607) eliminate the use of MinSdkVersion returning
999 // string
Artur Satayev480e25b2020-04-27 18:53:18 +01001000 if v := m.MinSdkVersion(); v != "" {
1001 toMinSdkVersion = v
1002 }
1003 }
Artur Satayev872a1442020-04-27 17:08:37 +01001004 depInfos[to.Name()] = android.ApexModuleDepInfo{
Artur Satayev480e25b2020-04-27 18:53:18 +01001005 To: to.Name(),
1006 From: []string{from.Name()},
1007 IsExternal: externalDep,
1008 MinSdkVersion: toMinSdkVersion,
Artur Satayev872a1442020-04-27 17:08:37 +01001009 }
1010 }
1011
1012 // As soon as the dependency graph crosses the APEX boundary, don't go further.
1013 return !externalDep
Jiyong Park83dc74b2020-01-14 18:38:44 +09001014 })
1015
Albert Martineefabcf2022-03-21 20:11:16 +00001016 a.ApexBundleDepsInfo.BuildDepsInfoLists(ctx, a.MinSdkVersion(ctx).Raw, depInfos)
Artur Satayev872a1442020-04-27 17:08:37 +01001017
Jiyong Park83dc74b2020-01-14 18:38:44 +09001018 ctx.Build(pctx, android.BuildParams{
1019 Rule: android.Phony,
1020 Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
Artur Satayeva8bd1132020-04-27 18:07:06 +01001021 Inputs: []android.Path{
1022 a.ApexBundleDepsInfo.FullListPath(),
1023 a.ApexBundleDepsInfo.FlatListPath(),
1024 },
Jiyong Park83dc74b2020-01-14 18:38:44 +09001025 })
1026}
Colin Cross08dca382020-07-21 20:31:17 -07001027
1028func (a *apexBundle) buildLintReports(ctx android.ModuleContext) {
1029 depSetsBuilder := java.NewLintDepSetBuilder()
1030 for _, fi := range a.filesInfo {
1031 depSetsBuilder.Transitive(fi.lintDepSets)
1032 }
1033
1034 a.lintReports = java.BuildModuleLintReportZips(ctx, depSetsBuilder.Build())
1035}
Jiyong Park1b0893e2021-12-13 23:40:17 +09001036
1037func (a *apexBundle) buildCannedFsConfig(ctx android.ModuleContext) android.OutputPath {
1038 var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
1039 var executablePaths []string // this also includes dirs
1040 var appSetDirs []string
1041 appSetFiles := make(map[string]android.Path)
1042 for _, f := range a.filesInfo {
1043 pathInApex := f.path()
1044 if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
1045 executablePaths = append(executablePaths, pathInApex)
1046 for _, d := range f.dataPaths {
1047 readOnlyPaths = append(readOnlyPaths, filepath.Join(f.installDir, d.RelativeInstallPath, d.SrcPath.Rel()))
1048 }
1049 for _, s := range f.symlinks {
1050 executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
1051 }
1052 } else if f.class == appSet {
1053 appSetDirs = append(appSetDirs, f.installDir)
1054 appSetFiles[f.installDir] = f.builtFile
1055 } else {
1056 readOnlyPaths = append(readOnlyPaths, pathInApex)
1057 }
1058 dir := f.installDir
1059 for !android.InList(dir, executablePaths) && dir != "" {
1060 executablePaths = append(executablePaths, dir)
1061 dir, _ = filepath.Split(dir) // move up to the parent
1062 if len(dir) > 0 {
1063 // remove trailing slash
1064 dir = dir[:len(dir)-1]
1065 }
1066 }
1067 }
1068 sort.Strings(readOnlyPaths)
1069 sort.Strings(executablePaths)
1070 sort.Strings(appSetDirs)
1071
1072 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
1073 builder := android.NewRuleBuilder(pctx, ctx)
1074 cmd := builder.Command()
1075 cmd.Text("(")
1076 cmd.Text("echo '/ 1000 1000 0755';")
1077 for _, p := range readOnlyPaths {
1078 cmd.Textf("echo '/%s 1000 1000 0644';", p)
1079 }
1080 for _, p := range executablePaths {
1081 cmd.Textf("echo '/%s 0 2000 0755';", p)
1082 }
1083 for _, dir := range appSetDirs {
1084 cmd.Textf("echo '/%s 0 2000 0755';", dir)
1085 file := appSetFiles[dir]
1086 cmd.Text("zipinfo -1").Input(file).Textf(`| sed "s:\(.*\):/%s/\1 1000 1000 0644:";`, dir)
1087 }
Jiyong Park038e8522021-12-13 23:56:35 +09001088 // Custom fs_config is "appended" to the last so that entries from the file are preferred
1089 // over default ones set above.
1090 if a.properties.Canned_fs_config != nil {
1091 cmd.Text("cat").Input(android.PathForModuleSrc(ctx, *a.properties.Canned_fs_config))
1092 }
Jiyong Park1b0893e2021-12-13 23:40:17 +09001093 cmd.Text(")").FlagWithOutput("> ", cannedFsConfig)
1094 builder.Build("generateFsConfig", fmt.Sprintf("Generating canned fs config for %s", a.BaseModuleName()))
1095
1096 return cannedFsConfig.OutputPath
1097}