blob: d4765d022c191fe4d064343c2530b569505aea5f [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
85 stripApexManifestRule = pctx.StaticRule("stripApexManifestRule", blueprint.RuleParams{
86 Command: `rm -f $out && ${conv_apex_manifest} strip $in -o $out`,
87 CommandDeps: []string{"${conv_apex_manifest}"},
88 Description: "strip ${in}=>${out}",
89 })
90
91 pbApexManifestRule = pctx.StaticRule("pbApexManifestRule", blueprint.RuleParams{
92 Command: `rm -f $out && ${conv_apex_manifest} proto $in -o $out`,
93 CommandDeps: []string{"${conv_apex_manifest}"},
94 Description: "convert ${in}=>${out}",
95 })
96
Joe Onoratob4638c12021-10-27 15:47:06 -070097 // TODO(b/113233103): make sure that file_contexts is as expected, i.e., validate
Jiyong Park09d77522019-11-18 11:16:27 +090098 // against the binary policy using sefcontext_compiler -p <policy>.
99
100 // TODO(b/114327326): automate the generation of file_contexts
101 apexRule = pctx.StaticRule("apexRule", blueprint.RuleParams{
102 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
103 `(. ${out}.copy_commands) && ` +
104 `APEXER_TOOL_PATH=${tool_path} ` +
105 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900106 `--file_contexts ${file_contexts} ` +
107 `--canned_fs_config ${canned_fs_config} ` +
Dario Freni0f4ae072020-01-02 15:24:12 +0000108 `--include_build_info ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900109 `--payload_type image ` +
Jingwen Chen6cb124b2022-04-19 13:58:58 +0000110 `--key ${key} ` +
111 `--apex_version_placeholder ${apex_version_placeholder} ` +
112 `${opt_flags} ${image_dir} ${out} `,
Jiyong Park09d77522019-11-18 11:16:27 +0900113 CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
Huang Jianan13cac632021-08-02 15:02:17 +0800114 "${mke2fs}", "${resize2fs}", "${sefcontext_compile}", "${make_f2fs}", "${sload_f2fs}", "${make_erofs}",
Jiyong Park09d77522019-11-18 11:16:27 +0900115 "${soong_zip}", "${zipalign}", "${aapt2}", "prebuilts/sdk/current/public/android.jar"},
116 Rspfile: "${out}.copy_commands",
117 RspfileContent: "${copy_commands}",
118 Description: "APEX ${image_dir} => ${out}",
Jingwen Chen6cb124b2022-04-19 13:58:58 +0000119 }, "tool_path", "image_dir", "copy_commands", "file_contexts", "canned_fs_config", "key", "opt_flags", "manifest", "payload_fs_type", "apex_version_placeholder")
Jiyong Park09d77522019-11-18 11:16:27 +0900120
121 zipApexRule = pctx.StaticRule("zipApexRule", blueprint.RuleParams{
122 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
123 `(. ${out}.copy_commands) && ` +
124 `APEXER_TOOL_PATH=${tool_path} ` +
Jooyung Han214bf372019-11-12 13:03:50 +0900125 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900126 `--payload_type zip ` +
Jingwen Chen6cb124b2022-04-19 13:58:58 +0000127 `--apex_version_placeholder ${apex_version_placeholder} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900128 `${image_dir} ${out} `,
129 CommandDeps: []string{"${apexer}", "${merge_zips}", "${soong_zip}", "${zipalign}", "${aapt2}"},
130 Rspfile: "${out}.copy_commands",
131 RspfileContent: "${copy_commands}",
132 Description: "ZipAPEX ${image_dir} => ${out}",
Jingwen Chen6cb124b2022-04-19 13:58:58 +0000133 }, "tool_path", "image_dir", "copy_commands", "manifest", "apex_version_placeholder")
Jiyong Park09d77522019-11-18 11:16:27 +0900134
135 apexProtoConvertRule = pctx.AndroidStaticRule("apexProtoConvertRule",
136 blueprint.RuleParams{
137 Command: `${aapt2} convert --output-format proto $in -o $out`,
138 CommandDeps: []string{"${aapt2}"},
139 })
140
141 apexBundleRule = pctx.StaticRule("apexBundleRule", blueprint.RuleParams{
Jiyong Parkbd159612020-02-28 15:22:21 +0900142 Command: `${zip2zip} -i $in -o $out.base ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900143 `apex_payload.img:apex/${abi}.img ` +
Dario Frenida1aefe2020-03-02 21:47:09 +0000144 `apex_build_info.pb:apex/${abi}.build_info.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900145 `apex_manifest.json:root/apex_manifest.json ` +
Jiyong Park53ae3342019-12-08 02:06:24 +0900146 `apex_manifest.pb:root/apex_manifest.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900147 `AndroidManifest.xml:manifest/AndroidManifest.xml ` +
Jiyong Parkbd159612020-02-28 15:22:21 +0900148 `assets/NOTICE.html.gz:assets/NOTICE.html.gz &&` +
149 `${soong_zip} -o $out.config -C $$(dirname ${config}) -f ${config} && ` +
150 `${merge_zips} $out $out.base $out.config`,
151 CommandDeps: []string{"${zip2zip}", "${soong_zip}", "${merge_zips}"},
Jiyong Park09d77522019-11-18 11:16:27 +0900152 Description: "app bundle",
Jiyong Parkbd159612020-02-28 15:22:21 +0900153 }, "abi", "config")
Jiyong Park09d77522019-11-18 11:16:27 +0900154
155 emitApexContentRule = pctx.StaticRule("emitApexContentRule", blueprint.RuleParams{
156 Command: `rm -f ${out} && touch ${out} && (. ${out}.emit_commands)`,
157 Rspfile: "${out}.emit_commands",
158 RspfileContent: "${emit_commands}",
159 Description: "Emit APEX image content",
160 }, "emit_commands")
161
162 diffApexContentRule = pctx.StaticRule("diffApexContentRule", blueprint.RuleParams{
163 Command: `diff --unchanged-group-format='' \` +
164 `--changed-group-format='%<' \` +
Colin Cross440e0d02020-06-11 11:32:11 -0700165 `${image_content_file} ${allowed_files_file} || (` +
Jiyong Park09d77522019-11-18 11:16:27 +0900166 `echo -e "New unexpected files were added to ${apex_module_name}." ` +
167 ` "To fix the build run following command:" && ` +
Colin Cross440e0d02020-06-11 11:32:11 -0700168 `echo "system/apex/tools/update_allowed_list.sh ${allowed_files_file} ${image_content_file}" && ` +
Dan Willemsen81e43c52020-01-28 15:40:19 -0800169 `exit 1); touch ${out}`,
Colin Cross440e0d02020-06-11 11:32:11 -0700170 Description: "Diff ${image_content_file} and ${allowed_files_file}",
171 }, "image_content_file", "allowed_files_file", "apex_module_name")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900172
sophiezc80a2b32020-11-12 16:39:19 +0000173 generateAPIsUsedbyApexRule = pctx.StaticRule("generateAPIsUsedbyApexRule", blueprint.RuleParams{
174 Command: "$genNdkUsedbyApexPath ${image_dir} ${readelf} ${out}",
175 CommandDeps: []string{"${genNdkUsedbyApexPath}"},
176 Description: "Generate symbol list used by Apex",
177 }, "image_dir", "readelf")
178
Jiyong Parkb81b9902020-11-24 19:51:18 +0900179 // Don't add more rules here. Consider using android.NewRuleBuilder instead.
Jiyong Park09d77522019-11-18 11:16:27 +0900180)
181
Jiyong Parkb81b9902020-11-24 19:51:18 +0900182// buildManifest creates buile rules to modify the input apex_manifest.json to add information
183// gathered by the build system such as provided/required native libraries. Two output files having
184// different formats are generated. a.manifestJsonOut is JSON format for Q devices, and
185// a.manifest.PbOut is protobuf format for R+ devices.
186// TODO(jiyong): make this to return paths instead of directly storing the paths to apexBundle
Jiyong Park09d77522019-11-18 11:16:27 +0900187func (a *apexBundle) buildManifest(ctx android.ModuleContext, provideNativeLibs, requireNativeLibs []string) {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900188 src := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
Jiyong Park09d77522019-11-18 11:16:27 +0900189
Jiyong Parkb81b9902020-11-24 19:51:18 +0900190 // Put dependency({provide|require}NativeLibs) in apex_manifest.json
Jiyong Park09d77522019-11-18 11:16:27 +0900191 provideNativeLibs = android.SortedUniqueStrings(provideNativeLibs)
192 requireNativeLibs = android.SortedUniqueStrings(android.RemoveListFromList(requireNativeLibs, provideNativeLibs))
193
Jiyong Parkb81b9902020-11-24 19:51:18 +0900194 // APEX name can be overridden
Jiyong Park09d77522019-11-18 11:16:27 +0900195 optCommands := []string{}
196 if a.properties.Apex_name != nil {
197 optCommands = append(optCommands, "-v name "+*a.properties.Apex_name)
198 }
199
Jiyong Parkb81b9902020-11-24 19:51:18 +0900200 // Collect jniLibs. Notice that a.filesInfo is already sorted
Jooyung Han643adc42020-02-27 13:50:06 +0900201 var jniLibs []string
202 for _, fi := range a.filesInfo {
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900203 if fi.isJniLib && !android.InList(fi.stem(), jniLibs) {
204 jniLibs = append(jniLibs, fi.stem())
Jooyung Han643adc42020-02-27 13:50:06 +0900205 }
206 }
207 if len(jniLibs) > 0 {
208 optCommands = append(optCommands, "-a jniLibs "+strings.Join(jniLibs, " "))
209 }
210
Jiyong Parkb81b9902020-11-24 19:51:18 +0900211 manifestJsonFullOut := android.PathForModuleOut(ctx, "apex_manifest_full.json")
Jiyong Park09d77522019-11-18 11:16:27 +0900212 ctx.Build(pctx, android.BuildParams{
213 Rule: apexManifestRule,
Jiyong Parkb81b9902020-11-24 19:51:18 +0900214 Input: src,
Jooyung Han214bf372019-11-12 13:03:50 +0900215 Output: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900216 Args: map[string]string{
217 "provideNativeLibs": strings.Join(provideNativeLibs, " "),
218 "requireNativeLibs": strings.Join(requireNativeLibs, " "),
219 "opt": strings.Join(optCommands, " "),
220 },
221 })
222
Jiyong Parkb81b9902020-11-24 19:51:18 +0900223 // b/143654022 Q apexd can't understand newly added keys in apex_manifest.json prepare
224 // stripped-down version so that APEX modules built from R+ can be installed to Q
Dan Albertc8060532020-07-22 22:32:17 -0700225 minSdkVersion := a.minSdkVersion(ctx)
226 if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
Jooyung Han214bf372019-11-12 13:03:50 +0900227 a.manifestJsonOut = android.PathForModuleOut(ctx, "apex_manifest.json")
228 ctx.Build(pctx, android.BuildParams{
229 Rule: stripApexManifestRule,
230 Input: manifestJsonFullOut,
231 Output: a.manifestJsonOut,
232 })
233 }
Jiyong Park09d77522019-11-18 11:16:27 +0900234
Jiyong Parkb81b9902020-11-24 19:51:18 +0900235 // From R+, protobuf binary format (.pb) is the standard format for apex_manifest
Jiyong Park09d77522019-11-18 11:16:27 +0900236 a.manifestPbOut = android.PathForModuleOut(ctx, "apex_manifest.pb")
237 ctx.Build(pctx, android.BuildParams{
238 Rule: pbApexManifestRule,
Jooyung Han214bf372019-11-12 13:03:50 +0900239 Input: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900240 Output: a.manifestPbOut,
241 })
242}
243
Jiyong Parkb81b9902020-11-24 19:51:18 +0900244// buildFileContexts create build rules to append an entry for apex_manifest.pb to the file_contexts
245// file for this APEX which is either from /systme/sepolicy/apex/<apexname>-file_contexts or from
246// the file_contexts property of this APEX. This is to make sure that the manifest file is correctly
247// labeled as system_file.
248func (a *apexBundle) buildFileContexts(ctx android.ModuleContext) android.OutputPath {
Jooyung Han580eb4f2020-06-24 19:33:06 +0900249 var fileContexts android.Path
Liz Kammer37997c42021-09-14 17:53:38 -0400250 var fileContextsDir string
Jooyung Han580eb4f2020-06-24 19:33:06 +0900251 if a.properties.File_contexts == nil {
252 fileContexts = android.PathForSource(ctx, "system/sepolicy/apex", ctx.ModuleName()+"-file_contexts")
253 } else {
Liz Kammer37997c42021-09-14 17:53:38 -0400254 if m, t := android.SrcIsModuleWithTag(*a.properties.File_contexts); m != "" {
255 otherModule := android.GetModuleFromPathDep(ctx, m, t)
256 fileContextsDir = ctx.OtherModuleDir(otherModule)
257 }
Jooyung Han580eb4f2020-06-24 19:33:06 +0900258 fileContexts = android.PathForModuleSrc(ctx, *a.properties.File_contexts)
259 }
Liz Kammer37997c42021-09-14 17:53:38 -0400260 if fileContextsDir == "" {
261 fileContextsDir = filepath.Dir(fileContexts.String())
262 }
263 fileContextsDir += string(filepath.Separator)
264
Jooyung Han580eb4f2020-06-24 19:33:06 +0900265 if a.Platform() {
Liz Kammer37997c42021-09-14 17:53:38 -0400266 if !strings.HasPrefix(fileContextsDir, "system/sepolicy/") {
267 ctx.PropertyErrorf("file_contexts", "should be under system/sepolicy, but found in %q", fileContextsDir)
Jooyung Han580eb4f2020-06-24 19:33:06 +0900268 }
269 }
270 if !android.ExistentPathForSource(ctx, fileContexts.String()).Valid() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900271 ctx.PropertyErrorf("file_contexts", "cannot find file_contexts file: %q", fileContexts.String())
Jooyung Han580eb4f2020-06-24 19:33:06 +0900272 }
273
274 output := android.PathForModuleOut(ctx, "file_contexts")
Colin Crossf1a035e2020-11-16 17:32:30 -0800275 rule := android.NewRuleBuilder(pctx, ctx)
Jooyung Han7f146c02020-09-23 19:15:55 +0900276
Jiyong Parkb81b9902020-11-24 19:51:18 +0900277 switch a.properties.ApexType {
278 case imageApex:
Jooyung Han7f146c02020-09-23 19:15:55 +0900279 // remove old file
280 rule.Command().Text("rm").FlagWithOutput("-f ", output)
281 // copy file_contexts
282 rule.Command().Text("cat").Input(fileContexts).Text(">>").Output(output)
283 // new line
284 rule.Command().Text("echo").Text(">>").Output(output)
285 // force-label /apex_manifest.pb and / as system_file so that apexd can read them
286 rule.Command().Text("echo").Flag("/apex_manifest\\\\.pb u:object_r:system_file:s0").Text(">>").Output(output)
287 rule.Command().Text("echo").Flag("/ u:object_r:system_file:s0").Text(">>").Output(output)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900288 case flattenedApex:
Jooyung Han7f146c02020-09-23 19:15:55 +0900289 // For flattened apexes, install path should be prepended.
290 // File_contexts file should be emiited to make via LOCAL_FILE_CONTEXTS
291 // so that it can be merged into file_contexts.bin
292 apexPath := android.InstallPathToOnDevicePath(ctx, a.installDir.Join(ctx, a.Name()))
293 apexPath = strings.ReplaceAll(apexPath, ".", `\\.`)
294 // remove old file
295 rule.Command().Text("rm").FlagWithOutput("-f ", output)
296 // copy file_contexts
297 rule.Command().Text("awk").Text(`'/object_r/{printf("` + apexPath + `%s\n", $0)}'`).Input(fileContexts).Text(">").Output(output)
298 // new line
299 rule.Command().Text("echo").Text(">>").Output(output)
300 // force-label /apex_manifest.pb and / as system_file so that apexd can read them
301 rule.Command().Text("echo").Flag(apexPath + `/apex_manifest\\.pb u:object_r:system_file:s0`).Text(">>").Output(output)
302 rule.Command().Text("echo").Flag(apexPath + "/ u:object_r:system_file:s0").Text(">>").Output(output)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900303 default:
304 panic(fmt.Errorf("unsupported type %v", a.properties.ApexType))
Jooyung Han7f146c02020-09-23 19:15:55 +0900305 }
306
Colin Crossf1a035e2020-11-16 17:32:30 -0800307 rule.Build("file_contexts."+a.Name(), "Generate file_contexts")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900308 return output.OutputPath
Jooyung Han580eb4f2020-06-24 19:33:06 +0900309}
310
Jiyong Parkb81b9902020-11-24 19:51:18 +0900311// buildInstalledFilesFile creates a build rule for the installed-files.txt file where the list of
312// files included in this APEX is shown. The text file is dist'ed so that people can see what's
313// included in the APEX without actually downloading and extracting it.
Jiyong Park3a1602e2020-01-14 14:39:19 +0900314func (a *apexBundle) buildInstalledFilesFile(ctx android.ModuleContext, builtApex android.Path, imageDir android.Path) android.OutputPath {
315 output := android.PathForModuleOut(ctx, "installed-files.txt")
Colin Crossf1a035e2020-11-16 17:32:30 -0800316 rule := android.NewRuleBuilder(pctx, ctx)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900317 rule.Command().
318 Implicit(builtApex).
319 Text("(cd " + imageDir.String() + " ; ").
Jiyong Parkbd63a102020-02-08 12:40:05 +0900320 Text("find . \\( -type f -o -type l \\) -printf \"%s %p\\n\") ").
Jiyong Park3a1602e2020-01-14 14:39:19 +0900321 Text(" | sort -nr > ").
322 Output(output)
Colin Crossf1a035e2020-11-16 17:32:30 -0800323 rule.Build("installed-files."+a.Name(), "Installed files")
Jiyong Park3a1602e2020-01-14 14:39:19 +0900324 return output.OutputPath
325}
326
Jiyong Parkb81b9902020-11-24 19:51:18 +0900327// buildBundleConfig creates a build rule for the bundle config file that will control the bundle
328// creation process.
Jiyong Parkbd159612020-02-28 15:22:21 +0900329func (a *apexBundle) buildBundleConfig(ctx android.ModuleContext) android.OutputPath {
330 output := android.PathForModuleOut(ctx, "bundle_config.json")
331
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900332 type ApkConfig struct {
333 Package_name string `json:"package_name"`
334 Apk_path string `json:"path"`
335 }
Jiyong Parkbd159612020-02-28 15:22:21 +0900336 config := struct {
337 Compression struct {
338 Uncompressed_glob []string `json:"uncompressed_glob"`
339 } `json:"compression"`
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900340 Apex_config struct {
341 Apex_embedded_apk_config []ApkConfig `json:"apex_embedded_apk_config,omitempty"`
342 } `json:"apex_config,omitempty"`
Jiyong Parkbd159612020-02-28 15:22:21 +0900343 }{}
344
345 config.Compression.Uncompressed_glob = []string{
346 "apex_payload.img",
347 "apex_manifest.*",
348 }
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900349
Jiyong Parkb81b9902020-11-24 19:51:18 +0900350 // Collect the manifest names and paths of android apps if their manifest names are
351 // overridden.
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900352 for _, fi := range a.filesInfo {
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700353 if fi.class != app && fi.class != appSet {
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900354 continue
355 }
356 packageName := fi.overriddenPackageName
357 if packageName != "" {
358 config.Apex_config.Apex_embedded_apk_config = append(
359 config.Apex_config.Apex_embedded_apk_config,
360 ApkConfig{
361 Package_name: packageName,
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900362 Apk_path: fi.path(),
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900363 })
364 }
365 }
366
Jiyong Parkbd159612020-02-28 15:22:21 +0900367 j, err := json.Marshal(config)
368 if err != nil {
369 panic(fmt.Errorf("error while marshalling to %q: %#v", output, err))
370 }
371
Colin Crosscf371cc2020-11-13 11:48:42 -0800372 android.WriteFileRule(ctx, output, string(j))
Jiyong Parkbd159612020-02-28 15:22:21 +0900373
374 return output.OutputPath
375}
376
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000377func markManifestTestOnly(ctx android.ModuleContext, androidManifestFile android.Path) android.Path {
Gurpreet Singh7deabfa2022-02-10 13:28:35 +0000378 return java.ManifestFixer(ctx, androidManifestFile, java.ManifestFixerParams{
379 TestOnly: true,
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000380 })
381}
382
Jiyong Parkb81b9902020-11-24 19:51:18 +0900383// buildUnflattendApex creates build rules to build an APEX using apexer.
Jiyong Park09d77522019-11-18 11:16:27 +0900384func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext) {
Jiyong Park09d77522019-11-18 11:16:27 +0900385 apexType := a.properties.ApexType
386 suffix := apexType.suffix()
Colin Cross6340ea52021-11-04 12:01:18 -0700387 apexName := proptools.StringDefault(a.properties.Apex_name, a.BaseModuleName())
Jiyong Park09d77522019-11-18 11:16:27 +0900388
Jiyong Parkb81b9902020-11-24 19:51:18 +0900389 ////////////////////////////////////////////////////////////////////////////////////////////
390 // Step 1: copy built files to appropriate directories under the image directory
391
392 imageDir := android.PathForModuleOut(ctx, "image"+suffix)
393
Colin Cross02730b92022-04-18 17:42:27 -0700394 installSymbolFiles := (!ctx.Config().KatiEnabled() || a.ExportedToMake()) && a.installable()
Colin Cross6340ea52021-11-04 12:01:18 -0700395
396 // b/140136207. When there are overriding APEXes for a VNDK APEX, the symbols file for the overridden
397 // APEX and the overriding APEX will have the same installation paths at /apex/com.android.vndk.v<ver>
398 // as their apexName will be the same. To avoid the path conflicts, skip installing the symbol files
399 // for the overriding VNDK APEXes.
400 if a.vndkApex && len(a.overridableProperties.Overrides) > 0 {
401 installSymbolFiles = false
402 }
403
404 // Avoid creating duplicate build rules for multi-installed APEXes.
405 if proptools.BoolDefault(a.properties.Multi_install_skip_symbol_files, false) {
406 installSymbolFiles = false
Colin Cross4acaea92021-12-10 23:05:02 +0000407
Colin Cross6340ea52021-11-04 12:01:18 -0700408 }
Colin Cross4acaea92021-12-10 23:05:02 +0000409 // set of dependency module:location mappings
410 installMapSet := make(map[string]bool)
Colin Cross6340ea52021-11-04 12:01:18 -0700411
Jiyong Parkb81b9902020-11-24 19:51:18 +0900412 // TODO(jiyong): use the RuleBuilder
Jiyong Park7cd10e32020-01-14 09:22:18 +0900413 var copyCommands []string
Jiyong Parkb81b9902020-11-24 19:51:18 +0900414 var implicitInputs []android.Path
Colin Cross6340ea52021-11-04 12:01:18 -0700415 pathWhenActivated := android.PathForModuleInPartitionInstall(ctx, "apex", apexName)
Jiyong Park7cd10e32020-01-14 09:22:18 +0900416 for _, fi := range a.filesInfo {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900417 destPath := imageDir.Join(ctx, fi.path()).String()
Jiyong Parkb81b9902020-11-24 19:51:18 +0900418 // Prepare the destination path
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700419 destPathDir := filepath.Dir(destPath)
420 if fi.class == appSet {
421 copyCommands = append(copyCommands, "rm -rf "+destPathDir)
422 }
423 copyCommands = append(copyCommands, "mkdir -p "+destPathDir)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900424
Colin Cross4acaea92021-12-10 23:05:02 +0000425 installMapPath := fi.builtFile
426
Jiyong Parkb81b9902020-11-24 19:51:18 +0900427 // Copy the built file to the directory. But if the symlink optimization is turned
428 // on, place a symlink to the corresponding file in /system partition instead.
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900429 if a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform() {
Jiyong Park7cd10e32020-01-14 09:22:18 +0900430 // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900431 pathOnDevice := filepath.Join("/system", fi.path())
Jiyong Park7cd10e32020-01-14 09:22:18 +0900432 copyCommands = append(copyCommands, "ln -sfn "+pathOnDevice+" "+destPath)
433 } else {
Colin Cross4acaea92021-12-10 23:05:02 +0000434 var installedPath android.InstallPath
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700435 if fi.class == appSet {
436 copyCommands = append(copyCommands,
Colin Crossffbcd1d2021-11-12 12:19:42 -0800437 fmt.Sprintf("unzip -qDD -d %s %s", destPathDir,
438 fi.module.(*java.AndroidAppSet).PackedAdditionalOutputs().String()))
Colin Cross6340ea52021-11-04 12:01:18 -0700439 if installSymbolFiles {
440 installedPath = ctx.InstallFileWithExtraFilesZip(pathWhenActivated.Join(ctx, fi.installDir),
441 fi.stem(), fi.builtFile, fi.module.(*java.AndroidAppSet).PackedAdditionalOutputs())
442 }
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700443 } else {
444 copyCommands = append(copyCommands, "cp -f "+fi.builtFile.String()+" "+destPath)
Colin Cross6340ea52021-11-04 12:01:18 -0700445 if installSymbolFiles {
446 installedPath = ctx.InstallFile(pathWhenActivated.Join(ctx, fi.installDir), fi.stem(), fi.builtFile)
447 }
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700448 }
Jiyong Park7cd10e32020-01-14 09:22:18 +0900449 implicitInputs = append(implicitInputs, fi.builtFile)
Colin Cross6340ea52021-11-04 12:01:18 -0700450 if installSymbolFiles {
451 implicitInputs = append(implicitInputs, installedPath)
452 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900453
Colin Cross4acaea92021-12-10 23:05:02 +0000454 // Create additional symlinks pointing the file inside the APEX (if any). Note that
455 // this is independent from the symlink optimization.
456 for _, symlinkPath := range fi.symlinkPaths() {
457 symlinkDest := imageDir.Join(ctx, symlinkPath).String()
458 copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
459 if installSymbolFiles {
460 installedSymlink := ctx.InstallSymlink(pathWhenActivated.Join(ctx, filepath.Dir(symlinkPath)), filepath.Base(symlinkPath), installedPath)
461 implicitInputs = append(implicitInputs, installedSymlink)
462 }
Colin Cross6340ea52021-11-04 12:01:18 -0700463 }
Colin Cross4acaea92021-12-10 23:05:02 +0000464
465 installMapPath = installedPath
Jiyong Park7cd10e32020-01-14 09:22:18 +0900466 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900467
468 // Copy the test files (if any)
Liz Kammer1c14a212020-05-12 15:26:55 -0700469 for _, d := range fi.dataPaths {
470 // 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 -0400471 relPath := d.SrcPath.Rel()
472 dataPath := d.SrcPath.String()
Liz Kammer1c14a212020-05-12 15:26:55 -0700473 if !strings.HasSuffix(dataPath, relPath) {
474 panic(fmt.Errorf("path %q does not end with %q", dataPath, relPath))
475 }
476
Jiyong Parkb81b9902020-11-24 19:51:18 +0900477 dataDest := imageDir.Join(ctx, fi.apexRelativePath(relPath), d.RelativeInstallPath).String()
Liz Kammer1c14a212020-05-12 15:26:55 -0700478
Chris Parsons216e10a2020-07-09 17:12:52 -0400479 copyCommands = append(copyCommands, "cp -f "+d.SrcPath.String()+" "+dataDest)
480 implicitInputs = append(implicitInputs, d.SrcPath)
Liz Kammer1c14a212020-05-12 15:26:55 -0700481 }
Colin Cross4acaea92021-12-10 23:05:02 +0000482
483 installMapSet[installMapPath.String()+":"+fi.installDir+"/"+fi.builtFile.Base()] = true
Jiyong Park09d77522019-11-18 11:16:27 +0900484 }
Jooyung Han214bf372019-11-12 13:03:50 +0900485 implicitInputs = append(implicitInputs, a.manifestPbOut)
Colin Cross6340ea52021-11-04 12:01:18 -0700486 if installSymbolFiles {
487 installedManifest := ctx.InstallFile(pathWhenActivated, "apex_manifest.pb", a.manifestPbOut)
488 installedKey := ctx.InstallFile(pathWhenActivated, "apex_pubkey", a.publicKeyFile)
489 implicitInputs = append(implicitInputs, installedManifest, installedKey)
490 }
Jiyong Park09d77522019-11-18 11:16:27 +0900491
Colin Cross4acaea92021-12-10 23:05:02 +0000492 if len(installMapSet) > 0 {
493 var installs []string
494 installs = append(installs, android.SortedStringKeys(installMapSet)...)
495 a.SetLicenseInstallMap(installs)
496 }
497
Jiyong Parkb81b9902020-11-24 19:51:18 +0900498 ////////////////////////////////////////////////////////////////////////////////////////////
499 // Step 1.a: Write the list of files in this APEX to a txt file and compare it against
500 // the allowed list given via the allowed_files property. Build fails when the two lists
501 // differ.
502 //
503 // TODO(jiyong): consider removing this. Nobody other than com.android.apex.cts.shim.* seems
504 // to be using this at this moment. Furthermore, this looks very similar to what
505 // buildInstalledFilesFile does. At least, move this to somewhere else so that this doesn't
506 // hurt readability.
507 // TODO(jiyong): use RuleBuilder
Jooyung Han938b5932020-06-20 12:47:47 +0900508 if a.overridableProperties.Allowed_files != nil {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900509 // Build content.txt
510 var emitCommands []string
511 imageContentFile := android.PathForModuleOut(ctx, "content.txt")
512 emitCommands = append(emitCommands, "echo ./apex_manifest.pb >> "+imageContentFile.String())
513 minSdkVersion := a.minSdkVersion(ctx)
514 if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
515 emitCommands = append(emitCommands, "echo ./apex_manifest.json >> "+imageContentFile.String())
516 }
517 for _, fi := range a.filesInfo {
518 emitCommands = append(emitCommands, "echo './"+fi.path()+"' >> "+imageContentFile.String())
519 }
520 emitCommands = append(emitCommands, "sort -o "+imageContentFile.String()+" "+imageContentFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900521 ctx.Build(pctx, android.BuildParams{
522 Rule: emitApexContentRule,
523 Implicits: implicitInputs,
524 Output: imageContentFile,
525 Description: "emit apex image content",
526 Args: map[string]string{
527 "emit_commands": strings.Join(emitCommands, " && "),
528 },
529 })
530 implicitInputs = append(implicitInputs, imageContentFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900531
Jiyong Parkb81b9902020-11-24 19:51:18 +0900532 // Compare content.txt against allowed_files.
533 allowedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.overridableProperties.Allowed_files))
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800534 phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
Jiyong Park09d77522019-11-18 11:16:27 +0900535 ctx.Build(pctx, android.BuildParams{
536 Rule: diffApexContentRule,
537 Implicits: implicitInputs,
538 Output: phonyOutput,
539 Description: "diff apex image content",
540 Args: map[string]string{
Colin Cross440e0d02020-06-11 11:32:11 -0700541 "allowed_files_file": allowedFilesFile.String(),
542 "image_content_file": imageContentFile.String(),
543 "apex_module_name": a.Name(),
Jiyong Park09d77522019-11-18 11:16:27 +0900544 },
545 })
Jiyong Park09d77522019-11-18 11:16:27 +0900546 implicitInputs = append(implicitInputs, phonyOutput)
547 }
548
Jiyong Parkb81b9902020-11-24 19:51:18 +0900549 unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
Colin Cross790ef352021-10-25 19:15:55 -0700550 outHostBinDir := ctx.Config().HostToolPath(ctx, "").String()
Jiyong Park09d77522019-11-18 11:16:27 +0900551 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
552
Oriol Prieto Gascoa07099d2021-10-14 15:33:41 -0400553 // Figure out if we need to compress the apex.
554 compressionEnabled := ctx.Config().CompressedApex() && proptools.BoolDefault(a.overridableProperties.Compressible, false) && !a.testApex && !ctx.Config().UnbundledBuildApps()
Jiyong Park09d77522019-11-18 11:16:27 +0900555 if apexType == imageApex {
Jiyong Park1b0893e2021-12-13 23:40:17 +0900556
Jiyong Parkb81b9902020-11-24 19:51:18 +0900557 ////////////////////////////////////////////////////////////////////////////////////
558 // Step 2: create canned_fs_config which encodes filemode,uid,gid of each files
559 // in this APEX. The file will be used by apexer in later steps.
Jiyong Park1b0893e2021-12-13 23:40:17 +0900560 cannedFsConfig := a.buildCannedFsConfig(ctx)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900561 implicitInputs = append(implicitInputs, cannedFsConfig)
Jiyong Park09d77522019-11-18 11:16:27 +0900562
Jiyong Parkb81b9902020-11-24 19:51:18 +0900563 ////////////////////////////////////////////////////////////////////////////////////
564 // Step 3: Prepare option flags for apexer and invoke it to create an unsigned APEX.
565 // TODO(jiyong): use the RuleBuilder
Jiyong Park09d77522019-11-18 11:16:27 +0900566 optFlags := []string{}
567
Jiyong Parkb81b9902020-11-24 19:51:18 +0900568 fileContexts := a.buildFileContexts(ctx)
569 implicitInputs = append(implicitInputs, fileContexts)
570
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800571 implicitInputs = append(implicitInputs, a.privateKeyFile, a.publicKeyFile)
572 optFlags = append(optFlags, "--pubkey "+a.publicKeyFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900573
Jooyung Han27151d92019-12-16 17:45:32 +0900574 manifestPackageName := a.getOverrideManifestPackageName(ctx)
575 if manifestPackageName != "" {
Jiyong Park09d77522019-11-18 11:16:27 +0900576 optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
577 }
578
579 if a.properties.AndroidManifest != nil {
580 androidManifestFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.AndroidManifest))
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000581
582 if a.testApex {
583 androidManifestFile = markManifestTestOnly(ctx, androidManifestFile)
584 }
585
Jiyong Park09d77522019-11-18 11:16:27 +0900586 implicitInputs = append(implicitInputs, androidManifestFile)
587 optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
Gurpreet Singha76f8742022-02-03 21:01:51 +0000588 } else if a.testApex {
589 optFlags = append(optFlags, "--test_only")
Jiyong Park09d77522019-11-18 11:16:27 +0900590 }
591
Jiyong Parkb81b9902020-11-24 19:51:18 +0900592 // Determine target/min sdk version from the context
593 // TODO(jiyong): make this as a function
Dan Albertc8060532020-07-22 22:32:17 -0700594 moduleMinSdkVersion := a.minSdkVersion(ctx)
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100595 minSdkVersion := moduleMinSdkVersion.String()
596
Jiyong Parkb81b9902020-11-24 19:51:18 +0900597 // bundletool doesn't understand what "current" is. We need to transform it to
598 // codename
Jooyung Haned124c32021-01-26 11:43:46 +0900599 if moduleMinSdkVersion.IsCurrent() || moduleMinSdkVersion.IsNone() {
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100600 minSdkVersion = ctx.Config().DefaultAppTargetSdk(ctx).String()
Liz Kammer4854a7d2021-05-27 14:28:27 -0400601
602 if java.UseApiFingerprint(ctx) {
603 minSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
604 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
605 }
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000606 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900607 // apex module doesn't have a concept of target_sdk_version, hence for the time
608 // being targetSdkVersion == default targetSdkVersion of the branch.
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100609 targetSdkVersion := strconv.Itoa(ctx.Config().DefaultAppTargetSdk(ctx).FinalOrFutureInt())
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000610
Nikita Ioffe1f4f3452020-03-02 16:58:11 +0000611 if java.UseApiFingerprint(ctx) {
612 targetSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
Baligh Uddinf6201372020-01-24 23:15:44 +0000613 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
614 }
Jiyong Park09d77522019-11-18 11:16:27 +0900615 optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
Baligh Uddinf6201372020-01-24 23:15:44 +0000616 optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
Jiyong Park09d77522019-11-18 11:16:27 +0900617
Baligh Uddin004d7172020-02-19 21:29:28 -0800618 if a.overridableProperties.Logging_parent != "" {
619 optFlags = append(optFlags, "--logging_parent ", a.overridableProperties.Logging_parent)
620 }
621
Bob Badourde6a0872022-04-01 18:00:00 +0000622 // Create a NOTICE file, and embed it as an asset file in the APEX.
Bob Badour2c8888e2022-04-04 16:12:21 -0700623 a.htmlGzNotice = android.PathForModuleOut(ctx, "NOTICE.html.gz")
Bob Badourde6a0872022-04-01 18:00:00 +0000624 android.BuildNoticeHtmlOutputFromLicenseMetadata(ctx, a.htmlGzNotice)
Bob Badour2c8888e2022-04-04 16:12:21 -0700625 noticeAssetPath := android.PathForModuleOut(ctx, "NOTICE", "NOTICE.html.gz")
626 builder := android.NewRuleBuilder(pctx, ctx)
627 builder.Command().Text("cp").
628 Input(a.htmlGzNotice).
629 Output(noticeAssetPath)
630 builder.Build("notice_dir", "Building notice dir")
631 implicitInputs = append(implicitInputs, noticeAssetPath)
632 optFlags = append(optFlags, "--assets_dir "+filepath.Dir(noticeAssetPath.String()))
Jiyong Park09d77522019-11-18 11:16:27 +0900633
Nikita Ioffe9d9960f2021-06-09 19:43:46 +0100634 if (moduleMinSdkVersion.GreaterThan(android.SdkVersion_Android10) && !a.shouldGenerateHashtree()) && !compressionEnabled {
Jiyong Park09d77522019-11-18 11:16:27 +0900635 // Apexes which are supposed to be installed in builtin dirs(/system, etc)
636 // don't need hashtree for activation. Therefore, by removing hashtree from
637 // apex bundle (filesystem image in it, to be specific), we can save storage.
638 optFlags = append(optFlags, "--no_hashtree")
639 }
640
Dario Frenica913392020-04-27 18:21:11 +0100641 if a.testOnlyShouldSkipPayloadSign() {
642 optFlags = append(optFlags, "--unsigned_payload")
643 }
644
Jiyong Park09d77522019-11-18 11:16:27 +0900645 if a.properties.Apex_name != nil {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900646 // If apex_name is set, apexer can skip checking if key name matches with
647 // apex name. Note that apex_manifest is also mended.
Jiyong Park09d77522019-11-18 11:16:27 +0900648 optFlags = append(optFlags, "--do_not_check_keyname")
649 }
650
Dan Albertc8060532020-07-22 22:32:17 -0700651 if moduleMinSdkVersion == android.SdkVersion_Android10 {
Jooyung Han214bf372019-11-12 13:03:50 +0900652 implicitInputs = append(implicitInputs, a.manifestJsonOut)
653 optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
654 }
655
Theotime Combes4ba38c12020-06-12 12:46:59 +0000656 optFlags = append(optFlags, "--payload_fs_type "+a.payloadFsType.string())
657
Jiyong Park09d77522019-11-18 11:16:27 +0900658 ctx.Build(pctx, android.BuildParams{
659 Rule: apexRule,
660 Implicits: implicitInputs,
661 Output: unsignedOutputFile,
662 Description: "apex (" + apexType.name() + ")",
663 Args: map[string]string{
Jingwen Chen6cb124b2022-04-19 13:58:58 +0000664 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
665 "image_dir": imageDir.String(),
666 "copy_commands": strings.Join(copyCommands, " && "),
667 "manifest": a.manifestPbOut.String(),
668 "file_contexts": fileContexts.String(),
669 "canned_fs_config": cannedFsConfig.String(),
670 "key": a.privateKeyFile.String(),
671 "opt_flags": strings.Join(optFlags, " "),
672 "apex_version_placeholder": APEX_VERSION_PLACEHOLDER,
Jiyong Park09d77522019-11-18 11:16:27 +0900673 },
674 })
675
Jiyong Parkb81b9902020-11-24 19:51:18 +0900676 // TODO(jiyong): make the two rules below as separate functions
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800677 apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
678 bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
Jiyong Park09d77522019-11-18 11:16:27 +0900679 a.bundleModuleFile = bundleModuleFile
680
681 ctx.Build(pctx, android.BuildParams{
682 Rule: apexProtoConvertRule,
683 Input: unsignedOutputFile,
684 Output: apexProtoFile,
685 Description: "apex proto convert",
686 })
687
sophiezc80a2b32020-11-12 16:39:19 +0000688 implicitInputs = append(implicitInputs, unsignedOutputFile)
689
690 // Run coverage analysis
sophiez6bde0b52021-01-09 01:03:42 +0000691 apisUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.txt")
sophiezc80a2b32020-11-12 16:39:19 +0000692 ctx.Build(pctx, android.BuildParams{
693 Rule: generateAPIsUsedbyApexRule,
694 Implicits: implicitInputs,
695 Description: "coverage",
696 Output: apisUsedbyOutputFile,
697 Args: map[string]string{
698 "image_dir": imageDir.String(),
699 "readelf": "${config.ClangBin}/llvm-readelf",
700 },
701 })
sophiez02347372021-11-02 17:58:02 -0700702 a.nativeApisUsedByModuleFile = apisUsedbyOutputFile
sophiez6bde0b52021-01-09 01:03:42 +0000703
sophiez02347372021-11-02 17:58:02 -0700704 var nativeLibNames []string
Colin Cross69f0a242021-02-08 16:49:57 -0800705 for _, f := range a.filesInfo {
706 if f.class == nativeSharedLib {
sophiez02347372021-11-02 17:58:02 -0700707 nativeLibNames = append(nativeLibNames, f.stem())
Colin Cross69f0a242021-02-08 16:49:57 -0800708 }
709 }
sophiez6bde0b52021-01-09 01:03:42 +0000710 apisBackedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_backing.txt")
sophiez6bde0b52021-01-09 01:03:42 +0000711 rule := android.NewRuleBuilder(pctx, ctx)
712 rule.Command().
713 Tool(android.PathForSource(ctx, "build/soong/scripts/gen_ndk_backedby_apex.sh")).
sophiez6bde0b52021-01-09 01:03:42 +0000714 Output(apisBackedbyOutputFile).
sophiez02347372021-11-02 17:58:02 -0700715 Flags(nativeLibNames)
sophiez6bde0b52021-01-09 01:03:42 +0000716 rule.Build("ndk_backedby_list", "Generate API libraries backed by Apex")
sophiez02347372021-11-02 17:58:02 -0700717 a.nativeApisBackedByModuleFile = apisBackedbyOutputFile
718
719 var javaLibOrApkPath []android.Path
720 for _, f := range a.filesInfo {
721 if f.class == javaSharedLib || f.class == app {
722 javaLibOrApkPath = append(javaLibOrApkPath, f.builtFile)
723 }
724 }
725 javaApiUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.xml")
726 javaUsedByRule := android.NewRuleBuilder(pctx, ctx)
727 javaUsedByRule.Command().
728 Tool(android.PathForSource(ctx, "build/soong/scripts/gen_java_usedby_apex.sh")).
729 BuiltTool("dexdeps").
730 Output(javaApiUsedbyOutputFile).
731 Inputs(javaLibOrApkPath)
732 javaUsedByRule.Build("java_usedby_list", "Generate Java APIs used by Apex")
733 a.javaApisUsedByModuleFile = javaApiUsedbyOutputFile
sophiezc80a2b32020-11-12 16:39:19 +0000734
Jiyong Parkbd159612020-02-28 15:22:21 +0900735 bundleConfig := a.buildBundleConfig(ctx)
736
Jiyong Parkb81b9902020-11-24 19:51:18 +0900737 var abis []string
738 for _, target := range ctx.MultiTargets() {
739 if len(target.Arch.Abi) > 0 {
740 abis = append(abis, target.Arch.Abi[0])
741 }
742 }
743
744 abis = android.FirstUniqueStrings(abis)
745
Jiyong Park09d77522019-11-18 11:16:27 +0900746 ctx.Build(pctx, android.BuildParams{
747 Rule: apexBundleRule,
748 Input: apexProtoFile,
Jiyong Parkbd159612020-02-28 15:22:21 +0900749 Implicit: bundleConfig,
Jiyong Park09d77522019-11-18 11:16:27 +0900750 Output: a.bundleModuleFile,
751 Description: "apex bundle module",
752 Args: map[string]string{
Jiyong Parkbd159612020-02-28 15:22:21 +0900753 "abi": strings.Join(abis, "."),
754 "config": bundleConfig.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900755 },
756 })
Jiyong Parkb81b9902020-11-24 19:51:18 +0900757 } else { // zipApex
Jiyong Park09d77522019-11-18 11:16:27 +0900758 ctx.Build(pctx, android.BuildParams{
759 Rule: zipApexRule,
760 Implicits: implicitInputs,
761 Output: unsignedOutputFile,
762 Description: "apex (" + apexType.name() + ")",
763 Args: map[string]string{
Jingwen Chen6cb124b2022-04-19 13:58:58 +0000764 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
765 "image_dir": imageDir.String(),
766 "copy_commands": strings.Join(copyCommands, " && "),
767 "manifest": a.manifestPbOut.String(),
768 "apex_version_placeholder": APEX_VERSION_PLACEHOLDER,
Jiyong Park09d77522019-11-18 11:16:27 +0900769 },
770 })
771 }
772
Jiyong Parkb81b9902020-11-24 19:51:18 +0900773 ////////////////////////////////////////////////////////////////////////////////////
774 // Step 4: Sign the APEX using signapk
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000775 signedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900776
777 pem, key := a.getCertificateAndPrivateKey(ctx)
Kousik Kumar309b1c02020-05-28 06:13:33 -0700778 rule := java.Signapk
779 args := map[string]string{
Jiyong Parkb81b9902020-11-24 19:51:18 +0900780 "certificates": pem.String() + " " + key.String(),
Jooyung Han5d00f502021-07-11 07:26:22 +0900781 "flags": "-a 4096 --align-file-size", //alignment
Kousik Kumar309b1c02020-05-28 06:13:33 -0700782 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900783 implicits := android.Paths{pem, key}
Ramy Medhat16f23a42020-09-03 01:29:49 -0400784 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
Kousik Kumar309b1c02020-05-28 06:13:33 -0700785 rule = java.SignapkRE
786 args["implicits"] = strings.Join(implicits.Strings(), ",")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000787 args["outCommaList"] = signedOutputFile.String()
Kousik Kumar309b1c02020-05-28 06:13:33 -0700788 }
Jiyong Park09d77522019-11-18 11:16:27 +0900789 ctx.Build(pctx, android.BuildParams{
Kousik Kumar309b1c02020-05-28 06:13:33 -0700790 Rule: rule,
Jiyong Park09d77522019-11-18 11:16:27 +0900791 Description: "signapk",
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000792 Output: signedOutputFile,
Jiyong Park09d77522019-11-18 11:16:27 +0900793 Input: unsignedOutputFile,
Kousik Kumar309b1c02020-05-28 06:13:33 -0700794 Implicits: implicits,
795 Args: args,
Jiyong Park09d77522019-11-18 11:16:27 +0900796 })
Jooyung Hana6d36672022-02-24 13:58:07 +0900797 if suffix == imageApexSuffix {
798 a.outputApexFile = signedOutputFile
799 }
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000800 a.outputFile = signedOutputFile
801
Mohammad Samiul Islama8008f92020-12-22 10:47:50 +0000802 if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && a.testOnlyShouldForceCompression() {
803 ctx.PropertyErrorf("test_only_force_compression", "not available")
804 return
805 }
Nikita Ioffebc035882021-04-14 21:35:24 +0100806
Mohammad Samiul Islama8008f92020-12-22 10:47:50 +0000807 if apexType == imageApex && (compressionEnabled || a.testOnlyShouldForceCompression()) {
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000808 a.isCompressed = true
Samiul Islam7c02e262021-09-08 17:48:28 +0100809 unsignedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix+".unsigned")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000810
811 compressRule := android.NewRuleBuilder(pctx, ctx)
812 compressRule.Command().
813 Text("rm").
814 FlagWithOutput("-f ", unsignedCompressedOutputFile)
815 compressRule.Command().
816 BuiltTool("apex_compression_tool").
817 Flag("compress").
818 FlagWithArg("--apex_compression_tool ", outHostBinDir+":"+prebuiltSdkToolsBinDir).
819 FlagWithInput("--input ", signedOutputFile).
820 FlagWithOutput("--output ", unsignedCompressedOutputFile)
821 compressRule.Build("compressRule", "Generate unsigned compressed APEX file")
822
Samiul Islam7c02e262021-09-08 17:48:28 +0100823 signedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix)
Mohammad Samiul Islam9ac0e322021-01-19 11:32:29 +0000824 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
825 args["outCommaList"] = signedCompressedOutputFile.String()
826 }
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000827 ctx.Build(pctx, android.BuildParams{
828 Rule: rule,
829 Description: "sign compressedApex",
830 Output: signedCompressedOutputFile,
831 Input: unsignedCompressedOutputFile,
832 Implicits: implicits,
833 Args: args,
834 })
835 a.outputFile = signedCompressedOutputFile
836 }
Jiyong Park09d77522019-11-18 11:16:27 +0900837
Colin Cross6340ea52021-11-04 12:01:18 -0700838 installSuffix := suffix
839 if a.isCompressed {
840 installSuffix = imageCapexSuffix
841 }
842
Colin Crossd9ccb6a2022-03-07 18:38:34 -0800843 if !a.installable() {
844 a.SkipInstall()
845 }
846
Jiyong Park17ff2832021-09-27 12:50:30 +0900847 // Install to $OUT/soong/{target,host}/.../apex.
Colin Cross6340ea52021-11-04 12:01:18 -0700848 a.installedFile = ctx.InstallFile(a.installDir, a.Name()+installSuffix, a.outputFile,
849 a.compatSymlinks.Paths()...)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900850
851 // installed-files.txt is dist'ed
852 a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900853}
854
Jiyong Parkb81b9902020-11-24 19:51:18 +0900855// buildFlattenedApex creates rules for a flattened APEX. Flattened APEX actually doesn't have a
856// single output file. It is a phony target for all the files under /system/apex/<name> directory.
857// This function creates the installation rules for the files.
Jiyong Park09d77522019-11-18 11:16:27 +0900858func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900859 bundleName := a.Name()
Colin Cross6340ea52021-11-04 12:01:18 -0700860 installedSymlinks := append(android.InstallPaths(nil), a.compatSymlinks...)
Jiyong Park09d77522019-11-18 11:16:27 +0900861 if a.installable() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900862 for _, fi := range a.filesInfo {
863 dir := filepath.Join("apex", bundleName, fi.installDir)
Colin Cross6340ea52021-11-04 12:01:18 -0700864 installDir := android.PathForModuleInstall(ctx, dir)
865 if a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform() {
866 // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
867 pathOnDevice := filepath.Join("/system", fi.path())
868 installedSymlinks = append(installedSymlinks,
869 ctx.InstallAbsoluteSymlink(installDir, fi.stem(), pathOnDevice))
870 } else {
871 target := ctx.InstallFile(installDir, fi.stem(), fi.builtFile)
872 for _, sym := range fi.symlinks {
873 installedSymlinks = append(installedSymlinks,
874 ctx.InstallSymlink(installDir, sym, target))
875 }
Jiyong Park09d77522019-11-18 11:16:27 +0900876 }
877 }
Colin Cross6340ea52021-11-04 12:01:18 -0700878
879 // Create install rules for the files added in GenerateAndroidBuildActions after
880 // buildFlattenedApex is called. Add the links to system libs (if any) as dependencies
881 // of the apex_manifest.pb file since it is always present.
882 dir := filepath.Join("apex", bundleName)
883 installDir := android.PathForModuleInstall(ctx, dir)
884 ctx.InstallFile(installDir, "apex_manifest.pb", a.manifestPbOut, installedSymlinks.Paths()...)
885 ctx.InstallFile(installDir, "apex_pubkey", a.publicKeyFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900886 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900887
888 a.fileContexts = a.buildFileContexts(ctx)
889
Colin Cross6340ea52021-11-04 12:01:18 -0700890 a.outputFile = android.PathForModuleInstall(ctx, "apex", bundleName)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900891}
892
893// getCertificateAndPrivateKey retrieves the cert and the private key that will be used to sign
894// the zip container of this APEX. See the description of the 'certificate' property for how
895// the cert and the private key are found.
896func (a *apexBundle) getCertificateAndPrivateKey(ctx android.PathContext) (pem, key android.Path) {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800897 if a.containerCertificateFile != nil {
898 return a.containerCertificateFile, a.containerPrivateKeyFile
Jiyong Parkb81b9902020-11-24 19:51:18 +0900899 }
900
Jaewoong Jung4cfdf7d2021-04-20 16:21:24 -0700901 cert := String(a.overridableProperties.Certificate)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900902 if cert == "" {
903 return ctx.Config().DefaultAppCertificate(ctx)
904 }
905
906 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
907 pem = defaultDir.Join(ctx, cert+".x509.pem")
908 key = defaultDir.Join(ctx, cert+".pk8")
909 return pem, key
Jiyong Park09d77522019-11-18 11:16:27 +0900910}
Jooyung Han27151d92019-12-16 17:45:32 +0900911
912func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
913 // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
914 // to see if it should be overridden because their <apex name> is dynamically generated
915 // according to its VNDK version.
916 if a.vndkApex {
917 overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
918 if overridden {
919 return strings.Replace(*a.properties.Apex_name, vndkApexName, overrideName, 1)
920 }
921 return ""
922 }
Baligh Uddin5b57dba2020-03-15 13:01:05 -0700923 if a.overridableProperties.Package_name != "" {
924 return a.overridableProperties.Package_name
925 }
Jiyong Park20bacab2020-03-03 11:45:41 +0900926 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jooyung Han27151d92019-12-16 17:45:32 +0900927 if overridden {
928 return manifestPackageName
929 }
930 return ""
931}
Jiyong Park83dc74b2020-01-14 18:38:44 +0900932
933func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
934 if !a.primaryApexType {
935 return
936 }
937
938 if a.properties.IsCoverageVariant {
939 // Otherwise, we will have duplicated rules for coverage and
940 // non-coverage variants of the same APEX
941 return
942 }
943
944 if ctx.Host() {
945 // No need to generate dependency info for host variant
946 return
947 }
948
Artur Satayev872a1442020-04-27 17:08:37 +0100949 depInfos := android.DepNameToDepInfoMap{}
Jooyung Han749dc692020-04-15 11:03:39 +0900950 a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
Artur Satayev872a1442020-04-27 17:08:37 +0100951 if from.Name() == to.Name() {
952 // This can happen for cc.reuseObjTag. We are not interested in tracking this.
953 // As soon as the dependency graph crosses the APEX boundary, don't go further.
954 return !externalDep
Jiyong Park678c8812020-02-07 17:25:49 +0900955 }
Jiyong Park83dc74b2020-01-14 18:38:44 +0900956
Artur Satayev533b98c2021-03-11 18:03:42 +0000957 // Skip dependencies that are only available to APEXes; they are developed with updatability
958 // in mind and don't need manual approval.
959 if to.(android.ApexModule).NotAvailableForPlatform() {
960 return !externalDep
961 }
962
Cindy Zhou18417cb2020-12-10 07:12:38 -0800963 depTag := ctx.OtherModuleDependencyTag(to)
Artur Satayev533b98c2021-03-11 18:03:42 +0000964 // Check to see if dependency been marked to skip the dependency check
Cindy Zhou18417cb2020-12-10 07:12:38 -0800965 if skipDepCheck, ok := depTag.(android.SkipApexAllowedDependenciesCheck); ok && skipDepCheck.SkipApexAllowedDependenciesCheck() {
Cindy Zhou18417cb2020-12-10 07:12:38 -0800966 return !externalDep
967 }
968
Artur Satayev872a1442020-04-27 17:08:37 +0100969 if info, exists := depInfos[to.Name()]; exists {
970 if !android.InList(from.Name(), info.From) {
971 info.From = append(info.From, from.Name())
972 }
973 info.IsExternal = info.IsExternal && externalDep
974 depInfos[to.Name()] = info
975 } else {
Artur Satayev480e25b2020-04-27 18:53:18 +0100976 toMinSdkVersion := "(no version)"
Jiyong Park92315372021-04-02 08:45:46 +0900977 if m, ok := to.(interface {
978 MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec
979 }); ok {
980 if v := m.MinSdkVersion(ctx); !v.ApiLevel.IsNone() {
981 toMinSdkVersion = v.ApiLevel.String()
982 }
983 } else if m, ok := to.(interface{ MinSdkVersion() string }); ok {
984 // TODO(b/175678607) eliminate the use of MinSdkVersion returning
985 // string
Artur Satayev480e25b2020-04-27 18:53:18 +0100986 if v := m.MinSdkVersion(); v != "" {
987 toMinSdkVersion = v
988 }
989 }
Artur Satayev872a1442020-04-27 17:08:37 +0100990 depInfos[to.Name()] = android.ApexModuleDepInfo{
Artur Satayev480e25b2020-04-27 18:53:18 +0100991 To: to.Name(),
992 From: []string{from.Name()},
993 IsExternal: externalDep,
994 MinSdkVersion: toMinSdkVersion,
Artur Satayev872a1442020-04-27 17:08:37 +0100995 }
996 }
997
998 // As soon as the dependency graph crosses the APEX boundary, don't go further.
999 return !externalDep
Jiyong Park83dc74b2020-01-14 18:38:44 +09001000 })
1001
Albert Martineefabcf2022-03-21 20:11:16 +00001002 a.ApexBundleDepsInfo.BuildDepsInfoLists(ctx, a.MinSdkVersion(ctx).Raw, depInfos)
Artur Satayev872a1442020-04-27 17:08:37 +01001003
Jiyong Park83dc74b2020-01-14 18:38:44 +09001004 ctx.Build(pctx, android.BuildParams{
1005 Rule: android.Phony,
1006 Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
Artur Satayeva8bd1132020-04-27 18:07:06 +01001007 Inputs: []android.Path{
1008 a.ApexBundleDepsInfo.FullListPath(),
1009 a.ApexBundleDepsInfo.FlatListPath(),
1010 },
Jiyong Park83dc74b2020-01-14 18:38:44 +09001011 })
1012}
Colin Cross08dca382020-07-21 20:31:17 -07001013
1014func (a *apexBundle) buildLintReports(ctx android.ModuleContext) {
1015 depSetsBuilder := java.NewLintDepSetBuilder()
1016 for _, fi := range a.filesInfo {
1017 depSetsBuilder.Transitive(fi.lintDepSets)
1018 }
1019
1020 a.lintReports = java.BuildModuleLintReportZips(ctx, depSetsBuilder.Build())
1021}
Jiyong Park1b0893e2021-12-13 23:40:17 +09001022
1023func (a *apexBundle) buildCannedFsConfig(ctx android.ModuleContext) android.OutputPath {
1024 var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
1025 var executablePaths []string // this also includes dirs
1026 var appSetDirs []string
1027 appSetFiles := make(map[string]android.Path)
1028 for _, f := range a.filesInfo {
1029 pathInApex := f.path()
1030 if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
1031 executablePaths = append(executablePaths, pathInApex)
1032 for _, d := range f.dataPaths {
1033 readOnlyPaths = append(readOnlyPaths, filepath.Join(f.installDir, d.RelativeInstallPath, d.SrcPath.Rel()))
1034 }
1035 for _, s := range f.symlinks {
1036 executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
1037 }
1038 } else if f.class == appSet {
1039 appSetDirs = append(appSetDirs, f.installDir)
1040 appSetFiles[f.installDir] = f.builtFile
1041 } else {
1042 readOnlyPaths = append(readOnlyPaths, pathInApex)
1043 }
1044 dir := f.installDir
1045 for !android.InList(dir, executablePaths) && dir != "" {
1046 executablePaths = append(executablePaths, dir)
1047 dir, _ = filepath.Split(dir) // move up to the parent
1048 if len(dir) > 0 {
1049 // remove trailing slash
1050 dir = dir[:len(dir)-1]
1051 }
1052 }
1053 }
1054 sort.Strings(readOnlyPaths)
1055 sort.Strings(executablePaths)
1056 sort.Strings(appSetDirs)
1057
1058 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
1059 builder := android.NewRuleBuilder(pctx, ctx)
1060 cmd := builder.Command()
1061 cmd.Text("(")
1062 cmd.Text("echo '/ 1000 1000 0755';")
1063 for _, p := range readOnlyPaths {
1064 cmd.Textf("echo '/%s 1000 1000 0644';", p)
1065 }
1066 for _, p := range executablePaths {
1067 cmd.Textf("echo '/%s 0 2000 0755';", p)
1068 }
1069 for _, dir := range appSetDirs {
1070 cmd.Textf("echo '/%s 0 2000 0755';", dir)
1071 file := appSetFiles[dir]
1072 cmd.Text("zipinfo -1").Input(file).Textf(`| sed "s:\(.*\):/%s/\1 1000 1000 0644:";`, dir)
1073 }
Jiyong Park038e8522021-12-13 23:56:35 +09001074 // Custom fs_config is "appended" to the last so that entries from the file are preferred
1075 // over default ones set above.
1076 if a.properties.Canned_fs_config != nil {
1077 cmd.Text("cat").Input(android.PathForModuleSrc(ctx, *a.properties.Canned_fs_config))
1078 }
Jiyong Park1b0893e2021-12-13 23:40:17 +09001079 cmd.Text(")").FlagWithOutput("> ", cannedFsConfig)
1080 builder.Build("generateFsConfig", fmt.Sprintf("Generating canned fs config for %s", a.BaseModuleName()))
1081
1082 return cannedFsConfig.OutputPath
1083}