blob: 3d557e4ee2d9e99f8a379ad5024779b8c509df53 [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"
23 "strings"
24
25 "android/soong/android"
26 "android/soong/java"
27
28 "github.com/google/blueprint"
29 "github.com/google/blueprint/proptools"
30)
31
32var (
33 pctx = android.NewPackageContext("android/apex")
34)
35
36func init() {
37 pctx.Import("android/soong/android")
38 pctx.Import("android/soong/java")
39 pctx.HostBinToolVariable("apexer", "apexer")
40 // ART minimal builds (using the master-art manifest) do not have the "frameworks/base"
41 // projects, and hence cannot built 'aapt2'. Use the SDK prebuilt instead.
42 hostBinToolVariableWithPrebuilt := func(name, prebuiltDir, tool string) {
43 pctx.VariableFunc(name, func(ctx android.PackageVarContext) string {
44 if !ctx.Config().FrameworksBaseDirExists(ctx) {
45 return filepath.Join(prebuiltDir, runtime.GOOS, "bin", tool)
46 } else {
Martin Stjernholm7260d062019-12-09 21:47:14 +000047 return ctx.Config().HostToolPath(ctx, tool).String()
Jiyong Park09d77522019-11-18 11:16:27 +090048 }
49 })
50 }
51 hostBinToolVariableWithPrebuilt("aapt2", "prebuilts/sdk/tools", "aapt2")
52 pctx.HostBinToolVariable("avbtool", "avbtool")
53 pctx.HostBinToolVariable("e2fsdroid", "e2fsdroid")
54 pctx.HostBinToolVariable("merge_zips", "merge_zips")
55 pctx.HostBinToolVariable("mke2fs", "mke2fs")
56 pctx.HostBinToolVariable("resize2fs", "resize2fs")
57 pctx.HostBinToolVariable("sefcontext_compile", "sefcontext_compile")
58 pctx.HostBinToolVariable("soong_zip", "soong_zip")
59 pctx.HostBinToolVariable("zip2zip", "zip2zip")
60 pctx.HostBinToolVariable("zipalign", "zipalign")
61 pctx.HostBinToolVariable("jsonmodify", "jsonmodify")
62 pctx.HostBinToolVariable("conv_apex_manifest", "conv_apex_manifest")
63}
64
65var (
66 // Create a canned fs config file where all files and directories are
67 // by default set to (uid/gid/mode) = (1000/1000/0644)
68 // TODO(b/113082813) make this configurable using config.fs syntax
69 generateFsConfig = pctx.StaticRule("generateFsConfig", blueprint.RuleParams{
70 Command: `echo '/ 1000 1000 0755' > ${out} && ` +
71 `echo ${ro_paths} | tr ' ' '\n' | awk '{print "/"$$1 " 1000 1000 0644"}' >> ${out} && ` +
72 `echo ${exec_paths} | tr ' ' '\n' | awk '{print "/"$$1 " 0 2000 0755"}' >> ${out}`,
73 Description: "fs_config ${out}",
74 }, "ro_paths", "exec_paths")
75
76 apexManifestRule = pctx.StaticRule("apexManifestRule", blueprint.RuleParams{
77 Command: `rm -f $out && ${jsonmodify} $in ` +
78 `-a provideNativeLibs ${provideNativeLibs} ` +
79 `-a requireNativeLibs ${requireNativeLibs} ` +
80 `${opt} ` +
81 `-o $out`,
82 CommandDeps: []string{"${jsonmodify}"},
83 Description: "prepare ${out}",
84 }, "provideNativeLibs", "requireNativeLibs", "opt")
85
86 stripApexManifestRule = pctx.StaticRule("stripApexManifestRule", blueprint.RuleParams{
87 Command: `rm -f $out && ${conv_apex_manifest} strip $in -o $out`,
88 CommandDeps: []string{"${conv_apex_manifest}"},
89 Description: "strip ${in}=>${out}",
90 })
91
92 pbApexManifestRule = pctx.StaticRule("pbApexManifestRule", blueprint.RuleParams{
93 Command: `rm -f $out && ${conv_apex_manifest} proto $in -o $out`,
94 CommandDeps: []string{"${conv_apex_manifest}"},
95 Description: "convert ${in}=>${out}",
96 })
97
98 // TODO(b/113233103): make sure that file_contexts is sane, i.e., validate
99 // against the binary policy using sefcontext_compiler -p <policy>.
100
101 // TODO(b/114327326): automate the generation of file_contexts
102 apexRule = pctx.StaticRule("apexRule", blueprint.RuleParams{
103 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
104 `(. ${out}.copy_commands) && ` +
105 `APEXER_TOOL_PATH=${tool_path} ` +
106 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900107 `--file_contexts ${file_contexts} ` +
108 `--canned_fs_config ${canned_fs_config} ` +
Dario Freni0f4ae072020-01-02 15:24:12 +0000109 `--include_build_info ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900110 `--payload_type image ` +
111 `--key ${key} ${opt_flags} ${image_dir} ${out} `,
112 CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
113 "${mke2fs}", "${resize2fs}", "${sefcontext_compile}",
114 "${soong_zip}", "${zipalign}", "${aapt2}", "prebuilts/sdk/current/public/android.jar"},
115 Rspfile: "${out}.copy_commands",
116 RspfileContent: "${copy_commands}",
117 Description: "APEX ${image_dir} => ${out}",
Jooyung Han214bf372019-11-12 13:03:50 +0900118 }, "tool_path", "image_dir", "copy_commands", "file_contexts", "canned_fs_config", "key", "opt_flags", "manifest")
Jiyong Park09d77522019-11-18 11:16:27 +0900119
120 zipApexRule = pctx.StaticRule("zipApexRule", blueprint.RuleParams{
121 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
122 `(. ${out}.copy_commands) && ` +
123 `APEXER_TOOL_PATH=${tool_path} ` +
Jooyung Han214bf372019-11-12 13:03:50 +0900124 `${apexer} --force --manifest ${manifest} ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900125 `--payload_type zip ` +
126 `${image_dir} ${out} `,
127 CommandDeps: []string{"${apexer}", "${merge_zips}", "${soong_zip}", "${zipalign}", "${aapt2}"},
128 Rspfile: "${out}.copy_commands",
129 RspfileContent: "${copy_commands}",
130 Description: "ZipAPEX ${image_dir} => ${out}",
Jooyung Han214bf372019-11-12 13:03:50 +0900131 }, "tool_path", "image_dir", "copy_commands", "manifest")
Jiyong Park09d77522019-11-18 11:16:27 +0900132
133 apexProtoConvertRule = pctx.AndroidStaticRule("apexProtoConvertRule",
134 blueprint.RuleParams{
135 Command: `${aapt2} convert --output-format proto $in -o $out`,
136 CommandDeps: []string{"${aapt2}"},
137 })
138
139 apexBundleRule = pctx.StaticRule("apexBundleRule", blueprint.RuleParams{
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900140 Command: `${zip2zip} -i $in -o $out.base ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900141 `apex_payload.img:apex/${abi}.img ` +
142 `apex_manifest.json:root/apex_manifest.json ` +
Jiyong Park53ae3342019-12-08 02:06:24 +0900143 `apex_manifest.pb:root/apex_manifest.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900144 `AndroidManifest.xml:manifest/AndroidManifest.xml ` +
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900145 `assets/NOTICE.html.gz:assets/NOTICE.html.gz &&` +
146 `${soong_zip} -o $out.config -C $$(dirname ${config}) -f ${config} && ` +
147 `${merge_zips} $out $out.base $out.config`,
148 CommandDeps: []string{"${zip2zip}", "${soong_zip}", "${merge_zips}"},
Jiyong Park09d77522019-11-18 11:16:27 +0900149 Description: "app bundle",
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900150 }, "abi", "config")
Jiyong Park09d77522019-11-18 11:16:27 +0900151
152 emitApexContentRule = pctx.StaticRule("emitApexContentRule", blueprint.RuleParams{
153 Command: `rm -f ${out} && touch ${out} && (. ${out}.emit_commands)`,
154 Rspfile: "${out}.emit_commands",
155 RspfileContent: "${emit_commands}",
156 Description: "Emit APEX image content",
157 }, "emit_commands")
158
159 diffApexContentRule = pctx.StaticRule("diffApexContentRule", blueprint.RuleParams{
160 Command: `diff --unchanged-group-format='' \` +
161 `--changed-group-format='%<' \` +
162 `${image_content_file} ${whitelisted_files_file} || (` +
163 `echo -e "New unexpected files were added to ${apex_module_name}." ` +
164 ` "To fix the build run following command:" && ` +
165 `echo "system/apex/tools/update_whitelist.sh ${whitelisted_files_file} ${image_content_file}" && ` +
Dan Willemsen81e43c52020-01-28 15:40:19 -0800166 `exit 1); touch ${out}`,
Jiyong Park09d77522019-11-18 11:16:27 +0900167 Description: "Diff ${image_content_file} and ${whitelisted_files_file}",
168 }, "image_content_file", "whitelisted_files_file", "apex_module_name")
169)
170
171func (a *apexBundle) buildManifest(ctx android.ModuleContext, provideNativeLibs, requireNativeLibs []string) {
172 manifestSrc := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
173
Jooyung Han214bf372019-11-12 13:03:50 +0900174 manifestJsonFullOut := android.PathForModuleOut(ctx, "apex_manifest_full.json")
Jiyong Park09d77522019-11-18 11:16:27 +0900175
176 // put dependency({provide|require}NativeLibs) in apex_manifest.json
177 provideNativeLibs = android.SortedUniqueStrings(provideNativeLibs)
178 requireNativeLibs = android.SortedUniqueStrings(android.RemoveListFromList(requireNativeLibs, provideNativeLibs))
179
180 // apex name can be overridden
181 optCommands := []string{}
182 if a.properties.Apex_name != nil {
183 optCommands = append(optCommands, "-v name "+*a.properties.Apex_name)
184 }
185
186 ctx.Build(pctx, android.BuildParams{
187 Rule: apexManifestRule,
188 Input: manifestSrc,
Jooyung Han214bf372019-11-12 13:03:50 +0900189 Output: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900190 Args: map[string]string{
191 "provideNativeLibs": strings.Join(provideNativeLibs, " "),
192 "requireNativeLibs": strings.Join(requireNativeLibs, " "),
193 "opt": strings.Join(optCommands, " "),
194 },
195 })
196
Jooyung Han214bf372019-11-12 13:03:50 +0900197 if proptools.Bool(a.properties.Legacy_android10_support) {
198 // b/143654022 Q apexd can't understand newly added keys in apex_manifest.json
199 // prepare stripped-down version so that APEX modules built from R+ can be installed to Q
200 a.manifestJsonOut = android.PathForModuleOut(ctx, "apex_manifest.json")
201 ctx.Build(pctx, android.BuildParams{
202 Rule: stripApexManifestRule,
203 Input: manifestJsonFullOut,
204 Output: a.manifestJsonOut,
205 })
206 }
Jiyong Park09d77522019-11-18 11:16:27 +0900207
208 // from R+, protobuf binary format (.pb) is the standard format for apex_manifest
209 a.manifestPbOut = android.PathForModuleOut(ctx, "apex_manifest.pb")
210 ctx.Build(pctx, android.BuildParams{
211 Rule: pbApexManifestRule,
Jooyung Han214bf372019-11-12 13:03:50 +0900212 Input: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900213 Output: a.manifestPbOut,
214 })
215}
216
Jiyong Park19972c72020-01-28 20:05:29 +0900217func (a *apexBundle) buildNoticeFiles(ctx android.ModuleContext, apexFileName string) android.NoticeOutputs {
Jiyong Park09d77522019-11-18 11:16:27 +0900218 noticeFiles := []android.Path{}
219 for _, f := range a.filesInfo {
220 if f.module != nil {
221 notice := f.module.NoticeFile()
222 if notice.Valid() {
223 noticeFiles = append(noticeFiles, notice.Path())
224 }
225 }
226 }
227 // append the notice file specified in the apex module itself
228 if a.NoticeFile().Valid() {
229 noticeFiles = append(noticeFiles, a.NoticeFile().Path())
230 }
231
232 if len(noticeFiles) == 0 {
Jiyong Park19972c72020-01-28 20:05:29 +0900233 return android.NoticeOutputs{}
Jiyong Park09d77522019-11-18 11:16:27 +0900234 }
235
Jiyong Park19972c72020-01-28 20:05:29 +0900236 return android.BuildNoticeOutput(ctx, a.installDir, apexFileName, android.FirstUniquePaths(noticeFiles))
Jiyong Park09d77522019-11-18 11:16:27 +0900237}
238
Jiyong Park3a1602e2020-01-14 14:39:19 +0900239func (a *apexBundle) buildInstalledFilesFile(ctx android.ModuleContext, builtApex android.Path, imageDir android.Path) android.OutputPath {
240 output := android.PathForModuleOut(ctx, "installed-files.txt")
241 rule := android.NewRuleBuilder()
242 rule.Command().
243 Implicit(builtApex).
244 Text("(cd " + imageDir.String() + " ; ").
Jiyong Parkbd63a102020-02-08 12:40:05 +0900245 Text("find . \\( -type f -o -type l \\) -printf \"%s %p\\n\") ").
Jiyong Park3a1602e2020-01-14 14:39:19 +0900246 Text(" | sort -nr > ").
247 Output(output)
248 rule.Build(pctx, ctx, "installed-files."+a.Name(), "Installed files")
249 return output.OutputPath
250}
251
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900252func (a *apexBundle) buildBundleConfig(ctx android.ModuleContext) android.OutputPath {
253 output := android.PathForModuleOut(ctx, "bundle_config.json")
254
255 config := struct {
256 Compression struct {
257 Uncompressed_glob []string `json:"uncompressed_glob"`
258 } `json:"compression"`
259 }{}
260
261 config.Compression.Uncompressed_glob = []string{
262 "apex_payload.img",
263 "apex_manifest.*",
264 }
265 j, err := json.Marshal(config)
266 if err != nil {
267 panic(fmt.Errorf("error while marshalling to %q: %#v", output, err))
268 }
269
270 ctx.Build(pctx, android.BuildParams{
271 Rule: android.WriteFile,
272 Output: output,
273 Description: "Bundle Config " + output.String(),
274 Args: map[string]string{
275 "content": string(j),
276 },
277 })
278
279 return output.OutputPath
280}
281
Jiyong Park09d77522019-11-18 11:16:27 +0900282func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext) {
283 var abis []string
284 for _, target := range ctx.MultiTargets() {
285 if len(target.Arch.Abi) > 0 {
286 abis = append(abis, target.Arch.Abi[0])
287 }
288 }
289
290 abis = android.FirstUniqueStrings(abis)
291
292 apexType := a.properties.ApexType
293 suffix := apexType.suffix()
Jiyong Park7cd10e32020-01-14 09:22:18 +0900294 var implicitInputs []android.Path
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800295 unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
Jiyong Park09d77522019-11-18 11:16:27 +0900296
Jiyong Park7cd10e32020-01-14 09:22:18 +0900297 // TODO(jiyong): construct the copy rules using RuleBuilder
298 var copyCommands []string
299 for _, fi := range a.filesInfo {
300 destPath := android.PathForModuleOut(ctx, "image"+suffix, fi.Path()).String()
301 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(destPath))
302 if a.linkToSystemLib && fi.transitiveDep && fi.AvailableToPlatform() {
303 // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
304 pathOnDevice := filepath.Join("/system", fi.Path())
305 copyCommands = append(copyCommands, "ln -sfn "+pathOnDevice+" "+destPath)
306 } else {
307 copyCommands = append(copyCommands, "cp -f "+fi.builtFile.String()+" "+destPath)
308 implicitInputs = append(implicitInputs, fi.builtFile)
309 }
310 // create additional symlinks pointing the file inside the APEX
311 for _, symlinkPath := range fi.SymlinkPaths() {
312 symlinkDest := android.PathForModuleOut(ctx, "image"+suffix, symlinkPath).String()
313 copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
314 }
Jiyong Park09d77522019-11-18 11:16:27 +0900315 }
316
Jiyong Park7cd10e32020-01-14 09:22:18 +0900317 // TODO(jiyong): use RuleBuilder
318 var emitCommands []string
319 imageContentFile := android.PathForModuleOut(ctx, "content.txt")
Jooyung Han214bf372019-11-12 13:03:50 +0900320 emitCommands = append(emitCommands, "echo ./apex_manifest.pb >> "+imageContentFile.String())
321 if proptools.Bool(a.properties.Legacy_android10_support) {
322 emitCommands = append(emitCommands, "echo ./apex_manifest.json >> "+imageContentFile.String())
323 }
Jiyong Park7cd10e32020-01-14 09:22:18 +0900324 for _, fi := range a.filesInfo {
325 emitCommands = append(emitCommands, "echo './"+fi.Path()+"' >> "+imageContentFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900326 }
327 emitCommands = append(emitCommands, "sort -o "+imageContentFile.String()+" "+imageContentFile.String())
Jooyung Han214bf372019-11-12 13:03:50 +0900328 implicitInputs = append(implicitInputs, a.manifestPbOut)
Jiyong Park09d77522019-11-18 11:16:27 +0900329
330 if a.properties.Whitelisted_files != nil {
331 ctx.Build(pctx, android.BuildParams{
332 Rule: emitApexContentRule,
333 Implicits: implicitInputs,
334 Output: imageContentFile,
335 Description: "emit apex image content",
336 Args: map[string]string{
337 "emit_commands": strings.Join(emitCommands, " && "),
338 },
339 })
340 implicitInputs = append(implicitInputs, imageContentFile)
341 whitelistedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.Whitelisted_files))
342
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800343 phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
Jiyong Park09d77522019-11-18 11:16:27 +0900344 ctx.Build(pctx, android.BuildParams{
345 Rule: diffApexContentRule,
346 Implicits: implicitInputs,
347 Output: phonyOutput,
348 Description: "diff apex image content",
349 Args: map[string]string{
350 "whitelisted_files_file": whitelistedFilesFile.String(),
351 "image_content_file": imageContentFile.String(),
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800352 "apex_module_name": a.Name(),
Jiyong Park09d77522019-11-18 11:16:27 +0900353 },
354 })
355
356 implicitInputs = append(implicitInputs, phonyOutput)
357 }
358
359 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
360 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
361
Jiyong Park3a1602e2020-01-14 14:39:19 +0900362 imageDir := android.PathForModuleOut(ctx, "image"+suffix)
Jiyong Park09d77522019-11-18 11:16:27 +0900363 if apexType == imageApex {
364 // files and dirs that will be created in APEX
365 var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
366 var executablePaths []string // this also includes dirs
367 for _, f := range a.filesInfo {
368 pathInApex := filepath.Join(f.installDir, f.builtFile.Base())
369 if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
370 executablePaths = append(executablePaths, pathInApex)
371 for _, s := range f.symlinks {
372 executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
373 }
374 } else {
375 readOnlyPaths = append(readOnlyPaths, pathInApex)
376 }
377 dir := f.installDir
378 for !android.InList(dir, executablePaths) && dir != "" {
379 executablePaths = append(executablePaths, dir)
380 dir, _ = filepath.Split(dir) // move up to the parent
381 if len(dir) > 0 {
382 // remove trailing slash
383 dir = dir[:len(dir)-1]
384 }
385 }
386 }
387 sort.Strings(readOnlyPaths)
388 sort.Strings(executablePaths)
389 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
390 ctx.Build(pctx, android.BuildParams{
391 Rule: generateFsConfig,
392 Output: cannedFsConfig,
393 Description: "generate fs config",
394 Args: map[string]string{
395 "ro_paths": strings.Join(readOnlyPaths, " "),
396 "exec_paths": strings.Join(executablePaths, " "),
397 },
398 })
399
Jiyong Park09d77522019-11-18 11:16:27 +0900400 optFlags := []string{}
401
402 // Additional implicit inputs.
Jooyung Han54aca7b2019-11-20 02:26:02 +0900403 implicitInputs = append(implicitInputs, cannedFsConfig, a.fileContexts, a.private_key_file, a.public_key_file)
Jiyong Park09d77522019-11-18 11:16:27 +0900404 optFlags = append(optFlags, "--pubkey "+a.public_key_file.String())
405
Jooyung Han27151d92019-12-16 17:45:32 +0900406 manifestPackageName := a.getOverrideManifestPackageName(ctx)
407 if manifestPackageName != "" {
Jiyong Park09d77522019-11-18 11:16:27 +0900408 optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
409 }
410
411 if a.properties.AndroidManifest != nil {
412 androidManifestFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.AndroidManifest))
413 implicitInputs = append(implicitInputs, androidManifestFile)
414 optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
415 }
416
417 targetSdkVersion := ctx.Config().DefaultAppTargetSdk()
Baligh Uddinf6201372020-01-24 23:15:44 +0000418 minSdkVersion := ctx.Config().DefaultAppTargetSdk()
Nikita Ioffedb10c132020-02-20 00:43:27 +0000419
420 if proptools.Bool(a.properties.Legacy_android10_support) {
421 if !java.UseApiFingerprint(ctx, targetSdkVersion) {
422 targetSdkVersion = "29"
423 }
424 if !java.UseApiFingerprint(ctx, minSdkVersion) {
425 minSdkVersion = "29"
426 }
427 }
428
Baligh Uddinf6201372020-01-24 23:15:44 +0000429 if java.UseApiFingerprint(ctx, targetSdkVersion) {
430 targetSdkVersion += fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
431 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
432 }
433 if java.UseApiFingerprint(ctx, minSdkVersion) {
434 minSdkVersion += fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
435 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
Jiyong Park09d77522019-11-18 11:16:27 +0900436 }
437 optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
Baligh Uddinf6201372020-01-24 23:15:44 +0000438 optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
Jiyong Park09d77522019-11-18 11:16:27 +0900439
Baligh Uddin004d7172020-02-19 21:29:28 -0800440 if a.overridableProperties.Logging_parent != "" {
441 optFlags = append(optFlags, "--logging_parent ", a.overridableProperties.Logging_parent)
442 }
443
Jiyong Park19972c72020-01-28 20:05:29 +0900444 a.mergedNotices = a.buildNoticeFiles(ctx, a.Name()+suffix)
445 if a.mergedNotices.HtmlGzOutput.Valid() {
Jiyong Park09d77522019-11-18 11:16:27 +0900446 // If there's a NOTICE file, embed it as an asset file in the APEX.
Jiyong Park19972c72020-01-28 20:05:29 +0900447 implicitInputs = append(implicitInputs, a.mergedNotices.HtmlGzOutput.Path())
448 optFlags = append(optFlags, "--assets_dir "+filepath.Dir(a.mergedNotices.HtmlGzOutput.String()))
Jiyong Park09d77522019-11-18 11:16:27 +0900449 }
450
Nikita Ioffeb4b44c02020-01-02 23:01:39 +0000451 if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && ctx.ModuleDir() != "system/apex/shim/build" && a.testOnlyShouldSkipHashtreeGeneration() {
Nikita Ioffec72b5dd2019-12-07 17:30:22 +0000452 ctx.PropertyErrorf("test_only_no_hashtree", "not available")
453 return
454 }
Dario Frenie3546902020-01-14 23:50:25 +0000455 if !proptools.Bool(a.properties.Legacy_android10_support) || a.testOnlyShouldSkipHashtreeGeneration() {
Jiyong Park09d77522019-11-18 11:16:27 +0900456 // Apexes which are supposed to be installed in builtin dirs(/system, etc)
457 // don't need hashtree for activation. Therefore, by removing hashtree from
458 // apex bundle (filesystem image in it, to be specific), we can save storage.
459 optFlags = append(optFlags, "--no_hashtree")
460 }
461
462 if a.properties.Apex_name != nil {
463 // If apex_name is set, apexer can skip checking if key name matches with apex name.
464 // Note that apex_manifest is also mended.
465 optFlags = append(optFlags, "--do_not_check_keyname")
466 }
467
Jooyung Han214bf372019-11-12 13:03:50 +0900468 if proptools.Bool(a.properties.Legacy_android10_support) {
469 implicitInputs = append(implicitInputs, a.manifestJsonOut)
470 optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
471 }
472
Jiyong Park09d77522019-11-18 11:16:27 +0900473 ctx.Build(pctx, android.BuildParams{
474 Rule: apexRule,
475 Implicits: implicitInputs,
476 Output: unsignedOutputFile,
477 Description: "apex (" + apexType.name() + ")",
478 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900479 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900480 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900481 "copy_commands": strings.Join(copyCommands, " && "),
482 "manifest": a.manifestPbOut.String(),
483 "file_contexts": a.fileContexts.String(),
484 "canned_fs_config": cannedFsConfig.String(),
485 "key": a.private_key_file.String(),
486 "opt_flags": strings.Join(optFlags, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900487 },
488 })
489
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800490 apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
491 bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
Jiyong Park09d77522019-11-18 11:16:27 +0900492 a.bundleModuleFile = bundleModuleFile
493
494 ctx.Build(pctx, android.BuildParams{
495 Rule: apexProtoConvertRule,
496 Input: unsignedOutputFile,
497 Output: apexProtoFile,
498 Description: "apex proto convert",
499 })
500
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900501 bundleConfig := a.buildBundleConfig(ctx)
502
Jiyong Park09d77522019-11-18 11:16:27 +0900503 ctx.Build(pctx, android.BuildParams{
504 Rule: apexBundleRule,
505 Input: apexProtoFile,
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900506 Implicit: bundleConfig,
Jiyong Park09d77522019-11-18 11:16:27 +0900507 Output: a.bundleModuleFile,
508 Description: "apex bundle module",
509 Args: map[string]string{
Jiyong Parkd93e1b12020-02-28 15:22:21 +0900510 "abi": strings.Join(abis, "."),
511 "config": bundleConfig.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900512 },
513 })
514 } else {
515 ctx.Build(pctx, android.BuildParams{
516 Rule: zipApexRule,
517 Implicits: implicitInputs,
518 Output: unsignedOutputFile,
519 Description: "apex (" + apexType.name() + ")",
520 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900521 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900522 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900523 "copy_commands": strings.Join(copyCommands, " && "),
524 "manifest": a.manifestPbOut.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900525 },
526 })
527 }
528
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800529 a.outputFile = android.PathForModuleOut(ctx, a.Name()+suffix)
Jiyong Park09d77522019-11-18 11:16:27 +0900530 ctx.Build(pctx, android.BuildParams{
531 Rule: java.Signapk,
532 Description: "signapk",
533 Output: a.outputFile,
534 Input: unsignedOutputFile,
535 Implicits: []android.Path{
536 a.container_certificate_file,
537 a.container_private_key_file,
538 },
539 Args: map[string]string{
540 "certificates": a.container_certificate_file.String() + " " + a.container_private_key_file.String(),
541 "flags": "-a 4096", //alignment
542 },
543 })
544
545 // Install to $OUT/soong/{target,host}/.../apex
546 if a.installable() {
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800547 ctx.InstallFile(a.installDir, a.Name()+suffix, a.outputFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900548 }
549 a.buildFilesInfo(ctx)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900550
551 // installed-files.txt is dist'ed
552 a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900553}
554
555func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
556 // Temporarily wrap the original `ctx` into a `flattenedApexContext` to have it
557 // reply true to `InstallBypassMake()` (thus making the call
558 // `android.PathForModuleInstall` below use `android.pathForInstallInMakeDir`
559 // instead of `android.PathForOutput`) to return the correct path to the flattened
560 // APEX (as its contents is installed by Make, not Soong).
561 factx := flattenedApexContext{ctx}
Jiyong Parka5948012020-02-07 10:15:14 +0900562 apexBundleName := a.Name()
563 a.outputFile = android.PathForModuleInstall(&factx, "apex", apexBundleName)
Jiyong Park09d77522019-11-18 11:16:27 +0900564
Jiyong Park317645e2019-12-05 13:20:58 +0900565 if a.installable() && a.GetOverriddenBy() == "" {
Jiyong Parka5948012020-02-07 10:15:14 +0900566 installPath := android.PathForModuleInstall(ctx, "apex", apexBundleName)
Jooyung Han54aca7b2019-11-20 02:26:02 +0900567 devicePath := android.InstallPathToOnDevicePath(ctx, installPath)
Jiyong Parka5948012020-02-07 10:15:14 +0900568 addFlattenedFileContextsInfos(ctx, apexBundleName+":"+devicePath+":"+a.fileContexts.String())
Jooyung Han54aca7b2019-11-20 02:26:02 +0900569 }
Jiyong Park09d77522019-11-18 11:16:27 +0900570 a.buildFilesInfo(ctx)
571}
572
573func (a *apexBundle) setCertificateAndPrivateKey(ctx android.ModuleContext) {
Jooyung Hanf121a652019-12-17 14:30:11 +0900574 if a.container_certificate_file == nil {
575 cert := String(a.properties.Certificate)
576 if cert == "" {
577 pem, key := ctx.Config().DefaultAppCertificate(ctx)
578 a.container_certificate_file = pem
579 a.container_private_key_file = key
580 } else {
581 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
582 a.container_certificate_file = defaultDir.Join(ctx, cert+".x509.pem")
583 a.container_private_key_file = defaultDir.Join(ctx, cert+".pk8")
584 }
Jiyong Park09d77522019-11-18 11:16:27 +0900585 }
586}
587
588func (a *apexBundle) buildFilesInfo(ctx android.ModuleContext) {
589 if a.installable() {
Jooyung Han214bf372019-11-12 13:03:50 +0900590 // 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 +0900591 // with other ordinary files.
Jiyong Park7cd10e32020-01-14 09:22:18 +0900592 a.filesInfo = append(a.filesInfo, newApexFile(ctx, a.manifestPbOut, "apex_manifest.pb", ".", etc, nil))
Jiyong Park09d77522019-11-18 11:16:27 +0900593
594 // rename to apex_pubkey
595 copiedPubkey := android.PathForModuleOut(ctx, "apex_pubkey")
596 ctx.Build(pctx, android.BuildParams{
597 Rule: android.Cp,
598 Input: a.public_key_file,
599 Output: copiedPubkey,
600 })
Jiyong Park7cd10e32020-01-14 09:22:18 +0900601 a.filesInfo = append(a.filesInfo, newApexFile(ctx, copiedPubkey, "apex_pubkey", ".", etc, nil))
Jiyong Park09d77522019-11-18 11:16:27 +0900602
603 if a.properties.ApexType == flattenedApex {
Jiyong Parka5948012020-02-07 10:15:14 +0900604 apexBundleName := a.Name()
Jiyong Park09d77522019-11-18 11:16:27 +0900605 for _, fi := range a.filesInfo {
Jiyong Parka5948012020-02-07 10:15:14 +0900606 dir := filepath.Join("apex", apexBundleName, fi.installDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900607 target := ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.builtFile.Base(), fi.builtFile)
608 for _, sym := range fi.symlinks {
609 ctx.InstallSymlink(android.PathForModuleInstall(ctx, dir), sym, target)
610 }
611 }
612 }
613 }
614}
Jooyung Han27151d92019-12-16 17:45:32 +0900615
616func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
617 // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
618 // to see if it should be overridden because their <apex name> is dynamically generated
619 // according to its VNDK version.
620 if a.vndkApex {
621 overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
622 if overridden {
623 return strings.Replace(*a.properties.Apex_name, vndkApexName, overrideName, 1)
624 }
625 return ""
626 }
627 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(a.Name())
628 if overridden {
629 return manifestPackageName
630 }
631 return ""
632}
Jiyong Park83dc74b2020-01-14 18:38:44 +0900633
634func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
635 if !a.primaryApexType {
636 return
637 }
638
639 if a.properties.IsCoverageVariant {
640 // Otherwise, we will have duplicated rules for coverage and
641 // non-coverage variants of the same APEX
642 return
643 }
644
645 if ctx.Host() {
646 // No need to generate dependency info for host variant
647 return
648 }
649
Jiyong Park83dc74b2020-01-14 18:38:44 +0900650 var content strings.Builder
Jiyong Park678c8812020-02-07 17:25:49 +0900651 for _, key := range android.SortedStringKeys(a.depInfos) {
652 info := a.depInfos[key]
653 toName := info.to
654 if info.isExternal {
655 toName = toName + " (external)"
656 }
657 fmt.Fprintf(&content, "%s <- %s\\n", toName, strings.Join(android.SortedUniqueStrings(info.from), ", "))
Jiyong Park83dc74b2020-01-14 18:38:44 +0900658 }
659
660 depsInfoFile := android.PathForOutput(ctx, a.Name()+"-deps-info.txt")
661 ctx.Build(pctx, android.BuildParams{
662 Rule: android.WriteFile,
663 Description: "Dependency Info",
664 Output: depsInfoFile,
665 Args: map[string]string{
666 "content": content.String(),
667 },
668 })
669
670 ctx.Build(pctx, android.BuildParams{
671 Rule: android.Phony,
672 Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
673 Inputs: []android.Path{depsInfoFile},
674 })
675}