Delete dead C++ rules code A lot of the code here could have been deleted a long time if it hadn't been blocked by the Starlarkification of one last internal rule which happened in Q4. @buildbreaker2021 is also responsible for the starlarkification of a lot of this deleted code. RELNOTES: PiperOrigin-RevId: 510098054 Change-Id: I427f791fc1b611eb5917d3a1dad27cf4e2444f58
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/cpp/BazelCcLibrary.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/cpp/BazelCcLibrary.java deleted file mode 100644 index 898e60a..0000000 --- a/src/main/java/com/google/devtools/build/lib/bazel/rules/cpp/BazelCcLibrary.java +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright 2014 The Bazel Authors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.devtools.build.lib.bazel.rules.cpp; - -import com.google.devtools.build.lib.rules.cpp.CcLibrary; - -/** - * Factory class for the {@code cc_library} rule. - */ -public class BazelCcLibrary extends CcLibrary { - public BazelCcLibrary() { - super(BazelCppSemantics.CPP); - } -}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/cpp/BazelCcLibraryRule.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/cpp/BazelCcLibraryRule.java index a26da04..a8f3b35 100644 --- a/src/main/java/com/google/devtools/build/lib/bazel/rules/cpp/BazelCcLibraryRule.java +++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/cpp/BazelCcLibraryRule.java
@@ -72,7 +72,7 @@ return RuleDefinition.Metadata.builder() .name("cc_library") .ancestors(CcLibraryBaseRule.class, BaseRuleClasses.MakeVariableExpandingRule.class) - .factoryClass(BazelCcLibrary.class) + .factoryClass(BaseRuleClasses.EmptyRuleConfiguredTargetFactory.class) .build(); } }
diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcCommon.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcCommon.java index c50a2ea..8059516 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcCommon.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcCommon.java
@@ -14,7 +14,6 @@ package com.google.devtools.build.lib.rules.cpp; import static com.google.common.collect.ImmutableList.toImmutableList; -import static com.google.devtools.build.lib.packages.BuildType.LABEL; import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST; import com.google.common.base.Joiner; @@ -25,28 +24,18 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; -import com.google.devtools.build.lib.actions.ActionAnalysisMetadata; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.AliasProvider; -import com.google.devtools.build.lib.analysis.AnalysisEnvironment; import com.google.devtools.build.lib.analysis.FileProvider; import com.google.devtools.build.lib.analysis.MakeVariableSupplier; -import com.google.devtools.build.lib.analysis.OutputGroupInfo; import com.google.devtools.build.lib.analysis.RuleContext; import com.google.devtools.build.lib.analysis.TransitiveInfoCollection; -import com.google.devtools.build.lib.analysis.actions.FileWriteAction; import com.google.devtools.build.lib.analysis.config.BuildConfigurationValue; import com.google.devtools.build.lib.analysis.config.CompilationMode; import com.google.devtools.build.lib.analysis.starlark.StarlarkRuleContext; import com.google.devtools.build.lib.analysis.stringtemplate.ExpansionException; -import com.google.devtools.build.lib.analysis.test.InstrumentedFilesCollector; -import com.google.devtools.build.lib.analysis.test.InstrumentedFilesCollector.LocalMetadataCollector; -import com.google.devtools.build.lib.analysis.test.InstrumentedFilesInfo; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.cmdline.PackageIdentifier; -import com.google.devtools.build.lib.collect.nestedset.NestedSet; -import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; -import com.google.devtools.build.lib.packages.BuildType; import com.google.devtools.build.lib.packages.Rule; import com.google.devtools.build.lib.packages.RuleClass; import com.google.devtools.build.lib.packages.RuleClass.ConfiguredTargetFactory.RuleErrorException; @@ -58,14 +47,12 @@ import com.google.devtools.build.lib.rules.cpp.CppConfiguration.HeadersCheckingMode; import com.google.devtools.build.lib.rules.cpp.Link.LinkTargetType; import com.google.devtools.build.lib.shell.ShellUtils; -import com.google.devtools.build.lib.util.FileType; import com.google.devtools.build.lib.util.Pair; import com.google.devtools.build.lib.vfs.PathFragment; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.TreeMap; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.stream.Stream; @@ -76,7 +63,6 @@ import net.starlark.java.eval.Starlark; import net.starlark.java.eval.StarlarkList; import net.starlark.java.eval.StarlarkValue; -import net.starlark.java.eval.Tuple; /** Common parts of the implementation of cc rules. */ public final class CcCommon implements StarlarkValue { @@ -96,24 +82,6 @@ private static final String NO_COPTS_ATTRIBUTE = "nocopts"; - /** - * Collects all metadata files generated by C++ compilation actions that output the .o files - * on the input. - */ - private static final LocalMetadataCollector CC_METADATA_COLLECTOR = - new LocalMetadataCollector() { - @Override - public void collectMetadataArtifacts(Iterable<Artifact> objectFiles, - AnalysisEnvironment analysisEnvironment, NestedSetBuilder<Artifact> metadataFilesBuilder) { - for (Artifact artifact : objectFiles) { - ActionAnalysisMetadata action = analysisEnvironment.getLocalGeneratingAction(artifact); - if (action instanceof CppCompileAction) { - addOutputs(metadataFilesBuilder, action, CppFileTypes.COVERAGE_NOTES); - } - } - } - }; - public static final ImmutableSet<String> ALL_COMPILE_ACTIONS = ImmutableSet.of( CppActionNames.C_COMPILE, @@ -177,14 +145,11 @@ } } - public static final String CC_TOOLCHAIN_DEFAULT_ATTRIBUTE_NAME = ":cc_toolchain"; private static final String SYSROOT_FLAG = "--sysroot="; private final RuleContext ruleContext; private final CcToolchainProvider ccToolchain; - private final CppConfiguration cppConfiguration; - private final FdoContext fdoContext; public CcCommon(RuleContext ruleContext) throws RuleErrorException { @@ -196,37 +161,11 @@ public CcCommon(RuleContext ruleContext, CcToolchainProvider ccToolchain) { this.ruleContext = ruleContext; - this.cppConfiguration = ruleContext.getFragment(CppConfiguration.class); this.fdoContext = ccToolchain.getFdoContext(); this.ccToolchain = ccToolchain; } /** - * Merges a list of output groups into one. The sets for each entry with a given key are merged. - */ - public static Map<String, NestedSet<Artifact>> mergeOutputGroups( - ImmutableList<Map<String, NestedSet<Artifact>>> outputGroups) { - Map<String, NestedSetBuilder<Artifact>> mergedOutputGroupsBuilder = new TreeMap<>(); - - for (Map<String, NestedSet<Artifact>> outputGroup : outputGroups) { - for (Map.Entry<String, NestedSet<Artifact>> entryOutputGroup : outputGroup.entrySet()) { - String key = entryOutputGroup.getKey(); - mergedOutputGroupsBuilder.computeIfAbsent( - key, (String k) -> NestedSetBuilder.compileOrder()); - mergedOutputGroupsBuilder.get(key).addTransitive(entryOutputGroup.getValue()); - } - } - - Map<String, NestedSet<Artifact>> mergedOutputGroups = new TreeMap<>(); - for (Map.Entry<String, NestedSetBuilder<Artifact>> entryOutputGroupBuilder : - mergedOutputGroupsBuilder.entrySet()) { - mergedOutputGroups.put( - entryOutputGroupBuilder.getKey(), entryOutputGroupBuilder.getValue().build()); - } - return mergedOutputGroups; - } - - /** * Returns our own linkopts from the rule attribute. This determines linker options to use when * building this target and anything that depends on it. */ @@ -378,10 +317,6 @@ return fdoContext; } - public void reportInvalidOptions(RuleContext ruleContext) { - reportInvalidOptions(ruleContext, cppConfiguration, ccToolchain); - } - public static void reportInvalidOptions( RuleContext ruleContext, CppConfiguration cppConfiguration, CcToolchainProvider ccToolchain) { if (cppConfiguration.getLibcTopLabel() != null && ccToolchain.getDefaultSysroot() == null) { @@ -468,12 +403,6 @@ } } - /** Returns copts filter built from the make variable expanded nocopts attribute. */ - public CoptsFilter getCoptsFilter() { - return getCoptsFilter(ruleContext); - } - - /** @see CcCommon#getCoptsFilter() */ private static CoptsFilter getCoptsFilter(RuleContext ruleContext) { Pattern noCoptsPattern = getNoCoptsPattern(ruleContext); if (noCoptsPattern == null) { @@ -511,7 +440,6 @@ } private static final String DEFINES_ATTRIBUTE = "defines"; - private static final String LOCAL_DEFINES_ATTRIBUTE = "local_defines"; /** * Returns a list of define tokens from "defines" attribute. @@ -525,18 +453,6 @@ return getDefinesFromAttribute(DEFINES_ATTRIBUTE); } - /** - * Returns a list of define tokens from "local_defines" attribute. - * - * <p>We tokenize the "local_defines" attribute, to ensure that the handling of quotes and - * backslash escapes is consistent Bazel's treatment of the "copts" attribute. - * - * <p>But we require that the "local_defines" attribute consists of a single token. - */ - public List<String> getNonTransitiveDefines() { - return getDefinesFromAttribute(LOCAL_DEFINES_ATTRIBUTE); - } - private List<String> getDefinesFromAttribute(String attr) { List<String> defines = new ArrayList<>(); @@ -671,31 +587,6 @@ return result; } - /** Collects compilation prerequisite artifacts. */ - static NestedSet<Artifact> collectCompilationPrerequisites( - RuleContext ruleContext, CcCompilationContext ccCompilationContext) { - // TODO(bazel-team): Use ccCompilationContext.getCompilationPrerequisites() instead; note - // that this - // will - // need cleaning up the prerequisites, as the {@code CcCompilationContext} currently - // collects them - // transitively (to get transitive headers), but source files are not transitive compilation - // prerequisites. - NestedSetBuilder<Artifact> prerequisites = NestedSetBuilder.stableOrder(); - if (ruleContext.attributes().has("srcs", BuildType.LABEL_LIST)) { - for (FileProvider provider : ruleContext.getPrerequisites("srcs", FileProvider.class)) { - prerequisites.addAll( - FileType.filter( - provider.getFilesToBuild().toList(), SourceCategory.CC_AND_OBJC.getSourceTypes())); - } - } - prerequisites.addTransitive(ccCompilationContext.getDeclaredIncludeSrcs()); - prerequisites.addTransitive(ccCompilationContext.getAdditionalInputs()); - prerequisites.addTransitive(ccCompilationContext.getTransitiveModules(true)); - prerequisites.addTransitive(ccCompilationContext.getTransitiveModules(false)); - return prerequisites.build(); - } - /** * Returns all additional linker inputs specified in the |additional_linker_inputs| attribute of * the rule. @@ -704,75 +595,6 @@ return ruleContext.getPrerequisiteArtifacts("additional_linker_inputs").list(); } - /** - * Replaces shared library artifact with mangled symlink and creates related - * symlink action. For artifacts that should retain filename (e.g. libraries - * with SONAME tag), link is created to the parent directory instead. - * - * This action is performed to minimize number of -rpath entries used during - * linking process (by essentially "collecting" as many shared libraries as - * possible in the single directory), since we will be paying quadratic price - * for each additional entry on the -rpath. - * - * @param library Shared library artifact that needs to be mangled - * @param preserveName true if filename should be preserved, false - mangled. - * @return mangled symlink artifact. - */ - public Artifact getDynamicLibrarySymlink(Artifact library, boolean preserveName) { - return SolibSymlinkAction.getDynamicLibrarySymlink( - /* actionRegistry= */ ruleContext, - /* actionConstructionContext= */ ruleContext, - ccToolchain.getSolibDirectory(), - library, - preserveName, - /* prefixConsumer= */ true); - } - - /** Returns any linker scripts found in the "deps" attribute of the rule. */ - List<Artifact> getLinkerScripts() { - return ruleContext.getPrerequisiteArtifacts("deps").filter(CppFileTypes.LINKER_SCRIPT).list(); - } - - /** Returns the Windows DEF file specified in win_def_file attribute of the rule. */ - @Nullable - Artifact getWinDefFile() { - if (!ruleContext.isAttrDefined("win_def_file", LABEL)) { - return null; - } - - return ruleContext.getPrerequisiteArtifact("win_def_file"); - } - - /** - * Returns the parser & Windows DEF file generator specified in $def_parser attribute of the rule. - */ - @Nullable - Artifact getDefParser() { - if (!ruleContext.isAttrDefined("$def_parser", LABEL)) { - return null; - } - - return ruleContext.getPrerequisiteArtifact("$def_parser"); - } - - public InstrumentedFilesInfo getInstrumentedFilesProvider( - Iterable<Artifact> files, - boolean withBaselineCoverage, - NestedSet<Tuple> virtualToOriginalHeaders, - @Nullable Iterable<Artifact> additionalMetadata) - throws RuleErrorException { - return InstrumentedFilesCollector.collect( - ruleContext, - CppRuleClasses.INSTRUMENTATION_SPEC, - CC_METADATA_COLLECTOR, - files, - CppHelper.getGcovFilesIfNeeded(ruleContext, ccToolchain), - CppHelper.getCoverageEnvironmentIfNeeded(ruleContext, cppConfiguration, ccToolchain), - withBaselineCoverage, - virtualToOriginalHeaders, - additionalMetadata); - } - public String getPurpose(CppSemantics semantics) { return semantics.getClass().getSimpleName() + "_build_arch_" @@ -1107,43 +929,6 @@ return ImmutableList.of(); } - /** Returns artifacts that help debug the state of C++ features for the given ruleContext. */ - public static Map<String, NestedSet<Artifact>> createSaveFeatureStateArtifacts( - CppConfiguration cppConfiguration, - FeatureConfiguration featureConfiguration, - RuleContext ruleContext) { - - ImmutableMap.Builder<String, NestedSet<Artifact>> outputGroupsBuilder = ImmutableMap.builder(); - - if (cppConfiguration.saveFeatureState()) { - Artifact enabledFeaturesFile = - ruleContext.getUniqueDirectoryArtifact("feature_debug", "enabled_features.txt"); - ruleContext.registerAction( - FileWriteAction.create( - ruleContext, - enabledFeaturesFile, - featureConfiguration.getEnabledFeatureNames().toString(), - /* makeExecutable= */ false)); - - Artifact requestedFeaturesFile = - ruleContext.getUniqueDirectoryArtifact("feature_debug", "requested_features.txt"); - ruleContext.registerAction( - FileWriteAction.create( - ruleContext, - requestedFeaturesFile, - featureConfiguration.getRequestedFeatures().toString(), - /* makeExecutable= */ false)); - - outputGroupsBuilder.put( - OutputGroupInfo.DEFAULT, - NestedSetBuilder.<Artifact>stableOrder() - .add(enabledFeaturesFile) - .add(requestedFeaturesFile) - .build()); - } - return outputGroupsBuilder.buildOrThrow(); - } - public static boolean isOldStarlarkApiWhiteListed( StarlarkRuleContext starlarkRuleContext, List<String> whitelistedPackages) { RuleContext context = starlarkRuleContext.getRuleContext();
diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcCompilationHelper.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcCompilationHelper.java index 9fd60eb..6f5b29f 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcCompilationHelper.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcCompilationHelper.java
@@ -24,7 +24,6 @@ import com.google.devtools.build.lib.actions.ActionRegistry; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.Artifact.SpecialArtifact; -import com.google.devtools.build.lib.analysis.OutputGroupInfo; import com.google.devtools.build.lib.analysis.RuleContext; import com.google.devtools.build.lib.analysis.RuleErrorConsumer; import com.google.devtools.build.lib.analysis.TransitiveInfoCollection; @@ -63,7 +62,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.TreeMap; import java.util.stream.Collectors; import javax.annotation.Nullable; import net.starlark.java.eval.Tuple; @@ -366,21 +364,6 @@ shouldProcessHeaders); } - /** Sets fields that overlap for cc_library and cc_binary rules. */ - @CanIgnoreReturnValue - public CcCompilationHelper fromCommon(CcCommon common, ImmutableList<String> additionalCopts) { - Preconditions.checkNotNull(additionalCopts); - - setCopts(ImmutableList.copyOf(Iterables.concat(common.getCopts(), additionalCopts))); - addDefines(common.getDefines()); - addNonTransitiveDefines(common.getNonTransitiveDefines()); - setLooseIncludeDirs(common.getLooseIncludeDirs()); - addSystemIncludeDirs(common.getSystemIncludeDirs()); - setCoptsFilter(common.getCoptsFilter()); - setPurpose(common.getPurpose(semantics)); - return this; - } - /** * Adds {@code headers} as public header files. These files will be made visible to dependent * rules. They may be parsed/preprocessed or compiled into a header module depending on the @@ -563,14 +546,6 @@ compilationUnitSources.put(header, CppSource.create(header, label, CppSource.Type.HEADER)); } - /** Adds a header to {@code publicHeaders}, but not to this target's module map. */ - @CanIgnoreReturnValue - public CcCompilationHelper addNonModuleMapHeader(Artifact header) { - Preconditions.checkNotNull(header); - nonModuleMapHeaders.add(header); - return this; - } - /** * Adds a source to {@code compilationUnitSources} if it is a compiled file type (including * parsed/preprocessed header) and to {@code privateHeaders} if it is a header. @@ -623,16 +598,6 @@ * targets. */ @CanIgnoreReturnValue - public CcCompilationHelper addDefines(NestedSet<String> defines) { - this.defines.addAll(defines.toList()); - return this; - } - - /** - * Adds the given defines to the compiler command line of this target as well as its dependent - * targets. - */ - @CanIgnoreReturnValue public CcCompilationHelper addDefines(Iterable<String> defines) { Iterables.addAll(this.defines, defines); return this; @@ -681,16 +646,6 @@ * "-isystem"} to the compiler); these are also passed to dependent rules. */ @CanIgnoreReturnValue - public CcCompilationHelper addSystemIncludeDirs(NestedSet<PathFragment> systemIncludeDirs) { - this.systemIncludeDirs.addAll(systemIncludeDirs.toList()); - return this; - } - - /** - * Adds the given directories to the system include directories (they are passed with {@code - * "-isystem"} to the compiler); these are also passed to dependent rules. - */ - @CanIgnoreReturnValue public CcCompilationHelper addSystemIncludeDirs(Iterable<PathFragment> systemIncludeDirs) { Iterables.addAll(this.systemIncludeDirs, systemIncludeDirs); return this; @@ -701,16 +656,6 @@ * "-iquote"} to the compiler); these are also passed to dependent rules. */ @CanIgnoreReturnValue - public CcCompilationHelper addQuoteIncludeDirs(NestedSet<PathFragment> quoteIncludeDirs) { - this.quoteIncludeDirs.addAll(quoteIncludeDirs.toList()); - return this; - } - - /** - * Adds the given directories to the quote include directories (they are passed with {@code - * "-iquote"} to the compiler); these are also passed to dependent rules. - */ - @CanIgnoreReturnValue public CcCompilationHelper addQuoteIncludeDirs(Iterable<PathFragment> quoteIncludeDirs) { Iterables.addAll(this.quoteIncludeDirs, quoteIncludeDirs); return this; @@ -721,16 +666,6 @@ * compiler); these are also passed to dependent rules. */ @CanIgnoreReturnValue - public CcCompilationHelper addIncludeDirs(NestedSet<PathFragment> includeDirs) { - this.includeDirs.addAll(includeDirs.toList()); - return this; - } - - /** - * Adds the given directories to the include directories (they are passed with {@code "-I"} to the - * compiler); these are also passed to dependent rules. - */ - @CanIgnoreReturnValue public CcCompilationHelper addIncludeDirs(Iterable<PathFragment> includeDirs) { Iterables.addAll(this.includeDirs, includeDirs); return this; @@ -869,54 +804,6 @@ } } - public static Map<String, NestedSet<Artifact>> buildOutputGroups( - CcCompilationOutputs ccCompilationOutputs) { - Map<String, NestedSet<Artifact>> outputGroups = new TreeMap<>(); - outputGroups.put(OutputGroupInfo.TEMP_FILES, ccCompilationOutputs.getTemps()); - return outputGroups; - } - - public static Map<String, NestedSet<Artifact>> buildOutputGroupsForEmittingCompileProviders( - CcCompilationOutputs ccCompilationOutputs, - CcCompilationContext ccCompilationContext, - CppConfiguration cppConfiguration, - CcToolchainProvider ccToolchain, - FeatureConfiguration featureConfiguration, - RuleContext ruleContext, - boolean generateHiddenTopLevelGroup) { - ImmutableMap.Builder<String, NestedSet<Artifact>> outputGroupsBuilder = ImmutableMap.builder(); - outputGroupsBuilder.put(OutputGroupInfo.TEMP_FILES, ccCompilationOutputs.getTemps()); - boolean processHeadersInDependencies = cppConfiguration.processHeadersInDependencies(); - boolean usePic = ccToolchain.usePicForDynamicLibraries(cppConfiguration, featureConfiguration); - NestedSet<Artifact> filesToCompile = - ccCompilationOutputs.getFilesToCompile(processHeadersInDependencies, usePic); - outputGroupsBuilder.put(OutputGroupInfo.FILES_TO_COMPILE, filesToCompile); - outputGroupsBuilder.put( - OutputGroupInfo.COMPILATION_PREREQUISITES, - CcCommon.collectCompilationPrerequisites(ruleContext, ccCompilationContext)); - if (generateHiddenTopLevelGroup) { - outputGroupsBuilder.put( - OutputGroupInfo.HIDDEN_TOP_LEVEL, - collectLibraryHiddenTopLevelArtifacts(ruleContext, filesToCompile)); - } - outputGroupsBuilder.putAll( - CcCommon.createSaveFeatureStateArtifacts( - cppConfiguration, featureConfiguration, ruleContext)); - return outputGroupsBuilder.buildOrThrow(); - } - - private static NestedSet<Artifact> collectLibraryHiddenTopLevelArtifacts( - RuleContext ruleContext, NestedSet<Artifact> filesToCompile) { - // Ensure that we build all the dependencies, otherwise users may get confused. - NestedSetBuilder<Artifact> artifactsToForceBuilder = NestedSetBuilder.stableOrder(); - artifactsToForceBuilder.addTransitive(filesToCompile); - for (OutputGroupInfo dep : - ruleContext.getPrerequisites("deps", OutputGroupInfo.STARLARK_CONSTRUCTOR)) { - artifactsToForceBuilder.addTransitive(dep.getOutputGroup(OutputGroupInfo.HIDDEN_TOP_LEVEL)); - } - return artifactsToForceBuilder.build(); - } - @Immutable private static class PublicHeaders { private final ImmutableList<Artifact> headers; @@ -1269,19 +1156,6 @@ !featureConfiguration.isEnabled(CppRuleClasses.MODULE_MAP_WITHOUT_EXTERN_MODULE)); } - public static CcCompilationContext getStlCcCompilationContext(RuleContext ruleContext) { - if (ruleContext.attributes().has("$stl", BuildType.LABEL)) { - CcInfo ccInfo = ruleContext.getPrerequisite("$stl", CcInfo.PROVIDER); - if (ccInfo != null) { - return ccInfo.getCcCompilationContext(); - } else { - return CcCompilationContext.EMPTY; - } - } else { - return CcCompilationContext.EMPTY; - } - } - private List<CppModuleMap> collectModuleMaps() { ImmutableList.Builder<CppModuleMap> builder = ImmutableList.<CppModuleMap>builder(); // TODO(bazel-team): Here we use the implementationDeps to build the dependents of this rule's
diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLibrary.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLibrary.java deleted file mode 100644 index e6c8f12..0000000 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLibrary.java +++ /dev/null
@@ -1,822 +0,0 @@ -// Copyright 2014 The Bazel Authors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package com.google.devtools.build.lib.rules.cpp; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSortedMap; -import com.google.common.collect.Iterables; -import com.google.devtools.build.lib.actions.Artifact; -import com.google.devtools.build.lib.actions.FailAction; -import com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException; -import com.google.devtools.build.lib.analysis.AnalysisUtils; -import com.google.devtools.build.lib.analysis.ConfiguredTarget; -import com.google.devtools.build.lib.analysis.FileProvider; -import com.google.devtools.build.lib.analysis.FilesToRunProvider; -import com.google.devtools.build.lib.analysis.MakeVariableSupplier.MapBackedMakeVariableSupplier; -import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder; -import com.google.devtools.build.lib.analysis.RuleConfiguredTargetFactory; -import com.google.devtools.build.lib.analysis.RuleContext; -import com.google.devtools.build.lib.analysis.RuleErrorConsumer; -import com.google.devtools.build.lib.analysis.Runfiles; -import com.google.devtools.build.lib.analysis.RunfilesProvider; -import com.google.devtools.build.lib.analysis.TransitiveInfoCollection; -import com.google.devtools.build.lib.analysis.config.BuildConfigurationValue; -import com.google.devtools.build.lib.analysis.test.InstrumentedFilesInfo; -import com.google.devtools.build.lib.cmdline.Label; -import com.google.devtools.build.lib.collect.nestedset.NestedSet; -import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; -import com.google.devtools.build.lib.collect.nestedset.Order; -import com.google.devtools.build.lib.packages.AttributeMap; -import com.google.devtools.build.lib.packages.BuildType; -import com.google.devtools.build.lib.packages.RawAttributeMapper; -import com.google.devtools.build.lib.packages.TargetUtils; -import com.google.devtools.build.lib.packages.Type; -import com.google.devtools.build.lib.rules.cpp.CcCommon.CcFlagsSupplier; -import com.google.devtools.build.lib.rules.cpp.CcCommon.Language; -import com.google.devtools.build.lib.rules.cpp.CcCompilationHelper.CompilationInfo; -import com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.FeatureConfiguration; -import com.google.devtools.build.lib.rules.cpp.Link.LinkTargetType; -import com.google.devtools.build.lib.server.FailureDetails.FailAction.Code; -import com.google.devtools.build.lib.util.FileTypeSet; -import com.google.devtools.build.lib.vfs.PathFragment; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import javax.annotation.Nullable; -import net.starlark.java.eval.EvalException; - -/** - * A ConfiguredTarget for <code>cc_library</code> rules. - */ -public abstract class CcLibrary implements RuleConfiguredTargetFactory { - - /** A string constant for the name of archive library(.a, .lo) output group. */ - public static final String ARCHIVE_LIBRARY_OUTPUT_GROUP_NAME = "archive"; - - /** A string constant for the name of dynamic library output group. */ - public static final String DYNAMIC_LIBRARY_OUTPUT_GROUP_NAME = "dynamic_library"; - - /** A string constant for the name of Windows def file output group. */ - public static final String DEF_FILE_OUTPUT_GROUP_NAME = "def_file"; - - private final CppSemantics semantics; - - protected CcLibrary(CppSemantics semantics) { - this.semantics = semantics; - } - - // These file extensions don't generate object files. - private static final FileTypeSet NO_OBJECT_GENERATING_FILETYPES = FileTypeSet.of( - CppFileTypes.CPP_HEADER, CppFileTypes.ARCHIVE, CppFileTypes.PIC_ARCHIVE, - CppFileTypes.ALWAYS_LINK_LIBRARY, CppFileTypes.ALWAYS_LINK_PIC_LIBRARY, - CppFileTypes.SHARED_LIBRARY, CppFileTypes.VERSIONED_SHARED_LIBRARY); - - @Override - @Nullable - public ConfiguredTarget create(RuleContext context) - throws InterruptedException, RuleErrorException, ActionConflictException { - RuleConfiguredTargetBuilder builder = new RuleConfiguredTargetBuilder(context); - boolean linkStatic = context.attributes().get("linkstatic", Type.BOOLEAN); - init( - semantics, - context, - builder, - /* additionalCopts= */ ImmutableList.of(), - /* soFilename= */ null, - context.attributes().get("alwayslink", Type.BOOLEAN), - /* neverLink= */ false, - linkStatic, - /* addDynamicRuntimeInputArtifactsToRunfiles= */ false); - return builder.build(); - } - - public static void init( - CppSemantics semantics, - RuleContext ruleContext, - RuleConfiguredTargetBuilder targetBuilder, - ImmutableList<String> additionalCopts, - PathFragment soFilename, - boolean alwaysLink, - boolean neverLink, - boolean linkStatic, - boolean addDynamicRuntimeInputArtifactsToRunfiles) - throws RuleErrorException, InterruptedException { - semantics.validateDeps(ruleContext); - if (ruleContext.hasErrors()) { - addEmptyRequiredProviders(targetBuilder); - return; - } - - semantics.checkCanUseImplementationDeps(ruleContext); - - final CcCommon common = new CcCommon(ruleContext); - common.reportInvalidOptions(ruleContext); - - CcToolchainProvider ccToolchain = common.getToolchain(); - - ImmutableMap.Builder<String, String> toolchainMakeVariables = ImmutableMap.builder(); - ccToolchain.addGlobalMakeVariables(toolchainMakeVariables); - ruleContext.initConfigurationMakeVariableContext( - new MapBackedMakeVariableSupplier(toolchainMakeVariables.buildOrThrow()), - new CcFlagsSupplier(ruleContext)); - - FdoContext fdoContext = common.getFdoContext(); - FeatureConfiguration featureConfiguration = - CcCommon.configureFeaturesOrReportRuleError( - ruleContext, Language.CPP, ccToolchain, semantics); - PrecompiledFiles precompiledFiles = new PrecompiledFiles(ruleContext); - - semantics.validateAttributes(ruleContext); - if (ruleContext.hasErrors()) { - addEmptyRequiredProviders(targetBuilder); - return; - } - - ImmutableList<TransitiveInfoCollection> deps = - ImmutableList.copyOf(ruleContext.getPrerequisites("deps")); - if (ruleContext.hasErrors()) { - addEmptyRequiredProviders(targetBuilder); - return; - } - - ImmutableList.Builder<CcCompilationContext> interfaceDeps = ImmutableList.builder(); - ImmutableList.Builder<CcCompilationContext> implementationDeps = ImmutableList.builder(); - - interfaceDeps.addAll( - CppHelper.getCompilationContextsFromDeps( - ImmutableList.copyOf(ruleContext.getPrerequisites("deps")))); - implementationDeps.addAll( - CppHelper.getCompilationContextsFromDeps( - ImmutableList.copyOf(ruleContext.getPrerequisites("implementation_deps")))); - interfaceDeps.add(CcCompilationHelper.getStlCcCompilationContext(ruleContext)); - - CcCompilationHelper compilationHelper = - new CcCompilationHelper( - ruleContext, - ruleContext, - ruleContext.getLabel(), - CppHelper.getGrepIncludes(ruleContext), - semantics, - featureConfiguration, - ccToolchain, - fdoContext, - TargetUtils.getExecutionInfo( - ruleContext.getRule(), ruleContext.isAllowTagsPropagation()), - /* shouldProcessHeaders= */ true) - .fromCommon(common, additionalCopts) - .addSources(common.getSources()) - .addPrivateHeaders(common.getPrivateHeaders()) - .addPublicHeaders(common.getHeaders()) - .setCodeCoverageEnabled(CcCompilationHelper.isCodeCoverageEnabled(ruleContext)) - .addCcCompilationContexts(interfaceDeps.build()) - .addImplementationDepsCcCompilationContexts(implementationDeps.build()) - .setHeadersCheckingMode(semantics.determineHeadersCheckingMode(ruleContext)); - - CcLinkingHelper linkingHelper = - new CcLinkingHelper( - ruleContext, - ruleContext.getLabel(), - ruleContext, - ruleContext, - semantics, - featureConfiguration, - ccToolchain, - fdoContext, - ruleContext.getConfiguration(), - ruleContext.getFragment(CppConfiguration.class), - ruleContext.getSymbolGenerator(), - TargetUtils.getExecutionInfo( - ruleContext.getRule(), ruleContext.isAllowTagsPropagation())) - .fromCommon(ruleContext, common) - .addCcLinkingContexts( - CppHelper.getLinkingContextsFromDeps( - ImmutableList.copyOf(ruleContext.getPrerequisites("deps")))) - .addCcLinkingContexts( - CppHelper.getLinkingContextsFromDeps( - ImmutableList.copyOf(ruleContext.getPrerequisites("implementation_deps")))) - .setGrepIncludes(CppHelper.getGrepIncludes(ruleContext)) - .setTestOrTestOnlyTarget(ruleContext.isTestOnlyTarget()) - .addLinkopts(common.getLinkopts()) - .emitInterfaceSharedLibraries(true) - .setAlwayslink(alwaysLink) - .setNeverLink(neverLink) - .addLinkstamps(ruleContext.getPrerequisites("linkstamp")); - - Artifact soImplArtifact = null; - boolean supportsDynamicLinker = ccToolchain.supportsDynamicLinker(featureConfiguration); - // TODO(djasper): This is hacky. We should actually try to figure out whether we generate - // ccOutputs. - boolean createDynamicLibrary = - !linkStatic - && supportsDynamicLinker - && (appearsToHaveObjectFiles(ruleContext.attributes()) - || featureConfiguration.isEnabled(CppRuleClasses.HEADER_MODULE_CODEGEN)); - if (soFilename != null) { - if (!soFilename.getPathString().endsWith(".so")) { - ruleContext.attributeError("outs", "file name must end in '.so'"); - } - if (createDynamicLibrary) { - soImplArtifact = ruleContext.getBinArtifact(soFilename); - } - } - - if (ruleContext.getRule().isAttrDefined("textual_hdrs", BuildType.LABEL_LIST)) { - compilationHelper.addPublicTextualHeaders( - ruleContext.getPrerequisiteArtifacts("textual_hdrs").list()); - } - if (ruleContext.getRule().isAttrDefined("include_prefix", Type.STRING) - && ruleContext.attributes().isAttributeValueExplicitlySpecified("include_prefix")) { - compilationHelper.setIncludePrefix( - ruleContext.attributes().get("include_prefix", Type.STRING)); - } - if (ruleContext.getRule().isAttrDefined("strip_include_prefix", Type.STRING) - && ruleContext.attributes().isAttributeValueExplicitlySpecified("strip_include_prefix")) { - compilationHelper.setStripIncludePrefix( - ruleContext.attributes().get("strip_include_prefix", Type.STRING)); - } - - if (common.getLinkopts().contains("-static")) { - ruleContext.attributeWarning( - "linkopts", - "Using '-static' here won't work. " + "Did you mean to use 'linkstatic=True' instead?"); - } - - linkingHelper.setShouldCreateDynamicLibrary(createDynamicLibrary); - linkingHelper.setLinkerOutputArtifact(soImplArtifact); - - CppConfiguration cppConfiguration = ruleContext.getFragment(CppConfiguration.class); - - // If the reason we're not creating a dynamic library is that the toolchain - // doesn't support it, then register an action which complains when triggered, - // which only happens when some rule explicitly depends on the dynamic library. - if (!createDynamicLibrary && !supportsDynamicLinker) { - ImmutableList.Builder<Artifact> dynamicLibraries = ImmutableList.builder(); - dynamicLibraries.add( - CppHelper.getLinkedArtifact( - ruleContext, - ccToolchain, - ruleContext.getConfiguration(), - LinkTargetType.NODEPS_DYNAMIC_LIBRARY, - CppHelper.getDLLHashSuffix(ruleContext, featureConfiguration))); - if (CppHelper.useInterfaceSharedLibraries( - cppConfiguration, ccToolchain, featureConfiguration)) { - dynamicLibraries.add( - CppHelper.getLinkedArtifact( - ruleContext, - ccToolchain, - ruleContext.getConfiguration(), - LinkTargetType.INTERFACE_DYNAMIC_LIBRARY)); - } - ruleContext.registerAction( - new FailAction( - ruleContext.getActionOwner(), - dynamicLibraries.build(), - "Toolchain does not support dynamic linking", - Code.DYNAMIC_LINKING_NOT_SUPPORTED)); - } else if (!createDynamicLibrary - && ruleContext.attributes().isConfigurable("srcs")) { - // If "srcs" is configurable, the .so output is always declared because the logic that - // determines implicit outs doesn't know which value of "srcs" will ultimately get chosen. - // Here, where we *do* have the correct value, it may not contain any source files to - // generate an .so with. If that's the case, register a fake generating action to prevent - // a "no generating action for this artifact" error. - ImmutableList.Builder<Artifact> dynamicLibraries = ImmutableList.builder(); - dynamicLibraries.add( - CppHelper.getLinkedArtifact( - ruleContext, - ccToolchain, - ruleContext.getConfiguration(), - LinkTargetType.NODEPS_DYNAMIC_LIBRARY, - CppHelper.getDLLHashSuffix(ruleContext, featureConfiguration))); - if (CppHelper.useInterfaceSharedLibraries( - cppConfiguration, ccToolchain, featureConfiguration)) { - dynamicLibraries.add( - CppHelper.getLinkedArtifact( - ruleContext, - ccToolchain, - ruleContext.getConfiguration(), - LinkTargetType.INTERFACE_DYNAMIC_LIBRARY)); - } - ruleContext.registerAction( - new FailAction( - ruleContext.getActionOwner(), - dynamicLibraries.build(), - "configurable \"srcs\" triggers an implicit .so output even though there are no" - + " sources to compile in this configuration", - Code.SOURCE_FILES_MISSING)); - } - - CompilationInfo compilationInfo = compilationHelper.compile(ruleContext); - CcCompilationOutputs precompiledFilesObjects = - CcCompilationOutputs.builder() - .addObjectFiles(precompiledFiles.getObjectFiles(/* usePic= */ true)) - .addPicObjectFiles(precompiledFiles.getObjectFiles(/* usePic= */ true)) - .build(); - CcCompilationOutputs ccCompilationOutputs = - CcCompilationOutputs.builder() - .merge(precompiledFilesObjects) - .merge(compilationInfo.getCcCompilationOutputs()) - .build(); - - // Generate .a and .so outputs even without object files to fulfill the rule class - // contract wrt. implicit output files, if the contract says so. Behavior here differs - // between Bazel and Blaze. - CcLinkingOutputs ccLinkingOutputs = CcLinkingOutputs.EMPTY; - if (semantics.createEmptyArchive() || !ccCompilationOutputs.isEmpty()) { - if (featureConfiguration.isEnabled(CppRuleClasses.TARGETS_WINDOWS)) { - String dllNameSuffix = CppHelper.getDLLHashSuffix(ruleContext, featureConfiguration); - linkingHelper.setLinkedDLLNameSuffix(dllNameSuffix); - Artifact generatedDefFile = null; - - Artifact defParser = common.getDefParser(); - if (defParser != null) { - generatedDefFile = - CppHelper.createDefFileActions( - ruleContext, - defParser, - ccCompilationOutputs.getObjectFiles(false), - ccToolchain - .getFeatures() - .getArtifactNameForCategory( - ArtifactCategory.DYNAMIC_LIBRARY, - ruleContext.getLabel().getName() + dllNameSuffix)); - targetBuilder.addOutputGroup(DEF_FILE_OUTPUT_GROUP_NAME, generatedDefFile); - } - linkingHelper.setDefFile( - CppHelper.getWindowsDefFileForLinking( - ruleContext, common.getWinDefFile(), generatedDefFile, featureConfiguration)); - } - ccLinkingOutputs = linkingHelper.link(ccCompilationOutputs); - } - - ImmutableSortedMap.Builder<String, NestedSet<Artifact>> outputGroups = - ImmutableSortedMap.naturalOrder(); - if (!ccLinkingOutputs.isEmpty()) { - outputGroups.putAll( - addLinkerOutputArtifacts( - ruleContext, - ccToolchain, - cppConfiguration, - ruleContext.getConfiguration(), - ccCompilationOutputs, - featureConfiguration)); - } - List<LibraryToLink> precompiledLibraries = - convertPrecompiledLibrariesToLibraryToLink( - ruleContext, - common, - ruleContext.getFragment(CppConfiguration.class).forcePic(), - precompiledFiles); - - if (!ccCompilationOutputs.isEmpty()) { - checkIfLinkOutputsCollidingWithPrecompiledFiles( - ruleContext, ccLinkingOutputs, precompiledLibraries); - } - - ImmutableList<LibraryToLink> libraryToLinks = - createLibrariesToLinkList( - ccLinkingOutputs.getLibraryToLink(), - precompiledLibraries, - ccCompilationOutputs.isEmpty()); - - CcLinkingContext ccLinkingContext = - linkingHelper.buildCcLinkingContextFromLibrariesToLink( - neverLink ? ImmutableList.of() : libraryToLinks, - compilationInfo.getCcCompilationContext()); - CcNativeLibraryInfo ccNativeLibraryInfo = - CppHelper.collectNativeCcLibraries(ruleContext.getPrerequisites("deps"), libraryToLinks); - - /* - * We always generate a static library, even if there aren't any source files. - * This keeps things simpler by avoiding special cases when making use of the library. - * For example, this is needed to ensure that building a library with "bazel build" - * will also build all of the library's "deps". - * However, we only generate a dynamic library if there are source files. - */ - // For now, we don't add the precompiled libraries to the files to build. - - NestedSetBuilder<Artifact> filesBuilder = NestedSetBuilder.stableOrder(); - if (!ccLinkingOutputs.isEmpty()) { - LibraryToLink artifactsToBuild = ccLinkingOutputs.getLibraryToLink(); - if (artifactsToBuild.getStaticLibrary() != null) { - filesBuilder.add(artifactsToBuild.getStaticLibrary()); - } - if (artifactsToBuild.getPicStaticLibrary() != null) { - filesBuilder.add(artifactsToBuild.getPicStaticLibrary()); - } - if (!featureConfiguration.isEnabled(CppRuleClasses.TARGETS_WINDOWS)) { - if (artifactsToBuild.getResolvedSymlinkDynamicLibrary() != null) { - filesBuilder.add(artifactsToBuild.getResolvedSymlinkDynamicLibrary()); - } else if (artifactsToBuild.getDynamicLibrary() != null) { - filesBuilder.add(artifactsToBuild.getDynamicLibrary()); - } - if (artifactsToBuild.getResolvedSymlinkInterfaceLibrary() != null) { - filesBuilder.add(artifactsToBuild.getResolvedSymlinkInterfaceLibrary()); - } else if (artifactsToBuild.getInterfaceLibrary() != null) { - filesBuilder.add(artifactsToBuild.getInterfaceLibrary()); - } - } - } - - if (!featureConfiguration.isEnabled(CppRuleClasses.HEADER_MODULE_CODEGEN)) { - warnAboutEmptyLibraries(ruleContext, ccCompilationOutputs, linkStatic); - } - NestedSet<Artifact> filesToBuild = filesBuilder.build(); - - List<Artifact> instrumentedObjectFiles = new ArrayList<>(); - instrumentedObjectFiles.addAll(compilationInfo.getCcCompilationOutputs().getObjectFiles(false)); - instrumentedObjectFiles.addAll(compilationInfo.getCcCompilationOutputs().getObjectFiles(true)); - InstrumentedFilesInfo instrumentedFilesProvider = - common.getInstrumentedFilesProvider( - instrumentedObjectFiles, - /* withBaselineCoverage= */ true, - /* virtualToOriginalHeaders= */ NestedSetBuilder.create(Order.STABLE_ORDER), - /* additionalMetadata= */ null); - CppHelper.maybeAddStaticLinkMarkerProvider(targetBuilder, ruleContext); - - Runfiles.Builder builder = new Runfiles.Builder(ruleContext.getWorkspaceName()); - builder.addDataDeps(ruleContext); - builder.add(ruleContext, RunfilesProvider.DEFAULT_RUNFILES); - if (addDynamicRuntimeInputArtifactsToRunfiles) { - try { - builder.addTransitiveArtifacts( - ccToolchain.getDynamicRuntimeLinkInputs(featureConfiguration)); - } catch (EvalException e) { - throw ruleContext.throwWithRuleError(e); - } - } - Runfiles runfiles = builder.build(); - Runfiles.Builder defaultRunfiles = - new Runfiles.Builder(ruleContext.getWorkspaceName()) - .merge(runfiles) - .addArtifacts(LibraryToLink.getDynamicLibrariesForRuntime(!neverLink, libraryToLinks)); - - Runfiles.Builder dataRunfiles = - new Runfiles.Builder(ruleContext.getWorkspaceName()) - .merge(runfiles) - .addArtifacts( - LibraryToLink.getDynamicLibrariesForRuntime( - /* linkingStatically= */ false, libraryToLinks)); - - Map<String, NestedSet<Artifact>> currentOutputGroups = - CcCompilationHelper.buildOutputGroupsForEmittingCompileProviders( - compilationInfo.getCcCompilationOutputs(), - compilationInfo.getCcCompilationContext(), - ruleContext.getFragment(CppConfiguration.class), - ccToolchain, - featureConfiguration, - ruleContext, - /* generateHiddenTopLevelGroup= */ true); - targetBuilder - .setFilesToBuild(filesToBuild) - .addNativeDeclaredProvider( - CcInfo.builder() - .setCcCompilationContext(compilationInfo.getCcCompilationContext()) - .setCcLinkingContext(ccLinkingContext) - .setCcDebugInfoContext( - CppHelper.mergeCcDebugInfoContexts( - compilationInfo.getCcCompilationOutputs(), - AnalysisUtils.getProviders(deps, CcInfo.PROVIDER))) - .setCcNativeLibraryInfo(ccNativeLibraryInfo) - .build()) - .addOutputGroups( - CcCommon.mergeOutputGroups( - ImmutableList.of(currentOutputGroups, outputGroups.buildOrThrow()))) - .addNativeDeclaredProvider(instrumentedFilesProvider) - .addProvider(RunfilesProvider.withData(defaultRunfiles.build(), dataRunfiles.build())); - } - - private static void warnAboutEmptyLibraries(RuleContext ruleContext, - CcCompilationOutputs ccCompilationOutputs, - boolean linkstaticAttribute) { - if (ccCompilationOutputs.getObjectFiles(false).isEmpty() - && ccCompilationOutputs.getObjectFiles(true).isEmpty()) { - if (!linkstaticAttribute && appearsToHaveObjectFiles(ruleContext.attributes())) { - ruleContext.attributeWarning( - "linkstatic", "setting 'linkstatic=True' is recommended if there are no object files"); - } - } else { - if (!linkstaticAttribute && !appearsToHaveObjectFiles(ruleContext.attributes())) { - Artifact element = Iterables.getFirst( - ccCompilationOutputs.getObjectFiles(false), - ccCompilationOutputs.getObjectFiles(true).get(0)); - ruleContext.attributeWarning( - "srcs", - "this library appears at first glance to have no object files, " - + "but on closer inspection it does have something to link, e.g. " - + element.prettyPrint() - + ". " - + "(You may have used some very confusing rule names in srcs? " - + "Or the library consists entirely of a linker script?) " - + "Bazel assumed linkstatic=True, but this may be inappropriate. " - + "You may need to add an explicit '.cc' file to 'srcs'. " - + "Alternatively, add 'linkstatic=True' to suppress this warning"); - } - } - } - - /** - * Returns true if the rule (which must be a cc_library rule) appears to have object files. - * This only looks at the rule itself, not at any other rules (from this package or other - * packages) that it might reference. - * - * <p>In some cases, this may return "true" even though the rule actually has no object files. - * For example, it will return true for a rule such as - * <code>cc_library(name = 'foo', srcs = [':bar'])</code> because we can't tell what ':bar' is; - * it might be a genrule that generates a source file, or it might be a genrule that generates a - * header file. Likewise, - * <code>cc_library(name = 'foo', srcs = select({':a': ['foo.cc'], ':b': []}))</code> returns - * "true" even though the sources *may* be empty. This reflects the fact that there's no way - * to tell which value "srcs" will take without knowing the rule's configuration. - * - * <p>In other cases, this may return "false" even though the rule actually does have object - * files. For example, it will return false for a rule such as - * <code>cc_library(name = 'foo', srcs = ['bar.h'])</code> but as in the other example above, - * we can't tell whether 'bar.h' is a file name or a rule name, and 'bar.h' could in fact be the - * name of a genrule that generates a source file. - */ - public static boolean appearsToHaveObjectFiles(AttributeMap rule) { - if ((rule instanceof RawAttributeMapper) && rule.isConfigurable("srcs")) { - // Since this method gets called by loading phase logic (e.g. the cc_library implicit outputs - // function), the attribute mapper may not be able to resolve configurable attributes. When - // that's the case, there's no way to know which value a configurable "srcs" will take, so - // we conservatively assume object files are possible. - return true; - } - - List<Label> srcs = rule.get("srcs", BuildType.LABEL_LIST); - if (srcs != null) { - for (Label srcfile : srcs) { - /* - * We cheat a little bit here by looking at the file extension - * of the Label treated as file name. In general that might - * not necessarily work, because of the possibility that the - * user might give a rule a funky name ending in one of these - * extensions, e.g. - * genrule(name = 'foo.h', outs = ['foo.cc'], ...) // Funky rule name! - * cc_library(name = 'bar', srcs = ['foo.h']) // This DOES have object files. - */ - if (!NO_OBJECT_GENERATING_FILETYPES.matches(srcfile.getName())) { - return true; - } - } - } - return false; - } - - /** - * Adds linker output artifacts to the given map, to be registered on the configured target as - * output groups. - */ - private static Map<String, NestedSet<Artifact>> addLinkerOutputArtifacts( - RuleContext ruleContext, - CcToolchainProvider ccToolchain, - CppConfiguration cppConfiguration, - BuildConfigurationValue configuration, - CcCompilationOutputs ccCompilationOutputs, - FeatureConfiguration featureConfiguration) - throws RuleErrorException { - - NestedSetBuilder<Artifact> archiveFile = new NestedSetBuilder<>(Order.STABLE_ORDER); - NestedSetBuilder<Artifact> dynamicLibrary = new NestedSetBuilder<>(Order.STABLE_ORDER); - - ImmutableSortedMap.Builder<String, NestedSet<Artifact>> outputGroups = - ImmutableSortedMap.naturalOrder(); - if (!ruleContext.attributes().has("alwayslink", Type.BOOLEAN) - || !ruleContext.attributes().has("linkstatic", Type.BOOLEAN)) { - return outputGroups.buildOrThrow(); - } - - if (ruleContext.attributes().get("alwayslink", Type.BOOLEAN)) { - archiveFile.add( - CppHelper.getLinkedArtifact( - ruleContext, - ccToolchain, - configuration, - Link.LinkTargetType.ALWAYS_LINK_STATIC_LIBRARY, - /* linkedArtifactNameSuffix= */ "")); - } else { - archiveFile.add( - CppHelper.getLinkedArtifact( - ruleContext, - ccToolchain, - configuration, - Link.LinkTargetType.STATIC_LIBRARY, - /* linkedArtifactNameSuffix= */ "")); - } - - if (!ruleContext.attributes().get("linkstatic", Type.BOOLEAN) - && !ccCompilationOutputs.isEmpty()) { - dynamicLibrary.add( - CppHelper.getLinkedArtifact( - ruleContext, - ccToolchain, - configuration, - Link.LinkTargetType.NODEPS_DYNAMIC_LIBRARY, - CppHelper.getDLLHashSuffix(ruleContext, featureConfiguration))); - - if (CppHelper.useInterfaceSharedLibraries( - cppConfiguration, ccToolchain, featureConfiguration)) { - dynamicLibrary.add( - CppHelper.getLinkedArtifact( - ruleContext, - ccToolchain, - configuration, - LinkTargetType.INTERFACE_DYNAMIC_LIBRARY, - /* linkedArtifactNameSuffix= */ "")); - } - } - - outputGroups.put(ARCHIVE_LIBRARY_OUTPUT_GROUP_NAME, archiveFile.build()); - outputGroups.put(DYNAMIC_LIBRARY_OUTPUT_GROUP_NAME, dynamicLibrary.build()); - return outputGroups.buildOrThrow(); - } - - private static ImmutableList<LibraryToLink> createLibrariesToLinkList( - @Nullable LibraryToLink outputLibrary, - List<LibraryToLink> precompiledLibraries, - boolean ccCompilationOutputsIsEmpty) { - ImmutableList.Builder<LibraryToLink> librariesToLink = ImmutableList.builder(); - librariesToLink.addAll(precompiledLibraries); - - // For cc_library if it contains precompiled libraries we link them. If it contains normal - // sources we link them as well, if it doesn't contain normal sources, then we don't do - // anything else if there were precompiled libraries. However, if there are no precompiled - // libraries and there are no normal sources, then we use the implicitly created link output - // files if they exist. - if (!ccCompilationOutputsIsEmpty - || (precompiledLibraries.isEmpty() - && isContentsOfCcLinkingOutputsImplicitlyCreated( - ccCompilationOutputsIsEmpty, outputLibrary == null))) { - if (outputLibrary != null) { - librariesToLink.add(outputLibrary); - } - } - - return librariesToLink.build(); - } - - private static boolean isContentsOfCcLinkingOutputsImplicitlyCreated( - boolean ccCompilationOutputsIsEmpty, boolean ccLinkingOutputsIsEmpty) { - return ccCompilationOutputsIsEmpty && !ccLinkingOutputsIsEmpty; - } - - private static ImmutableMap<String, Artifact> buildMapIdentifierToArtifact( - RuleErrorConsumer ruleErrorConsumer, Iterable<Artifact> artifacts) { - Map<String, Artifact> libraries = new LinkedHashMap<>(); - for (Artifact artifact : artifacts) { - String identifier = CcLinkingOutputs.libraryIdentifierOf(artifact); - if (libraries.containsKey(identifier)) { - ruleErrorConsumer.attributeError( - "srcs", - String.format( - "Trying to link twice a library with the same identifier '%s', files: %s and %s", - identifier, artifact.toDetailString(), libraries.get(identifier).toDetailString())); - } - libraries.put(identifier, artifact); - } - return ImmutableMap.copyOf(libraries); - } - - /* - * Add the libraries from srcs, if any. For static/mostly static - * linking we setup the dynamic libraries if there are no static libraries - * to choose from. Path to the libraries will be mangled to avoid using - * absolute path names on the -rpath, but library filenames will be - * preserved (since some libraries might have SONAME tag) - symlink will - * be created to the parent directory instead. - * - * For compatibility with existing BUILD files, any ".a" or ".lo" files listed in - * srcs are assumed to be position-independent code, or at least suitable for - * inclusion in shared libraries, unless they end with ".nopic.a" or ".nopic.lo". - * - * Note that some target platforms do not require shared library code to be PIC. - */ - private static List<LibraryToLink> convertPrecompiledLibrariesToLibraryToLink( - RuleErrorConsumer ruleErrorConsumer, - CcCommon common, - boolean forcePic, - PrecompiledFiles precompiledFiles) { - ImmutableList.Builder<LibraryToLink> librariesToLink = ImmutableList.builder(); - - Map<String, Artifact> staticLibraries = - buildMapIdentifierToArtifact(ruleErrorConsumer, precompiledFiles.getStaticLibraries()); - Map<String, Artifact> picStaticLibraries = - buildMapIdentifierToArtifact(ruleErrorConsumer, precompiledFiles.getPicStaticLibraries()); - Map<String, Artifact> alwayslinkStaticLibraries = - buildMapIdentifierToArtifact( - ruleErrorConsumer, precompiledFiles.getAlwayslinkStaticLibraries()); - Map<String, Artifact> alwayslinkPicStaticLibraries = - buildMapIdentifierToArtifact( - ruleErrorConsumer, precompiledFiles.getPicAlwayslinkLibraries()); - Map<String, Artifact> dynamicLibraries = - buildMapIdentifierToArtifact(ruleErrorConsumer, precompiledFiles.getSharedLibraries()); - - Set<String> identifiersUsed = new HashSet<>(); - for (Map.Entry<String, Artifact> staticLibraryEntry : - Iterables.concat(staticLibraries.entrySet(), alwayslinkStaticLibraries.entrySet())) { - LibraryToLink.Builder libraryToLinkBuilder = LibraryToLink.builder(); - String identifier = staticLibraryEntry.getKey(); - libraryToLinkBuilder.setLibraryIdentifier(identifier); - boolean hasPic = picStaticLibraries.containsKey(identifier); - boolean hasAlwaysPic = alwayslinkPicStaticLibraries.containsKey(identifier); - if (hasPic || hasAlwaysPic) { - Artifact picStaticLibrary = null; - if (hasPic) { - picStaticLibrary = picStaticLibraries.get(identifier); - } else { - picStaticLibrary = alwayslinkPicStaticLibraries.get(identifier); - } - libraryToLinkBuilder.setPicStaticLibrary(picStaticLibrary); - } - if (!forcePic || !(hasPic || hasAlwaysPic)) { - libraryToLinkBuilder.setStaticLibrary(staticLibraryEntry.getValue()); - } - if (dynamicLibraries.containsKey(identifier)) { - Artifact library = dynamicLibraries.get(identifier); - Artifact symlink = common.getDynamicLibrarySymlink(library, true); - libraryToLinkBuilder.setDynamicLibrary(symlink); - libraryToLinkBuilder.setResolvedSymlinkDynamicLibrary(library); - } - libraryToLinkBuilder.setAlwayslink(alwayslinkStaticLibraries.containsKey(identifier)); - identifiersUsed.add(identifier); - librariesToLink.add(libraryToLinkBuilder.build()); - } - - for (Map.Entry<String, Artifact> picStaticLibraryEntry : - Iterables.concat(picStaticLibraries.entrySet(), alwayslinkPicStaticLibraries.entrySet())) { - String identifier = picStaticLibraryEntry.getKey(); - if (identifiersUsed.contains(identifier)) { - continue; - } - LibraryToLink.Builder libraryToLinkBuilder = LibraryToLink.builder(); - libraryToLinkBuilder.setLibraryIdentifier(identifier); - libraryToLinkBuilder.setPicStaticLibrary(picStaticLibraryEntry.getValue()); - if (dynamicLibraries.containsKey(identifier)) { - Artifact library = dynamicLibraries.get(identifier); - Artifact symlink = common.getDynamicLibrarySymlink(library, true); - libraryToLinkBuilder.setDynamicLibrary(symlink); - libraryToLinkBuilder.setResolvedSymlinkDynamicLibrary(library); - } - libraryToLinkBuilder.setAlwayslink(alwayslinkPicStaticLibraries.containsKey(identifier)); - identifiersUsed.add(identifier); - librariesToLink.add(libraryToLinkBuilder.build()); - } - - for (Map.Entry<String, Artifact> dynamicLibraryEntry : dynamicLibraries.entrySet()) { - String identifier = dynamicLibraryEntry.getKey(); - if (identifiersUsed.contains(identifier)) { - continue; - } - LibraryToLink.Builder libraryToLinkBuilder = LibraryToLink.builder(); - libraryToLinkBuilder.setLibraryIdentifier(identifier); - Artifact library = dynamicLibraryEntry.getValue(); - Artifact symlink = common.getDynamicLibrarySymlink(library, true); - libraryToLinkBuilder.setDynamicLibrary(symlink); - libraryToLinkBuilder.setResolvedSymlinkDynamicLibrary(library); - librariesToLink.add(libraryToLinkBuilder.build()); - } - return librariesToLink.build(); - } - - private static void checkIfLinkOutputsCollidingWithPrecompiledFiles( - RuleContext ruleContext, - CcLinkingOutputs ccLinkingOutputs, - List<LibraryToLink> precompiledLibraries) { - String identifier = ccLinkingOutputs.getLibraryToLink().getLibraryIdentifier(); - for (LibraryToLink precompiledLibrary : precompiledLibraries) { - if (identifier.equals(precompiledLibrary.getLibraryIdentifier())) { - ruleContext.ruleError( - "Can't put library with identifier '" - + precompiledLibrary.getLibraryIdentifier() - + "' into the srcs of a " - + ruleContext.getRuleClassNameForLogging() - + " with the same name (" - + ruleContext.getRule().getName() - + ") which also contains other code or objects to link"); - } - } - } - - private static void addEmptyRequiredProviders(RuleConfiguredTargetBuilder builder) { - builder.addProvider(RunfilesProvider.EMPTY); - builder.addProvider(FileProvider.EMPTY); - builder.addProvider(FilesToRunProvider.EMPTY); - } -}
diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLinkingHelper.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLinkingHelper.java index 3af5a08..83eeadb 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLinkingHelper.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CcLinkingHelper.java
@@ -22,10 +22,8 @@ import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.ArtifactRoot; import com.google.devtools.build.lib.actions.CommandLineExpansionException; -import com.google.devtools.build.lib.analysis.FileProvider; import com.google.devtools.build.lib.analysis.RuleContext; import com.google.devtools.build.lib.analysis.RuleErrorConsumer; -import com.google.devtools.build.lib.analysis.TransitiveInfoCollection; import com.google.devtools.build.lib.analysis.actions.ActionConstructionContext; import com.google.devtools.build.lib.analysis.config.BuildConfigurationValue; import com.google.devtools.build.lib.cmdline.Label; @@ -174,16 +172,6 @@ this.executionInfo = executionInfo; } - /** Sets fields that overlap for cc_library and cc_binary rules. */ - @CanIgnoreReturnValue - public CcLinkingHelper fromCommon(RuleContext ruleContext, CcCommon common) { - addCcLinkingContexts( - CppHelper.getLinkingContextsFromDeps( - ImmutableList.copyOf(ruleContext.getPrerequisites("deps")))); - addNonCodeLinkerInputs(common.getLinkerScripts()); - return this; - } - @CanIgnoreReturnValue public CcLinkingHelper setNativeDeps(boolean nativeDeps) { this.nativeDeps = nativeDeps; @@ -246,26 +234,6 @@ return this; } - /** - * Adds the given linkstamps. Note that linkstamps are usually not compiled at the library level, - * but only in the dependent binary rules. - */ - @CanIgnoreReturnValue - public CcLinkingHelper addLinkstamps(Iterable<? extends TransitiveInfoCollection> linkstamps) { - for (TransitiveInfoCollection linkstamp : linkstamps) { - this.linkstamps.addTransitive(linkstamp.getProvider(FileProvider.class).getFilesToBuild()); - } - return this; - } - - /** Adds the given artifact to the input of any generated link actions. */ - @CanIgnoreReturnValue - public CcLinkingHelper addLinkActionInput(Artifact input) { - Preconditions.checkNotNull(input); - this.linkActionInputs.add(input); - return this; - } - /** Adds a variableExtension to template the crosstool. */ @CanIgnoreReturnValue public CcLinkingHelper addVariableExtension(VariablesExtension variableExtension) {
diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppHelper.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppHelper.java index 403237c..0051a56 100644 --- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppHelper.java +++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppHelper.java
@@ -17,9 +17,7 @@ import static com.google.devtools.build.lib.packages.BuildType.LABEL; import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST; import static com.google.devtools.build.lib.packages.BuildType.NODEP_LABEL; -import static java.nio.charset.StandardCharsets.UTF_8; -import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; @@ -29,21 +27,15 @@ import com.google.devtools.build.lib.actions.Artifact.SpecialArtifact; import com.google.devtools.build.lib.actions.ArtifactRoot; import com.google.devtools.build.lib.actions.FailAction; -import com.google.devtools.build.lib.actions.ParamFileInfo; -import com.google.devtools.build.lib.actions.ParameterFile; import com.google.devtools.build.lib.analysis.AliasProvider; import com.google.devtools.build.lib.analysis.AnalysisUtils; import com.google.devtools.build.lib.analysis.Expander; import com.google.devtools.build.lib.analysis.FileProvider; -import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder; import com.google.devtools.build.lib.analysis.RuleContext; import com.google.devtools.build.lib.analysis.RuleErrorConsumer; -import com.google.devtools.build.lib.analysis.Runfiles; -import com.google.devtools.build.lib.analysis.StaticallyLinkedMarkerProvider; import com.google.devtools.build.lib.analysis.TransitiveInfoCollection; import com.google.devtools.build.lib.analysis.actions.ActionConstructionContext; import com.google.devtools.build.lib.analysis.actions.CustomCommandLine; -import com.google.devtools.build.lib.analysis.actions.FileWriteAction; import com.google.devtools.build.lib.analysis.actions.SpawnAction; import com.google.devtools.build.lib.analysis.actions.SymlinkAction; import com.google.devtools.build.lib.analysis.config.BuildConfigurationValue; @@ -51,22 +43,15 @@ import com.google.devtools.build.lib.analysis.platform.ToolchainInfo; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.collect.nestedset.NestedSet; -import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; -import com.google.devtools.build.lib.collect.nestedset.Order; import com.google.devtools.build.lib.packages.RuleClass.ConfiguredTargetFactory.RuleErrorException; import com.google.devtools.build.lib.packages.Type; -import com.google.devtools.build.lib.rules.cpp.CcCommon.Language; import com.google.devtools.build.lib.rules.cpp.CcLinkingContext.Linkstamp; import com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.ExpansionException; import com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.FeatureConfiguration; -import com.google.devtools.build.lib.rules.cpp.CppConfiguration.DynamicMode; -import com.google.devtools.build.lib.rules.cpp.CppConfiguration.Tool; import com.google.devtools.build.lib.rules.cpp.Link.LinkTargetType; import com.google.devtools.build.lib.server.FailureDetails.FailAction.Code; import com.google.devtools.build.lib.shell.ShellUtils; import com.google.devtools.build.lib.util.FileTypeSet; -import com.google.devtools.build.lib.util.Fingerprint; -import com.google.devtools.build.lib.util.Pair; import com.google.devtools.build.lib.vfs.PathFragment; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -191,46 +176,6 @@ return ImmutableList.of(); } - public static NestedSet<Pair<String, String>> getCoverageEnvironmentIfNeeded( - RuleContext ruleContext, CppConfiguration cppConfiguration, CcToolchainProvider toolchain) - throws RuleErrorException { - if (cppConfiguration.collectCodeCoverage()) { - String llvmCov = toolchain.getToolPathStringOrNull(Tool.LLVM_COV); - if (llvmCov == null) { - llvmCov = ""; - } - String llvmProfdata = toolchain.getToolPathStringOrNull(Tool.LLVM_PROFDATA); - if (llvmProfdata == null) { - llvmProfdata = ""; - } - String gcov = toolchain.getToolPathStringOrNull(Tool.GCOV); - if (gcov == null) { - gcov = ""; - } - NestedSetBuilder<Pair<String, String>> coverageEnvironment = - NestedSetBuilder.<Pair<String, String>>stableOrder() - .add(Pair.of("COVERAGE_GCOV_PATH", gcov)) - .add(Pair.of("LLVM_COV", llvmCov)) - .add(Pair.of("LLVM_PROFDATA", llvmProfdata)) - .add(Pair.of("GENERATE_LLVM_LCOV", cppConfiguration.generateLlvmLCov() ? "1" : "0")); - if (cppConfiguration.getFdoInstrument() != null) { - coverageEnvironment.add(Pair.of("FDO_DIR", cppConfiguration.getFdoInstrument())); - } - return coverageEnvironment.build(); - } else { - return NestedSetBuilder.emptySet(Order.COMPILE_ORDER); - } - } - - public static NestedSet<Artifact> getGcovFilesIfNeeded( - RuleContext ruleContext, CcToolchainProvider toolchain) { - if (ruleContext.getConfiguration().isCodeCoverageEnabled()) { - return toolchain.getCoverageFiles(); - } else { - return NestedSetBuilder.emptySet(Order.STABLE_ORDER); - } - } - /** * This almost trivial method looks up the default cc toolchain attribute on the rule context, * makes sure that it refers to a rule that has a {@link CcToolchainProvider} (gives an error @@ -255,64 +200,6 @@ } /** - * Convenience function for finding the dynamic runtime inputs for the current toolchain. Useful - * for non C++ rules that link against the C++ runtime. - * - * <p>This uses the default feature configuration. Do *not* use this method in rules that use a - * non-default feature configuration, or risk a mismatch. - */ - public static NestedSet<Artifact> getDefaultCcToolchainDynamicRuntimeInputs( - RuleContext ruleContext, CppSemantics semantics) throws RuleErrorException { - try { - return getDefaultCcToolchainDynamicRuntimeInputsFromStarlark(ruleContext, semantics); - } catch (EvalException e) { - throw ruleContext.throwWithRuleError(e); - } - } - - /** - * Convenience function for finding the dynamic runtime inputs for the current toolchain. Useful - * for Starlark-defined rules that link against the C++ runtime. - * - * <p>This uses the default feature configuration. Do *not* use this method in rules that use a - * non-default feature configuration, or risk a mismatch. - */ - public static NestedSet<Artifact> getDefaultCcToolchainDynamicRuntimeInputsFromStarlark( - RuleContext ruleContext, CppSemantics semantics) throws EvalException, RuleErrorException { - CcToolchainProvider defaultToolchain = - getToolchainUsingDefaultCcToolchainAttribute(ruleContext); - if (defaultToolchain == null) { - return NestedSetBuilder.emptySet(Order.STABLE_ORDER); - } - FeatureConfiguration featureConfiguration = - CcCommon.configureFeaturesOrReportRuleError( - ruleContext, Language.CPP, defaultToolchain, semantics); - - return defaultToolchain.getDynamicRuntimeLinkInputs(featureConfiguration); - } - - /** - * Convenience function for finding the static runtime inputs for the current toolchain. Useful - * for non C++ rules that link against the C++ runtime. - */ - public static NestedSet<Artifact> getDefaultCcToolchainStaticRuntimeInputs( - RuleContext ruleContext, CppSemantics semantics) throws RuleErrorException { - CcToolchainProvider defaultToolchain = - getToolchainUsingDefaultCcToolchainAttribute(ruleContext); - if (defaultToolchain == null) { - return NestedSetBuilder.emptySet(Order.STABLE_ORDER); - } - FeatureConfiguration featureConfiguration = - CcCommon.configureFeaturesOrReportRuleError( - ruleContext, Language.CPP, defaultToolchain, semantics); - try { - return defaultToolchain.getStaticRuntimeLinkInputs(featureConfiguration); - } catch (EvalException e) { - throw ruleContext.throwWithRuleError(e); - } - } - - /** * Makes sure that the given info collection has a {@link CcToolchainProvider} (gives an error * otherwise), and returns a reference to that {@link CcToolchainProvider}. */ @@ -420,103 +307,6 @@ ruleLabel, usePic ? PIC_DIA_FILES : DIA_FILES, siblingRepositoryLayout); } - /** - * Returns a function that gets the C++ runfiles from a {@link TransitiveInfoCollection} or the - * empty runfiles instance if it does not contain that provider. - */ - public static final Function<TransitiveInfoCollection, Runfiles> runfilesFunction( - RuleContext ruleContext, boolean linkingStatically) { - final Function<TransitiveInfoCollection, Runfiles> runfilesForLinkingDynamically = - input -> { - CcInfo provider = input.get(CcInfo.PROVIDER); - if (provider == null) { - return Runfiles.EMPTY; - } else { - // Cannot add libraries directly because the nested set has link order. - NestedSet<Artifact> dynamicLibrariesForRuntime = - NestedSetBuilder.<Artifact>stableOrder() - .addAll( - provider - .getCcLinkingContext() - .getDynamicLibrariesForRuntime(/* linkingStatically= */ false)) - .build(); - return new Runfiles.Builder(ruleContext.getWorkspaceName()) - .addTransitiveArtifacts(dynamicLibrariesForRuntime) - .build(); - } - }; - - final Function<TransitiveInfoCollection, Runfiles> runfilesForLinkingStatically = - input -> { - CcInfo provider = input.get(CcInfo.PROVIDER); - if (provider == null) { - return Runfiles.EMPTY; - } else { - // Cannot add libraries directly because the nested set has link order. - NestedSet<Artifact> dynamicLibrariesForRuntime = - NestedSetBuilder.<Artifact>stableOrder() - .addAll( - provider - .getCcLinkingContext() - .getDynamicLibrariesForRuntime(/* linkingStatically= */ true)) - .build(); - return new Runfiles.Builder(ruleContext.getWorkspaceName()) - .addTransitiveArtifacts(dynamicLibrariesForRuntime) - .build(); - } - }; - return linkingStatically ? runfilesForLinkingStatically : runfilesForLinkingDynamically; - } - - /** - * Returns the linked artifact. - * - * @param ruleContext the ruleContext to be used to scope the artifact - * @param config the configuration to be used to scope the artifact - * @param linkType the type of artifact, used to determine extension - */ - public static Artifact getLinkedArtifact( - RuleContext ruleContext, - CcToolchainProvider ccToolchain, - BuildConfigurationValue config, - LinkTargetType linkType) - throws RuleErrorException { - return getLinkedArtifact( - ruleContext, ccToolchain, config, linkType, /* linkedArtifactNameSuffix= */ ""); - } - - /** Returns the linked artifact with the given suffix. */ - public static Artifact getLinkedArtifact( - RuleContext ruleContext, - CcToolchainProvider ccToolchain, - BuildConfigurationValue config, - LinkTargetType linkType, - String linkedArtifactNameSuffix) - throws RuleErrorException { - PathFragment name = PathFragment.create(ruleContext.getLabel().getName()); - try { - name = - name.replaceName( - getArtifactNameForCategory( - ccToolchain, - linkType.getLinkerOutput(), - name.getBaseName() - + linkedArtifactNameSuffix - + linkType.getPicExtensionWhenApplicable())); - } catch (RuleErrorException e) { - ruleContext.throwWithRuleError("Cannot get linked artifact name: " + e.getMessage()); - } - - return getLinkedArtifact( - ruleContext.getLabel(), - ruleContext, - ruleContext.getBinDirectory(), - config, - linkType, - linkedArtifactNameSuffix, - name); - } - public static Artifact getLinkedArtifact( Label label, ActionConstructionContext actionConstructionContext, @@ -728,13 +518,6 @@ } } - public static void maybeAddStaticLinkMarkerProvider( - RuleConfiguredTargetBuilder builder, RuleContext ruleContext) { - if (ruleContext.getFeatures().contains("fully_static_link")) { - builder.addNativeDeclaredProvider(new StaticallyLinkedMarkerProvider(true)); - } - } - static Artifact getCompileOutputArtifact( ActionConstructionContext actionConstructionContext, Label label, @@ -832,123 +615,6 @@ } /** - * Returns true when {@link CppRuleClasses#WINDOWS_EXPORT_ALL_SYMBOLS} feature is enabled and - * {@link CppRuleClasses#NO_WINDOWS_EXPORT_ALL_SYMBOLS} feature is not enabled and no custom DEF - * file is specified in win_def_file attribute. - */ - public static boolean shouldUseGeneratedDefFile( - RuleContext ruleContext, FeatureConfiguration featureConfiguration) { - return featureConfiguration.isEnabled(CppRuleClasses.WINDOWS_EXPORT_ALL_SYMBOLS) - && !featureConfiguration.isEnabled(CppRuleClasses.NO_WINDOWS_EXPORT_ALL_SYMBOLS) - && ruleContext.getPrerequisiteArtifact("win_def_file") == null; - } - - /** - * Create actions for parsing object files to generate a DEF file, should only be used when - * targeting Windows. - * - * @param defParser The tool we use to parse object files for generating the DEF file. - * @param objectFiles A list of object files to parse - * @param dllName The DLL name to be written into the DEF file, it specifies which DLL is required - * at runtime - * @return The DEF file artifact. - */ - public static Artifact createDefFileActions( - RuleContext ruleContext, - Artifact defParser, - ImmutableList<Artifact> objectFiles, - String dllName) { - Artifact defFile = - ruleContext.getBinArtifact( - ruleContext.getLabel().getName() - + ".gen" - + Iterables.getOnlyElement(CppFileTypes.WINDOWS_DEF_FILE.getExtensions())); - CustomCommandLine.Builder argv = new CustomCommandLine.Builder(); - for (Artifact objectFile : objectFiles) { - argv.addDynamicString(objectFile.getExecPathString()); - } - - ruleContext.registerAction( - new SpawnAction.Builder() - .addInputs(objectFiles) - .addOutput(defFile) - .setExecutable(defParser) - .useDefaultShellEnvironment() - .addCommandLine( - CustomCommandLine.builder().addExecPath(defFile).addDynamicString(dllName).build()) - .addCommandLine( - argv.build(), - ParamFileInfo.builder(ParameterFile.ParameterFileType.SHELL_QUOTED) - .setCharset(UTF_8) - .setUseAlways(true) - .build()) - .setMnemonic("DefParser") - .build(ruleContext)); - return defFile; - } - - /** - * Create action for generating an empty DEF file without any exports, should only be used when - * targeting Windows. - * - * @return The artifact of an empty DEF file. - */ - private static Artifact createEmptyDefFileAction(RuleContext ruleContext) { - Artifact trivialDefFile = - ruleContext.getBinArtifact( - ruleContext.getLabel().getName() - + ".gen.empty" - + Iterables.getOnlyElement(CppFileTypes.WINDOWS_DEF_FILE.getExtensions())); - ruleContext.registerAction(FileWriteAction.create(ruleContext, trivialDefFile, "", false)); - return trivialDefFile; - } - - /** - * Decide which DEF file should be used for the linking action. - * - * @return The artifact of the DEF file that should be used for the linking action. - */ - public static Artifact getWindowsDefFileForLinking( - RuleContext ruleContext, - Artifact customDefFile, - Artifact generatedDefFile, - FeatureConfiguration featureConfiguration) { - // 1. If a custom DEF file is specified in win_def_file attribute, use it. - // 2. If a generated DEF file is available and should be used, use it. - // 3. Otherwise, we use an empty DEF file to ensure the import library will be generated. - if (customDefFile != null) { - return customDefFile; - } else if (generatedDefFile != null - && CppHelper.shouldUseGeneratedDefFile(ruleContext, featureConfiguration)) { - return generatedDefFile; - } else { - return createEmptyDefFileAction(ruleContext); - } - } - - // TODO(gnish): Delete this method once cc_library is fully migrated to Starlark implementation. - /** Returns the suffix (_{hash}) for artifacts generated by cc_library on Windows. */ - public static String getDLLHashSuffix( - RuleContext ruleContext, FeatureConfiguration featureConfiguration) { - CppOptions cppOptions = - Preconditions.checkNotNull( - ruleContext.getConfiguration().getOptions().get(CppOptions.class)); - if (cppOptions.renameDLL - && cppOptions.dynamicMode != DynamicMode.OFF - && featureConfiguration.isEnabled(CppRuleClasses.TARGETS_WINDOWS) - // Because the custom DEF file in `win_def_file` does not contain the suffix of the DLL, we - // should not calculate _{hash} when `win_def_file` is used. - && (!ruleContext.isAttrDefined("win_def_file", LABEL) - || ruleContext.getPrerequisiteArtifact("win_def_file") == null)) { - Fingerprint digest = new Fingerprint(); - digest.addString(ruleContext.getRepository().getNameWithAt()); - digest.addPath(ruleContext.getPackageDirectory()); - return "_" + digest.hexDigestAndReset().substring(0, 10); - } - return ""; - } - - /** * Returns true if the build implied by the given config and toolchain uses --start-lib/--end-lib * ld options. */ @@ -983,16 +649,6 @@ && cppConfiguration.getUseInterfaceSharedLibraries(); } - public static CcNativeLibraryInfo collectNativeCcLibraries( - List<? extends TransitiveInfoCollection> deps, List<LibraryToLink> libraries) { - NestedSetBuilder<LibraryToLink> result = NestedSetBuilder.linkOrder(); - result.addAll(libraries); - for (CcInfo dep : AnalysisUtils.getProviders(deps, CcInfo.PROVIDER)) { - result.addTransitive(dep.getCcNativeLibraryInfo().getTransitiveCcNativeLibraries()); - } - return new CcNativeLibraryInfo(result.build()); - } - static boolean useToolchainResolution(RuleContext ruleContext) { CppOptions cppOptions = Preconditions.checkNotNull( @@ -1001,37 +657,6 @@ return cppOptions.enableCcToolchainResolution; } - public static ImmutableList<CcCompilationContext> getCompilationContextsFromDeps( - List<TransitiveInfoCollection> deps) { - return AnalysisUtils.getProviders(deps, CcInfo.PROVIDER).stream() - .map(CcInfo::getCcCompilationContext) - .collect(ImmutableList.toImmutableList()); - } - - public static CcDebugInfoContext mergeCcDebugInfoContexts( - CcCompilationOutputs compilationOutputs, Iterable<CcInfo> deps) { - ImmutableList.Builder<CcDebugInfoContext> contexts = ImmutableList.builder(); - for (CcInfo ccInfo : deps) { - contexts.add(ccInfo.getCcDebugInfoContext()); - } - contexts.add(CcDebugInfoContext.from(compilationOutputs)); - return CcDebugInfoContext.merge(contexts.build()); - } - - public static ImmutableList<CcLinkingContext> getLinkingContextsFromDeps( - ImmutableList<TransitiveInfoCollection> deps) { - return AnalysisUtils.getProviders(deps, CcInfo.PROVIDER).stream() - .map(CcInfo::getCcLinkingContext) - .collect(ImmutableList.toImmutableList()); - } - - public static ImmutableList<CcDebugInfoContext> getDebugInfoContextsFromDeps( - List<TransitiveInfoCollection> deps) { - return AnalysisUtils.getProviders(deps, CcInfo.PROVIDER).stream() - .map(CcInfo::getCcDebugInfoContext) - .collect(ImmutableList.toImmutableList()); - } - @Nullable public static Artifact getGrepIncludes(RuleContext ruleContext) { return ruleContext.attributes().has("$grep_includes")
diff --git a/src/test/java/com/google/devtools/build/lib/rules/cpp/CcLibraryConfiguredTargetTest.java b/src/test/java/com/google/devtools/build/lib/rules/cpp/CcLibraryConfiguredTargetTest.java index 1fdf0ba..70733dc 100644 --- a/src/test/java/com/google/devtools/build/lib/rules/cpp/CcLibraryConfiguredTargetTest.java +++ b/src/test/java/com/google/devtools/build/lib/rules/cpp/CcLibraryConfiguredTargetTest.java
@@ -497,8 +497,7 @@ Artifact helloBinExe = getFilesToBuild(helloBin).toList().get(0); assertThat(helloBinExe.getExecPathString()).endsWith("hello_bin.exe"); - assertThat( - artifactsToStrings(getOutputGroup(hello, CcLibrary.DYNAMIC_LIBRARY_OUTPUT_GROUP_NAME))) + assertThat(artifactsToStrings(getOutputGroup(hello, "dynamic_library"))) .containsExactly("bin hello/hello_5e918d2.dll", "bin hello/hello.if.lib"); }