blob: d7a20e422dbbb2c3a5a397a2c4fa80415cf2e36b [file] [log] [blame]
Jiyong Park09d77522019-11-18 11:16:27 +09001// Copyright (C) 2019 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package apex
16
17import (
Jiyong Parkbd159612020-02-28 15:22:21 +090018 "encoding/json"
Jiyong Park09d77522019-11-18 11:16:27 +090019 "fmt"
20 "path/filepath"
21 "runtime"
22 "sort"
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 Parkbd159612020-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 ` +
Dario Frenida1aefe2020-03-02 21:47:09 +0000142 `apex_build_info.pb:apex/${abi}.build_info.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900143 `apex_manifest.json:root/apex_manifest.json ` +
Jiyong Park53ae3342019-12-08 02:06:24 +0900144 `apex_manifest.pb:root/apex_manifest.pb ` +
Jiyong Park09d77522019-11-18 11:16:27 +0900145 `AndroidManifest.xml:manifest/AndroidManifest.xml ` +
Jiyong Parkbd159612020-02-28 15:22:21 +0900146 `assets/NOTICE.html.gz:assets/NOTICE.html.gz &&` +
147 `${soong_zip} -o $out.config -C $$(dirname ${config}) -f ${config} && ` +
148 `${merge_zips} $out $out.base $out.config`,
149 CommandDeps: []string{"${zip2zip}", "${soong_zip}", "${merge_zips}"},
Jiyong Park09d77522019-11-18 11:16:27 +0900150 Description: "app bundle",
Jiyong Parkbd159612020-02-28 15:22:21 +0900151 }, "abi", "config")
Jiyong Park09d77522019-11-18 11:16:27 +0900152
153 emitApexContentRule = pctx.StaticRule("emitApexContentRule", blueprint.RuleParams{
154 Command: `rm -f ${out} && touch ${out} && (. ${out}.emit_commands)`,
155 Rspfile: "${out}.emit_commands",
156 RspfileContent: "${emit_commands}",
157 Description: "Emit APEX image content",
158 }, "emit_commands")
159
160 diffApexContentRule = pctx.StaticRule("diffApexContentRule", blueprint.RuleParams{
161 Command: `diff --unchanged-group-format='' \` +
162 `--changed-group-format='%<' \` +
163 `${image_content_file} ${whitelisted_files_file} || (` +
164 `echo -e "New unexpected files were added to ${apex_module_name}." ` +
165 ` "To fix the build run following command:" && ` +
166 `echo "system/apex/tools/update_whitelist.sh ${whitelisted_files_file} ${image_content_file}" && ` +
Dan Willemsen81e43c52020-01-28 15:40:19 -0800167 `exit 1); touch ${out}`,
Jiyong Park09d77522019-11-18 11:16:27 +0900168 Description: "Diff ${image_content_file} and ${whitelisted_files_file}",
169 }, "image_content_file", "whitelisted_files_file", "apex_module_name")
170)
171
172func (a *apexBundle) buildManifest(ctx android.ModuleContext, provideNativeLibs, requireNativeLibs []string) {
173 manifestSrc := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
174
Jooyung Han214bf372019-11-12 13:03:50 +0900175 manifestJsonFullOut := android.PathForModuleOut(ctx, "apex_manifest_full.json")
Jiyong Park09d77522019-11-18 11:16:27 +0900176
177 // put dependency({provide|require}NativeLibs) in apex_manifest.json
178 provideNativeLibs = android.SortedUniqueStrings(provideNativeLibs)
179 requireNativeLibs = android.SortedUniqueStrings(android.RemoveListFromList(requireNativeLibs, provideNativeLibs))
180
181 // apex name can be overridden
182 optCommands := []string{}
183 if a.properties.Apex_name != nil {
184 optCommands = append(optCommands, "-v name "+*a.properties.Apex_name)
185 }
186
Jooyung Han643adc42020-02-27 13:50:06 +0900187 // collect jniLibs. Notice that a.filesInfo is already sorted
188 var jniLibs []string
189 for _, fi := range a.filesInfo {
190 if fi.isJniLib {
191 jniLibs = append(jniLibs, fi.builtFile.Base())
192 }
193 }
194 if len(jniLibs) > 0 {
195 optCommands = append(optCommands, "-a jniLibs "+strings.Join(jniLibs, " "))
196 }
197
Jiyong Park09d77522019-11-18 11:16:27 +0900198 ctx.Build(pctx, android.BuildParams{
199 Rule: apexManifestRule,
200 Input: manifestSrc,
Jooyung Han214bf372019-11-12 13:03:50 +0900201 Output: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900202 Args: map[string]string{
203 "provideNativeLibs": strings.Join(provideNativeLibs, " "),
204 "requireNativeLibs": strings.Join(requireNativeLibs, " "),
205 "opt": strings.Join(optCommands, " "),
206 },
207 })
208
Jooyung Han214bf372019-11-12 13:03:50 +0900209 if proptools.Bool(a.properties.Legacy_android10_support) {
210 // b/143654022 Q apexd can't understand newly added keys in apex_manifest.json
211 // prepare stripped-down version so that APEX modules built from R+ can be installed to Q
212 a.manifestJsonOut = android.PathForModuleOut(ctx, "apex_manifest.json")
213 ctx.Build(pctx, android.BuildParams{
214 Rule: stripApexManifestRule,
215 Input: manifestJsonFullOut,
216 Output: a.manifestJsonOut,
217 })
218 }
Jiyong Park09d77522019-11-18 11:16:27 +0900219
220 // from R+, protobuf binary format (.pb) is the standard format for apex_manifest
221 a.manifestPbOut = android.PathForModuleOut(ctx, "apex_manifest.pb")
222 ctx.Build(pctx, android.BuildParams{
223 Rule: pbApexManifestRule,
Jooyung Han214bf372019-11-12 13:03:50 +0900224 Input: manifestJsonFullOut,
Jiyong Park09d77522019-11-18 11:16:27 +0900225 Output: a.manifestPbOut,
226 })
227}
228
Jiyong Park19972c72020-01-28 20:05:29 +0900229func (a *apexBundle) buildNoticeFiles(ctx android.ModuleContext, apexFileName string) android.NoticeOutputs {
Jiyong Park09d77522019-11-18 11:16:27 +0900230 noticeFiles := []android.Path{}
231 for _, f := range a.filesInfo {
232 if f.module != nil {
Bob Badoura75b0572020-02-18 20:21:55 -0800233 notices := f.module.NoticeFiles()
234 if len(notices) > 0 {
235 noticeFiles = append(noticeFiles, notices...)
Jiyong Park09d77522019-11-18 11:16:27 +0900236 }
237 }
238 }
239 // append the notice file specified in the apex module itself
Bob Badoura75b0572020-02-18 20:21:55 -0800240 if len(a.NoticeFiles()) > 0 {
241 noticeFiles = append(noticeFiles, a.NoticeFiles()...)
Jiyong Park09d77522019-11-18 11:16:27 +0900242 }
243
244 if len(noticeFiles) == 0 {
Jiyong Park19972c72020-01-28 20:05:29 +0900245 return android.NoticeOutputs{}
Jiyong Park09d77522019-11-18 11:16:27 +0900246 }
247
Jiyong Park19972c72020-01-28 20:05:29 +0900248 return android.BuildNoticeOutput(ctx, a.installDir, apexFileName, android.FirstUniquePaths(noticeFiles))
Jiyong Park09d77522019-11-18 11:16:27 +0900249}
250
Jiyong Park3a1602e2020-01-14 14:39:19 +0900251func (a *apexBundle) buildInstalledFilesFile(ctx android.ModuleContext, builtApex android.Path, imageDir android.Path) android.OutputPath {
252 output := android.PathForModuleOut(ctx, "installed-files.txt")
253 rule := android.NewRuleBuilder()
254 rule.Command().
255 Implicit(builtApex).
256 Text("(cd " + imageDir.String() + " ; ").
Jiyong Parkbd63a102020-02-08 12:40:05 +0900257 Text("find . \\( -type f -o -type l \\) -printf \"%s %p\\n\") ").
Jiyong Park3a1602e2020-01-14 14:39:19 +0900258 Text(" | sort -nr > ").
259 Output(output)
260 rule.Build(pctx, ctx, "installed-files."+a.Name(), "Installed files")
261 return output.OutputPath
262}
263
Jiyong Parkbd159612020-02-28 15:22:21 +0900264func (a *apexBundle) buildBundleConfig(ctx android.ModuleContext) android.OutputPath {
265 output := android.PathForModuleOut(ctx, "bundle_config.json")
266
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900267 type ApkConfig struct {
268 Package_name string `json:"package_name"`
269 Apk_path string `json:"path"`
270 }
Jiyong Parkbd159612020-02-28 15:22:21 +0900271 config := struct {
272 Compression struct {
273 Uncompressed_glob []string `json:"uncompressed_glob"`
274 } `json:"compression"`
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900275 Apex_config struct {
276 Apex_embedded_apk_config []ApkConfig `json:"apex_embedded_apk_config,omitempty"`
277 } `json:"apex_config,omitempty"`
Jiyong Parkbd159612020-02-28 15:22:21 +0900278 }{}
279
280 config.Compression.Uncompressed_glob = []string{
281 "apex_payload.img",
282 "apex_manifest.*",
283 }
Jiyong Parkcfaa1642020-02-28 16:51:07 +0900284
285 // collect the manifest names and paths of android apps
286 // if their manifest names are overridden
287 for _, fi := range a.filesInfo {
288 if fi.class != app {
289 continue
290 }
291 packageName := fi.overriddenPackageName
292 if packageName != "" {
293 config.Apex_config.Apex_embedded_apk_config = append(
294 config.Apex_config.Apex_embedded_apk_config,
295 ApkConfig{
296 Package_name: packageName,
297 Apk_path: fi.Path(),
298 })
299 }
300 }
301
Jiyong Parkbd159612020-02-28 15:22:21 +0900302 j, err := json.Marshal(config)
303 if err != nil {
304 panic(fmt.Errorf("error while marshalling to %q: %#v", output, err))
305 }
306
307 ctx.Build(pctx, android.BuildParams{
308 Rule: android.WriteFile,
309 Output: output,
310 Description: "Bundle Config " + output.String(),
311 Args: map[string]string{
312 "content": string(j),
313 },
314 })
315
316 return output.OutputPath
317}
318
Jiyong Park09d77522019-11-18 11:16:27 +0900319func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext) {
320 var abis []string
321 for _, target := range ctx.MultiTargets() {
322 if len(target.Arch.Abi) > 0 {
323 abis = append(abis, target.Arch.Abi[0])
324 }
325 }
326
327 abis = android.FirstUniqueStrings(abis)
328
329 apexType := a.properties.ApexType
330 suffix := apexType.suffix()
Jiyong Park7cd10e32020-01-14 09:22:18 +0900331 var implicitInputs []android.Path
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800332 unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
Jiyong Park09d77522019-11-18 11:16:27 +0900333
Jiyong Park7cd10e32020-01-14 09:22:18 +0900334 // TODO(jiyong): construct the copy rules using RuleBuilder
335 var copyCommands []string
336 for _, fi := range a.filesInfo {
337 destPath := android.PathForModuleOut(ctx, "image"+suffix, fi.Path()).String()
338 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(destPath))
339 if a.linkToSystemLib && fi.transitiveDep && fi.AvailableToPlatform() {
340 // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
341 pathOnDevice := filepath.Join("/system", fi.Path())
342 copyCommands = append(copyCommands, "ln -sfn "+pathOnDevice+" "+destPath)
343 } else {
344 copyCommands = append(copyCommands, "cp -f "+fi.builtFile.String()+" "+destPath)
345 implicitInputs = append(implicitInputs, fi.builtFile)
346 }
347 // create additional symlinks pointing the file inside the APEX
348 for _, symlinkPath := range fi.SymlinkPaths() {
349 symlinkDest := android.PathForModuleOut(ctx, "image"+suffix, symlinkPath).String()
350 copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
351 }
Jiyong Park09d77522019-11-18 11:16:27 +0900352 }
353
Jiyong Park7cd10e32020-01-14 09:22:18 +0900354 // TODO(jiyong): use RuleBuilder
355 var emitCommands []string
356 imageContentFile := android.PathForModuleOut(ctx, "content.txt")
Jooyung Han214bf372019-11-12 13:03:50 +0900357 emitCommands = append(emitCommands, "echo ./apex_manifest.pb >> "+imageContentFile.String())
358 if proptools.Bool(a.properties.Legacy_android10_support) {
359 emitCommands = append(emitCommands, "echo ./apex_manifest.json >> "+imageContentFile.String())
360 }
Jiyong Park7cd10e32020-01-14 09:22:18 +0900361 for _, fi := range a.filesInfo {
362 emitCommands = append(emitCommands, "echo './"+fi.Path()+"' >> "+imageContentFile.String())
Jiyong Park09d77522019-11-18 11:16:27 +0900363 }
364 emitCommands = append(emitCommands, "sort -o "+imageContentFile.String()+" "+imageContentFile.String())
Jooyung Han214bf372019-11-12 13:03:50 +0900365 implicitInputs = append(implicitInputs, a.manifestPbOut)
Jiyong Park09d77522019-11-18 11:16:27 +0900366
367 if a.properties.Whitelisted_files != nil {
368 ctx.Build(pctx, android.BuildParams{
369 Rule: emitApexContentRule,
370 Implicits: implicitInputs,
371 Output: imageContentFile,
372 Description: "emit apex image content",
373 Args: map[string]string{
374 "emit_commands": strings.Join(emitCommands, " && "),
375 },
376 })
377 implicitInputs = append(implicitInputs, imageContentFile)
378 whitelistedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.Whitelisted_files))
379
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800380 phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
Jiyong Park09d77522019-11-18 11:16:27 +0900381 ctx.Build(pctx, android.BuildParams{
382 Rule: diffApexContentRule,
383 Implicits: implicitInputs,
384 Output: phonyOutput,
385 Description: "diff apex image content",
386 Args: map[string]string{
387 "whitelisted_files_file": whitelistedFilesFile.String(),
388 "image_content_file": imageContentFile.String(),
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800389 "apex_module_name": a.Name(),
Jiyong Park09d77522019-11-18 11:16:27 +0900390 },
391 })
392
393 implicitInputs = append(implicitInputs, phonyOutput)
394 }
395
396 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
397 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
398
Jiyong Park3a1602e2020-01-14 14:39:19 +0900399 imageDir := android.PathForModuleOut(ctx, "image"+suffix)
Jiyong Park09d77522019-11-18 11:16:27 +0900400 if apexType == imageApex {
401 // files and dirs that will be created in APEX
402 var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
403 var executablePaths []string // this also includes dirs
404 for _, f := range a.filesInfo {
405 pathInApex := filepath.Join(f.installDir, f.builtFile.Base())
406 if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
407 executablePaths = append(executablePaths, pathInApex)
408 for _, s := range f.symlinks {
409 executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
410 }
411 } else {
412 readOnlyPaths = append(readOnlyPaths, pathInApex)
413 }
414 dir := f.installDir
415 for !android.InList(dir, executablePaths) && dir != "" {
416 executablePaths = append(executablePaths, dir)
417 dir, _ = filepath.Split(dir) // move up to the parent
418 if len(dir) > 0 {
419 // remove trailing slash
420 dir = dir[:len(dir)-1]
421 }
422 }
423 }
424 sort.Strings(readOnlyPaths)
425 sort.Strings(executablePaths)
426 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
427 ctx.Build(pctx, android.BuildParams{
428 Rule: generateFsConfig,
429 Output: cannedFsConfig,
430 Description: "generate fs config",
431 Args: map[string]string{
432 "ro_paths": strings.Join(readOnlyPaths, " "),
433 "exec_paths": strings.Join(executablePaths, " "),
434 },
435 })
436
Jiyong Park09d77522019-11-18 11:16:27 +0900437 optFlags := []string{}
438
439 // Additional implicit inputs.
Jooyung Han54aca7b2019-11-20 02:26:02 +0900440 implicitInputs = append(implicitInputs, cannedFsConfig, a.fileContexts, a.private_key_file, a.public_key_file)
Jiyong Park09d77522019-11-18 11:16:27 +0900441 optFlags = append(optFlags, "--pubkey "+a.public_key_file.String())
442
Jooyung Han27151d92019-12-16 17:45:32 +0900443 manifestPackageName := a.getOverrideManifestPackageName(ctx)
444 if manifestPackageName != "" {
Jiyong Park09d77522019-11-18 11:16:27 +0900445 optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
446 }
447
448 if a.properties.AndroidManifest != nil {
449 androidManifestFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.AndroidManifest))
450 implicitInputs = append(implicitInputs, androidManifestFile)
451 optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
452 }
453
454 targetSdkVersion := ctx.Config().DefaultAppTargetSdk()
Baligh Uddinf6201372020-01-24 23:15:44 +0000455 minSdkVersion := ctx.Config().DefaultAppTargetSdk()
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000456
Nikita Ioffe1f4f3452020-03-02 16:58:11 +0000457 // TODO: this should be based on min_sdk_version property of an APEX.
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000458 if proptools.Bool(a.properties.Legacy_android10_support) {
Nikita Ioffe1f4f3452020-03-02 16:58:11 +0000459 targetSdkVersion = "29"
460 minSdkVersion = "29"
Nikita Ioffe5d600c92020-02-20 00:43:27 +0000461 }
462
Nikita Ioffe1f4f3452020-03-02 16:58:11 +0000463 if java.UseApiFingerprint(ctx) {
464 targetSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
Baligh Uddinf6201372020-01-24 23:15:44 +0000465 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
466 }
Nikita Ioffe1f4f3452020-03-02 16:58:11 +0000467 if java.UseApiFingerprint(ctx) {
468 minSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
Baligh Uddinf6201372020-01-24 23:15:44 +0000469 implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
Jiyong Park09d77522019-11-18 11:16:27 +0900470 }
471 optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
Baligh Uddinf6201372020-01-24 23:15:44 +0000472 optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
Jiyong Park09d77522019-11-18 11:16:27 +0900473
Baligh Uddin004d7172020-02-19 21:29:28 -0800474 if a.overridableProperties.Logging_parent != "" {
475 optFlags = append(optFlags, "--logging_parent ", a.overridableProperties.Logging_parent)
476 }
477
Jiyong Park19972c72020-01-28 20:05:29 +0900478 a.mergedNotices = a.buildNoticeFiles(ctx, a.Name()+suffix)
479 if a.mergedNotices.HtmlGzOutput.Valid() {
Jiyong Park09d77522019-11-18 11:16:27 +0900480 // If there's a NOTICE file, embed it as an asset file in the APEX.
Jiyong Park19972c72020-01-28 20:05:29 +0900481 implicitInputs = append(implicitInputs, a.mergedNotices.HtmlGzOutput.Path())
482 optFlags = append(optFlags, "--assets_dir "+filepath.Dir(a.mergedNotices.HtmlGzOutput.String()))
Jiyong Park09d77522019-11-18 11:16:27 +0900483 }
484
Nikita Ioffeb4b44c02020-01-02 23:01:39 +0000485 if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && ctx.ModuleDir() != "system/apex/shim/build" && a.testOnlyShouldSkipHashtreeGeneration() {
Nikita Ioffec72b5dd2019-12-07 17:30:22 +0000486 ctx.PropertyErrorf("test_only_no_hashtree", "not available")
487 return
488 }
Dario Frenie3546902020-01-14 23:50:25 +0000489 if !proptools.Bool(a.properties.Legacy_android10_support) || a.testOnlyShouldSkipHashtreeGeneration() {
Jiyong Park09d77522019-11-18 11:16:27 +0900490 // Apexes which are supposed to be installed in builtin dirs(/system, etc)
491 // don't need hashtree for activation. Therefore, by removing hashtree from
492 // apex bundle (filesystem image in it, to be specific), we can save storage.
493 optFlags = append(optFlags, "--no_hashtree")
494 }
495
496 if a.properties.Apex_name != nil {
497 // If apex_name is set, apexer can skip checking if key name matches with apex name.
498 // Note that apex_manifest is also mended.
499 optFlags = append(optFlags, "--do_not_check_keyname")
500 }
501
Jooyung Han214bf372019-11-12 13:03:50 +0900502 if proptools.Bool(a.properties.Legacy_android10_support) {
503 implicitInputs = append(implicitInputs, a.manifestJsonOut)
504 optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
505 }
506
Jiyong Park09d77522019-11-18 11:16:27 +0900507 ctx.Build(pctx, android.BuildParams{
508 Rule: apexRule,
509 Implicits: implicitInputs,
510 Output: unsignedOutputFile,
511 Description: "apex (" + apexType.name() + ")",
512 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900513 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900514 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900515 "copy_commands": strings.Join(copyCommands, " && "),
516 "manifest": a.manifestPbOut.String(),
517 "file_contexts": a.fileContexts.String(),
518 "canned_fs_config": cannedFsConfig.String(),
519 "key": a.private_key_file.String(),
520 "opt_flags": strings.Join(optFlags, " "),
Jiyong Park09d77522019-11-18 11:16:27 +0900521 },
522 })
523
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800524 apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
525 bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
Jiyong Park09d77522019-11-18 11:16:27 +0900526 a.bundleModuleFile = bundleModuleFile
527
528 ctx.Build(pctx, android.BuildParams{
529 Rule: apexProtoConvertRule,
530 Input: unsignedOutputFile,
531 Output: apexProtoFile,
532 Description: "apex proto convert",
533 })
534
Jiyong Parkbd159612020-02-28 15:22:21 +0900535 bundleConfig := a.buildBundleConfig(ctx)
536
Jiyong Park09d77522019-11-18 11:16:27 +0900537 ctx.Build(pctx, android.BuildParams{
538 Rule: apexBundleRule,
539 Input: apexProtoFile,
Jiyong Parkbd159612020-02-28 15:22:21 +0900540 Implicit: bundleConfig,
Jiyong Park09d77522019-11-18 11:16:27 +0900541 Output: a.bundleModuleFile,
542 Description: "apex bundle module",
543 Args: map[string]string{
Jiyong Parkbd159612020-02-28 15:22:21 +0900544 "abi": strings.Join(abis, "."),
545 "config": bundleConfig.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900546 },
547 })
548 } else {
549 ctx.Build(pctx, android.BuildParams{
550 Rule: zipApexRule,
551 Implicits: implicitInputs,
552 Output: unsignedOutputFile,
553 Description: "apex (" + apexType.name() + ")",
554 Args: map[string]string{
Jooyung Han214bf372019-11-12 13:03:50 +0900555 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
Jiyong Park3a1602e2020-01-14 14:39:19 +0900556 "image_dir": imageDir.String(),
Jooyung Han214bf372019-11-12 13:03:50 +0900557 "copy_commands": strings.Join(copyCommands, " && "),
558 "manifest": a.manifestPbOut.String(),
Jiyong Park09d77522019-11-18 11:16:27 +0900559 },
560 })
561 }
562
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800563 a.outputFile = android.PathForModuleOut(ctx, a.Name()+suffix)
Jiyong Park09d77522019-11-18 11:16:27 +0900564 ctx.Build(pctx, android.BuildParams{
565 Rule: java.Signapk,
566 Description: "signapk",
567 Output: a.outputFile,
568 Input: unsignedOutputFile,
569 Implicits: []android.Path{
570 a.container_certificate_file,
571 a.container_private_key_file,
572 },
573 Args: map[string]string{
574 "certificates": a.container_certificate_file.String() + " " + a.container_private_key_file.String(),
575 "flags": "-a 4096", //alignment
576 },
577 })
578
579 // Install to $OUT/soong/{target,host}/.../apex
580 if a.installable() {
Jaewoong Jung1670ca02019-11-22 14:50:42 -0800581 ctx.InstallFile(a.installDir, a.Name()+suffix, a.outputFile)
Jiyong Park09d77522019-11-18 11:16:27 +0900582 }
583 a.buildFilesInfo(ctx)
Jiyong Park3a1602e2020-01-14 14:39:19 +0900584
585 // installed-files.txt is dist'ed
586 a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900587}
588
589func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
590 // Temporarily wrap the original `ctx` into a `flattenedApexContext` to have it
591 // reply true to `InstallBypassMake()` (thus making the call
592 // `android.PathForModuleInstall` below use `android.pathForInstallInMakeDir`
593 // instead of `android.PathForOutput`) to return the correct path to the flattened
594 // APEX (as its contents is installed by Make, not Soong).
595 factx := flattenedApexContext{ctx}
Jiyong Parka5948012020-02-07 10:15:14 +0900596 apexBundleName := a.Name()
597 a.outputFile = android.PathForModuleInstall(&factx, "apex", apexBundleName)
Jiyong Park09d77522019-11-18 11:16:27 +0900598
Jiyong Park317645e2019-12-05 13:20:58 +0900599 if a.installable() && a.GetOverriddenBy() == "" {
Jiyong Parka5948012020-02-07 10:15:14 +0900600 installPath := android.PathForModuleInstall(ctx, "apex", apexBundleName)
Jooyung Han54aca7b2019-11-20 02:26:02 +0900601 devicePath := android.InstallPathToOnDevicePath(ctx, installPath)
Jiyong Parka5948012020-02-07 10:15:14 +0900602 addFlattenedFileContextsInfos(ctx, apexBundleName+":"+devicePath+":"+a.fileContexts.String())
Jooyung Han54aca7b2019-11-20 02:26:02 +0900603 }
Jiyong Park09d77522019-11-18 11:16:27 +0900604 a.buildFilesInfo(ctx)
605}
606
607func (a *apexBundle) setCertificateAndPrivateKey(ctx android.ModuleContext) {
Jooyung Hanf121a652019-12-17 14:30:11 +0900608 if a.container_certificate_file == nil {
609 cert := String(a.properties.Certificate)
610 if cert == "" {
611 pem, key := ctx.Config().DefaultAppCertificate(ctx)
612 a.container_certificate_file = pem
613 a.container_private_key_file = key
614 } else {
615 defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
616 a.container_certificate_file = defaultDir.Join(ctx, cert+".x509.pem")
617 a.container_private_key_file = defaultDir.Join(ctx, cert+".pk8")
618 }
Jiyong Park09d77522019-11-18 11:16:27 +0900619 }
620}
621
622func (a *apexBundle) buildFilesInfo(ctx android.ModuleContext) {
623 if a.installable() {
Jooyung Han214bf372019-11-12 13:03:50 +0900624 // 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 +0900625 // with other ordinary files.
Jiyong Park7cd10e32020-01-14 09:22:18 +0900626 a.filesInfo = append(a.filesInfo, newApexFile(ctx, a.manifestPbOut, "apex_manifest.pb", ".", etc, nil))
Jiyong Park09d77522019-11-18 11:16:27 +0900627
628 // rename to apex_pubkey
629 copiedPubkey := android.PathForModuleOut(ctx, "apex_pubkey")
630 ctx.Build(pctx, android.BuildParams{
631 Rule: android.Cp,
632 Input: a.public_key_file,
633 Output: copiedPubkey,
634 })
Jiyong Park7cd10e32020-01-14 09:22:18 +0900635 a.filesInfo = append(a.filesInfo, newApexFile(ctx, copiedPubkey, "apex_pubkey", ".", etc, nil))
Jiyong Park09d77522019-11-18 11:16:27 +0900636
637 if a.properties.ApexType == flattenedApex {
Jiyong Parka5948012020-02-07 10:15:14 +0900638 apexBundleName := a.Name()
Jiyong Park09d77522019-11-18 11:16:27 +0900639 for _, fi := range a.filesInfo {
Jiyong Parka5948012020-02-07 10:15:14 +0900640 dir := filepath.Join("apex", apexBundleName, fi.installDir)
Jiyong Park09d77522019-11-18 11:16:27 +0900641 target := ctx.InstallFile(android.PathForModuleInstall(ctx, dir), fi.builtFile.Base(), fi.builtFile)
642 for _, sym := range fi.symlinks {
643 ctx.InstallSymlink(android.PathForModuleInstall(ctx, dir), sym, target)
644 }
645 }
646 }
647 }
648}
Jooyung Han27151d92019-12-16 17:45:32 +0900649
650func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
651 // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
652 // to see if it should be overridden because their <apex name> is dynamically generated
653 // according to its VNDK version.
654 if a.vndkApex {
655 overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
656 if overridden {
657 return strings.Replace(*a.properties.Apex_name, vndkApexName, overrideName, 1)
658 }
659 return ""
660 }
Jiyong Park20bacab2020-03-03 11:45:41 +0900661 manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
Jooyung Han27151d92019-12-16 17:45:32 +0900662 if overridden {
663 return manifestPackageName
664 }
665 return ""
666}
Jiyong Park83dc74b2020-01-14 18:38:44 +0900667
668func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
669 if !a.primaryApexType {
670 return
671 }
672
673 if a.properties.IsCoverageVariant {
674 // Otherwise, we will have duplicated rules for coverage and
675 // non-coverage variants of the same APEX
676 return
677 }
678
679 if ctx.Host() {
680 // No need to generate dependency info for host variant
681 return
682 }
683
Jiyong Park83dc74b2020-01-14 18:38:44 +0900684 var content strings.Builder
Jiyong Park678c8812020-02-07 17:25:49 +0900685 for _, key := range android.SortedStringKeys(a.depInfos) {
686 info := a.depInfos[key]
687 toName := info.to
688 if info.isExternal {
689 toName = toName + " (external)"
690 }
691 fmt.Fprintf(&content, "%s <- %s\\n", toName, strings.Join(android.SortedUniqueStrings(info.from), ", "))
Jiyong Park83dc74b2020-01-14 18:38:44 +0900692 }
693
694 depsInfoFile := android.PathForOutput(ctx, a.Name()+"-deps-info.txt")
695 ctx.Build(pctx, android.BuildParams{
696 Rule: android.WriteFile,
697 Description: "Dependency Info",
698 Output: depsInfoFile,
699 Args: map[string]string{
700 "content": content.String(),
701 },
702 })
703
704 ctx.Build(pctx, android.BuildParams{
705 Rule: android.Phony,
706 Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
707 Inputs: []android.Path{depsInfoFile},
708 })
709}