blob: ee097e49f819d9cf680ca4d93a487cc81467be2a [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 Parkd93e1b12020-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 Han23b0adf2020-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 Jung8cf307e2020-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 Parkd93e1b12020-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 Freni18423782020-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 Parkd93e1b12020-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 Parkd93e1b12020-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
189 ctx.Build(pctx, android.BuildParams{
190 Rule: apexManifestRule,
191 Input: manifestSrc,
Jooyung Han214bf372019-11-12 13:03:50 +0900192 Output: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900193 Args: map[string]string{
194 "provideNativeLibs": strings.Join(provideNativeLibs, " "),
195 "requireNativeLibs": strings.Join(requireNativeLibs, " "),
196 "opt": strings.Join(optCommands, " "),
197 },
198 })
199
Jooyung Han23b0adf2020-03-12 18:37:20 +0900200 if a.minSdkVersion(ctx) == android.SdkVersion_Android10 {
Jooyung Han214bf372019-11-12 13:03:50 +0900201 // b/143654022 Q apexd can't understand newly added keys in apex_manifest.json
202 // prepare stripped-down version so that APEX modules built from R+ can be installed to Q
203 a.manifestJsonOut = android.PathForModuleOut(ctx, "apex_manifest.json")
204 ctx.Build(pctx, android.BuildParams{
205 Rule: stripApexManifestRule,
206 Input: manifestJsonFullOut,
207 Output: a.manifestJsonOut,
208 })
209 }
Jiyong Park09d77522019-11-18 11:16:27 +0900210
211 // from R+, protobuf binary format (.pb) is the standard format for apex_manifest
212 a.manifestPbOut = android.PathForModuleOut(ctx, "apex_manifest.pb")
213 ctx.Build(pctx, android.BuildParams{
214 Rule: pbApexManifestRule,
Jooyung Han214bf372019-11-12 13:03:50 +0900215 Input: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900216 Output: a.manifestPbOut,
217 })
218}
219
Jiyong Park19972c72020-01-28 20:05:29 +0900220func (a *apexBundle) buildNoticeFiles(ctx android.ModuleContext, apexFileName string) android.NoticeOutputs {
Jiyong Park162e8442020-03-17 19:16:40 +0900221 var noticeFiles android.Paths
222
Paul Duffin133608f2020-03-30 15:54:08 +0100223 a.walkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
Jiyong Park162e8442020-03-17 19:16:40 +0900224 if externalDep {
Paul Duffin133608f2020-03-30 15:54:08 +0100225 // As soon as the dependency graph crosses the APEX boundary, don't go further.
226 return false
Jiyong Park09d77522019-11-18 11:16:27 +0900227 }
Paul Duffin133608f2020-03-30 15:54:08 +0100228
Jiyong Park162e8442020-03-17 19:16:40 +0900229 notice := to.NoticeFile()
230 if notice.Valid() {
231 noticeFiles = append(noticeFiles, notice.Path())
232 }
Paul Duffin133608f2020-03-30 15:54:08 +0100233
234 return true
Jiyong Park162e8442020-03-17 19:16:40 +0900235 })
Jiyong Park09d77522019-11-18 11:16:27 +0900236
237 if len(noticeFiles) == 0 {
Jiyong Park19972c72020-01-28 20:05:29 +0900238 return android.NoticeOutputs{}
Jiyong Park09d77522019-11-18 11:16:27 +0900239 }
240
Jiyong Park19972c72020-01-28 20:05:29 +0900241 return android.BuildNoticeOutput(ctx, a.installDir, apexFileName, android.FirstUniquePaths(noticeFiles))
Jiyong Park09d77522019-11-18 11:16:27 +0900242}
243
Jiyong Park3a1602e2020-01-14 14:39:19 +0900244func (a *apexBundle) buildInstalledFilesFile(ctx android.ModuleContext, builtApex android.Path, imageDir android.Path) android.OutputPath {
245 output := android.PathForModuleOut(ctx, "installed-files.txt")
246 rule := android.NewRuleBuilder()
247 rule.Command().
248 Implicit(builtApex).
249 Text("(cd " + imageDir.String() + " ; ").
Jiyong Parkbd63a102020-02-08 12:40:05 +0900250 Text("find . \\( -type f -o -type l \\) -printf \"%s %p\\n\") ").
Jiyong Park3a1602e2020-01-14 14:39:19 +0900251 Text(" | sort -nr > ").
252 Output(output)
253 rule.Build(pctx, ctx, "installed-files."+a.Name(), "Installed files")
254 return output.OutputPath
255}
256
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900257func (a *apexBundle) buildBundleConfig(ctx android.ModuleContext) android.OutputPath {
258 output := android.PathForModuleOut(ctx, "bundle_config.json")
259
Jiyong Parkaf8998c2020-02-28 16:51:07 +0900260 type ApkConfig struct {
261 Package_name string `json:"package_name"`
262 Apk_path string `json:"path"`
263 }
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900264 config := struct {
265 Compression struct {
266 Uncompressed_glob []string `json:"uncompressed_glob"`
267 } `json:"compression"`
Jiyong Parkaf8998c2020-02-28 16:51:07 +0900268 Apex_config struct {
269 Apex_embedded_apk_config []ApkConfig `json:"apex_embedded_apk_config,omitempty"`
270 } `json:"apex_config,omitempty"`
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900271 }{}
272
273 config.Compression.Uncompressed_glob = []string{
274 "apex_payload.img",
275 "apex_manifest.*",
276 }
Jiyong Parkaf8998c2020-02-28 16:51:07 +0900277
278 // collect the manifest names and paths of android apps
279 // if their manifest names are overridden
280 for _, fi := range a.filesInfo {
281 if fi.class != app {
282 continue
283 }
284 packageName := fi.overriddenPackageName
285 if packageName != "" {
286 config.Apex_config.Apex_embedded_apk_config = append(
287 config.Apex_config.Apex_embedded_apk_config,
288 ApkConfig{
289 Package_name: packageName,
290 Apk_path: fi.Path(),
291 })
292 }
293 }
294
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900295 j, err := json.Marshal(config)
296 if err != nil {
297 panic(fmt.Errorf("error while marshalling to %q: %#v", output, err))
298 }
299
300 ctx.Build(pctx, android.BuildParams{
301 Rule: android.WriteFile,
302 Output: output,
303 Description: "Bundle Config " + output.String(),
304 Args: map[string]string{
305 "content": string(j),
306 },
307 })
308
309 return output.OutputPath
310}
311
Jiyong Park09d77522019-11-18 11:16:27 +0900312func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext) {
313 var abis []string
314 for _, target := range ctx.MultiTargets() {
315 if len(target.Arch.Abi) > 0 {
316 abis = append(abis, target.Arch.Abi[0])
317 }
318 }
319
320 abis = android.FirstUniqueStrings(abis)
321
322 apexType := a.properties.ApexType
323 suffix := apexType.suffix()
Jiyong Park7cd10e32020-01-14 09:22:18 +0900324 var implicitInputs []android.Path
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800325 unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
Jiyong Park09d77522019-11-18 11:16:27 +0900326
Jiyong Park7cd10e32020-01-14 09:22:18 +0900327 // TODO(jiyong): construct the copy rules using RuleBuilder
328 var copyCommands []string
329 for _, fi := range a.filesInfo {
330 destPath := android.PathForModuleOut(ctx, "image"+suffix, fi.Path()).String()
331 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(destPath))
332 if a.linkToSystemLib && fi.transitiveDep && fi.AvailableToPlatform() {
333 // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
334 pathOnDevice := filepath.Join("/system", fi.Path())
335 copyCommands = append(copyCommands, "ln -sfn "+pathOnDevice+" "+destPath)
336 } else {
337 copyCommands = append(copyCommands, "cp -f "+fi.builtFile.String()+" "+destPath)
338 implicitInputs = append(implicitInputs, fi.builtFile)
339 }
340 // create additional symlinks pointing the file inside the APEX
341 for _, symlinkPath := range fi.SymlinkPaths() {
342 symlinkDest := android.PathForModuleOut(ctx, "image"+suffix, symlinkPath).String()
343 copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
344 }
Jiyong Park09d77522019-11-18 11:16:27 +0900345 }
346
Jiyong Park7cd10e32020-01-14 09:22:18 +0900347 // TODO(jiyong): use RuleBuilder
348 var emitCommands []string
349 imageContentFile := android.PathForModuleOut(ctx, "content.txt")
Jooyung Han214bf372019-11-12 13:03:50 +0900350 emitCommands = append(emitCommands, "echo ./apex_manifest.pb >> "+imageContentFile.String())
Jooyung Han23b0adf2020-03-12 18:37:20 +0900351 if a.minSdkVersion(ctx) == android.SdkVersion_Android10 {
Jooyung Han214bf372019-11-12 13:03:50 +0900352 emitCommands = append(emitCommands, "echo ./apex_manifest.json >> "+imageContentFile.String())
353 }
Jiyong Park7cd10e32020-01-14 09:22:18 +0900354 for _, fi := range a.filesInfo {
355 emitCommands = append(emitCommands, "echo './"+fi.Path()+"' >> "+imageContentFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900356 }
357 emitCommands = append(emitCommands, "sort -o "+imageContentFile.String()+" "+imageContentFile.String())
Jooyung Han214bf372019-11-12 13:03:50 +0900358 implicitInputs = append(implicitInputs, a.manifestPbOut)
Jiyong Park09d77522019-11-18 11:16:27 +0900359
360 if a.properties.Whitelisted_files != nil {
361 ctx.Build(pctx, android.BuildParams{
362 Rule: emitApexContentRule,
363 Implicits: implicitInputs,
364 Output: imageContentFile,
365 Description: "emit apex image content",
366 Args: map[string]string{
367 "emit_commands": strings.Join(emitCommands, " && "),
368 },
369 })
370 implicitInputs = append(implicitInputs, imageContentFile)
371 whitelistedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.Whitelisted_files))
372
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800373 phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
Jiyong Park09d77522019-11-18 11:16:27 +0900374 ctx.Build(pctx, android.BuildParams{
375 Rule: diffApexContentRule,
376 Implicits: implicitInputs,
377 Output: phonyOutput,
378 Description: "diff apex image content",
379 Args: map[string]string{
380 "whitelisted_files_file": whitelistedFilesFile.String(),
381 "image_content_file": imageContentFile.String(),
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800382 "apex_module_name": a.Name(),
Jiyong Park09d77522019-11-18 11:16:27 +0900383 },
384 })
385
386 implicitInputs = append(implicitInputs, phonyOutput)
387 }
388
389 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
390 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
391
Jiyong Park3a1602e2020-01-14 14:39:19 +0900392 imageDir := android.PathForModuleOut(ctx, "image"+suffix)
Jiyong Park09d77522019-11-18 11:16:27 +0900393 if apexType == imageApex {
394 // files and dirs that will be created in APEX
395 var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
396 var executablePaths []string // this also includes dirs
397 for _, f := range a.filesInfo {
Jiyong Parkcbe50c72020-05-29 21:29:20 +0900398 pathInApex := f.Path()
Jiyong Park09d77522019-11-18 11:16:27 +0900399 if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
400 executablePaths = append(executablePaths, pathInApex)
401 for _, s := range f.symlinks {
402 executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
403 }
404 } else {
405 readOnlyPaths = append(readOnlyPaths, pathInApex)
406 }
407 dir := f.installDir
408 for !android.InList(dir, executablePaths) && dir != "" {
409 executablePaths = append(executablePaths, dir)
410 dir, _ = filepath.Split(dir) // move up to the parent
411 if len(dir) > 0 {
412 // remove trailing slash
413 dir = dir[:len(dir)-1]
414 }
415 }
416 }
417 sort.Strings(readOnlyPaths)
418 sort.Strings(executablePaths)
419 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
420 ctx.Build(pctx, android.BuildParams{
421 Rule: generateFsConfig,
422 Output: cannedFsConfig,
423 Description: "generate fs config",
424 Args: map[string]string{
425 "ro_paths": strings.Join(readOnlyPaths, " "),
426 "exec_paths": strings.Join(executablePaths, " "),
427 },
428 })
429
Jiyong Park09d77522019-11-18 11:16:27 +0900430 optFlags := []string{}
431
432 // Additional implicit inputs.
Jooyung Han54aca7b2019-11-20 02:26:02 +0900433 implicitInputs = append(implicitInputs, cannedFsConfig, a.fileContexts, a.private_key_file, a.public_key_file)
Jiyong Park09d77522019-11-18 11:16:27 +0900434 optFlags = append(optFlags, "--pubkey "+a.public_key_file.String())
435
Jooyung Han27151d92019-12-16 17:45:32 +0900436 manifestPackageName := a.getOverrideManifestPackageName(ctx)
437 if manifestPackageName != "" {
Jiyong Park09d77522019-11-18 11:16:27 +0900438 optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
439 }
440
441 if a.properties.AndroidManifest != nil {
442 androidManifestFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.AndroidManifest))
443 implicitInputs = append(implicitInputs, androidManifestFile)
444 optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
445 }
446
447 targetSdkVersion := ctx.Config().DefaultAppTargetSdk()
Nikita Ioffe5f6771e2020-05-20 00:16:27 +0100448 // TODO(b/157078772): propagate min_sdk_version to apexer.
Baligh Uddinf6201372020-01-24 23:15:44 +0000449 minSdkVersion := ctx.Config().DefaultAppTargetSdk()
Nikita Ioffedb10c132020-02-20 00:43:27 +0000450
Jooyung Han23b0adf2020-03-12 18:37:20 +0900451 if a.minSdkVersion(ctx) == android.SdkVersion_Android10 {
452 minSdkVersion = strconv.Itoa(a.minSdkVersion(ctx))
Nikita Ioffedb10c132020-02-20 00:43:27 +0000453 }
454
Nikita Ioffe934c4f22020-03-02 16:58:11 +0000455 if java.UseApiFingerprint(ctx) {
456 targetSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
Baligh Uddinf6201372020-01-24 23:15:44 +0000457 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
458 }
Nikita Ioffe934c4f22020-03-02 16:58:11 +0000459 if java.UseApiFingerprint(ctx) {
460 minSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
Baligh Uddinf6201372020-01-24 23:15:44 +0000461 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
Jiyong Park09d77522019-11-18 11:16:27 +0900462 }
463 optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
Baligh Uddinf6201372020-01-24 23:15:44 +0000464 optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
Jiyong Park09d77522019-11-18 11:16:27 +0900465
Baligh Uddin004d7172020-02-19 21:29:28 -0800466 if a.overridableProperties.Logging_parent != "" {
467 optFlags = append(optFlags, "--logging_parent ", a.overridableProperties.Logging_parent)
468 }
469
Jiyong Park19972c72020-01-28 20:05:29 +0900470 a.mergedNotices = a.buildNoticeFiles(ctx, a.Name()+suffix)
471 if a.mergedNotices.HtmlGzOutput.Valid() {
Jiyong Park09d77522019-11-18 11:16:27 +0900472 // If there's a NOTICE file, embed it as an asset file in the APEX.
Jiyong Park19972c72020-01-28 20:05:29 +0900473 implicitInputs = append(implicitInputs, a.mergedNotices.HtmlGzOutput.Path())
474 optFlags = append(optFlags, "--assets_dir "+filepath.Dir(a.mergedNotices.HtmlGzOutput.String()))
Jiyong Park09d77522019-11-18 11:16:27 +0900475 }
476
Nikita Ioffeb4b44c02020-01-02 23:01:39 +0000477 if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && ctx.ModuleDir() != "system/apex/shim/build" && a.testOnlyShouldSkipHashtreeGeneration() {
Nikita Ioffec72b5dd2019-12-07 17:30:22 +0000478 ctx.PropertyErrorf("test_only_no_hashtree", "not available")
479 return
480 }
Jooyung Han23b0adf2020-03-12 18:37:20 +0900481 if a.minSdkVersion(ctx) > android.SdkVersion_Android10 || a.testOnlyShouldSkipHashtreeGeneration() {
Jiyong Park09d77522019-11-18 11:16:27 +0900482 // Apexes which are supposed to be installed in builtin dirs(/system, etc)
483 // don't need hashtree for activation. Therefore, by removing hashtree from
484 // apex bundle (filesystem image in it, to be specific), we can save storage.
485 optFlags = append(optFlags, "--no_hashtree")
486 }
487
Dario Freni98410fd2020-04-27 18:21:11 +0100488 if a.testOnlyShouldSkipPayloadSign() {
489 optFlags = append(optFlags, "--unsigned_payload")
490 }
491
Jiyong Park09d77522019-11-18 11:16:27 +0900492 if a.properties.Apex_name != nil {
493 // If apex_name is set, apexer can skip checking if key name matches with apex name.
494 // Note that apex_manifest is also mended.
495 optFlags = append(optFlags, "--do_not_check_keyname")
496 }
497
Jooyung Han23b0adf2020-03-12 18:37:20 +0900498 if a.minSdkVersion(ctx) == android.SdkVersion_Android10 {
Jooyung Han214bf372019-11-12 13:03:50 +0900499 implicitInputs = append(implicitInputs, a.manifestJsonOut)
500 optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
501 }
502
Jiyong Park09d77522019-11-18 11:16:27 +0900503 ctx.Build(pctx, android.BuildParams{
504 Rule: apexRule,
505 Implicits: implicitInputs,
506 Output: unsignedOutputFile,
507 Description: "apex (" + apexType.name() + ")",
508 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900509 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900510 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900511 "copy_commands": strings.Join(copyCommands, " && "),
512 "manifest": a.manifestPbOut.String(),
513 "file_contexts": a.fileContexts.String(),
514 "canned_fs_config": cannedFsConfig.String(),
515 "key": a.private_key_file.String(),
516 "opt_flags": strings.Join(optFlags, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900517 },
518 })
519
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800520 apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
521 bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
Jiyong Park09d77522019-11-18 11:16:27 +0900522 a.bundleModuleFile = bundleModuleFile
523
524 ctx.Build(pctx, android.BuildParams{
525 Rule: apexProtoConvertRule,
526 Input: unsignedOutputFile,
527 Output: apexProtoFile,
528 Description: "apex proto convert",
529 })
530
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900531 bundleConfig := a.buildBundleConfig(ctx)
532
Jiyong Park09d77522019-11-18 11:16:27 +0900533 ctx.Build(pctx, android.BuildParams{
534 Rule: apexBundleRule,
535 Input: apexProtoFile,
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900536 Implicit: bundleConfig,
Jiyong Park09d77522019-11-18 11:16:27 +0900537 Output: a.bundleModuleFile,
538 Description: "apex bundle module",
539 Args: map[string]string{
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900540 "abi": strings.Join(abis, "."),
541 "config": bundleConfig.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900542 },
543 })
544 } else {
545 ctx.Build(pctx, android.BuildParams{
546 Rule: zipApexRule,
547 Implicits: implicitInputs,
548 Output: unsignedOutputFile,
549 Description: "apex (" + apexType.name() + ")",
550 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900551 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900552 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900553 "copy_commands": strings.Join(copyCommands, " && "),
554 "manifest": a.manifestPbOut.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900555 },
556 })
557 }
558
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800559 a.outputFile = android.PathForModuleOut(ctx, a.Name()+suffix)
Jiyong Park09d77522019-11-18 11:16:27 +0900560 ctx.Build(pctx, android.BuildParams{
561 Rule: java.Signapk,
562 Description: "signapk",
563 Output: a.outputFile,
564 Input: unsignedOutputFile,
565 Implicits: []android.Path{
566 a.container_certificate_file,
567 a.container_private_key_file,
568 },
569 Args: map[string]string{
570 "certificates": a.container_certificate_file.String() + " " + a.container_private_key_file.String(),
571 "flags": "-a 4096", //alignment
572 },
573 })
574
575 // Install to $OUT/soong/{target,host}/.../apex
576 if a.installable() {
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800577 ctx.InstallFile(a.installDir, a.Name()+suffix, a.outputFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900578 }
579 a.buildFilesInfo(ctx)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900580
581 // installed-files.txt is dist'ed
582 a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900583}
584
585func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
586 // Temporarily wrap the original `ctx` into a `flattenedApexContext` to have it
587 // reply true to `InstallBypassMake()` (thus making the call
588 // `android.PathForModuleInstall` below use `android.pathForInstallInMakeDir`
589 // instead of `android.PathForOutput`) to return the correct path to the flattened
590 // APEX (as its contents is installed by Make, not Soong).
591 factx := flattenedApexContext{ctx}
Jiyong Parka5948012020-02-07 10:15:14 +0900592 apexBundleName := a.Name()
593 a.outputFile = android.PathForModuleInstall(&factx, "apex", apexBundleName)
Jiyong Park09d77522019-11-18 11:16:27 +0900594
Jooyung Han6bfc0432020-04-27 22:18:19 +0900595 if a.installable() {
Jiyong Parka5948012020-02-07 10:15:14 +0900596 installPath := android.PathForModuleInstall(ctx, "apex", apexBundleName)
Jooyung Han54aca7b2019-11-20 02:26:02 +0900597 devicePath := android.InstallPathToOnDevicePath(ctx, installPath)
Jiyong Parka5948012020-02-07 10:15:14 +0900598 addFlattenedFileContextsInfos(ctx, apexBundleName+":"+devicePath+":"+a.fileContexts.String())
Jooyung Han54aca7b2019-11-20 02:26:02 +0900599 }
Jiyong Park09d77522019-11-18 11:16:27 +0900600 a.buildFilesInfo(ctx)
601}
602
603func (a *apexBundle) setCertificateAndPrivateKey(ctx android.ModuleContext) {
Jooyung Hanf121a652019-12-17 14:30:11 +0900604 if a.container_certificate_file == nil {
605 cert := String(a.properties.Certificate)
606 if cert == "" {
607 pem, key := ctx.Config().DefaultAppCertificate(ctx)
608 a.container_certificate_file = pem
609 a.container_private_key_file = key
610 } else {
611 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
612 a.container_certificate_file = defaultDir.Join(ctx, cert+".x509.pem")
613 a.container_private_key_file = defaultDir.Join(ctx, cert+".pk8")
614 }
Jiyong Park09d77522019-11-18 11:16:27 +0900615 }
616}
617
618func (a *apexBundle) buildFilesInfo(ctx android.ModuleContext) {
619 if a.installable() {
Jooyung Han214bf372019-11-12 13:03:50 +0900620 // 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 +0900621 // with other ordinary files.
Jiyong Park7cd10e32020-01-14 09:22:18 +0900622 a.filesInfo = append(a.filesInfo, newApexFile(ctx, a.manifestPbOut, "apex_manifest.pb", ".", etc, nil))
Jiyong Park09d77522019-11-18 11:16:27 +0900623
624 // rename to apex_pubkey
625 copiedPubkey := android.PathForModuleOut(ctx, "apex_pubkey")
626 ctx.Build(pctx, android.BuildParams{
627 Rule: android.Cp,
628 Input: a.public_key_file,
629 Output: copiedPubkey,
630 })
Jiyong Park7cd10e32020-01-14 09:22:18 +0900631 a.filesInfo = append(a.filesInfo, newApexFile(ctx, copiedPubkey, "apex_pubkey", ".", etc, nil))
Jiyong Park09d77522019-11-18 11:16:27 +0900632
633 if a.properties.ApexType == flattenedApex {
Jiyong Parka5948012020-02-07 10:15:14 +0900634 apexBundleName := a.Name()
Jiyong Park09d77522019-11-18 11:16:27 +0900635 for _, fi := range a.filesInfo {
Jiyong Parka5948012020-02-07 10:15:14 +0900636 dir := filepath.Join("apex", apexBundleName, fi.installDir)
Jiyong Parkcbe50c72020-05-29 21:29:20 +0900637 target := ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.Stem(), fi.builtFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900638 for _, sym := range fi.symlinks {
639 ctx.InstallSymlink(android.PathForModuleInstall(ctx, dir), sym, target)
640 }
641 }
642 }
643 }
644}
Jooyung Han27151d92019-12-16 17:45:32 +0900645
646func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
647 // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
648 // to see if it should be overridden because their <apex name> is dynamically generated
649 // according to its VNDK version.
650 if a.vndkApex {
651 overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
652 if overridden {
653 return strings.Replace(*a.properties.Apex_name, vndkApexName, overrideName, 1)
654 }
655 return ""
656 }
Baligh Uddincb6aa122020-03-15 13:01:05 -0700657 if a.overridableProperties.Package_name != "" {
658 return a.overridableProperties.Package_name
659 }
Jiyong Parka519c542020-03-03 11:45:41 +0900660 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jooyung Han27151d92019-12-16 17:45:32 +0900661 if overridden {
662 return manifestPackageName
663 }
664 return ""
665}
Jiyong Park83dc74b2020-01-14 18:38:44 +0900666
667func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
668 if !a.primaryApexType {
669 return
670 }
671
672 if a.properties.IsCoverageVariant {
673 // Otherwise, we will have duplicated rules for coverage and
674 // non-coverage variants of the same APEX
675 return
676 }
677
678 if ctx.Host() {
679 // No need to generate dependency info for host variant
680 return
681 }
682
Artur Satayev334b5172020-04-27 17:08:37 +0100683 depInfos := android.DepNameToDepInfoMap{}
684 a.walkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
685 if from.Name() == to.Name() {
686 // This can happen for cc.reuseObjTag. We are not interested in tracking this.
687 // As soon as the dependency graph crosses the APEX boundary, don't go further.
688 return !externalDep
Jiyong Park678c8812020-02-07 17:25:49 +0900689 }
Jiyong Park83dc74b2020-01-14 18:38:44 +0900690
Artur Satayev334b5172020-04-27 17:08:37 +0100691 if info, exists := depInfos[to.Name()]; exists {
692 if !android.InList(from.Name(), info.From) {
693 info.From = append(info.From, from.Name())
694 }
695 info.IsExternal = info.IsExternal && externalDep
696 depInfos[to.Name()] = info
697 } else {
Artur Satayev388d39b2020-04-27 18:53:18 +0100698 toMinSdkVersion := "(no version)"
699 if m, ok := to.(interface{ MinSdkVersion() string }); ok {
700 if v := m.MinSdkVersion(); v != "" {
701 toMinSdkVersion = v
702 }
703 }
704
Artur Satayev334b5172020-04-27 17:08:37 +0100705 depInfos[to.Name()] = android.ApexModuleDepInfo{
Artur Satayev388d39b2020-04-27 18:53:18 +0100706 To: to.Name(),
707 From: []string{from.Name()},
708 IsExternal: externalDep,
709 MinSdkVersion: toMinSdkVersion,
Artur Satayev334b5172020-04-27 17:08:37 +0100710 }
711 }
712
713 // As soon as the dependency graph crosses the APEX boundary, don't go further.
714 return !externalDep
Jiyong Park83dc74b2020-01-14 18:38:44 +0900715 })
716
Artur Satayev388d39b2020-04-27 18:53:18 +0100717 a.ApexBundleDepsInfo.BuildDepsInfoLists(ctx, proptools.String(a.properties.Min_sdk_version), depInfos)
Artur Satayev334b5172020-04-27 17:08:37 +0100718
Jiyong Park83dc74b2020-01-14 18:38:44 +0900719 ctx.Build(pctx, android.BuildParams{
720 Rule: android.Phony,
721 Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
Artur Satayev5e7c32d2020-04-27 18:07:06 +0100722 Inputs: []android.Path{
723 a.ApexBundleDepsInfo.FullListPath(),
724 a.ApexBundleDepsInfo.FlatListPath(),
725 },
Jiyong Park83dc74b2020-01-14 18:38:44 +0900726 })
727}