blob: 6a57725836764ba0ca1f48ca20fbaa887b6b5f94 [file] [log] [blame]
Colin Cross2fe66872015-03-30 17:20:39 -07001// Copyright 2015 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
17// This file generates the final rules for compiling all Java. All properties related to
18// compiling should have been translated into javaBuilderFlags or another argument to the Transform*
19// functions.
20
21import (
Spandan Daseaa47512024-04-09 21:30:12 +000022 "fmt"
Nan Zhang61eaedb2017-11-02 13:28:15 -070023 "path/filepath"
24 "strconv"
Colin Cross2fe66872015-03-30 17:20:39 -070025 "strings"
26
Colin Cross2fe66872015-03-30 17:20:39 -070027 "github.com/google/blueprint"
Colin Crossfe4bc362018-09-12 10:02:13 -070028 "github.com/google/blueprint/proptools"
Colin Crossfee57cb2017-09-05 13:16:45 -070029
30 "android/soong/android"
Ramy Medhat1dcc27e2020-04-21 21:36:23 -040031 "android/soong/remoteexec"
Colin Cross2fe66872015-03-30 17:20:39 -070032)
33
34var (
Colin Cross635c3b02016-05-18 15:37:25 -070035 pctx = android.NewPackageContext("android/soong/java")
Colin Cross2fe66872015-03-30 17:20:39 -070036
37 // Compiling java is not conducive to proper dependency tracking. The path-matches-class-name
38 // requirement leads to unpredictable generated source file names, and a single .java file
39 // will get compiled into multiple .class files if it contains inner classes. To work around
Colin Crossf7eac7a2018-02-08 12:48:39 -080040 // this, all java rules write into separate directories and then are combined into a .jar file
41 // (if the rule produces .class files) or a .srcjar file (if the rule produces .java files).
42 // .srcjar files are unzipped into a temporary directory when compiled with javac.
Colin Cross1ec3fce2020-03-05 12:43:14 -080043 // TODO(b/143658984): goma can't handle the --system argument to javac.
Colin Cross77cdcfd2021-03-12 11:28:25 -080044 javac, javacRE = pctx.MultiCommandRemoteStaticRules("javac",
Colin Cross2fe66872015-03-30 17:20:39 -070045 blueprint.RuleParams{
LaMont Jonesfeff3f32023-06-14 20:43:14 +000046 Command: `rm -rf "$outDir" "$annoDir" "$annoSrcJar.tmp" "$srcJarDir" "$out.tmp" && ` +
Vadim Spivak3c496f02023-06-08 06:14:59 +000047 `mkdir -p "$outDir" "$annoDir" "$srcJarDir" && ` +
Colin Cross436b7652018-03-15 16:24:10 -070048 `${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
Sundong Ahn24a099c2018-06-28 14:53:20 +090049 `(if [ -s $srcJarDir/list ] || [ -s $out.rsp ] ; then ` +
Kousik Kumar366afc52020-05-20 11:27:16 -070050 `${config.SoongJavacWrapper} $javaTemplate${config.JavacCmd} ` +
Sasha Smundak26c6d9e2019-06-11 13:30:13 -070051 `${config.JavacHeapFlags} ${config.JavacVmFlags} ${config.CommonJdkFlags} ` +
Colin Crossbe9cdb82019-01-21 21:37:16 -080052 `$processorpath $processor $javacFlags $bootClasspath $classpath ` +
Colin Cross64162712017-08-08 13:17:59 -070053 `-source $javaVersion -target $javaVersion ` +
Sundong Ahn24a099c2018-06-28 14:53:20 +090054 `-d $outDir -s $annoDir @$out.rsp @$srcJarDir/list ; fi ) && ` +
LaMont Jonesfeff3f32023-06-14 20:43:14 +000055 `$annoSrcJarTemplate${config.SoongZipCmd} -jar -o $annoSrcJar.tmp -C $annoDir -D $annoDir && ` +
56 `$zipTemplate${config.SoongZipCmd} -jar -o $out.tmp -C $outDir -D $outDir && ` +
57 `if ! cmp -s "$out.tmp" "$out"; then mv "$out.tmp" "$out"; fi && ` +
58 `if ! cmp -s "$annoSrcJar.tmp" "$annoSrcJar"; then mv "$annoSrcJar.tmp" "$annoSrcJar"; fi && ` +
Colin Cross49889c02023-07-26 16:16:47 -070059 `rm -rf "$srcJarDir" "$outDir"`,
Colin Cross8eadbf02017-10-24 17:46:00 -070060 CommandDeps: []string{
61 "${config.JavacCmd}",
62 "${config.SoongZipCmd}",
Colin Cross436b7652018-03-15 16:24:10 -070063 "${config.ZipSyncCmd}",
Colin Cross8eadbf02017-10-24 17:46:00 -070064 },
Colin Crossa4820652017-10-17 13:56:52 -070065 CommandOrderOnly: []string{"${config.SoongJavacWrapper}"},
LaMont Jonesfeff3f32023-06-14 20:43:14 +000066 Restat: true,
Colin Crossa4820652017-10-17 13:56:52 -070067 Rspfile: "$out.rsp",
68 RspfileContent: "$in",
Kousik Kumar366afc52020-05-20 11:27:16 -070069 }, map[string]*remoteexec.REParams{
70 "$javaTemplate": &remoteexec.REParams{
71 Labels: map[string]string{"type": "compile", "lang": "java", "compiler": "javac"},
Spandan Daseaa47512024-04-09 21:30:12 +000072 Inputs: []string{"${config.JavacCmd}"},
73 RSPFiles: []string{"${out}.rsp", "${javacREClasspathDeps}"},
Kousik Kumar366afc52020-05-20 11:27:16 -070074 ExecStrategy: "${config.REJavacExecStrategy}",
75 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
76 },
77 "$zipTemplate": &remoteexec.REParams{
78 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
79 Inputs: []string{"${config.SoongZipCmd}", "$outDir"},
LaMont Jonesfeff3f32023-06-14 20:43:14 +000080 OutputFiles: []string{"$out.tmp"},
Kousik Kumar366afc52020-05-20 11:27:16 -070081 ExecStrategy: "${config.REJavacExecStrategy}",
82 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
83 },
Vadim Spivak3c496f02023-06-08 06:14:59 +000084 "$annoSrcJarTemplate": &remoteexec.REParams{
85 Labels: map[string]string{"type": "tool", "name": "soong_zip"},
86 Inputs: []string{"${config.SoongZipCmd}", "$annoDir"},
LaMont Jonesfeff3f32023-06-14 20:43:14 +000087 OutputFiles: []string{"$annoSrcJar.tmp"},
Vadim Spivak3c496f02023-06-08 06:14:59 +000088 ExecStrategy: "${config.REJavacExecStrategy}",
89 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
90 },
Ramy Medhat1dcc27e2020-04-21 21:36:23 -040091 }, []string{"javacFlags", "bootClasspath", "classpath", "processorpath", "processor", "srcJars", "srcJarDir",
Spandan Daseaa47512024-04-09 21:30:12 +000092 "outDir", "annoDir", "annoSrcJar", "javaVersion"}, []string{"javacREClasspathDeps"})
Colin Cross2fe66872015-03-30 17:20:39 -070093
Sasha Smundak2a4549e2018-11-05 16:49:08 -080094 _ = pctx.VariableFunc("kytheCorpus",
95 func(ctx android.PackageVarContext) string { return ctx.Config().XrefCorpusName() })
Sasha Smundak6c2d4f92020-01-09 17:34:23 -080096 _ = pctx.VariableFunc("kytheCuEncoding",
97 func(ctx android.PackageVarContext) string { return ctx.Config().XrefCuEncoding() })
Sasha Smundakb0addaf2021-02-16 10:39:40 -080098 _ = pctx.VariableFunc("kytheCuJavaSourceMax",
99 func(ctx android.PackageVarContext) string { return ctx.Config().XrefCuJavaSourceMax() })
Sasha Smundak65143642019-09-26 20:14:28 -0700100 _ = pctx.SourcePathVariable("kytheVnames", "build/soong/vnames.json")
Sasha Smundak706d35f2022-10-23 15:23:55 -0700101 // Run it with several --add-exports to allow the classes in the
102 // com.google.devtools.kythe.extractors.java.standalone package access the packages in the
103 // jdk.compiler compiler module. Long live Java modules.
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800104 kytheExtract = pctx.AndroidStaticRule("kythe",
105 blueprint.RuleParams{
106 Command: `${config.ZipSyncCmd} -d $srcJarDir ` +
107 `-l $srcJarDir/list -f "*.java" $srcJars && ` +
108 `( [ ! -s $srcJarDir/list -a ! -s $out.rsp ] || ` +
109 `KYTHE_ROOT_DIRECTORY=. KYTHE_OUTPUT_FILE=$out ` +
110 `KYTHE_CORPUS=${kytheCorpus} ` +
Sasha Smundak65143642019-09-26 20:14:28 -0700111 `KYTHE_VNAMES=${kytheVnames} ` +
Sasha Smundak6c2d4f92020-01-09 17:34:23 -0800112 `KYTHE_KZIP_ENCODING=${kytheCuEncoding} ` +
Sasha Smundakb0addaf2021-02-16 10:39:40 -0800113 `KYTHE_JAVA_SOURCE_BATCH_SIZE=${kytheCuJavaSourceMax} ` +
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800114 `${config.SoongJavacWrapper} ${config.JavaCmd} ` +
Sasha Smundak706d35f2022-10-23 15:23:55 -0700115 // Avoid JDK9's warning about "Illegal reflective access by com.google.protobuf.Utf8$UnsafeProcessor ...
116 // to field java.nio.Buffer.address"
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800117 `--add-opens=java.base/java.nio=ALL-UNNAMED ` +
Sasha Smundak706d35f2022-10-23 15:23:55 -0700118 // Allow the classes in the com.google.devtools.kythe.extractors.java.standalone package
119 // access the packages in the jdk.compiler compiler module
120 `--add-opens=java.base/java.nio=ALL-UNNAMED ` +
121 `--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED ` +
122 `--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED ` +
123 `--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED ` +
124 `--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED ` +
125 `--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED ` +
Sorin Basca79b7ca12024-03-14 16:59:49 +0000126 `--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED ` +
127 `--add-exports=jdk.internal.opt/jdk.internal.opt=ALL-UNNAMED ` +
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800128 `-jar ${config.JavaKytheExtractorJar} ` +
129 `${config.JavacHeapFlags} ${config.CommonJdkFlags} ` +
130 `$processorpath $processor $javacFlags $bootClasspath $classpath ` +
131 `-source $javaVersion -target $javaVersion ` +
132 `-d $outDir -s $annoDir @$out.rsp @$srcJarDir/list)`,
133 CommandDeps: []string{
134 "${config.JavaCmd}",
135 "${config.JavaKytheExtractorJar}",
Sasha Smundak65143642019-09-26 20:14:28 -0700136 "${kytheVnames}",
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800137 "${config.ZipSyncCmd}",
138 },
139 CommandOrderOnly: []string{"${config.SoongJavacWrapper}"},
140 Rspfile: "$out.rsp",
141 RspfileContent: "$in",
142 },
143 "javacFlags", "bootClasspath", "classpath", "processorpath", "processor", "srcJars", "srcJarDir",
144 "outDir", "annoDir", "javaVersion")
145
Sasha Smundaka7856c02020-04-23 09:49:59 -0700146 extractMatchingApks = pctx.StaticRule(
147 "extractMatchingApks",
148 blueprint.RuleParams{
149 Command: `rm -rf "$out" && ` +
Colin Crossffbcd1d2021-11-12 12:19:42 -0800150 `${config.ExtractApksCmd} -o "${out}" -zip "${zip}" -allow-prereleased=${allow-prereleased} ` +
Pranav Gupta51645ff2023-03-20 16:19:53 -0700151 `-sdk-version=${sdk-version} -skip-sdk-check=${skip-sdk-check} -abis=${abis} ` +
Sasha Smundaka7856c02020-04-23 09:49:59 -0700152 `--screen-densities=${screen-densities} --stem=${stem} ` +
Jaewoong Jung11c1e0f2020-06-29 19:18:44 -0700153 `-apkcerts=${apkcerts} -partition=${partition} ` +
Sasha Smundaka7856c02020-04-23 09:49:59 -0700154 `${in}`,
155 CommandDeps: []string{"${config.ExtractApksCmd}"},
156 },
Pranav Gupta51645ff2023-03-20 16:19:53 -0700157 "abis", "allow-prereleased", "screen-densities", "sdk-version", "skip-sdk-check", "stem", "apkcerts", "partition", "zip")
Sasha Smundaka7856c02020-04-23 09:49:59 -0700158
Colin Cross77cdcfd2021-03-12 11:28:25 -0800159 turbine, turbineRE = pctx.RemoteStaticRules("turbine",
Nan Zhanged19fc32017-10-19 13:06:22 -0700160 blueprint.RuleParams{
Colin Crossf61766e2022-03-16 18:06:48 -0700161 Command: `$reTemplate${config.JavaCmd} ${config.JavaVmFlags} -jar ${config.TurbineJar} $outputFlags ` +
Colin Cross411647e2022-03-16 14:28:36 -0700162 `--sources @$out.rsp --source_jars $srcJars ` +
Nan Zhanged19fc32017-10-19 13:06:22 -0700163 `--javacopts ${config.CommonJdkFlags} ` +
Colin Crossf61766e2022-03-16 18:06:48 -0700164 `$javacFlags -source $javaVersion -target $javaVersion -- $turbineFlags && ` +
165 `(for o in $outputs; do if cmp -s $${o}.tmp $${o} ; then rm $${o}.tmp ; else mv $${o}.tmp $${o} ; fi; done )`,
Colin Cross8eadbf02017-10-24 17:46:00 -0700166 CommandDeps: []string{
167 "${config.TurbineJar}",
168 "${config.JavaCmd}",
Colin Cross8eadbf02017-10-24 17:46:00 -0700169 },
Nan Zhanged19fc32017-10-19 13:06:22 -0700170 Rspfile: "$out.rsp",
171 RspfileContent: "$in",
172 Restat: true,
173 },
Kousik Kumar1372c1b2020-05-20 07:55:56 -0700174 &remoteexec.REParams{Labels: map[string]string{"type": "tool", "name": "turbine"},
Colin Cross411647e2022-03-16 14:28:36 -0700175 ExecStrategy: "${config.RETurbineExecStrategy}",
176 Inputs: []string{"${config.TurbineJar}", "${out}.rsp", "$implicits"},
177 RSPFiles: []string{"${out}.rsp"},
Colin Crossf61766e2022-03-16 18:06:48 -0700178 OutputFiles: []string{"$rbeOutputs"},
Colin Cross411647e2022-03-16 14:28:36 -0700179 ToolchainInputs: []string{"${config.JavaCmd}"},
180 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
Colin Crossf61766e2022-03-16 18:06:48 -0700181 },
182 []string{"javacFlags", "turbineFlags", "outputFlags", "javaVersion", "outputs", "rbeOutputs", "srcJars"}, []string{"implicits"})
Nan Zhanged19fc32017-10-19 13:06:22 -0700183
Colin Cross77cdcfd2021-03-12 11:28:25 -0800184 jar, jarRE = pctx.RemoteStaticRules("jar",
Colin Cross2fe66872015-03-30 17:20:39 -0700185 blueprint.RuleParams{
Kousik Kumar366afc52020-05-20 11:27:16 -0700186 Command: `$reTemplate${config.SoongZipCmd} -jar -o $out @$out.rsp`,
Nan Zhang674dd932018-01-26 18:30:36 -0800187 CommandDeps: []string{"${config.SoongZipCmd}"},
188 Rspfile: "$out.rsp",
189 RspfileContent: "$jarArgs",
Colin Cross2fe66872015-03-30 17:20:39 -0700190 },
Kousik Kumar366afc52020-05-20 11:27:16 -0700191 &remoteexec.REParams{
192 ExecStrategy: "${config.REJarExecStrategy}",
193 Inputs: []string{"${config.SoongZipCmd}", "${out}.rsp"},
Colin Crossa4eafdd2021-03-24 14:09:28 -0700194 RSPFiles: []string{"${out}.rsp"},
Kousik Kumar366afc52020-05-20 11:27:16 -0700195 OutputFiles: []string{"$out"},
196 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
197 }, []string{"jarArgs"}, nil)
Colin Cross0a6e0072017-08-30 14:24:55 -0700198
Colin Cross77cdcfd2021-03-12 11:28:25 -0800199 zip, zipRE = pctx.RemoteStaticRules("zip",
Colin Crossa4f08812018-10-02 22:03:40 -0700200 blueprint.RuleParams{
201 Command: `${config.SoongZipCmd} -o $out @$out.rsp`,
202 CommandDeps: []string{"${config.SoongZipCmd}"},
203 Rspfile: "$out.rsp",
204 RspfileContent: "$jarArgs",
205 },
Kousik Kumar366afc52020-05-20 11:27:16 -0700206 &remoteexec.REParams{
207 ExecStrategy: "${config.REZipExecStrategy}",
208 Inputs: []string{"${config.SoongZipCmd}", "${out}.rsp", "$implicits"},
Colin Crossa4eafdd2021-03-24 14:09:28 -0700209 RSPFiles: []string{"${out}.rsp"},
Kousik Kumar366afc52020-05-20 11:27:16 -0700210 OutputFiles: []string{"$out"},
211 Platform: map[string]string{remoteexec.PoolKey: "${config.REJavaPool}"},
212 }, []string{"jarArgs"}, []string{"implicits"})
Colin Crossa4f08812018-10-02 22:03:40 -0700213
Colin Cross0a6e0072017-08-30 14:24:55 -0700214 combineJar = pctx.AndroidStaticRule("combineJar",
215 blueprint.RuleParams{
Colin Crossf91a08c2018-02-07 15:41:31 -0800216 Command: `${config.MergeZipsCmd} --ignore-duplicates -j $jarArgs $out $in`,
Colin Cross0a6e0072017-08-30 14:24:55 -0700217 CommandDeps: []string{"${config.MergeZipsCmd}"},
218 },
Colin Cross635acc92017-09-12 22:50:46 -0700219 "jarArgs")
Colin Crossc52d5232024-01-10 16:43:33 -0800220 combineJarRsp = pctx.AndroidStaticRule("combineJarRsp",
221 blueprint.RuleParams{
222 Command: `${config.MergeZipsCmd} --ignore-duplicates -j $jarArgs $out @$out.rsp`,
223 CommandDeps: []string{"${config.MergeZipsCmd}"},
224 Rspfile: "$out.rsp",
225 RspfileContent: "$in",
226 },
227 "jarArgs")
Colin Cross2fe66872015-03-30 17:20:39 -0700228
Colin Cross9d45bb72016-08-29 16:14:13 -0700229 jarjar = pctx.AndroidStaticRule("jarjar",
Colin Cross65bf4f22015-04-03 16:54:17 -0700230 blueprint.RuleParams{
Colin Crossd97cf632021-02-08 10:14:04 -0800231 Command: "" +
232 // Jarjar doesn't exit with an error when the rules file contains a syntax error,
233 // leading to stale or missing files later in the build. Remove the output file
234 // before running jarjar.
235 "rm -f ${out} && " +
236 "${config.JavaCmd} ${config.JavaVmFlags}" +
Artur Satayev762d9f32020-04-15 12:50:04 +0100237 // b/146418363 Enable Android specific jarjar transformer to drop compat annotations
238 // for newly repackaged classes. Dropping @UnsupportedAppUsage on repackaged classes
239 // avoids adding new hiddenapis after jarjar'ing.
240 " -DremoveAndroidCompatAnnotations=true" +
Colin Crossd97cf632021-02-08 10:14:04 -0800241 " -jar ${config.JarjarCmd} process $rulesFile $in $out && " +
242 // Turn a missing output file into a ninja error
243 `[ -e ${out} ] || (echo "Missing output file"; exit 1)`,
Colin Cross64162712017-08-08 13:17:59 -0700244 CommandDeps: []string{"${config.JavaCmd}", "${config.JarjarCmd}", "$rulesFile"},
Colin Cross65bf4f22015-04-03 16:54:17 -0700245 },
246 "rulesFile")
Nan Zhang4c819fb2018-08-27 18:31:46 -0700247
Vladimir Marko0975ee02019-04-02 10:29:55 +0100248 packageCheck = pctx.AndroidStaticRule("packageCheck",
249 blueprint.RuleParams{
250 Command: "rm -f $out && " +
251 "${config.PackageCheckCmd} $in $packages && " +
Colin Crossb549b772020-06-03 17:14:31 +0000252 "touch $out",
Vladimir Marko0975ee02019-04-02 10:29:55 +0100253 CommandDeps: []string{"${config.PackageCheckCmd}"},
254 },
255 "packages")
256
Nan Zhang4c819fb2018-08-27 18:31:46 -0700257 jetifier = pctx.AndroidStaticRule("jetifier",
258 blueprint.RuleParams{
Colin Crossdb9f1af2022-12-13 15:57:01 -0800259 Command: "${config.JavaCmd} ${config.JavaVmFlags} -jar ${config.JetifierJar} -l error -o $out -i $in -t epoch",
Nan Zhang4c819fb2018-08-27 18:31:46 -0700260 CommandDeps: []string{"${config.JavaCmd}", "${config.JetifierJar}"},
261 },
262 )
Colin Cross43f08db2018-11-12 10:13:39 -0800263
264 zipalign = pctx.AndroidStaticRule("zipalign",
265 blueprint.RuleParams{
Colin Crosse4246ab2019-02-05 21:55:21 -0800266 Command: "if ! ${config.ZipAlign} -c -p 4 $in > /dev/null; then " +
267 "${config.ZipAlign} -f -p 4 $in $out; " +
Colin Cross43f08db2018-11-12 10:13:39 -0800268 "else " +
269 "cp -f $in $out; " +
270 "fi",
271 CommandDeps: []string{"${config.ZipAlign}"},
272 },
273 )
Cole Faust2f1da162023-04-17 15:06:56 -0700274
Colin Crossf06d8dc2023-07-18 22:11:07 -0700275 convertImplementationJarToHeaderJarRule = pctx.AndroidStaticRule("convertImplementationJarToHeaderJar",
276 blueprint.RuleParams{
277 Command: `${config.Zip2ZipCmd} -i ${in} -o ${out} -x 'META-INF/services/**/*'`,
278 CommandDeps: []string{"${config.Zip2ZipCmd}"},
279 })
Colin Cross312634e2023-11-21 15:13:56 -0800280
281 writeCombinedProguardFlagsFileRule = pctx.AndroidStaticRule("writeCombinedProguardFlagsFileRule",
282 blueprint.RuleParams{
283 Command: `rm -f $out && ` +
284 `for f in $in; do ` +
285 ` echo && ` +
286 ` echo "# including $$f" && ` +
287 ` cat $$f; ` +
288 `done > $out`,
289 })
Jihoon Kang6592e872023-12-19 01:13:16 +0000290
291 gatherReleasedFlaggedApisRule = pctx.AndroidStaticRule("gatherReleasedFlaggedApisRule",
292 blueprint.RuleParams{
Yu Liu748ade22024-02-08 19:11:39 +0000293 Command: `${aconfig} dump-cache --dedup --format='{fully_qualified_name}={state:bool}' ` +
Jihoon Kang6592e872023-12-19 01:13:16 +0000294 `--out ${out} ` +
295 `${flags_path} ` +
296 `${filter_args} `,
297 CommandDeps: []string{"${aconfig}"},
298 Description: "aconfig_bool",
299 }, "flags_path", "filter_args")
300
301 generateMetalavaRevertAnnotationsRule = pctx.AndroidStaticRule("generateMetalavaRevertAnnotationsRule",
302 blueprint.RuleParams{
Jihoon Kang150d87f2024-01-09 19:21:27 +0000303 Command: `${keep-flagged-apis} ${in} > ${out}`,
304 CommandDeps: []string{"${keep-flagged-apis}"},
Jihoon Kang6592e872023-12-19 01:13:16 +0000305 })
Colin Cross2fe66872015-03-30 17:20:39 -0700306)
307
308func init() {
Colin Crosscc0ce802019-04-02 16:14:11 -0700309 pctx.Import("android/soong/android")
Colin Cross64162712017-08-08 13:17:59 -0700310 pctx.Import("android/soong/java/config")
Jihoon Kang6592e872023-12-19 01:13:16 +0000311
312 pctx.HostBinToolVariable("aconfig", "aconfig")
313 pctx.HostBinToolVariable("keep-flagged-apis", "keep-flagged-apis")
Colin Cross2fe66872015-03-30 17:20:39 -0700314}
315
316type javaBuilderFlags struct {
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700317 javacFlags string
318
319 // bootClasspath is the list of jars that form the boot classpath (generally the java.* and
320 // android.* classes) for tools that still use it. javac targeting 1.9 or higher uses
321 // systemModules and java9Classpath instead.
322 bootClasspath classpath
323
324 // classpath is the list of jars that form the classpath for javac and kotlinc rules. It
325 // contains header jars for all static and non-static dependencies.
326 classpath classpath
327
328 // dexClasspath is the list of jars that form the classpath for d8 and r8 rules. It contains
329 // header jars for all non-static dependencies. Static dependencies have already been
330 // combined into the program jar.
331 dexClasspath classpath
332
333 // java9Classpath is the list of jars that will be added to the classpath when targeting
334 // 1.9 or higher. It generally contains the android.* classes, while the java.* classes
335 // are provided by systemModules.
Colin Cross6cef4812019-10-17 14:23:50 -0700336 java9Classpath classpath
Colin Cross9bb9bfb2022-03-17 11:12:32 -0700337
338 processorPath classpath
339 processors []string
340 systemModules *systemModules
341 aidlFlags string
342 aidlDeps android.Paths
343 javaVersion javaVersion
Colin Cross6af17aa2017-09-20 12:59:05 -0700344
Andreas Gampef3e5b552018-01-22 21:27:21 -0800345 errorProneExtraJavacFlags string
Colin Cross66548102018-06-19 22:47:35 -0700346 errorProneProcessorPath classpath
Andreas Gampef3e5b552018-01-22 21:27:21 -0800347
Colin Cross93e85952017-08-15 13:34:18 -0700348 kotlincFlags string
349 kotlincClasspath classpath
Colin Crossa1ff7c62021-09-17 14:11:52 -0700350 kotlincDeps android.Paths
Colin Cross93e85952017-08-15 13:34:18 -0700351
Colin Cross19878da2019-03-28 14:45:07 -0700352 proto android.ProtoFlags
Colin Cross2fe66872015-03-30 17:20:39 -0700353}
354
Joe Onorato175073c2023-06-01 14:42:59 -0700355func DefaultJavaBuilderFlags() javaBuilderFlags {
356 return javaBuilderFlags{
357 javaVersion: JAVA_VERSION_8,
358 }
359}
360
Nan Zhang61eaedb2017-11-02 13:28:15 -0700361func TransformJavaToClasses(ctx android.ModuleContext, outputFile android.WritablePath, shardIdx int,
Vadim Spivak3c496f02023-06-08 06:14:59 +0000362 srcFiles, srcJars android.Paths, annoSrcJar android.WritablePath, flags javaBuilderFlags, deps android.Paths) {
Colin Cross2fe66872015-03-30 17:20:39 -0700363
Nan Zhang61eaedb2017-11-02 13:28:15 -0700364 // Compile java sources into .class files
365 desc := "javac"
366 if shardIdx >= 0 {
367 desc += strconv.Itoa(shardIdx)
368 }
369
Vadim Spivak3c496f02023-06-08 06:14:59 +0000370 transformJavaToClasses(ctx, outputFile, shardIdx, srcFiles, srcJars, annoSrcJar, flags, deps, "javac", desc)
Colin Cross2fe66872015-03-30 17:20:39 -0700371}
372
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800373// Emits the rule to generate Xref input file (.kzip file) for the given set of source files and source jars
374// to compile with given set of builder flags, etc.
Colin Cross3b706fd2019-09-05 16:44:18 -0700375func emitXrefRule(ctx android.ModuleContext, xrefFile android.WritablePath, idx int,
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800376 srcFiles, srcJars android.Paths,
Colin Cross3b706fd2019-09-05 16:44:18 -0700377 flags javaBuilderFlags, deps android.Paths) {
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800378
379 deps = append(deps, srcJars...)
Sasha Smundak09950a42019-11-04 16:29:45 -0800380 classpath := flags.classpath
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800381
382 var bootClasspath string
Colin Cross1e743852019-10-28 11:37:20 -0700383 if flags.javaVersion.usesJavaModules() {
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800384 var systemModuleDeps android.Paths
385 bootClasspath, systemModuleDeps = flags.systemModules.FormJavaSystemModulesPath(ctx.Device())
386 deps = append(deps, systemModuleDeps...)
Sasha Smundak09950a42019-11-04 16:29:45 -0800387 classpath = append(flags.java9Classpath, classpath...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800388 } else {
389 deps = append(deps, flags.bootClasspath...)
390 if len(flags.bootClasspath) == 0 && ctx.Device() {
391 // explicitly specify -bootclasspath "" if the bootclasspath is empty to
392 // ensure java does not fall back to the default bootclasspath.
393 bootClasspath = `-bootclasspath ""`
394 } else {
395 bootClasspath = flags.bootClasspath.FormJavaClassPath("-bootclasspath")
396 }
397 }
398
Sasha Smundak09950a42019-11-04 16:29:45 -0800399 deps = append(deps, classpath...)
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800400 deps = append(deps, flags.processorPath...)
401
402 processor := "-proc:none"
Colin Cross5a116862020-04-22 11:44:34 -0700403 if len(flags.processors) > 0 {
404 processor = "-processor " + strings.Join(flags.processors, ",")
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800405 }
406
Colin Cross3b706fd2019-09-05 16:44:18 -0700407 intermediatesDir := "xref"
408 if idx >= 0 {
409 intermediatesDir += strconv.Itoa(idx)
410 }
411
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800412 ctx.Build(pctx,
413 android.BuildParams{
414 Rule: kytheExtract,
415 Description: "Xref Java extractor",
416 Output: xrefFile,
417 Inputs: srcFiles,
418 Implicits: deps,
419 Args: map[string]string{
420 "annoDir": android.PathForModuleOut(ctx, intermediatesDir, "anno").String(),
421 "bootClasspath": bootClasspath,
Sasha Smundak09950a42019-11-04 16:29:45 -0800422 "classpath": classpath.FormJavaClassPath("-classpath"),
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800423 "javacFlags": flags.javacFlags,
Colin Cross1e743852019-10-28 11:37:20 -0700424 "javaVersion": flags.javaVersion.String(),
Sasha Smundak2a4549e2018-11-05 16:49:08 -0800425 "outDir": android.PathForModuleOut(ctx, "javac", "classes.xref").String(),
426 "processorpath": flags.processorPath.FormJavaClassPath("-processorpath"),
427 "processor": processor,
428 "srcJarDir": android.PathForModuleOut(ctx, intermediatesDir, "srcjars.xref").String(),
429 "srcJars": strings.Join(srcJars.Strings(), " "),
430 },
431 })
432}
433
Colin Crossc52d5232024-01-10 16:43:33 -0800434func turbineFlags(ctx android.ModuleContext, flags javaBuilderFlags, dir string) (string, android.Paths) {
Nan Zhanged19fc32017-10-19 13:06:22 -0700435 var deps android.Paths
Nan Zhanged19fc32017-10-19 13:06:22 -0700436
Colin Cross6cef4812019-10-17 14:23:50 -0700437 classpath := flags.classpath
438
Nan Zhanged19fc32017-10-19 13:06:22 -0700439 var bootClasspath string
Colin Crossbf3119e2019-10-28 14:25:10 -0700440 if flags.javaVersion.usesJavaModules() {
441 var systemModuleDeps android.Paths
442 bootClasspath, systemModuleDeps = flags.systemModules.FormTurbineSystemModulesPath(ctx.Device())
443 deps = append(deps, systemModuleDeps...)
Colin Cross6cef4812019-10-17 14:23:50 -0700444 classpath = append(flags.java9Classpath, classpath...)
Nan Zhanged19fc32017-10-19 13:06:22 -0700445 } else {
Colin Crossbf3119e2019-10-28 14:25:10 -0700446 deps = append(deps, flags.bootClasspath...)
447 if len(flags.bootClasspath) == 0 && ctx.Device() {
448 // explicitly specify -bootclasspath "" if the bootclasspath is empty to
449 // ensure turbine does not fall back to the default bootclasspath.
450 bootClasspath = `--bootclasspath ""`
451 } else {
Colin Crossc2557d12019-10-31 15:22:57 -0700452 bootClasspath = flags.bootClasspath.FormTurbineClassPath("--bootclasspath ")
Colin Crossbf3119e2019-10-28 14:25:10 -0700453 }
Nan Zhanged19fc32017-10-19 13:06:22 -0700454 }
Colin Cross8eadbf02017-10-24 17:46:00 -0700455
Colin Cross6cef4812019-10-17 14:23:50 -0700456 deps = append(deps, classpath...)
Colin Crossf61766e2022-03-16 18:06:48 -0700457 turbineFlags := bootClasspath + " " + classpath.FormTurbineClassPath("--classpath ")
458
Colin Crossc52d5232024-01-10 16:43:33 -0800459 const flagsLimit = 32 * 1024
460 if len(turbineFlags) > flagsLimit {
461 flagsRspFile := android.PathForModuleOut(ctx, dir, "turbine-flags.rsp")
462 android.WriteFileRule(ctx, flagsRspFile, turbineFlags)
463 turbineFlags = "@" + flagsRspFile.String()
464 deps = append(deps, flagsRspFile)
465 }
466
Colin Crossf61766e2022-03-16 18:06:48 -0700467 return turbineFlags, deps
468}
469
470func TransformJavaToHeaderClasses(ctx android.ModuleContext, outputFile android.WritablePath,
471 srcFiles, srcJars android.Paths, flags javaBuilderFlags) {
472
Colin Crossc52d5232024-01-10 16:43:33 -0800473 turbineFlags, deps := turbineFlags(ctx, flags, "turbine")
Colin Crossf61766e2022-03-16 18:06:48 -0700474
475 deps = append(deps, srcJars...)
Colin Crossbf3119e2019-10-28 14:25:10 -0700476
Kousik Kumar1372c1b2020-05-20 07:55:56 -0700477 rule := turbine
478 args := map[string]string{
Colin Crossf61766e2022-03-16 18:06:48 -0700479 "javacFlags": flags.javacFlags,
480 "srcJars": strings.Join(srcJars.Strings(), " "),
481 "javaVersion": flags.javaVersion.String(),
482 "turbineFlags": turbineFlags,
483 "outputFlags": "--output " + outputFile.String() + ".tmp",
484 "outputs": outputFile.String(),
Kousik Kumar1372c1b2020-05-20 07:55:56 -0700485 }
Ramy Medhat16f23a42020-09-03 01:29:49 -0400486 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_TURBINE") {
Kousik Kumar1372c1b2020-05-20 07:55:56 -0700487 rule = turbineRE
488 args["implicits"] = strings.Join(deps.Strings(), ",")
Colin Crossf61766e2022-03-16 18:06:48 -0700489 args["rbeOutputs"] = outputFile.String() + ".tmp"
Kousik Kumar1372c1b2020-05-20 07:55:56 -0700490 }
Colin Crossae887032017-10-23 17:16:14 -0700491 ctx.Build(pctx, android.BuildParams{
Kousik Kumar1372c1b2020-05-20 07:55:56 -0700492 Rule: rule,
Nan Zhanged19fc32017-10-19 13:06:22 -0700493 Description: "turbine",
494 Output: outputFile,
495 Inputs: srcFiles,
496 Implicits: deps,
Kousik Kumar1372c1b2020-05-20 07:55:56 -0700497 Args: args,
Nan Zhanged19fc32017-10-19 13:06:22 -0700498 })
499}
500
Colin Crossf61766e2022-03-16 18:06:48 -0700501// TurbineApt produces a rule to run annotation processors using turbine.
Isaac Chioua23d9942022-04-06 06:14:38 +0000502func TurbineApt(ctx android.ModuleContext, outputSrcJar, outputResJar android.WritablePath,
Colin Crossf61766e2022-03-16 18:06:48 -0700503 srcFiles, srcJars android.Paths, flags javaBuilderFlags) {
504
Colin Crossc52d5232024-01-10 16:43:33 -0800505 turbineFlags, deps := turbineFlags(ctx, flags, "kapt")
Colin Crossf61766e2022-03-16 18:06:48 -0700506
507 deps = append(deps, srcJars...)
508
509 deps = append(deps, flags.processorPath...)
510 turbineFlags += " " + flags.processorPath.FormTurbineClassPath("--processorpath ")
511 turbineFlags += " --processors " + strings.Join(flags.processors, " ")
512
Isaac Chioua23d9942022-04-06 06:14:38 +0000513 outputs := android.WritablePaths{outputSrcJar, outputResJar}
514 outputFlags := "--gensrc_output " + outputSrcJar.String() + ".tmp " +
Colin Crossf61766e2022-03-16 18:06:48 -0700515 "--resource_output " + outputResJar.String() + ".tmp"
516
517 rule := turbine
518 args := map[string]string{
519 "javacFlags": flags.javacFlags,
520 "srcJars": strings.Join(srcJars.Strings(), " "),
521 "javaVersion": flags.javaVersion.String(),
522 "turbineFlags": turbineFlags,
523 "outputFlags": outputFlags,
524 "outputs": strings.Join(outputs.Strings(), " "),
525 }
526 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_TURBINE") {
527 rule = turbineRE
528 args["implicits"] = strings.Join(deps.Strings(), ",")
Isaac Chioua23d9942022-04-06 06:14:38 +0000529 args["rbeOutputs"] = outputSrcJar.String() + ".tmp," + outputResJar.String() + ".tmp"
Colin Crossf61766e2022-03-16 18:06:48 -0700530 }
531 ctx.Build(pctx, android.BuildParams{
532 Rule: rule,
533 Description: "turbine apt",
534 Output: outputs[0],
535 ImplicitOutputs: outputs[1:],
536 Inputs: srcFiles,
537 Implicits: deps,
538 Args: args,
539 })
540}
541
Colin Cross070879e2017-10-11 11:21:07 -0700542// transformJavaToClasses takes source files and converts them to a jar containing .class files.
Colin Cross59149b62017-10-16 18:07:29 -0700543// srcFiles is a list of paths to sources, srcJars is a list of paths to jar files that contain
544// sources. flags contains various command line flags to be passed to the compiler.
Colin Cross070879e2017-10-11 11:21:07 -0700545//
546// This method may be used for different compilers, including javac and Error Prone. The rule
547// argument specifies which command line to use and desc sets the description of the rule that will
548// be printed at build time. The stem argument provides the file name of the output jar, and
549// suffix will be appended to various intermediate files and directories to avoid collisions when
550// this function is called twice in the same module directory.
Colin Crosse9a275b2017-10-16 17:09:48 -0700551func transformJavaToClasses(ctx android.ModuleContext, outputFile android.WritablePath,
Vadim Spivak3c496f02023-06-08 06:14:59 +0000552 shardIdx int, srcFiles, srcJars android.Paths, annoSrcJar android.WritablePath,
Colin Crosse9a275b2017-10-16 17:09:48 -0700553 flags javaBuilderFlags, deps android.Paths,
Colin Cross66548102018-06-19 22:47:35 -0700554 intermediatesDir, desc string) {
Colin Crossc6bbef32017-08-14 14:16:06 -0700555
Colin Cross59149b62017-10-16 18:07:29 -0700556 deps = append(deps, srcJars...)
Colin Cross1369cdb2017-09-29 17:58:17 -0700557
Colin Crossc52d5232024-01-10 16:43:33 -0800558 javacClasspath := flags.classpath
Colin Cross6cef4812019-10-17 14:23:50 -0700559
Colin Cross1369cdb2017-09-29 17:58:17 -0700560 var bootClasspath string
Colin Cross1e743852019-10-28 11:37:20 -0700561 if flags.javaVersion.usesJavaModules() {
Colin Crossb77043e2019-07-16 13:57:13 -0700562 var systemModuleDeps android.Paths
563 bootClasspath, systemModuleDeps = flags.systemModules.FormJavaSystemModulesPath(ctx.Device())
564 deps = append(deps, systemModuleDeps...)
Colin Crossc52d5232024-01-10 16:43:33 -0800565 javacClasspath = append(flags.java9Classpath, javacClasspath...)
Colin Cross1369cdb2017-09-29 17:58:17 -0700566 } else {
567 deps = append(deps, flags.bootClasspath...)
Nan Zhanged19fc32017-10-19 13:06:22 -0700568 if len(flags.bootClasspath) == 0 && ctx.Device() {
569 // explicitly specify -bootclasspath "" if the bootclasspath is empty to
570 // ensure java does not fall back to the default bootclasspath.
571 bootClasspath = `-bootclasspath ""`
572 } else {
573 bootClasspath = flags.bootClasspath.FormJavaClassPath("-bootclasspath")
574 }
Colin Cross1369cdb2017-09-29 17:58:17 -0700575 }
576
Colin Crossc52d5232024-01-10 16:43:33 -0800577 classpathArg := javacClasspath.FormJavaClassPath("-classpath")
578
579 // Keep the command line under the MAX_ARG_STRLEN limit by putting the classpath argument into an rsp file
580 // if it is too long.
581 const classpathLimit = 64 * 1024
582 if len(classpathArg) > classpathLimit {
583 classpathRspFile := outputFile.ReplaceExtension(ctx, "classpath")
584 android.WriteFileRule(ctx, classpathRspFile, classpathArg)
585 deps = append(deps, classpathRspFile)
586 classpathArg = "@" + classpathRspFile.String()
587 }
588
589 deps = append(deps, javacClasspath...)
Colin Cross6a77c982018-06-19 22:43:34 -0700590 deps = append(deps, flags.processorPath...)
Colin Crossc6bbef32017-08-14 14:16:06 -0700591
Colin Cross7788c122019-01-23 16:14:02 -0800592 processor := "-proc:none"
Colin Cross5a116862020-04-22 11:44:34 -0700593 if len(flags.processors) > 0 {
594 processor = "-processor " + strings.Join(flags.processors, ",")
Colin Crossbe9cdb82019-01-21 21:37:16 -0800595 }
596
Nan Zhang61eaedb2017-11-02 13:28:15 -0700597 srcJarDir := "srcjars"
598 outDir := "classes"
599 annoDir := "anno"
600 if shardIdx >= 0 {
601 shardDir := "shard" + strconv.Itoa(shardIdx)
602 srcJarDir = filepath.Join(shardDir, srcJarDir)
603 outDir = filepath.Join(shardDir, outDir)
604 annoDir = filepath.Join(shardDir, annoDir)
605 }
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400606 rule := javac
Spandan Daseaa47512024-04-09 21:30:12 +0000607 args := map[string]string{
608 "javacFlags": flags.javacFlags,
609 "bootClasspath": bootClasspath,
610 "classpath": classpathArg,
611 "processorpath": flags.processorPath.FormJavaClassPath("-processorpath"),
612 "processor": processor,
613 "srcJars": strings.Join(srcJars.Strings(), " "),
614 "srcJarDir": android.PathForModuleOut(ctx, intermediatesDir, srcJarDir).String(),
615 "outDir": android.PathForModuleOut(ctx, intermediatesDir, outDir).String(),
616 "annoDir": android.PathForModuleOut(ctx, intermediatesDir, annoDir).String(),
617 "annoSrcJar": annoSrcJar.String(),
618 "javaVersion": flags.javaVersion.String(),
619 }
620
Ramy Medhat16f23a42020-09-03 01:29:49 -0400621 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_JAVAC") {
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400622 rule = javacRE
Spandan Daseaa47512024-04-09 21:30:12 +0000623
624 // Write the classpath deps to a file that can be passed as an input to javacRE.
625 // Skip the shardIdx if the java library is unsharded
626 shardIdxSuffix := strconv.Itoa(shardIdx)
627 if shardIdx == -1 {
628 shardIdxSuffix = ""
629 }
630 javacREClasspathDepsFile := outputFile.ReplaceExtension(ctx, fmt.Sprintf("javacre.classpathdeps%v", shardIdxSuffix))
631 android.WriteFileRule(ctx, javacREClasspathDepsFile, strings.Join(javacClasspath.Strings(), ",")) // The classpath jars are an implicit dep of javacRE
632 args["javacREClasspathDeps"] = javacREClasspathDepsFile.String()
633
634 // Add the deps file to the implicit inputs
635 deps = append(deps, javacREClasspathDepsFile)
Ramy Medhat1dcc27e2020-04-21 21:36:23 -0400636 }
Colin Crossae887032017-10-23 17:16:14 -0700637 ctx.Build(pctx, android.BuildParams{
Vadim Spivak3c496f02023-06-08 06:14:59 +0000638 Rule: rule,
639 Description: desc,
640 Output: outputFile,
641 ImplicitOutput: annoSrcJar,
642 Inputs: srcFiles,
643 Implicits: deps,
Spandan Daseaa47512024-04-09 21:30:12 +0000644 Args: args,
Colin Crossc6bbef32017-08-14 14:16:06 -0700645 })
Colin Crossc6bbef32017-08-14 14:16:06 -0700646}
647
Colin Crosse9a275b2017-10-16 17:09:48 -0700648func TransformResourcesToJar(ctx android.ModuleContext, outputFile android.WritablePath,
649 jarArgs []string, deps android.Paths) {
Colin Cross2fe66872015-03-30 17:20:39 -0700650
Kousik Kumar366afc52020-05-20 11:27:16 -0700651 rule := jar
Ramy Medhat16f23a42020-09-03 01:29:49 -0400652 if ctx.Config().UseRBE() && ctx.Config().IsEnvTrue("RBE_JAR") {
Kousik Kumar366afc52020-05-20 11:27:16 -0700653 rule = jarRE
654 }
Colin Crossae887032017-10-23 17:16:14 -0700655 ctx.Build(pctx, android.BuildParams{
Kousik Kumar366afc52020-05-20 11:27:16 -0700656 Rule: rule,
Colin Cross67a5c132017-05-09 13:45:28 -0700657 Description: "jar",
658 Output: outputFile,
659 Implicits: deps,
Colin Cross2fe66872015-03-30 17:20:39 -0700660 Args: map[string]string{
Colin Cross0b9f31f2019-02-28 11:00:01 -0800661 "jarArgs": strings.Join(proptools.NinjaAndShellEscapeList(jarArgs), " "),
Colin Cross2fe66872015-03-30 17:20:39 -0700662 },
663 })
Colin Cross2fe66872015-03-30 17:20:39 -0700664}
665
Nan Zhanged19fc32017-10-19 13:06:22 -0700666func TransformJarsToJar(ctx android.ModuleContext, outputFile android.WritablePath, desc string,
Colin Cross37f6d792018-07-12 12:28:41 -0700667 jars android.Paths, manifest android.OptionalPath, stripDirEntries bool, filesToStrip []string,
668 dirsToStrip []string) {
Colin Cross0a6e0072017-08-30 14:24:55 -0700669
Colin Cross635acc92017-09-12 22:50:46 -0700670 var deps android.Paths
671
672 var jarArgs []string
673 if manifest.Valid() {
Nan Zhanged19fc32017-10-19 13:06:22 -0700674 jarArgs = append(jarArgs, "-m ", manifest.String())
Colin Cross635acc92017-09-12 22:50:46 -0700675 deps = append(deps, manifest.Path())
676 }
677
Colin Cross37f6d792018-07-12 12:28:41 -0700678 for _, dir := range dirsToStrip {
679 jarArgs = append(jarArgs, "-stripDir ", dir)
680 }
681
682 for _, file := range filesToStrip {
683 jarArgs = append(jarArgs, "-stripFile ", file)
Nan Zhanged19fc32017-10-19 13:06:22 -0700684 }
685
Colin Cross7b60cdd2017-12-21 13:52:58 -0800686 // Remove any module-info.class files that may have come from prebuilt jars, they cause problems
687 // for downstream tools like desugar.
688 jarArgs = append(jarArgs, "-stripFile module-info.class")
689
Colin Cross37f6d792018-07-12 12:28:41 -0700690 if stripDirEntries {
Colin Cross635acc92017-09-12 22:50:46 -0700691 jarArgs = append(jarArgs, "-D")
692 }
693
Colin Crossc52d5232024-01-10 16:43:33 -0800694 rule := combineJar
695 // Keep the command line under the MAX_ARG_STRLEN limit by putting the list of jars into an rsp file
696 // if it is too long.
697 const jarsLengthLimit = 64 * 1024
698 jarsLength := 0
699 for i, jar := range jars {
700 if i != 0 {
701 jarsLength += 1
702 }
703 jarsLength += len(jar.String())
704 }
705 if jarsLength > jarsLengthLimit {
706 rule = combineJarRsp
707 }
708
Colin Crossae887032017-10-23 17:16:14 -0700709 ctx.Build(pctx, android.BuildParams{
Colin Crossc52d5232024-01-10 16:43:33 -0800710 Rule: rule,
Nan Zhanged19fc32017-10-19 13:06:22 -0700711 Description: desc,
Colin Cross0a6e0072017-08-30 14:24:55 -0700712 Output: outputFile,
713 Inputs: jars,
Colin Cross635acc92017-09-12 22:50:46 -0700714 Implicits: deps,
715 Args: map[string]string{
716 "jarArgs": strings.Join(jarArgs, " "),
717 },
Colin Cross0a6e0072017-08-30 14:24:55 -0700718 })
Colin Cross0a6e0072017-08-30 14:24:55 -0700719}
720
Colin Crossf06d8dc2023-07-18 22:11:07 -0700721func convertImplementationJarToHeaderJar(ctx android.ModuleContext, implementationJarFile android.Path,
722 headerJarFile android.WritablePath) {
723 ctx.Build(pctx, android.BuildParams{
724 Rule: convertImplementationJarToHeaderJarRule,
725 Input: implementationJarFile,
726 Output: headerJarFile,
727 })
728}
729
Colin Crosse9a275b2017-10-16 17:09:48 -0700730func TransformJarJar(ctx android.ModuleContext, outputFile android.WritablePath,
731 classesJar android.Path, rulesFile android.Path) {
Colin Crossae887032017-10-23 17:16:14 -0700732 ctx.Build(pctx, android.BuildParams{
Colin Cross67a5c132017-05-09 13:45:28 -0700733 Rule: jarjar,
734 Description: "jarjar",
735 Output: outputFile,
736 Input: classesJar,
737 Implicit: rulesFile,
Colin Cross65bf4f22015-04-03 16:54:17 -0700738 Args: map[string]string{
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700739 "rulesFile": rulesFile.String(),
Colin Cross65bf4f22015-04-03 16:54:17 -0700740 },
741 })
Colin Cross65bf4f22015-04-03 16:54:17 -0700742}
Colin Cross6ade34f2017-09-15 13:00:47 -0700743
Colin Crossb549b772020-06-03 17:14:31 +0000744func CheckJarPackages(ctx android.ModuleContext, outputFile android.WritablePath,
745 classesJar android.Path, permittedPackages []string) {
Vladimir Marko0975ee02019-04-02 10:29:55 +0100746 ctx.Build(pctx, android.BuildParams{
747 Rule: packageCheck,
748 Description: "packageCheck",
749 Output: outputFile,
750 Input: classesJar,
751 Args: map[string]string{
752 "packages": strings.Join(permittedPackages, " "),
753 },
754 })
755}
756
Nan Zhang4c819fb2018-08-27 18:31:46 -0700757func TransformJetifier(ctx android.ModuleContext, outputFile android.WritablePath,
758 inputFile android.Path) {
759 ctx.Build(pctx, android.BuildParams{
760 Rule: jetifier,
761 Description: "jetifier",
762 Output: outputFile,
763 Input: inputFile,
764 })
765}
766
Colin Cross094054a2018-10-17 15:10:48 -0700767func GenerateMainClassManifest(ctx android.ModuleContext, outputFile android.WritablePath, mainClass string) {
Colin Crosscf371cc2020-11-13 11:48:42 -0800768 android.WriteFileRule(ctx, outputFile, "Main-Class: "+mainClass+"\n")
Colin Cross094054a2018-10-17 15:10:48 -0700769}
770
Cole Faust61585282023-07-14 16:23:39 -0700771func TransformZipAlign(ctx android.ModuleContext, outputFile android.WritablePath, inputFile android.Path, validations android.Paths) {
Colin Cross43f08db2018-11-12 10:13:39 -0800772 ctx.Build(pctx, android.BuildParams{
773 Rule: zipalign,
774 Description: "align",
775 Input: inputFile,
776 Output: outputFile,
Cole Faust61585282023-07-14 16:23:39 -0700777 Validations: validations,
Colin Cross43f08db2018-11-12 10:13:39 -0800778 })
779}
780
Colin Cross312634e2023-11-21 15:13:56 -0800781func writeCombinedProguardFlagsFile(ctx android.ModuleContext, outputFile android.WritablePath, files android.Paths) {
782 ctx.Build(pctx, android.BuildParams{
783 Rule: writeCombinedProguardFlagsFileRule,
784 Description: "write combined proguard flags file",
785 Inputs: files,
786 Output: outputFile,
787 })
788}
789
Colin Cross33961b52019-07-11 11:01:22 -0700790type classpath android.Paths
Colin Cross6ade34f2017-09-15 13:00:47 -0700791
Colin Crossc2557d12019-10-31 15:22:57 -0700792func (x *classpath) formJoinedClassPath(optName string, sep string) string {
Colin Cross81440082018-08-15 20:21:55 -0700793 if optName != "" && !strings.HasSuffix(optName, "=") && !strings.HasSuffix(optName, " ") {
794 optName += " "
795 }
Colin Cross59149b62017-10-16 18:07:29 -0700796 if len(*x) > 0 {
Colin Crossc2557d12019-10-31 15:22:57 -0700797 return optName + strings.Join(x.Strings(), sep)
Colin Cross6ade34f2017-09-15 13:00:47 -0700798 } else {
799 return ""
800 }
801}
Colin Crossc2557d12019-10-31 15:22:57 -0700802func (x *classpath) FormJavaClassPath(optName string) string {
803 return x.formJoinedClassPath(optName, ":")
804}
Colin Cross6ade34f2017-09-15 13:00:47 -0700805
Colin Crossc2557d12019-10-31 15:22:57 -0700806func (x *classpath) FormTurbineClassPath(optName string) string {
807 return x.formJoinedClassPath(optName, " ")
808}
809
810// FormRepeatedClassPath returns a list of arguments with the given optName prefixed to each element of the classpath.
811func (x *classpath) FormRepeatedClassPath(optName string) []string {
Colin Cross6ade34f2017-09-15 13:00:47 -0700812 if x == nil || *x == nil {
813 return nil
814 }
815 flags := make([]string, len(*x))
816 for i, v := range *x {
Colin Crossafbb1732019-01-17 15:42:52 -0800817 flags[i] = optName + v.String()
Colin Cross6ade34f2017-09-15 13:00:47 -0700818 }
819
820 return flags
821}
822
Colin Cross6ade34f2017-09-15 13:00:47 -0700823// Convert a classpath to an android.Paths
824func (x *classpath) Paths() android.Paths {
825 return append(android.Paths(nil), (*x)...)
826}
827
828func (x *classpath) Strings() []string {
829 if x == nil {
830 return nil
831 }
832 ret := make([]string, len(*x))
833 for i, path := range *x {
834 ret[i] = path.String()
835 }
836 return ret
837}
Colin Crossb77043e2019-07-16 13:57:13 -0700838
839type systemModules struct {
840 dir android.Path
841 deps android.Paths
842}
843
Colin Crossbf3119e2019-10-28 14:25:10 -0700844// Returns a --system argument in the form javac expects with -source 1.9 and the list of files to
845// depend on. If forceEmpty is true, returns --system=none if the list is empty to ensure javac
846// does not fall back to the default system modules.
Colin Crossb77043e2019-07-16 13:57:13 -0700847func (x *systemModules) FormJavaSystemModulesPath(forceEmpty bool) (string, android.Paths) {
848 if x != nil {
849 return "--system=" + x.dir.String(), x.deps
850 } else if forceEmpty {
851 return "--system=none", nil
852 } else {
853 return "", nil
854 }
855}
Colin Crossbf3119e2019-10-28 14:25:10 -0700856
857// Returns a --system argument in the form turbine expects with -source 1.9 and the list of files to
858// depend on. If forceEmpty is true, returns --bootclasspath "" if the list is empty to ensure turbine
859// does not fall back to the default bootclasspath.
860func (x *systemModules) FormTurbineSystemModulesPath(forceEmpty bool) (string, android.Paths) {
861 if x != nil {
862 return "--system " + x.dir.String(), x.deps
863 } else if forceEmpty {
864 return `--bootclasspath ""`, nil
865 } else {
Colin Crossf61766e2022-03-16 18:06:48 -0700866 return "--system ${config.JavaHome}", nil
Colin Crossbf3119e2019-10-28 14:25:10 -0700867 }
868}