use of com.google.devtools.build.lib.analysis.RunfilesSupport in project bazel by bazelbuild.
the class ShBinary method create.
@Override
public ConfiguredTarget create(RuleContext ruleContext) throws RuleErrorException {
ImmutableList<Artifact> srcs = ruleContext.getPrerequisiteArtifacts("srcs", Mode.TARGET).list();
if (srcs.size() != 1) {
ruleContext.attributeError("srcs", "you must specify exactly one file in 'srcs'");
return null;
}
Artifact symlink = ruleContext.createOutputArtifact();
// Note that src is used as the executable script too
Artifact src = srcs.get(0);
// The interpretation of this deceptively simple yet incredibly generic rule is complicated
// by the distinction between targets and (not properly encapsulated) artifacts. It depends
// on the notion of other rule's "files-to-build" sets, which are undocumented, making it
// impossible to give a precise definition of what this rule does in all cases (e.g. what
// happens when srcs = ['x', 'y'] but 'x' is an empty filegroup?). This is a pervasive
// problem in Blaze.
ruleContext.registerAction(new ExecutableSymlinkAction(ruleContext.getActionOwner(), src, symlink));
NestedSet<Artifact> filesToBuild = NestedSetBuilder.<Artifact>stableOrder().add(src).add(symlink).build();
Runfiles runfiles = new Runfiles.Builder(ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles()).addTransitiveArtifacts(filesToBuild).addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES).build();
RunfilesSupport runfilesSupport = RunfilesSupport.withExecutable(ruleContext, runfiles, symlink);
return new RuleConfiguredTargetBuilder(ruleContext).setFilesToBuild(filesToBuild).setRunfilesSupport(runfilesSupport, symlink).addProvider(RunfilesProvider.class, RunfilesProvider.simple(runfiles)).build();
}
use of com.google.devtools.build.lib.analysis.RunfilesSupport in project bazel by bazelbuild.
the class CcBinary method init.
public static ConfiguredTarget init(CppSemantics semantics, RuleContext ruleContext, boolean fake) throws InterruptedException, RuleErrorException {
ruleContext.checkSrcsSamePackage(true);
CcCommon common = new CcCommon(ruleContext);
CcToolchainProvider ccToolchain = common.getToolchain();
FdoSupportProvider fdoSupport = common.getFdoSupport();
FeatureConfiguration featureConfiguration = CcCommon.configureFeatures(ruleContext, ccToolchain);
CppConfiguration cppConfiguration = ruleContext.getFragment(CppConfiguration.class);
PrecompiledFiles precompiledFiles = new PrecompiledFiles(ruleContext);
LinkTargetType linkType = isLinkShared(ruleContext) ? LinkTargetType.DYNAMIC_LIBRARY : LinkTargetType.EXECUTABLE;
semantics.validateAttributes(ruleContext);
if (ruleContext.hasErrors()) {
return null;
}
List<String> linkopts = common.getLinkopts();
LinkStaticness linkStaticness = getLinkStaticness(ruleContext, linkopts, cppConfiguration);
// We currently only want link the dynamic library generated for test code separately.
boolean linkCompileOutputSeparately = ruleContext.isTestTarget() && cppConfiguration.getLinkCompileOutputSeparately() && linkStaticness == LinkStaticness.DYNAMIC;
CcLibraryHelper helper = new CcLibraryHelper(ruleContext, semantics, featureConfiguration, ccToolchain, fdoSupport).fromCommon(common).addSources(common.getSources()).addDeps(ImmutableList.of(CppHelper.mallocForTarget(ruleContext))).setFake(fake).addPrecompiledFiles(precompiledFiles).enableInterfaceSharedObjects();
// When linking the object files directly into the resulting binary, we do not need
// library-level link outputs; thus, we do not let CcLibraryHelper produce link outputs
// (either shared object files or archives) for a non-library link type [*], and add
// the object files explicitly in determineLinkerArguments.
//
// When linking the object files into their own library, we want CcLibraryHelper to
// take care of creating the library link outputs for us, so we need to set the link
// type to STATIC_LIBRARY.
//
// [*] The only library link type is STATIC_LIBRARY. EXECUTABLE specifies a normal
// cc_binary output, while DYNAMIC_LIBRARY is a cc_binary rules that produces an
// output matching a shared object, for example cc_binary(name="foo.so", ...) on linux.
helper.setLinkType(linkCompileOutputSeparately ? LinkTargetType.STATIC_LIBRARY : linkType);
CcLibraryHelper.Info info = helper.build();
CppCompilationContext cppCompilationContext = info.getCppCompilationContext();
CcCompilationOutputs ccCompilationOutputs = info.getCcCompilationOutputs();
// if cc_binary includes "linkshared=1", then gcc will be invoked with
// linkopt "-shared", which causes the result of linking to be a shared
// library. In this case, the name of the executable target should end
// in ".so" or "dylib" or ".dll".
PathFragment binaryPath = new PathFragment(ruleContext.getTarget().getName());
if (!isLinkShared(ruleContext)) {
binaryPath = new PathFragment(binaryPath.getPathString() + OsUtils.executableExtension());
}
Artifact binary = ruleContext.getBinArtifact(binaryPath);
if (isLinkShared(ruleContext) && !CppFileTypes.SHARED_LIBRARY.matches(binary.getFilename()) && !CppFileTypes.VERSIONED_SHARED_LIBRARY.matches(binary.getFilename())) {
ruleContext.attributeError("linkshared", "'linkshared' used in non-shared library");
return null;
}
CppLinkActionBuilder linkActionBuilder = determineLinkerArguments(ruleContext, ccToolchain, fdoSupport, common, precompiledFiles, info, cppCompilationContext.getTransitiveCompilationPrerequisites(), fake, binary, linkStaticness, linkopts, linkCompileOutputSeparately);
linkActionBuilder.setUseTestOnlyFlags(ruleContext.isTestTarget());
if (linkStaticness == LinkStaticness.DYNAMIC) {
linkActionBuilder.setRuntimeInputs(ArtifactCategory.DYNAMIC_LIBRARY, ccToolchain.getDynamicRuntimeLinkMiddleman(), ccToolchain.getDynamicRuntimeLinkInputs());
} else {
linkActionBuilder.setRuntimeInputs(ArtifactCategory.STATIC_LIBRARY, ccToolchain.getStaticRuntimeLinkMiddleman(), ccToolchain.getStaticRuntimeLinkInputs());
// TODO(bazel-team): Move this to CcToolchain.
if (!ccToolchain.getStaticRuntimeLinkInputs().isEmpty()) {
linkActionBuilder.addLinkopt("-static-libgcc");
}
}
linkActionBuilder.setLinkType(linkType);
linkActionBuilder.setLinkStaticness(linkStaticness);
linkActionBuilder.setFake(fake);
linkActionBuilder.setFeatureConfiguration(featureConfiguration);
if (CppLinkAction.enableSymbolsCounts(cppConfiguration, fake, linkType)) {
linkActionBuilder.setSymbolCountsOutput(ruleContext.getBinArtifact(CppLinkAction.symbolCountsFileName(binaryPath)));
}
if (isLinkShared(ruleContext)) {
linkActionBuilder.setLibraryIdentifier(CcLinkingOutputs.libraryIdentifierOf(binary));
}
// Store immutable context for use in other *_binary rules that are implemented by
// linking the interpreter (Java, Python, etc.) together with native deps.
CppLinkAction.Context linkContext = new CppLinkAction.Context(linkActionBuilder);
Iterable<LTOBackendArtifacts> ltoBackendArtifacts = ImmutableList.of();
boolean usePic = CppHelper.usePic(ruleContext, !isLinkShared(ruleContext));
if (featureConfiguration.isEnabled(CppRuleClasses.THIN_LTO)) {
linkActionBuilder.setLTOIndexing(true);
linkActionBuilder.setUsePicForLTOBackendActions(usePic);
linkActionBuilder.setUseFissionForLTOBackendActions(cppConfiguration.useFission());
CppLinkAction indexAction = linkActionBuilder.build();
ruleContext.registerAction(indexAction);
ltoBackendArtifacts = indexAction.getAllLTOBackendArtifacts();
linkActionBuilder.setLTOIndexing(false);
}
CppLinkAction linkAction = linkActionBuilder.build();
ruleContext.registerAction(linkAction);
LibraryToLink outputLibrary = linkAction.getOutputLibrary();
Iterable<Artifact> fakeLinkerInputs = fake ? linkAction.getInputs() : ImmutableList.<Artifact>of();
Artifact executable = linkAction.getLinkOutput();
CcLinkingOutputs.Builder linkingOutputsBuilder = new CcLinkingOutputs.Builder();
if (isLinkShared(ruleContext)) {
linkingOutputsBuilder.addDynamicLibrary(outputLibrary);
linkingOutputsBuilder.addExecutionDynamicLibrary(outputLibrary);
}
// Also add all shared libraries from srcs.
for (Artifact library : precompiledFiles.getSharedLibraries()) {
Artifact symlink = common.getDynamicLibrarySymlink(library, true);
LibraryToLink symlinkLibrary = LinkerInputs.solibLibraryToLink(symlink, library, CcLinkingOutputs.libraryIdentifierOf(library));
linkingOutputsBuilder.addDynamicLibrary(symlinkLibrary);
linkingOutputsBuilder.addExecutionDynamicLibrary(symlinkLibrary);
}
CcLinkingOutputs linkingOutputs = linkingOutputsBuilder.build();
NestedSet<Artifact> filesToBuild = NestedSetBuilder.create(Order.STABLE_ORDER, executable);
// Create the stripped binary, but don't add it to filesToBuild; it's only built when requested.
Artifact strippedFile = ruleContext.getImplicitOutputArtifact(CppRuleClasses.CC_BINARY_STRIPPED);
CppHelper.createStripAction(ruleContext, ccToolchain, cppConfiguration, executable, strippedFile);
DwoArtifactsCollector dwoArtifacts = collectTransitiveDwoArtifacts(ruleContext, ccCompilationOutputs, linkStaticness, cppConfiguration.useFission(), usePic, ltoBackendArtifacts);
Artifact dwpFile = ruleContext.getImplicitOutputArtifact(CppRuleClasses.CC_BINARY_DEBUG_PACKAGE);
createDebugPackagerActions(ruleContext, ccToolchain, cppConfiguration, dwpFile, dwoArtifacts);
// The debug package should include the dwp file only if it was explicitly requested.
Artifact explicitDwpFile = dwpFile;
if (!cppConfiguration.useFission()) {
explicitDwpFile = null;
} else {
// built statically.
if (TargetUtils.isTestRule(ruleContext.getRule()) && linkStaticness != LinkStaticness.DYNAMIC && cppConfiguration.shouldBuildTestDwp()) {
filesToBuild = NestedSetBuilder.fromNestedSet(filesToBuild).add(dwpFile).build();
}
}
// TODO(bazel-team): Do we need to put original shared libraries (along with
// mangled symlinks) into the RunfilesSupport object? It does not seem
// logical since all symlinked libraries will be linked anyway and would
// not require manual loading but if we do, then we would need to collect
// their names and use a different constructor below.
Runfiles runfiles = collectRunfiles(ruleContext, ccToolchain, linkingOutputs, info, linkStaticness, filesToBuild, fakeLinkerInputs, fake, helper.getCompilationUnitSources(), linkCompileOutputSeparately);
RunfilesSupport runfilesSupport = RunfilesSupport.withExecutable(ruleContext, runfiles, executable, ruleContext.getConfiguration().buildRunfiles());
TransitiveLipoInfoProvider transitiveLipoInfo;
if (cppConfiguration.isLipoContextCollector()) {
transitiveLipoInfo = common.collectTransitiveLipoLabels(ccCompilationOutputs);
} else {
transitiveLipoInfo = TransitiveLipoInfoProvider.EMPTY;
}
RuleConfiguredTargetBuilder ruleBuilder = new RuleConfiguredTargetBuilder(ruleContext);
addTransitiveInfoProviders(ruleContext, cppConfiguration, common, ruleBuilder, filesToBuild, ccCompilationOutputs, cppCompilationContext, linkingOutputs, dwoArtifacts, transitiveLipoInfo, fake);
Map<Artifact, IncludeScannable> scannableMap = new LinkedHashMap<>();
Map<PathFragment, Artifact> sourceFileMap = new LinkedHashMap<>();
if (cppConfiguration.isLipoContextCollector()) {
for (IncludeScannable scannable : transitiveLipoInfo.getTransitiveIncludeScannables()) {
// These should all be CppCompileActions, which should have only one source file.
// This is also checked when they are put into the nested set.
Artifact source = Iterables.getOnlyElement(scannable.getIncludeScannerSources());
scannableMap.put(source, scannable);
sourceFileMap.put(source.getExecPath(), source);
}
}
// Support test execution on darwin.
if (Platform.isApplePlatform(cppConfiguration.getTargetCpu()) && TargetUtils.isTestRule(ruleContext.getRule())) {
ruleBuilder.addNativeDeclaredProvider(new ExecutionInfoProvider(ImmutableMap.of(ExecutionRequirements.REQUIRES_DARWIN, "")));
}
return ruleBuilder.addProvider(RunfilesProvider.class, RunfilesProvider.simple(runfiles)).addProvider(CppDebugPackageProvider.class, new CppDebugPackageProvider(ruleContext.getLabel(), strippedFile, executable, explicitDwpFile)).setRunfilesSupport(runfilesSupport, executable).addProvider(LipoContextProvider.class, new LipoContextProvider(cppCompilationContext, ImmutableMap.copyOf(scannableMap), ImmutableMap.copyOf(sourceFileMap))).addProvider(CppLinkAction.Context.class, linkContext).addSkylarkTransitiveInfo(CcSkylarkApiProvider.NAME, new CcSkylarkApiProvider()).build();
}
use of com.google.devtools.build.lib.analysis.RunfilesSupport in project bazel by bazelbuild.
the class RunCommand method exec.
@Override
public ExitCode exec(CommandEnvironment env, OptionsProvider options) {
RunOptions runOptions = options.getOptions(RunOptions.class);
// This list should look like: ["//executable:target", "arg1", "arg2"]
List<String> targetAndArgs = options.getResidue();
// The user must at the least specify an executable target.
if (targetAndArgs.isEmpty()) {
env.getReporter().handle(Event.error("Must specify a target to run"));
return ExitCode.COMMAND_LINE_ERROR;
}
String targetString = targetAndArgs.get(0);
List<String> runTargetArgs = targetAndArgs.subList(1, targetAndArgs.size());
RunUnder runUnder = options.getOptions(BuildConfiguration.Options.class).runUnder;
OutErr outErr = env.getReporter().getOutErr();
List<String> targets = (runUnder != null) && (runUnder.getLabel() != null) ? ImmutableList.of(targetString, runUnder.getLabel().toString()) : ImmutableList.of(targetString);
BuildRequest request = BuildRequest.create(this.getClass().getAnnotation(Command.class).name(), options, env.getRuntime().getStartupOptionsProvider(), targets, outErr, env.getCommandId(), env.getCommandStartTime());
currentRunUnder = runUnder;
BuildResult result;
try {
result = processRequest(env, request);
} finally {
currentRunUnder = null;
}
if (!result.getSuccess()) {
env.getReporter().handle(Event.error("Build failed. Not running target"));
return result.getExitCondition();
}
// Make sure that we have exactly 1 built target (excluding --run_under),
// and that it is executable.
// These checks should only fail if keepGoing is true, because we already did
// validation before the build began. See {@link #validateTargets()}.
Collection<ConfiguredTarget> targetsBuilt = result.getSuccessfulTargets();
ConfiguredTarget targetToRun = null;
ConfiguredTarget runUnderTarget = null;
if (targetsBuilt != null) {
int maxTargets = runUnder != null && runUnder.getLabel() != null ? 2 : 1;
if (targetsBuilt.size() > maxTargets) {
env.getReporter().handle(Event.error(SINGLE_TARGET_MESSAGE));
return ExitCode.COMMAND_LINE_ERROR;
}
for (ConfiguredTarget target : targetsBuilt) {
ExitCode targetValidation = fullyValidateTarget(env, target);
if (!targetValidation.equals(ExitCode.SUCCESS)) {
return targetValidation;
}
if (runUnder != null && target.getLabel().equals(runUnder.getLabel())) {
if (runUnderTarget != null) {
env.getReporter().handle(Event.error(null, "Can't identify the run_under target from multiple options?"));
return ExitCode.COMMAND_LINE_ERROR;
}
runUnderTarget = target;
} else if (targetToRun == null) {
targetToRun = target;
} else {
env.getReporter().handle(Event.error(SINGLE_TARGET_MESSAGE));
return ExitCode.COMMAND_LINE_ERROR;
}
}
}
// Handle target & run_under referring to the same target.
if ((targetToRun == null) && (runUnderTarget != null)) {
targetToRun = runUnderTarget;
}
if (targetToRun == null) {
env.getReporter().handle(Event.error(NO_TARGET_MESSAGE));
return ExitCode.COMMAND_LINE_ERROR;
}
Path executablePath = Preconditions.checkNotNull(targetToRun.getProvider(FilesToRunProvider.class).getExecutable().getPath());
BuildConfiguration configuration = targetToRun.getConfiguration();
if (configuration == null) {
// The target may be an input file, which doesn't have a configuration. In that case, we
// choose any target configuration.
configuration = result.getBuildConfigurationCollection().getTargetConfigurations().get(0);
}
Path workingDir;
try {
workingDir = ensureRunfilesBuilt(env, targetToRun);
} catch (CommandException e) {
env.getReporter().handle(Event.error("Error creating runfiles: " + e.getMessage()));
return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
}
List<String> args = runTargetArgs;
FilesToRunProvider provider = targetToRun.getProvider(FilesToRunProvider.class);
RunfilesSupport runfilesSupport = provider == null ? null : provider.getRunfilesSupport();
if (runfilesSupport != null && runfilesSupport.getArgs() != null) {
List<String> targetArgs = runfilesSupport.getArgs();
if (!targetArgs.isEmpty()) {
args = Lists.newArrayListWithCapacity(targetArgs.size() + runTargetArgs.size());
args.addAll(targetArgs);
args.addAll(runTargetArgs);
}
}
String productName = env.getRuntime().getProductName();
//
// We now have a unique executable ready to be run.
//
// We build up two different versions of the command to run: one with an absolute path, which
// we'll actually run, and a prettier one with the long absolute path to the executable
// replaced with a shorter relative path that uses the symlinks in the workspace.
PathFragment prettyExecutablePath = OutputDirectoryLinksUtils.getPrettyPath(executablePath, env.getWorkspaceName(), env.getWorkspace(), options.getOptions(BuildRequestOptions.class).getSymlinkPrefix(productName), productName);
List<String> cmdLine = new ArrayList<>();
if (runOptions.scriptPath == null) {
PathFragment processWrapperPath = env.getBlazeWorkspace().getBinTools().getExecPath(PROCESS_WRAPPER);
Preconditions.checkNotNull(processWrapperPath, PROCESS_WRAPPER + " not found in embedded tools");
cmdLine.add(env.getExecRoot().getRelative(processWrapperPath).getPathString());
cmdLine.add("-1");
cmdLine.add("15");
cmdLine.add("-");
cmdLine.add("-");
}
List<String> prettyCmdLine = new ArrayList<>();
// at the start of the command line.
if (runUnder != null) {
String runUnderValue = runUnder.getValue();
if (runUnderTarget != null) {
// --run_under specifies a target. Get the corresponding executable.
// This must be an absolute path, because the run_under target is only
// in the runfiles of test targets.
runUnderValue = runUnderTarget.getProvider(FilesToRunProvider.class).getExecutable().getPath().getPathString();
// If the run_under command contains any options, make sure to add them
// to the command line as well.
List<String> opts = runUnder.getOptions();
if (!opts.isEmpty()) {
runUnderValue += " " + ShellEscaper.escapeJoinAll(opts);
}
}
cmdLine.add(configuration.getShellExecutable().getPathString());
cmdLine.add("-c");
cmdLine.add(runUnderValue + " " + executablePath.getPathString() + " " + ShellEscaper.escapeJoinAll(args));
prettyCmdLine.add(configuration.getShellExecutable().getPathString());
prettyCmdLine.add("-c");
prettyCmdLine.add(runUnderValue + " " + prettyExecutablePath.getPathString() + " " + ShellEscaper.escapeJoinAll(args));
} else {
cmdLine.add(executablePath.getPathString());
cmdLine.addAll(args);
prettyCmdLine.add(prettyExecutablePath.getPathString());
prettyCmdLine.addAll(args);
}
// Add a newline between the blaze output and the binary's output.
outErr.printErrLn("");
if (runOptions.scriptPath != null) {
String unisolatedCommand = CommandFailureUtils.describeCommand(CommandDescriptionForm.COMPLETE_UNISOLATED, cmdLine, null, workingDir.getPathString());
if (writeScript(env, runOptions.scriptPath, unisolatedCommand)) {
return ExitCode.SUCCESS;
} else {
return ExitCode.RUN_FAILURE;
}
}
env.getReporter().handle(Event.info(null, "Running command line: " + ShellEscaper.escapeJoinAll(prettyCmdLine)));
com.google.devtools.build.lib.shell.Command command = new CommandBuilder().addArgs(cmdLine).setEnv(env.getClientEnv()).setWorkingDir(workingDir).build();
try {
// Restore a raw EventHandler if it is registered. This allows for blaze run to produce the
// actual output of the command being run even if --color=no is specified.
env.getReporter().switchToAnsiAllowingHandler();
// The command API is a little strange in that the following statement
// will return normally only if the program exits with exit code 0.
// If it ends with any other code, we have to catch BadExitStatusException.
command.execute(com.google.devtools.build.lib.shell.Command.NO_INPUT, com.google.devtools.build.lib.shell.Command.NO_OBSERVER, outErr.getOutputStream(), outErr.getErrorStream(), true).getTerminationStatus().getExitCode();
return ExitCode.SUCCESS;
} catch (BadExitStatusException e) {
String message = "Non-zero return code '" + e.getResult().getTerminationStatus().getExitCode() + "' from command: " + e.getMessage();
env.getReporter().handle(Event.error(message));
return ExitCode.RUN_FAILURE;
} catch (AbnormalTerminationException e) {
// The process was likely terminated by a signal in this case.
return ExitCode.INTERRUPTED;
} catch (CommandException e) {
env.getReporter().handle(Event.error("Error running program: " + e.getMessage()));
return ExitCode.RUN_FAILURE;
}
}
use of com.google.devtools.build.lib.analysis.RunfilesSupport in project bazel by bazelbuild.
the class JavaBinary method create.
@Override
public ConfiguredTarget create(RuleContext ruleContext) throws InterruptedException, RuleErrorException {
final JavaCommon common = new JavaCommon(ruleContext, semantics);
DeployArchiveBuilder deployArchiveBuilder = new DeployArchiveBuilder(semantics, ruleContext);
Runfiles.Builder runfilesBuilder = new Runfiles.Builder(ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles());
List<String> jvmFlags = new ArrayList<>();
JavaTargetAttributes.Builder attributesBuilder = common.initCommon();
attributesBuilder.addClassPathResources(ruleContext.getPrerequisiteArtifacts("classpath_resources", Mode.TARGET).list());
// Add Java8 timezone resource data
addTimezoneResourceForJavaBinaries(ruleContext, attributesBuilder);
List<String> userJvmFlags = JavaCommon.getJvmFlags(ruleContext);
ruleContext.checkSrcsSamePackage(true);
boolean createExecutable = ruleContext.attributes().get("create_executable", Type.BOOLEAN);
if (!createExecutable) {
// TODO(cushon): disallow combining launcher=JDK_LAUNCHER_LABEL with create_executable=0
// and use isAttributeExplicitlySpecified here
Label launcherAttribute = ruleContext.attributes().get("launcher", BuildType.LABEL);
if (launcherAttribute != null && !JavaHelper.isJdkLauncher(ruleContext, launcherAttribute)) {
ruleContext.ruleError("launcher specified but create_executable is false");
}
}
semantics.checkRule(ruleContext, common);
semantics.checkForProtoLibraryAndJavaProtoLibraryOnSameProto(ruleContext, common);
String mainClass = semantics.getMainClass(ruleContext, common.getSrcsArtifacts());
String originalMainClass = mainClass;
if (ruleContext.hasErrors()) {
return null;
}
// Collect the transitive dependencies.
JavaCompilationHelper helper = new JavaCompilationHelper(ruleContext, semantics, common.getJavacOpts(), attributesBuilder);
List<TransitiveInfoCollection> deps = // Do not remove <TransitiveInfoCollection>: workaround for Java 7 type inference.
Lists.<TransitiveInfoCollection>newArrayList(common.targetsTreatedAsDeps(ClasspathType.COMPILE_ONLY));
helper.addLibrariesToAttributes(deps);
attributesBuilder.addNativeLibraries(collectNativeLibraries(common.targetsTreatedAsDeps(ClasspathType.BOTH)));
// deploy_env is valid for java_binary, but not for java_test.
if (ruleContext.getRule().isAttrDefined("deploy_env", BuildType.LABEL_LIST)) {
for (JavaRuntimeClasspathProvider envTarget : ruleContext.getPrerequisites("deploy_env", Mode.TARGET, JavaRuntimeClasspathProvider.class)) {
attributesBuilder.addExcludedArtifacts(envTarget.getRuntimeClasspath());
}
}
Artifact srcJar = ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_BINARY_SOURCE_JAR);
JavaSourceJarsProvider.Builder javaSourceJarsProviderBuilder = JavaSourceJarsProvider.builder().addSourceJar(srcJar).addAllTransitiveSourceJars(common.collectTransitiveSourceJars(srcJar));
Artifact classJar = ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_BINARY_CLASS_JAR);
JavaRuleOutputJarsProvider.Builder ruleOutputJarsProviderBuilder = JavaRuleOutputJarsProvider.builder().addOutputJar(classJar, null, /* iJar */
ImmutableList.of(srcJar));
CppConfiguration cppConfiguration = ruleContext.getConfiguration().getFragment(CppConfiguration.class);
boolean stripAsDefault = cppConfiguration.useFission() && cppConfiguration.getCompilationMode() == CompilationMode.OPT;
Artifact launcher = semantics.getLauncher(ruleContext, common, deployArchiveBuilder, runfilesBuilder, jvmFlags, attributesBuilder, stripAsDefault);
DeployArchiveBuilder unstrippedDeployArchiveBuilder = null;
Artifact unstrippedLauncher = null;
if (stripAsDefault) {
unstrippedDeployArchiveBuilder = new DeployArchiveBuilder(semantics, ruleContext);
unstrippedLauncher = semantics.getLauncher(ruleContext, common, unstrippedDeployArchiveBuilder, runfilesBuilder, jvmFlags, attributesBuilder, false);
}
JavaCompilationArtifacts.Builder javaArtifactsBuilder = new JavaCompilationArtifacts.Builder();
Artifact instrumentationMetadata = helper.createInstrumentationMetadata(classJar, javaArtifactsBuilder);
NestedSetBuilder<Artifact> filesBuilder = NestedSetBuilder.stableOrder();
Artifact executableForRunfiles = null;
if (createExecutable) {
// This artifact is named as the rule itself, e.g. //foo:bar_bin -> bazel-bin/foo/bar_bin
executableForRunfiles = ruleContext.createOutputArtifact();
filesBuilder.add(classJar).add(executableForRunfiles);
if (ruleContext.getConfiguration().isCodeCoverageEnabled()) {
mainClass = semantics.addCoverageSupport(helper, attributesBuilder, executableForRunfiles, instrumentationMetadata, javaArtifactsBuilder, mainClass);
}
} else {
filesBuilder.add(classJar);
}
JavaTargetAttributes attributes = helper.getAttributes();
List<Artifact> nativeLibraries = attributes.getNativeLibraries();
if (!nativeLibraries.isEmpty()) {
jvmFlags.add("-Djava.library.path=" + JavaCommon.javaLibraryPath(nativeLibraries, ruleContext.getRule().getPackage().getWorkspaceName()));
}
JavaConfiguration javaConfig = ruleContext.getFragment(JavaConfiguration.class);
if (attributes.hasMessages()) {
helper.setTranslations(semantics.translate(ruleContext, javaConfig, attributes.getMessages()));
}
if (attributes.hasSourceFiles() || attributes.hasSourceJars() || attributes.hasResources() || attributes.hasClassPathResources()) {
// We only want to add a jar to the classpath of a dependent rule if it has content.
javaArtifactsBuilder.addRuntimeJar(classJar);
}
GeneratedExtensionRegistryProvider generatedExtensionRegistryProvider = semantics.createGeneratedExtensionRegistry(ruleContext, common, filesBuilder, javaArtifactsBuilder, ruleOutputJarsProviderBuilder, javaSourceJarsProviderBuilder);
Artifact outputDepsProto = helper.createOutputDepsProtoArtifact(classJar, javaArtifactsBuilder);
ruleOutputJarsProviderBuilder.setJdeps(outputDepsProto);
JavaCompilationArtifacts javaArtifacts = javaArtifactsBuilder.build();
common.setJavaCompilationArtifacts(javaArtifacts);
Artifact manifestProtoOutput = helper.createManifestProtoOutput(classJar);
// The gensrc jar is created only if the target uses annotation processing. Otherwise,
// it is null, and the source jar action will not depend on the compile action.
Artifact genSourceJar = null;
Artifact genClassJar = null;
if (helper.usesAnnotationProcessing()) {
genClassJar = helper.createGenJar(classJar);
genSourceJar = helper.createGensrcJar(classJar);
helper.createGenJarAction(classJar, manifestProtoOutput, genClassJar);
}
helper.createCompileAction(classJar, manifestProtoOutput, genSourceJar, outputDepsProto, instrumentationMetadata);
helper.createSourceJarAction(srcJar, genSourceJar);
common.setClassPathFragment(new ClasspathConfiguredFragment(javaArtifacts, attributes, false, helper.getBootclasspathOrDefault()));
// Collect the action inputs for the runfiles collector here because we need to access the
// analysis environment, and that may no longer be safe when the runfiles collector runs.
Iterable<Artifact> dynamicRuntimeActionInputs = CppHelper.getToolchain(ruleContext, ":cc_toolchain").getDynamicRuntimeLinkInputs();
Iterables.addAll(jvmFlags, semantics.getJvmFlags(ruleContext, common.getSrcsArtifacts(), userJvmFlags));
if (ruleContext.hasErrors()) {
return null;
}
Artifact executableToRun = executableForRunfiles;
if (createExecutable) {
// Create a shell stub for a Java application
executableToRun = semantics.createStubAction(ruleContext, common, jvmFlags, executableForRunfiles, mainClass, JavaCommon.getJavaBinSubstitution(ruleContext, launcher));
if (!executableToRun.equals(executableForRunfiles)) {
filesBuilder.add(executableToRun);
runfilesBuilder.addArtifact(executableToRun);
}
}
JavaSourceJarsProvider sourceJarsProvider = javaSourceJarsProviderBuilder.build();
NestedSet<Artifact> transitiveSourceJars = sourceJarsProvider.getTransitiveSourceJars();
// TODO(bazel-team): if (getOptions().sourceJars) then make this a dummy prerequisite for the
// DeployArchiveAction ? Needs a few changes there as we can't pass inputs
SingleJarActionBuilder.createSourceJarAction(ruleContext, ImmutableMap.<PathFragment, Artifact>of(), transitiveSourceJars.toCollection(), ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_BINARY_DEPLOY_SOURCE_JAR));
RuleConfiguredTargetBuilder builder = new RuleConfiguredTargetBuilder(ruleContext);
builder.add(JavaPrimaryClassProvider.class, new JavaPrimaryClassProvider(semantics.getPrimaryClass(ruleContext, common.getSrcsArtifacts())));
semantics.addProviders(ruleContext, common, jvmFlags, classJar, srcJar, genClassJar, genSourceJar, ImmutableMap.<Artifact, Artifact>of(), filesBuilder, builder);
if (generatedExtensionRegistryProvider != null) {
builder.add(GeneratedExtensionRegistryProvider.class, generatedExtensionRegistryProvider);
}
Artifact deployJar = ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_BINARY_DEPLOY_JAR);
boolean runProguard = applyProguardIfRequested(ruleContext, deployJar, common.getBootClasspath(), mainClass, semantics, filesBuilder);
if (javaConfig.isEnforceOneVersion()) {
Artifact oneVersionOutput = ruleContext.getAnalysisEnvironment().getDerivedArtifact(replaceExtension(classJar.getRootRelativePath(), "-one-version.txt"), classJar.getRoot());
filesBuilder.add(oneVersionOutput);
NestedSet<Artifact> transitiveDependencies = NestedSetBuilder.fromNestedSet(attributes.getRuntimeClassPath()).add(classJar).build();
OneVersionCheckActionBuilder.build(ruleContext, transitiveDependencies, oneVersionOutput);
}
NestedSet<Artifact> filesToBuild = filesBuilder.build();
// Need not include normal runtime classpath in runfiles if Proguard is used because _deploy.jar
// is used as classpath instead. Keeping runfiles unchanged has however the advantage that
// manually running executable without --singlejar works (although it won't depend on Proguard).
collectDefaultRunfiles(runfilesBuilder, ruleContext, common, javaArtifacts, filesToBuild, launcher, dynamicRuntimeActionInputs);
Runfiles defaultRunfiles = runfilesBuilder.build();
RunfilesSupport runfilesSupport = null;
if (createExecutable) {
List<String> extraArgs = new ArrayList<>(semantics.getExtraArguments(ruleContext, common.getSrcsArtifacts()));
if (runProguard) {
// Instead of changing the classpath written into the wrapper script, pass --singlejar when
// running the script (which causes the deploy.jar written by Proguard to be used instead of
// the normal classpath). It's a bit odd to do this b/c manually running the script wouldn't
// use Proguard's output unless --singlejar is explicitly supplied. On the other hand the
// behavior of the script is more consistent: the (proguarded) deploy.jar is only used with
// --singlejar. Moreover, people will almost always run tests using blaze test, which does
// use Proguard's output thanks to this extra arg when enabled. Also, it's actually hard to
// get the classpath changed in the wrapper script (would require calling
// JavaCommon.setClasspathFragment with a new fragment at the *end* of this method because
// the classpath is evaluated lazily when generating the wrapper script) and the wrapper
// script would essentially have an if (--singlejar was set), set classpath to deploy jar,
// otherwise, set classpath to deploy jar.
extraArgs.add("--wrapper_script_flag=--singlejar");
}
// The executable we pass here will be used when creating the runfiles directory. E.g. for the
// stub script called bazel-bin/foo/bar_bin, the runfiles directory will be created under
// bazel-bin/foo/bar_bin.runfiles . On platforms where there's an extra stub script (Windows)
// which dispatches to this one, we still create the runfiles directory for the shell script,
// but use the dispatcher script (a batch file) as the RunfilesProvider's executable.
runfilesSupport = RunfilesSupport.withExecutable(ruleContext, defaultRunfiles, executableForRunfiles, extraArgs);
}
RunfilesProvider runfilesProvider = RunfilesProvider.withData(defaultRunfiles, new Runfiles.Builder(ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles()).merge(runfilesSupport).build());
ImmutableList<String> deployManifestLines = getDeployManifestLines(ruleContext, originalMainClass);
// When running Proguard:
// (1) write single jar to intermediate destination; Proguard will write _deploy.jar file
// (2) Don't depend on runfiles to avoid circular dependency, since _deploy.jar is itself part
// of runfiles when Proguard runs (because executable then needs it) and _deploy.jar depends
// on this single jar.
// (3) Don't bother with compression since Proguard will write the final jar anyways
deployArchiveBuilder.setOutputJar(runProguard ? ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_BINARY_MERGED_JAR) : deployJar).setJavaStartClass(mainClass).setDeployManifestLines(deployManifestLines).setAttributes(attributes).addRuntimeJars(javaArtifacts.getRuntimeJars()).setIncludeBuildData(true).setRunfilesMiddleman(runProguard || runfilesSupport == null ? null : runfilesSupport.getRunfilesMiddleman()).setCompression(runProguard ? UNCOMPRESSED : COMPRESSED).setLauncher(launcher).build();
Artifact unstrippedDeployJar = ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_UNSTRIPPED_BINARY_DEPLOY_JAR);
if (stripAsDefault) {
unstrippedDeployArchiveBuilder.setOutputJar(unstrippedDeployJar).setJavaStartClass(mainClass).setDeployManifestLines(deployManifestLines).setAttributes(attributes).addRuntimeJars(javaArtifacts.getRuntimeJars()).setIncludeBuildData(true).setRunfilesMiddleman(runfilesSupport == null ? null : runfilesSupport.getRunfilesMiddleman()).setCompression(COMPRESSED).setLauncher(unstrippedLauncher);
unstrippedDeployArchiveBuilder.build();
} else {
// Write an empty file as the name_deploy.jar.unstripped when the default output jar is not
// stripped.
ruleContext.registerAction(FileWriteAction.create(ruleContext, unstrippedDeployJar, "", false));
}
JavaRuleOutputJarsProvider ruleOutputJarsProvider = ruleOutputJarsProviderBuilder.build();
JavaSkylarkApiProvider.Builder skylarkApiProvider = JavaSkylarkApiProvider.builder().setRuleOutputJarsProvider(ruleOutputJarsProvider).setSourceJarsProvider(sourceJarsProvider);
common.addTransitiveInfoProviders(builder, skylarkApiProvider, filesToBuild, classJar);
common.addGenJarsProvider(builder, skylarkApiProvider, genClassJar, genSourceJar);
return builder.setFilesToBuild(filesToBuild).addSkylarkTransitiveInfo(JavaSkylarkApiProvider.NAME, skylarkApiProvider.build()).add(JavaRuleOutputJarsProvider.class, ruleOutputJarsProvider).add(RunfilesProvider.class, runfilesProvider).setRunfilesSupport(runfilesSupport, executableToRun).add(JavaRuntimeClasspathProvider.class, new JavaRuntimeClasspathProvider(common.getRuntimeClasspath())).add(JavaSourceInfoProvider.class, JavaSourceInfoProvider.fromJavaTargetAttributes(attributes, semantics)).add(JavaSourceJarsProvider.class, sourceJarsProvider).addOutputGroup(JavaSemantics.SOURCE_JARS_OUTPUT_GROUP, transitiveSourceJars).build();
}
use of com.google.devtools.build.lib.analysis.RunfilesSupport in project bazel by bazelbuild.
the class PyBinary method init.
static RuleConfiguredTargetBuilder init(RuleContext ruleContext, PythonSemantics semantics, PyCommon common) throws InterruptedException {
CcLinkParamsStore ccLinkParamsStore = initializeCcLinkParamStore(ruleContext);
List<Artifact> srcs = common.validateSrcs();
List<Artifact> allOutputs = new ArrayList<>(semantics.precompiledPythonFiles(ruleContext, srcs, common));
if (ruleContext.hasErrors()) {
return null;
}
common.initBinary(allOutputs);
semantics.validate(ruleContext, common);
if (ruleContext.hasErrors()) {
return null;
}
NestedSet<PathFragment> imports = common.collectImports(ruleContext, semantics);
if (ruleContext.hasErrors()) {
return null;
}
semantics.createExecutable(ruleContext, common, ccLinkParamsStore, imports);
Runfiles commonRunfiles = collectCommonRunfiles(ruleContext, common, semantics);
Runfiles.Builder defaultRunfilesBuilder = new Runfiles.Builder(ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles()).merge(commonRunfiles);
semantics.collectDefaultRunfilesForBinary(ruleContext, defaultRunfilesBuilder);
Runfiles defaultRunfiles = defaultRunfilesBuilder.build();
RunfilesSupport runfilesSupport = RunfilesSupport.withExecutable(ruleContext, defaultRunfiles, common.getExecutable(), ruleContext.shouldCreateRunfilesSymlinks());
if (ruleContext.hasErrors()) {
return null;
}
// Only include common runfiles and middleman. Default runfiles added by semantics are
// excluded. The middleman is necessary to ensure the runfiles trees are generated for all
// dependency binaries.
Runfiles dataRunfiles = new Runfiles.Builder(ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles()).merge(commonRunfiles).addArtifact(runfilesSupport.getRunfilesMiddleman()).build();
RunfilesProvider runfilesProvider = RunfilesProvider.withData(defaultRunfiles, dataRunfiles);
RuleConfiguredTargetBuilder builder = new RuleConfiguredTargetBuilder(ruleContext);
common.addCommonTransitiveInfoProviders(builder, semantics, common.getFilesToBuild());
semantics.postInitBinary(ruleContext, runfilesSupport, common);
return builder.setFilesToBuild(common.getFilesToBuild()).add(RunfilesProvider.class, runfilesProvider).setRunfilesSupport(runfilesSupport, common.getExecutable()).add(CcLinkParamsProvider.class, new CcLinkParamsProvider(ccLinkParamsStore)).add(PythonImportsProvider.class, new PythonImportsProvider(imports));
}
Aggregations