blob: 9ef1e0d86465093114d3e7328080579cef25d92b [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")
64}
65
66var (
67 // Create a canned fs config file where all files and directories are
68 // by default set to (uid/gid/mode) = (1000/1000/0644)
69 // TODO(b/113082813) make this configurable using config.fs syntax
70 generateFsConfig = pctx.StaticRule("generateFsConfig", blueprint.RuleParams{
71 Command: `echo '/ 1000 1000 0755' > ${out} && ` +
72 `echo ${ro_paths} | tr ' ' '\n' | awk '{print "/"$$1 " 1000 1000 0644"}' >> ${out} && ` +
73 `echo ${exec_paths} | tr ' ' '\n' | awk '{print "/"$$1 " 0 2000 0755"}' >> ${out}`,
74 Description: "fs_config ${out}",
75 }, "ro_paths", "exec_paths")
76
77 apexManifestRule = pctx.StaticRule("apexManifestRule", blueprint.RuleParams{
78 Command: `rm -f $out && ${jsonmodify} $in ` +
79 `-a provideNativeLibs ${provideNativeLibs} ` +
80 `-a requireNativeLibs ${requireNativeLibs} ` +
81 `${opt} ` +
82 `-o $out`,
83 CommandDeps: []string{"${jsonmodify}"},
84 Description: "prepare ${out}",
85 }, "provideNativeLibs", "requireNativeLibs", "opt")
86
87 stripApexManifestRule = pctx.StaticRule("stripApexManifestRule", blueprint.RuleParams{
88 Command: `rm -f $out && ${conv_apex_manifest} strip $in -o $out`,
89 CommandDeps: []string{"${conv_apex_manifest}"},
90 Description: "strip ${in}=>${out}",
91 })
92
93 pbApexManifestRule = pctx.StaticRule("pbApexManifestRule", blueprint.RuleParams{
94 Command: `rm -f $out && ${conv_apex_manifest} proto $in -o $out`,
95 CommandDeps: []string{"${conv_apex_manifest}"},
96 Description: "convert ${in}=>${out}",
97 })
98
99 // TODO(b/113233103): make sure that file_contexts is sane, i.e., validate
100 // against the binary policy using sefcontext_compiler -p <policy>.
101
102 // TODO(b/114327326): automate the generation of file_contexts
103 apexRule = pctx.StaticRule("apexRule", blueprint.RuleParams{
104 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
105 `(. ${out}.copy_commands) && ` +
106 `APEXER_TOOL_PATH=${tool_path} ` +
107 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900108 `--file_contexts ${file_contexts} ` +
109 `--canned_fs_config ${canned_fs_config} ` +
Dario Freni0f4ae072020-01-02 15:24:12 +0000110 `--include_build_info ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900111 `--payload_type image ` +
112 `--key ${key} ${opt_flags} ${image_dir} ${out} `,
113 CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
114 "${mke2fs}", "${resize2fs}", "${sefcontext_compile}",
115 "${soong_zip}", "${zipalign}", "${aapt2}", "prebuilts/sdk/current/public/android.jar"},
116 Rspfile: "${out}.copy_commands",
117 RspfileContent: "${copy_commands}",
118 Description: "APEX ${image_dir} => ${out}",
Jooyung Han214bf372019-11-12 13:03:50 +0900119 }, "tool_path", "image_dir", "copy_commands", "file_contexts", "canned_fs_config", "key", "opt_flags", "manifest")
Jiyong Park09d77522019-11-18 11:16:27 +0900120
121 zipApexRule = pctx.StaticRule("zipApexRule", blueprint.RuleParams{
122 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
123 `(. ${out}.copy_commands) && ` +
124 `APEXER_TOOL_PATH=${tool_path} ` +
Jooyung Han214bf372019-11-12 13:03:50 +0900125 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900126 `--payload_type zip ` +
127 `${image_dir} ${out} `,
128 CommandDeps: []string{"${apexer}", "${merge_zips}", "${soong_zip}", "${zipalign}", "${aapt2}"},
129 Rspfile: "${out}.copy_commands",
130 RspfileContent: "${copy_commands}",
131 Description: "ZipAPEX ${image_dir} => ${out}",
Jooyung Han214bf372019-11-12 13:03:50 +0900132 }, "tool_path", "image_dir", "copy_commands", "manifest")
Jiyong Park09d77522019-11-18 11:16:27 +0900133
134 apexProtoConvertRule = pctx.AndroidStaticRule("apexProtoConvertRule",
135 blueprint.RuleParams{
136 Command: `${aapt2} convert --output-format proto $in -o $out`,
137 CommandDeps: []string{"${aapt2}"},
138 })
139
140 apexBundleRule = pctx.StaticRule("apexBundleRule", blueprint.RuleParams{
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900141 Command: `${zip2zip} -i $in -o $out.base ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900142 `apex_payload.img:apex/${abi}.img ` +
Dario Freni18423782020-03-02 21:47:09 +0000143 `apex_build_info.pb:apex/${abi}.build_info.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900144 `apex_manifest.json:root/apex_manifest.json ` +
Jiyong Park53ae3342019-12-08 02:06:24 +0900145 `apex_manifest.pb:root/apex_manifest.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900146 `AndroidManifest.xml:manifest/AndroidManifest.xml ` +
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900147 `assets/NOTICE.html.gz:assets/NOTICE.html.gz &&` +
148 `${soong_zip} -o $out.config -C $$(dirname ${config}) -f ${config} && ` +
149 `${merge_zips} $out $out.base $out.config`,
150 CommandDeps: []string{"${zip2zip}", "${soong_zip}", "${merge_zips}"},
Jiyong Park09d77522019-11-18 11:16:27 +0900151 Description: "app bundle",
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900152 }, "abi", "config")
Jiyong Park09d77522019-11-18 11:16:27 +0900153
154 emitApexContentRule = pctx.StaticRule("emitApexContentRule", blueprint.RuleParams{
155 Command: `rm -f ${out} && touch ${out} && (. ${out}.emit_commands)`,
156 Rspfile: "${out}.emit_commands",
157 RspfileContent: "${emit_commands}",
158 Description: "Emit APEX image content",
159 }, "emit_commands")
160
161 diffApexContentRule = pctx.StaticRule("diffApexContentRule", blueprint.RuleParams{
162 Command: `diff --unchanged-group-format='' \` +
163 `--changed-group-format='%<' \` +
164 `${image_content_file} ${whitelisted_files_file} || (` +
165 `echo -e "New unexpected files were added to ${apex_module_name}." ` +
166 ` "To fix the build run following command:" && ` +
167 `echo "system/apex/tools/update_whitelist.sh ${whitelisted_files_file} ${image_content_file}" && ` +
Dan Willemsen81e43c52020-01-28 15:40:19 -0800168 `exit 1); touch ${out}`,
Jiyong Park09d77522019-11-18 11:16:27 +0900169 Description: "Diff ${image_content_file} and ${whitelisted_files_file}",
170 }, "image_content_file", "whitelisted_files_file", "apex_module_name")
171)
172
173func (a *apexBundle) buildManifest(ctx android.ModuleContext, provideNativeLibs, requireNativeLibs []string) {
174 manifestSrc := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
175
Jooyung Han214bf372019-11-12 13:03:50 +0900176 manifestJsonFullOut := android.PathForModuleOut(ctx, "apex_manifest_full.json")
Jiyong Park09d77522019-11-18 11:16:27 +0900177
178 // put dependency({provide|require}NativeLibs) in apex_manifest.json
179 provideNativeLibs = android.SortedUniqueStrings(provideNativeLibs)
180 requireNativeLibs = android.SortedUniqueStrings(android.RemoveListFromList(requireNativeLibs, provideNativeLibs))
181
182 // apex name can be overridden
183 optCommands := []string{}
184 if a.properties.Apex_name != nil {
185 optCommands = append(optCommands, "-v name "+*a.properties.Apex_name)
186 }
187
188 ctx.Build(pctx, android.BuildParams{
189 Rule: apexManifestRule,
190 Input: manifestSrc,
Jooyung Han214bf372019-11-12 13:03:50 +0900191 Output: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900192 Args: map[string]string{
193 "provideNativeLibs": strings.Join(provideNativeLibs, " "),
194 "requireNativeLibs": strings.Join(requireNativeLibs, " "),
195 "opt": strings.Join(optCommands, " "),
196 },
197 })
198
Jooyung Han23b0adf2020-03-12 18:37:20 +0900199 if a.minSdkVersion(ctx) == android.SdkVersion_Android10 {
Jooyung Han214bf372019-11-12 13:03:50 +0900200 // b/143654022 Q apexd can't understand newly added keys in apex_manifest.json
201 // prepare stripped-down version so that APEX modules built from R+ can be installed to Q
202 a.manifestJsonOut = android.PathForModuleOut(ctx, "apex_manifest.json")
203 ctx.Build(pctx, android.BuildParams{
204 Rule: stripApexManifestRule,
205 Input: manifestJsonFullOut,
206 Output: a.manifestJsonOut,
207 })
208 }
Jiyong Park09d77522019-11-18 11:16:27 +0900209
210 // from R+, protobuf binary format (.pb) is the standard format for apex_manifest
211 a.manifestPbOut = android.PathForModuleOut(ctx, "apex_manifest.pb")
212 ctx.Build(pctx, android.BuildParams{
213 Rule: pbApexManifestRule,
Jooyung Han214bf372019-11-12 13:03:50 +0900214 Input: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900215 Output: a.manifestPbOut,
216 })
217}
218
Jiyong Park19972c72020-01-28 20:05:29 +0900219func (a *apexBundle) buildNoticeFiles(ctx android.ModuleContext, apexFileName string) android.NoticeOutputs {
Jiyong Park162e8442020-03-17 19:16:40 +0900220 var noticeFiles android.Paths
221
Paul Duffin133608f2020-03-30 15:54:08 +0100222 a.walkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
Jiyong Park162e8442020-03-17 19:16:40 +0900223 if externalDep {
Paul Duffin133608f2020-03-30 15:54:08 +0100224 // As soon as the dependency graph crosses the APEX boundary, don't go further.
225 return false
Jiyong Park09d77522019-11-18 11:16:27 +0900226 }
Paul Duffin133608f2020-03-30 15:54:08 +0100227
Jiyong Park162e8442020-03-17 19:16:40 +0900228 notice := to.NoticeFile()
229 if notice.Valid() {
230 noticeFiles = append(noticeFiles, notice.Path())
231 }
Paul Duffin133608f2020-03-30 15:54:08 +0100232
233 return true
Jiyong Park162e8442020-03-17 19:16:40 +0900234 })
Jiyong Park09d77522019-11-18 11:16:27 +0900235
236 if len(noticeFiles) == 0 {
Jiyong Park19972c72020-01-28 20:05:29 +0900237 return android.NoticeOutputs{}
Jiyong Park09d77522019-11-18 11:16:27 +0900238 }
239
Jiyong Park19972c72020-01-28 20:05:29 +0900240 return android.BuildNoticeOutput(ctx, a.installDir, apexFileName, android.FirstUniquePaths(noticeFiles))
Jiyong Park09d77522019-11-18 11:16:27 +0900241}
242
Jiyong Park3a1602e2020-01-14 14:39:19 +0900243func (a *apexBundle) buildInstalledFilesFile(ctx android.ModuleContext, builtApex android.Path, imageDir android.Path) android.OutputPath {
244 output := android.PathForModuleOut(ctx, "installed-files.txt")
245 rule := android.NewRuleBuilder()
246 rule.Command().
247 Implicit(builtApex).
248 Text("(cd " + imageDir.String() + " ; ").
Jiyong Parkbd63a102020-02-08 12:40:05 +0900249 Text("find . \\( -type f -o -type l \\) -printf \"%s %p\\n\") ").
Jiyong Park3a1602e2020-01-14 14:39:19 +0900250 Text(" | sort -nr > ").
251 Output(output)
252 rule.Build(pctx, ctx, "installed-files."+a.Name(), "Installed files")
253 return output.OutputPath
254}
255
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900256func (a *apexBundle) buildBundleConfig(ctx android.ModuleContext) android.OutputPath {
257 output := android.PathForModuleOut(ctx, "bundle_config.json")
258
Jiyong Parkaf8998c2020-02-28 16:51:07 +0900259 type ApkConfig struct {
260 Package_name string `json:"package_name"`
261 Apk_path string `json:"path"`
262 }
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900263 config := struct {
264 Compression struct {
265 Uncompressed_glob []string `json:"uncompressed_glob"`
266 } `json:"compression"`
Jiyong Parkaf8998c2020-02-28 16:51:07 +0900267 Apex_config struct {
268 Apex_embedded_apk_config []ApkConfig `json:"apex_embedded_apk_config,omitempty"`
269 } `json:"apex_config,omitempty"`
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900270 }{}
271
272 config.Compression.Uncompressed_glob = []string{
273 "apex_payload.img",
274 "apex_manifest.*",
275 }
Jiyong Parkaf8998c2020-02-28 16:51:07 +0900276
277 // collect the manifest names and paths of android apps
278 // if their manifest names are overridden
279 for _, fi := range a.filesInfo {
280 if fi.class != app {
281 continue
282 }
283 packageName := fi.overriddenPackageName
284 if packageName != "" {
285 config.Apex_config.Apex_embedded_apk_config = append(
286 config.Apex_config.Apex_embedded_apk_config,
287 ApkConfig{
288 Package_name: packageName,
289 Apk_path: fi.Path(),
290 })
291 }
292 }
293
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900294 j, err := json.Marshal(config)
295 if err != nil {
296 panic(fmt.Errorf("error while marshalling to %q: %#v", output, err))
297 }
298
299 ctx.Build(pctx, android.BuildParams{
300 Rule: android.WriteFile,
301 Output: output,
302 Description: "Bundle Config " + output.String(),
303 Args: map[string]string{
304 "content": string(j),
305 },
306 })
307
308 return output.OutputPath
309}
310
Jiyong Park09d77522019-11-18 11:16:27 +0900311func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext) {
312 var abis []string
313 for _, target := range ctx.MultiTargets() {
314 if len(target.Arch.Abi) > 0 {
315 abis = append(abis, target.Arch.Abi[0])
316 }
317 }
318
319 abis = android.FirstUniqueStrings(abis)
320
321 apexType := a.properties.ApexType
322 suffix := apexType.suffix()
Jiyong Park7cd10e32020-01-14 09:22:18 +0900323 var implicitInputs []android.Path
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800324 unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
Jiyong Park09d77522019-11-18 11:16:27 +0900325
Jiyong Park7cd10e32020-01-14 09:22:18 +0900326 // TODO(jiyong): construct the copy rules using RuleBuilder
327 var copyCommands []string
328 for _, fi := range a.filesInfo {
329 destPath := android.PathForModuleOut(ctx, "image"+suffix, fi.Path()).String()
330 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(destPath))
331 if a.linkToSystemLib && fi.transitiveDep && fi.AvailableToPlatform() {
332 // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
333 pathOnDevice := filepath.Join("/system", fi.Path())
334 copyCommands = append(copyCommands, "ln -sfn "+pathOnDevice+" "+destPath)
335 } else {
336 copyCommands = append(copyCommands, "cp -f "+fi.builtFile.String()+" "+destPath)
337 implicitInputs = append(implicitInputs, fi.builtFile)
338 }
339 // create additional symlinks pointing the file inside the APEX
340 for _, symlinkPath := range fi.SymlinkPaths() {
341 symlinkDest := android.PathForModuleOut(ctx, "image"+suffix, symlinkPath).String()
342 copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
343 }
Jiyong Park09d77522019-11-18 11:16:27 +0900344 }
345
Jiyong Park7cd10e32020-01-14 09:22:18 +0900346 // TODO(jiyong): use RuleBuilder
347 var emitCommands []string
348 imageContentFile := android.PathForModuleOut(ctx, "content.txt")
Jooyung Han214bf372019-11-12 13:03:50 +0900349 emitCommands = append(emitCommands, "echo ./apex_manifest.pb >> "+imageContentFile.String())
Jooyung Han23b0adf2020-03-12 18:37:20 +0900350 if a.minSdkVersion(ctx) == android.SdkVersion_Android10 {
Jooyung Han214bf372019-11-12 13:03:50 +0900351 emitCommands = append(emitCommands, "echo ./apex_manifest.json >> "+imageContentFile.String())
352 }
Jiyong Park7cd10e32020-01-14 09:22:18 +0900353 for _, fi := range a.filesInfo {
354 emitCommands = append(emitCommands, "echo './"+fi.Path()+"' >> "+imageContentFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900355 }
356 emitCommands = append(emitCommands, "sort -o "+imageContentFile.String()+" "+imageContentFile.String())
Jooyung Han214bf372019-11-12 13:03:50 +0900357 implicitInputs = append(implicitInputs, a.manifestPbOut)
Jiyong Park09d77522019-11-18 11:16:27 +0900358
359 if a.properties.Whitelisted_files != nil {
360 ctx.Build(pctx, android.BuildParams{
361 Rule: emitApexContentRule,
362 Implicits: implicitInputs,
363 Output: imageContentFile,
364 Description: "emit apex image content",
365 Args: map[string]string{
366 "emit_commands": strings.Join(emitCommands, " && "),
367 },
368 })
369 implicitInputs = append(implicitInputs, imageContentFile)
370 whitelistedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.Whitelisted_files))
371
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800372 phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
Jiyong Park09d77522019-11-18 11:16:27 +0900373 ctx.Build(pctx, android.BuildParams{
374 Rule: diffApexContentRule,
375 Implicits: implicitInputs,
376 Output: phonyOutput,
377 Description: "diff apex image content",
378 Args: map[string]string{
379 "whitelisted_files_file": whitelistedFilesFile.String(),
380 "image_content_file": imageContentFile.String(),
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800381 "apex_module_name": a.Name(),
Jiyong Park09d77522019-11-18 11:16:27 +0900382 },
383 })
384
385 implicitInputs = append(implicitInputs, phonyOutput)
386 }
387
388 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
389 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
390
Jiyong Park3a1602e2020-01-14 14:39:19 +0900391 imageDir := android.PathForModuleOut(ctx, "image"+suffix)
Jiyong Park09d77522019-11-18 11:16:27 +0900392 if apexType == imageApex {
393 // files and dirs that will be created in APEX
394 var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
395 var executablePaths []string // this also includes dirs
396 for _, f := range a.filesInfo {
397 pathInApex := filepath.Join(f.installDir, f.builtFile.Base())
398 if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
399 executablePaths = append(executablePaths, pathInApex)
400 for _, s := range f.symlinks {
401 executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
402 }
403 } else {
404 readOnlyPaths = append(readOnlyPaths, pathInApex)
405 }
406 dir := f.installDir
407 for !android.InList(dir, executablePaths) && dir != "" {
408 executablePaths = append(executablePaths, dir)
409 dir, _ = filepath.Split(dir) // move up to the parent
410 if len(dir) > 0 {
411 // remove trailing slash
412 dir = dir[:len(dir)-1]
413 }
414 }
415 }
416 sort.Strings(readOnlyPaths)
417 sort.Strings(executablePaths)
418 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
419 ctx.Build(pctx, android.BuildParams{
420 Rule: generateFsConfig,
421 Output: cannedFsConfig,
422 Description: "generate fs config",
423 Args: map[string]string{
424 "ro_paths": strings.Join(readOnlyPaths, " "),
425 "exec_paths": strings.Join(executablePaths, " "),
426 },
427 })
428
Jiyong Park09d77522019-11-18 11:16:27 +0900429 optFlags := []string{}
430
431 // Additional implicit inputs.
Jooyung Han54aca7b2019-11-20 02:26:02 +0900432 implicitInputs = append(implicitInputs, cannedFsConfig, a.fileContexts, a.private_key_file, a.public_key_file)
Jiyong Park09d77522019-11-18 11:16:27 +0900433 optFlags = append(optFlags, "--pubkey "+a.public_key_file.String())
434
Jooyung Han27151d92019-12-16 17:45:32 +0900435 manifestPackageName := a.getOverrideManifestPackageName(ctx)
436 if manifestPackageName != "" {
Jiyong Park09d77522019-11-18 11:16:27 +0900437 optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
438 }
439
440 if a.properties.AndroidManifest != nil {
441 androidManifestFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.AndroidManifest))
442 implicitInputs = append(implicitInputs, androidManifestFile)
443 optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
444 }
445
446 targetSdkVersion := ctx.Config().DefaultAppTargetSdk()
Baligh Uddinf6201372020-01-24 23:15:44 +0000447 minSdkVersion := ctx.Config().DefaultAppTargetSdk()
Nikita Ioffedb10c132020-02-20 00:43:27 +0000448
Jooyung Han23b0adf2020-03-12 18:37:20 +0900449 if a.minSdkVersion(ctx) == android.SdkVersion_Android10 {
450 minSdkVersion = strconv.Itoa(a.minSdkVersion(ctx))
451 targetSdkVersion = strconv.Itoa(a.minSdkVersion(ctx))
Nikita Ioffedb10c132020-02-20 00:43:27 +0000452 }
453
Nikita Ioffe934c4f22020-03-02 16:58:11 +0000454 if java.UseApiFingerprint(ctx) {
455 targetSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
Baligh Uddinf6201372020-01-24 23:15:44 +0000456 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
457 }
Nikita Ioffe934c4f22020-03-02 16:58:11 +0000458 if java.UseApiFingerprint(ctx) {
459 minSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
Baligh Uddinf6201372020-01-24 23:15:44 +0000460 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
Jiyong Park09d77522019-11-18 11:16:27 +0900461 }
462 optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
Baligh Uddinf6201372020-01-24 23:15:44 +0000463 optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
Jiyong Park09d77522019-11-18 11:16:27 +0900464
Baligh Uddin004d7172020-02-19 21:29:28 -0800465 if a.overridableProperties.Logging_parent != "" {
466 optFlags = append(optFlags, "--logging_parent ", a.overridableProperties.Logging_parent)
467 }
468
Jiyong Park19972c72020-01-28 20:05:29 +0900469 a.mergedNotices = a.buildNoticeFiles(ctx, a.Name()+suffix)
470 if a.mergedNotices.HtmlGzOutput.Valid() {
Jiyong Park09d77522019-11-18 11:16:27 +0900471 // If there's a NOTICE file, embed it as an asset file in the APEX.
Jiyong Park19972c72020-01-28 20:05:29 +0900472 implicitInputs = append(implicitInputs, a.mergedNotices.HtmlGzOutput.Path())
473 optFlags = append(optFlags, "--assets_dir "+filepath.Dir(a.mergedNotices.HtmlGzOutput.String()))
Jiyong Park09d77522019-11-18 11:16:27 +0900474 }
475
Nikita Ioffeb4b44c02020-01-02 23:01:39 +0000476 if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && ctx.ModuleDir() != "system/apex/shim/build" && a.testOnlyShouldSkipHashtreeGeneration() {
Nikita Ioffec72b5dd2019-12-07 17:30:22 +0000477 ctx.PropertyErrorf("test_only_no_hashtree", "not available")
478 return
479 }
Jooyung Han23b0adf2020-03-12 18:37:20 +0900480 if a.minSdkVersion(ctx) > android.SdkVersion_Android10 || a.testOnlyShouldSkipHashtreeGeneration() {
Jiyong Park09d77522019-11-18 11:16:27 +0900481 // Apexes which are supposed to be installed in builtin dirs(/system, etc)
482 // don't need hashtree for activation. Therefore, by removing hashtree from
483 // apex bundle (filesystem image in it, to be specific), we can save storage.
484 optFlags = append(optFlags, "--no_hashtree")
485 }
486
Dario Freni98410fd2020-04-27 18:21:11 +0100487 if a.testOnlyShouldSkipPayloadSign() {
488 optFlags = append(optFlags, "--unsigned_payload")
489 }
490
Jiyong Park09d77522019-11-18 11:16:27 +0900491 if a.properties.Apex_name != nil {
492 // If apex_name is set, apexer can skip checking if key name matches with apex name.
493 // Note that apex_manifest is also mended.
494 optFlags = append(optFlags, "--do_not_check_keyname")
495 }
496
Jooyung Han23b0adf2020-03-12 18:37:20 +0900497 if a.minSdkVersion(ctx) == android.SdkVersion_Android10 {
Jooyung Han214bf372019-11-12 13:03:50 +0900498 implicitInputs = append(implicitInputs, a.manifestJsonOut)
499 optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
500 }
501
Jiyong Park09d77522019-11-18 11:16:27 +0900502 ctx.Build(pctx, android.BuildParams{
503 Rule: apexRule,
504 Implicits: implicitInputs,
505 Output: unsignedOutputFile,
506 Description: "apex (" + apexType.name() + ")",
507 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900508 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900509 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900510 "copy_commands": strings.Join(copyCommands, " && "),
511 "manifest": a.manifestPbOut.String(),
512 "file_contexts": a.fileContexts.String(),
513 "canned_fs_config": cannedFsConfig.String(),
514 "key": a.private_key_file.String(),
515 "opt_flags": strings.Join(optFlags, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900516 },
517 })
518
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800519 apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
520 bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
Jiyong Park09d77522019-11-18 11:16:27 +0900521 a.bundleModuleFile = bundleModuleFile
522
523 ctx.Build(pctx, android.BuildParams{
524 Rule: apexProtoConvertRule,
525 Input: unsignedOutputFile,
526 Output: apexProtoFile,
527 Description: "apex proto convert",
528 })
529
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900530 bundleConfig := a.buildBundleConfig(ctx)
531
Jiyong Park09d77522019-11-18 11:16:27 +0900532 ctx.Build(pctx, android.BuildParams{
533 Rule: apexBundleRule,
534 Input: apexProtoFile,
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900535 Implicit: bundleConfig,
Jiyong Park09d77522019-11-18 11:16:27 +0900536 Output: a.bundleModuleFile,
537 Description: "apex bundle module",
538 Args: map[string]string{
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900539 "abi": strings.Join(abis, "."),
540 "config": bundleConfig.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900541 },
542 })
543 } else {
544 ctx.Build(pctx, android.BuildParams{
545 Rule: zipApexRule,
546 Implicits: implicitInputs,
547 Output: unsignedOutputFile,
548 Description: "apex (" + apexType.name() + ")",
549 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900550 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900551 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900552 "copy_commands": strings.Join(copyCommands, " && "),
553 "manifest": a.manifestPbOut.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900554 },
555 })
556 }
557
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800558 a.outputFile = android.PathForModuleOut(ctx, a.Name()+suffix)
Jiyong Park09d77522019-11-18 11:16:27 +0900559 ctx.Build(pctx, android.BuildParams{
560 Rule: java.Signapk,
561 Description: "signapk",
562 Output: a.outputFile,
563 Input: unsignedOutputFile,
564 Implicits: []android.Path{
565 a.container_certificate_file,
566 a.container_private_key_file,
567 },
568 Args: map[string]string{
569 "certificates": a.container_certificate_file.String() + " " + a.container_private_key_file.String(),
570 "flags": "-a 4096", //alignment
571 },
572 })
573
574 // Install to $OUT/soong/{target,host}/.../apex
575 if a.installable() {
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800576 ctx.InstallFile(a.installDir, a.Name()+suffix, a.outputFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900577 }
578 a.buildFilesInfo(ctx)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900579
580 // installed-files.txt is dist'ed
581 a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900582}
583
584func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
585 // Temporarily wrap the original `ctx` into a `flattenedApexContext` to have it
586 // reply true to `InstallBypassMake()` (thus making the call
587 // `android.PathForModuleInstall` below use `android.pathForInstallInMakeDir`
588 // instead of `android.PathForOutput`) to return the correct path to the flattened
589 // APEX (as its contents is installed by Make, not Soong).
590 factx := flattenedApexContext{ctx}
Jiyong Parka5948012020-02-07 10:15:14 +0900591 apexBundleName := a.Name()
592 a.outputFile = android.PathForModuleInstall(&factx, "apex", apexBundleName)
Jiyong Park09d77522019-11-18 11:16:27 +0900593
Jiyong Park317645e2019-12-05 13:20:58 +0900594 if a.installable() && a.GetOverriddenBy() == "" {
Jiyong Parka5948012020-02-07 10:15:14 +0900595 installPath := android.PathForModuleInstall(ctx, "apex", apexBundleName)
Jooyung Han54aca7b2019-11-20 02:26:02 +0900596 devicePath := android.InstallPathToOnDevicePath(ctx, installPath)
Jiyong Parka5948012020-02-07 10:15:14 +0900597 addFlattenedFileContextsInfos(ctx, apexBundleName+":"+devicePath+":"+a.fileContexts.String())
Jooyung Han54aca7b2019-11-20 02:26:02 +0900598 }
Jiyong Park09d77522019-11-18 11:16:27 +0900599 a.buildFilesInfo(ctx)
600}
601
602func (a *apexBundle) setCertificateAndPrivateKey(ctx android.ModuleContext) {
Jooyung Hanf121a652019-12-17 14:30:11 +0900603 if a.container_certificate_file == nil {
604 cert := String(a.properties.Certificate)
605 if cert == "" {
606 pem, key := ctx.Config().DefaultAppCertificate(ctx)
607 a.container_certificate_file = pem
608 a.container_private_key_file = key
609 } else {
610 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
611 a.container_certificate_file = defaultDir.Join(ctx, cert+".x509.pem")
612 a.container_private_key_file = defaultDir.Join(ctx, cert+".pk8")
613 }
Jiyong Park09d77522019-11-18 11:16:27 +0900614 }
615}
616
617func (a *apexBundle) buildFilesInfo(ctx android.ModuleContext) {
618 if a.installable() {
Jooyung Han214bf372019-11-12 13:03:50 +0900619 // 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 +0900620 // with other ordinary files.
Jiyong Park7cd10e32020-01-14 09:22:18 +0900621 a.filesInfo = append(a.filesInfo, newApexFile(ctx, a.manifestPbOut, "apex_manifest.pb", ".", etc, nil))
Jiyong Park09d77522019-11-18 11:16:27 +0900622
623 // rename to apex_pubkey
624 copiedPubkey := android.PathForModuleOut(ctx, "apex_pubkey")
625 ctx.Build(pctx, android.BuildParams{
626 Rule: android.Cp,
627 Input: a.public_key_file,
628 Output: copiedPubkey,
629 })
Jiyong Park7cd10e32020-01-14 09:22:18 +0900630 a.filesInfo = append(a.filesInfo, newApexFile(ctx, copiedPubkey, "apex_pubkey", ".", etc, nil))
Jiyong Park09d77522019-11-18 11:16:27 +0900631
632 if a.properties.ApexType == flattenedApex {
Jiyong Parka5948012020-02-07 10:15:14 +0900633 apexBundleName := a.Name()
Jiyong Park09d77522019-11-18 11:16:27 +0900634 for _, fi := range a.filesInfo {
Jiyong Parka5948012020-02-07 10:15:14 +0900635 dir := filepath.Join("apex", apexBundleName, fi.installDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900636 target := ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.builtFile.Base(), fi.builtFile)
637 for _, sym := range fi.symlinks {
638 ctx.InstallSymlink(android.PathForModuleInstall(ctx, dir), sym, target)
639 }
640 }
641 }
642 }
643}
Jooyung Han27151d92019-12-16 17:45:32 +0900644
645func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
646 // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
647 // to see if it should be overridden because their <apex name> is dynamically generated
648 // according to its VNDK version.
649 if a.vndkApex {
650 overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
651 if overridden {
652 return strings.Replace(*a.properties.Apex_name, vndkApexName, overrideName, 1)
653 }
654 return ""
655 }
Baligh Uddincb6aa122020-03-15 13:01:05 -0700656 if a.overridableProperties.Package_name != "" {
657 return a.overridableProperties.Package_name
658 }
Jiyong Parka519c542020-03-03 11:45:41 +0900659 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jooyung Han27151d92019-12-16 17:45:32 +0900660 if overridden {
661 return manifestPackageName
662 }
663 return ""
664}
Jiyong Park83dc74b2020-01-14 18:38:44 +0900665
666func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
667 if !a.primaryApexType {
668 return
669 }
670
671 if a.properties.IsCoverageVariant {
672 // Otherwise, we will have duplicated rules for coverage and
673 // non-coverage variants of the same APEX
674 return
675 }
676
677 if ctx.Host() {
678 // No need to generate dependency info for host variant
679 return
680 }
681
Jiyong Park83dc74b2020-01-14 18:38:44 +0900682 var content strings.Builder
Jiyong Park678c8812020-02-07 17:25:49 +0900683 for _, key := range android.SortedStringKeys(a.depInfos) {
684 info := a.depInfos[key]
685 toName := info.to
686 if info.isExternal {
687 toName = toName + " (external)"
688 }
689 fmt.Fprintf(&content, "%s <- %s\\n", toName, strings.Join(android.SortedUniqueStrings(info.from), ", "))
Jiyong Park83dc74b2020-01-14 18:38:44 +0900690 }
691
692 depsInfoFile := android.PathForOutput(ctx, a.Name()+"-deps-info.txt")
693 ctx.Build(pctx, android.BuildParams{
694 Rule: android.WriteFile,
695 Description: "Dependency Info",
696 Output: depsInfoFile,
697 Args: map[string]string{
698 "content": content.String(),
699 },
700 })
701
702 ctx.Build(pctx, android.BuildParams{
703 Rule: android.Phony,
704 Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
705 Inputs: []android.Path{depsInfoFile},
706 })
707}