builder.go 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  1. // 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. package apex
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "path/filepath"
  19. "runtime"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "android/soong/android"
  24. "android/soong/java"
  25. "github.com/google/blueprint"
  26. "github.com/google/blueprint/proptools"
  27. )
  28. var (
  29. pctx = android.NewPackageContext("android/apex")
  30. )
  31. func init() {
  32. pctx.Import("android/soong/android")
  33. pctx.Import("android/soong/cc/config")
  34. pctx.Import("android/soong/java")
  35. pctx.HostBinToolVariable("apexer", "apexer")
  36. // ART minimal builds (using the master-art manifest) do not have the "frameworks/base"
  37. // projects, and hence cannot build 'aapt2'. Use the SDK prebuilt instead.
  38. hostBinToolVariableWithPrebuilt := func(name, prebuiltDir, tool string) {
  39. pctx.VariableFunc(name, func(ctx android.PackageVarContext) string {
  40. if !ctx.Config().FrameworksBaseDirExists(ctx) {
  41. return filepath.Join(prebuiltDir, runtime.GOOS, "bin", tool)
  42. } else {
  43. return ctx.Config().HostToolPath(ctx, tool).String()
  44. }
  45. })
  46. }
  47. hostBinToolVariableWithPrebuilt("aapt2", "prebuilts/sdk/tools", "aapt2")
  48. pctx.HostBinToolVariable("avbtool", "avbtool")
  49. pctx.HostBinToolVariable("e2fsdroid", "e2fsdroid")
  50. pctx.HostBinToolVariable("merge_zips", "merge_zips")
  51. pctx.HostBinToolVariable("mke2fs", "mke2fs")
  52. pctx.HostBinToolVariable("resize2fs", "resize2fs")
  53. pctx.HostBinToolVariable("sefcontext_compile", "sefcontext_compile")
  54. pctx.HostBinToolVariable("soong_zip", "soong_zip")
  55. pctx.HostBinToolVariable("zip2zip", "zip2zip")
  56. pctx.HostBinToolVariable("zipalign", "zipalign")
  57. pctx.HostBinToolVariable("jsonmodify", "jsonmodify")
  58. pctx.HostBinToolVariable("conv_apex_manifest", "conv_apex_manifest")
  59. pctx.HostBinToolVariable("extract_apks", "extract_apks")
  60. pctx.HostBinToolVariable("make_f2fs", "make_f2fs")
  61. pctx.HostBinToolVariable("sload_f2fs", "sload_f2fs")
  62. pctx.HostBinToolVariable("make_erofs", "make_erofs")
  63. pctx.HostBinToolVariable("apex_compression_tool", "apex_compression_tool")
  64. pctx.HostBinToolVariable("dexdeps", "dexdeps")
  65. pctx.SourcePathVariable("genNdkUsedbyApexPath", "build/soong/scripts/gen_ndk_usedby_apex.sh")
  66. }
  67. var (
  68. apexManifestRule = pctx.StaticRule("apexManifestRule", blueprint.RuleParams{
  69. Command: `rm -f $out && ${jsonmodify} $in ` +
  70. `-a provideNativeLibs ${provideNativeLibs} ` +
  71. `-a requireNativeLibs ${requireNativeLibs} ` +
  72. `-se version 0 ${default_version} ` +
  73. `${opt} ` +
  74. `-o $out`,
  75. CommandDeps: []string{"${jsonmodify}"},
  76. Description: "prepare ${out}",
  77. }, "provideNativeLibs", "requireNativeLibs", "default_version", "opt")
  78. stripCommentsApexManifestRule = pctx.StaticRule("stripCommentsApexManifestRule", blueprint.RuleParams{
  79. Command: `sed '/^\s*\/\//d' $in > $out`,
  80. Description: "strip lines starting with // ${in}=>${out}",
  81. })
  82. stripApexManifestRule = pctx.StaticRule("stripApexManifestRule", blueprint.RuleParams{
  83. Command: `rm -f $out && ${conv_apex_manifest} strip $in -o $out`,
  84. CommandDeps: []string{"${conv_apex_manifest}"},
  85. Description: "strip ${in}=>${out}",
  86. })
  87. pbApexManifestRule = pctx.StaticRule("pbApexManifestRule", blueprint.RuleParams{
  88. Command: `rm -f $out && ${conv_apex_manifest} proto $in -o $out`,
  89. CommandDeps: []string{"${conv_apex_manifest}"},
  90. Description: "convert ${in}=>${out}",
  91. })
  92. // TODO(b/113233103): make sure that file_contexts is as expected, i.e., validate
  93. // against the binary policy using sefcontext_compiler -p <policy>.
  94. // TODO(b/114327326): automate the generation of file_contexts
  95. apexRule = pctx.StaticRule("apexRule", blueprint.RuleParams{
  96. Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
  97. `(. ${out}.copy_commands) && ` +
  98. `APEXER_TOOL_PATH=${tool_path} ` +
  99. `${apexer} --force --manifest ${manifest} ` +
  100. `--file_contexts ${file_contexts} ` +
  101. `--canned_fs_config ${canned_fs_config} ` +
  102. `--include_build_info ` +
  103. `--payload_type image ` +
  104. `--apex_version ${apex_version} ` +
  105. `--key ${key} ${opt_flags} ${image_dir} ${out} `,
  106. CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
  107. "${mke2fs}", "${resize2fs}", "${sefcontext_compile}", "${make_f2fs}", "${sload_f2fs}", "${make_erofs}",
  108. "${soong_zip}", "${zipalign}", "${aapt2}", "prebuilts/sdk/current/public/android.jar"},
  109. Rspfile: "${out}.copy_commands",
  110. RspfileContent: "${copy_commands}",
  111. Description: "APEX ${image_dir} => ${out}",
  112. }, "tool_path", "image_dir", "copy_commands", "file_contexts", "canned_fs_config", "key", "opt_flags", "manifest", "payload_fs_type", "apex_version")
  113. zipApexRule = pctx.StaticRule("zipApexRule", blueprint.RuleParams{
  114. Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
  115. `(. ${out}.copy_commands) && ` +
  116. `APEXER_TOOL_PATH=${tool_path} ` +
  117. `${apexer} --force --manifest ${manifest} ` +
  118. `--payload_type zip ` +
  119. `--apex_version ${apex_version} ` +
  120. `${image_dir} ${out} `,
  121. CommandDeps: []string{"${apexer}", "${merge_zips}", "${soong_zip}", "${zipalign}", "${aapt2}"},
  122. Rspfile: "${out}.copy_commands",
  123. RspfileContent: "${copy_commands}",
  124. Description: "ZipAPEX ${image_dir} => ${out}",
  125. }, "tool_path", "image_dir", "copy_commands", "manifest", "apex_version")
  126. apexProtoConvertRule = pctx.AndroidStaticRule("apexProtoConvertRule",
  127. blueprint.RuleParams{
  128. Command: `${aapt2} convert --output-format proto $in -o $out`,
  129. CommandDeps: []string{"${aapt2}"},
  130. })
  131. apexBundleRule = pctx.StaticRule("apexBundleRule", blueprint.RuleParams{
  132. Command: `${zip2zip} -i $in -o $out.base ` +
  133. `apex_payload.img:apex/${abi}.img ` +
  134. `apex_build_info.pb:apex/${abi}.build_info.pb ` +
  135. `apex_manifest.json:root/apex_manifest.json ` +
  136. `apex_manifest.pb:root/apex_manifest.pb ` +
  137. `AndroidManifest.xml:manifest/AndroidManifest.xml ` +
  138. `assets/NOTICE.html.gz:assets/NOTICE.html.gz &&` +
  139. `${soong_zip} -o $out.config -C $$(dirname ${config}) -f ${config} && ` +
  140. `${merge_zips} $out $out.base $out.config`,
  141. CommandDeps: []string{"${zip2zip}", "${soong_zip}", "${merge_zips}"},
  142. Description: "app bundle",
  143. }, "abi", "config")
  144. emitApexContentRule = pctx.StaticRule("emitApexContentRule", blueprint.RuleParams{
  145. Command: `rm -f ${out} && touch ${out} && (. ${out}.emit_commands)`,
  146. Rspfile: "${out}.emit_commands",
  147. RspfileContent: "${emit_commands}",
  148. Description: "Emit APEX image content",
  149. }, "emit_commands")
  150. diffApexContentRule = pctx.StaticRule("diffApexContentRule", blueprint.RuleParams{
  151. Command: `diff --unchanged-group-format='' \` +
  152. `--changed-group-format='%<' \` +
  153. `${image_content_file} ${allowed_files_file} || (` +
  154. `echo -e "New unexpected files were added to ${apex_module_name}." ` +
  155. ` "To fix the build run following command:" && ` +
  156. `echo "system/apex/tools/update_allowed_list.sh ${allowed_files_file} ${image_content_file}" && ` +
  157. `exit 1); touch ${out}`,
  158. Description: "Diff ${image_content_file} and ${allowed_files_file}",
  159. }, "image_content_file", "allowed_files_file", "apex_module_name")
  160. generateAPIsUsedbyApexRule = pctx.StaticRule("generateAPIsUsedbyApexRule", blueprint.RuleParams{
  161. Command: "$genNdkUsedbyApexPath ${image_dir} ${readelf} ${out}",
  162. CommandDeps: []string{"${genNdkUsedbyApexPath}"},
  163. Description: "Generate symbol list used by Apex",
  164. }, "image_dir", "readelf")
  165. // Don't add more rules here. Consider using android.NewRuleBuilder instead.
  166. )
  167. // buildManifest creates buile rules to modify the input apex_manifest.json to add information
  168. // gathered by the build system such as provided/required native libraries. Two output files having
  169. // different formats are generated. a.manifestJsonOut is JSON format for Q devices, and
  170. // a.manifest.PbOut is protobuf format for R+ devices.
  171. // TODO(jiyong): make this to return paths instead of directly storing the paths to apexBundle
  172. func (a *apexBundle) buildManifest(ctx android.ModuleContext, provideNativeLibs, requireNativeLibs []string) {
  173. src := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
  174. // Put dependency({provide|require}NativeLibs) in apex_manifest.json
  175. provideNativeLibs = android.SortedUniqueStrings(provideNativeLibs)
  176. requireNativeLibs = android.SortedUniqueStrings(android.RemoveListFromList(requireNativeLibs, provideNativeLibs))
  177. // APEX name can be overridden
  178. optCommands := []string{}
  179. if a.properties.Apex_name != nil {
  180. optCommands = append(optCommands, "-v name "+*a.properties.Apex_name)
  181. }
  182. // Collect jniLibs. Notice that a.filesInfo is already sorted
  183. var jniLibs []string
  184. for _, fi := range a.filesInfo {
  185. if fi.isJniLib && !android.InList(fi.stem(), jniLibs) {
  186. jniLibs = append(jniLibs, fi.stem())
  187. }
  188. }
  189. if len(jniLibs) > 0 {
  190. optCommands = append(optCommands, "-a jniLibs "+strings.Join(jniLibs, " "))
  191. }
  192. manifestJsonCommentsStripped := android.PathForModuleOut(ctx, "apex_manifest_comments_stripped.json")
  193. ctx.Build(pctx, android.BuildParams{
  194. Rule: stripCommentsApexManifestRule,
  195. Input: src,
  196. Output: manifestJsonCommentsStripped,
  197. })
  198. manifestJsonFullOut := android.PathForModuleOut(ctx, "apex_manifest_full.json")
  199. ctx.Build(pctx, android.BuildParams{
  200. Rule: apexManifestRule,
  201. Input: manifestJsonCommentsStripped,
  202. Output: manifestJsonFullOut,
  203. Args: map[string]string{
  204. "provideNativeLibs": strings.Join(provideNativeLibs, " "),
  205. "requireNativeLibs": strings.Join(requireNativeLibs, " "),
  206. "default_version": defaultManifestVersion,
  207. "opt": strings.Join(optCommands, " "),
  208. },
  209. })
  210. // b/143654022 Q apexd can't understand newly added keys in apex_manifest.json prepare
  211. // stripped-down version so that APEX modules built from R+ can be installed to Q
  212. minSdkVersion := a.minSdkVersion(ctx)
  213. if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
  214. a.manifestJsonOut = android.PathForModuleOut(ctx, "apex_manifest.json")
  215. ctx.Build(pctx, android.BuildParams{
  216. Rule: stripApexManifestRule,
  217. Input: manifestJsonFullOut,
  218. Output: a.manifestJsonOut,
  219. })
  220. }
  221. // From R+, protobuf binary format (.pb) is the standard format for apex_manifest
  222. a.manifestPbOut = android.PathForModuleOut(ctx, "apex_manifest.pb")
  223. ctx.Build(pctx, android.BuildParams{
  224. Rule: pbApexManifestRule,
  225. Input: manifestJsonFullOut,
  226. Output: a.manifestPbOut,
  227. })
  228. }
  229. // buildFileContexts create build rules to append an entry for apex_manifest.pb to the file_contexts
  230. // file for this APEX which is either from /systme/sepolicy/apex/<apexname>-file_contexts or from
  231. // the file_contexts property of this APEX. This is to make sure that the manifest file is correctly
  232. // labeled as system_file.
  233. func (a *apexBundle) buildFileContexts(ctx android.ModuleContext) android.OutputPath {
  234. var fileContexts android.Path
  235. var fileContextsDir string
  236. if a.properties.File_contexts == nil {
  237. fileContexts = android.PathForSource(ctx, "system/sepolicy/apex", ctx.ModuleName()+"-file_contexts")
  238. } else {
  239. if m, t := android.SrcIsModuleWithTag(*a.properties.File_contexts); m != "" {
  240. otherModule := android.GetModuleFromPathDep(ctx, m, t)
  241. fileContextsDir = ctx.OtherModuleDir(otherModule)
  242. }
  243. fileContexts = android.PathForModuleSrc(ctx, *a.properties.File_contexts)
  244. }
  245. if fileContextsDir == "" {
  246. fileContextsDir = filepath.Dir(fileContexts.String())
  247. }
  248. fileContextsDir += string(filepath.Separator)
  249. if a.Platform() {
  250. if !strings.HasPrefix(fileContextsDir, "system/sepolicy/") {
  251. ctx.PropertyErrorf("file_contexts", "should be under system/sepolicy, but found in %q", fileContextsDir)
  252. }
  253. }
  254. if !android.ExistentPathForSource(ctx, fileContexts.String()).Valid() {
  255. ctx.PropertyErrorf("file_contexts", "cannot find file_contexts file: %q", fileContexts.String())
  256. }
  257. output := android.PathForModuleOut(ctx, "file_contexts")
  258. rule := android.NewRuleBuilder(pctx, ctx)
  259. switch a.properties.ApexType {
  260. case imageApex:
  261. // remove old file
  262. rule.Command().Text("rm").FlagWithOutput("-f ", output)
  263. // copy file_contexts
  264. rule.Command().Text("cat").Input(fileContexts).Text(">>").Output(output)
  265. // new line
  266. rule.Command().Text("echo").Text(">>").Output(output)
  267. // force-label /apex_manifest.pb and / as system_file so that apexd can read them
  268. rule.Command().Text("echo").Flag("/apex_manifest\\\\.pb u:object_r:system_file:s0").Text(">>").Output(output)
  269. rule.Command().Text("echo").Flag("/ u:object_r:system_file:s0").Text(">>").Output(output)
  270. case flattenedApex:
  271. // For flattened apexes, install path should be prepended.
  272. // File_contexts file should be emiited to make via LOCAL_FILE_CONTEXTS
  273. // so that it can be merged into file_contexts.bin
  274. apexPath := android.InstallPathToOnDevicePath(ctx, a.installDir.Join(ctx, a.Name()))
  275. apexPath = strings.ReplaceAll(apexPath, ".", `\\.`)
  276. // remove old file
  277. rule.Command().Text("rm").FlagWithOutput("-f ", output)
  278. // copy file_contexts
  279. rule.Command().Text("awk").Text(`'/object_r/{printf("` + apexPath + `%s\n", $0)}'`).Input(fileContexts).Text(">").Output(output)
  280. // new line
  281. rule.Command().Text("echo").Text(">>").Output(output)
  282. // force-label /apex_manifest.pb and / as system_file so that apexd can read them
  283. rule.Command().Text("echo").Flag(apexPath + `/apex_manifest\\.pb u:object_r:system_file:s0`).Text(">>").Output(output)
  284. rule.Command().Text("echo").Flag(apexPath + "/ u:object_r:system_file:s0").Text(">>").Output(output)
  285. default:
  286. panic(fmt.Errorf("unsupported type %v", a.properties.ApexType))
  287. }
  288. rule.Build("file_contexts."+a.Name(), "Generate file_contexts")
  289. return output.OutputPath
  290. }
  291. // buildInstalledFilesFile creates a build rule for the installed-files.txt file where the list of
  292. // files included in this APEX is shown. The text file is dist'ed so that people can see what's
  293. // included in the APEX without actually downloading and extracting it.
  294. func (a *apexBundle) buildInstalledFilesFile(ctx android.ModuleContext, builtApex android.Path, imageDir android.Path) android.OutputPath {
  295. output := android.PathForModuleOut(ctx, "installed-files.txt")
  296. rule := android.NewRuleBuilder(pctx, ctx)
  297. rule.Command().
  298. Implicit(builtApex).
  299. Text("(cd " + imageDir.String() + " ; ").
  300. Text("find . \\( -type f -o -type l \\) -printf \"%s %p\\n\") ").
  301. Text(" | sort -nr > ").
  302. Output(output)
  303. rule.Build("installed-files."+a.Name(), "Installed files")
  304. return output.OutputPath
  305. }
  306. // buildBundleConfig creates a build rule for the bundle config file that will control the bundle
  307. // creation process.
  308. func (a *apexBundle) buildBundleConfig(ctx android.ModuleContext) android.OutputPath {
  309. output := android.PathForModuleOut(ctx, "bundle_config.json")
  310. type ApkConfig struct {
  311. Package_name string `json:"package_name"`
  312. Apk_path string `json:"path"`
  313. }
  314. config := struct {
  315. Compression struct {
  316. Uncompressed_glob []string `json:"uncompressed_glob"`
  317. } `json:"compression"`
  318. Apex_config struct {
  319. Apex_embedded_apk_config []ApkConfig `json:"apex_embedded_apk_config,omitempty"`
  320. } `json:"apex_config,omitempty"`
  321. }{}
  322. config.Compression.Uncompressed_glob = []string{
  323. "apex_payload.img",
  324. "apex_manifest.*",
  325. }
  326. // Collect the manifest names and paths of android apps if their manifest names are
  327. // overridden.
  328. for _, fi := range a.filesInfo {
  329. if fi.class != app && fi.class != appSet {
  330. continue
  331. }
  332. packageName := fi.overriddenPackageName
  333. if packageName != "" {
  334. config.Apex_config.Apex_embedded_apk_config = append(
  335. config.Apex_config.Apex_embedded_apk_config,
  336. ApkConfig{
  337. Package_name: packageName,
  338. Apk_path: fi.path(),
  339. })
  340. }
  341. }
  342. j, err := json.Marshal(config)
  343. if err != nil {
  344. panic(fmt.Errorf("error while marshalling to %q: %#v", output, err))
  345. }
  346. android.WriteFileRule(ctx, output, string(j))
  347. return output.OutputPath
  348. }
  349. func markManifestTestOnly(ctx android.ModuleContext, androidManifestFile android.Path) android.Path {
  350. return java.ManifestFixer(ctx, androidManifestFile, java.ManifestFixerParams{
  351. TestOnly: true,
  352. })
  353. }
  354. // buildUnflattendApex creates build rules to build an APEX using apexer.
  355. func (a *apexBundle) buildUnflattenedApex(ctx android.ModuleContext) {
  356. apexType := a.properties.ApexType
  357. suffix := apexType.suffix()
  358. apexName := proptools.StringDefault(a.properties.Apex_name, a.BaseModuleName())
  359. ////////////////////////////////////////////////////////////////////////////////////////////
  360. // Step 1: copy built files to appropriate directories under the image directory
  361. imageDir := android.PathForModuleOut(ctx, "image"+suffix)
  362. installSymbolFiles := (!ctx.Config().KatiEnabled() || a.ExportedToMake()) && a.installable()
  363. // b/140136207. When there are overriding APEXes for a VNDK APEX, the symbols file for the overridden
  364. // APEX and the overriding APEX will have the same installation paths at /apex/com.android.vndk.v<ver>
  365. // as their apexName will be the same. To avoid the path conflicts, skip installing the symbol files
  366. // for the overriding VNDK APEXes.
  367. if a.vndkApex && len(a.overridableProperties.Overrides) > 0 {
  368. installSymbolFiles = false
  369. }
  370. // Avoid creating duplicate build rules for multi-installed APEXes.
  371. if proptools.BoolDefault(a.properties.Multi_install_skip_symbol_files, false) {
  372. installSymbolFiles = false
  373. }
  374. // set of dependency module:location mappings
  375. installMapSet := make(map[string]bool)
  376. // TODO(jiyong): use the RuleBuilder
  377. var copyCommands []string
  378. var implicitInputs []android.Path
  379. pathWhenActivated := android.PathForModuleInPartitionInstall(ctx, "apex", apexName)
  380. for _, fi := range a.filesInfo {
  381. destPath := imageDir.Join(ctx, fi.path()).String()
  382. // Prepare the destination path
  383. destPathDir := filepath.Dir(destPath)
  384. if fi.class == appSet {
  385. copyCommands = append(copyCommands, "rm -rf "+destPathDir)
  386. }
  387. copyCommands = append(copyCommands, "mkdir -p "+destPathDir)
  388. installMapPath := fi.builtFile
  389. // Copy the built file to the directory. But if the symlink optimization is turned
  390. // on, place a symlink to the corresponding file in /system partition instead.
  391. if a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform() {
  392. // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
  393. pathOnDevice := filepath.Join("/system", fi.path())
  394. copyCommands = append(copyCommands, "ln -sfn "+pathOnDevice+" "+destPath)
  395. } else {
  396. var installedPath android.InstallPath
  397. if fi.class == appSet {
  398. copyCommands = append(copyCommands,
  399. fmt.Sprintf("unzip -qDD -d %s %s", destPathDir,
  400. fi.module.(*java.AndroidAppSet).PackedAdditionalOutputs().String()))
  401. if installSymbolFiles {
  402. installedPath = ctx.InstallFileWithExtraFilesZip(pathWhenActivated.Join(ctx, fi.installDir),
  403. fi.stem(), fi.builtFile, fi.module.(*java.AndroidAppSet).PackedAdditionalOutputs())
  404. }
  405. } else {
  406. copyCommands = append(copyCommands, "cp -f "+fi.builtFile.String()+" "+destPath)
  407. if installSymbolFiles {
  408. installedPath = ctx.InstallFile(pathWhenActivated.Join(ctx, fi.installDir), fi.stem(), fi.builtFile)
  409. }
  410. }
  411. implicitInputs = append(implicitInputs, fi.builtFile)
  412. if installSymbolFiles {
  413. implicitInputs = append(implicitInputs, installedPath)
  414. }
  415. // Create additional symlinks pointing the file inside the APEX (if any). Note that
  416. // this is independent from the symlink optimization.
  417. for _, symlinkPath := range fi.symlinkPaths() {
  418. symlinkDest := imageDir.Join(ctx, symlinkPath).String()
  419. copyCommands = append(copyCommands, "ln -sfn "+filepath.Base(destPath)+" "+symlinkDest)
  420. if installSymbolFiles {
  421. installedSymlink := ctx.InstallSymlink(pathWhenActivated.Join(ctx, filepath.Dir(symlinkPath)), filepath.Base(symlinkPath), installedPath)
  422. implicitInputs = append(implicitInputs, installedSymlink)
  423. }
  424. }
  425. installMapPath = installedPath
  426. }
  427. // Copy the test files (if any)
  428. for _, d := range fi.dataPaths {
  429. // TODO(eakammer): This is now the third repetition of ~this logic for test paths, refactoring should be possible
  430. relPath := d.SrcPath.Rel()
  431. dataPath := d.SrcPath.String()
  432. if !strings.HasSuffix(dataPath, relPath) {
  433. panic(fmt.Errorf("path %q does not end with %q", dataPath, relPath))
  434. }
  435. dataDest := imageDir.Join(ctx, fi.apexRelativePath(relPath), d.RelativeInstallPath).String()
  436. copyCommands = append(copyCommands, "cp -f "+d.SrcPath.String()+" "+dataDest)
  437. implicitInputs = append(implicitInputs, d.SrcPath)
  438. }
  439. installMapSet[installMapPath.String()+":"+fi.installDir+"/"+fi.builtFile.Base()] = true
  440. }
  441. implicitInputs = append(implicitInputs, a.manifestPbOut)
  442. if installSymbolFiles {
  443. installedManifest := ctx.InstallFile(pathWhenActivated, "apex_manifest.pb", a.manifestPbOut)
  444. installedKey := ctx.InstallFile(pathWhenActivated, "apex_pubkey", a.publicKeyFile)
  445. implicitInputs = append(implicitInputs, installedManifest, installedKey)
  446. }
  447. if len(installMapSet) > 0 {
  448. var installs []string
  449. installs = append(installs, android.SortedStringKeys(installMapSet)...)
  450. a.SetLicenseInstallMap(installs)
  451. }
  452. ////////////////////////////////////////////////////////////////////////////////////////////
  453. // Step 1.a: Write the list of files in this APEX to a txt file and compare it against
  454. // the allowed list given via the allowed_files property. Build fails when the two lists
  455. // differ.
  456. //
  457. // TODO(jiyong): consider removing this. Nobody other than com.android.apex.cts.shim.* seems
  458. // to be using this at this moment. Furthermore, this looks very similar to what
  459. // buildInstalledFilesFile does. At least, move this to somewhere else so that this doesn't
  460. // hurt readability.
  461. // TODO(jiyong): use RuleBuilder
  462. if a.overridableProperties.Allowed_files != nil {
  463. // Build content.txt
  464. var emitCommands []string
  465. imageContentFile := android.PathForModuleOut(ctx, "content.txt")
  466. emitCommands = append(emitCommands, "echo ./apex_manifest.pb >> "+imageContentFile.String())
  467. minSdkVersion := a.minSdkVersion(ctx)
  468. if minSdkVersion.EqualTo(android.SdkVersion_Android10) {
  469. emitCommands = append(emitCommands, "echo ./apex_manifest.json >> "+imageContentFile.String())
  470. }
  471. for _, fi := range a.filesInfo {
  472. emitCommands = append(emitCommands, "echo './"+fi.path()+"' >> "+imageContentFile.String())
  473. }
  474. emitCommands = append(emitCommands, "sort -o "+imageContentFile.String()+" "+imageContentFile.String())
  475. ctx.Build(pctx, android.BuildParams{
  476. Rule: emitApexContentRule,
  477. Implicits: implicitInputs,
  478. Output: imageContentFile,
  479. Description: "emit apex image content",
  480. Args: map[string]string{
  481. "emit_commands": strings.Join(emitCommands, " && "),
  482. },
  483. })
  484. implicitInputs = append(implicitInputs, imageContentFile)
  485. // Compare content.txt against allowed_files.
  486. allowedFilesFile := android.PathForModuleSrc(ctx, proptools.String(a.overridableProperties.Allowed_files))
  487. phonyOutput := android.PathForModuleOut(ctx, a.Name()+"-diff-phony-output")
  488. ctx.Build(pctx, android.BuildParams{
  489. Rule: diffApexContentRule,
  490. Implicits: implicitInputs,
  491. Output: phonyOutput,
  492. Description: "diff apex image content",
  493. Args: map[string]string{
  494. "allowed_files_file": allowedFilesFile.String(),
  495. "image_content_file": imageContentFile.String(),
  496. "apex_module_name": a.Name(),
  497. },
  498. })
  499. implicitInputs = append(implicitInputs, phonyOutput)
  500. }
  501. unsignedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix+".unsigned")
  502. outHostBinDir := ctx.Config().HostToolPath(ctx, "").String()
  503. prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
  504. // Figure out if we need to compress the apex.
  505. compressionEnabled := ctx.Config().CompressedApex() && proptools.BoolDefault(a.overridableProperties.Compressible, false) && !a.testApex && !ctx.Config().UnbundledBuildApps()
  506. if apexType == imageApex {
  507. ////////////////////////////////////////////////////////////////////////////////////
  508. // Step 2: create canned_fs_config which encodes filemode,uid,gid of each files
  509. // in this APEX. The file will be used by apexer in later steps.
  510. cannedFsConfig := a.buildCannedFsConfig(ctx)
  511. implicitInputs = append(implicitInputs, cannedFsConfig)
  512. ////////////////////////////////////////////////////////////////////////////////////
  513. // Step 3: Prepare option flags for apexer and invoke it to create an unsigned APEX.
  514. // TODO(jiyong): use the RuleBuilder
  515. optFlags := []string{}
  516. fileContexts := a.buildFileContexts(ctx)
  517. implicitInputs = append(implicitInputs, fileContexts)
  518. implicitInputs = append(implicitInputs, a.privateKeyFile, a.publicKeyFile)
  519. optFlags = append(optFlags, "--pubkey "+a.publicKeyFile.String())
  520. manifestPackageName := a.getOverrideManifestPackageName(ctx)
  521. if manifestPackageName != "" {
  522. optFlags = append(optFlags, "--override_apk_package_name "+manifestPackageName)
  523. }
  524. if a.properties.AndroidManifest != nil {
  525. androidManifestFile := android.PathForModuleSrc(ctx, proptools.String(a.properties.AndroidManifest))
  526. if a.testApex {
  527. androidManifestFile = markManifestTestOnly(ctx, androidManifestFile)
  528. }
  529. implicitInputs = append(implicitInputs, androidManifestFile)
  530. optFlags = append(optFlags, "--android_manifest "+androidManifestFile.String())
  531. } else if a.testApex {
  532. optFlags = append(optFlags, "--test_only")
  533. }
  534. // Determine target/min sdk version from the context
  535. // TODO(jiyong): make this as a function
  536. moduleMinSdkVersion := a.minSdkVersion(ctx)
  537. minSdkVersion := moduleMinSdkVersion.String()
  538. // bundletool doesn't understand what "current" is. We need to transform it to
  539. // codename
  540. if moduleMinSdkVersion.IsCurrent() || moduleMinSdkVersion.IsNone() {
  541. minSdkVersion = ctx.Config().DefaultAppTargetSdk(ctx).String()
  542. if java.UseApiFingerprint(ctx) {
  543. minSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
  544. implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
  545. }
  546. }
  547. // apex module doesn't have a concept of target_sdk_version, hence for the time
  548. // being targetSdkVersion == default targetSdkVersion of the branch.
  549. targetSdkVersion := strconv.Itoa(ctx.Config().DefaultAppTargetSdk(ctx).FinalOrFutureInt())
  550. if java.UseApiFingerprint(ctx) {
  551. targetSdkVersion = ctx.Config().PlatformSdkCodename() + fmt.Sprintf(".$$(cat %s)", java.ApiFingerprintPath(ctx).String())
  552. implicitInputs = append(implicitInputs, java.ApiFingerprintPath(ctx))
  553. }
  554. optFlags = append(optFlags, "--target_sdk_version "+targetSdkVersion)
  555. optFlags = append(optFlags, "--min_sdk_version "+minSdkVersion)
  556. if a.overridableProperties.Logging_parent != "" {
  557. optFlags = append(optFlags, "--logging_parent ", a.overridableProperties.Logging_parent)
  558. }
  559. // Create a NOTICE file, and embed it as an asset file in the APEX.
  560. a.htmlGzNotice = android.PathForModuleOut(ctx, "NOTICE.html.gz")
  561. android.BuildNoticeHtmlOutputFromLicenseMetadata(
  562. ctx, a.htmlGzNotice, "", "",
  563. []string{
  564. android.PathForModuleInstall(ctx).String() + "/",
  565. android.PathForModuleInPartitionInstall(ctx, "apex").String() + "/",
  566. })
  567. noticeAssetPath := android.PathForModuleOut(ctx, "NOTICE", "NOTICE.html.gz")
  568. builder := android.NewRuleBuilder(pctx, ctx)
  569. builder.Command().Text("cp").
  570. Input(a.htmlGzNotice).
  571. Output(noticeAssetPath)
  572. builder.Build("notice_dir", "Building notice dir")
  573. implicitInputs = append(implicitInputs, noticeAssetPath)
  574. optFlags = append(optFlags, "--assets_dir "+filepath.Dir(noticeAssetPath.String()))
  575. if (moduleMinSdkVersion.GreaterThan(android.SdkVersion_Android10) && !a.shouldGenerateHashtree()) && !compressionEnabled {
  576. // Apexes which are supposed to be installed in builtin dirs(/system, etc)
  577. // don't need hashtree for activation. Therefore, by removing hashtree from
  578. // apex bundle (filesystem image in it, to be specific), we can save storage.
  579. optFlags = append(optFlags, "--no_hashtree")
  580. }
  581. if a.testOnlyShouldSkipPayloadSign() {
  582. optFlags = append(optFlags, "--unsigned_payload")
  583. }
  584. if a.properties.Apex_name != nil {
  585. // If apex_name is set, apexer can skip checking if key name matches with
  586. // apex name. Note that apex_manifest is also mended.
  587. optFlags = append(optFlags, "--do_not_check_keyname")
  588. }
  589. if moduleMinSdkVersion == android.SdkVersion_Android10 {
  590. implicitInputs = append(implicitInputs, a.manifestJsonOut)
  591. optFlags = append(optFlags, "--manifest_json "+a.manifestJsonOut.String())
  592. }
  593. optFlags = append(optFlags, "--payload_fs_type "+a.payloadFsType.string())
  594. ctx.Build(pctx, android.BuildParams{
  595. Rule: apexRule,
  596. Implicits: implicitInputs,
  597. Output: unsignedOutputFile,
  598. Description: "apex (" + apexType.name() + ")",
  599. Args: map[string]string{
  600. "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
  601. "image_dir": imageDir.String(),
  602. "copy_commands": strings.Join(copyCommands, " && "),
  603. "manifest": a.manifestPbOut.String(),
  604. "file_contexts": fileContexts.String(),
  605. "canned_fs_config": cannedFsConfig.String(),
  606. "key": a.privateKeyFile.String(),
  607. "apex_version": defaultManifestVersion,
  608. "opt_flags": strings.Join(optFlags, " "),
  609. },
  610. })
  611. // TODO(jiyong): make the two rules below as separate functions
  612. apexProtoFile := android.PathForModuleOut(ctx, a.Name()+".pb"+suffix)
  613. bundleModuleFile := android.PathForModuleOut(ctx, a.Name()+suffix+"-base.zip")
  614. a.bundleModuleFile = bundleModuleFile
  615. ctx.Build(pctx, android.BuildParams{
  616. Rule: apexProtoConvertRule,
  617. Input: unsignedOutputFile,
  618. Output: apexProtoFile,
  619. Description: "apex proto convert",
  620. })
  621. implicitInputs = append(implicitInputs, unsignedOutputFile)
  622. // Run coverage analysis
  623. apisUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.txt")
  624. ctx.Build(pctx, android.BuildParams{
  625. Rule: generateAPIsUsedbyApexRule,
  626. Implicits: implicitInputs,
  627. Description: "coverage",
  628. Output: apisUsedbyOutputFile,
  629. Args: map[string]string{
  630. "image_dir": imageDir.String(),
  631. "readelf": "${config.ClangBin}/llvm-readelf",
  632. },
  633. })
  634. a.nativeApisUsedByModuleFile = apisUsedbyOutputFile
  635. var nativeLibNames []string
  636. for _, f := range a.filesInfo {
  637. if f.class == nativeSharedLib {
  638. nativeLibNames = append(nativeLibNames, f.stem())
  639. }
  640. }
  641. apisBackedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_backing.txt")
  642. rule := android.NewRuleBuilder(pctx, ctx)
  643. rule.Command().
  644. Tool(android.PathForSource(ctx, "build/soong/scripts/gen_ndk_backedby_apex.sh")).
  645. Output(apisBackedbyOutputFile).
  646. Flags(nativeLibNames)
  647. rule.Build("ndk_backedby_list", "Generate API libraries backed by Apex")
  648. a.nativeApisBackedByModuleFile = apisBackedbyOutputFile
  649. var javaLibOrApkPath []android.Path
  650. for _, f := range a.filesInfo {
  651. if f.class == javaSharedLib || f.class == app {
  652. javaLibOrApkPath = append(javaLibOrApkPath, f.builtFile)
  653. }
  654. }
  655. javaApiUsedbyOutputFile := android.PathForModuleOut(ctx, a.Name()+"_using.xml")
  656. javaUsedByRule := android.NewRuleBuilder(pctx, ctx)
  657. javaUsedByRule.Command().
  658. Tool(android.PathForSource(ctx, "build/soong/scripts/gen_java_usedby_apex.sh")).
  659. BuiltTool("dexdeps").
  660. Output(javaApiUsedbyOutputFile).
  661. Inputs(javaLibOrApkPath)
  662. javaUsedByRule.Build("java_usedby_list", "Generate Java APIs used by Apex")
  663. a.javaApisUsedByModuleFile = javaApiUsedbyOutputFile
  664. bundleConfig := a.buildBundleConfig(ctx)
  665. var abis []string
  666. for _, target := range ctx.MultiTargets() {
  667. if len(target.Arch.Abi) > 0 {
  668. abis = append(abis, target.Arch.Abi[0])
  669. }
  670. }
  671. abis = android.FirstUniqueStrings(abis)
  672. ctx.Build(pctx, android.BuildParams{
  673. Rule: apexBundleRule,
  674. Input: apexProtoFile,
  675. Implicit: bundleConfig,
  676. Output: a.bundleModuleFile,
  677. Description: "apex bundle module",
  678. Args: map[string]string{
  679. "abi": strings.Join(abis, "."),
  680. "config": bundleConfig.String(),
  681. },
  682. })
  683. } else { // zipApex
  684. ctx.Build(pctx, android.BuildParams{
  685. Rule: zipApexRule,
  686. Implicits: implicitInputs,
  687. Output: unsignedOutputFile,
  688. Description: "apex (" + apexType.name() + ")",
  689. Args: map[string]string{
  690. "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
  691. "image_dir": imageDir.String(),
  692. "copy_commands": strings.Join(copyCommands, " && "),
  693. "manifest": a.manifestPbOut.String(),
  694. "apex_version": defaultManifestVersion,
  695. },
  696. })
  697. }
  698. ////////////////////////////////////////////////////////////////////////////////////
  699. // Step 4: Sign the APEX using signapk
  700. signedOutputFile := android.PathForModuleOut(ctx, a.Name()+suffix)
  701. pem, key := a.getCertificateAndPrivateKey(ctx)
  702. rule := java.Signapk
  703. args := map[string]string{
  704. "certificates": pem.String() + " " + key.String(),
  705. "flags": "-a 4096 --align-file-size", //alignment
  706. }
  707. implicits := android.Paths{pem, key}
  708. if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
  709. rule = java.SignapkRE
  710. args["implicits"] = strings.Join(implicits.Strings(), ",")
  711. args["outCommaList"] = signedOutputFile.String()
  712. }
  713. ctx.Build(pctx, android.BuildParams{
  714. Rule: rule,
  715. Description: "signapk",
  716. Output: signedOutputFile,
  717. Input: unsignedOutputFile,
  718. Implicits: implicits,
  719. Args: args,
  720. })
  721. if suffix == imageApexSuffix {
  722. a.outputApexFile = signedOutputFile
  723. }
  724. a.outputFile = signedOutputFile
  725. if ctx.ModuleDir() != "system/apex/apexd/apexd_testdata" && a.testOnlyShouldForceCompression() {
  726. ctx.PropertyErrorf("test_only_force_compression", "not available")
  727. return
  728. }
  729. if apexType == imageApex && (compressionEnabled || a.testOnlyShouldForceCompression()) {
  730. a.isCompressed = true
  731. unsignedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix+".unsigned")
  732. compressRule := android.NewRuleBuilder(pctx, ctx)
  733. compressRule.Command().
  734. Text("rm").
  735. FlagWithOutput("-f ", unsignedCompressedOutputFile)
  736. compressRule.Command().
  737. BuiltTool("apex_compression_tool").
  738. Flag("compress").
  739. FlagWithArg("--apex_compression_tool ", outHostBinDir+":"+prebuiltSdkToolsBinDir).
  740. FlagWithInput("--input ", signedOutputFile).
  741. FlagWithOutput("--output ", unsignedCompressedOutputFile)
  742. compressRule.Build("compressRule", "Generate unsigned compressed APEX file")
  743. signedCompressedOutputFile := android.PathForModuleOut(ctx, a.Name()+imageCapexSuffix)
  744. if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_SIGNAPK") {
  745. args["outCommaList"] = signedCompressedOutputFile.String()
  746. }
  747. ctx.Build(pctx, android.BuildParams{
  748. Rule: rule,
  749. Description: "sign compressedApex",
  750. Output: signedCompressedOutputFile,
  751. Input: unsignedCompressedOutputFile,
  752. Implicits: implicits,
  753. Args: args,
  754. })
  755. a.outputFile = signedCompressedOutputFile
  756. }
  757. installSuffix := suffix
  758. if a.isCompressed {
  759. installSuffix = imageCapexSuffix
  760. }
  761. if !a.installable() {
  762. a.SkipInstall()
  763. }
  764. // Install to $OUT/soong/{target,host}/.../apex.
  765. a.installedFile = ctx.InstallFile(a.installDir, a.Name()+installSuffix, a.outputFile,
  766. a.compatSymlinks.Paths()...)
  767. // installed-files.txt is dist'ed
  768. a.installedFilesFile = a.buildInstalledFilesFile(ctx, a.outputFile, imageDir)
  769. }
  770. // buildFlattenedApex creates rules for a flattened APEX. Flattened APEX actually doesn't have a
  771. // single output file. It is a phony target for all the files under /system/apex/<name> directory.
  772. // This function creates the installation rules for the files.
  773. func (a *apexBundle) buildFlattenedApex(ctx android.ModuleContext) {
  774. bundleName := a.Name()
  775. installedSymlinks := append(android.InstallPaths(nil), a.compatSymlinks...)
  776. if a.installable() {
  777. for _, fi := range a.filesInfo {
  778. dir := filepath.Join("apex", bundleName, fi.installDir)
  779. installDir := android.PathForModuleInstall(ctx, dir)
  780. if a.linkToSystemLib && fi.transitiveDep && fi.availableToPlatform() {
  781. // TODO(jiyong): pathOnDevice should come from fi.module, not being calculated here
  782. pathOnDevice := filepath.Join("/system", fi.path())
  783. installedSymlinks = append(installedSymlinks,
  784. ctx.InstallAbsoluteSymlink(installDir, fi.stem(), pathOnDevice))
  785. } else {
  786. target := ctx.InstallFile(installDir, fi.stem(), fi.builtFile)
  787. for _, sym := range fi.symlinks {
  788. installedSymlinks = append(installedSymlinks,
  789. ctx.InstallSymlink(installDir, sym, target))
  790. }
  791. }
  792. }
  793. // Create install rules for the files added in GenerateAndroidBuildActions after
  794. // buildFlattenedApex is called. Add the links to system libs (if any) as dependencies
  795. // of the apex_manifest.pb file since it is always present.
  796. dir := filepath.Join("apex", bundleName)
  797. installDir := android.PathForModuleInstall(ctx, dir)
  798. ctx.InstallFile(installDir, "apex_manifest.pb", a.manifestPbOut, installedSymlinks.Paths()...)
  799. ctx.InstallFile(installDir, "apex_pubkey", a.publicKeyFile)
  800. }
  801. a.fileContexts = a.buildFileContexts(ctx)
  802. a.outputFile = android.PathForModuleInstall(ctx, "apex", bundleName)
  803. }
  804. // getCertificateAndPrivateKey retrieves the cert and the private key that will be used to sign
  805. // the zip container of this APEX. See the description of the 'certificate' property for how
  806. // the cert and the private key are found.
  807. func (a *apexBundle) getCertificateAndPrivateKey(ctx android.PathContext) (pem, key android.Path) {
  808. if a.containerCertificateFile != nil {
  809. return a.containerCertificateFile, a.containerPrivateKeyFile
  810. }
  811. cert := String(a.overridableProperties.Certificate)
  812. if cert == "" {
  813. return ctx.Config().DefaultAppCertificate(ctx)
  814. }
  815. defaultDir := ctx.Config().DefaultAppCertificateDir(ctx)
  816. pem = defaultDir.Join(ctx, cert+".x509.pem")
  817. key = defaultDir.Join(ctx, cert+".pk8")
  818. return pem, key
  819. }
  820. func (a *apexBundle) getOverrideManifestPackageName(ctx android.ModuleContext) string {
  821. // For VNDK APEXes, check "com.android.vndk" in PRODUCT_MANIFEST_PACKAGE_NAME_OVERRIDES
  822. // to see if it should be overridden because their <apex name> is dynamically generated
  823. // according to its VNDK version.
  824. if a.vndkApex {
  825. overrideName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(vndkApexName)
  826. if overridden {
  827. return strings.Replace(*a.properties.Apex_name, vndkApexName, overrideName, 1)
  828. }
  829. return ""
  830. }
  831. if a.overridableProperties.Package_name != "" {
  832. return a.overridableProperties.Package_name
  833. }
  834. manifestPackageName, overridden := ctx.DeviceConfig().OverrideManifestPackageNameFor(ctx.ModuleName())
  835. if overridden {
  836. return manifestPackageName
  837. }
  838. return ""
  839. }
  840. func (a *apexBundle) buildApexDependencyInfo(ctx android.ModuleContext) {
  841. if !a.primaryApexType {
  842. return
  843. }
  844. if a.properties.IsCoverageVariant {
  845. // Otherwise, we will have duplicated rules for coverage and
  846. // non-coverage variants of the same APEX
  847. return
  848. }
  849. if ctx.Host() {
  850. // No need to generate dependency info for host variant
  851. return
  852. }
  853. depInfos := android.DepNameToDepInfoMap{}
  854. a.WalkPayloadDeps(ctx, func(ctx android.ModuleContext, from blueprint.Module, to android.ApexModule, externalDep bool) bool {
  855. if from.Name() == to.Name() {
  856. // This can happen for cc.reuseObjTag. We are not interested in tracking this.
  857. // As soon as the dependency graph crosses the APEX boundary, don't go further.
  858. return !externalDep
  859. }
  860. // Skip dependencies that are only available to APEXes; they are developed with updatability
  861. // in mind and don't need manual approval.
  862. if to.(android.ApexModule).NotAvailableForPlatform() {
  863. return !externalDep
  864. }
  865. depTag := ctx.OtherModuleDependencyTag(to)
  866. // Check to see if dependency been marked to skip the dependency check
  867. if skipDepCheck, ok := depTag.(android.SkipApexAllowedDependenciesCheck); ok && skipDepCheck.SkipApexAllowedDependenciesCheck() {
  868. return !externalDep
  869. }
  870. if info, exists := depInfos[to.Name()]; exists {
  871. if !android.InList(from.Name(), info.From) {
  872. info.From = append(info.From, from.Name())
  873. }
  874. info.IsExternal = info.IsExternal && externalDep
  875. depInfos[to.Name()] = info
  876. } else {
  877. toMinSdkVersion := "(no version)"
  878. if m, ok := to.(interface {
  879. MinSdkVersion(ctx android.EarlyModuleContext) android.SdkSpec
  880. }); ok {
  881. if v := m.MinSdkVersion(ctx); !v.ApiLevel.IsNone() {
  882. toMinSdkVersion = v.ApiLevel.String()
  883. }
  884. } else if m, ok := to.(interface{ MinSdkVersion() string }); ok {
  885. // TODO(b/175678607) eliminate the use of MinSdkVersion returning
  886. // string
  887. if v := m.MinSdkVersion(); v != "" {
  888. toMinSdkVersion = v
  889. }
  890. }
  891. depInfos[to.Name()] = android.ApexModuleDepInfo{
  892. To: to.Name(),
  893. From: []string{from.Name()},
  894. IsExternal: externalDep,
  895. MinSdkVersion: toMinSdkVersion,
  896. }
  897. }
  898. // As soon as the dependency graph crosses the APEX boundary, don't go further.
  899. return !externalDep
  900. })
  901. a.ApexBundleDepsInfo.BuildDepsInfoLists(ctx, a.MinSdkVersion(ctx).Raw, depInfos)
  902. ctx.Build(pctx, android.BuildParams{
  903. Rule: android.Phony,
  904. Output: android.PathForPhony(ctx, a.Name()+"-deps-info"),
  905. Inputs: []android.Path{
  906. a.ApexBundleDepsInfo.FullListPath(),
  907. a.ApexBundleDepsInfo.FlatListPath(),
  908. },
  909. })
  910. }
  911. func (a *apexBundle) buildLintReports(ctx android.ModuleContext) {
  912. depSetsBuilder := java.NewLintDepSetBuilder()
  913. for _, fi := range a.filesInfo {
  914. depSetsBuilder.Transitive(fi.lintDepSets)
  915. }
  916. a.lintReports = java.BuildModuleLintReportZips(ctx, depSetsBuilder.Build())
  917. }
  918. func (a *apexBundle) buildCannedFsConfig(ctx android.ModuleContext) android.OutputPath {
  919. var readOnlyPaths = []string{"apex_manifest.json", "apex_manifest.pb"}
  920. var executablePaths []string // this also includes dirs
  921. var appSetDirs []string
  922. appSetFiles := make(map[string]android.Path)
  923. for _, f := range a.filesInfo {
  924. pathInApex := f.path()
  925. if f.installDir == "bin" || strings.HasPrefix(f.installDir, "bin/") {
  926. executablePaths = append(executablePaths, pathInApex)
  927. for _, d := range f.dataPaths {
  928. readOnlyPaths = append(readOnlyPaths, filepath.Join(f.installDir, d.RelativeInstallPath, d.SrcPath.Rel()))
  929. }
  930. for _, s := range f.symlinks {
  931. executablePaths = append(executablePaths, filepath.Join(f.installDir, s))
  932. }
  933. } else if f.class == appSet {
  934. appSetDirs = append(appSetDirs, f.installDir)
  935. appSetFiles[f.installDir] = f.builtFile
  936. } else {
  937. readOnlyPaths = append(readOnlyPaths, pathInApex)
  938. }
  939. dir := f.installDir
  940. for !android.InList(dir, executablePaths) && dir != "" {
  941. executablePaths = append(executablePaths, dir)
  942. dir, _ = filepath.Split(dir) // move up to the parent
  943. if len(dir) > 0 {
  944. // remove trailing slash
  945. dir = dir[:len(dir)-1]
  946. }
  947. }
  948. }
  949. sort.Strings(readOnlyPaths)
  950. sort.Strings(executablePaths)
  951. sort.Strings(appSetDirs)
  952. cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
  953. builder := android.NewRuleBuilder(pctx, ctx)
  954. cmd := builder.Command()
  955. cmd.Text("(")
  956. cmd.Text("echo '/ 1000 1000 0755';")
  957. for _, p := range readOnlyPaths {
  958. cmd.Textf("echo '/%s 1000 1000 0644';", p)
  959. }
  960. for _, p := range executablePaths {
  961. cmd.Textf("echo '/%s 0 2000 0755';", p)
  962. }
  963. for _, dir := range appSetDirs {
  964. cmd.Textf("echo '/%s 0 2000 0755';", dir)
  965. file := appSetFiles[dir]
  966. cmd.Text("zipinfo -1").Input(file).Textf(`| sed "s:\(.*\):/%s/\1 1000 1000 0644:";`, dir)
  967. }
  968. // Custom fs_config is "appended" to the last so that entries from the file are preferred
  969. // over default ones set above.
  970. if a.properties.Canned_fs_config != nil {
  971. cmd.Text("cat").Input(android.PathForModuleSrc(ctx, *a.properties.Canned_fs_config))
  972. }
  973. cmd.Text(")").FlagWithOutput("> ", cannedFsConfig)
  974. builder.Build("generateFsConfig", fmt.Sprintf("Generating canned fs config for %s", a.BaseModuleName()))
  975. return cannedFsConfig.OutputPath
  976. }