blob: 772f7897a3b175c3bd2166a10bfc1d5815baef91 [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")
sophiezc80a2b32020-11-12 16:39:19 +000070 pctx.SourcePathVariable("genNdkUsedbyApexPath", "build/soong/scripts/gen_ndk_usedby_apex.sh")
Jiyong Park09d77522019-11-18 11:16:27 +090071}
72
73var (
74 // Create a canned fs config file where all files and directories are
75 // by default set to (uid/gid/mode) = (1000/1000/0644)
76 // TODO(b/113082813) make this configurable using config.fs syntax
77 generateFsConfig = pctx.StaticRule("generateFsConfig", blueprint.RuleParams{
LaMont Jones4224c622021-08-05 20:59:17 +000078 Command: `( set -e; echo '/ 1000 1000 0755' ` +
Sasha Smundak18d98bc2020-05-27 16:36:07 -070079 `&& for i in ${ro_paths}; do echo "/$$i 1000 1000 0644"; done ` +
80 `&& for i in ${exec_paths}; do echo "/$$i 0 2000 0755"; done ` +
81 `&& ( 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}`,
82 Description: "fs_config ${out}",
83 Rspfile: "$out.apklist",
84 RspfileContent: "$in",
85 }, "ro_paths", "exec_paths", "apk_paths")
Jiyong Park09d77522019-11-18 11:16:27 +090086
87 apexManifestRule = pctx.StaticRule("apexManifestRule", blueprint.RuleParams{
88 Command: `rm -f $out && ${jsonmodify} $in ` +
89 `-a provideNativeLibs ${provideNativeLibs} ` +
90 `-a requireNativeLibs ${requireNativeLibs} ` +
91 `${opt} ` +
92 `-o $out`,
93 CommandDeps: []string{"${jsonmodify}"},
94 Description: "prepare ${out}",
95 }, "provideNativeLibs", "requireNativeLibs", "opt")
96
97 stripApexManifestRule = pctx.StaticRule("stripApexManifestRule", blueprint.RuleParams{
98 Command: `rm -f $out && ${conv_apex_manifest} strip $in -o $out`,
99 CommandDeps: []string{"${conv_apex_manifest}"},
100 Description: "strip ${in}=>${out}",
101 })
102
103 pbApexManifestRule = pctx.StaticRule("pbApexManifestRule", blueprint.RuleParams{
104 Command: `rm -f $out && ${conv_apex_manifest} proto $in -o $out`,
105 CommandDeps: []string{"${conv_apex_manifest}"},
106 Description: "convert ${in}=>${out}",
107 })
108
109 // TODO(b/113233103): make sure that file_contexts is sane, i.e., validate
110 // against the binary policy using sefcontext_compiler -p <policy>.
111
112 // TODO(b/114327326): automate the generation of file_contexts
113 apexRule = pctx.StaticRule("apexRule", blueprint.RuleParams{
114 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
115 `(. ${out}.copy_commands) && ` +
116 `APEXER_TOOL_PATH=${tool_path} ` +
117 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900118 `--file_contexts ${file_contexts} ` +
119 `--canned_fs_config ${canned_fs_config} ` +
Dario Freni0f4ae072020-01-02 15:24:12 +0000120 `--include_build_info ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900121 `--payload_type image ` +
122 `--key ${key} ${opt_flags} ${image_dir} ${out} `,
123 CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
Huang Jianan13cac632021-08-02 15:02:17 +0800124 "${mke2fs}", "${resize2fs}", "${sefcontext_compile}", "${make_f2fs}", "${sload_f2fs}", "${make_erofs}",
Jiyong Park09d77522019-11-18 11:16:27 +0900125 "${soong_zip}", "${zipalign}", "${aapt2}", "prebuilts/sdk/current/public/android.jar"},
126 Rspfile: "${out}.copy_commands",
127 RspfileContent: "${copy_commands}",
128 Description: "APEX ${image_dir} => ${out}",
Theotime Combes4ba38c12020-06-12 12:46:59 +0000129 }, "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 +0900130
131 zipApexRule = pctx.StaticRule("zipApexRule", blueprint.RuleParams{
132 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
133 `(. ${out}.copy_commands) && ` +
134 `APEXER_TOOL_PATH=${tool_path} ` +
Jooyung Han214bf372019-11-12 13:03:50 +0900135 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900136 `--payload_type zip ` +
137 `${image_dir} ${out} `,
138 CommandDeps: []string{"${apexer}", "${merge_zips}", "${soong_zip}", "${zipalign}", "${aapt2}"},
139 Rspfile: "${out}.copy_commands",
140 RspfileContent: "${copy_commands}",
141 Description: "ZipAPEX ${image_dir} => ${out}",
Jooyung Han214bf372019-11-12 13:03:50 +0900142 }, "tool_path", "image_dir", "copy_commands", "manifest")
Jiyong Park09d77522019-11-18 11:16:27 +0900143
144 apexProtoConvertRule = pctx.AndroidStaticRule("apexProtoConvertRule",
145 blueprint.RuleParams{
146 Command: `${aapt2} convert --output-format proto $in -o $out`,
147 CommandDeps: []string{"${aapt2}"},
148 })
149
150 apexBundleRule = pctx.StaticRule("apexBundleRule", blueprint.RuleParams{
Jiyong Parkbd159612020-02-28 15:22:21 +0900151 Command: `${zip2zip} -i $in -o $out.base ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900152 `apex_payload.img:apex/${abi}.img ` +
Dario Frenida1aefe2020-03-02 21:47:09 +0000153 `apex_build_info.pb:apex/${abi}.build_info.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900154 `apex_manifest.json:root/apex_manifest.json ` +
Jiyong Park53ae3342019-12-08 02:06:24 +0900155 `apex_manifest.pb:root/apex_manifest.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900156 `AndroidManifest.xml:manifest/AndroidManifest.xml ` +
Jiyong Parkbd159612020-02-28 15:22:21 +0900157 `assets/NOTICE.html.gz:assets/NOTICE.html.gz &&` +
158 `${soong_zip} -o $out.config -C $$(dirname ${config}) -f ${config} && ` +
159 `${merge_zips} $out $out.base $out.config`,
160 CommandDeps: []string{"${zip2zip}", "${soong_zip}", "${merge_zips}"},
Jiyong Park09d77522019-11-18 11:16:27 +0900161 Description: "app bundle",
Jiyong Parkbd159612020-02-28 15:22:21 +0900162 }, "abi", "config")
Jiyong Park09d77522019-11-18 11:16:27 +0900163
164 emitApexContentRule = pctx.StaticRule("emitApexContentRule", blueprint.RuleParams{
165 Command: `rm -f ${out} && touch ${out} && (. ${out}.emit_commands)`,
166 Rspfile: "${out}.emit_commands",
167 RspfileContent: "${emit_commands}",
168 Description: "Emit APEX image content",
169 }, "emit_commands")
170
171 diffApexContentRule = pctx.StaticRule("diffApexContentRule", blueprint.RuleParams{
172 Command: `diff --unchanged-group-format='' \` +
173 `--changed-group-format='%<' \` +
Colin Cross440e0d02020-06-11 11:32:11 -0700174 `${image_content_file} ${allowed_files_file} || (` +
Jiyong Park09d77522019-11-18 11:16:27 +0900175 `echo -e "New unexpected files were added to ${apex_module_name}." ` +
176 ` "To fix the build run following command:" && ` +
Colin Cross440e0d02020-06-11 11:32:11 -0700177 `echo "system/apex/tools/update_allowed_list.sh ${allowed_files_file} ${image_content_file}" && ` +
Dan Willemsen81e43c52020-01-28 15:40:19 -0800178 `exit 1); touch ${out}`,
Colin Cross440e0d02020-06-11 11:32:11 -0700179 Description: "Diff ${image_content_file} and ${allowed_files_file}",
180 }, "image_content_file", "allowed_files_file", "apex_module_name")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900181
sophiezc80a2b32020-11-12 16:39:19 +0000182 generateAPIsUsedbyApexRule = pctx.StaticRule("generateAPIsUsedbyApexRule", blueprint.RuleParams{
183 Command: "$genNdkUsedbyApexPath ${image_dir} ${readelf} ${out}",
184 CommandDeps: []string{"${genNdkUsedbyApexPath}"},
185 Description: "Generate symbol list used by Apex",
186 }, "image_dir", "readelf")
187
Jiyong Parkb81b9902020-11-24 19:51:18 +0900188 // Don't add more rules here. Consider using android.NewRuleBuilder instead.
Jiyong Park09d77522019-11-18 11:16:27 +0900189)
190
Jiyong Parkb81b9902020-11-24 19:51:18 +0900191// buildManifest creates buile rules to modify the input apex_manifest.json to add information
192// gathered by the build system such as provided/required native libraries. Two output files having
193// different formats are generated. a.manifestJsonOut is JSON format for Q devices, and
194// a.manifest.PbOut is protobuf format for R+ devices.
195// TODO(jiyong): make this to return paths instead of directly storing the paths to apexBundle
Jiyong Park09d77522019-11-18 11:16:27 +0900196func (a *apexBundle) buildManifest(ctx android.ModuleContext, provideNativeLibs, requireNativeLibs []string) {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900197 src := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
Jiyong Park09d77522019-11-18 11:16:27 +0900198
Jiyong Parkb81b9902020-11-24 19:51:18 +0900199 // Put dependency({provide|require}NativeLibs) in apex_manifest.json
Jiyong Park09d77522019-11-18 11:16:27 +0900200 provideNativeLibs = android.SortedUniqueStrings(provideNativeLibs)
201 requireNativeLibs = android.SortedUniqueStrings(android.RemoveListFromList(requireNativeLibs, provideNativeLibs))
202
Jiyong Parkb81b9902020-11-24 19:51:18 +0900203 // APEX name can be overridden
Jiyong Park09d77522019-11-18 11:16:27 +0900204 optCommands := []string{}
205 if a.properties.Apex_name != nil {
206 optCommands = append(optCommands, "-v name "+*a.properties.Apex_name)
207 }
208
Jiyong Parkb81b9902020-11-24 19:51:18 +0900209 // Collect jniLibs. Notice that a.filesInfo is already sorted
Jooyung Han643adc42020-02-27 13:50:06 +0900210 var jniLibs []string
211 for _, fi := range a.filesInfo {
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900212 if fi.isJniLib && !android.InList(fi.stem(), jniLibs) {
213 jniLibs = append(jniLibs, fi.stem())
Jooyung Han643adc42020-02-27 13:50:06 +0900214 }
215 }
216 if len(jniLibs) > 0 {
217 optCommands = append(optCommands, "-a jniLibs "+strings.Join(jniLibs, " "))
218 }
219
Jiyong Parkb81b9902020-11-24 19:51:18 +0900220 manifestJsonFullOut := android.PathForModuleOut(ctx, "apex_manifest_full.json")
Jiyong Park09d77522019-11-18 11:16:27 +0900221 ctx.Build(pctx, android.BuildParams{
222 Rule: apexManifestRule,
Jiyong Parkb81b9902020-11-24 19:51:18 +0900223 Input: src,
Jooyung Han214bf372019-11-12 13:03:50 +0900224 Output: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900225 Args: map[string]string{
226 "provideNativeLibs": strings.Join(provideNativeLibs, " "),
227 "requireNativeLibs": strings.Join(requireNativeLibs, " "),
228 "opt": strings.Join(optCommands, " "),
229 },
230 })
231
Jiyong Parkb81b9902020-11-24 19:51:18 +0900232 // b/143654022 Q apexd can't understand newly added keys in apex_manifest.json prepare
233 // stripped-down version so that APEX modules built from R+ can be installed to Q
Dan Albertc8060532020-07-22 22:32:17 -0700234 minSdkVersion := a.minSdkVersion(ctx)
235 if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
Jooyung Han214bf372019-11-12 13:03:50 +0900236 a.manifestJsonOut = android.PathForModuleOut(ctx, "apex_manifest.json")
237 ctx.Build(pctx, android.BuildParams{
238 Rule: stripApexManifestRule,
239 Input: manifestJsonFullOut,
240 Output: a.manifestJsonOut,
241 })
242 }
Jiyong Park09d77522019-11-18 11:16:27 +0900243
Jiyong Parkb81b9902020-11-24 19:51:18 +0900244 // From R+, protobuf binary format (.pb) is the standard format for apex_manifest
Jiyong Park09d77522019-11-18 11:16:27 +0900245 a.manifestPbOut = android.PathForModuleOut(ctx, "apex_manifest.pb")
246 ctx.Build(pctx, android.BuildParams{
247 Rule: pbApexManifestRule,
Jooyung Han214bf372019-11-12 13:03:50 +0900248 Input: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900249 Output: a.manifestPbOut,
250 })
251}
252
Jiyong Parkb81b9902020-11-24 19:51:18 +0900253// buildFileContexts create build rules to append an entry for apex_manifest.pb to the file_contexts
254// file for this APEX which is either from /systme/sepolicy/apex/<apexname>-file_contexts or from
255// the file_contexts property of this APEX. This is to make sure that the manifest file is correctly
256// labeled as system_file.
257func (a *apexBundle) buildFileContexts(ctx android.ModuleContext) android.OutputPath {
Jooyung Han580eb4f2020-06-24 19:33:06 +0900258 var fileContexts android.Path
Liz Kammer37997c42021-09-14 17:53:38 -0400259 var fileContextsDir string
Jooyung Han580eb4f2020-06-24 19:33:06 +0900260 if a.properties.File_contexts == nil {
261 fileContexts = android.PathForSource(ctx, "system/sepolicy/apex", ctx.ModuleName()+"-file_contexts")
262 } else {
Liz Kammer37997c42021-09-14 17:53:38 -0400263 if m, t := android.SrcIsModuleWithTag(*a.properties.File_contexts); m != "" {
264 otherModule := android.GetModuleFromPathDep(ctx, m, t)
265 fileContextsDir = ctx.OtherModuleDir(otherModule)
266 }
Jooyung Han580eb4f2020-06-24 19:33:06 +0900267 fileContexts = android.PathForModuleSrc(ctx, *a.properties.File_contexts)
268 }
Liz Kammer37997c42021-09-14 17:53:38 -0400269 if fileContextsDir == "" {
270 fileContextsDir = filepath.Dir(fileContexts.String())
271 }
272 fileContextsDir += string(filepath.Separator)
273
Jooyung Han580eb4f2020-06-24 19:33:06 +0900274 if a.Platform() {
Liz Kammer37997c42021-09-14 17:53:38 -0400275 if !strings.HasPrefix(fileContextsDir, "system/sepolicy/") {
276 ctx.PropertyErrorf("file_contexts", "should be under system/sepolicy, but found in %q", fileContextsDir)
Jooyung Han580eb4f2020-06-24 19:33:06 +0900277 }
278 }
279 if !android.ExistentPathForSource(ctx, fileContexts.String()).Valid() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900280 ctx.PropertyErrorf("file_contexts", "cannot find file_contexts file: %q", fileContexts.String())
Jooyung Han580eb4f2020-06-24 19:33:06 +0900281 }
282
283 output := android.PathForModuleOut(ctx, "file_contexts")
Colin Crossf1a035e2020-11-16 17:32:30 -0800284 rule := android.NewRuleBuilder(pctx, ctx)
Jooyung Han7f146c02020-09-23 19:15:55 +0900285
Jiyong Parkb81b9902020-11-24 19:51:18 +0900286 switch a.properties.ApexType {
287 case imageApex:
Jooyung Han7f146c02020-09-23 19:15:55 +0900288 // remove old file
289 rule.Command().Text("rm").FlagWithOutput("-f ", output)
290 // copy file_contexts
291 rule.Command().Text("cat").Input(fileContexts).Text(">>").Output(output)
292 // new line
293 rule.Command().Text("echo").Text(">>").Output(output)
294 // force-label /apex_manifest.pb and / as system_file so that apexd can read them
295 rule.Command().Text("echo").Flag("/apex_manifest\\\\.pb u:object_r:system_file:s0").Text(">>").Output(output)
296 rule.Command().Text("echo").Flag("/ u:object_r:system_file:s0").Text(">>").Output(output)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900297 case flattenedApex:
Jooyung Han7f146c02020-09-23 19:15:55 +0900298 // For flattened apexes, install path should be prepended.
299 // File_contexts file should be emiited to make via LOCAL_FILE_CONTEXTS
300 // so that it can be merged into file_contexts.bin
301 apexPath := android.InstallPathToOnDevicePath(ctx, a.installDir.Join(ctx, a.Name()))
302 apexPath = strings.ReplaceAll(apexPath, ".", `\\.`)
303 // remove old file
304 rule.Command().Text("rm").FlagWithOutput("-f ", output)
305 // copy file_contexts
306 rule.Command().Text("awk").Text(`'/object_r/{printf("` + apexPath + `%s\n", $0)}'`).Input(fileContexts).Text(">").Output(output)
307 // new line
308 rule.Command().Text("echo").Text(">>").Output(output)
309 // force-label /apex_manifest.pb and / as system_file so that apexd can read them
310 rule.Command().Text("echo").Flag(apexPath + `/apex_manifest\\.pb u:object_r:system_file:s0`).Text(">>").Output(output)
311 rule.Command().Text("echo").Flag(apexPath + "/ u:object_r:system_file:s0").Text(">>").Output(output)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900312 default:
313 panic(fmt.Errorf("unsupported type %v", a.properties.ApexType))
Jooyung Han7f146c02020-09-23 19:15:55 +0900314 }
315
Colin Crossf1a035e2020-11-16 17:32:30 -0800316 rule.Build("file_contexts."+a.Name(), "Generate file_contexts")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900317 return output.OutputPath
Jooyung Han580eb4f2020-06-24 19:33:06 +0900318}
319
Jiyong Parkb81b9902020-11-24 19:51:18 +0900320// buildNoticeFiles creates a buile rule for aggregating notice files from the modules that
321// contributes to this APEX. The notice files are merged into a big notice file.
Jiyong Park19972c72020-01-28 20:05:29 +0900322func (a *apexBundle) buildNoticeFiles(ctx android.ModuleContext, apexFileName string) android.NoticeOutputs {
Jiyong Park9918e1a2020-03-17 19:16:40 +0900323 var noticeFiles android.Paths
324
Jooyung Han749dc692020-04-15 11:03:39 +0900325 a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
Jiyong Park9918e1a2020-03-17 19:16:40 +0900326 if externalDep {
Paul Duffinbe5a5be2020-03-30 15:54:08 +0100327 // As soon as the dependency graph crosses the APEX boundary, don't go further.
328 return false
Jiyong Park09d77522019-11-18 11:16:27 +0900329 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900330 noticeFiles = append(noticeFiles, to.NoticeFiles()...)
Paul Duffinbe5a5be2020-03-30 15:54:08 +0100331 return true
Jiyong Park9918e1a2020-03-17 19:16:40 +0900332 })
Jiyong Park09d77522019-11-18 11:16:27 +0900333
Jiyong Parkb81b9902020-11-24 19:51:18 +0900334 // TODO(jiyong): why do we need this? WalkPayloadDeps should have already covered this.
Jiyong Park41f637d2020-09-09 13:18:02 +0900335 for _, fi := range a.filesInfo {
336 noticeFiles = append(noticeFiles, fi.noticeFiles...)
337 }
338
Jiyong Park09d77522019-11-18 11:16:27 +0900339 if len(noticeFiles) == 0 {
Jiyong Park19972c72020-01-28 20:05:29 +0900340 return android.NoticeOutputs{}
Jiyong Park09d77522019-11-18 11:16:27 +0900341 }
342
Jiyong Park33c77362020-05-29 22:00:16 +0900343 return android.BuildNoticeOutput(ctx, a.installDir, apexFileName, android.SortedUniquePaths(noticeFiles))
Jiyong Park09d77522019-11-18 11:16:27 +0900344}
345
Jiyong Parkb81b9902020-11-24 19:51:18 +0900346// buildInstalledFilesFile creates a build rule for the installed-files.txt file where the list of
347// files included in this APEX is shown. The text file is dist'ed so that people can see what's
348// included in the APEX without actually downloading and extracting it.
Jiyong Park3a1602e2020-01-14 14:39:19 +0900349func (a *apexBundle) buildInstalledFilesFile(ctx android.ModuleContext, builtApex android.Path, imageDir android.Path) android.OutputPath {
350 output := android.PathForModuleOut(ctx, "installed-files.txt")
Colin Crossf1a035e2020-11-16 17:32:30 -0800351 rule := android.NewRuleBuilder(pctx, ctx)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900352 rule.Command().
353 Implicit(builtApex).
354 Text("(cd " + imageDir.String() + " ; ").
Jiyong Parkbd63a102020-02-08 12:40:05 +0900355 Text("find . \\( -type f -o -type l \\) -printf \"%s %p\\n\") ").
Jiyong Park3a1602e2020-01-14 14:39:19 +0900356 Text(" | sort -nr > ").
357 Output(output)
Colin Crossf1a035e2020-11-16 17:32:30 -0800358 rule.Build("installed-files."+a.Name(), "Installed files")
Jiyong Park3a1602e2020-01-14 14:39:19 +0900359 return output.OutputPath
360}
361
Jiyong Parkb81b9902020-11-24 19:51:18 +0900362// buildBundleConfig creates a build rule for the bundle config file that will control the bundle
363// creation process.
Jiyong Parkbd159612020-02-28 15:22:21 +0900364func (a *apexBundle) buildBundleConfig(ctx android.ModuleContext) android.OutputPath {
365 output := android.PathForModuleOut(ctx, "bundle_config.json")
366
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900367 type ApkConfig struct {
368 Package_name string `json:"package_name"`
369 Apk_path string `json:"path"`
370 }
Jiyong Parkbd159612020-02-28 15:22:21 +0900371 config := struct {
372 Compression struct {
373 Uncompressed_glob []string `json:"uncompressed_glob"`
374 } `json:"compression"`
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900375 Apex_config struct {
376 Apex_embedded_apk_config []ApkConfig `json:"apex_embedded_apk_config,omitempty"`
377 } `json:"apex_config,omitempty"`
Jiyong Parkbd159612020-02-28 15:22:21 +0900378 }{}
379
380 config.Compression.Uncompressed_glob = []string{
381 "apex_payload.img",
382 "apex_manifest.*",
383 }
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900384
Jiyong Parkb81b9902020-11-24 19:51:18 +0900385 // Collect the manifest names and paths of android apps if their manifest names are
386 // overridden.
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900387 for _, fi := range a.filesInfo {
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700388 if fi.class != app && fi.class != appSet {
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900389 continue
390 }
391 packageName := fi.overriddenPackageName
392 if packageName != "" {
393 config.Apex_config.Apex_embedded_apk_config = append(
394 config.Apex_config.Apex_embedded_apk_config,
395 ApkConfig{
396 Package_name: packageName,
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900397 Apk_path: fi.path(),
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900398 })
399 }
400 }
401
Jiyong Parkbd159612020-02-28 15:22:21 +0900402 j, err := json.Marshal(config)
403 if err != nil {
404 panic(fmt.Errorf("error while marshalling to %q: %#v", output, err))
405 }
406
Colin Crosscf371cc2020-11-13 11:48:42 -0800407 android.WriteFileRule(ctx, output, string(j))
Jiyong Parkbd159612020-02-28 15:22:21 +0900408
409 return output.OutputPath
410}
411
Jiyong Parkb81b9902020-11-24 19:51:18 +0900412// buildUnflattendApex creates build rules to build an APEX using apexer.
Jiyong Park09d77522019-11-18 11:16:27 +0900413func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext) {
Jiyong Park09d77522019-11-18 11:16:27 +0900414 apexType := a.properties.ApexType
415 suffix := apexType.suffix()
Jiyong Park09d77522019-11-18 11:16:27 +0900416
Jiyong Parkb81b9902020-11-24 19:51:18 +0900417 ////////////////////////////////////////////////////////////////////////////////////////////
418 // Step 1: copy built files to appropriate directories under the image directory
419
420 imageDir := android.PathForModuleOut(ctx, "image"+suffix)
421
422 // TODO(jiyong): use the RuleBuilder
Jiyong Park7cd10e32020-01-14 09:22:18 +0900423 var copyCommands []string
Jiyong Parkb81b9902020-11-24 19:51:18 +0900424 var implicitInputs []android.Path
Jiyong Park7cd10e32020-01-14 09:22:18 +0900425 for _, fi := range a.filesInfo {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900426 destPath := imageDir.Join(ctx, fi.path()).String()
427
428 // Prepare the destination path
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700429 destPathDir := filepath.Dir(destPath)
430 if fi.class == appSet {
431 copyCommands = append(copyCommands, "rm -rf "+destPathDir)
432 }
433 copyCommands = append(copyCommands, "mkdir -p "+destPathDir)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900434
435 // Copy the built file to the directory. But if the symlink optimization is turned
436 // on, place a symlink to the corresponding file in /system partition instead.
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900437 if a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform() {
Jiyong Park7cd10e32020-01-14 09:22:18 +0900438 // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900439 pathOnDevice := filepath.Join("/system", fi.path())
Jiyong Park7cd10e32020-01-14 09:22:18 +0900440 copyCommands = append(copyCommands, "ln -sfn "+pathOnDevice+" "+destPath)
441 } else {
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700442 if fi.class == appSet {
443 copyCommands = append(copyCommands,
Colin Crossd783bbb2020-07-11 22:30:45 -0700444 fmt.Sprintf("unzip -qDD -d %s %s", destPathDir, fi.builtFile.String()))
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700445 } else {
446 copyCommands = append(copyCommands, "cp -f "+fi.builtFile.String()+" "+destPath)
447 }
Jiyong Park7cd10e32020-01-14 09:22:18 +0900448 implicitInputs = append(implicitInputs, fi.builtFile)
449 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900450
451 // Create additional symlinks pointing the file inside the APEX (if any). Note that
452 // this is independent from the symlink optimization.
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900453 for _, symlinkPath := range fi.symlinkPaths() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900454 symlinkDest := imageDir.Join(ctx, symlinkPath).String()
Tim Joinesc1ef1bb2020-03-18 18:00:41 +0000455 copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
Jiyong Park7cd10e32020-01-14 09:22:18 +0900456 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900457
458 // Copy the test files (if any)
Liz Kammer1c14a212020-05-12 15:26:55 -0700459 for _, d := range fi.dataPaths {
460 // 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 -0400461 relPath := d.SrcPath.Rel()
462 dataPath := d.SrcPath.String()
Liz Kammer1c14a212020-05-12 15:26:55 -0700463 if !strings.HasSuffix(dataPath, relPath) {
464 panic(fmt.Errorf("path %q does not end with %q", dataPath, relPath))
465 }
466
Jiyong Parkb81b9902020-11-24 19:51:18 +0900467 dataDest := imageDir.Join(ctx, fi.apexRelativePath(relPath), d.RelativeInstallPath).String()
Liz Kammer1c14a212020-05-12 15:26:55 -0700468
Chris Parsons216e10a2020-07-09 17:12:52 -0400469 copyCommands = append(copyCommands, "cp -f "+d.SrcPath.String()+" "+dataDest)
470 implicitInputs = append(implicitInputs, d.SrcPath)
Liz Kammer1c14a212020-05-12 15:26:55 -0700471 }
Jiyong Park09d77522019-11-18 11:16:27 +0900472 }
Jooyung Han214bf372019-11-12 13:03:50 +0900473 implicitInputs = append(implicitInputs, a.manifestPbOut)
Jiyong Park09d77522019-11-18 11:16:27 +0900474
Jiyong Parkb81b9902020-11-24 19:51:18 +0900475 ////////////////////////////////////////////////////////////////////////////////////////////
476 // Step 1.a: Write the list of files in this APEX to a txt file and compare it against
477 // the allowed list given via the allowed_files property. Build fails when the two lists
478 // differ.
479 //
480 // TODO(jiyong): consider removing this. Nobody other than com.android.apex.cts.shim.* seems
481 // to be using this at this moment. Furthermore, this looks very similar to what
482 // buildInstalledFilesFile does. At least, move this to somewhere else so that this doesn't
483 // hurt readability.
484 // TODO(jiyong): use RuleBuilder
Jooyung Han938b5932020-06-20 12:47:47 +0900485 if a.overridableProperties.Allowed_files != nil {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900486 // Build content.txt
487 var emitCommands []string
488 imageContentFile := android.PathForModuleOut(ctx, "content.txt")
489 emitCommands = append(emitCommands, "echo ./apex_manifest.pb >> "+imageContentFile.String())
490 minSdkVersion := a.minSdkVersion(ctx)
491 if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
492 emitCommands = append(emitCommands, "echo ./apex_manifest.json >> "+imageContentFile.String())
493 }
494 for _, fi := range a.filesInfo {
495 emitCommands = append(emitCommands, "echo './"+fi.path()+"' >> "+imageContentFile.String())
496 }
497 emitCommands = append(emitCommands, "sort -o "+imageContentFile.String()+" "+imageContentFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900498 ctx.Build(pctx, android.BuildParams{
499 Rule: emitApexContentRule,
500 Implicits: implicitInputs,
501 Output: imageContentFile,
502 Description: "emit apex image content",
503 Args: map[string]string{
504 "emit_commands": strings.Join(emitCommands, " && "),
505 },
506 })
507 implicitInputs = append(implicitInputs, imageContentFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900508
Jiyong Parkb81b9902020-11-24 19:51:18 +0900509 // Compare content.txt against allowed_files.
510 allowedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.overridableProperties.Allowed_files))
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800511 phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
Jiyong Park09d77522019-11-18 11:16:27 +0900512 ctx.Build(pctx, android.BuildParams{
513 Rule: diffApexContentRule,
514 Implicits: implicitInputs,
515 Output: phonyOutput,
516 Description: "diff apex image content",
517 Args: map[string]string{
Colin Cross440e0d02020-06-11 11:32:11 -0700518 "allowed_files_file": allowedFilesFile.String(),
519 "image_content_file": imageContentFile.String(),
520 "apex_module_name": a.Name(),
Jiyong Park09d77522019-11-18 11:16:27 +0900521 },
522 })
Jiyong Park09d77522019-11-18 11:16:27 +0900523 implicitInputs = append(implicitInputs, phonyOutput)
524 }
525
Jiyong Parkb81b9902020-11-24 19:51:18 +0900526 unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
Jiyong Park09d77522019-11-18 11:16:27 +0900527 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
528 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
529
Nikita Ioffebc035882021-04-14 21:35:24 +0100530 // Figure out if need to compress apex.
Nikita Ioffeb6ea6c22021-04-19 13:07:24 +0100531 compressionEnabled := ctx.Config().CompressedApex() && proptools.BoolDefault(a.properties.Compressible, false) && !a.testApex && !ctx.Config().UnbundledBuildApps()
Jiyong Park09d77522019-11-18 11:16:27 +0900532 if apexType == imageApex {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900533 ////////////////////////////////////////////////////////////////////////////////////
534 // Step 2: create canned_fs_config which encodes filemode,uid,gid of each files
535 // in this APEX. The file will be used by apexer in later steps.
536 // TODO(jiyong): make this as a function
537 // TODO(jiyong): use the RuleBuilder
Jiyong Park09d77522019-11-18 11:16:27 +0900538 var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
539 var executablePaths []string // this also includes dirs
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700540 var extractedAppSetPaths android.Paths
541 var extractedAppSetDirs []string
Jiyong Park09d77522019-11-18 11:16:27 +0900542 for _, f := range a.filesInfo {
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900543 pathInApex := f.path()
Jiyong Park09d77522019-11-18 11:16:27 +0900544 if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
545 executablePaths = append(executablePaths, pathInApex)
Liz Kammer1c14a212020-05-12 15:26:55 -0700546 for _, d := range f.dataPaths {
Liz Kammer0a51aa22020-07-21 11:13:17 -0700547 readOnlyPaths = append(readOnlyPaths, filepath.Join(f.installDir, d.RelativeInstallPath, d.SrcPath.Rel()))
Liz Kammer1c14a212020-05-12 15:26:55 -0700548 }
Jiyong Park09d77522019-11-18 11:16:27 +0900549 for _, s := range f.symlinks {
550 executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
551 }
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700552 } else if f.class == appSet {
553 extractedAppSetPaths = append(extractedAppSetPaths, f.builtFile)
554 extractedAppSetDirs = append(extractedAppSetDirs, f.installDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900555 } else {
556 readOnlyPaths = append(readOnlyPaths, pathInApex)
557 }
558 dir := f.installDir
559 for !android.InList(dir, executablePaths) && dir != "" {
560 executablePaths = append(executablePaths, dir)
561 dir, _ = filepath.Split(dir) // move up to the parent
562 if len(dir) > 0 {
563 // remove trailing slash
564 dir = dir[:len(dir)-1]
565 }
566 }
567 }
568 sort.Strings(readOnlyPaths)
569 sort.Strings(executablePaths)
570 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
571 ctx.Build(pctx, android.BuildParams{
572 Rule: generateFsConfig,
573 Output: cannedFsConfig,
574 Description: "generate fs config",
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700575 Inputs: extractedAppSetPaths,
Jiyong Park09d77522019-11-18 11:16:27 +0900576 Args: map[string]string{
577 "ro_paths": strings.Join(readOnlyPaths, " "),
578 "exec_paths": strings.Join(executablePaths, " "),
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700579 "apk_paths": strings.Join(extractedAppSetDirs, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900580 },
581 })
Jiyong Parkb81b9902020-11-24 19:51:18 +0900582 implicitInputs = append(implicitInputs, cannedFsConfig)
Jiyong Park09d77522019-11-18 11:16:27 +0900583
Jiyong Parkb81b9902020-11-24 19:51:18 +0900584 ////////////////////////////////////////////////////////////////////////////////////
585 // Step 3: Prepare option flags for apexer and invoke it to create an unsigned APEX.
586 // TODO(jiyong): use the RuleBuilder
Jiyong Park09d77522019-11-18 11:16:27 +0900587 optFlags := []string{}
588
Jiyong Parkb81b9902020-11-24 19:51:18 +0900589 fileContexts := a.buildFileContexts(ctx)
590 implicitInputs = append(implicitInputs, fileContexts)
591
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800592 implicitInputs = append(implicitInputs, a.privateKeyFile, a.publicKeyFile)
593 optFlags = append(optFlags, "--pubkey "+a.publicKeyFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900594
Jooyung Han27151d92019-12-16 17:45:32 +0900595 manifestPackageName := a.getOverrideManifestPackageName(ctx)
596 if manifestPackageName != "" {
Jiyong Park09d77522019-11-18 11:16:27 +0900597 optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
598 }
599
600 if a.properties.AndroidManifest != nil {
601 androidManifestFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.AndroidManifest))
602 implicitInputs = append(implicitInputs, androidManifestFile)
603 optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
604 }
605
Jiyong Parkb81b9902020-11-24 19:51:18 +0900606 // Determine target/min sdk version from the context
607 // TODO(jiyong): make this as a function
Dan Albertc8060532020-07-22 22:32:17 -0700608 moduleMinSdkVersion := a.minSdkVersion(ctx)
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100609 minSdkVersion := moduleMinSdkVersion.String()
610
Jiyong Parkb81b9902020-11-24 19:51:18 +0900611 // bundletool doesn't understand what "current" is. We need to transform it to
612 // codename
Jooyung Haned124c32021-01-26 11:43:46 +0900613 if moduleMinSdkVersion.IsCurrent() || moduleMinSdkVersion.IsNone() {
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100614 minSdkVersion = ctx.Config().DefaultAppTargetSdk(ctx).String()
Liz Kammer4854a7d2021-05-27 14:28:27 -0400615
616 if java.UseApiFingerprint(ctx) {
617 minSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
618 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
619 }
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000620 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900621 // apex module doesn't have a concept of target_sdk_version, hence for the time
622 // being targetSdkVersion == default targetSdkVersion of the branch.
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100623 targetSdkVersion := strconv.Itoa(ctx.Config().DefaultAppTargetSdk(ctx).FinalOrFutureInt())
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000624
Nikita Ioffe1f4f3452020-03-02 16:58:11 +0000625 if java.UseApiFingerprint(ctx) {
626 targetSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
Baligh Uddinf6201372020-01-24 23:15:44 +0000627 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
628 }
Jiyong Park09d77522019-11-18 11:16:27 +0900629 optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
Baligh Uddinf6201372020-01-24 23:15:44 +0000630 optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
Jiyong Park09d77522019-11-18 11:16:27 +0900631
Baligh Uddin004d7172020-02-19 21:29:28 -0800632 if a.overridableProperties.Logging_parent != "" {
633 optFlags = append(optFlags, "--logging_parent ", a.overridableProperties.Logging_parent)
634 }
635
Jiyong Park19972c72020-01-28 20:05:29 +0900636 a.mergedNotices = a.buildNoticeFiles(ctx, a.Name()+suffix)
637 if a.mergedNotices.HtmlGzOutput.Valid() {
Jiyong Park09d77522019-11-18 11:16:27 +0900638 // If there's a NOTICE file, embed it as an asset file in the APEX.
Jiyong Park19972c72020-01-28 20:05:29 +0900639 implicitInputs = append(implicitInputs, a.mergedNotices.HtmlGzOutput.Path())
640 optFlags = append(optFlags, "--assets_dir "+filepath.Dir(a.mergedNotices.HtmlGzOutput.String()))
Jiyong Park09d77522019-11-18 11:16:27 +0900641 }
642
Nikita Ioffe9d9960f2021-06-09 19:43:46 +0100643 if (moduleMinSdkVersion.GreaterThan(android.SdkVersion_Android10) && !a.shouldGenerateHashtree()) && !compressionEnabled {
Jiyong Park09d77522019-11-18 11:16:27 +0900644 // Apexes which are supposed to be installed in builtin dirs(/system, etc)
645 // don't need hashtree for activation. Therefore, by removing hashtree from
646 // apex bundle (filesystem image in it, to be specific), we can save storage.
647 optFlags = append(optFlags, "--no_hashtree")
648 }
649
Dario Frenica913392020-04-27 18:21:11 +0100650 if a.testOnlyShouldSkipPayloadSign() {
651 optFlags = append(optFlags, "--unsigned_payload")
652 }
653
Jiyong Park09d77522019-11-18 11:16:27 +0900654 if a.properties.Apex_name != nil {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900655 // If apex_name is set, apexer can skip checking if key name matches with
656 // apex name. Note that apex_manifest is also mended.
Jiyong Park09d77522019-11-18 11:16:27 +0900657 optFlags = append(optFlags, "--do_not_check_keyname")
658 }
659
Dan Albertc8060532020-07-22 22:32:17 -0700660 if moduleMinSdkVersion == android.SdkVersion_Android10 {
Jooyung Han214bf372019-11-12 13:03:50 +0900661 implicitInputs = append(implicitInputs, a.manifestJsonOut)
662 optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
663 }
664
Theotime Combes4ba38c12020-06-12 12:46:59 +0000665 optFlags = append(optFlags, "--payload_fs_type "+a.payloadFsType.string())
666
Jiyong Park09d77522019-11-18 11:16:27 +0900667 ctx.Build(pctx, android.BuildParams{
668 Rule: apexRule,
669 Implicits: implicitInputs,
670 Output: unsignedOutputFile,
671 Description: "apex (" + apexType.name() + ")",
672 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900673 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900674 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900675 "copy_commands": strings.Join(copyCommands, " && "),
676 "manifest": a.manifestPbOut.String(),
Jiyong Parkb81b9902020-11-24 19:51:18 +0900677 "file_contexts": fileContexts.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900678 "canned_fs_config": cannedFsConfig.String(),
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800679 "key": a.privateKeyFile.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900680 "opt_flags": strings.Join(optFlags, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900681 },
682 })
683
Jiyong Parkb81b9902020-11-24 19:51:18 +0900684 // TODO(jiyong): make the two rules below as separate functions
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800685 apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
686 bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
Jiyong Park09d77522019-11-18 11:16:27 +0900687 a.bundleModuleFile = bundleModuleFile
688
689 ctx.Build(pctx, android.BuildParams{
690 Rule: apexProtoConvertRule,
691 Input: unsignedOutputFile,
692 Output: apexProtoFile,
693 Description: "apex proto convert",
694 })
695
sophiezc80a2b32020-11-12 16:39:19 +0000696 implicitInputs = append(implicitInputs, unsignedOutputFile)
697
698 // Run coverage analysis
sophiez6bde0b52021-01-09 01:03:42 +0000699 apisUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.txt")
sophiezc80a2b32020-11-12 16:39:19 +0000700 ctx.Build(pctx, android.BuildParams{
701 Rule: generateAPIsUsedbyApexRule,
702 Implicits: implicitInputs,
703 Description: "coverage",
704 Output: apisUsedbyOutputFile,
705 Args: map[string]string{
706 "image_dir": imageDir.String(),
707 "readelf": "${config.ClangBin}/llvm-readelf",
708 },
709 })
sophiez6bde0b52021-01-09 01:03:42 +0000710 a.apisUsedByModuleFile = apisUsedbyOutputFile
711
Colin Cross69f0a242021-02-08 16:49:57 -0800712 var libNames []string
713 for _, f := range a.filesInfo {
714 if f.class == nativeSharedLib {
715 libNames = append(libNames, f.stem())
716 }
717 }
sophiez6bde0b52021-01-09 01:03:42 +0000718 apisBackedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_backing.txt")
sophiez6bde0b52021-01-09 01:03:42 +0000719 rule := android.NewRuleBuilder(pctx, ctx)
720 rule.Command().
721 Tool(android.PathForSource(ctx, "build/soong/scripts/gen_ndk_backedby_apex.sh")).
sophiez6bde0b52021-01-09 01:03:42 +0000722 Output(apisBackedbyOutputFile).
Colin Cross69f0a242021-02-08 16:49:57 -0800723 Flags(libNames)
sophiez6bde0b52021-01-09 01:03:42 +0000724 rule.Build("ndk_backedby_list", "Generate API libraries backed by Apex")
725 a.apisBackedByModuleFile = apisBackedbyOutputFile
sophiezc80a2b32020-11-12 16:39:19 +0000726
Jiyong Parkbd159612020-02-28 15:22:21 +0900727 bundleConfig := a.buildBundleConfig(ctx)
728
Jiyong Parkb81b9902020-11-24 19:51:18 +0900729 var abis []string
730 for _, target := range ctx.MultiTargets() {
731 if len(target.Arch.Abi) > 0 {
732 abis = append(abis, target.Arch.Abi[0])
733 }
734 }
735
736 abis = android.FirstUniqueStrings(abis)
737
Jiyong Park09d77522019-11-18 11:16:27 +0900738 ctx.Build(pctx, android.BuildParams{
739 Rule: apexBundleRule,
740 Input: apexProtoFile,
Jiyong Parkbd159612020-02-28 15:22:21 +0900741 Implicit: bundleConfig,
Jiyong Park09d77522019-11-18 11:16:27 +0900742 Output: a.bundleModuleFile,
743 Description: "apex bundle module",
744 Args: map[string]string{
Jiyong Parkbd159612020-02-28 15:22:21 +0900745 "abi": strings.Join(abis, "."),
746 "config": bundleConfig.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900747 },
748 })
Jiyong Parkb81b9902020-11-24 19:51:18 +0900749 } else { // zipApex
Jiyong Park09d77522019-11-18 11:16:27 +0900750 ctx.Build(pctx, android.BuildParams{
751 Rule: zipApexRule,
752 Implicits: implicitInputs,
753 Output: unsignedOutputFile,
754 Description: "apex (" + apexType.name() + ")",
755 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900756 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900757 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900758 "copy_commands": strings.Join(copyCommands, " && "),
759 "manifest": a.manifestPbOut.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900760 },
761 })
762 }
763
Jiyong Parkb81b9902020-11-24 19:51:18 +0900764 ////////////////////////////////////////////////////////////////////////////////////
765 // Step 4: Sign the APEX using signapk
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000766 signedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900767
768 pem, key := a.getCertificateAndPrivateKey(ctx)
Kousik Kumar309b1c02020-05-28 06:13:33 -0700769 rule := java.Signapk
770 args := map[string]string{
Jiyong Parkb81b9902020-11-24 19:51:18 +0900771 "certificates": pem.String() + " " + key.String(),
Jooyung Han5d00f502021-07-11 07:26:22 +0900772 "flags": "-a 4096 --align-file-size", //alignment
Kousik Kumar309b1c02020-05-28 06:13:33 -0700773 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900774 implicits := android.Paths{pem, key}
Ramy Medhat16f23a42020-09-03 01:29:49 -0400775 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
Kousik Kumar309b1c02020-05-28 06:13:33 -0700776 rule = java.SignapkRE
777 args["implicits"] = strings.Join(implicits.Strings(), ",")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000778 args["outCommaList"] = signedOutputFile.String()
Kousik Kumar309b1c02020-05-28 06:13:33 -0700779 }
Jiyong Park09d77522019-11-18 11:16:27 +0900780 ctx.Build(pctx, android.BuildParams{
Kousik Kumar309b1c02020-05-28 06:13:33 -0700781 Rule: rule,
Jiyong Park09d77522019-11-18 11:16:27 +0900782 Description: "signapk",
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000783 Output: signedOutputFile,
Jiyong Park09d77522019-11-18 11:16:27 +0900784 Input: unsignedOutputFile,
Kousik Kumar309b1c02020-05-28 06:13:33 -0700785 Implicits: implicits,
786 Args: args,
Jiyong Park09d77522019-11-18 11:16:27 +0900787 })
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000788 a.outputFile = signedOutputFile
789
Mohammad Samiul Islama8008f92020-12-22 10:47:50 +0000790 if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && a.testOnlyShouldForceCompression() {
791 ctx.PropertyErrorf("test_only_force_compression", "not available")
792 return
793 }
Nikita Ioffebc035882021-04-14 21:35:24 +0100794
Mohammad Samiul Islama8008f92020-12-22 10:47:50 +0000795 if apexType == imageApex && (compressionEnabled || a.testOnlyShouldForceCompression()) {
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000796 a.isCompressed = true
Samiul Islam7c02e262021-09-08 17:48:28 +0100797 unsignedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix+".unsigned")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000798
799 compressRule := android.NewRuleBuilder(pctx, ctx)
800 compressRule.Command().
801 Text("rm").
802 FlagWithOutput("-f ", unsignedCompressedOutputFile)
803 compressRule.Command().
804 BuiltTool("apex_compression_tool").
805 Flag("compress").
806 FlagWithArg("--apex_compression_tool ", outHostBinDir+":"+prebuiltSdkToolsBinDir).
807 FlagWithInput("--input ", signedOutputFile).
808 FlagWithOutput("--output ", unsignedCompressedOutputFile)
809 compressRule.Build("compressRule", "Generate unsigned compressed APEX file")
810
Samiul Islam7c02e262021-09-08 17:48:28 +0100811 signedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix)
Mohammad Samiul Islam9ac0e322021-01-19 11:32:29 +0000812 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
813 args["outCommaList"] = signedCompressedOutputFile.String()
814 }
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000815 ctx.Build(pctx, android.BuildParams{
816 Rule: rule,
817 Description: "sign compressedApex",
818 Output: signedCompressedOutputFile,
819 Input: unsignedCompressedOutputFile,
820 Implicits: implicits,
821 Args: args,
822 })
823 a.outputFile = signedCompressedOutputFile
824 }
Jiyong Park09d77522019-11-18 11:16:27 +0900825
Jiyong Park17ff2832021-09-27 12:50:30 +0900826 // Install to $OUT/soong/{target,host}/.../apex.
827 ctx.InstallFile(a.installDir, a.Name()+suffix, a.outputFile)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900828
829 // installed-files.txt is dist'ed
830 a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900831}
832
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900833// Context "decorator", overriding the InstallBypassMake method to always reply `true`.
834type flattenedApexContext struct {
835 android.ModuleContext
836}
837
838func (c *flattenedApexContext) InstallBypassMake() bool {
839 return true
840}
841
Jiyong Parkb81b9902020-11-24 19:51:18 +0900842// buildFlattenedApex creates rules for a flattened APEX. Flattened APEX actually doesn't have a
843// single output file. It is a phony target for all the files under /system/apex/<name> directory.
844// This function creates the installation rules for the files.
Jiyong Park09d77522019-11-18 11:16:27 +0900845func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900846 bundleName := a.Name()
Jiyong Park09d77522019-11-18 11:16:27 +0900847 if a.installable() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900848 for _, fi := range a.filesInfo {
849 dir := filepath.Join("apex", bundleName, fi.installDir)
850 target := ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.stem(), fi.builtFile)
851 for _, sym := range fi.symlinks {
852 ctx.InstallSymlink(android.PathForModuleInstall(ctx, dir), sym, target)
Jiyong Park09d77522019-11-18 11:16:27 +0900853 }
854 }
855 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900856
857 a.fileContexts = a.buildFileContexts(ctx)
858
859 // Temporarily wrap the original `ctx` into a `flattenedApexContext` to have it reply true
860 // to `InstallBypassMake()` (thus making the call `android.PathForModuleInstall` below use
861 // `android.pathForInstallInMakeDir` instead of `android.PathForOutput`) to return the
862 // correct path to the flattened APEX (as its contents is installed by Make, not Soong).
863 // TODO(jiyong): Why do we need to set outputFile for flattened APEX? We don't seem to use
864 // it and it actually points to a path that can never be built. Remove this.
865 factx := flattenedApexContext{ctx}
866 a.outputFile = android.PathForModuleInstall(&factx, "apex", bundleName)
867}
868
869// getCertificateAndPrivateKey retrieves the cert and the private key that will be used to sign
870// the zip container of this APEX. See the description of the 'certificate' property for how
871// the cert and the private key are found.
872func (a *apexBundle) getCertificateAndPrivateKey(ctx android.PathContext) (pem, key android.Path) {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800873 if a.containerCertificateFile != nil {
874 return a.containerCertificateFile, a.containerPrivateKeyFile
Jiyong Parkb81b9902020-11-24 19:51:18 +0900875 }
876
Jaewoong Jung4cfdf7d2021-04-20 16:21:24 -0700877 cert := String(a.overridableProperties.Certificate)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900878 if cert == "" {
879 return ctx.Config().DefaultAppCertificate(ctx)
880 }
881
882 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
883 pem = defaultDir.Join(ctx, cert+".x509.pem")
884 key = defaultDir.Join(ctx, cert+".pk8")
885 return pem, key
Jiyong Park09d77522019-11-18 11:16:27 +0900886}
Jooyung Han27151d92019-12-16 17:45:32 +0900887
888func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
889 // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
890 // to see if it should be overridden because their <apex name> is dynamically generated
891 // according to its VNDK version.
892 if a.vndkApex {
893 overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
894 if overridden {
895 return strings.Replace(*a.properties.Apex_name, vndkApexName, overrideName, 1)
896 }
897 return ""
898 }
Baligh Uddin5b57dba2020-03-15 13:01:05 -0700899 if a.overridableProperties.Package_name != "" {
900 return a.overridableProperties.Package_name
901 }
Jiyong Park20bacab2020-03-03 11:45:41 +0900902 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jooyung Han27151d92019-12-16 17:45:32 +0900903 if overridden {
904 return manifestPackageName
905 }
906 return ""
907}
Jiyong Park83dc74b2020-01-14 18:38:44 +0900908
909func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
910 if !a.primaryApexType {
911 return
912 }
913
914 if a.properties.IsCoverageVariant {
915 // Otherwise, we will have duplicated rules for coverage and
916 // non-coverage variants of the same APEX
917 return
918 }
919
920 if ctx.Host() {
921 // No need to generate dependency info for host variant
922 return
923 }
924
Artur Satayev872a1442020-04-27 17:08:37 +0100925 depInfos := android.DepNameToDepInfoMap{}
Jooyung Han749dc692020-04-15 11:03:39 +0900926 a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
Artur Satayev872a1442020-04-27 17:08:37 +0100927 if from.Name() == to.Name() {
928 // This can happen for cc.reuseObjTag. We are not interested in tracking this.
929 // As soon as the dependency graph crosses the APEX boundary, don't go further.
930 return !externalDep
Jiyong Park678c8812020-02-07 17:25:49 +0900931 }
Jiyong Park83dc74b2020-01-14 18:38:44 +0900932
Artur Satayev533b98c2021-03-11 18:03:42 +0000933 // Skip dependencies that are only available to APEXes; they are developed with updatability
934 // in mind and don't need manual approval.
935 if to.(android.ApexModule).NotAvailableForPlatform() {
936 return !externalDep
937 }
938
Cindy Zhou18417cb2020-12-10 07:12:38 -0800939 depTag := ctx.OtherModuleDependencyTag(to)
Artur Satayev533b98c2021-03-11 18:03:42 +0000940 // Check to see if dependency been marked to skip the dependency check
Cindy Zhou18417cb2020-12-10 07:12:38 -0800941 if skipDepCheck, ok := depTag.(android.SkipApexAllowedDependenciesCheck); ok && skipDepCheck.SkipApexAllowedDependenciesCheck() {
Cindy Zhou18417cb2020-12-10 07:12:38 -0800942 return !externalDep
943 }
944
Artur Satayev872a1442020-04-27 17:08:37 +0100945 if info, exists := depInfos[to.Name()]; exists {
946 if !android.InList(from.Name(), info.From) {
947 info.From = append(info.From, from.Name())
948 }
949 info.IsExternal = info.IsExternal && externalDep
950 depInfos[to.Name()] = info
951 } else {
Artur Satayev480e25b2020-04-27 18:53:18 +0100952 toMinSdkVersion := "(no version)"
Jiyong Park92315372021-04-02 08:45:46 +0900953 if m, ok := to.(interface {
954 MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec
955 }); ok {
956 if v := m.MinSdkVersion(ctx); !v.ApiLevel.IsNone() {
957 toMinSdkVersion = v.ApiLevel.String()
958 }
959 } else if m, ok := to.(interface{ MinSdkVersion() string }); ok {
960 // TODO(b/175678607) eliminate the use of MinSdkVersion returning
961 // string
Artur Satayev480e25b2020-04-27 18:53:18 +0100962 if v := m.MinSdkVersion(); v != "" {
963 toMinSdkVersion = v
964 }
965 }
Artur Satayev872a1442020-04-27 17:08:37 +0100966 depInfos[to.Name()] = android.ApexModuleDepInfo{
Artur Satayev480e25b2020-04-27 18:53:18 +0100967 To: to.Name(),
968 From: []string{from.Name()},
969 IsExternal: externalDep,
970 MinSdkVersion: toMinSdkVersion,
Artur Satayev872a1442020-04-27 17:08:37 +0100971 }
972 }
973
974 // As soon as the dependency graph crosses the APEX boundary, don't go further.
975 return !externalDep
Jiyong Park83dc74b2020-01-14 18:38:44 +0900976 })
977
Artur Satayev480e25b2020-04-27 18:53:18 +0100978 a.ApexBundleDepsInfo.BuildDepsInfoLists(ctx, proptools.String(a.properties.Min_sdk_version), depInfos)
Artur Satayev872a1442020-04-27 17:08:37 +0100979
Jiyong Park83dc74b2020-01-14 18:38:44 +0900980 ctx.Build(pctx, android.BuildParams{
981 Rule: android.Phony,
982 Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
Artur Satayeva8bd1132020-04-27 18:07:06 +0100983 Inputs: []android.Path{
984 a.ApexBundleDepsInfo.FullListPath(),
985 a.ApexBundleDepsInfo.FlatListPath(),
986 },
Jiyong Park83dc74b2020-01-14 18:38:44 +0900987 })
988}
Colin Cross08dca382020-07-21 20:31:17 -0700989
990func (a *apexBundle) buildLintReports(ctx android.ModuleContext) {
991 depSetsBuilder := java.NewLintDepSetBuilder()
992 for _, fi := range a.filesInfo {
993 depSetsBuilder.Transitive(fi.lintDepSets)
994 }
995
996 a.lintReports = java.BuildModuleLintReportZips(ctx, depSetsBuilder.Build())
997}