C++: Fixes IllegalStateException in LibrariesToLinkCollector.generateLtoMap()

RELNOTES:none
PiperOrigin-RevId: 304187004
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 6effe70..73779ce 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
@@ -743,11 +743,18 @@
 
     if (dynamicLinkActionBuilder.hasLtoBitcodeInputs()
         && featureConfiguration.isEnabled(CppRuleClasses.THIN_LTO)) {
-      dynamicLinkActionBuilder.setLtoIndexing(true);
-      dynamicLinkActionBuilder.setUsePicForLtoBackendActions(usePic);
-      CppLinkAction indexAction = dynamicLinkActionBuilder.build();
-      if (indexAction != null) {
-        actionConstructionContext.registerAction(indexAction);
+      if (featureConfiguration.isEnabled(CppRuleClasses.SUPPORTS_START_END_LIB)) {
+        dynamicLinkActionBuilder.setLtoIndexing(true);
+        dynamicLinkActionBuilder.setUsePicForLtoBackendActions(usePic);
+        CppLinkAction indexAction = dynamicLinkActionBuilder.build();
+        if (indexAction != null) {
+          actionConstructionContext.registerAction(indexAction);
+        }
+      } else {
+        ruleErrorConsumer.ruleError(
+            "When using LTO. The feature "
+                + CppRuleClasses.SUPPORTS_START_END_LIB
+                + " must be enabled.");
       }
 
       dynamicLinkActionBuilder.setLtoIndexing(false);
diff --git a/src/test/java/com/google/devtools/build/lib/rules/cpp/CcBinaryThinLtoTest.java b/src/test/java/com/google/devtools/build/lib/rules/cpp/CcBinaryThinLtoTest.java
index 0a8ab0d..676af813 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/cpp/CcBinaryThinLtoTest.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/cpp/CcBinaryThinLtoTest.java
@@ -1931,4 +1931,14 @@
   public void testFdoCachePrefetchAndFdoLLVMOptionsToBackendFromLabel() throws Exception {
     testLLVMCachePrefetchBackendOption("--fdo_optimize=./profile.zip", true);
   }
+
+  @Test
+  public void testThinLtoWithoutSupportsStartEndLibError() throws Exception {
+    createBuildFiles("bin", "testonly = 1,");
+    AnalysisMock.get()
+        .ccSupport()
+        .setupCcToolchainConfig(
+            mockToolsConfig, CcToolchainConfig.builder().withFeatures(CppRuleClasses.THIN_LTO));
+    checkError("//pkg:bin", "The feature supports_start_end_lib must be enabled.");
+  }
 }