blob: 3599c5d01f6a38423e9bd0de89b4de45dab50ac0 [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 (
75 // Create a canned fs config file where all files and directories are
76 // by default set to (uid/gid/mode) = (1000/1000/0644)
77 // TODO(b/113082813) make this configurable using config.fs syntax
78 generateFsConfig = pctx.StaticRule("generateFsConfig", blueprint.RuleParams{
LaMont Jones4224c622021-08-05 20:59:17 +000079 Command: `( set -e; echo '/ 1000 1000 0755' ` +
Sasha Smundak18d98bc2020-05-27 16:36:07 -070080 `&& for i in ${ro_paths}; do echo "/$$i 1000 1000 0644"; done ` +
81 `&& for i in ${exec_paths}; do echo "/$$i 0 2000 0755"; done ` +
82 `&& ( tr ' ' '\n' <${out}.apklist | for i in ${apk_paths}; do read apk; echo "/$$i 0 2000 0755"; zipinfo -1 $$apk | sed "s:\(.*\):/$$i/\1 1000 1000 0644:"; done ) ) > ${out}`,
83 Description: "fs_config ${out}",
84 Rspfile: "$out.apklist",
85 RspfileContent: "$in",
86 }, "ro_paths", "exec_paths", "apk_paths")
Jiyong Park09d77522019-11-18 11:16:27 +090087
88 apexManifestRule = pctx.StaticRule("apexManifestRule", blueprint.RuleParams{
89 Command: `rm -f $out && ${jsonmodify} $in ` +
90 `-a provideNativeLibs ${provideNativeLibs} ` +
91 `-a requireNativeLibs ${requireNativeLibs} ` +
92 `${opt} ` +
93 `-o $out`,
94 CommandDeps: []string{"${jsonmodify}"},
95 Description: "prepare ${out}",
96 }, "provideNativeLibs", "requireNativeLibs", "opt")
97
98 stripApexManifestRule = pctx.StaticRule("stripApexManifestRule", blueprint.RuleParams{
99 Command: `rm -f $out && ${conv_apex_manifest} strip $in -o $out`,
100 CommandDeps: []string{"${conv_apex_manifest}"},
101 Description: "strip ${in}=>${out}",
102 })
103
104 pbApexManifestRule = pctx.StaticRule("pbApexManifestRule", blueprint.RuleParams{
105 Command: `rm -f $out && ${conv_apex_manifest} proto $in -o $out`,
106 CommandDeps: []string{"${conv_apex_manifest}"},
107 Description: "convert ${in}=>${out}",
108 })
109
Joe Onoratob4638c12021-10-27 15:47:06 -0700110 // TODO(b/113233103): make sure that file_contexts is as expected, i.e., validate
Jiyong Park09d77522019-11-18 11:16:27 +0900111 // against the binary policy using sefcontext_compiler -p <policy>.
112
113 // TODO(b/114327326): automate the generation of file_contexts
114 apexRule = pctx.StaticRule("apexRule", blueprint.RuleParams{
115 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
116 `(. ${out}.copy_commands) && ` +
117 `APEXER_TOOL_PATH=${tool_path} ` +
118 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900119 `--file_contexts ${file_contexts} ` +
120 `--canned_fs_config ${canned_fs_config} ` +
Dario Freni0f4ae072020-01-02 15:24:12 +0000121 `--include_build_info ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900122 `--payload_type image ` +
123 `--key ${key} ${opt_flags} ${image_dir} ${out} `,
124 CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
Huang Jianan13cac632021-08-02 15:02:17 +0800125 "${mke2fs}", "${resize2fs}", "${sefcontext_compile}", "${make_f2fs}", "${sload_f2fs}", "${make_erofs}",
Jiyong Park09d77522019-11-18 11:16:27 +0900126 "${soong_zip}", "${zipalign}", "${aapt2}", "prebuilts/sdk/current/public/android.jar"},
127 Rspfile: "${out}.copy_commands",
128 RspfileContent: "${copy_commands}",
129 Description: "APEX ${image_dir} => ${out}",
Theotime Combes4ba38c12020-06-12 12:46:59 +0000130 }, "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 +0900131
132 zipApexRule = pctx.StaticRule("zipApexRule", blueprint.RuleParams{
133 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
134 `(. ${out}.copy_commands) && ` +
135 `APEXER_TOOL_PATH=${tool_path} ` +
Jooyung Han214bf372019-11-12 13:03:50 +0900136 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900137 `--payload_type zip ` +
138 `${image_dir} ${out} `,
139 CommandDeps: []string{"${apexer}", "${merge_zips}", "${soong_zip}", "${zipalign}", "${aapt2}"},
140 Rspfile: "${out}.copy_commands",
141 RspfileContent: "${copy_commands}",
142 Description: "ZipAPEX ${image_dir} => ${out}",
Jooyung Han214bf372019-11-12 13:03:50 +0900143 }, "tool_path", "image_dir", "copy_commands", "manifest")
Jiyong Park09d77522019-11-18 11:16:27 +0900144
145 apexProtoConvertRule = pctx.AndroidStaticRule("apexProtoConvertRule",
146 blueprint.RuleParams{
147 Command: `${aapt2} convert --output-format proto $in -o $out`,
148 CommandDeps: []string{"${aapt2}"},
149 })
150
151 apexBundleRule = pctx.StaticRule("apexBundleRule", blueprint.RuleParams{
Jiyong Parkbd159612020-02-28 15:22:21 +0900152 Command: `${zip2zip} -i $in -o $out.base ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900153 `apex_payload.img:apex/${abi}.img ` +
Dario Frenida1aefe2020-03-02 21:47:09 +0000154 `apex_build_info.pb:apex/${abi}.build_info.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900155 `apex_manifest.json:root/apex_manifest.json ` +
Jiyong Park53ae3342019-12-08 02:06:24 +0900156 `apex_manifest.pb:root/apex_manifest.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900157 `AndroidManifest.xml:manifest/AndroidManifest.xml ` +
Jiyong Parkbd159612020-02-28 15:22:21 +0900158 `assets/NOTICE.html.gz:assets/NOTICE.html.gz &&` +
159 `${soong_zip} -o $out.config -C $$(dirname ${config}) -f ${config} && ` +
160 `${merge_zips} $out $out.base $out.config`,
161 CommandDeps: []string{"${zip2zip}", "${soong_zip}", "${merge_zips}"},
Jiyong Park09d77522019-11-18 11:16:27 +0900162 Description: "app bundle",
Jiyong Parkbd159612020-02-28 15:22:21 +0900163 }, "abi", "config")
Jiyong Park09d77522019-11-18 11:16:27 +0900164
165 emitApexContentRule = pctx.StaticRule("emitApexContentRule", blueprint.RuleParams{
166 Command: `rm -f ${out} && touch ${out} && (. ${out}.emit_commands)`,
167 Rspfile: "${out}.emit_commands",
168 RspfileContent: "${emit_commands}",
169 Description: "Emit APEX image content",
170 }, "emit_commands")
171
172 diffApexContentRule = pctx.StaticRule("diffApexContentRule", blueprint.RuleParams{
173 Command: `diff --unchanged-group-format='' \` +
174 `--changed-group-format='%<' \` +
Colin Cross440e0d02020-06-11 11:32:11 -0700175 `${image_content_file} ${allowed_files_file} || (` +
Jiyong Park09d77522019-11-18 11:16:27 +0900176 `echo -e "New unexpected files were added to ${apex_module_name}." ` +
177 ` "To fix the build run following command:" && ` +
Colin Cross440e0d02020-06-11 11:32:11 -0700178 `echo "system/apex/tools/update_allowed_list.sh ${allowed_files_file} ${image_content_file}" && ` +
Dan Willemsen81e43c52020-01-28 15:40:19 -0800179 `exit 1); touch ${out}`,
Colin Cross440e0d02020-06-11 11:32:11 -0700180 Description: "Diff ${image_content_file} and ${allowed_files_file}",
181 }, "image_content_file", "allowed_files_file", "apex_module_name")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900182
sophiezc80a2b32020-11-12 16:39:19 +0000183 generateAPIsUsedbyApexRule = pctx.StaticRule("generateAPIsUsedbyApexRule", blueprint.RuleParams{
184 Command: "$genNdkUsedbyApexPath ${image_dir} ${readelf} ${out}",
185 CommandDeps: []string{"${genNdkUsedbyApexPath}"},
186 Description: "Generate symbol list used by Apex",
187 }, "image_dir", "readelf")
188
Jiyong Parkb81b9902020-11-24 19:51:18 +0900189 // Don't add more rules here. Consider using android.NewRuleBuilder instead.
Jiyong Park09d77522019-11-18 11:16:27 +0900190)
191
Jiyong Parkb81b9902020-11-24 19:51:18 +0900192// buildManifest creates buile rules to modify the input apex_manifest.json to add information
193// gathered by the build system such as provided/required native libraries. Two output files having
194// different formats are generated. a.manifestJsonOut is JSON format for Q devices, and
195// a.manifest.PbOut is protobuf format for R+ devices.
196// TODO(jiyong): make this to return paths instead of directly storing the paths to apexBundle
Jiyong Park09d77522019-11-18 11:16:27 +0900197func (a *apexBundle) buildManifest(ctx android.ModuleContext, provideNativeLibs, requireNativeLibs []string) {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900198 src := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
Jiyong Park09d77522019-11-18 11:16:27 +0900199
Jiyong Parkb81b9902020-11-24 19:51:18 +0900200 // Put dependency({provide|require}NativeLibs) in apex_manifest.json
Jiyong Park09d77522019-11-18 11:16:27 +0900201 provideNativeLibs = android.SortedUniqueStrings(provideNativeLibs)
202 requireNativeLibs = android.SortedUniqueStrings(android.RemoveListFromList(requireNativeLibs, provideNativeLibs))
203
Jiyong Parkb81b9902020-11-24 19:51:18 +0900204 // APEX name can be overridden
Jiyong Park09d77522019-11-18 11:16:27 +0900205 optCommands := []string{}
206 if a.properties.Apex_name != nil {
207 optCommands = append(optCommands, "-v name "+*a.properties.Apex_name)
208 }
209
Jiyong Parkb81b9902020-11-24 19:51:18 +0900210 // Collect jniLibs. Notice that a.filesInfo is already sorted
Jooyung Han643adc42020-02-27 13:50:06 +0900211 var jniLibs []string
212 for _, fi := range a.filesInfo {
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900213 if fi.isJniLib && !android.InList(fi.stem(), jniLibs) {
214 jniLibs = append(jniLibs, fi.stem())
Jooyung Han643adc42020-02-27 13:50:06 +0900215 }
216 }
217 if len(jniLibs) > 0 {
218 optCommands = append(optCommands, "-a jniLibs "+strings.Join(jniLibs, " "))
219 }
220
Jiyong Parkb81b9902020-11-24 19:51:18 +0900221 manifestJsonFullOut := android.PathForModuleOut(ctx, "apex_manifest_full.json")
Jiyong Park09d77522019-11-18 11:16:27 +0900222 ctx.Build(pctx, android.BuildParams{
223 Rule: apexManifestRule,
Jiyong Parkb81b9902020-11-24 19:51:18 +0900224 Input: src,
Jooyung Han214bf372019-11-12 13:03:50 +0900225 Output: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900226 Args: map[string]string{
227 "provideNativeLibs": strings.Join(provideNativeLibs, " "),
228 "requireNativeLibs": strings.Join(requireNativeLibs, " "),
229 "opt": strings.Join(optCommands, " "),
230 },
231 })
232
Jiyong Parkb81b9902020-11-24 19:51:18 +0900233 // b/143654022 Q apexd can't understand newly added keys in apex_manifest.json prepare
234 // stripped-down version so that APEX modules built from R+ can be installed to Q
Dan Albertc8060532020-07-22 22:32:17 -0700235 minSdkVersion := a.minSdkVersion(ctx)
236 if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
Jooyung Han214bf372019-11-12 13:03:50 +0900237 a.manifestJsonOut = android.PathForModuleOut(ctx, "apex_manifest.json")
238 ctx.Build(pctx, android.BuildParams{
239 Rule: stripApexManifestRule,
240 Input: manifestJsonFullOut,
241 Output: a.manifestJsonOut,
242 })
243 }
Jiyong Park09d77522019-11-18 11:16:27 +0900244
Jiyong Parkb81b9902020-11-24 19:51:18 +0900245 // From R+, protobuf binary format (.pb) is the standard format for apex_manifest
Jiyong Park09d77522019-11-18 11:16:27 +0900246 a.manifestPbOut = android.PathForModuleOut(ctx, "apex_manifest.pb")
247 ctx.Build(pctx, android.BuildParams{
248 Rule: pbApexManifestRule,
Jooyung Han214bf372019-11-12 13:03:50 +0900249 Input: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900250 Output: a.manifestPbOut,
251 })
252}
253
Jiyong Parkb81b9902020-11-24 19:51:18 +0900254// buildFileContexts create build rules to append an entry for apex_manifest.pb to the file_contexts
255// file for this APEX which is either from /systme/sepolicy/apex/<apexname>-file_contexts or from
256// the file_contexts property of this APEX. This is to make sure that the manifest file is correctly
257// labeled as system_file.
258func (a *apexBundle) buildFileContexts(ctx android.ModuleContext) android.OutputPath {
Jooyung Han580eb4f2020-06-24 19:33:06 +0900259 var fileContexts android.Path
Liz Kammer37997c42021-09-14 17:53:38 -0400260 var fileContextsDir string
Jooyung Han580eb4f2020-06-24 19:33:06 +0900261 if a.properties.File_contexts == nil {
262 fileContexts = android.PathForSource(ctx, "system/sepolicy/apex", ctx.ModuleName()+"-file_contexts")
263 } else {
Liz Kammer37997c42021-09-14 17:53:38 -0400264 if m, t := android.SrcIsModuleWithTag(*a.properties.File_contexts); m != "" {
265 otherModule := android.GetModuleFromPathDep(ctx, m, t)
266 fileContextsDir = ctx.OtherModuleDir(otherModule)
267 }
Jooyung Han580eb4f2020-06-24 19:33:06 +0900268 fileContexts = android.PathForModuleSrc(ctx, *a.properties.File_contexts)
269 }
Liz Kammer37997c42021-09-14 17:53:38 -0400270 if fileContextsDir == "" {
271 fileContextsDir = filepath.Dir(fileContexts.String())
272 }
273 fileContextsDir += string(filepath.Separator)
274
Jooyung Han580eb4f2020-06-24 19:33:06 +0900275 if a.Platform() {
Liz Kammer37997c42021-09-14 17:53:38 -0400276 if !strings.HasPrefix(fileContextsDir, "system/sepolicy/") {
277 ctx.PropertyErrorf("file_contexts", "should be under system/sepolicy, but found in %q", fileContextsDir)
Jooyung Han580eb4f2020-06-24 19:33:06 +0900278 }
279 }
280 if !android.ExistentPathForSource(ctx, fileContexts.String()).Valid() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900281 ctx.PropertyErrorf("file_contexts", "cannot find file_contexts file: %q", fileContexts.String())
Jooyung Han580eb4f2020-06-24 19:33:06 +0900282 }
283
284 output := android.PathForModuleOut(ctx, "file_contexts")
Colin Crossf1a035e2020-11-16 17:32:30 -0800285 rule := android.NewRuleBuilder(pctx, ctx)
Jooyung Han7f146c02020-09-23 19:15:55 +0900286
Jiyong Parkb81b9902020-11-24 19:51:18 +0900287 switch a.properties.ApexType {
288 case imageApex:
Jooyung Han7f146c02020-09-23 19:15:55 +0900289 // remove old file
290 rule.Command().Text("rm").FlagWithOutput("-f ", output)
291 // copy file_contexts
292 rule.Command().Text("cat").Input(fileContexts).Text(">>").Output(output)
293 // new line
294 rule.Command().Text("echo").Text(">>").Output(output)
295 // force-label /apex_manifest.pb and / as system_file so that apexd can read them
296 rule.Command().Text("echo").Flag("/apex_manifest\\\\.pb u:object_r:system_file:s0").Text(">>").Output(output)
297 rule.Command().Text("echo").Flag("/ u:object_r:system_file:s0").Text(">>").Output(output)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900298 case flattenedApex:
Jooyung Han7f146c02020-09-23 19:15:55 +0900299 // For flattened apexes, install path should be prepended.
300 // File_contexts file should be emiited to make via LOCAL_FILE_CONTEXTS
301 // so that it can be merged into file_contexts.bin
302 apexPath := android.InstallPathToOnDevicePath(ctx, a.installDir.Join(ctx, a.Name()))
303 apexPath = strings.ReplaceAll(apexPath, ".", `\\.`)
304 // remove old file
305 rule.Command().Text("rm").FlagWithOutput("-f ", output)
306 // copy file_contexts
307 rule.Command().Text("awk").Text(`'/object_r/{printf("` + apexPath + `%s\n", $0)}'`).Input(fileContexts).Text(">").Output(output)
308 // new line
309 rule.Command().Text("echo").Text(">>").Output(output)
310 // force-label /apex_manifest.pb and / as system_file so that apexd can read them
311 rule.Command().Text("echo").Flag(apexPath + `/apex_manifest\\.pb u:object_r:system_file:s0`).Text(">>").Output(output)
312 rule.Command().Text("echo").Flag(apexPath + "/ u:object_r:system_file:s0").Text(">>").Output(output)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900313 default:
314 panic(fmt.Errorf("unsupported type %v", a.properties.ApexType))
Jooyung Han7f146c02020-09-23 19:15:55 +0900315 }
316
Colin Crossf1a035e2020-11-16 17:32:30 -0800317 rule.Build("file_contexts."+a.Name(), "Generate file_contexts")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900318 return output.OutputPath
Jooyung Han580eb4f2020-06-24 19:33:06 +0900319}
320
Jiyong Parkb81b9902020-11-24 19:51:18 +0900321// buildNoticeFiles creates a buile rule for aggregating notice files from the modules that
322// contributes to this APEX. The notice files are merged into a big notice file.
Jiyong Park19972c72020-01-28 20:05:29 +0900323func (a *apexBundle) buildNoticeFiles(ctx android.ModuleContext, apexFileName string) android.NoticeOutputs {
Jiyong Park9918e1a2020-03-17 19:16:40 +0900324 var noticeFiles android.Paths
325
Jooyung Han749dc692020-04-15 11:03:39 +0900326 a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
Jiyong Park9918e1a2020-03-17 19:16:40 +0900327 if externalDep {
Paul Duffinbe5a5be2020-03-30 15:54:08 +0100328 // As soon as the dependency graph crosses the APEX boundary, don't go further.
329 return false
Jiyong Park09d77522019-11-18 11:16:27 +0900330 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900331 noticeFiles = append(noticeFiles, to.NoticeFiles()...)
Paul Duffinbe5a5be2020-03-30 15:54:08 +0100332 return true
Jiyong Park9918e1a2020-03-17 19:16:40 +0900333 })
Jiyong Park09d77522019-11-18 11:16:27 +0900334
Jiyong Parkb81b9902020-11-24 19:51:18 +0900335 // TODO(jiyong): why do we need this? WalkPayloadDeps should have already covered this.
Jiyong Park41f637d2020-09-09 13:18:02 +0900336 for _, fi := range a.filesInfo {
337 noticeFiles = append(noticeFiles, fi.noticeFiles...)
338 }
339
Jiyong Park09d77522019-11-18 11:16:27 +0900340 if len(noticeFiles) == 0 {
Jiyong Park19972c72020-01-28 20:05:29 +0900341 return android.NoticeOutputs{}
Jiyong Park09d77522019-11-18 11:16:27 +0900342 }
343
Jiyong Park33c77362020-05-29 22:00:16 +0900344 return android.BuildNoticeOutput(ctx, a.installDir, apexFileName, android.SortedUniquePaths(noticeFiles))
Jiyong Park09d77522019-11-18 11:16:27 +0900345}
346
Jiyong Parkb81b9902020-11-24 19:51:18 +0900347// buildInstalledFilesFile creates a build rule for the installed-files.txt file where the list of
348// files included in this APEX is shown. The text file is dist'ed so that people can see what's
349// included in the APEX without actually downloading and extracting it.
Jiyong Park3a1602e2020-01-14 14:39:19 +0900350func (a *apexBundle) buildInstalledFilesFile(ctx android.ModuleContext, builtApex android.Path, imageDir android.Path) android.OutputPath {
351 output := android.PathForModuleOut(ctx, "installed-files.txt")
Colin Crossf1a035e2020-11-16 17:32:30 -0800352 rule := android.NewRuleBuilder(pctx, ctx)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900353 rule.Command().
354 Implicit(builtApex).
355 Text("(cd " + imageDir.String() + " ; ").
Jiyong Parkbd63a102020-02-08 12:40:05 +0900356 Text("find . \\( -type f -o -type l \\) -printf \"%s %p\\n\") ").
Jiyong Park3a1602e2020-01-14 14:39:19 +0900357 Text(" | sort -nr > ").
358 Output(output)
Colin Crossf1a035e2020-11-16 17:32:30 -0800359 rule.Build("installed-files."+a.Name(), "Installed files")
Jiyong Park3a1602e2020-01-14 14:39:19 +0900360 return output.OutputPath
361}
362
Jiyong Parkb81b9902020-11-24 19:51:18 +0900363// buildBundleConfig creates a build rule for the bundle config file that will control the bundle
364// creation process.
Jiyong Parkbd159612020-02-28 15:22:21 +0900365func (a *apexBundle) buildBundleConfig(ctx android.ModuleContext) android.OutputPath {
366 output := android.PathForModuleOut(ctx, "bundle_config.json")
367
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900368 type ApkConfig struct {
369 Package_name string `json:"package_name"`
370 Apk_path string `json:"path"`
371 }
Jiyong Parkbd159612020-02-28 15:22:21 +0900372 config := struct {
373 Compression struct {
374 Uncompressed_glob []string `json:"uncompressed_glob"`
375 } `json:"compression"`
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900376 Apex_config struct {
377 Apex_embedded_apk_config []ApkConfig `json:"apex_embedded_apk_config,omitempty"`
378 } `json:"apex_config,omitempty"`
Jiyong Parkbd159612020-02-28 15:22:21 +0900379 }{}
380
381 config.Compression.Uncompressed_glob = []string{
382 "apex_payload.img",
383 "apex_manifest.*",
384 }
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900385
Jiyong Parkb81b9902020-11-24 19:51:18 +0900386 // Collect the manifest names and paths of android apps if their manifest names are
387 // overridden.
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900388 for _, fi := range a.filesInfo {
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700389 if fi.class != app && fi.class != appSet {
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900390 continue
391 }
392 packageName := fi.overriddenPackageName
393 if packageName != "" {
394 config.Apex_config.Apex_embedded_apk_config = append(
395 config.Apex_config.Apex_embedded_apk_config,
396 ApkConfig{
397 Package_name: packageName,
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900398 Apk_path: fi.path(),
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900399 })
400 }
401 }
402
Jiyong Parkbd159612020-02-28 15:22:21 +0900403 j, err := json.Marshal(config)
404 if err != nil {
405 panic(fmt.Errorf("error while marshalling to %q: %#v", output, err))
406 }
407
Colin Crosscf371cc2020-11-13 11:48:42 -0800408 android.WriteFileRule(ctx, output, string(j))
Jiyong Parkbd159612020-02-28 15:22:21 +0900409
410 return output.OutputPath
411}
412
Jiyong Parkb81b9902020-11-24 19:51:18 +0900413// buildUnflattendApex creates build rules to build an APEX using apexer.
Jiyong Park09d77522019-11-18 11:16:27 +0900414func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext) {
Jiyong Park09d77522019-11-18 11:16:27 +0900415 apexType := a.properties.ApexType
416 suffix := apexType.suffix()
Jiyong Park09d77522019-11-18 11:16:27 +0900417
Jiyong Parkb81b9902020-11-24 19:51:18 +0900418 ////////////////////////////////////////////////////////////////////////////////////////////
419 // Step 1: copy built files to appropriate directories under the image directory
420
421 imageDir := android.PathForModuleOut(ctx, "image"+suffix)
422
423 // TODO(jiyong): use the RuleBuilder
Jiyong Park7cd10e32020-01-14 09:22:18 +0900424 var copyCommands []string
Jiyong Parkb81b9902020-11-24 19:51:18 +0900425 var implicitInputs []android.Path
Jiyong Park7cd10e32020-01-14 09:22:18 +0900426 for _, fi := range a.filesInfo {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900427 destPath := imageDir.Join(ctx, fi.path()).String()
428
429 // Prepare the destination path
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700430 destPathDir := filepath.Dir(destPath)
431 if fi.class == appSet {
432 copyCommands = append(copyCommands, "rm -rf "+destPathDir)
433 }
434 copyCommands = append(copyCommands, "mkdir -p "+destPathDir)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900435
436 // 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 {
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700443 if fi.class == appSet {
444 copyCommands = append(copyCommands,
Colin Crossffbcd1d2021-11-12 12:19:42 -0800445 fmt.Sprintf("unzip -qDD -d %s %s", destPathDir,
446 fi.module.(*java.AndroidAppSet).PackedAdditionalOutputs().String()))
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700447 } else {
448 copyCommands = append(copyCommands, "cp -f "+fi.builtFile.String()+" "+destPath)
449 }
Jiyong Park7cd10e32020-01-14 09:22:18 +0900450 implicitInputs = append(implicitInputs, fi.builtFile)
451 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900452
453 // Create additional symlinks pointing the file inside the APEX (if any). Note that
454 // this is independent from the symlink optimization.
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900455 for _, symlinkPath := range fi.symlinkPaths() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900456 symlinkDest := imageDir.Join(ctx, symlinkPath).String()
Tim Joinesc1ef1bb2020-03-18 18:00:41 +0000457 copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
Jiyong Park7cd10e32020-01-14 09:22:18 +0900458 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900459
460 // Copy the test files (if any)
Liz Kammer1c14a212020-05-12 15:26:55 -0700461 for _, d := range fi.dataPaths {
462 // 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 -0400463 relPath := d.SrcPath.Rel()
464 dataPath := d.SrcPath.String()
Liz Kammer1c14a212020-05-12 15:26:55 -0700465 if !strings.HasSuffix(dataPath, relPath) {
466 panic(fmt.Errorf("path %q does not end with %q", dataPath, relPath))
467 }
468
Jiyong Parkb81b9902020-11-24 19:51:18 +0900469 dataDest := imageDir.Join(ctx, fi.apexRelativePath(relPath), d.RelativeInstallPath).String()
Liz Kammer1c14a212020-05-12 15:26:55 -0700470
Chris Parsons216e10a2020-07-09 17:12:52 -0400471 copyCommands = append(copyCommands, "cp -f "+d.SrcPath.String()+" "+dataDest)
472 implicitInputs = append(implicitInputs, d.SrcPath)
Liz Kammer1c14a212020-05-12 15:26:55 -0700473 }
Jiyong Park09d77522019-11-18 11:16:27 +0900474 }
Jooyung Han214bf372019-11-12 13:03:50 +0900475 implicitInputs = append(implicitInputs, a.manifestPbOut)
Jiyong Park09d77522019-11-18 11:16:27 +0900476
Jiyong Parkb81b9902020-11-24 19:51:18 +0900477 ////////////////////////////////////////////////////////////////////////////////////////////
478 // Step 1.a: Write the list of files in this APEX to a txt file and compare it against
479 // the allowed list given via the allowed_files property. Build fails when the two lists
480 // differ.
481 //
482 // TODO(jiyong): consider removing this. Nobody other than com.android.apex.cts.shim.* seems
483 // to be using this at this moment. Furthermore, this looks very similar to what
484 // buildInstalledFilesFile does. At least, move this to somewhere else so that this doesn't
485 // hurt readability.
486 // TODO(jiyong): use RuleBuilder
Jooyung Han938b5932020-06-20 12:47:47 +0900487 if a.overridableProperties.Allowed_files != nil {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900488 // Build content.txt
489 var emitCommands []string
490 imageContentFile := android.PathForModuleOut(ctx, "content.txt")
491 emitCommands = append(emitCommands, "echo ./apex_manifest.pb >> "+imageContentFile.String())
492 minSdkVersion := a.minSdkVersion(ctx)
493 if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
494 emitCommands = append(emitCommands, "echo ./apex_manifest.json >> "+imageContentFile.String())
495 }
496 for _, fi := range a.filesInfo {
497 emitCommands = append(emitCommands, "echo './"+fi.path()+"' >> "+imageContentFile.String())
498 }
499 emitCommands = append(emitCommands, "sort -o "+imageContentFile.String()+" "+imageContentFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900500 ctx.Build(pctx, android.BuildParams{
501 Rule: emitApexContentRule,
502 Implicits: implicitInputs,
503 Output: imageContentFile,
504 Description: "emit apex image content",
505 Args: map[string]string{
506 "emit_commands": strings.Join(emitCommands, " && "),
507 },
508 })
509 implicitInputs = append(implicitInputs, imageContentFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900510
Jiyong Parkb81b9902020-11-24 19:51:18 +0900511 // Compare content.txt against allowed_files.
512 allowedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.overridableProperties.Allowed_files))
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800513 phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
Jiyong Park09d77522019-11-18 11:16:27 +0900514 ctx.Build(pctx, android.BuildParams{
515 Rule: diffApexContentRule,
516 Implicits: implicitInputs,
517 Output: phonyOutput,
518 Description: "diff apex image content",
519 Args: map[string]string{
Colin Cross440e0d02020-06-11 11:32:11 -0700520 "allowed_files_file": allowedFilesFile.String(),
521 "image_content_file": imageContentFile.String(),
522 "apex_module_name": a.Name(),
Jiyong Park09d77522019-11-18 11:16:27 +0900523 },
524 })
Jiyong Park09d77522019-11-18 11:16:27 +0900525 implicitInputs = append(implicitInputs, phonyOutput)
526 }
527
Jiyong Parkb81b9902020-11-24 19:51:18 +0900528 unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
Colin Cross790ef352021-10-25 19:15:55 -0700529 outHostBinDir := ctx.Config().HostToolPath(ctx, "").String()
Jiyong Park09d77522019-11-18 11:16:27 +0900530 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
531
Nikita Ioffebc035882021-04-14 21:35:24 +0100532 // Figure out if need to compress apex.
Nikita Ioffeb6ea6c22021-04-19 13:07:24 +0100533 compressionEnabled := ctx.Config().CompressedApex() && proptools.BoolDefault(a.properties.Compressible, false) && !a.testApex && !ctx.Config().UnbundledBuildApps()
Jiyong Park09d77522019-11-18 11:16:27 +0900534 if apexType == imageApex {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900535 ////////////////////////////////////////////////////////////////////////////////////
536 // Step 2: create canned_fs_config which encodes filemode,uid,gid of each files
537 // in this APEX. The file will be used by apexer in later steps.
538 // TODO(jiyong): make this as a function
539 // TODO(jiyong): use the RuleBuilder
Jiyong Park09d77522019-11-18 11:16:27 +0900540 var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
541 var executablePaths []string // this also includes dirs
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700542 var extractedAppSetPaths android.Paths
543 var extractedAppSetDirs []string
Jiyong Park09d77522019-11-18 11:16:27 +0900544 for _, f := range a.filesInfo {
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900545 pathInApex := f.path()
Jiyong Park09d77522019-11-18 11:16:27 +0900546 if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
547 executablePaths = append(executablePaths, pathInApex)
Liz Kammer1c14a212020-05-12 15:26:55 -0700548 for _, d := range f.dataPaths {
Liz Kammer0a51aa22020-07-21 11:13:17 -0700549 readOnlyPaths = append(readOnlyPaths, filepath.Join(f.installDir, d.RelativeInstallPath, d.SrcPath.Rel()))
Liz Kammer1c14a212020-05-12 15:26:55 -0700550 }
Jiyong Park09d77522019-11-18 11:16:27 +0900551 for _, s := range f.symlinks {
552 executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
553 }
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700554 } else if f.class == appSet {
555 extractedAppSetPaths = append(extractedAppSetPaths, f.builtFile)
556 extractedAppSetDirs = append(extractedAppSetDirs, f.installDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900557 } else {
558 readOnlyPaths = append(readOnlyPaths, pathInApex)
559 }
560 dir := f.installDir
561 for !android.InList(dir, executablePaths) && dir != "" {
562 executablePaths = append(executablePaths, dir)
563 dir, _ = filepath.Split(dir) // move up to the parent
564 if len(dir) > 0 {
565 // remove trailing slash
566 dir = dir[:len(dir)-1]
567 }
568 }
569 }
570 sort.Strings(readOnlyPaths)
571 sort.Strings(executablePaths)
572 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
573 ctx.Build(pctx, android.BuildParams{
574 Rule: generateFsConfig,
575 Output: cannedFsConfig,
576 Description: "generate fs config",
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700577 Inputs: extractedAppSetPaths,
Jiyong Park09d77522019-11-18 11:16:27 +0900578 Args: map[string]string{
579 "ro_paths": strings.Join(readOnlyPaths, " "),
580 "exec_paths": strings.Join(executablePaths, " "),
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700581 "apk_paths": strings.Join(extractedAppSetDirs, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900582 },
583 })
Jiyong Parkb81b9902020-11-24 19:51:18 +0900584 implicitInputs = append(implicitInputs, cannedFsConfig)
Jiyong Park09d77522019-11-18 11:16:27 +0900585
Jiyong Parkb81b9902020-11-24 19:51:18 +0900586 ////////////////////////////////////////////////////////////////////////////////////
587 // Step 3: Prepare option flags for apexer and invoke it to create an unsigned APEX.
588 // TODO(jiyong): use the RuleBuilder
Jiyong Park09d77522019-11-18 11:16:27 +0900589 optFlags := []string{}
590
Jiyong Parkb81b9902020-11-24 19:51:18 +0900591 fileContexts := a.buildFileContexts(ctx)
592 implicitInputs = append(implicitInputs, fileContexts)
593
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800594 implicitInputs = append(implicitInputs, a.privateKeyFile, a.publicKeyFile)
595 optFlags = append(optFlags, "--pubkey "+a.publicKeyFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900596
Jooyung Han27151d92019-12-16 17:45:32 +0900597 manifestPackageName := a.getOverrideManifestPackageName(ctx)
598 if manifestPackageName != "" {
Jiyong Park09d77522019-11-18 11:16:27 +0900599 optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
600 }
601
602 if a.properties.AndroidManifest != nil {
603 androidManifestFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.AndroidManifest))
604 implicitInputs = append(implicitInputs, androidManifestFile)
605 optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
606 }
607
Jiyong Parkb81b9902020-11-24 19:51:18 +0900608 // Determine target/min sdk version from the context
609 // TODO(jiyong): make this as a function
Dan Albertc8060532020-07-22 22:32:17 -0700610 moduleMinSdkVersion := a.minSdkVersion(ctx)
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100611 minSdkVersion := moduleMinSdkVersion.String()
612
Jiyong Parkb81b9902020-11-24 19:51:18 +0900613 // bundletool doesn't understand what "current" is. We need to transform it to
614 // codename
Jooyung Haned124c32021-01-26 11:43:46 +0900615 if moduleMinSdkVersion.IsCurrent() || moduleMinSdkVersion.IsNone() {
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100616 minSdkVersion = ctx.Config().DefaultAppTargetSdk(ctx).String()
Liz Kammer4854a7d2021-05-27 14:28:27 -0400617
618 if java.UseApiFingerprint(ctx) {
619 minSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
620 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
621 }
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000622 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900623 // apex module doesn't have a concept of target_sdk_version, hence for the time
624 // being targetSdkVersion == default targetSdkVersion of the branch.
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100625 targetSdkVersion := strconv.Itoa(ctx.Config().DefaultAppTargetSdk(ctx).FinalOrFutureInt())
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000626
Nikita Ioffe1f4f3452020-03-02 16:58:11 +0000627 if java.UseApiFingerprint(ctx) {
628 targetSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
Baligh Uddinf6201372020-01-24 23:15:44 +0000629 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
630 }
Jiyong Park09d77522019-11-18 11:16:27 +0900631 optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
Baligh Uddinf6201372020-01-24 23:15:44 +0000632 optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
Jiyong Park09d77522019-11-18 11:16:27 +0900633
Baligh Uddin004d7172020-02-19 21:29:28 -0800634 if a.overridableProperties.Logging_parent != "" {
635 optFlags = append(optFlags, "--logging_parent ", a.overridableProperties.Logging_parent)
636 }
637
Jiyong Park19972c72020-01-28 20:05:29 +0900638 a.mergedNotices = a.buildNoticeFiles(ctx, a.Name()+suffix)
639 if a.mergedNotices.HtmlGzOutput.Valid() {
Jiyong Park09d77522019-11-18 11:16:27 +0900640 // If there's a NOTICE file, embed it as an asset file in the APEX.
Jiyong Park19972c72020-01-28 20:05:29 +0900641 implicitInputs = append(implicitInputs, a.mergedNotices.HtmlGzOutput.Path())
642 optFlags = append(optFlags, "--assets_dir "+filepath.Dir(a.mergedNotices.HtmlGzOutput.String()))
Jiyong Park09d77522019-11-18 11:16:27 +0900643 }
644
Nikita Ioffe9d9960f2021-06-09 19:43:46 +0100645 if (moduleMinSdkVersion.GreaterThan(android.SdkVersion_Android10) && !a.shouldGenerateHashtree()) && !compressionEnabled {
Jiyong Park09d77522019-11-18 11:16:27 +0900646 // Apexes which are supposed to be installed in builtin dirs(/system, etc)
647 // don't need hashtree for activation. Therefore, by removing hashtree from
648 // apex bundle (filesystem image in it, to be specific), we can save storage.
649 optFlags = append(optFlags, "--no_hashtree")
650 }
651
Dario Frenica913392020-04-27 18:21:11 +0100652 if a.testOnlyShouldSkipPayloadSign() {
653 optFlags = append(optFlags, "--unsigned_payload")
654 }
655
Jiyong Park09d77522019-11-18 11:16:27 +0900656 if a.properties.Apex_name != nil {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900657 // If apex_name is set, apexer can skip checking if key name matches with
658 // apex name. Note that apex_manifest is also mended.
Jiyong Park09d77522019-11-18 11:16:27 +0900659 optFlags = append(optFlags, "--do_not_check_keyname")
660 }
661
Dan Albertc8060532020-07-22 22:32:17 -0700662 if moduleMinSdkVersion == android.SdkVersion_Android10 {
Jooyung Han214bf372019-11-12 13:03:50 +0900663 implicitInputs = append(implicitInputs, a.manifestJsonOut)
664 optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
665 }
666
Theotime Combes4ba38c12020-06-12 12:46:59 +0000667 optFlags = append(optFlags, "--payload_fs_type "+a.payloadFsType.string())
668
Jiyong Park09d77522019-11-18 11:16:27 +0900669 ctx.Build(pctx, android.BuildParams{
670 Rule: apexRule,
671 Implicits: implicitInputs,
672 Output: unsignedOutputFile,
673 Description: "apex (" + apexType.name() + ")",
674 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900675 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900676 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900677 "copy_commands": strings.Join(copyCommands, " && "),
678 "manifest": a.manifestPbOut.String(),
Jiyong Parkb81b9902020-11-24 19:51:18 +0900679 "file_contexts": fileContexts.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900680 "canned_fs_config": cannedFsConfig.String(),
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800681 "key": a.privateKeyFile.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900682 "opt_flags": strings.Join(optFlags, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900683 },
684 })
685
Jiyong Parkb81b9902020-11-24 19:51:18 +0900686 // TODO(jiyong): make the two rules below as separate functions
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800687 apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
688 bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
Jiyong Park09d77522019-11-18 11:16:27 +0900689 a.bundleModuleFile = bundleModuleFile
690
691 ctx.Build(pctx, android.BuildParams{
692 Rule: apexProtoConvertRule,
693 Input: unsignedOutputFile,
694 Output: apexProtoFile,
695 Description: "apex proto convert",
696 })
697
sophiezc80a2b32020-11-12 16:39:19 +0000698 implicitInputs = append(implicitInputs, unsignedOutputFile)
699
700 // Run coverage analysis
sophiez6bde0b52021-01-09 01:03:42 +0000701 apisUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.txt")
sophiezc80a2b32020-11-12 16:39:19 +0000702 ctx.Build(pctx, android.BuildParams{
703 Rule: generateAPIsUsedbyApexRule,
704 Implicits: implicitInputs,
705 Description: "coverage",
706 Output: apisUsedbyOutputFile,
707 Args: map[string]string{
708 "image_dir": imageDir.String(),
709 "readelf": "${config.ClangBin}/llvm-readelf",
710 },
711 })
sophiez02347372021-11-02 17:58:02 -0700712 a.nativeApisUsedByModuleFile = apisUsedbyOutputFile
sophiez6bde0b52021-01-09 01:03:42 +0000713
sophiez02347372021-11-02 17:58:02 -0700714 var nativeLibNames []string
Colin Cross69f0a242021-02-08 16:49:57 -0800715 for _, f := range a.filesInfo {
716 if f.class == nativeSharedLib {
sophiez02347372021-11-02 17:58:02 -0700717 nativeLibNames = append(nativeLibNames, f.stem())
Colin Cross69f0a242021-02-08 16:49:57 -0800718 }
719 }
sophiez6bde0b52021-01-09 01:03:42 +0000720 apisBackedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_backing.txt")
sophiez6bde0b52021-01-09 01:03:42 +0000721 rule := android.NewRuleBuilder(pctx, ctx)
722 rule.Command().
723 Tool(android.PathForSource(ctx, "build/soong/scripts/gen_ndk_backedby_apex.sh")).
sophiez6bde0b52021-01-09 01:03:42 +0000724 Output(apisBackedbyOutputFile).
sophiez02347372021-11-02 17:58:02 -0700725 Flags(nativeLibNames)
sophiez6bde0b52021-01-09 01:03:42 +0000726 rule.Build("ndk_backedby_list", "Generate API libraries backed by Apex")
sophiez02347372021-11-02 17:58:02 -0700727 a.nativeApisBackedByModuleFile = apisBackedbyOutputFile
728
729 var javaLibOrApkPath []android.Path
730 for _, f := range a.filesInfo {
731 if f.class == javaSharedLib || f.class == app {
732 javaLibOrApkPath = append(javaLibOrApkPath, f.builtFile)
733 }
734 }
735 javaApiUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.xml")
736 javaUsedByRule := android.NewRuleBuilder(pctx, ctx)
737 javaUsedByRule.Command().
738 Tool(android.PathForSource(ctx, "build/soong/scripts/gen_java_usedby_apex.sh")).
739 BuiltTool("dexdeps").
740 Output(javaApiUsedbyOutputFile).
741 Inputs(javaLibOrApkPath)
742 javaUsedByRule.Build("java_usedby_list", "Generate Java APIs used by Apex")
743 a.javaApisUsedByModuleFile = javaApiUsedbyOutputFile
sophiezc80a2b32020-11-12 16:39:19 +0000744
Jiyong Parkbd159612020-02-28 15:22:21 +0900745 bundleConfig := a.buildBundleConfig(ctx)
746
Jiyong Parkb81b9902020-11-24 19:51:18 +0900747 var abis []string
748 for _, target := range ctx.MultiTargets() {
749 if len(target.Arch.Abi) > 0 {
750 abis = append(abis, target.Arch.Abi[0])
751 }
752 }
753
754 abis = android.FirstUniqueStrings(abis)
755
Jiyong Park09d77522019-11-18 11:16:27 +0900756 ctx.Build(pctx, android.BuildParams{
757 Rule: apexBundleRule,
758 Input: apexProtoFile,
Jiyong Parkbd159612020-02-28 15:22:21 +0900759 Implicit: bundleConfig,
Jiyong Park09d77522019-11-18 11:16:27 +0900760 Output: a.bundleModuleFile,
761 Description: "apex bundle module",
762 Args: map[string]string{
Jiyong Parkbd159612020-02-28 15:22:21 +0900763 "abi": strings.Join(abis, "."),
764 "config": bundleConfig.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900765 },
766 })
Jiyong Parkb81b9902020-11-24 19:51:18 +0900767 } else { // zipApex
Jiyong Park09d77522019-11-18 11:16:27 +0900768 ctx.Build(pctx, android.BuildParams{
769 Rule: zipApexRule,
770 Implicits: implicitInputs,
771 Output: unsignedOutputFile,
772 Description: "apex (" + apexType.name() + ")",
773 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900774 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900775 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900776 "copy_commands": strings.Join(copyCommands, " && "),
777 "manifest": a.manifestPbOut.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900778 },
779 })
780 }
781
Jiyong Parkb81b9902020-11-24 19:51:18 +0900782 ////////////////////////////////////////////////////////////////////////////////////
783 // Step 4: Sign the APEX using signapk
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000784 signedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900785
786 pem, key := a.getCertificateAndPrivateKey(ctx)
Kousik Kumar309b1c02020-05-28 06:13:33 -0700787 rule := java.Signapk
788 args := map[string]string{
Jiyong Parkb81b9902020-11-24 19:51:18 +0900789 "certificates": pem.String() + " " + key.String(),
Jooyung Han5d00f502021-07-11 07:26:22 +0900790 "flags": "-a 4096 --align-file-size", //alignment
Kousik Kumar309b1c02020-05-28 06:13:33 -0700791 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900792 implicits := android.Paths{pem, key}
Ramy Medhat16f23a42020-09-03 01:29:49 -0400793 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
Kousik Kumar309b1c02020-05-28 06:13:33 -0700794 rule = java.SignapkRE
795 args["implicits"] = strings.Join(implicits.Strings(), ",")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000796 args["outCommaList"] = signedOutputFile.String()
Kousik Kumar309b1c02020-05-28 06:13:33 -0700797 }
Jiyong Park09d77522019-11-18 11:16:27 +0900798 ctx.Build(pctx, android.BuildParams{
Kousik Kumar309b1c02020-05-28 06:13:33 -0700799 Rule: rule,
Jiyong Park09d77522019-11-18 11:16:27 +0900800 Description: "signapk",
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000801 Output: signedOutputFile,
Jiyong Park09d77522019-11-18 11:16:27 +0900802 Input: unsignedOutputFile,
Kousik Kumar309b1c02020-05-28 06:13:33 -0700803 Implicits: implicits,
804 Args: args,
Jiyong Park09d77522019-11-18 11:16:27 +0900805 })
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000806 a.outputFile = signedOutputFile
807
Mohammad Samiul Islama8008f92020-12-22 10:47:50 +0000808 if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && a.testOnlyShouldForceCompression() {
809 ctx.PropertyErrorf("test_only_force_compression", "not available")
810 return
811 }
Nikita Ioffebc035882021-04-14 21:35:24 +0100812
Mohammad Samiul Islama8008f92020-12-22 10:47:50 +0000813 if apexType == imageApex && (compressionEnabled || a.testOnlyShouldForceCompression()) {
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000814 a.isCompressed = true
Samiul Islam7c02e262021-09-08 17:48:28 +0100815 unsignedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix+".unsigned")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000816
817 compressRule := android.NewRuleBuilder(pctx, ctx)
818 compressRule.Command().
819 Text("rm").
820 FlagWithOutput("-f ", unsignedCompressedOutputFile)
821 compressRule.Command().
822 BuiltTool("apex_compression_tool").
823 Flag("compress").
824 FlagWithArg("--apex_compression_tool ", outHostBinDir+":"+prebuiltSdkToolsBinDir).
825 FlagWithInput("--input ", signedOutputFile).
826 FlagWithOutput("--output ", unsignedCompressedOutputFile)
827 compressRule.Build("compressRule", "Generate unsigned compressed APEX file")
828
Samiul Islam7c02e262021-09-08 17:48:28 +0100829 signedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix)
Mohammad Samiul Islam9ac0e322021-01-19 11:32:29 +0000830 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
831 args["outCommaList"] = signedCompressedOutputFile.String()
832 }
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000833 ctx.Build(pctx, android.BuildParams{
834 Rule: rule,
835 Description: "sign compressedApex",
836 Output: signedCompressedOutputFile,
837 Input: unsignedCompressedOutputFile,
838 Implicits: implicits,
839 Args: args,
840 })
841 a.outputFile = signedCompressedOutputFile
842 }
Jiyong Park09d77522019-11-18 11:16:27 +0900843
Jiyong Park17ff2832021-09-27 12:50:30 +0900844 // Install to $OUT/soong/{target,host}/.../apex.
845 ctx.InstallFile(a.installDir, a.Name()+suffix, a.outputFile)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900846
847 // installed-files.txt is dist'ed
848 a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900849}
850
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900851// Context "decorator", overriding the InstallBypassMake method to always reply `true`.
852type flattenedApexContext struct {
853 android.ModuleContext
854}
855
856func (c *flattenedApexContext) InstallBypassMake() bool {
857 return true
858}
859
Jiyong Parkb81b9902020-11-24 19:51:18 +0900860// buildFlattenedApex creates rules for a flattened APEX. Flattened APEX actually doesn't have a
861// single output file. It is a phony target for all the files under /system/apex/<name> directory.
862// This function creates the installation rules for the files.
Jiyong Park09d77522019-11-18 11:16:27 +0900863func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900864 bundleName := a.Name()
Jiyong Park09d77522019-11-18 11:16:27 +0900865 if a.installable() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900866 for _, fi := range a.filesInfo {
867 dir := filepath.Join("apex", bundleName, fi.installDir)
868 target := ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.stem(), fi.builtFile)
869 for _, sym := range fi.symlinks {
870 ctx.InstallSymlink(android.PathForModuleInstall(ctx, dir), sym, target)
Jiyong Park09d77522019-11-18 11:16:27 +0900871 }
872 }
873 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900874
875 a.fileContexts = a.buildFileContexts(ctx)
876
877 // Temporarily wrap the original `ctx` into a `flattenedApexContext` to have it reply true
878 // to `InstallBypassMake()` (thus making the call `android.PathForModuleInstall` below use
879 // `android.pathForInstallInMakeDir` instead of `android.PathForOutput`) to return the
880 // correct path to the flattened APEX (as its contents is installed by Make, not Soong).
881 // TODO(jiyong): Why do we need to set outputFile for flattened APEX? We don't seem to use
882 // it and it actually points to a path that can never be built. Remove this.
883 factx := flattenedApexContext{ctx}
884 a.outputFile = android.PathForModuleInstall(&factx, "apex", bundleName)
885}
886
887// getCertificateAndPrivateKey retrieves the cert and the private key that will be used to sign
888// the zip container of this APEX. See the description of the 'certificate' property for how
889// the cert and the private key are found.
890func (a *apexBundle) getCertificateAndPrivateKey(ctx android.PathContext) (pem, key android.Path) {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800891 if a.containerCertificateFile != nil {
892 return a.containerCertificateFile, a.containerPrivateKeyFile
Jiyong Parkb81b9902020-11-24 19:51:18 +0900893 }
894
Jaewoong Jung4cfdf7d2021-04-20 16:21:24 -0700895 cert := String(a.overridableProperties.Certificate)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900896 if cert == "" {
897 return ctx.Config().DefaultAppCertificate(ctx)
898 }
899
900 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
901 pem = defaultDir.Join(ctx, cert+".x509.pem")
902 key = defaultDir.Join(ctx, cert+".pk8")
903 return pem, key
Jiyong Park09d77522019-11-18 11:16:27 +0900904}
Jooyung Han27151d92019-12-16 17:45:32 +0900905
906func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
907 // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
908 // to see if it should be overridden because their <apex name> is dynamically generated
909 // according to its VNDK version.
910 if a.vndkApex {
911 overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
912 if overridden {
913 return strings.Replace(*a.properties.Apex_name, vndkApexName, overrideName, 1)
914 }
915 return ""
916 }
Baligh Uddin5b57dba2020-03-15 13:01:05 -0700917 if a.overridableProperties.Package_name != "" {
918 return a.overridableProperties.Package_name
919 }
Jiyong Park20bacab2020-03-03 11:45:41 +0900920 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jooyung Han27151d92019-12-16 17:45:32 +0900921 if overridden {
922 return manifestPackageName
923 }
924 return ""
925}
Jiyong Park83dc74b2020-01-14 18:38:44 +0900926
927func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
928 if !a.primaryApexType {
929 return
930 }
931
932 if a.properties.IsCoverageVariant {
933 // Otherwise, we will have duplicated rules for coverage and
934 // non-coverage variants of the same APEX
935 return
936 }
937
938 if ctx.Host() {
939 // No need to generate dependency info for host variant
940 return
941 }
942
Artur Satayev872a1442020-04-27 17:08:37 +0100943 depInfos := android.DepNameToDepInfoMap{}
Jooyung Han749dc692020-04-15 11:03:39 +0900944 a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
Artur Satayev872a1442020-04-27 17:08:37 +0100945 if from.Name() == to.Name() {
946 // This can happen for cc.reuseObjTag. We are not interested in tracking this.
947 // As soon as the dependency graph crosses the APEX boundary, don't go further.
948 return !externalDep
Jiyong Park678c8812020-02-07 17:25:49 +0900949 }
Jiyong Park83dc74b2020-01-14 18:38:44 +0900950
Artur Satayev533b98c2021-03-11 18:03:42 +0000951 // Skip dependencies that are only available to APEXes; they are developed with updatability
952 // in mind and don't need manual approval.
953 if to.(android.ApexModule).NotAvailableForPlatform() {
954 return !externalDep
955 }
956
Cindy Zhou18417cb2020-12-10 07:12:38 -0800957 depTag := ctx.OtherModuleDependencyTag(to)
Artur Satayev533b98c2021-03-11 18:03:42 +0000958 // Check to see if dependency been marked to skip the dependency check
Cindy Zhou18417cb2020-12-10 07:12:38 -0800959 if skipDepCheck, ok := depTag.(android.SkipApexAllowedDependenciesCheck); ok && skipDepCheck.SkipApexAllowedDependenciesCheck() {
Cindy Zhou18417cb2020-12-10 07:12:38 -0800960 return !externalDep
961 }
962
Artur Satayev872a1442020-04-27 17:08:37 +0100963 if info, exists := depInfos[to.Name()]; exists {
964 if !android.InList(from.Name(), info.From) {
965 info.From = append(info.From, from.Name())
966 }
967 info.IsExternal = info.IsExternal && externalDep
968 depInfos[to.Name()] = info
969 } else {
Artur Satayev480e25b2020-04-27 18:53:18 +0100970 toMinSdkVersion := "(no version)"
Jiyong Park92315372021-04-02 08:45:46 +0900971 if m, ok := to.(interface {
972 MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec
973 }); ok {
974 if v := m.MinSdkVersion(ctx); !v.ApiLevel.IsNone() {
975 toMinSdkVersion = v.ApiLevel.String()
976 }
977 } else if m, ok := to.(interface{ MinSdkVersion() string }); ok {
978 // TODO(b/175678607) eliminate the use of MinSdkVersion returning
979 // string
Artur Satayev480e25b2020-04-27 18:53:18 +0100980 if v := m.MinSdkVersion(); v != "" {
981 toMinSdkVersion = v
982 }
983 }
Artur Satayev872a1442020-04-27 17:08:37 +0100984 depInfos[to.Name()] = android.ApexModuleDepInfo{
Artur Satayev480e25b2020-04-27 18:53:18 +0100985 To: to.Name(),
986 From: []string{from.Name()},
987 IsExternal: externalDep,
988 MinSdkVersion: toMinSdkVersion,
Artur Satayev872a1442020-04-27 17:08:37 +0100989 }
990 }
991
992 // As soon as the dependency graph crosses the APEX boundary, don't go further.
993 return !externalDep
Jiyong Park83dc74b2020-01-14 18:38:44 +0900994 })
995
Artur Satayev480e25b2020-04-27 18:53:18 +0100996 a.ApexBundleDepsInfo.BuildDepsInfoLists(ctx, proptools.String(a.properties.Min_sdk_version), depInfos)
Artur Satayev872a1442020-04-27 17:08:37 +0100997
Jiyong Park83dc74b2020-01-14 18:38:44 +0900998 ctx.Build(pctx, android.BuildParams{
999 Rule: android.Phony,
1000 Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
Artur Satayeva8bd1132020-04-27 18:07:06 +01001001 Inputs: []android.Path{
1002 a.ApexBundleDepsInfo.FullListPath(),
1003 a.ApexBundleDepsInfo.FlatListPath(),
1004 },
Jiyong Park83dc74b2020-01-14 18:38:44 +09001005 })
1006}
Colin Cross08dca382020-07-21 20:31:17 -07001007
1008func (a *apexBundle) buildLintReports(ctx android.ModuleContext) {
1009 depSetsBuilder := java.NewLintDepSetBuilder()
1010 for _, fi := range a.filesInfo {
1011 depSetsBuilder.Transitive(fi.lintDepSets)
1012 }
1013
1014 a.lintReports = java.BuildModuleLintReportZips(ctx, depSetsBuilder.Build())
1015}