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