blob: a6a347b5f87deb6a06f84ae05f482d222a3be68b [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"
Jooyung Han5417f772020-03-12 18:37:20 +090023 "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")
39 pctx.Import("android/soong/java")
40 pctx.HostBinToolVariable("apexer", "apexer")
41 // ART minimal builds (using the master-art manifest) do not have the "frameworks/base"
42 // projects, and hence cannot built 'aapt2'. Use the SDK prebuilt instead.
43 hostBinToolVariableWithPrebuilt := func(name, prebuiltDir, tool string) {
44 pctx.VariableFunc(name, func(ctx android.PackageVarContext) string {
45 if !ctx.Config().FrameworksBaseDirExists(ctx) {
46 return filepath.Join(prebuiltDir, runtime.GOOS, "bin", tool)
47 } else {
Martin Stjernholm7260d062019-12-09 21:47:14 +000048 return ctx.Config().HostToolPath(ctx, tool).String()
Jiyong Park09d77522019-11-18 11:16:27 +090049 }
50 })
51 }
52 hostBinToolVariableWithPrebuilt("aapt2", "prebuilts/sdk/tools", "aapt2")
53 pctx.HostBinToolVariable("avbtool", "avbtool")
54 pctx.HostBinToolVariable("e2fsdroid", "e2fsdroid")
55 pctx.HostBinToolVariable("merge_zips", "merge_zips")
56 pctx.HostBinToolVariable("mke2fs", "mke2fs")
57 pctx.HostBinToolVariable("resize2fs", "resize2fs")
58 pctx.HostBinToolVariable("sefcontext_compile", "sefcontext_compile")
59 pctx.HostBinToolVariable("soong_zip", "soong_zip")
60 pctx.HostBinToolVariable("zip2zip", "zip2zip")
61 pctx.HostBinToolVariable("zipalign", "zipalign")
62 pctx.HostBinToolVariable("jsonmodify", "jsonmodify")
63 pctx.HostBinToolVariable("conv_apex_manifest", "conv_apex_manifest")
Jaewoong Jungfa00c062020-05-14 14:15:24 -070064 pctx.HostBinToolVariable("extract_apks", "extract_apks")
Jiyong Park09d77522019-11-18 11:16:27 +090065}
66
67var (
68 // Create a canned fs config file where all files and directories are
69 // by default set to (uid/gid/mode) = (1000/1000/0644)
70 // TODO(b/113082813) make this configurable using config.fs syntax
71 generateFsConfig = pctx.StaticRule("generateFsConfig", blueprint.RuleParams{
72 Command: `echo '/ 1000 1000 0755' > ${out} && ` +
73 `echo ${ro_paths} | tr ' ' '\n' | awk '{print "/"$$1 " 1000 1000 0644"}' >> ${out} && ` +
74 `echo ${exec_paths} | tr ' ' '\n' | awk '{print "/"$$1 " 0 2000 0755"}' >> ${out}`,
75 Description: "fs_config ${out}",
76 }, "ro_paths", "exec_paths")
77
78 apexManifestRule = pctx.StaticRule("apexManifestRule", blueprint.RuleParams{
79 Command: `rm -f $out && ${jsonmodify} $in ` +
80 `-a provideNativeLibs ${provideNativeLibs} ` +
81 `-a requireNativeLibs ${requireNativeLibs} ` +
82 `${opt} ` +
83 `-o $out`,
84 CommandDeps: []string{"${jsonmodify}"},
85 Description: "prepare ${out}",
86 }, "provideNativeLibs", "requireNativeLibs", "opt")
87
88 stripApexManifestRule = pctx.StaticRule("stripApexManifestRule", blueprint.RuleParams{
89 Command: `rm -f $out && ${conv_apex_manifest} strip $in -o $out`,
90 CommandDeps: []string{"${conv_apex_manifest}"},
91 Description: "strip ${in}=>${out}",
92 })
93
94 pbApexManifestRule = pctx.StaticRule("pbApexManifestRule", blueprint.RuleParams{
95 Command: `rm -f $out && ${conv_apex_manifest} proto $in -o $out`,
96 CommandDeps: []string{"${conv_apex_manifest}"},
97 Description: "convert ${in}=>${out}",
98 })
99
100 // TODO(b/113233103): make sure that file_contexts is sane, i.e., validate
101 // against the binary policy using sefcontext_compiler -p <policy>.
102
103 // TODO(b/114327326): automate the generation of file_contexts
104 apexRule = pctx.StaticRule("apexRule", blueprint.RuleParams{
105 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
106 `(. ${out}.copy_commands) && ` +
107 `APEXER_TOOL_PATH=${tool_path} ` +
108 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900109 `--file_contexts ${file_contexts} ` +
110 `--canned_fs_config ${canned_fs_config} ` +
Dario Freni0f4ae072020-01-02 15:24:12 +0000111 `--include_build_info ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900112 `--payload_type image ` +
113 `--key ${key} ${opt_flags} ${image_dir} ${out} `,
114 CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
115 "${mke2fs}", "${resize2fs}", "${sefcontext_compile}",
116 "${soong_zip}", "${zipalign}", "${aapt2}", "prebuilts/sdk/current/public/android.jar"},
117 Rspfile: "${out}.copy_commands",
118 RspfileContent: "${copy_commands}",
119 Description: "APEX ${image_dir} => ${out}",
Jooyung Han214bf372019-11-12 13:03:50 +0900120 }, "tool_path", "image_dir", "copy_commands", "file_contexts", "canned_fs_config", "key", "opt_flags", "manifest")
Jiyong Park09d77522019-11-18 11:16:27 +0900121
122 zipApexRule = pctx.StaticRule("zipApexRule", blueprint.RuleParams{
123 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
124 `(. ${out}.copy_commands) && ` +
125 `APEXER_TOOL_PATH=${tool_path} ` +
Jooyung Han214bf372019-11-12 13:03:50 +0900126 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900127 `--payload_type zip ` +
128 `${image_dir} ${out} `,
129 CommandDeps: []string{"${apexer}", "${merge_zips}", "${soong_zip}", "${zipalign}", "${aapt2}"},
130 Rspfile: "${out}.copy_commands",
131 RspfileContent: "${copy_commands}",
132 Description: "ZipAPEX ${image_dir} => ${out}",
Jooyung Han214bf372019-11-12 13:03:50 +0900133 }, "tool_path", "image_dir", "copy_commands", "manifest")
Jiyong Park09d77522019-11-18 11:16:27 +0900134
135 apexProtoConvertRule = pctx.AndroidStaticRule("apexProtoConvertRule",
136 blueprint.RuleParams{
137 Command: `${aapt2} convert --output-format proto $in -o $out`,
138 CommandDeps: []string{"${aapt2}"},
139 })
140
141 apexBundleRule = pctx.StaticRule("apexBundleRule", blueprint.RuleParams{
Jiyong Parkbd159612020-02-28 15:22:21 +0900142 Command: `${zip2zip} -i $in -o $out.base ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900143 `apex_payload.img:apex/${abi}.img ` +
Dario Frenida1aefe2020-03-02 21:47:09 +0000144 `apex_build_info.pb:apex/${abi}.build_info.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900145 `apex_manifest.json:root/apex_manifest.json ` +
Jiyong Park53ae3342019-12-08 02:06:24 +0900146 `apex_manifest.pb:root/apex_manifest.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900147 `AndroidManifest.xml:manifest/AndroidManifest.xml ` +
Jiyong Parkbd159612020-02-28 15:22:21 +0900148 `assets/NOTICE.html.gz:assets/NOTICE.html.gz &&` +
149 `${soong_zip} -o $out.config -C $$(dirname ${config}) -f ${config} && ` +
150 `${merge_zips} $out $out.base $out.config`,
151 CommandDeps: []string{"${zip2zip}", "${soong_zip}", "${merge_zips}"},
Jiyong Park09d77522019-11-18 11:16:27 +0900152 Description: "app bundle",
Jiyong Parkbd159612020-02-28 15:22:21 +0900153 }, "abi", "config")
Jiyong Park09d77522019-11-18 11:16:27 +0900154
155 emitApexContentRule = pctx.StaticRule("emitApexContentRule", blueprint.RuleParams{
156 Command: `rm -f ${out} && touch ${out} && (. ${out}.emit_commands)`,
157 Rspfile: "${out}.emit_commands",
158 RspfileContent: "${emit_commands}",
159 Description: "Emit APEX image content",
160 }, "emit_commands")
161
162 diffApexContentRule = pctx.StaticRule("diffApexContentRule", blueprint.RuleParams{
163 Command: `diff --unchanged-group-format='' \` +
164 `--changed-group-format='%<' \` +
165 `${image_content_file} ${whitelisted_files_file} || (` +
166 `echo -e "New unexpected files were added to ${apex_module_name}." ` +
167 ` "To fix the build run following command:" && ` +
168 `echo "system/apex/tools/update_whitelist.sh ${whitelisted_files_file} ${image_content_file}" && ` +
Dan Willemsen81e43c52020-01-28 15:40:19 -0800169 `exit 1); touch ${out}`,
Jiyong Park09d77522019-11-18 11:16:27 +0900170 Description: "Diff ${image_content_file} and ${whitelisted_files_file}",
171 }, "image_content_file", "whitelisted_files_file", "apex_module_name")
172)
173
174func (a *apexBundle) buildManifest(ctx android.ModuleContext, provideNativeLibs, requireNativeLibs []string) {
175 manifestSrc := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
176
Jooyung Han214bf372019-11-12 13:03:50 +0900177 manifestJsonFullOut := android.PathForModuleOut(ctx, "apex_manifest_full.json")
Jiyong Park09d77522019-11-18 11:16:27 +0900178
179 // put dependency({provide|require}NativeLibs) in apex_manifest.json
180 provideNativeLibs = android.SortedUniqueStrings(provideNativeLibs)
181 requireNativeLibs = android.SortedUniqueStrings(android.RemoveListFromList(requireNativeLibs, provideNativeLibs))
182
183 // apex name can be overridden
184 optCommands := []string{}
185 if a.properties.Apex_name != nil {
186 optCommands = append(optCommands, "-v name "+*a.properties.Apex_name)
187 }
188
Jooyung Han643adc42020-02-27 13:50:06 +0900189 // collect jniLibs. Notice that a.filesInfo is already sorted
190 var jniLibs []string
191 for _, fi := range a.filesInfo {
192 if fi.isJniLib {
193 jniLibs = append(jniLibs, fi.builtFile.Base())
194 }
195 }
196 if len(jniLibs) > 0 {
197 optCommands = append(optCommands, "-a jniLibs "+strings.Join(jniLibs, " "))
198 }
199
Jiyong Park09d77522019-11-18 11:16:27 +0900200 ctx.Build(pctx, android.BuildParams{
201 Rule: apexManifestRule,
202 Input: manifestSrc,
Jooyung Han214bf372019-11-12 13:03:50 +0900203 Output: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900204 Args: map[string]string{
205 "provideNativeLibs": strings.Join(provideNativeLibs, " "),
206 "requireNativeLibs": strings.Join(requireNativeLibs, " "),
207 "opt": strings.Join(optCommands, " "),
208 },
209 })
210
Jooyung Han5417f772020-03-12 18:37:20 +0900211 if a.minSdkVersion(ctx) == android.SdkVersion_Android10 {
Jooyung Han214bf372019-11-12 13:03:50 +0900212 // b/143654022 Q apexd can't understand newly added keys in apex_manifest.json
213 // prepare stripped-down version so that APEX modules built from R+ can be installed to Q
214 a.manifestJsonOut = android.PathForModuleOut(ctx, "apex_manifest.json")
215 ctx.Build(pctx, android.BuildParams{
216 Rule: stripApexManifestRule,
217 Input: manifestJsonFullOut,
218 Output: a.manifestJsonOut,
219 })
220 }
Jiyong Park09d77522019-11-18 11:16:27 +0900221
222 // from R+, protobuf binary format (.pb) is the standard format for apex_manifest
223 a.manifestPbOut = android.PathForModuleOut(ctx, "apex_manifest.pb")
224 ctx.Build(pctx, android.BuildParams{
225 Rule: pbApexManifestRule,
Jooyung Han214bf372019-11-12 13:03:50 +0900226 Input: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900227 Output: a.manifestPbOut,
228 })
229}
230
Jiyong Park19972c72020-01-28 20:05:29 +0900231func (a *apexBundle) buildNoticeFiles(ctx android.ModuleContext, apexFileName string) android.NoticeOutputs {
Jiyong Park9918e1a2020-03-17 19:16:40 +0900232 var noticeFiles android.Paths
233
Paul Duffinbe5a5be2020-03-30 15:54:08 +0100234 a.walkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
Jiyong Park9918e1a2020-03-17 19:16:40 +0900235 if externalDep {
Paul Duffinbe5a5be2020-03-30 15:54:08 +0100236 // As soon as the dependency graph crosses the APEX boundary, don't go further.
237 return false
Jiyong Park09d77522019-11-18 11:16:27 +0900238 }
Paul Duffinbe5a5be2020-03-30 15:54:08 +0100239
Jiyong Park9918e1a2020-03-17 19:16:40 +0900240 notices := to.NoticeFiles()
241 noticeFiles = append(noticeFiles, notices...)
Paul Duffinbe5a5be2020-03-30 15:54:08 +0100242
243 return true
Jiyong Park9918e1a2020-03-17 19:16:40 +0900244 })
Jiyong Park09d77522019-11-18 11:16:27 +0900245
246 if len(noticeFiles) == 0 {
Jiyong Park19972c72020-01-28 20:05:29 +0900247 return android.NoticeOutputs{}
Jiyong Park09d77522019-11-18 11:16:27 +0900248 }
249
Jiyong Park19972c72020-01-28 20:05:29 +0900250 return android.BuildNoticeOutput(ctx, a.installDir, apexFileName, android.FirstUniquePaths(noticeFiles))
Jiyong Park09d77522019-11-18 11:16:27 +0900251}
252
Jiyong Park3a1602e2020-01-14 14:39:19 +0900253func (a *apexBundle) buildInstalledFilesFile(ctx android.ModuleContext, builtApex android.Path, imageDir android.Path) android.OutputPath {
254 output := android.PathForModuleOut(ctx, "installed-files.txt")
255 rule := android.NewRuleBuilder()
256 rule.Command().
257 Implicit(builtApex).
258 Text("(cd " + imageDir.String() + " ; ").
Jiyong Parkbd63a102020-02-08 12:40:05 +0900259 Text("find . \\( -type f -o -type l \\) -printf \"%s %p\\n\") ").
Jiyong Park3a1602e2020-01-14 14:39:19 +0900260 Text(" | sort -nr > ").
261 Output(output)
262 rule.Build(pctx, ctx, "installed-files."+a.Name(), "Installed files")
263 return output.OutputPath
264}
265
Jiyong Parkbd159612020-02-28 15:22:21 +0900266func (a *apexBundle) buildBundleConfig(ctx android.ModuleContext) android.OutputPath {
267 output := android.PathForModuleOut(ctx, "bundle_config.json")
268
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900269 type ApkConfig struct {
270 Package_name string `json:"package_name"`
271 Apk_path string `json:"path"`
272 }
Jiyong Parkbd159612020-02-28 15:22:21 +0900273 config := struct {
274 Compression struct {
275 Uncompressed_glob []string `json:"uncompressed_glob"`
276 } `json:"compression"`
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900277 Apex_config struct {
278 Apex_embedded_apk_config []ApkConfig `json:"apex_embedded_apk_config,omitempty"`
279 } `json:"apex_config,omitempty"`
Jiyong Parkbd159612020-02-28 15:22:21 +0900280 }{}
281
282 config.Compression.Uncompressed_glob = []string{
283 "apex_payload.img",
284 "apex_manifest.*",
285 }
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900286
287 // collect the manifest names and paths of android apps
288 // if their manifest names are overridden
289 for _, fi := range a.filesInfo {
290 if fi.class != app {
291 continue
292 }
293 packageName := fi.overriddenPackageName
294 if packageName != "" {
295 config.Apex_config.Apex_embedded_apk_config = append(
296 config.Apex_config.Apex_embedded_apk_config,
297 ApkConfig{
298 Package_name: packageName,
299 Apk_path: fi.Path(),
300 })
301 }
302 }
303
Jiyong Parkbd159612020-02-28 15:22:21 +0900304 j, err := json.Marshal(config)
305 if err != nil {
306 panic(fmt.Errorf("error while marshalling to %q: %#v", output, err))
307 }
308
309 ctx.Build(pctx, android.BuildParams{
310 Rule: android.WriteFile,
311 Output: output,
312 Description: "Bundle Config " + output.String(),
313 Args: map[string]string{
314 "content": string(j),
315 },
316 })
317
318 return output.OutputPath
319}
320
Jiyong Park09d77522019-11-18 11:16:27 +0900321func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext) {
322 var abis []string
323 for _, target := range ctx.MultiTargets() {
324 if len(target.Arch.Abi) > 0 {
325 abis = append(abis, target.Arch.Abi[0])
326 }
327 }
328
329 abis = android.FirstUniqueStrings(abis)
330
331 apexType := a.properties.ApexType
332 suffix := apexType.suffix()
Jiyong Park7cd10e32020-01-14 09:22:18 +0900333 var implicitInputs []android.Path
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800334 unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
Jiyong Park09d77522019-11-18 11:16:27 +0900335
Jiyong Park7cd10e32020-01-14 09:22:18 +0900336 // TODO(jiyong): construct the copy rules using RuleBuilder
337 var copyCommands []string
338 for _, fi := range a.filesInfo {
339 destPath := android.PathForModuleOut(ctx, "image"+suffix, fi.Path()).String()
340 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(destPath))
341 if a.linkToSystemLib && fi.transitiveDep && fi.AvailableToPlatform() {
342 // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
343 pathOnDevice := filepath.Join("/system", fi.Path())
344 copyCommands = append(copyCommands, "ln -sfn "+pathOnDevice+" "+destPath)
345 } else {
346 copyCommands = append(copyCommands, "cp -f "+fi.builtFile.String()+" "+destPath)
347 implicitInputs = append(implicitInputs, fi.builtFile)
348 }
349 // create additional symlinks pointing the file inside the APEX
350 for _, symlinkPath := range fi.SymlinkPaths() {
351 symlinkDest := android.PathForModuleOut(ctx, "image"+suffix, symlinkPath).String()
Tim Joinesc1ef1bb2020-03-18 18:00:41 +0000352 copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
Jiyong Park7cd10e32020-01-14 09:22:18 +0900353 }
Liz Kammer1c14a212020-05-12 15:26:55 -0700354 for _, d := range fi.dataPaths {
355 // TODO(eakammer): This is now the third repetition of ~this logic for test paths, refactoring should be possible
356 relPath := d.Rel()
357 dataPath := d.String()
358 if !strings.HasSuffix(dataPath, relPath) {
359 panic(fmt.Errorf("path %q does not end with %q", dataPath, relPath))
360 }
361
362 dataDest := android.PathForModuleOut(ctx, "image"+suffix, fi.apexRelativePath(relPath)).String()
363
364 copyCommands = append(copyCommands, "cp -f "+d.String()+" "+dataDest)
365 implicitInputs = append(implicitInputs, d)
366 }
Jiyong Park09d77522019-11-18 11:16:27 +0900367 }
368
Jiyong Park7cd10e32020-01-14 09:22:18 +0900369 // TODO(jiyong): use RuleBuilder
370 var emitCommands []string
371 imageContentFile := android.PathForModuleOut(ctx, "content.txt")
Jooyung Han214bf372019-11-12 13:03:50 +0900372 emitCommands = append(emitCommands, "echo ./apex_manifest.pb >> "+imageContentFile.String())
Jooyung Han5417f772020-03-12 18:37:20 +0900373 if a.minSdkVersion(ctx) == android.SdkVersion_Android10 {
Jooyung Han214bf372019-11-12 13:03:50 +0900374 emitCommands = append(emitCommands, "echo ./apex_manifest.json >> "+imageContentFile.String())
375 }
Jiyong Park7cd10e32020-01-14 09:22:18 +0900376 for _, fi := range a.filesInfo {
377 emitCommands = append(emitCommands, "echo './"+fi.Path()+"' >> "+imageContentFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900378 }
379 emitCommands = append(emitCommands, "sort -o "+imageContentFile.String()+" "+imageContentFile.String())
Jooyung Han214bf372019-11-12 13:03:50 +0900380 implicitInputs = append(implicitInputs, a.manifestPbOut)
Jiyong Park09d77522019-11-18 11:16:27 +0900381
382 if a.properties.Whitelisted_files != nil {
383 ctx.Build(pctx, android.BuildParams{
384 Rule: emitApexContentRule,
385 Implicits: implicitInputs,
386 Output: imageContentFile,
387 Description: "emit apex image content",
388 Args: map[string]string{
389 "emit_commands": strings.Join(emitCommands, " && "),
390 },
391 })
392 implicitInputs = append(implicitInputs, imageContentFile)
393 whitelistedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.Whitelisted_files))
394
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800395 phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
Jiyong Park09d77522019-11-18 11:16:27 +0900396 ctx.Build(pctx, android.BuildParams{
397 Rule: diffApexContentRule,
398 Implicits: implicitInputs,
399 Output: phonyOutput,
400 Description: "diff apex image content",
401 Args: map[string]string{
402 "whitelisted_files_file": whitelistedFilesFile.String(),
403 "image_content_file": imageContentFile.String(),
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800404 "apex_module_name": a.Name(),
Jiyong Park09d77522019-11-18 11:16:27 +0900405 },
406 })
407
408 implicitInputs = append(implicitInputs, phonyOutput)
409 }
410
411 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
412 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
413
Jiyong Park3a1602e2020-01-14 14:39:19 +0900414 imageDir := android.PathForModuleOut(ctx, "image"+suffix)
Jiyong Park09d77522019-11-18 11:16:27 +0900415 if apexType == imageApex {
416 // files and dirs that will be created in APEX
417 var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
418 var executablePaths []string // this also includes dirs
419 for _, f := range a.filesInfo {
420 pathInApex := filepath.Join(f.installDir, f.builtFile.Base())
421 if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
422 executablePaths = append(executablePaths, pathInApex)
Liz Kammer1c14a212020-05-12 15:26:55 -0700423 for _, d := range f.dataPaths {
424 readOnlyPaths = append(readOnlyPaths, filepath.Join(f.installDir, d.Rel()))
425 }
Jiyong Park09d77522019-11-18 11:16:27 +0900426 for _, s := range f.symlinks {
427 executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
428 }
429 } else {
430 readOnlyPaths = append(readOnlyPaths, pathInApex)
431 }
432 dir := f.installDir
433 for !android.InList(dir, executablePaths) && dir != "" {
434 executablePaths = append(executablePaths, dir)
435 dir, _ = filepath.Split(dir) // move up to the parent
436 if len(dir) > 0 {
437 // remove trailing slash
438 dir = dir[:len(dir)-1]
439 }
440 }
441 }
442 sort.Strings(readOnlyPaths)
443 sort.Strings(executablePaths)
444 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
445 ctx.Build(pctx, android.BuildParams{
446 Rule: generateFsConfig,
447 Output: cannedFsConfig,
448 Description: "generate fs config",
449 Args: map[string]string{
450 "ro_paths": strings.Join(readOnlyPaths, " "),
451 "exec_paths": strings.Join(executablePaths, " "),
452 },
453 })
454
Jiyong Park09d77522019-11-18 11:16:27 +0900455 optFlags := []string{}
456
457 // Additional implicit inputs.
Jooyung Han54aca7b2019-11-20 02:26:02 +0900458 implicitInputs = append(implicitInputs, cannedFsConfig, a.fileContexts, a.private_key_file, a.public_key_file)
Jiyong Park09d77522019-11-18 11:16:27 +0900459 optFlags = append(optFlags, "--pubkey "+a.public_key_file.String())
460
Jooyung Han27151d92019-12-16 17:45:32 +0900461 manifestPackageName := a.getOverrideManifestPackageName(ctx)
462 if manifestPackageName != "" {
Jiyong Park09d77522019-11-18 11:16:27 +0900463 optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
464 }
465
466 if a.properties.AndroidManifest != nil {
467 androidManifestFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.AndroidManifest))
468 implicitInputs = append(implicitInputs, androidManifestFile)
469 optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
470 }
471
472 targetSdkVersion := ctx.Config().DefaultAppTargetSdk()
Nikita Ioffe644009a2020-05-20 00:16:27 +0100473 // TODO(b/157078772): propagate min_sdk_version to apexer.
Baligh Uddinf6201372020-01-24 23:15:44 +0000474 minSdkVersion := ctx.Config().DefaultAppTargetSdk()
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000475
Jooyung Han5417f772020-03-12 18:37:20 +0900476 if a.minSdkVersion(ctx) == android.SdkVersion_Android10 {
477 minSdkVersion = strconv.Itoa(a.minSdkVersion(ctx))
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000478 }
479
Nikita Ioffe1f4f3452020-03-02 16:58:11 +0000480 if java.UseApiFingerprint(ctx) {
481 targetSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
Baligh Uddinf6201372020-01-24 23:15:44 +0000482 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
483 }
Nikita Ioffe1f4f3452020-03-02 16:58:11 +0000484 if java.UseApiFingerprint(ctx) {
485 minSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
Baligh Uddinf6201372020-01-24 23:15:44 +0000486 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
Jiyong Park09d77522019-11-18 11:16:27 +0900487 }
488 optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
Baligh Uddinf6201372020-01-24 23:15:44 +0000489 optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
Jiyong Park09d77522019-11-18 11:16:27 +0900490
Baligh Uddin004d7172020-02-19 21:29:28 -0800491 if a.overridableProperties.Logging_parent != "" {
492 optFlags = append(optFlags, "--logging_parent ", a.overridableProperties.Logging_parent)
493 }
494
Jiyong Park19972c72020-01-28 20:05:29 +0900495 a.mergedNotices = a.buildNoticeFiles(ctx, a.Name()+suffix)
496 if a.mergedNotices.HtmlGzOutput.Valid() {
Jiyong Park09d77522019-11-18 11:16:27 +0900497 // If there's a NOTICE file, embed it as an asset file in the APEX.
Jiyong Park19972c72020-01-28 20:05:29 +0900498 implicitInputs = append(implicitInputs, a.mergedNotices.HtmlGzOutput.Path())
499 optFlags = append(optFlags, "--assets_dir "+filepath.Dir(a.mergedNotices.HtmlGzOutput.String()))
Jiyong Park09d77522019-11-18 11:16:27 +0900500 }
501
Nikita Ioffeb4b44c02020-01-02 23:01:39 +0000502 if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && ctx.ModuleDir() != "system/apex/shim/build" && a.testOnlyShouldSkipHashtreeGeneration() {
Nikita Ioffec72b5dd2019-12-07 17:30:22 +0000503 ctx.PropertyErrorf("test_only_no_hashtree", "not available")
504 return
505 }
Jooyung Han5417f772020-03-12 18:37:20 +0900506 if a.minSdkVersion(ctx) > android.SdkVersion_Android10 || a.testOnlyShouldSkipHashtreeGeneration() {
Jiyong Park09d77522019-11-18 11:16:27 +0900507 // Apexes which are supposed to be installed in builtin dirs(/system, etc)
508 // don't need hashtree for activation. Therefore, by removing hashtree from
509 // apex bundle (filesystem image in it, to be specific), we can save storage.
510 optFlags = append(optFlags, "--no_hashtree")
511 }
512
Dario Frenica913392020-04-27 18:21:11 +0100513 if a.testOnlyShouldSkipPayloadSign() {
514 optFlags = append(optFlags, "--unsigned_payload")
515 }
516
Jiyong Park09d77522019-11-18 11:16:27 +0900517 if a.properties.Apex_name != nil {
518 // If apex_name is set, apexer can skip checking if key name matches with apex name.
519 // Note that apex_manifest is also mended.
520 optFlags = append(optFlags, "--do_not_check_keyname")
521 }
522
Jooyung Han5417f772020-03-12 18:37:20 +0900523 if a.minSdkVersion(ctx) == android.SdkVersion_Android10 {
Jooyung Han214bf372019-11-12 13:03:50 +0900524 implicitInputs = append(implicitInputs, a.manifestJsonOut)
525 optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
526 }
527
Jiyong Park09d77522019-11-18 11:16:27 +0900528 ctx.Build(pctx, android.BuildParams{
529 Rule: apexRule,
530 Implicits: implicitInputs,
531 Output: unsignedOutputFile,
532 Description: "apex (" + apexType.name() + ")",
533 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900534 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900535 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900536 "copy_commands": strings.Join(copyCommands, " && "),
537 "manifest": a.manifestPbOut.String(),
538 "file_contexts": a.fileContexts.String(),
539 "canned_fs_config": cannedFsConfig.String(),
540 "key": a.private_key_file.String(),
541 "opt_flags": strings.Join(optFlags, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900542 },
543 })
544
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800545 apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
546 bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
Jiyong Park09d77522019-11-18 11:16:27 +0900547 a.bundleModuleFile = bundleModuleFile
548
549 ctx.Build(pctx, android.BuildParams{
550 Rule: apexProtoConvertRule,
551 Input: unsignedOutputFile,
552 Output: apexProtoFile,
553 Description: "apex proto convert",
554 })
555
Jiyong Parkbd159612020-02-28 15:22:21 +0900556 bundleConfig := a.buildBundleConfig(ctx)
557
Jiyong Park09d77522019-11-18 11:16:27 +0900558 ctx.Build(pctx, android.BuildParams{
559 Rule: apexBundleRule,
560 Input: apexProtoFile,
Jiyong Parkbd159612020-02-28 15:22:21 +0900561 Implicit: bundleConfig,
Jiyong Park09d77522019-11-18 11:16:27 +0900562 Output: a.bundleModuleFile,
563 Description: "apex bundle module",
564 Args: map[string]string{
Jiyong Parkbd159612020-02-28 15:22:21 +0900565 "abi": strings.Join(abis, "."),
566 "config": bundleConfig.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900567 },
568 })
569 } else {
570 ctx.Build(pctx, android.BuildParams{
571 Rule: zipApexRule,
572 Implicits: implicitInputs,
573 Output: unsignedOutputFile,
574 Description: "apex (" + apexType.name() + ")",
575 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900576 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900577 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900578 "copy_commands": strings.Join(copyCommands, " && "),
579 "manifest": a.manifestPbOut.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900580 },
581 })
582 }
583
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800584 a.outputFile = android.PathForModuleOut(ctx, a.Name()+suffix)
Kousik Kumar309b1c02020-05-28 06:13:33 -0700585 rule := java.Signapk
586 args := map[string]string{
587 "certificates": a.container_certificate_file.String() + " " + a.container_private_key_file.String(),
588 "flags": "-a 4096", //alignment
589 }
590 implicits := android.Paths{
591 a.container_certificate_file,
592 a.container_private_key_file,
593 }
594 if ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
595 rule = java.SignapkRE
596 args["implicits"] = strings.Join(implicits.Strings(), ",")
597 args["outCommaList"] = a.outputFile.String()
598 }
Jiyong Park09d77522019-11-18 11:16:27 +0900599 ctx.Build(pctx, android.BuildParams{
Kousik Kumar309b1c02020-05-28 06:13:33 -0700600 Rule: rule,
Jiyong Park09d77522019-11-18 11:16:27 +0900601 Description: "signapk",
602 Output: a.outputFile,
603 Input: unsignedOutputFile,
Kousik Kumar309b1c02020-05-28 06:13:33 -0700604 Implicits: implicits,
605 Args: args,
Jiyong Park09d77522019-11-18 11:16:27 +0900606 })
607
608 // Install to $OUT/soong/{target,host}/.../apex
609 if a.installable() {
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800610 ctx.InstallFile(a.installDir, a.Name()+suffix, a.outputFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900611 }
612 a.buildFilesInfo(ctx)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900613
614 // installed-files.txt is dist'ed
615 a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900616}
617
618func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
619 // Temporarily wrap the original `ctx` into a `flattenedApexContext` to have it
620 // reply true to `InstallBypassMake()` (thus making the call
621 // `android.PathForModuleInstall` below use `android.pathForInstallInMakeDir`
622 // instead of `android.PathForOutput`) to return the correct path to the flattened
623 // APEX (as its contents is installed by Make, not Soong).
624 factx := flattenedApexContext{ctx}
Jiyong Parka5948012020-02-07 10:15:14 +0900625 apexBundleName := a.Name()
626 a.outputFile = android.PathForModuleInstall(&factx, "apex", apexBundleName)
Jiyong Park09d77522019-11-18 11:16:27 +0900627
Jiyong Park317645e2019-12-05 13:20:58 +0900628 if a.installable() && a.GetOverriddenBy() == "" {
Jiyong Parka5948012020-02-07 10:15:14 +0900629 installPath := android.PathForModuleInstall(ctx, "apex", apexBundleName)
Jooyung Han54aca7b2019-11-20 02:26:02 +0900630 devicePath := android.InstallPathToOnDevicePath(ctx, installPath)
Jiyong Parka5948012020-02-07 10:15:14 +0900631 addFlattenedFileContextsInfos(ctx, apexBundleName+":"+devicePath+":"+a.fileContexts.String())
Jooyung Han54aca7b2019-11-20 02:26:02 +0900632 }
Jiyong Park09d77522019-11-18 11:16:27 +0900633 a.buildFilesInfo(ctx)
634}
635
636func (a *apexBundle) setCertificateAndPrivateKey(ctx android.ModuleContext) {
Jooyung Hanf121a652019-12-17 14:30:11 +0900637 if a.container_certificate_file == nil {
638 cert := String(a.properties.Certificate)
639 if cert == "" {
640 pem, key := ctx.Config().DefaultAppCertificate(ctx)
641 a.container_certificate_file = pem
642 a.container_private_key_file = key
643 } else {
644 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
645 a.container_certificate_file = defaultDir.Join(ctx, cert+".x509.pem")
646 a.container_private_key_file = defaultDir.Join(ctx, cert+".pk8")
647 }
Jiyong Park09d77522019-11-18 11:16:27 +0900648 }
649}
650
651func (a *apexBundle) buildFilesInfo(ctx android.ModuleContext) {
652 if a.installable() {
Jooyung Han214bf372019-11-12 13:03:50 +0900653 // For flattened APEX, do nothing but make sure that APEX manifest and apex_pubkey are also copied along
Jiyong Park09d77522019-11-18 11:16:27 +0900654 // with other ordinary files.
Jiyong Park7cd10e32020-01-14 09:22:18 +0900655 a.filesInfo = append(a.filesInfo, newApexFile(ctx, a.manifestPbOut, "apex_manifest.pb", ".", etc, nil))
Jiyong Park09d77522019-11-18 11:16:27 +0900656
657 // rename to apex_pubkey
658 copiedPubkey := android.PathForModuleOut(ctx, "apex_pubkey")
659 ctx.Build(pctx, android.BuildParams{
660 Rule: android.Cp,
661 Input: a.public_key_file,
662 Output: copiedPubkey,
663 })
Jiyong Park7cd10e32020-01-14 09:22:18 +0900664 a.filesInfo = append(a.filesInfo, newApexFile(ctx, copiedPubkey, "apex_pubkey", ".", etc, nil))
Jiyong Park09d77522019-11-18 11:16:27 +0900665
666 if a.properties.ApexType == flattenedApex {
Jiyong Parka5948012020-02-07 10:15:14 +0900667 apexBundleName := a.Name()
Jiyong Park09d77522019-11-18 11:16:27 +0900668 for _, fi := range a.filesInfo {
Jiyong Parka5948012020-02-07 10:15:14 +0900669 dir := filepath.Join("apex", apexBundleName, fi.installDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900670 target := ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.builtFile.Base(), fi.builtFile)
671 for _, sym := range fi.symlinks {
672 ctx.InstallSymlink(android.PathForModuleInstall(ctx, dir), sym, target)
673 }
674 }
675 }
676 }
677}
Jooyung Han27151d92019-12-16 17:45:32 +0900678
679func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
680 // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
681 // to see if it should be overridden because their <apex name> is dynamically generated
682 // according to its VNDK version.
683 if a.vndkApex {
684 overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
685 if overridden {
686 return strings.Replace(*a.properties.Apex_name, vndkApexName, overrideName, 1)
687 }
688 return ""
689 }
Baligh Uddin5b57dba2020-03-15 13:01:05 -0700690 if a.overridableProperties.Package_name != "" {
691 return a.overridableProperties.Package_name
692 }
Jiyong Park20bacab2020-03-03 11:45:41 +0900693 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jooyung Han27151d92019-12-16 17:45:32 +0900694 if overridden {
695 return manifestPackageName
696 }
697 return ""
698}
Jiyong Park83dc74b2020-01-14 18:38:44 +0900699
700func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
701 if !a.primaryApexType {
702 return
703 }
704
705 if a.properties.IsCoverageVariant {
706 // Otherwise, we will have duplicated rules for coverage and
707 // non-coverage variants of the same APEX
708 return
709 }
710
711 if ctx.Host() {
712 // No need to generate dependency info for host variant
713 return
714 }
715
Artur Satayev872a1442020-04-27 17:08:37 +0100716 depInfos := android.DepNameToDepInfoMap{}
717 a.walkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
718 if from.Name() == to.Name() {
719 // This can happen for cc.reuseObjTag. We are not interested in tracking this.
720 // As soon as the dependency graph crosses the APEX boundary, don't go further.
721 return !externalDep
Jiyong Park678c8812020-02-07 17:25:49 +0900722 }
Jiyong Park83dc74b2020-01-14 18:38:44 +0900723
Artur Satayev872a1442020-04-27 17:08:37 +0100724 if info, exists := depInfos[to.Name()]; exists {
725 if !android.InList(from.Name(), info.From) {
726 info.From = append(info.From, from.Name())
727 }
728 info.IsExternal = info.IsExternal && externalDep
729 depInfos[to.Name()] = info
730 } else {
Artur Satayev480e25b2020-04-27 18:53:18 +0100731 toMinSdkVersion := "(no version)"
732 if m, ok := to.(interface{ MinSdkVersion() string }); ok {
733 if v := m.MinSdkVersion(); v != "" {
734 toMinSdkVersion = v
735 }
736 }
737
Artur Satayev872a1442020-04-27 17:08:37 +0100738 depInfos[to.Name()] = android.ApexModuleDepInfo{
Artur Satayev480e25b2020-04-27 18:53:18 +0100739 To: to.Name(),
740 From: []string{from.Name()},
741 IsExternal: externalDep,
742 MinSdkVersion: toMinSdkVersion,
Artur Satayev872a1442020-04-27 17:08:37 +0100743 }
744 }
745
746 // As soon as the dependency graph crosses the APEX boundary, don't go further.
747 return !externalDep
Jiyong Park83dc74b2020-01-14 18:38:44 +0900748 })
749
Artur Satayev480e25b2020-04-27 18:53:18 +0100750 a.ApexBundleDepsInfo.BuildDepsInfoLists(ctx, proptools.String(a.properties.Min_sdk_version), depInfos)
Artur Satayev872a1442020-04-27 17:08:37 +0100751
Jiyong Park83dc74b2020-01-14 18:38:44 +0900752 ctx.Build(pctx, android.BuildParams{
753 Rule: android.Phony,
754 Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
Artur Satayeva8bd1132020-04-27 18:07:06 +0100755 Inputs: []android.Path{
756 a.ApexBundleDepsInfo.FullListPath(),
757 a.ApexBundleDepsInfo.FlatListPath(),
758 },
Jiyong Park83dc74b2020-01-14 18:38:44 +0900759 })
760}