blob: 61cf373819823fffa2fe4522cff671a6c7eb2486 [file] [log] [blame]
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001// Copyright 2017 Google Inc. All rights reserved.
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 java
16
17import (
18 "path/filepath"
Colin Crossb69301e2017-12-01 10:48:26 -080019 "sort"
Colin Cross3bc7ffa2017-11-22 16:19:37 -080020 "strconv"
21 "strings"
22
23 "github.com/google/blueprint"
24
25 "android/soong/android"
26)
27
Inseob Kim34dc4cd2023-11-07 13:37:14 +090028func isPathValueResource(res android.Path) bool {
29 subDir := filepath.Dir(res.String())
30 subDir, lastDir := filepath.Split(subDir)
31 return strings.HasPrefix(lastDir, "values")
32}
33
Colin Cross3bc7ffa2017-11-22 16:19:37 -080034// Convert input resource file path to output file path.
35// values-[config]/<file>.xml -> values-[config]_<file>.arsc.flat;
Jaewoong Jung60d6d572020-11-20 17:58:27 -080036// For other resource file, just replace the last "/" with "_" and add .flat extension.
Colin Cross3bc7ffa2017-11-22 16:19:37 -080037func pathToAapt2Path(ctx android.ModuleContext, res android.Path) android.WritablePath {
38
39 name := res.Base()
Inseob Kim34dc4cd2023-11-07 13:37:14 +090040 if isPathValueResource(res) {
Colin Cross3bc7ffa2017-11-22 16:19:37 -080041 name = strings.TrimSuffix(name, ".xml") + ".arsc"
42 }
Inseob Kim34dc4cd2023-11-07 13:37:14 +090043 subDir := filepath.Dir(res.String())
44 subDir, lastDir := filepath.Split(subDir)
Colin Cross3bc7ffa2017-11-22 16:19:37 -080045 name = lastDir + "_" + name + ".flat"
46 return android.PathForModuleOut(ctx, "aapt2", subDir, name)
47}
48
Jaewoong Jung60d6d572020-11-20 17:58:27 -080049// pathsToAapt2Paths Calls pathToAapt2Path on each entry of the given Paths, i.e. []Path.
Colin Cross3bc7ffa2017-11-22 16:19:37 -080050func pathsToAapt2Paths(ctx android.ModuleContext, resPaths android.Paths) android.WritablePaths {
51 outPaths := make(android.WritablePaths, len(resPaths))
52
53 for i, res := range resPaths {
54 outPaths[i] = pathToAapt2Path(ctx, res)
55 }
56
57 return outPaths
58}
59
Jaewoong Jung60d6d572020-11-20 17:58:27 -080060// Shard resource files for efficiency. See aapt2Compile for details.
61const AAPT2_SHARD_SIZE = 100
62
Colin Cross3bc7ffa2017-11-22 16:19:37 -080063var aapt2CompileRule = pctx.AndroidStaticRule("aapt2Compile",
64 blueprint.RuleParams{
Colin Cross4215cfd2019-06-20 16:53:30 -070065 Command: `${config.Aapt2Cmd} compile -o $outDir $cFlags $in`,
Colin Cross3bc7ffa2017-11-22 16:19:37 -080066 CommandDeps: []string{"${config.Aapt2Cmd}"},
67 },
68 "outDir", "cFlags")
69
Jaewoong Jung60d6d572020-11-20 17:58:27 -080070// aapt2Compile compiles resources and puts the results in the requested directory.
Colin Crossa0ba2f52019-06-22 12:59:27 -070071func aapt2Compile(ctx android.ModuleContext, dir android.Path, paths android.Paths,
Jihoon Kang98ea8362024-07-16 18:20:03 +000072 flags []string, productToFilter string, featureFlagsPaths android.Paths) android.WritablePaths {
Inseob Kim34dc4cd2023-11-07 13:37:14 +090073 if productToFilter != "" && productToFilter != "default" {
74 // --filter-product leaves only product-specific resources. Product-specific resources only exist
75 // in value resources (values/*.xml), so filter value resource files only. Ignore other types of
76 // resources as they don't need to be in product characteristics RRO (and they will cause aapt2
77 // compile errors)
78 filteredPaths := android.Paths{}
79 for _, path := range paths {
80 if isPathValueResource(path) {
81 filteredPaths = append(filteredPaths, path)
82 }
83 }
84 paths = filteredPaths
85 flags = append([]string{"--filter-product " + productToFilter}, flags...)
86 }
Colin Crossa0ba2f52019-06-22 12:59:27 -070087
Jihoon Kang98ea8362024-07-16 18:20:03 +000088 for _, featureFlagsPath := range android.SortedUniquePaths(featureFlagsPaths) {
89 flags = append(flags, "--feature-flags", "@"+featureFlagsPath.String())
90 }
91
Jaewoong Jung60d6d572020-11-20 17:58:27 -080092 // Shard the input paths so that they can be processed in parallel. If we shard them into too
93 // small chunks, the additional cost of spinning up aapt2 outweighs the performance gain. The
94 // current shard size, 100, seems to be a good balance between the added cost and the gain.
95 // The aapt2 compile actions are trivially short, but each action in ninja takes on the order of
96 // ~10 ms to run. frameworks/base/core/res/res has >10k resource files, so compiling each one
97 // with an individual action could take 100 CPU seconds. Sharding them reduces the overhead of
98 // starting actions by a factor of 100, at the expense of recompiling more files when one
99 // changes. Since the individual compiles are trivial it's a good tradeoff.
Colin Cross0a2f7192019-09-23 14:33:09 -0700100 shards := android.ShardPaths(paths, AAPT2_SHARD_SIZE)
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800101
102 ret := make(android.WritablePaths, 0, len(paths))
103
104 for i, shard := range shards {
Jaewoong Jung60d6d572020-11-20 17:58:27 -0800105 // This should be kept in sync with pathToAapt2Path. The aapt2 compile command takes an
106 // output directory path, but not output file paths. So, outPaths is just where we expect
107 // the output files will be located.
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800108 outPaths := pathsToAapt2Paths(ctx, shard)
109 ret = append(ret, outPaths...)
110
111 shardDesc := ""
112 if i != 0 {
113 shardDesc = " " + strconv.Itoa(i+1)
114 }
115
116 ctx.Build(pctx, android.BuildParams{
117 Rule: aapt2CompileRule,
118 Description: "aapt2 compile " + dir.String() + shardDesc,
Jihoon Kang98ea8362024-07-16 18:20:03 +0000119 Implicits: featureFlagsPaths,
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800120 Inputs: shard,
121 Outputs: outPaths,
122 Args: map[string]string{
Jaewoong Jung60d6d572020-11-20 17:58:27 -0800123 // The aapt2 compile command takes an output directory path, but not output file paths.
124 // outPaths specified above is only used for dependency management purposes. In order for
125 // the outPaths values to match the actual outputs from aapt2, the dir parameter value
126 // must be a common prefix path of the paths values, and the top-level path segment used
127 // below, "aapt2", must always be kept in sync with the one in pathToAapt2Path.
128 // TODO(b/174505750): Make this easier and robust to use.
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800129 "outDir": android.PathForModuleOut(ctx, "aapt2", dir.String()).String(),
Colin Crossa0ba2f52019-06-22 12:59:27 -0700130 "cFlags": strings.Join(flags, " "),
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800131 },
132 })
133 }
134
Colin Crossb69301e2017-12-01 10:48:26 -0800135 sort.Slice(ret, func(i, j int) bool {
136 return ret[i].String() < ret[j].String()
137 })
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800138 return ret
139}
140
Colin Crossa592e3e2019-02-19 16:59:53 -0800141var aapt2CompileZipRule = pctx.AndroidStaticRule("aapt2CompileZip",
142 blueprint.RuleParams{
Dan Willemsen304cfec2019-05-28 14:49:06 -0700143 Command: `${config.ZipSyncCmd} -d $resZipDir $zipSyncFlags $in && ` +
Colin Cross4215cfd2019-06-20 16:53:30 -0700144 `${config.Aapt2Cmd} compile -o $out $cFlags --dir $resZipDir`,
Colin Crossa592e3e2019-02-19 16:59:53 -0800145 CommandDeps: []string{
146 "${config.Aapt2Cmd}",
147 "${config.ZipSyncCmd}",
148 },
Dan Willemsen304cfec2019-05-28 14:49:06 -0700149 }, "cFlags", "resZipDir", "zipSyncFlags")
Colin Crossa592e3e2019-02-19 16:59:53 -0800150
Jaewoong Jung60d6d572020-11-20 17:58:27 -0800151// Unzips the given compressed file and compiles the resource source files in it. The zipPrefix
152// parameter points to the subdirectory in the zip file where the resource files are located.
Colin Crossa0ba2f52019-06-22 12:59:27 -0700153func aapt2CompileZip(ctx android.ModuleContext, flata android.WritablePath, zip android.Path, zipPrefix string,
154 flags []string) {
155
Dan Willemsen304cfec2019-05-28 14:49:06 -0700156 if zipPrefix != "" {
157 zipPrefix = "--zip-prefix " + zipPrefix
158 }
Colin Crossa592e3e2019-02-19 16:59:53 -0800159 ctx.Build(pctx, android.BuildParams{
160 Rule: aapt2CompileZipRule,
161 Description: "aapt2 compile zip",
162 Input: zip,
163 Output: flata,
164 Args: map[string]string{
Colin Crossa0ba2f52019-06-22 12:59:27 -0700165 "cFlags": strings.Join(flags, " "),
Dan Willemsen304cfec2019-05-28 14:49:06 -0700166 "resZipDir": android.PathForModuleOut(ctx, "aapt2", "reszip", flata.Base()).String(),
167 "zipSyncFlags": zipPrefix,
Colin Crossa592e3e2019-02-19 16:59:53 -0800168 },
169 })
170}
171
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800172var aapt2LinkRule = pctx.AndroidStaticRule("aapt2Link",
173 blueprint.RuleParams{
Colin Crossf3b7bad2023-08-02 15:49:00 -0700174 Command: `$preamble` +
175 `${config.Aapt2Cmd} link -o $out $flags --proguard $proguardOptions ` +
176 `--output-text-symbols ${rTxt} $inFlags` +
177 `$postamble`,
Colin Cross66f78822018-05-02 12:58:28 -0700178
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800179 CommandDeps: []string{
Colin Cross44f06682017-11-29 00:17:36 -0800180 "${config.Aapt2Cmd}",
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800181 "${config.SoongZipCmd}",
182 },
183 Restat: true,
184 },
Colin Crossf3b7bad2023-08-02 15:49:00 -0700185 "flags", "inFlags", "proguardOptions", "rTxt", "extraPackages", "preamble", "postamble")
186
187var aapt2ExtractExtraPackagesRule = pctx.AndroidStaticRule("aapt2ExtractExtraPackages",
188 blueprint.RuleParams{
189 Command: `${config.ExtractJarPackagesCmd} -i $in -o $out --prefix '--extra-packages '`,
190 CommandDeps: []string{"${config.ExtractJarPackagesCmd}"},
191 Restat: true,
192 })
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800193
194var fileListToFileRule = pctx.AndroidStaticRule("fileListToFile",
195 blueprint.RuleParams{
196 Command: `cp $out.rsp $out`,
197 Rspfile: "$out.rsp",
198 RspfileContent: "$in",
199 })
200
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800201var mergeAssetsRule = pctx.AndroidStaticRule("mergeAssets",
202 blueprint.RuleParams{
203 Command: `${config.MergeZipsCmd} ${out} ${in}`,
204 CommandDeps: []string{"${config.MergeZipsCmd}"},
205 })
206
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800207func aapt2Link(ctx android.ModuleContext,
Colin Crossf3b7bad2023-08-02 15:49:00 -0700208 packageRes, genJar, proguardOptions, rTxt android.WritablePath,
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800209 flags []string, deps android.Paths,
Jihoon Kang84b25892023-12-01 22:01:06 +0000210 compiledRes, compiledOverlay, assetPackages android.Paths, splitPackages android.WritablePaths,
211 featureFlagsPaths android.Paths) {
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800212
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800213 var inFlags []string
214
215 if len(compiledRes) > 0 {
Jaewoong Jung60d6d572020-11-20 17:58:27 -0800216 // Create a file that contains the list of all compiled resource file paths.
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800217 resFileList := android.PathForModuleOut(ctx, "aapt2", "res.list")
218 // Write out file lists to files
219 ctx.Build(pctx, android.BuildParams{
220 Rule: fileListToFileRule,
221 Description: "resource file list",
222 Inputs: compiledRes,
223 Output: resFileList,
224 })
225
226 deps = append(deps, compiledRes...)
227 deps = append(deps, resFileList)
Jaewoong Jung60d6d572020-11-20 17:58:27 -0800228 // aapt2 filepath arguments that start with "@" mean file-list files.
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800229 inFlags = append(inFlags, "@"+resFileList.String())
230 }
231
232 if len(compiledOverlay) > 0 {
Jaewoong Jung60d6d572020-11-20 17:58:27 -0800233 // Compiled overlay files are processed the same way as compiled resources.
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800234 overlayFileList := android.PathForModuleOut(ctx, "aapt2", "overlay.list")
235 ctx.Build(pctx, android.BuildParams{
236 Rule: fileListToFileRule,
237 Description: "overlay resource file list",
238 Inputs: compiledOverlay,
239 Output: overlayFileList,
240 })
241
242 deps = append(deps, compiledOverlay...)
243 deps = append(deps, overlayFileList)
Jaewoong Jung60d6d572020-11-20 17:58:27 -0800244 // Compiled overlay files are passed over to aapt2 using -R option.
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800245 inFlags = append(inFlags, "-R", "@"+overlayFileList.String())
246 }
247
Jaewoong Jung60d6d572020-11-20 17:58:27 -0800248 // Set auxiliary outputs as implicit outputs to establish correct dependency chains.
Colin Crossf3b7bad2023-08-02 15:49:00 -0700249 implicitOutputs := append(splitPackages, proguardOptions, rTxt)
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800250 linkOutput := packageRes
251
252 // AAPT2 ignores assets in overlays. Merge them after linking.
253 if len(assetPackages) > 0 {
254 linkOutput = android.PathForModuleOut(ctx, "aapt2", "package-res.apk")
255 inputZips := append(android.Paths{linkOutput}, assetPackages...)
256 ctx.Build(pctx, android.BuildParams{
257 Rule: mergeAssetsRule,
258 Inputs: inputZips,
259 Output: packageRes,
260 Description: "merge assets from dependencies",
261 })
262 }
Colin Crosse560c4a2019-03-19 16:03:11 -0700263
Jihoon Kang84b25892023-12-01 22:01:06 +0000264 for _, featureFlagsPath := range featureFlagsPaths {
265 deps = append(deps, featureFlagsPath)
266 inFlags = append(inFlags, "--feature-flags", "@"+featureFlagsPath.String())
267 }
268
Colin Crossf3b7bad2023-08-02 15:49:00 -0700269 // Note the absence of splitPackages. The caller is supposed to compose and provide --split flag
270 // values via the flags parameter when it wants to split outputs.
271 // TODO(b/174509108): Perhaps we can process it in this func while keeping the code reasonably
272 // tidy.
273 args := map[string]string{
274 "flags": strings.Join(flags, " "),
275 "inFlags": strings.Join(inFlags, " "),
276 "proguardOptions": proguardOptions.String(),
277 "rTxt": rTxt.String(),
278 }
279
280 if genJar != nil {
281 // Generating java source files from aapt2 was requested, use aapt2LinkAndGenRule and pass it
282 // genJar and genDir args.
283 genDir := android.PathForModuleGen(ctx, "aapt2", "R")
284 ctx.Variable(pctx, "aapt2GenDir", genDir.String())
285 ctx.Variable(pctx, "aapt2GenJar", genJar.String())
286 implicitOutputs = append(implicitOutputs, genJar)
287 args["preamble"] = `rm -rf $aapt2GenDir && `
288 args["postamble"] = `&& ${config.SoongZipCmd} -write_if_changed -jar -o $aapt2GenJar -C $aapt2GenDir -D $aapt2GenDir && ` +
289 `rm -rf $aapt2GenDir`
290 args["flags"] += " --java $aapt2GenDir"
291 }
292
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800293 ctx.Build(pctx, android.BuildParams{
294 Rule: aapt2LinkRule,
295 Description: "aapt2 link",
296 Implicits: deps,
Jaewoong Jung6431ca72020-01-15 14:15:10 -0800297 Output: linkOutput,
Colin Crosse560c4a2019-03-19 16:03:11 -0700298 ImplicitOutputs: implicitOutputs,
Colin Crossf3b7bad2023-08-02 15:49:00 -0700299 Args: args,
300 })
301}
302
303// aapt2ExtractExtraPackages takes a srcjar generated by aapt2 or a classes jar generated by ResourceProcessorBusyBox
304// and converts it to a text file containing a list of --extra_package arguments for passing to Make modules so they
305// correctly generate R.java entries for packages provided by transitive dependencies.
306func aapt2ExtractExtraPackages(ctx android.ModuleContext, out android.WritablePath, in android.Path) {
307 ctx.Build(pctx, android.BuildParams{
308 Rule: aapt2ExtractExtraPackagesRule,
309 Description: "aapt2 extract extra packages",
310 Input: in,
311 Output: out,
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800312 })
313}
Colin Crossf6237212018-10-29 23:14:58 -0700314
315var aapt2ConvertRule = pctx.AndroidStaticRule("aapt2Convert",
316 blueprint.RuleParams{
Rico Wind21862282023-08-01 14:38:36 +0200317 Command: `${config.Aapt2Cmd} convert --enable-compact-entries ` +
318 `--output-format $format $in -o $out`,
Colin Crossf6237212018-10-29 23:14:58 -0700319 CommandDeps: []string{"${config.Aapt2Cmd}"},
Rico Wind351bac92022-09-22 10:41:42 +0200320 }, "format",
321)
Colin Crossf6237212018-10-29 23:14:58 -0700322
Jaewoong Jung60d6d572020-11-20 17:58:27 -0800323// Converts xml files and resource tables (resources.arsc) in the given jar/apk file to a proto
324// format. The proto definition is available at frameworks/base/tools/aapt2/Resources.proto.
Rico Wind351bac92022-09-22 10:41:42 +0200325func aapt2Convert(ctx android.ModuleContext, out android.WritablePath, in android.Path, format string) {
Colin Crossf6237212018-10-29 23:14:58 -0700326 ctx.Build(pctx, android.BuildParams{
327 Rule: aapt2ConvertRule,
328 Input: in,
329 Output: out,
Rico Wind351bac92022-09-22 10:41:42 +0200330 Description: "convert to " + format,
331 Args: map[string]string{
332 "format": format,
333 },
Colin Crossf6237212018-10-29 23:14:58 -0700334 })
335}