• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2022 The Bazel Authors. 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
15"""Rules for defining default_java_toolchain"""
16
17load("//java:defs.bzl", "java_toolchain")
18
19# JVM options, without patching java.compiler and jdk.compiler modules.
20BASE_JDK9_JVM_OPTS = [
21    # Allow JavaBuilder to access internal javac APIs.
22    "--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED",
23    "--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED",
24    "--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED",
25    "--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED",
26    "--add-exports=jdk.compiler/com.sun.tools.javac.resources=ALL-UNNAMED",
27    "--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED",
28    "--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED",
29    "--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED",
30    "--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED",
31    "--add-opens=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED",
32    "--add-opens=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED",
33
34    # quiet warnings from com.google.protobuf.UnsafeUtil,
35    # see: https://github.com/google/protobuf/issues/3781
36    # and: https://github.com/bazelbuild/bazel/issues/5599
37    "--add-opens=java.base/java.nio=ALL-UNNAMED",
38    "--add-opens=java.base/java.lang=ALL-UNNAMED",
39
40    # TODO(b/64485048): Disable this option in persistent worker mode only.
41    # Disable symlinks resolution cache since symlinks in exec root change
42    "-Dsun.io.useCanonCaches=false",
43
44    # Compact strings make JavaBuilder slightly slower.
45    "-XX:-CompactStrings",
46
47    # Since https://bugs.openjdk.org/browse/JDK-8153723, JVM logging goes to stdout. This
48    # makes it go to stderr instead.
49    "-Xlog:disable",
50    "-Xlog:all=warning:stderr:uptime,level,tags",
51]
52
53JDK9_JVM_OPTS = BASE_JDK9_JVM_OPTS
54
55DEFAULT_JAVACOPTS = [
56    "-XDskipDuplicateBridges=true",
57    "-XDcompilePolicy=simple",
58    "-g",
59    "-parameters",
60    # https://github.com/bazelbuild/bazel/issues/15219
61    "-Xep:ReturnValueIgnored:OFF",
62    # https://github.com/bazelbuild/bazel/issues/16996
63    "-Xep:IgnoredPureGetter:OFF",
64    "-Xep:EmptyTopLevelDeclaration:OFF",
65    "-Xep:LenientFormatStringValidation:OFF",
66    "-Xep:ReturnMissingNullable:OFF",
67]
68
69# Default java_toolchain parameters
70_BASE_TOOLCHAIN_CONFIGURATION = dict(
71    forcibly_disable_header_compilation = False,
72    genclass = [Label("@remote_java_tools//:GenClass")],
73    header_compiler = [Label("@remote_java_tools//:TurbineDirect")],
74    header_compiler_direct = [Label("@remote_java_tools//:TurbineDirect")],
75    ijar = [Label("//toolchains:ijar")],
76    javabuilder = [Label("@remote_java_tools//:JavaBuilder")],
77    javac_supports_workers = True,
78    jacocorunner = Label("@remote_java_tools//:jacoco_coverage_runner_filegroup"),
79    jvm_opts = BASE_JDK9_JVM_OPTS,
80    turbine_jvm_opts = [
81        # Turbine is not a worker and parallel GC is faster for short-lived programs.
82        "-XX:+UseParallelGC",
83    ],
84    misc = DEFAULT_JAVACOPTS,
85    singlejar = [Label("//toolchains:singlejar")],
86    # Code to enumerate target JVM boot classpath uses host JVM. Because
87    # java_runtime-s are involved, its implementation is in @bazel_tools.
88    bootclasspath = [Label("//toolchains:platformclasspath")],
89    source_version = "8",
90    target_version = "8",
91    reduced_classpath_incompatible_processors = [
92        "dagger.hilt.processor.internal.root.RootProcessor",  # see b/21307381
93    ],
94    java_runtime = Label("//toolchains:remotejdk_17"),
95)
96
97DEFAULT_TOOLCHAIN_CONFIGURATION = _BASE_TOOLCHAIN_CONFIGURATION
98
99# The 'vanilla' toolchain is an unsupported alternative to the default.
100#
101# It does not provide any of the following features:
102#   * Error Prone
103#   * Strict Java Deps
104#   * Reduced Classpath Optimization
105#
106# It uses the version of internal javac from the `--host_javabase` JDK instead
107# of providing a javac. Internal javac may not be source- or bug-compatible with
108# the javac that is provided with other toolchains.
109#
110# However it does allow using a wider range of `--host_javabase`s, including
111# versions newer than the current JDK.
112VANILLA_TOOLCHAIN_CONFIGURATION = dict(
113    javabuilder = [Label("@remote_java_tools//:VanillaJavaBuilder")],
114    jvm_opts = [],
115    java_runtime = None,
116)
117
118# The new toolchain is using all the pre-built tools, including
119# singlejar and ijar, even on remote execution. This toolchain
120# should be used only when host and execution platform are the
121# same, otherwise the binaries will not work on the execution
122# platform.
123PREBUILT_TOOLCHAIN_CONFIGURATION = dict(
124    ijar = [Label("//toolchains:ijar_prebuilt_binary")],
125    singlejar = [Label("//toolchains:prebuilt_singlejar")],
126)
127
128# The new toolchain is using all the tools from sources.
129NONPREBUILT_TOOLCHAIN_CONFIGURATION = dict(
130    ijar = [Label("@remote_java_tools//:ijar_cc_binary")],
131    singlejar = [Label("@remote_java_tools//:singlejar_cc_bin")],
132)
133
134_DEFAULT_SOURCE_VERSION = "8"
135
136def default_java_toolchain(name, configuration = DEFAULT_TOOLCHAIN_CONFIGURATION, toolchain_definition = True, exec_compatible_with = [], target_compatible_with = [], **kwargs):
137    """Defines a remote java_toolchain with appropriate defaults for Bazel.
138
139    Args:
140        name: The name of the toolchain
141        configuration: Toolchain configuration
142        toolchain_definition: Whether to define toolchain target and its config setting
143        exec_compatible_with: A list of constraint values that must be
144            satisifed for the exec platform.
145        target_compatible_with: A list of constraint values that must be
146            satisifed for the target platform.
147        **kwargs: More arguments for the java_toolchain target
148    """
149
150    toolchain_args = dict(_BASE_TOOLCHAIN_CONFIGURATION)
151    toolchain_args.update(configuration)
152    toolchain_args.update(kwargs)
153    java_toolchain(
154        name = name,
155        **toolchain_args
156    )
157    if toolchain_definition:
158        source_version = toolchain_args["source_version"]
159        if source_version == _DEFAULT_SOURCE_VERSION:
160            native.config_setting(
161                name = name + "_default_version_setting",
162                values = {"java_language_version": ""},
163                visibility = ["//visibility:private"],
164            )
165            native.toolchain(
166                name = name + "_default_definition",
167                toolchain_type = Label("@bazel_tools//tools/jdk:toolchain_type"),
168                target_settings = [name + "_default_version_setting"],
169                toolchain = name,
170                exec_compatible_with = exec_compatible_with,
171                target_compatible_with = target_compatible_with,
172            )
173
174        native.config_setting(
175            name = name + "_version_setting",
176            values = {"java_language_version": source_version},
177            visibility = ["//visibility:private"],
178        )
179        native.toolchain(
180            name = name + "_definition",
181            toolchain_type = Label("@bazel_tools//tools/jdk:toolchain_type"),
182            target_settings = [name + "_version_setting"],
183            toolchain = name,
184            exec_compatible_with = exec_compatible_with,
185            target_compatible_with = target_compatible_with,
186        )
187
188def java_runtime_files(name, srcs):
189    """Copies the given sources out of the current Java runtime."""
190
191    native.filegroup(
192        name = name,
193        srcs = srcs,
194        tags = ["manual"],
195    )
196    for src in srcs:
197        native.genrule(
198            name = "gen_%s" % src,
199            srcs = [Label("//toolchains:current_java_runtime")],
200            toolchains = [Label("//toolchains:current_java_runtime")],
201            cmd = "cp $(JAVABASE)/%s $@" % src,
202            outs = [src],
203            tags = ["manual"],
204        )
205
206def _bootclasspath_impl(ctx):
207    host_javabase = ctx.attr.host_javabase[java_common.JavaRuntimeInfo]
208
209    class_dir = ctx.actions.declare_directory("%s_classes" % ctx.label.name)
210
211    args = ctx.actions.args()
212    args.add("-source")
213    args.add("8")
214    args.add("-target")
215    args.add("8")
216    args.add("-Xlint:-options")
217    args.add("-d")
218    args.add_all([class_dir], expand_directories = False)
219    args.add(ctx.file.src)
220
221    ctx.actions.run(
222        executable = "%s/bin/javac" % host_javabase.java_home,
223        mnemonic = "JavaToolchainCompileClasses",
224        inputs = [ctx.file.src] + ctx.files.host_javabase,
225        outputs = [class_dir],
226        arguments = [args],
227    )
228
229    bootclasspath = ctx.outputs.output_jar
230
231    inputs = [class_dir] + ctx.files.host_javabase
232
233    args = ctx.actions.args()
234    args.add("-XX:+IgnoreUnrecognizedVMOptions")
235    args.add("--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED")
236    args.add("--add-exports=jdk.compiler/com.sun.tools.javac.platform=ALL-UNNAMED")
237    args.add("--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED")
238    args.add_all("-cp", [class_dir], expand_directories = False)
239    args.add("DumpPlatformClassPath")
240    args.add(bootclasspath)
241
242    system_files = ("release", "modules", "jrt-fs.jar")
243    system = [f for f in ctx.files.target_javabase if f.basename in system_files]
244    if len(system) != len(system_files):
245        system = None
246    if ctx.attr.target_javabase:
247        inputs.extend(ctx.files.target_javabase)
248        args.add(ctx.attr.target_javabase[java_common.JavaRuntimeInfo].java_home)
249
250    ctx.actions.run(
251        executable = str(host_javabase.java_executable_exec_path),
252        mnemonic = "JavaToolchainCompileBootClasspath",
253        inputs = inputs,
254        outputs = [bootclasspath],
255        arguments = [args],
256    )
257    return [
258        DefaultInfo(files = depset([bootclasspath])),
259        java_common.BootClassPathInfo(
260            bootclasspath = [bootclasspath],
261            system = system,
262        ),
263        OutputGroupInfo(jar = [bootclasspath]),
264    ]
265
266_bootclasspath = rule(
267    implementation = _bootclasspath_impl,
268    attrs = {
269        "host_javabase": attr.label(
270            cfg = "exec",
271            providers = [java_common.JavaRuntimeInfo],
272        ),
273        "output_jar": attr.output(mandatory = True),
274        "src": attr.label(
275            cfg = "exec",
276            allow_single_file = True,
277        ),
278        "target_javabase": attr.label(
279            providers = [java_common.JavaRuntimeInfo],
280        ),
281    },
282)
283
284def bootclasspath(name, **kwargs):
285    _bootclasspath(
286        name = name,
287        output_jar = name + ".jar",
288        **kwargs
289    )
290