blob: 85d76829efe971a795efaca4dd24b16a1b7faa98 [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"
Jooyung Han580eb4f2020-06-24 19:33:06 +090020 "path"
Jiyong Park09d77522019-11-18 11:16:27 +090021 "path/filepath"
22 "runtime"
23 "sort"
Nikita Ioffe5335bc42020-10-20 00:02:15 +010024 "strconv"
Jiyong Park09d77522019-11-18 11:16:27 +090025 "strings"
26
27 "android/soong/android"
28 "android/soong/java"
29
30 "github.com/google/blueprint"
31 "github.com/google/blueprint/proptools"
32)
33
34var (
35 pctx = android.NewPackageContext("android/apex")
36)
37
38func init() {
39 pctx.Import("android/soong/android")
sophiezc80a2b32020-11-12 16:39:19 +000040 pctx.Import("android/soong/cc/config")
Jiyong Park09d77522019-11-18 11:16:27 +090041 pctx.Import("android/soong/java")
42 pctx.HostBinToolVariable("apexer", "apexer")
43 // ART minimal builds (using the master-art manifest) do not have the "frameworks/base"
Jiyong Parkb81b9902020-11-24 19:51:18 +090044 // projects, and hence cannot build 'aapt2'. Use the SDK prebuilt instead.
Jiyong Park09d77522019-11-18 11:16:27 +090045 hostBinToolVariableWithPrebuilt := func(name, prebuiltDir, tool string) {
46 pctx.VariableFunc(name, func(ctx android.PackageVarContext) string {
47 if !ctx.Config().FrameworksBaseDirExists(ctx) {
48 return filepath.Join(prebuiltDir, runtime.GOOS, "bin", tool)
49 } else {
Martin Stjernholm7260d062019-12-09 21:47:14 +000050 return ctx.Config().HostToolPath(ctx, tool).String()
Jiyong Park09d77522019-11-18 11:16:27 +090051 }
52 })
53 }
54 hostBinToolVariableWithPrebuilt("aapt2", "prebuilts/sdk/tools", "aapt2")
55 pctx.HostBinToolVariable("avbtool", "avbtool")
56 pctx.HostBinToolVariable("e2fsdroid", "e2fsdroid")
57 pctx.HostBinToolVariable("merge_zips", "merge_zips")
58 pctx.HostBinToolVariable("mke2fs", "mke2fs")
59 pctx.HostBinToolVariable("resize2fs", "resize2fs")
60 pctx.HostBinToolVariable("sefcontext_compile", "sefcontext_compile")
61 pctx.HostBinToolVariable("soong_zip", "soong_zip")
62 pctx.HostBinToolVariable("zip2zip", "zip2zip")
63 pctx.HostBinToolVariable("zipalign", "zipalign")
64 pctx.HostBinToolVariable("jsonmodify", "jsonmodify")
65 pctx.HostBinToolVariable("conv_apex_manifest", "conv_apex_manifest")
Jaewoong Jungfa00c062020-05-14 14:15:24 -070066 pctx.HostBinToolVariable("extract_apks", "extract_apks")
Theotime Combes4ba38c12020-06-12 12:46:59 +000067 pctx.HostBinToolVariable("make_f2fs", "make_f2fs")
68 pctx.HostBinToolVariable("sload_f2fs", "sload_f2fs")
Huang Jianan13cac632021-08-02 15:02:17 +080069 pctx.HostBinToolVariable("make_erofs", "make_erofs")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +000070 pctx.HostBinToolVariable("apex_compression_tool", "apex_compression_tool")
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{
Sasha Smundak18d98bc2020-05-27 16:36:07 -070079 Command: `( echo '/ 1000 1000 0755' ` +
80 `&& 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
110 // TODO(b/113233103): make sure that file_contexts is sane, i.e., validate
111 // 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
260 if a.properties.File_contexts == nil {
261 fileContexts = android.PathForSource(ctx, "system/sepolicy/apex", ctx.ModuleName()+"-file_contexts")
262 } else {
263 fileContexts = android.PathForModuleSrc(ctx, *a.properties.File_contexts)
264 }
265 if a.Platform() {
266 if matched, err := path.Match("system/sepolicy/**/*", fileContexts.String()); err != nil || !matched {
267 ctx.PropertyErrorf("file_contexts", "should be under system/sepolicy, but %q", fileContexts)
Jooyung Han580eb4f2020-06-24 19:33:06 +0900268 }
269 }
270 if !android.ExistentPathForSource(ctx, fileContexts.String()).Valid() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900271 ctx.PropertyErrorf("file_contexts", "cannot find file_contexts file: %q", fileContexts.String())
Jooyung Han580eb4f2020-06-24 19:33:06 +0900272 }
273
274 output := android.PathForModuleOut(ctx, "file_contexts")
Colin Crossf1a035e2020-11-16 17:32:30 -0800275 rule := android.NewRuleBuilder(pctx, ctx)
Jooyung Han7f146c02020-09-23 19:15:55 +0900276
Jiyong Parkb81b9902020-11-24 19:51:18 +0900277 switch a.properties.ApexType {
278 case imageApex:
Jooyung Han7f146c02020-09-23 19:15:55 +0900279 // remove old file
280 rule.Command().Text("rm").FlagWithOutput("-f ", output)
281 // copy file_contexts
282 rule.Command().Text("cat").Input(fileContexts).Text(">>").Output(output)
283 // new line
284 rule.Command().Text("echo").Text(">>").Output(output)
285 // force-label /apex_manifest.pb and / as system_file so that apexd can read them
286 rule.Command().Text("echo").Flag("/apex_manifest\\\\.pb u:object_r:system_file:s0").Text(">>").Output(output)
287 rule.Command().Text("echo").Flag("/ u:object_r:system_file:s0").Text(">>").Output(output)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900288 case flattenedApex:
Jooyung Han7f146c02020-09-23 19:15:55 +0900289 // For flattened apexes, install path should be prepended.
290 // File_contexts file should be emiited to make via LOCAL_FILE_CONTEXTS
291 // so that it can be merged into file_contexts.bin
292 apexPath := android.InstallPathToOnDevicePath(ctx, a.installDir.Join(ctx, a.Name()))
293 apexPath = strings.ReplaceAll(apexPath, ".", `\\.`)
294 // remove old file
295 rule.Command().Text("rm").FlagWithOutput("-f ", output)
296 // copy file_contexts
297 rule.Command().Text("awk").Text(`'/object_r/{printf("` + apexPath + `%s\n", $0)}'`).Input(fileContexts).Text(">").Output(output)
298 // new line
299 rule.Command().Text("echo").Text(">>").Output(output)
300 // force-label /apex_manifest.pb and / as system_file so that apexd can read them
301 rule.Command().Text("echo").Flag(apexPath + `/apex_manifest\\.pb u:object_r:system_file:s0`).Text(">>").Output(output)
302 rule.Command().Text("echo").Flag(apexPath + "/ u:object_r:system_file:s0").Text(">>").Output(output)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900303 default:
304 panic(fmt.Errorf("unsupported type %v", a.properties.ApexType))
Jooyung Han7f146c02020-09-23 19:15:55 +0900305 }
306
Colin Crossf1a035e2020-11-16 17:32:30 -0800307 rule.Build("file_contexts."+a.Name(), "Generate file_contexts")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900308 return output.OutputPath
Jooyung Han580eb4f2020-06-24 19:33:06 +0900309}
310
Jiyong Parkb81b9902020-11-24 19:51:18 +0900311// buildNoticeFiles creates a buile rule for aggregating notice files from the modules that
312// contributes to this APEX. The notice files are merged into a big notice file.
Jiyong Park19972c72020-01-28 20:05:29 +0900313func (a *apexBundle) buildNoticeFiles(ctx android.ModuleContext, apexFileName string) android.NoticeOutputs {
Jiyong Park9918e1a2020-03-17 19:16:40 +0900314 var noticeFiles android.Paths
315
Jooyung Han749dc692020-04-15 11:03:39 +0900316 a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
Jiyong Park9918e1a2020-03-17 19:16:40 +0900317 if externalDep {
Paul Duffinbe5a5be2020-03-30 15:54:08 +0100318 // As soon as the dependency graph crosses the APEX boundary, don't go further.
319 return false
Jiyong Park09d77522019-11-18 11:16:27 +0900320 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900321 noticeFiles = append(noticeFiles, to.NoticeFiles()...)
Paul Duffinbe5a5be2020-03-30 15:54:08 +0100322 return true
Jiyong Park9918e1a2020-03-17 19:16:40 +0900323 })
Jiyong Park09d77522019-11-18 11:16:27 +0900324
Jiyong Parkb81b9902020-11-24 19:51:18 +0900325 // TODO(jiyong): why do we need this? WalkPayloadDeps should have already covered this.
Jiyong Park41f637d2020-09-09 13:18:02 +0900326 for _, fi := range a.filesInfo {
327 noticeFiles = append(noticeFiles, fi.noticeFiles...)
328 }
329
Jiyong Park09d77522019-11-18 11:16:27 +0900330 if len(noticeFiles) == 0 {
Jiyong Park19972c72020-01-28 20:05:29 +0900331 return android.NoticeOutputs{}
Jiyong Park09d77522019-11-18 11:16:27 +0900332 }
333
Jiyong Park33c77362020-05-29 22:00:16 +0900334 return android.BuildNoticeOutput(ctx, a.installDir, apexFileName, android.SortedUniquePaths(noticeFiles))
Jiyong Park09d77522019-11-18 11:16:27 +0900335}
336
Jiyong Parkb81b9902020-11-24 19:51:18 +0900337// buildInstalledFilesFile creates a build rule for the installed-files.txt file where the list of
338// files included in this APEX is shown. The text file is dist'ed so that people can see what's
339// included in the APEX without actually downloading and extracting it.
Jiyong Park3a1602e2020-01-14 14:39:19 +0900340func (a *apexBundle) buildInstalledFilesFile(ctx android.ModuleContext, builtApex android.Path, imageDir android.Path) android.OutputPath {
341 output := android.PathForModuleOut(ctx, "installed-files.txt")
Colin Crossf1a035e2020-11-16 17:32:30 -0800342 rule := android.NewRuleBuilder(pctx, ctx)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900343 rule.Command().
344 Implicit(builtApex).
345 Text("(cd " + imageDir.String() + " ; ").
Jiyong Parkbd63a102020-02-08 12:40:05 +0900346 Text("find . \\( -type f -o -type l \\) -printf \"%s %p\\n\") ").
Jiyong Park3a1602e2020-01-14 14:39:19 +0900347 Text(" | sort -nr > ").
348 Output(output)
Colin Crossf1a035e2020-11-16 17:32:30 -0800349 rule.Build("installed-files."+a.Name(), "Installed files")
Jiyong Park3a1602e2020-01-14 14:39:19 +0900350 return output.OutputPath
351}
352
Jiyong Parkb81b9902020-11-24 19:51:18 +0900353// buildBundleConfig creates a build rule for the bundle config file that will control the bundle
354// creation process.
Jiyong Parkbd159612020-02-28 15:22:21 +0900355func (a *apexBundle) buildBundleConfig(ctx android.ModuleContext) android.OutputPath {
356 output := android.PathForModuleOut(ctx, "bundle_config.json")
357
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900358 type ApkConfig struct {
359 Package_name string `json:"package_name"`
360 Apk_path string `json:"path"`
361 }
Jiyong Parkbd159612020-02-28 15:22:21 +0900362 config := struct {
363 Compression struct {
364 Uncompressed_glob []string `json:"uncompressed_glob"`
365 } `json:"compression"`
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900366 Apex_config struct {
367 Apex_embedded_apk_config []ApkConfig `json:"apex_embedded_apk_config,omitempty"`
368 } `json:"apex_config,omitempty"`
Jiyong Parkbd159612020-02-28 15:22:21 +0900369 }{}
370
371 config.Compression.Uncompressed_glob = []string{
372 "apex_payload.img",
373 "apex_manifest.*",
374 }
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900375
Jiyong Parkb81b9902020-11-24 19:51:18 +0900376 // Collect the manifest names and paths of android apps if their manifest names are
377 // overridden.
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900378 for _, fi := range a.filesInfo {
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700379 if fi.class != app && fi.class != appSet {
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900380 continue
381 }
382 packageName := fi.overriddenPackageName
383 if packageName != "" {
384 config.Apex_config.Apex_embedded_apk_config = append(
385 config.Apex_config.Apex_embedded_apk_config,
386 ApkConfig{
387 Package_name: packageName,
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900388 Apk_path: fi.path(),
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900389 })
390 }
391 }
392
Jiyong Parkbd159612020-02-28 15:22:21 +0900393 j, err := json.Marshal(config)
394 if err != nil {
395 panic(fmt.Errorf("error while marshalling to %q: %#v", output, err))
396 }
397
Colin Crosscf371cc2020-11-13 11:48:42 -0800398 android.WriteFileRule(ctx, output, string(j))
Jiyong Parkbd159612020-02-28 15:22:21 +0900399
400 return output.OutputPath
401}
402
Jiyong Parkb81b9902020-11-24 19:51:18 +0900403// buildUnflattendApex creates build rules to build an APEX using apexer.
Jiyong Park09d77522019-11-18 11:16:27 +0900404func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext) {
Jiyong Park09d77522019-11-18 11:16:27 +0900405 apexType := a.properties.ApexType
406 suffix := apexType.suffix()
Jiyong Park09d77522019-11-18 11:16:27 +0900407
Jiyong Parkb81b9902020-11-24 19:51:18 +0900408 ////////////////////////////////////////////////////////////////////////////////////////////
409 // Step 1: copy built files to appropriate directories under the image directory
410
411 imageDir := android.PathForModuleOut(ctx, "image"+suffix)
412
413 // TODO(jiyong): use the RuleBuilder
Jiyong Park7cd10e32020-01-14 09:22:18 +0900414 var copyCommands []string
Jiyong Parkb81b9902020-11-24 19:51:18 +0900415 var implicitInputs []android.Path
Jiyong Park7cd10e32020-01-14 09:22:18 +0900416 for _, fi := range a.filesInfo {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900417 destPath := imageDir.Join(ctx, fi.path()).String()
418
419 // Prepare the destination path
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700420 destPathDir := filepath.Dir(destPath)
421 if fi.class == appSet {
422 copyCommands = append(copyCommands, "rm -rf "+destPathDir)
423 }
424 copyCommands = append(copyCommands, "mkdir -p "+destPathDir)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900425
426 // Copy the built file to the directory. But if the symlink optimization is turned
427 // on, place a symlink to the corresponding file in /system partition instead.
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900428 if a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform() {
Jiyong Park7cd10e32020-01-14 09:22:18 +0900429 // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900430 pathOnDevice := filepath.Join("/system", fi.path())
Jiyong Park7cd10e32020-01-14 09:22:18 +0900431 copyCommands = append(copyCommands, "ln -sfn "+pathOnDevice+" "+destPath)
432 } else {
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700433 if fi.class == appSet {
434 copyCommands = append(copyCommands,
Colin Crossd783bbb2020-07-11 22:30:45 -0700435 fmt.Sprintf("unzip -qDD -d %s %s", destPathDir, fi.builtFile.String()))
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700436 } else {
437 copyCommands = append(copyCommands, "cp -f "+fi.builtFile.String()+" "+destPath)
438 }
Jiyong Park7cd10e32020-01-14 09:22:18 +0900439 implicitInputs = append(implicitInputs, fi.builtFile)
440 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900441
442 // Create additional symlinks pointing the file inside the APEX (if any). Note that
443 // this is independent from the symlink optimization.
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900444 for _, symlinkPath := range fi.symlinkPaths() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900445 symlinkDest := imageDir.Join(ctx, symlinkPath).String()
Tim Joinesc1ef1bb2020-03-18 18:00:41 +0000446 copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
Jiyong Park7cd10e32020-01-14 09:22:18 +0900447 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900448
449 // Copy the test files (if any)
Liz Kammer1c14a212020-05-12 15:26:55 -0700450 for _, d := range fi.dataPaths {
451 // 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 -0400452 relPath := d.SrcPath.Rel()
453 dataPath := d.SrcPath.String()
Liz Kammer1c14a212020-05-12 15:26:55 -0700454 if !strings.HasSuffix(dataPath, relPath) {
455 panic(fmt.Errorf("path %q does not end with %q", dataPath, relPath))
456 }
457
Jiyong Parkb81b9902020-11-24 19:51:18 +0900458 dataDest := imageDir.Join(ctx, fi.apexRelativePath(relPath), d.RelativeInstallPath).String()
Liz Kammer1c14a212020-05-12 15:26:55 -0700459
Chris Parsons216e10a2020-07-09 17:12:52 -0400460 copyCommands = append(copyCommands, "cp -f "+d.SrcPath.String()+" "+dataDest)
461 implicitInputs = append(implicitInputs, d.SrcPath)
Liz Kammer1c14a212020-05-12 15:26:55 -0700462 }
Jiyong Park09d77522019-11-18 11:16:27 +0900463 }
Jooyung Han214bf372019-11-12 13:03:50 +0900464 implicitInputs = append(implicitInputs, a.manifestPbOut)
Jiyong Park09d77522019-11-18 11:16:27 +0900465
Jiyong Parkb81b9902020-11-24 19:51:18 +0900466 ////////////////////////////////////////////////////////////////////////////////////////////
467 // Step 1.a: Write the list of files in this APEX to a txt file and compare it against
468 // the allowed list given via the allowed_files property. Build fails when the two lists
469 // differ.
470 //
471 // TODO(jiyong): consider removing this. Nobody other than com.android.apex.cts.shim.* seems
472 // to be using this at this moment. Furthermore, this looks very similar to what
473 // buildInstalledFilesFile does. At least, move this to somewhere else so that this doesn't
474 // hurt readability.
475 // TODO(jiyong): use RuleBuilder
Jooyung Han938b5932020-06-20 12:47:47 +0900476 if a.overridableProperties.Allowed_files != nil {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900477 // Build content.txt
478 var emitCommands []string
479 imageContentFile := android.PathForModuleOut(ctx, "content.txt")
480 emitCommands = append(emitCommands, "echo ./apex_manifest.pb >> "+imageContentFile.String())
481 minSdkVersion := a.minSdkVersion(ctx)
482 if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
483 emitCommands = append(emitCommands, "echo ./apex_manifest.json >> "+imageContentFile.String())
484 }
485 for _, fi := range a.filesInfo {
486 emitCommands = append(emitCommands, "echo './"+fi.path()+"' >> "+imageContentFile.String())
487 }
488 emitCommands = append(emitCommands, "sort -o "+imageContentFile.String()+" "+imageContentFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900489 ctx.Build(pctx, android.BuildParams{
490 Rule: emitApexContentRule,
491 Implicits: implicitInputs,
492 Output: imageContentFile,
493 Description: "emit apex image content",
494 Args: map[string]string{
495 "emit_commands": strings.Join(emitCommands, " && "),
496 },
497 })
498 implicitInputs = append(implicitInputs, imageContentFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900499
Jiyong Parkb81b9902020-11-24 19:51:18 +0900500 // Compare content.txt against allowed_files.
501 allowedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.overridableProperties.Allowed_files))
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800502 phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
Jiyong Park09d77522019-11-18 11:16:27 +0900503 ctx.Build(pctx, android.BuildParams{
504 Rule: diffApexContentRule,
505 Implicits: implicitInputs,
506 Output: phonyOutput,
507 Description: "diff apex image content",
508 Args: map[string]string{
Colin Cross440e0d02020-06-11 11:32:11 -0700509 "allowed_files_file": allowedFilesFile.String(),
510 "image_content_file": imageContentFile.String(),
511 "apex_module_name": a.Name(),
Jiyong Park09d77522019-11-18 11:16:27 +0900512 },
513 })
Jiyong Park09d77522019-11-18 11:16:27 +0900514 implicitInputs = append(implicitInputs, phonyOutput)
515 }
516
Jiyong Parkb81b9902020-11-24 19:51:18 +0900517 unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
Jiyong Park09d77522019-11-18 11:16:27 +0900518 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
519 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
520
Nikita Ioffebc035882021-04-14 21:35:24 +0100521 // Figure out if need to compress apex.
Nikita Ioffeb6ea6c22021-04-19 13:07:24 +0100522 compressionEnabled := ctx.Config().CompressedApex() && proptools.BoolDefault(a.properties.Compressible, false) && !a.testApex && !ctx.Config().UnbundledBuildApps()
Jiyong Park09d77522019-11-18 11:16:27 +0900523 if apexType == imageApex {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900524 ////////////////////////////////////////////////////////////////////////////////////
525 // Step 2: create canned_fs_config which encodes filemode,uid,gid of each files
526 // in this APEX. The file will be used by apexer in later steps.
527 // TODO(jiyong): make this as a function
528 // TODO(jiyong): use the RuleBuilder
Jiyong Park09d77522019-11-18 11:16:27 +0900529 var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
530 var executablePaths []string // this also includes dirs
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700531 var extractedAppSetPaths android.Paths
532 var extractedAppSetDirs []string
Jiyong Park09d77522019-11-18 11:16:27 +0900533 for _, f := range a.filesInfo {
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900534 pathInApex := f.path()
Jiyong Park09d77522019-11-18 11:16:27 +0900535 if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
536 executablePaths = append(executablePaths, pathInApex)
Liz Kammer1c14a212020-05-12 15:26:55 -0700537 for _, d := range f.dataPaths {
Liz Kammer0a51aa22020-07-21 11:13:17 -0700538 readOnlyPaths = append(readOnlyPaths, filepath.Join(f.installDir, d.RelativeInstallPath, d.SrcPath.Rel()))
Liz Kammer1c14a212020-05-12 15:26:55 -0700539 }
Jiyong Park09d77522019-11-18 11:16:27 +0900540 for _, s := range f.symlinks {
541 executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
542 }
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700543 } else if f.class == appSet {
544 extractedAppSetPaths = append(extractedAppSetPaths, f.builtFile)
545 extractedAppSetDirs = append(extractedAppSetDirs, f.installDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900546 } else {
547 readOnlyPaths = append(readOnlyPaths, pathInApex)
548 }
549 dir := f.installDir
550 for !android.InList(dir, executablePaths) && dir != "" {
551 executablePaths = append(executablePaths, dir)
552 dir, _ = filepath.Split(dir) // move up to the parent
553 if len(dir) > 0 {
554 // remove trailing slash
555 dir = dir[:len(dir)-1]
556 }
557 }
558 }
559 sort.Strings(readOnlyPaths)
560 sort.Strings(executablePaths)
561 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
562 ctx.Build(pctx, android.BuildParams{
563 Rule: generateFsConfig,
564 Output: cannedFsConfig,
565 Description: "generate fs config",
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700566 Inputs: extractedAppSetPaths,
Jiyong Park09d77522019-11-18 11:16:27 +0900567 Args: map[string]string{
568 "ro_paths": strings.Join(readOnlyPaths, " "),
569 "exec_paths": strings.Join(executablePaths, " "),
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700570 "apk_paths": strings.Join(extractedAppSetDirs, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900571 },
572 })
Jiyong Parkb81b9902020-11-24 19:51:18 +0900573 implicitInputs = append(implicitInputs, cannedFsConfig)
Jiyong Park09d77522019-11-18 11:16:27 +0900574
Jiyong Parkb81b9902020-11-24 19:51:18 +0900575 ////////////////////////////////////////////////////////////////////////////////////
576 // Step 3: Prepare option flags for apexer and invoke it to create an unsigned APEX.
577 // TODO(jiyong): use the RuleBuilder
Jiyong Park09d77522019-11-18 11:16:27 +0900578 optFlags := []string{}
579
Jiyong Parkb81b9902020-11-24 19:51:18 +0900580 fileContexts := a.buildFileContexts(ctx)
581 implicitInputs = append(implicitInputs, fileContexts)
582
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800583 implicitInputs = append(implicitInputs, a.privateKeyFile, a.publicKeyFile)
584 optFlags = append(optFlags, "--pubkey "+a.publicKeyFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900585
Jooyung Han27151d92019-12-16 17:45:32 +0900586 manifestPackageName := a.getOverrideManifestPackageName(ctx)
587 if manifestPackageName != "" {
Jiyong Park09d77522019-11-18 11:16:27 +0900588 optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
589 }
590
591 if a.properties.AndroidManifest != nil {
592 androidManifestFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.AndroidManifest))
593 implicitInputs = append(implicitInputs, androidManifestFile)
594 optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
595 }
596
Jiyong Parkb81b9902020-11-24 19:51:18 +0900597 // Determine target/min sdk version from the context
598 // TODO(jiyong): make this as a function
Dan Albertc8060532020-07-22 22:32:17 -0700599 moduleMinSdkVersion := a.minSdkVersion(ctx)
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100600 minSdkVersion := moduleMinSdkVersion.String()
601
Jiyong Parkb81b9902020-11-24 19:51:18 +0900602 // bundletool doesn't understand what "current" is. We need to transform it to
603 // codename
Jooyung Haned124c32021-01-26 11:43:46 +0900604 if moduleMinSdkVersion.IsCurrent() || moduleMinSdkVersion.IsNone() {
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100605 minSdkVersion = ctx.Config().DefaultAppTargetSdk(ctx).String()
Liz Kammer4854a7d2021-05-27 14:28:27 -0400606
607 if java.UseApiFingerprint(ctx) {
608 minSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
609 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
610 }
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000611 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900612 // apex module doesn't have a concept of target_sdk_version, hence for the time
613 // being targetSdkVersion == default targetSdkVersion of the branch.
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100614 targetSdkVersion := strconv.Itoa(ctx.Config().DefaultAppTargetSdk(ctx).FinalOrFutureInt())
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000615
Nikita Ioffe1f4f3452020-03-02 16:58:11 +0000616 if java.UseApiFingerprint(ctx) {
617 targetSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
Baligh Uddinf6201372020-01-24 23:15:44 +0000618 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
619 }
Jiyong Park09d77522019-11-18 11:16:27 +0900620 optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
Baligh Uddinf6201372020-01-24 23:15:44 +0000621 optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
Jiyong Park09d77522019-11-18 11:16:27 +0900622
Baligh Uddin004d7172020-02-19 21:29:28 -0800623 if a.overridableProperties.Logging_parent != "" {
624 optFlags = append(optFlags, "--logging_parent ", a.overridableProperties.Logging_parent)
625 }
626
Jiyong Park19972c72020-01-28 20:05:29 +0900627 a.mergedNotices = a.buildNoticeFiles(ctx, a.Name()+suffix)
628 if a.mergedNotices.HtmlGzOutput.Valid() {
Jiyong Park09d77522019-11-18 11:16:27 +0900629 // If there's a NOTICE file, embed it as an asset file in the APEX.
Jiyong Park19972c72020-01-28 20:05:29 +0900630 implicitInputs = append(implicitInputs, a.mergedNotices.HtmlGzOutput.Path())
631 optFlags = append(optFlags, "--assets_dir "+filepath.Dir(a.mergedNotices.HtmlGzOutput.String()))
Jiyong Park09d77522019-11-18 11:16:27 +0900632 }
633
Nikita Ioffe9d9960f2021-06-09 19:43:46 +0100634 if (moduleMinSdkVersion.GreaterThan(android.SdkVersion_Android10) && !a.shouldGenerateHashtree()) && !compressionEnabled {
Jiyong Park09d77522019-11-18 11:16:27 +0900635 // Apexes which are supposed to be installed in builtin dirs(/system, etc)
636 // don't need hashtree for activation. Therefore, by removing hashtree from
637 // apex bundle (filesystem image in it, to be specific), we can save storage.
638 optFlags = append(optFlags, "--no_hashtree")
639 }
640
Dario Frenica913392020-04-27 18:21:11 +0100641 if a.testOnlyShouldSkipPayloadSign() {
642 optFlags = append(optFlags, "--unsigned_payload")
643 }
644
Jiyong Park09d77522019-11-18 11:16:27 +0900645 if a.properties.Apex_name != nil {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900646 // If apex_name is set, apexer can skip checking if key name matches with
647 // apex name. Note that apex_manifest is also mended.
Jiyong Park09d77522019-11-18 11:16:27 +0900648 optFlags = append(optFlags, "--do_not_check_keyname")
649 }
650
Dan Albertc8060532020-07-22 22:32:17 -0700651 if moduleMinSdkVersion == android.SdkVersion_Android10 {
Jooyung Han214bf372019-11-12 13:03:50 +0900652 implicitInputs = append(implicitInputs, a.manifestJsonOut)
653 optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
654 }
655
Theotime Combes4ba38c12020-06-12 12:46:59 +0000656 optFlags = append(optFlags, "--payload_fs_type "+a.payloadFsType.string())
657
Jiyong Park09d77522019-11-18 11:16:27 +0900658 ctx.Build(pctx, android.BuildParams{
659 Rule: apexRule,
660 Implicits: implicitInputs,
661 Output: unsignedOutputFile,
662 Description: "apex (" + apexType.name() + ")",
663 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900664 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900665 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900666 "copy_commands": strings.Join(copyCommands, " && "),
667 "manifest": a.manifestPbOut.String(),
Jiyong Parkb81b9902020-11-24 19:51:18 +0900668 "file_contexts": fileContexts.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900669 "canned_fs_config": cannedFsConfig.String(),
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800670 "key": a.privateKeyFile.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900671 "opt_flags": strings.Join(optFlags, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900672 },
673 })
674
Jiyong Parkb81b9902020-11-24 19:51:18 +0900675 // TODO(jiyong): make the two rules below as separate functions
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800676 apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
677 bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
Jiyong Park09d77522019-11-18 11:16:27 +0900678 a.bundleModuleFile = bundleModuleFile
679
680 ctx.Build(pctx, android.BuildParams{
681 Rule: apexProtoConvertRule,
682 Input: unsignedOutputFile,
683 Output: apexProtoFile,
684 Description: "apex proto convert",
685 })
686
sophiezc80a2b32020-11-12 16:39:19 +0000687 implicitInputs = append(implicitInputs, unsignedOutputFile)
688
689 // Run coverage analysis
sophiez6bde0b52021-01-09 01:03:42 +0000690 apisUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.txt")
sophiezc80a2b32020-11-12 16:39:19 +0000691 ctx.Build(pctx, android.BuildParams{
692 Rule: generateAPIsUsedbyApexRule,
693 Implicits: implicitInputs,
694 Description: "coverage",
695 Output: apisUsedbyOutputFile,
696 Args: map[string]string{
697 "image_dir": imageDir.String(),
698 "readelf": "${config.ClangBin}/llvm-readelf",
699 },
700 })
sophiez6bde0b52021-01-09 01:03:42 +0000701 a.apisUsedByModuleFile = apisUsedbyOutputFile
702
Colin Cross69f0a242021-02-08 16:49:57 -0800703 var libNames []string
704 for _, f := range a.filesInfo {
705 if f.class == nativeSharedLib {
706 libNames = append(libNames, f.stem())
707 }
708 }
sophiez6bde0b52021-01-09 01:03:42 +0000709 apisBackedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_backing.txt")
710 ndkLibraryList := android.PathForSource(ctx, "system/core/rootdir/etc/public.libraries.android.txt")
711 rule := android.NewRuleBuilder(pctx, ctx)
712 rule.Command().
713 Tool(android.PathForSource(ctx, "build/soong/scripts/gen_ndk_backedby_apex.sh")).
sophiez6bde0b52021-01-09 01:03:42 +0000714 Output(apisBackedbyOutputFile).
Colin Cross69f0a242021-02-08 16:49:57 -0800715 Input(ndkLibraryList).
716 Flags(libNames)
sophiez6bde0b52021-01-09 01:03:42 +0000717 rule.Build("ndk_backedby_list", "Generate API libraries backed by Apex")
718 a.apisBackedByModuleFile = apisBackedbyOutputFile
sophiezc80a2b32020-11-12 16:39:19 +0000719
Jiyong Parkbd159612020-02-28 15:22:21 +0900720 bundleConfig := a.buildBundleConfig(ctx)
721
Jiyong Parkb81b9902020-11-24 19:51:18 +0900722 var abis []string
723 for _, target := range ctx.MultiTargets() {
724 if len(target.Arch.Abi) > 0 {
725 abis = append(abis, target.Arch.Abi[0])
726 }
727 }
728
729 abis = android.FirstUniqueStrings(abis)
730
Jiyong Park09d77522019-11-18 11:16:27 +0900731 ctx.Build(pctx, android.BuildParams{
732 Rule: apexBundleRule,
733 Input: apexProtoFile,
Jiyong Parkbd159612020-02-28 15:22:21 +0900734 Implicit: bundleConfig,
Jiyong Park09d77522019-11-18 11:16:27 +0900735 Output: a.bundleModuleFile,
736 Description: "apex bundle module",
737 Args: map[string]string{
Jiyong Parkbd159612020-02-28 15:22:21 +0900738 "abi": strings.Join(abis, "."),
739 "config": bundleConfig.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900740 },
741 })
Jiyong Parkb81b9902020-11-24 19:51:18 +0900742 } else { // zipApex
Jiyong Park09d77522019-11-18 11:16:27 +0900743 ctx.Build(pctx, android.BuildParams{
744 Rule: zipApexRule,
745 Implicits: implicitInputs,
746 Output: unsignedOutputFile,
747 Description: "apex (" + apexType.name() + ")",
748 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900749 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900750 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900751 "copy_commands": strings.Join(copyCommands, " && "),
752 "manifest": a.manifestPbOut.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900753 },
754 })
755 }
756
Jiyong Parkb81b9902020-11-24 19:51:18 +0900757 ////////////////////////////////////////////////////////////////////////////////////
758 // Step 4: Sign the APEX using signapk
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000759 signedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900760
761 pem, key := a.getCertificateAndPrivateKey(ctx)
Kousik Kumar309b1c02020-05-28 06:13:33 -0700762 rule := java.Signapk
763 args := map[string]string{
Jiyong Parkb81b9902020-11-24 19:51:18 +0900764 "certificates": pem.String() + " " + key.String(),
Jooyung Han5d00f502021-07-11 07:26:22 +0900765 "flags": "-a 4096 --align-file-size", //alignment
Kousik Kumar309b1c02020-05-28 06:13:33 -0700766 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900767 implicits := android.Paths{pem, key}
Ramy Medhat16f23a42020-09-03 01:29:49 -0400768 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
Kousik Kumar309b1c02020-05-28 06:13:33 -0700769 rule = java.SignapkRE
770 args["implicits"] = strings.Join(implicits.Strings(), ",")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000771 args["outCommaList"] = signedOutputFile.String()
Kousik Kumar309b1c02020-05-28 06:13:33 -0700772 }
Jiyong Park09d77522019-11-18 11:16:27 +0900773 ctx.Build(pctx, android.BuildParams{
Kousik Kumar309b1c02020-05-28 06:13:33 -0700774 Rule: rule,
Jiyong Park09d77522019-11-18 11:16:27 +0900775 Description: "signapk",
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000776 Output: signedOutputFile,
Jiyong Park09d77522019-11-18 11:16:27 +0900777 Input: unsignedOutputFile,
Kousik Kumar309b1c02020-05-28 06:13:33 -0700778 Implicits: implicits,
779 Args: args,
Jiyong Park09d77522019-11-18 11:16:27 +0900780 })
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000781 a.outputFile = signedOutputFile
782
Mohammad Samiul Islama8008f92020-12-22 10:47:50 +0000783 if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && a.testOnlyShouldForceCompression() {
784 ctx.PropertyErrorf("test_only_force_compression", "not available")
785 return
786 }
Nikita Ioffebc035882021-04-14 21:35:24 +0100787
Mohammad Samiul Islama8008f92020-12-22 10:47:50 +0000788 if apexType == imageApex && (compressionEnabled || a.testOnlyShouldForceCompression()) {
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000789 a.isCompressed = true
790 unsignedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+".capex.unsigned")
791
792 compressRule := android.NewRuleBuilder(pctx, ctx)
793 compressRule.Command().
794 Text("rm").
795 FlagWithOutput("-f ", unsignedCompressedOutputFile)
796 compressRule.Command().
797 BuiltTool("apex_compression_tool").
798 Flag("compress").
799 FlagWithArg("--apex_compression_tool ", outHostBinDir+":"+prebuiltSdkToolsBinDir).
800 FlagWithInput("--input ", signedOutputFile).
801 FlagWithOutput("--output ", unsignedCompressedOutputFile)
802 compressRule.Build("compressRule", "Generate unsigned compressed APEX file")
803
804 signedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+".capex")
Mohammad Samiul Islam9ac0e322021-01-19 11:32:29 +0000805 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
806 args["outCommaList"] = signedCompressedOutputFile.String()
807 }
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000808 ctx.Build(pctx, android.BuildParams{
809 Rule: rule,
810 Description: "sign compressedApex",
811 Output: signedCompressedOutputFile,
812 Input: unsignedCompressedOutputFile,
813 Implicits: implicits,
814 Args: args,
815 })
816 a.outputFile = signedCompressedOutputFile
817 }
Jiyong Park09d77522019-11-18 11:16:27 +0900818
819 // Install to $OUT/soong/{target,host}/.../apex
820 if a.installable() {
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800821 ctx.InstallFile(a.installDir, a.Name()+suffix, a.outputFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900822 }
Jiyong Park3a1602e2020-01-14 14:39:19 +0900823
824 // installed-files.txt is dist'ed
825 a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900826}
827
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900828// Context "decorator", overriding the InstallBypassMake method to always reply `true`.
829type flattenedApexContext struct {
830 android.ModuleContext
831}
832
833func (c *flattenedApexContext) InstallBypassMake() bool {
834 return true
835}
836
Jiyong Parkb81b9902020-11-24 19:51:18 +0900837// buildFlattenedApex creates rules for a flattened APEX. Flattened APEX actually doesn't have a
838// single output file. It is a phony target for all the files under /system/apex/<name> directory.
839// This function creates the installation rules for the files.
Jiyong Park09d77522019-11-18 11:16:27 +0900840func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900841 bundleName := a.Name()
Jiyong Park09d77522019-11-18 11:16:27 +0900842 if a.installable() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900843 for _, fi := range a.filesInfo {
844 dir := filepath.Join("apex", bundleName, fi.installDir)
845 target := ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.stem(), fi.builtFile)
846 for _, sym := range fi.symlinks {
847 ctx.InstallSymlink(android.PathForModuleInstall(ctx, dir), sym, target)
Jiyong Park09d77522019-11-18 11:16:27 +0900848 }
849 }
850 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900851
852 a.fileContexts = a.buildFileContexts(ctx)
853
854 // Temporarily wrap the original `ctx` into a `flattenedApexContext` to have it reply true
855 // to `InstallBypassMake()` (thus making the call `android.PathForModuleInstall` below use
856 // `android.pathForInstallInMakeDir` instead of `android.PathForOutput`) to return the
857 // correct path to the flattened APEX (as its contents is installed by Make, not Soong).
858 // TODO(jiyong): Why do we need to set outputFile for flattened APEX? We don't seem to use
859 // it and it actually points to a path that can never be built. Remove this.
860 factx := flattenedApexContext{ctx}
861 a.outputFile = android.PathForModuleInstall(&factx, "apex", bundleName)
862}
863
864// getCertificateAndPrivateKey retrieves the cert and the private key that will be used to sign
865// the zip container of this APEX. See the description of the 'certificate' property for how
866// the cert and the private key are found.
867func (a *apexBundle) getCertificateAndPrivateKey(ctx android.PathContext) (pem, key android.Path) {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800868 if a.containerCertificateFile != nil {
869 return a.containerCertificateFile, a.containerPrivateKeyFile
Jiyong Parkb81b9902020-11-24 19:51:18 +0900870 }
871
Jaewoong Jung4cfdf7d2021-04-20 16:21:24 -0700872 cert := String(a.overridableProperties.Certificate)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900873 if cert == "" {
874 return ctx.Config().DefaultAppCertificate(ctx)
875 }
876
877 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
878 pem = defaultDir.Join(ctx, cert+".x509.pem")
879 key = defaultDir.Join(ctx, cert+".pk8")
880 return pem, key
Jiyong Park09d77522019-11-18 11:16:27 +0900881}
Jooyung Han27151d92019-12-16 17:45:32 +0900882
883func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
884 // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
885 // to see if it should be overridden because their <apex name> is dynamically generated
886 // according to its VNDK version.
887 if a.vndkApex {
888 overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
889 if overridden {
890 return strings.Replace(*a.properties.Apex_name, vndkApexName, overrideName, 1)
891 }
892 return ""
893 }
Baligh Uddin5b57dba2020-03-15 13:01:05 -0700894 if a.overridableProperties.Package_name != "" {
895 return a.overridableProperties.Package_name
896 }
Jiyong Park20bacab2020-03-03 11:45:41 +0900897 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jooyung Han27151d92019-12-16 17:45:32 +0900898 if overridden {
899 return manifestPackageName
900 }
901 return ""
902}
Jiyong Park83dc74b2020-01-14 18:38:44 +0900903
904func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
905 if !a.primaryApexType {
906 return
907 }
908
909 if a.properties.IsCoverageVariant {
910 // Otherwise, we will have duplicated rules for coverage and
911 // non-coverage variants of the same APEX
912 return
913 }
914
915 if ctx.Host() {
916 // No need to generate dependency info for host variant
917 return
918 }
919
Artur Satayev872a1442020-04-27 17:08:37 +0100920 depInfos := android.DepNameToDepInfoMap{}
Jooyung Han749dc692020-04-15 11:03:39 +0900921 a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
Artur Satayev872a1442020-04-27 17:08:37 +0100922 if from.Name() == to.Name() {
923 // This can happen for cc.reuseObjTag. We are not interested in tracking this.
924 // As soon as the dependency graph crosses the APEX boundary, don't go further.
925 return !externalDep
Jiyong Park678c8812020-02-07 17:25:49 +0900926 }
Jiyong Park83dc74b2020-01-14 18:38:44 +0900927
Artur Satayev533b98c2021-03-11 18:03:42 +0000928 // Skip dependencies that are only available to APEXes; they are developed with updatability
929 // in mind and don't need manual approval.
930 if to.(android.ApexModule).NotAvailableForPlatform() {
931 return !externalDep
932 }
933
Cindy Zhou18417cb2020-12-10 07:12:38 -0800934 depTag := ctx.OtherModuleDependencyTag(to)
Artur Satayev533b98c2021-03-11 18:03:42 +0000935 // Check to see if dependency been marked to skip the dependency check
Cindy Zhou18417cb2020-12-10 07:12:38 -0800936 if skipDepCheck, ok := depTag.(android.SkipApexAllowedDependenciesCheck); ok && skipDepCheck.SkipApexAllowedDependenciesCheck() {
Cindy Zhou18417cb2020-12-10 07:12:38 -0800937 return !externalDep
938 }
939
Artur Satayev872a1442020-04-27 17:08:37 +0100940 if info, exists := depInfos[to.Name()]; exists {
941 if !android.InList(from.Name(), info.From) {
942 info.From = append(info.From, from.Name())
943 }
944 info.IsExternal = info.IsExternal && externalDep
945 depInfos[to.Name()] = info
946 } else {
Artur Satayev480e25b2020-04-27 18:53:18 +0100947 toMinSdkVersion := "(no version)"
Jiyong Park92315372021-04-02 08:45:46 +0900948 if m, ok := to.(interface {
949 MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec
950 }); ok {
951 if v := m.MinSdkVersion(ctx); !v.ApiLevel.IsNone() {
952 toMinSdkVersion = v.ApiLevel.String()
953 }
954 } else if m, ok := to.(interface{ MinSdkVersion() string }); ok {
955 // TODO(b/175678607) eliminate the use of MinSdkVersion returning
956 // string
Artur Satayev480e25b2020-04-27 18:53:18 +0100957 if v := m.MinSdkVersion(); v != "" {
958 toMinSdkVersion = v
959 }
960 }
Artur Satayev872a1442020-04-27 17:08:37 +0100961 depInfos[to.Name()] = android.ApexModuleDepInfo{
Artur Satayev480e25b2020-04-27 18:53:18 +0100962 To: to.Name(),
963 From: []string{from.Name()},
964 IsExternal: externalDep,
965 MinSdkVersion: toMinSdkVersion,
Artur Satayev872a1442020-04-27 17:08:37 +0100966 }
967 }
968
969 // As soon as the dependency graph crosses the APEX boundary, don't go further.
970 return !externalDep
Jiyong Park83dc74b2020-01-14 18:38:44 +0900971 })
972
Artur Satayev480e25b2020-04-27 18:53:18 +0100973 a.ApexBundleDepsInfo.BuildDepsInfoLists(ctx, proptools.String(a.properties.Min_sdk_version), depInfos)
Artur Satayev872a1442020-04-27 17:08:37 +0100974
Jiyong Park83dc74b2020-01-14 18:38:44 +0900975 ctx.Build(pctx, android.BuildParams{
976 Rule: android.Phony,
977 Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
Artur Satayeva8bd1132020-04-27 18:07:06 +0100978 Inputs: []android.Path{
979 a.ApexBundleDepsInfo.FullListPath(),
980 a.ApexBundleDepsInfo.FlatListPath(),
981 },
Jiyong Park83dc74b2020-01-14 18:38:44 +0900982 })
983}
Colin Cross08dca382020-07-21 20:31:17 -0700984
985func (a *apexBundle) buildLintReports(ctx android.ModuleContext) {
986 depSetsBuilder := java.NewLintDepSetBuilder()
987 for _, fi := range a.filesInfo {
988 depSetsBuilder.Transitive(fi.lintDepSets)
989 }
990
991 a.lintReports = java.BuildModuleLintReportZips(ctx, depSetsBuilder.Build())
992}