blob: 6df40f4b86cda9d6d0e0ae845c4a62aa4a08efea [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")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +000068 pctx.HostBinToolVariable("apex_compression_tool", "apex_compression_tool")
sophiezc80a2b32020-11-12 16:39:19 +000069 pctx.SourcePathVariable("genNdkUsedbyApexPath", "build/soong/scripts/gen_ndk_usedby_apex.sh")
Jiyong Park09d77522019-11-18 11:16:27 +090070}
71
72var (
73 // Create a canned fs config file where all files and directories are
74 // by default set to (uid/gid/mode) = (1000/1000/0644)
75 // TODO(b/113082813) make this configurable using config.fs syntax
76 generateFsConfig = pctx.StaticRule("generateFsConfig", blueprint.RuleParams{
LaMont Jones4224c622021-08-05 20:59:17 +000077 Command: `( set -e; echo '/ 1000 1000 0755' ` +
Sasha Smundak18d98bc2020-05-27 16:36:07 -070078 `&& for i in ${ro_paths}; do echo "/$$i 1000 1000 0644"; done ` +
79 `&& for i in ${exec_paths}; do echo "/$$i 0 2000 0755"; done ` +
80 `&& ( 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}`,
81 Description: "fs_config ${out}",
82 Rspfile: "$out.apklist",
83 RspfileContent: "$in",
84 }, "ro_paths", "exec_paths", "apk_paths")
Jiyong Park09d77522019-11-18 11:16:27 +090085
86 apexManifestRule = pctx.StaticRule("apexManifestRule", blueprint.RuleParams{
87 Command: `rm -f $out && ${jsonmodify} $in ` +
88 `-a provideNativeLibs ${provideNativeLibs} ` +
89 `-a requireNativeLibs ${requireNativeLibs} ` +
90 `${opt} ` +
91 `-o $out`,
92 CommandDeps: []string{"${jsonmodify}"},
93 Description: "prepare ${out}",
94 }, "provideNativeLibs", "requireNativeLibs", "opt")
95
96 stripApexManifestRule = pctx.StaticRule("stripApexManifestRule", blueprint.RuleParams{
97 Command: `rm -f $out && ${conv_apex_manifest} strip $in -o $out`,
98 CommandDeps: []string{"${conv_apex_manifest}"},
99 Description: "strip ${in}=>${out}",
100 })
101
102 pbApexManifestRule = pctx.StaticRule("pbApexManifestRule", blueprint.RuleParams{
103 Command: `rm -f $out && ${conv_apex_manifest} proto $in -o $out`,
104 CommandDeps: []string{"${conv_apex_manifest}"},
105 Description: "convert ${in}=>${out}",
106 })
107
108 // TODO(b/113233103): make sure that file_contexts is sane, i.e., validate
109 // against the binary policy using sefcontext_compiler -p <policy>.
110
111 // TODO(b/114327326): automate the generation of file_contexts
112 apexRule = pctx.StaticRule("apexRule", blueprint.RuleParams{
113 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
114 `(. ${out}.copy_commands) && ` +
115 `APEXER_TOOL_PATH=${tool_path} ` +
116 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900117 `--file_contexts ${file_contexts} ` +
118 `--canned_fs_config ${canned_fs_config} ` +
Dario Freni0f4ae072020-01-02 15:24:12 +0000119 `--include_build_info ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900120 `--payload_type image ` +
121 `--key ${key} ${opt_flags} ${image_dir} ${out} `,
122 CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
Theotime Combes4ba38c12020-06-12 12:46:59 +0000123 "${mke2fs}", "${resize2fs}", "${sefcontext_compile}", "${make_f2fs}", "${sload_f2fs}",
Jiyong Park09d77522019-11-18 11:16:27 +0900124 "${soong_zip}", "${zipalign}", "${aapt2}", "prebuilts/sdk/current/public/android.jar"},
125 Rspfile: "${out}.copy_commands",
126 RspfileContent: "${copy_commands}",
127 Description: "APEX ${image_dir} => ${out}",
Theotime Combes4ba38c12020-06-12 12:46:59 +0000128 }, "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 +0900129
130 zipApexRule = pctx.StaticRule("zipApexRule", blueprint.RuleParams{
131 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
132 `(. ${out}.copy_commands) && ` +
133 `APEXER_TOOL_PATH=${tool_path} ` +
Jooyung Han214bf372019-11-12 13:03:50 +0900134 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900135 `--payload_type zip ` +
136 `${image_dir} ${out} `,
137 CommandDeps: []string{"${apexer}", "${merge_zips}", "${soong_zip}", "${zipalign}", "${aapt2}"},
138 Rspfile: "${out}.copy_commands",
139 RspfileContent: "${copy_commands}",
140 Description: "ZipAPEX ${image_dir} => ${out}",
Jooyung Han214bf372019-11-12 13:03:50 +0900141 }, "tool_path", "image_dir", "copy_commands", "manifest")
Jiyong Park09d77522019-11-18 11:16:27 +0900142
143 apexProtoConvertRule = pctx.AndroidStaticRule("apexProtoConvertRule",
144 blueprint.RuleParams{
145 Command: `${aapt2} convert --output-format proto $in -o $out`,
146 CommandDeps: []string{"${aapt2}"},
147 })
148
149 apexBundleRule = pctx.StaticRule("apexBundleRule", blueprint.RuleParams{
Jiyong Parkbd159612020-02-28 15:22:21 +0900150 Command: `${zip2zip} -i $in -o $out.base ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900151 `apex_payload.img:apex/${abi}.img ` +
Dario Frenida1aefe2020-03-02 21:47:09 +0000152 `apex_build_info.pb:apex/${abi}.build_info.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900153 `apex_manifest.json:root/apex_manifest.json ` +
Jiyong Park53ae3342019-12-08 02:06:24 +0900154 `apex_manifest.pb:root/apex_manifest.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900155 `AndroidManifest.xml:manifest/AndroidManifest.xml ` +
Jiyong Parkbd159612020-02-28 15:22:21 +0900156 `assets/NOTICE.html.gz:assets/NOTICE.html.gz &&` +
157 `${soong_zip} -o $out.config -C $$(dirname ${config}) -f ${config} && ` +
158 `${merge_zips} $out $out.base $out.config`,
159 CommandDeps: []string{"${zip2zip}", "${soong_zip}", "${merge_zips}"},
Jiyong Park09d77522019-11-18 11:16:27 +0900160 Description: "app bundle",
Jiyong Parkbd159612020-02-28 15:22:21 +0900161 }, "abi", "config")
Jiyong Park09d77522019-11-18 11:16:27 +0900162
163 emitApexContentRule = pctx.StaticRule("emitApexContentRule", blueprint.RuleParams{
164 Command: `rm -f ${out} && touch ${out} && (. ${out}.emit_commands)`,
165 Rspfile: "${out}.emit_commands",
166 RspfileContent: "${emit_commands}",
167 Description: "Emit APEX image content",
168 }, "emit_commands")
169
170 diffApexContentRule = pctx.StaticRule("diffApexContentRule", blueprint.RuleParams{
171 Command: `diff --unchanged-group-format='' \` +
172 `--changed-group-format='%<' \` +
Colin Cross440e0d02020-06-11 11:32:11 -0700173 `${image_content_file} ${allowed_files_file} || (` +
Jiyong Park09d77522019-11-18 11:16:27 +0900174 `echo -e "New unexpected files were added to ${apex_module_name}." ` +
175 ` "To fix the build run following command:" && ` +
Colin Cross440e0d02020-06-11 11:32:11 -0700176 `echo "system/apex/tools/update_allowed_list.sh ${allowed_files_file} ${image_content_file}" && ` +
Dan Willemsen81e43c52020-01-28 15:40:19 -0800177 `exit 1); touch ${out}`,
Colin Cross440e0d02020-06-11 11:32:11 -0700178 Description: "Diff ${image_content_file} and ${allowed_files_file}",
179 }, "image_content_file", "allowed_files_file", "apex_module_name")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900180
sophiezc80a2b32020-11-12 16:39:19 +0000181 generateAPIsUsedbyApexRule = pctx.StaticRule("generateAPIsUsedbyApexRule", blueprint.RuleParams{
182 Command: "$genNdkUsedbyApexPath ${image_dir} ${readelf} ${out}",
183 CommandDeps: []string{"${genNdkUsedbyApexPath}"},
184 Description: "Generate symbol list used by Apex",
185 }, "image_dir", "readelf")
186
Jiyong Parkb81b9902020-11-24 19:51:18 +0900187 // Don't add more rules here. Consider using android.NewRuleBuilder instead.
Jiyong Park09d77522019-11-18 11:16:27 +0900188)
189
Jiyong Parkb81b9902020-11-24 19:51:18 +0900190// buildManifest creates buile rules to modify the input apex_manifest.json to add information
191// gathered by the build system such as provided/required native libraries. Two output files having
192// different formats are generated. a.manifestJsonOut is JSON format for Q devices, and
193// a.manifest.PbOut is protobuf format for R+ devices.
194// TODO(jiyong): make this to return paths instead of directly storing the paths to apexBundle
Jiyong Park09d77522019-11-18 11:16:27 +0900195func (a *apexBundle) buildManifest(ctx android.ModuleContext, provideNativeLibs, requireNativeLibs []string) {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900196 src := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
Jiyong Park09d77522019-11-18 11:16:27 +0900197
Jiyong Parkb81b9902020-11-24 19:51:18 +0900198 // Put dependency({provide|require}NativeLibs) in apex_manifest.json
Jiyong Park09d77522019-11-18 11:16:27 +0900199 provideNativeLibs = android.SortedUniqueStrings(provideNativeLibs)
200 requireNativeLibs = android.SortedUniqueStrings(android.RemoveListFromList(requireNativeLibs, provideNativeLibs))
201
Jiyong Parkb81b9902020-11-24 19:51:18 +0900202 // APEX name can be overridden
Jiyong Park09d77522019-11-18 11:16:27 +0900203 optCommands := []string{}
204 if a.properties.Apex_name != nil {
205 optCommands = append(optCommands, "-v name "+*a.properties.Apex_name)
206 }
207
Jiyong Parkb81b9902020-11-24 19:51:18 +0900208 // Collect jniLibs. Notice that a.filesInfo is already sorted
Jooyung Han643adc42020-02-27 13:50:06 +0900209 var jniLibs []string
210 for _, fi := range a.filesInfo {
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900211 if fi.isJniLib && !android.InList(fi.stem(), jniLibs) {
212 jniLibs = append(jniLibs, fi.stem())
Jooyung Han643adc42020-02-27 13:50:06 +0900213 }
214 }
215 if len(jniLibs) > 0 {
216 optCommands = append(optCommands, "-a jniLibs "+strings.Join(jniLibs, " "))
217 }
218
Jiyong Parkb81b9902020-11-24 19:51:18 +0900219 manifestJsonFullOut := android.PathForModuleOut(ctx, "apex_manifest_full.json")
Jiyong Park09d77522019-11-18 11:16:27 +0900220 ctx.Build(pctx, android.BuildParams{
221 Rule: apexManifestRule,
Jiyong Parkb81b9902020-11-24 19:51:18 +0900222 Input: src,
Jooyung Han214bf372019-11-12 13:03:50 +0900223 Output: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900224 Args: map[string]string{
225 "provideNativeLibs": strings.Join(provideNativeLibs, " "),
226 "requireNativeLibs": strings.Join(requireNativeLibs, " "),
227 "opt": strings.Join(optCommands, " "),
228 },
229 })
230
Jiyong Parkb81b9902020-11-24 19:51:18 +0900231 // b/143654022 Q apexd can't understand newly added keys in apex_manifest.json prepare
232 // stripped-down version so that APEX modules built from R+ can be installed to Q
Dan Albertc8060532020-07-22 22:32:17 -0700233 minSdkVersion := a.minSdkVersion(ctx)
234 if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
Jooyung Han214bf372019-11-12 13:03:50 +0900235 a.manifestJsonOut = android.PathForModuleOut(ctx, "apex_manifest.json")
236 ctx.Build(pctx, android.BuildParams{
237 Rule: stripApexManifestRule,
238 Input: manifestJsonFullOut,
239 Output: a.manifestJsonOut,
240 })
241 }
Jiyong Park09d77522019-11-18 11:16:27 +0900242
Jiyong Parkb81b9902020-11-24 19:51:18 +0900243 // From R+, protobuf binary format (.pb) is the standard format for apex_manifest
Jiyong Park09d77522019-11-18 11:16:27 +0900244 a.manifestPbOut = android.PathForModuleOut(ctx, "apex_manifest.pb")
245 ctx.Build(pctx, android.BuildParams{
246 Rule: pbApexManifestRule,
Jooyung Han214bf372019-11-12 13:03:50 +0900247 Input: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900248 Output: a.manifestPbOut,
249 })
250}
251
Jiyong Parkb81b9902020-11-24 19:51:18 +0900252// buildFileContexts create build rules to append an entry for apex_manifest.pb to the file_contexts
253// file for this APEX which is either from /systme/sepolicy/apex/<apexname>-file_contexts or from
254// the file_contexts property of this APEX. This is to make sure that the manifest file is correctly
255// labeled as system_file.
256func (a *apexBundle) buildFileContexts(ctx android.ModuleContext) android.OutputPath {
Jooyung Han580eb4f2020-06-24 19:33:06 +0900257 var fileContexts android.Path
Liz Kammer37997c42021-09-14 17:53:38 -0400258 var fileContextsDir string
Jooyung Han580eb4f2020-06-24 19:33:06 +0900259 if a.properties.File_contexts == nil {
260 fileContexts = android.PathForSource(ctx, "system/sepolicy/apex", ctx.ModuleName()+"-file_contexts")
261 } else {
Liz Kammer37997c42021-09-14 17:53:38 -0400262 if m, t := android.SrcIsModuleWithTag(*a.properties.File_contexts); m != "" {
263 otherModule := android.GetModuleFromPathDep(ctx, m, t)
264 fileContextsDir = ctx.OtherModuleDir(otherModule)
265 }
Jooyung Han580eb4f2020-06-24 19:33:06 +0900266 fileContexts = android.PathForModuleSrc(ctx, *a.properties.File_contexts)
267 }
Liz Kammer37997c42021-09-14 17:53:38 -0400268 if fileContextsDir == "" {
269 fileContextsDir = filepath.Dir(fileContexts.String())
270 }
271 fileContextsDir += string(filepath.Separator)
272
Jooyung Han580eb4f2020-06-24 19:33:06 +0900273 if a.Platform() {
Liz Kammer37997c42021-09-14 17:53:38 -0400274 if !strings.HasPrefix(fileContextsDir, "system/sepolicy/") {
275 ctx.PropertyErrorf("file_contexts", "should be under system/sepolicy, but found in %q", fileContextsDir)
Jooyung Han580eb4f2020-06-24 19:33:06 +0900276 }
277 }
278 if !android.ExistentPathForSource(ctx, fileContexts.String()).Valid() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900279 ctx.PropertyErrorf("file_contexts", "cannot find file_contexts file: %q", fileContexts.String())
Jooyung Han580eb4f2020-06-24 19:33:06 +0900280 }
281
282 output := android.PathForModuleOut(ctx, "file_contexts")
Colin Crossf1a035e2020-11-16 17:32:30 -0800283 rule := android.NewRuleBuilder(pctx, ctx)
Jooyung Han7f146c02020-09-23 19:15:55 +0900284
Jiyong Parkb81b9902020-11-24 19:51:18 +0900285 switch a.properties.ApexType {
286 case imageApex:
Jooyung Han7f146c02020-09-23 19:15:55 +0900287 // remove old file
288 rule.Command().Text("rm").FlagWithOutput("-f ", output)
289 // copy file_contexts
290 rule.Command().Text("cat").Input(fileContexts).Text(">>").Output(output)
291 // new line
292 rule.Command().Text("echo").Text(">>").Output(output)
293 // force-label /apex_manifest.pb and / as system_file so that apexd can read them
294 rule.Command().Text("echo").Flag("/apex_manifest\\\\.pb u:object_r:system_file:s0").Text(">>").Output(output)
295 rule.Command().Text("echo").Flag("/ u:object_r:system_file:s0").Text(">>").Output(output)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900296 case flattenedApex:
Jooyung Han7f146c02020-09-23 19:15:55 +0900297 // For flattened apexes, install path should be prepended.
298 // File_contexts file should be emiited to make via LOCAL_FILE_CONTEXTS
299 // so that it can be merged into file_contexts.bin
300 apexPath := android.InstallPathToOnDevicePath(ctx, a.installDir.Join(ctx, a.Name()))
301 apexPath = strings.ReplaceAll(apexPath, ".", `\\.`)
302 // remove old file
303 rule.Command().Text("rm").FlagWithOutput("-f ", output)
304 // copy file_contexts
305 rule.Command().Text("awk").Text(`'/object_r/{printf("` + apexPath + `%s\n", $0)}'`).Input(fileContexts).Text(">").Output(output)
306 // new line
307 rule.Command().Text("echo").Text(">>").Output(output)
308 // force-label /apex_manifest.pb and / as system_file so that apexd can read them
309 rule.Command().Text("echo").Flag(apexPath + `/apex_manifest\\.pb u:object_r:system_file:s0`).Text(">>").Output(output)
310 rule.Command().Text("echo").Flag(apexPath + "/ u:object_r:system_file:s0").Text(">>").Output(output)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900311 default:
312 panic(fmt.Errorf("unsupported type %v", a.properties.ApexType))
Jooyung Han7f146c02020-09-23 19:15:55 +0900313 }
314
Colin Crossf1a035e2020-11-16 17:32:30 -0800315 rule.Build("file_contexts."+a.Name(), "Generate file_contexts")
Jiyong Parkb81b9902020-11-24 19:51:18 +0900316 return output.OutputPath
Jooyung Han580eb4f2020-06-24 19:33:06 +0900317}
318
Jiyong Parkb81b9902020-11-24 19:51:18 +0900319// buildNoticeFiles creates a buile rule for aggregating notice files from the modules that
320// contributes to this APEX. The notice files are merged into a big notice file.
Jiyong Park19972c72020-01-28 20:05:29 +0900321func (a *apexBundle) buildNoticeFiles(ctx android.ModuleContext, apexFileName string) android.NoticeOutputs {
Jiyong Park9918e1a2020-03-17 19:16:40 +0900322 var noticeFiles android.Paths
323
Jooyung Han749dc692020-04-15 11:03:39 +0900324 a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
Jiyong Park9918e1a2020-03-17 19:16:40 +0900325 if externalDep {
Paul Duffinbe5a5be2020-03-30 15:54:08 +0100326 // As soon as the dependency graph crosses the APEX boundary, don't go further.
327 return false
Jiyong Park09d77522019-11-18 11:16:27 +0900328 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900329 noticeFiles = append(noticeFiles, to.NoticeFiles()...)
Paul Duffinbe5a5be2020-03-30 15:54:08 +0100330 return true
Jiyong Park9918e1a2020-03-17 19:16:40 +0900331 })
Jiyong Park09d77522019-11-18 11:16:27 +0900332
Jiyong Parkb81b9902020-11-24 19:51:18 +0900333 // TODO(jiyong): why do we need this? WalkPayloadDeps should have already covered this.
Jiyong Park41f637d2020-09-09 13:18:02 +0900334 for _, fi := range a.filesInfo {
335 noticeFiles = append(noticeFiles, fi.noticeFiles...)
336 }
337
Jiyong Park09d77522019-11-18 11:16:27 +0900338 if len(noticeFiles) == 0 {
Jiyong Park19972c72020-01-28 20:05:29 +0900339 return android.NoticeOutputs{}
Jiyong Park09d77522019-11-18 11:16:27 +0900340 }
341
Jiyong Park33c77362020-05-29 22:00:16 +0900342 return android.BuildNoticeOutput(ctx, a.installDir, apexFileName, android.SortedUniquePaths(noticeFiles))
Jiyong Park09d77522019-11-18 11:16:27 +0900343}
344
Jiyong Parkb81b9902020-11-24 19:51:18 +0900345// buildInstalledFilesFile creates a build rule for the installed-files.txt file where the list of
346// files included in this APEX is shown. The text file is dist'ed so that people can see what's
347// included in the APEX without actually downloading and extracting it.
Jiyong Park3a1602e2020-01-14 14:39:19 +0900348func (a *apexBundle) buildInstalledFilesFile(ctx android.ModuleContext, builtApex android.Path, imageDir android.Path) android.OutputPath {
349 output := android.PathForModuleOut(ctx, "installed-files.txt")
Colin Crossf1a035e2020-11-16 17:32:30 -0800350 rule := android.NewRuleBuilder(pctx, ctx)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900351 rule.Command().
352 Implicit(builtApex).
353 Text("(cd " + imageDir.String() + " ; ").
Jiyong Parkbd63a102020-02-08 12:40:05 +0900354 Text("find . \\( -type f -o -type l \\) -printf \"%s %p\\n\") ").
Jiyong Park3a1602e2020-01-14 14:39:19 +0900355 Text(" | sort -nr > ").
356 Output(output)
Colin Crossf1a035e2020-11-16 17:32:30 -0800357 rule.Build("installed-files."+a.Name(), "Installed files")
Jiyong Park3a1602e2020-01-14 14:39:19 +0900358 return output.OutputPath
359}
360
Jiyong Parkb81b9902020-11-24 19:51:18 +0900361// buildBundleConfig creates a build rule for the bundle config file that will control the bundle
362// creation process.
Jiyong Parkbd159612020-02-28 15:22:21 +0900363func (a *apexBundle) buildBundleConfig(ctx android.ModuleContext) android.OutputPath {
364 output := android.PathForModuleOut(ctx, "bundle_config.json")
365
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900366 type ApkConfig struct {
367 Package_name string `json:"package_name"`
368 Apk_path string `json:"path"`
369 }
Jiyong Parkbd159612020-02-28 15:22:21 +0900370 config := struct {
371 Compression struct {
372 Uncompressed_glob []string `json:"uncompressed_glob"`
373 } `json:"compression"`
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900374 Apex_config struct {
375 Apex_embedded_apk_config []ApkConfig `json:"apex_embedded_apk_config,omitempty"`
376 } `json:"apex_config,omitempty"`
Jiyong Parkbd159612020-02-28 15:22:21 +0900377 }{}
378
379 config.Compression.Uncompressed_glob = []string{
380 "apex_payload.img",
381 "apex_manifest.*",
382 }
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900383
Jiyong Parkb81b9902020-11-24 19:51:18 +0900384 // Collect the manifest names and paths of android apps if their manifest names are
385 // overridden.
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900386 for _, fi := range a.filesInfo {
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700387 if fi.class != app && fi.class != appSet {
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900388 continue
389 }
390 packageName := fi.overriddenPackageName
391 if packageName != "" {
392 config.Apex_config.Apex_embedded_apk_config = append(
393 config.Apex_config.Apex_embedded_apk_config,
394 ApkConfig{
395 Package_name: packageName,
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900396 Apk_path: fi.path(),
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900397 })
398 }
399 }
400
Jiyong Parkbd159612020-02-28 15:22:21 +0900401 j, err := json.Marshal(config)
402 if err != nil {
403 panic(fmt.Errorf("error while marshalling to %q: %#v", output, err))
404 }
405
Colin Crosscf371cc2020-11-13 11:48:42 -0800406 android.WriteFileRule(ctx, output, string(j))
Jiyong Parkbd159612020-02-28 15:22:21 +0900407
408 return output.OutputPath
409}
410
Jiyong Parkb81b9902020-11-24 19:51:18 +0900411// buildUnflattendApex creates build rules to build an APEX using apexer.
Jiyong Park09d77522019-11-18 11:16:27 +0900412func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext) {
Jiyong Park09d77522019-11-18 11:16:27 +0900413 apexType := a.properties.ApexType
414 suffix := apexType.suffix()
Jiyong Park09d77522019-11-18 11:16:27 +0900415
Jiyong Parkb81b9902020-11-24 19:51:18 +0900416 ////////////////////////////////////////////////////////////////////////////////////////////
417 // Step 1: copy built files to appropriate directories under the image directory
418
419 imageDir := android.PathForModuleOut(ctx, "image"+suffix)
420
421 // TODO(jiyong): use the RuleBuilder
Jiyong Park7cd10e32020-01-14 09:22:18 +0900422 var copyCommands []string
Jiyong Parkb81b9902020-11-24 19:51:18 +0900423 var implicitInputs []android.Path
Jiyong Park7cd10e32020-01-14 09:22:18 +0900424 for _, fi := range a.filesInfo {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900425 destPath := imageDir.Join(ctx, fi.path()).String()
426
427 // Prepare the destination path
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700428 destPathDir := filepath.Dir(destPath)
429 if fi.class == appSet {
430 copyCommands = append(copyCommands, "rm -rf "+destPathDir)
431 }
432 copyCommands = append(copyCommands, "mkdir -p "+destPathDir)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900433
434 // Copy the built file to the directory. But if the symlink optimization is turned
435 // on, place a symlink to the corresponding file in /system partition instead.
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900436 if a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform() {
Jiyong Park7cd10e32020-01-14 09:22:18 +0900437 // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900438 pathOnDevice := filepath.Join("/system", fi.path())
Jiyong Park7cd10e32020-01-14 09:22:18 +0900439 copyCommands = append(copyCommands, "ln -sfn "+pathOnDevice+" "+destPath)
440 } else {
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700441 if fi.class == appSet {
442 copyCommands = append(copyCommands,
Colin Crossd783bbb2020-07-11 22:30:45 -0700443 fmt.Sprintf("unzip -qDD -d %s %s", destPathDir, fi.builtFile.String()))
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700444 } else {
445 copyCommands = append(copyCommands, "cp -f "+fi.builtFile.String()+" "+destPath)
446 }
Jiyong Park7cd10e32020-01-14 09:22:18 +0900447 implicitInputs = append(implicitInputs, fi.builtFile)
448 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900449
450 // Create additional symlinks pointing the file inside the APEX (if any). Note that
451 // this is independent from the symlink optimization.
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900452 for _, symlinkPath := range fi.symlinkPaths() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900453 symlinkDest := imageDir.Join(ctx, symlinkPath).String()
Tim Joinesc1ef1bb2020-03-18 18:00:41 +0000454 copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
Jiyong Park7cd10e32020-01-14 09:22:18 +0900455 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900456
457 // Copy the test files (if any)
Liz Kammer1c14a212020-05-12 15:26:55 -0700458 for _, d := range fi.dataPaths {
459 // 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 -0400460 relPath := d.SrcPath.Rel()
461 dataPath := d.SrcPath.String()
Liz Kammer1c14a212020-05-12 15:26:55 -0700462 if !strings.HasSuffix(dataPath, relPath) {
463 panic(fmt.Errorf("path %q does not end with %q", dataPath, relPath))
464 }
465
Jiyong Parkb81b9902020-11-24 19:51:18 +0900466 dataDest := imageDir.Join(ctx, fi.apexRelativePath(relPath), d.RelativeInstallPath).String()
Liz Kammer1c14a212020-05-12 15:26:55 -0700467
Chris Parsons216e10a2020-07-09 17:12:52 -0400468 copyCommands = append(copyCommands, "cp -f "+d.SrcPath.String()+" "+dataDest)
469 implicitInputs = append(implicitInputs, d.SrcPath)
Liz Kammer1c14a212020-05-12 15:26:55 -0700470 }
Jiyong Park09d77522019-11-18 11:16:27 +0900471 }
Jooyung Han214bf372019-11-12 13:03:50 +0900472 implicitInputs = append(implicitInputs, a.manifestPbOut)
Jiyong Park09d77522019-11-18 11:16:27 +0900473
Jiyong Parkb81b9902020-11-24 19:51:18 +0900474 ////////////////////////////////////////////////////////////////////////////////////////////
475 // Step 1.a: Write the list of files in this APEX to a txt file and compare it against
476 // the allowed list given via the allowed_files property. Build fails when the two lists
477 // differ.
478 //
479 // TODO(jiyong): consider removing this. Nobody other than com.android.apex.cts.shim.* seems
480 // to be using this at this moment. Furthermore, this looks very similar to what
481 // buildInstalledFilesFile does. At least, move this to somewhere else so that this doesn't
482 // hurt readability.
483 // TODO(jiyong): use RuleBuilder
Jooyung Han938b5932020-06-20 12:47:47 +0900484 if a.overridableProperties.Allowed_files != nil {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900485 // Build content.txt
486 var emitCommands []string
487 imageContentFile := android.PathForModuleOut(ctx, "content.txt")
488 emitCommands = append(emitCommands, "echo ./apex_manifest.pb >> "+imageContentFile.String())
489 minSdkVersion := a.minSdkVersion(ctx)
490 if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
491 emitCommands = append(emitCommands, "echo ./apex_manifest.json >> "+imageContentFile.String())
492 }
493 for _, fi := range a.filesInfo {
494 emitCommands = append(emitCommands, "echo './"+fi.path()+"' >> "+imageContentFile.String())
495 }
496 emitCommands = append(emitCommands, "sort -o "+imageContentFile.String()+" "+imageContentFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900497 ctx.Build(pctx, android.BuildParams{
498 Rule: emitApexContentRule,
499 Implicits: implicitInputs,
500 Output: imageContentFile,
501 Description: "emit apex image content",
502 Args: map[string]string{
503 "emit_commands": strings.Join(emitCommands, " && "),
504 },
505 })
506 implicitInputs = append(implicitInputs, imageContentFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900507
Jiyong Parkb81b9902020-11-24 19:51:18 +0900508 // Compare content.txt against allowed_files.
509 allowedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.overridableProperties.Allowed_files))
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800510 phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
Jiyong Park09d77522019-11-18 11:16:27 +0900511 ctx.Build(pctx, android.BuildParams{
512 Rule: diffApexContentRule,
513 Implicits: implicitInputs,
514 Output: phonyOutput,
515 Description: "diff apex image content",
516 Args: map[string]string{
Colin Cross440e0d02020-06-11 11:32:11 -0700517 "allowed_files_file": allowedFilesFile.String(),
518 "image_content_file": imageContentFile.String(),
519 "apex_module_name": a.Name(),
Jiyong Park09d77522019-11-18 11:16:27 +0900520 },
521 })
Jiyong Park09d77522019-11-18 11:16:27 +0900522 implicitInputs = append(implicitInputs, phonyOutput)
523 }
524
Jiyong Parkb81b9902020-11-24 19:51:18 +0900525 unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
Jiyong Park09d77522019-11-18 11:16:27 +0900526 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
527 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
528
Nikita Ioffebc035882021-04-14 21:35:24 +0100529 // Figure out if need to compress apex.
Nikita Ioffeb6ea6c22021-04-19 13:07:24 +0100530 compressionEnabled := ctx.Config().CompressedApex() && proptools.BoolDefault(a.properties.Compressible, false) && !a.testApex && !ctx.Config().UnbundledBuildApps()
Jiyong Park09d77522019-11-18 11:16:27 +0900531 if apexType == imageApex {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900532 ////////////////////////////////////////////////////////////////////////////////////
533 // Step 2: create canned_fs_config which encodes filemode,uid,gid of each files
534 // in this APEX. The file will be used by apexer in later steps.
535 // TODO(jiyong): make this as a function
536 // TODO(jiyong): use the RuleBuilder
Jiyong Park09d77522019-11-18 11:16:27 +0900537 var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
538 var executablePaths []string // this also includes dirs
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700539 var extractedAppSetPaths android.Paths
540 var extractedAppSetDirs []string
Jiyong Park09d77522019-11-18 11:16:27 +0900541 for _, f := range a.filesInfo {
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900542 pathInApex := f.path()
Jiyong Park09d77522019-11-18 11:16:27 +0900543 if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
544 executablePaths = append(executablePaths, pathInApex)
Liz Kammer1c14a212020-05-12 15:26:55 -0700545 for _, d := range f.dataPaths {
Liz Kammer0a51aa22020-07-21 11:13:17 -0700546 readOnlyPaths = append(readOnlyPaths, filepath.Join(f.installDir, d.RelativeInstallPath, d.SrcPath.Rel()))
Liz Kammer1c14a212020-05-12 15:26:55 -0700547 }
Jiyong Park09d77522019-11-18 11:16:27 +0900548 for _, s := range f.symlinks {
549 executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
550 }
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700551 } else if f.class == appSet {
552 extractedAppSetPaths = append(extractedAppSetPaths, f.builtFile)
553 extractedAppSetDirs = append(extractedAppSetDirs, f.installDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900554 } else {
555 readOnlyPaths = append(readOnlyPaths, pathInApex)
556 }
557 dir := f.installDir
558 for !android.InList(dir, executablePaths) && dir != "" {
559 executablePaths = append(executablePaths, dir)
560 dir, _ = filepath.Split(dir) // move up to the parent
561 if len(dir) > 0 {
562 // remove trailing slash
563 dir = dir[:len(dir)-1]
564 }
565 }
566 }
567 sort.Strings(readOnlyPaths)
568 sort.Strings(executablePaths)
569 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
570 ctx.Build(pctx, android.BuildParams{
571 Rule: generateFsConfig,
572 Output: cannedFsConfig,
573 Description: "generate fs config",
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700574 Inputs: extractedAppSetPaths,
Jiyong Park09d77522019-11-18 11:16:27 +0900575 Args: map[string]string{
576 "ro_paths": strings.Join(readOnlyPaths, " "),
577 "exec_paths": strings.Join(executablePaths, " "),
Sasha Smundak18d98bc2020-05-27 16:36:07 -0700578 "apk_paths": strings.Join(extractedAppSetDirs, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900579 },
580 })
Jiyong Parkb81b9902020-11-24 19:51:18 +0900581 implicitInputs = append(implicitInputs, cannedFsConfig)
Jiyong Park09d77522019-11-18 11:16:27 +0900582
Jiyong Parkb81b9902020-11-24 19:51:18 +0900583 ////////////////////////////////////////////////////////////////////////////////////
584 // Step 3: Prepare option flags for apexer and invoke it to create an unsigned APEX.
585 // TODO(jiyong): use the RuleBuilder
Jiyong Park09d77522019-11-18 11:16:27 +0900586 optFlags := []string{}
587
Jiyong Parkb81b9902020-11-24 19:51:18 +0900588 fileContexts := a.buildFileContexts(ctx)
589 implicitInputs = append(implicitInputs, fileContexts)
590
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800591 implicitInputs = append(implicitInputs, a.privateKeyFile, a.publicKeyFile)
592 optFlags = append(optFlags, "--pubkey "+a.publicKeyFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900593
Jooyung Han27151d92019-12-16 17:45:32 +0900594 manifestPackageName := a.getOverrideManifestPackageName(ctx)
595 if manifestPackageName != "" {
Jiyong Park09d77522019-11-18 11:16:27 +0900596 optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
597 }
598
599 if a.properties.AndroidManifest != nil {
600 androidManifestFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.AndroidManifest))
601 implicitInputs = append(implicitInputs, androidManifestFile)
602 optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
603 }
604
Jiyong Parkb81b9902020-11-24 19:51:18 +0900605 // Determine target/min sdk version from the context
606 // TODO(jiyong): make this as a function
Dan Albertc8060532020-07-22 22:32:17 -0700607 moduleMinSdkVersion := a.minSdkVersion(ctx)
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100608 minSdkVersion := moduleMinSdkVersion.String()
609
Jiyong Parkb81b9902020-11-24 19:51:18 +0900610 // bundletool doesn't understand what "current" is. We need to transform it to
611 // codename
Jooyung Haned124c32021-01-26 11:43:46 +0900612 if moduleMinSdkVersion.IsCurrent() || moduleMinSdkVersion.IsNone() {
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100613 minSdkVersion = ctx.Config().DefaultAppTargetSdk(ctx).String()
Liz Kammer4854a7d2021-05-27 14:28:27 -0400614
615 if java.UseApiFingerprint(ctx) {
616 minSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
617 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
618 }
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000619 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900620 // apex module doesn't have a concept of target_sdk_version, hence for the time
621 // being targetSdkVersion == default targetSdkVersion of the branch.
Nikita Ioffe5335bc42020-10-20 00:02:15 +0100622 targetSdkVersion := strconv.Itoa(ctx.Config().DefaultAppTargetSdk(ctx).FinalOrFutureInt())
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000623
Nikita Ioffe1f4f3452020-03-02 16:58:11 +0000624 if java.UseApiFingerprint(ctx) {
625 targetSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
Baligh Uddinf6201372020-01-24 23:15:44 +0000626 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
627 }
Jiyong Park09d77522019-11-18 11:16:27 +0900628 optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
Baligh Uddinf6201372020-01-24 23:15:44 +0000629 optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
Jiyong Park09d77522019-11-18 11:16:27 +0900630
Baligh Uddin004d7172020-02-19 21:29:28 -0800631 if a.overridableProperties.Logging_parent != "" {
632 optFlags = append(optFlags, "--logging_parent ", a.overridableProperties.Logging_parent)
633 }
634
Jiyong Park19972c72020-01-28 20:05:29 +0900635 a.mergedNotices = a.buildNoticeFiles(ctx, a.Name()+suffix)
636 if a.mergedNotices.HtmlGzOutput.Valid() {
Jiyong Park09d77522019-11-18 11:16:27 +0900637 // If there's a NOTICE file, embed it as an asset file in the APEX.
Jiyong Park19972c72020-01-28 20:05:29 +0900638 implicitInputs = append(implicitInputs, a.mergedNotices.HtmlGzOutput.Path())
639 optFlags = append(optFlags, "--assets_dir "+filepath.Dir(a.mergedNotices.HtmlGzOutput.String()))
Jiyong Park09d77522019-11-18 11:16:27 +0900640 }
641
Nikita Ioffe9d9960f2021-06-09 19:43:46 +0100642 if (moduleMinSdkVersion.GreaterThan(android.SdkVersion_Android10) && !a.shouldGenerateHashtree()) && !compressionEnabled {
Jiyong Park09d77522019-11-18 11:16:27 +0900643 // Apexes which are supposed to be installed in builtin dirs(/system, etc)
644 // don't need hashtree for activation. Therefore, by removing hashtree from
645 // apex bundle (filesystem image in it, to be specific), we can save storage.
646 optFlags = append(optFlags, "--no_hashtree")
647 }
648
Dario Frenica913392020-04-27 18:21:11 +0100649 if a.testOnlyShouldSkipPayloadSign() {
650 optFlags = append(optFlags, "--unsigned_payload")
651 }
652
Jiyong Park09d77522019-11-18 11:16:27 +0900653 if a.properties.Apex_name != nil {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900654 // If apex_name is set, apexer can skip checking if key name matches with
655 // apex name. Note that apex_manifest is also mended.
Jiyong Park09d77522019-11-18 11:16:27 +0900656 optFlags = append(optFlags, "--do_not_check_keyname")
657 }
658
Dan Albertc8060532020-07-22 22:32:17 -0700659 if moduleMinSdkVersion == android.SdkVersion_Android10 {
Jooyung Han214bf372019-11-12 13:03:50 +0900660 implicitInputs = append(implicitInputs, a.manifestJsonOut)
661 optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
662 }
663
Theotime Combes4ba38c12020-06-12 12:46:59 +0000664 optFlags = append(optFlags, "--payload_fs_type "+a.payloadFsType.string())
665
Jiyong Park09d77522019-11-18 11:16:27 +0900666 ctx.Build(pctx, android.BuildParams{
667 Rule: apexRule,
668 Implicits: implicitInputs,
669 Output: unsignedOutputFile,
670 Description: "apex (" + apexType.name() + ")",
671 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900672 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900673 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900674 "copy_commands": strings.Join(copyCommands, " && "),
675 "manifest": a.manifestPbOut.String(),
Jiyong Parkb81b9902020-11-24 19:51:18 +0900676 "file_contexts": fileContexts.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900677 "canned_fs_config": cannedFsConfig.String(),
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800678 "key": a.privateKeyFile.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900679 "opt_flags": strings.Join(optFlags, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900680 },
681 })
682
Jiyong Parkb81b9902020-11-24 19:51:18 +0900683 // TODO(jiyong): make the two rules below as separate functions
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800684 apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
685 bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
Jiyong Park09d77522019-11-18 11:16:27 +0900686 a.bundleModuleFile = bundleModuleFile
687
688 ctx.Build(pctx, android.BuildParams{
689 Rule: apexProtoConvertRule,
690 Input: unsignedOutputFile,
691 Output: apexProtoFile,
692 Description: "apex proto convert",
693 })
694
sophiezc80a2b32020-11-12 16:39:19 +0000695 implicitInputs = append(implicitInputs, unsignedOutputFile)
696
697 // Run coverage analysis
sophiez6bde0b52021-01-09 01:03:42 +0000698 apisUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.txt")
sophiezc80a2b32020-11-12 16:39:19 +0000699 ctx.Build(pctx, android.BuildParams{
700 Rule: generateAPIsUsedbyApexRule,
701 Implicits: implicitInputs,
702 Description: "coverage",
703 Output: apisUsedbyOutputFile,
704 Args: map[string]string{
705 "image_dir": imageDir.String(),
706 "readelf": "${config.ClangBin}/llvm-readelf",
707 },
708 })
sophiez6bde0b52021-01-09 01:03:42 +0000709 a.apisUsedByModuleFile = apisUsedbyOutputFile
710
Colin Cross69f0a242021-02-08 16:49:57 -0800711 var libNames []string
712 for _, f := range a.filesInfo {
713 if f.class == nativeSharedLib {
714 libNames = append(libNames, f.stem())
715 }
716 }
sophiez6bde0b52021-01-09 01:03:42 +0000717 apisBackedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_backing.txt")
718 ndkLibraryList := android.PathForSource(ctx, "system/core/rootdir/etc/public.libraries.android.txt")
719 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 Input(ndkLibraryList).
724 Flags(libNames)
sophiez6bde0b52021-01-09 01:03:42 +0000725 rule.Build("ndk_backedby_list", "Generate API libraries backed by Apex")
726 a.apisBackedByModuleFile = apisBackedbyOutputFile
sophiezc80a2b32020-11-12 16:39:19 +0000727
Jiyong Parkbd159612020-02-28 15:22:21 +0900728 bundleConfig := a.buildBundleConfig(ctx)
729
Jiyong Parkb81b9902020-11-24 19:51:18 +0900730 var abis []string
731 for _, target := range ctx.MultiTargets() {
732 if len(target.Arch.Abi) > 0 {
733 abis = append(abis, target.Arch.Abi[0])
734 }
735 }
736
737 abis = android.FirstUniqueStrings(abis)
738
Jiyong Park09d77522019-11-18 11:16:27 +0900739 ctx.Build(pctx, android.BuildParams{
740 Rule: apexBundleRule,
741 Input: apexProtoFile,
Jiyong Parkbd159612020-02-28 15:22:21 +0900742 Implicit: bundleConfig,
Jiyong Park09d77522019-11-18 11:16:27 +0900743 Output: a.bundleModuleFile,
744 Description: "apex bundle module",
745 Args: map[string]string{
Jiyong Parkbd159612020-02-28 15:22:21 +0900746 "abi": strings.Join(abis, "."),
747 "config": bundleConfig.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900748 },
749 })
Jiyong Parkb81b9902020-11-24 19:51:18 +0900750 } else { // zipApex
Jiyong Park09d77522019-11-18 11:16:27 +0900751 ctx.Build(pctx, android.BuildParams{
752 Rule: zipApexRule,
753 Implicits: implicitInputs,
754 Output: unsignedOutputFile,
755 Description: "apex (" + apexType.name() + ")",
756 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900757 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900758 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900759 "copy_commands": strings.Join(copyCommands, " && "),
760 "manifest": a.manifestPbOut.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900761 },
762 })
763 }
764
Jiyong Parkb81b9902020-11-24 19:51:18 +0900765 ////////////////////////////////////////////////////////////////////////////////////
766 // Step 4: Sign the APEX using signapk
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000767 signedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900768
769 pem, key := a.getCertificateAndPrivateKey(ctx)
Kousik Kumar309b1c02020-05-28 06:13:33 -0700770 rule := java.Signapk
771 args := map[string]string{
Jiyong Parkb81b9902020-11-24 19:51:18 +0900772 "certificates": pem.String() + " " + key.String(),
Jooyung Han5d00f502021-07-11 07:26:22 +0900773 "flags": "-a 4096 --align-file-size", //alignment
Kousik Kumar309b1c02020-05-28 06:13:33 -0700774 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900775 implicits := android.Paths{pem, key}
Ramy Medhat16f23a42020-09-03 01:29:49 -0400776 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
Kousik Kumar309b1c02020-05-28 06:13:33 -0700777 rule = java.SignapkRE
778 args["implicits"] = strings.Join(implicits.Strings(), ",")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000779 args["outCommaList"] = signedOutputFile.String()
Kousik Kumar309b1c02020-05-28 06:13:33 -0700780 }
Jiyong Park09d77522019-11-18 11:16:27 +0900781 ctx.Build(pctx, android.BuildParams{
Kousik Kumar309b1c02020-05-28 06:13:33 -0700782 Rule: rule,
Jiyong Park09d77522019-11-18 11:16:27 +0900783 Description: "signapk",
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000784 Output: signedOutputFile,
Jiyong Park09d77522019-11-18 11:16:27 +0900785 Input: unsignedOutputFile,
Kousik Kumar309b1c02020-05-28 06:13:33 -0700786 Implicits: implicits,
787 Args: args,
Jiyong Park09d77522019-11-18 11:16:27 +0900788 })
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000789 a.outputFile = signedOutputFile
790
Mohammad Samiul Islama8008f92020-12-22 10:47:50 +0000791 if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && a.testOnlyShouldForceCompression() {
792 ctx.PropertyErrorf("test_only_force_compression", "not available")
793 return
794 }
Nikita Ioffebc035882021-04-14 21:35:24 +0100795
Mohammad Samiul Islama8008f92020-12-22 10:47:50 +0000796 if apexType == imageApex && (compressionEnabled || a.testOnlyShouldForceCompression()) {
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000797 a.isCompressed = true
Samiul Islam7c02e262021-09-08 17:48:28 +0100798 unsignedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix+".unsigned")
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000799
800 compressRule := android.NewRuleBuilder(pctx, ctx)
801 compressRule.Command().
802 Text("rm").
803 FlagWithOutput("-f ", unsignedCompressedOutputFile)
804 compressRule.Command().
805 BuiltTool("apex_compression_tool").
806 Flag("compress").
807 FlagWithArg("--apex_compression_tool ", outHostBinDir+":"+prebuiltSdkToolsBinDir).
808 FlagWithInput("--input ", signedOutputFile).
809 FlagWithOutput("--output ", unsignedCompressedOutputFile)
810 compressRule.Build("compressRule", "Generate unsigned compressed APEX file")
811
Samiul Islam7c02e262021-09-08 17:48:28 +0100812 signedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix)
Mohammad Samiul Islam9ac0e322021-01-19 11:32:29 +0000813 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
814 args["outCommaList"] = signedCompressedOutputFile.String()
815 }
Mohammad Samiul Islam3cd005d2020-11-26 13:32:26 +0000816 ctx.Build(pctx, android.BuildParams{
817 Rule: rule,
818 Description: "sign compressedApex",
819 Output: signedCompressedOutputFile,
820 Input: unsignedCompressedOutputFile,
821 Implicits: implicits,
822 Args: args,
823 })
824 a.outputFile = signedCompressedOutputFile
825 }
Jiyong Park09d77522019-11-18 11:16:27 +0900826
827 // Install to $OUT/soong/{target,host}/.../apex
828 if a.installable() {
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800829 ctx.InstallFile(a.installDir, a.Name()+suffix, a.outputFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900830 }
Jiyong Park3a1602e2020-01-14 14:39:19 +0900831
832 // installed-files.txt is dist'ed
833 a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900834}
835
Jiyong Parkc0ec6f92020-11-19 23:00:52 +0900836// Context "decorator", overriding the InstallBypassMake method to always reply `true`.
837type flattenedApexContext struct {
838 android.ModuleContext
839}
840
841func (c *flattenedApexContext) InstallBypassMake() bool {
842 return true
843}
844
Jiyong Parkb81b9902020-11-24 19:51:18 +0900845// buildFlattenedApex creates rules for a flattened APEX. Flattened APEX actually doesn't have a
846// single output file. It is a phony target for all the files under /system/apex/<name> directory.
847// This function creates the installation rules for the files.
Jiyong Park09d77522019-11-18 11:16:27 +0900848func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900849 bundleName := a.Name()
Jiyong Park09d77522019-11-18 11:16:27 +0900850 if a.installable() {
Jiyong Parkb81b9902020-11-24 19:51:18 +0900851 for _, fi := range a.filesInfo {
852 dir := filepath.Join("apex", bundleName, fi.installDir)
853 target := ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.stem(), fi.builtFile)
854 for _, sym := range fi.symlinks {
855 ctx.InstallSymlink(android.PathForModuleInstall(ctx, dir), sym, target)
Jiyong Park09d77522019-11-18 11:16:27 +0900856 }
857 }
858 }
Jiyong Parkb81b9902020-11-24 19:51:18 +0900859
860 a.fileContexts = a.buildFileContexts(ctx)
861
862 // Temporarily wrap the original `ctx` into a `flattenedApexContext` to have it reply true
863 // to `InstallBypassMake()` (thus making the call `android.PathForModuleInstall` below use
864 // `android.pathForInstallInMakeDir` instead of `android.PathForOutput`) to return the
865 // correct path to the flattened APEX (as its contents is installed by Make, not Soong).
866 // TODO(jiyong): Why do we need to set outputFile for flattened APEX? We don't seem to use
867 // it and it actually points to a path that can never be built. Remove this.
868 factx := flattenedApexContext{ctx}
869 a.outputFile = android.PathForModuleInstall(&factx, "apex", bundleName)
870}
871
872// getCertificateAndPrivateKey retrieves the cert and the private key that will be used to sign
873// the zip container of this APEX. See the description of the 'certificate' property for how
874// the cert and the private key are found.
875func (a *apexBundle) getCertificateAndPrivateKey(ctx android.PathContext) (pem, key android.Path) {
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800876 if a.containerCertificateFile != nil {
877 return a.containerCertificateFile, a.containerPrivateKeyFile
Jiyong Parkb81b9902020-11-24 19:51:18 +0900878 }
879
Jaewoong Jung4cfdf7d2021-04-20 16:21:24 -0700880 cert := String(a.overridableProperties.Certificate)
Jiyong Parkb81b9902020-11-24 19:51:18 +0900881 if cert == "" {
882 return ctx.Config().DefaultAppCertificate(ctx)
883 }
884
885 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
886 pem = defaultDir.Join(ctx, cert+".x509.pem")
887 key = defaultDir.Join(ctx, cert+".pk8")
888 return pem, key
Jiyong Park09d77522019-11-18 11:16:27 +0900889}
Jooyung Han27151d92019-12-16 17:45:32 +0900890
891func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
892 // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
893 // to see if it should be overridden because their <apex name> is dynamically generated
894 // according to its VNDK version.
895 if a.vndkApex {
896 overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
897 if overridden {
898 return strings.Replace(*a.properties.Apex_name, vndkApexName, overrideName, 1)
899 }
900 return ""
901 }
Baligh Uddin5b57dba2020-03-15 13:01:05 -0700902 if a.overridableProperties.Package_name != "" {
903 return a.overridableProperties.Package_name
904 }
Jiyong Park20bacab2020-03-03 11:45:41 +0900905 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jooyung Han27151d92019-12-16 17:45:32 +0900906 if overridden {
907 return manifestPackageName
908 }
909 return ""
910}
Jiyong Park83dc74b2020-01-14 18:38:44 +0900911
912func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
913 if !a.primaryApexType {
914 return
915 }
916
917 if a.properties.IsCoverageVariant {
918 // Otherwise, we will have duplicated rules for coverage and
919 // non-coverage variants of the same APEX
920 return
921 }
922
923 if ctx.Host() {
924 // No need to generate dependency info for host variant
925 return
926 }
927
Artur Satayev872a1442020-04-27 17:08:37 +0100928 depInfos := android.DepNameToDepInfoMap{}
Jooyung Han749dc692020-04-15 11:03:39 +0900929 a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
Artur Satayev872a1442020-04-27 17:08:37 +0100930 if from.Name() == to.Name() {
931 // This can happen for cc.reuseObjTag. We are not interested in tracking this.
932 // As soon as the dependency graph crosses the APEX boundary, don't go further.
933 return !externalDep
Jiyong Park678c8812020-02-07 17:25:49 +0900934 }
Jiyong Park83dc74b2020-01-14 18:38:44 +0900935
Artur Satayev533b98c2021-03-11 18:03:42 +0000936 // Skip dependencies that are only available to APEXes; they are developed with updatability
937 // in mind and don't need manual approval.
938 if to.(android.ApexModule).NotAvailableForPlatform() {
939 return !externalDep
940 }
941
Cindy Zhou18417cb2020-12-10 07:12:38 -0800942 depTag := ctx.OtherModuleDependencyTag(to)
Artur Satayev533b98c2021-03-11 18:03:42 +0000943 // Check to see if dependency been marked to skip the dependency check
Cindy Zhou18417cb2020-12-10 07:12:38 -0800944 if skipDepCheck, ok := depTag.(android.SkipApexAllowedDependenciesCheck); ok && skipDepCheck.SkipApexAllowedDependenciesCheck() {
Cindy Zhou18417cb2020-12-10 07:12:38 -0800945 return !externalDep
946 }
947
Artur Satayev872a1442020-04-27 17:08:37 +0100948 if info, exists := depInfos[to.Name()]; exists {
949 if !android.InList(from.Name(), info.From) {
950 info.From = append(info.From, from.Name())
951 }
952 info.IsExternal = info.IsExternal && externalDep
953 depInfos[to.Name()] = info
954 } else {
Artur Satayev480e25b2020-04-27 18:53:18 +0100955 toMinSdkVersion := "(no version)"
Jiyong Park92315372021-04-02 08:45:46 +0900956 if m, ok := to.(interface {
957 MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec
958 }); ok {
959 if v := m.MinSdkVersion(ctx); !v.ApiLevel.IsNone() {
960 toMinSdkVersion = v.ApiLevel.String()
961 }
962 } else if m, ok := to.(interface{ MinSdkVersion() string }); ok {
963 // TODO(b/175678607) eliminate the use of MinSdkVersion returning
964 // string
Artur Satayev480e25b2020-04-27 18:53:18 +0100965 if v := m.MinSdkVersion(); v != "" {
966 toMinSdkVersion = v
967 }
968 }
Artur Satayev872a1442020-04-27 17:08:37 +0100969 depInfos[to.Name()] = android.ApexModuleDepInfo{
Artur Satayev480e25b2020-04-27 18:53:18 +0100970 To: to.Name(),
971 From: []string{from.Name()},
972 IsExternal: externalDep,
973 MinSdkVersion: toMinSdkVersion,
Artur Satayev872a1442020-04-27 17:08:37 +0100974 }
975 }
976
977 // As soon as the dependency graph crosses the APEX boundary, don't go further.
978 return !externalDep
Jiyong Park83dc74b2020-01-14 18:38:44 +0900979 })
980
Artur Satayev480e25b2020-04-27 18:53:18 +0100981 a.ApexBundleDepsInfo.BuildDepsInfoLists(ctx, proptools.String(a.properties.Min_sdk_version), depInfos)
Artur Satayev872a1442020-04-27 17:08:37 +0100982
Jiyong Park83dc74b2020-01-14 18:38:44 +0900983 ctx.Build(pctx, android.BuildParams{
984 Rule: android.Phony,
985 Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
Artur Satayeva8bd1132020-04-27 18:07:06 +0100986 Inputs: []android.Path{
987 a.ApexBundleDepsInfo.FullListPath(),
988 a.ApexBundleDepsInfo.FlatListPath(),
989 },
Jiyong Park83dc74b2020-01-14 18:38:44 +0900990 })
991}
Colin Cross08dca382020-07-21 20:31:17 -0700992
993func (a *apexBundle) buildLintReports(ctx android.ModuleContext) {
994 depSetsBuilder := java.NewLintDepSetBuilder()
995 for _, fi := range a.filesInfo {
996 depSetsBuilder.Transitive(fi.lintDepSets)
997 }
998
999 a.lintReports = java.BuildModuleLintReportZips(ctx, depSetsBuilder.Build())
1000}