Fix java.util.ConcurrentModificationException

Fixes: b/359385828
Change-Id: Ib59bed89294d831e26ae9e6e4e3b2aa63406958a
diff --git a/src/main/java/com/android/tools/r8/shaking/Enqueuer.java b/src/main/java/com/android/tools/r8/shaking/Enqueuer.java
index 1bfff48..31ca73c 100644
--- a/src/main/java/com/android/tools/r8/shaking/Enqueuer.java
+++ b/src/main/java/com/android/tools/r8/shaking/Enqueuer.java
@@ -2343,20 +2343,25 @@
   private void processDeferredAnnotations(
       Map<DexType, Map<DexAnnotation, List<ProgramDefinition>>> deferredAnnotations,
       Function<ProgramDefinition, AnnotatedKind> kindProvider) {
+    // Collect annotations to process as processing the annotation can modify liveAnnotations.
+    Set<Map<DexAnnotation, List<ProgramDefinition>>> toProcess = Sets.newIdentityHashSet();
     for (DexType annotationType : liveAnnotations) {
       Map<DexAnnotation, List<ProgramDefinition>> annotations =
           deferredAnnotations.remove(annotationType);
       if (annotations != null) {
         assert annotations.keySet().stream()
             .allMatch(annotation -> annotationType.isIdenticalTo(annotation.getAnnotationType()));
-        annotations.forEach(
-            (annotation, annotatedItems) ->
-                annotatedItems.forEach(
-                    annotatedItem ->
-                        processAnnotation(
-                            annotatedItem, annotation, kindProvider.apply(annotatedItem))));
+        toProcess.add(annotations);
       }
     }
+    toProcess.forEach(
+        annotations ->
+            annotations.forEach(
+                (annotation, annotatedItems) ->
+                    annotatedItems.forEach(
+                        annotatedItem ->
+                            processAnnotation(
+                                annotatedItem, annotation, kindProvider.apply(annotatedItem)))));
   }
 
   private void ensureMethodsContinueToWidenAccess(ClassDefinition clazz) {
diff --git a/src/test/java/com/android/tools/r8/annotations/NestedAnnotationsUnusedTest.java b/src/test/java/com/android/tools/r8/annotations/NestedAnnotationsUnusedTest.java
new file mode 100644
index 0000000..a807a27
--- /dev/null
+++ b/src/test/java/com/android/tools/r8/annotations/NestedAnnotationsUnusedTest.java
@@ -0,0 +1,75 @@
+// Copyright (c) 2024, the R8 project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+package com.android.tools.r8.annotations;
+
+import static com.android.tools.r8.utils.codeinspector.Matchers.isAbsent;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import com.android.tools.r8.TestBase;
+import com.android.tools.r8.TestParameters;
+import com.android.tools.r8.TestParametersCollection;
+import com.android.tools.r8.annotations.NestedAnnotationsUsedTest.A;
+import com.android.tools.r8.annotations.NestedAnnotationsUsedTest.TestClass;
+import com.android.tools.r8.utils.StringUtils;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameter;
+import org.junit.runners.Parameterized.Parameters;
+
+// This is a regression test for b/359385828.
+@RunWith(Parameterized.class)
+public class NestedAnnotationsUnusedTest extends TestBase {
+
+  @Parameter(0)
+  public TestParameters parameters;
+
+  @Parameters(name = "{0}")
+  public static TestParametersCollection data() {
+    return getTestParameters().withAllRuntimesAndApiLevels().build();
+  }
+
+  private static final String EXPECTED_OUTPUT = StringUtils.lines("Found");
+
+  @Test
+  public void testR8() throws Exception {
+    testForR8(parameters.getBackend())
+        .addInnerClasses(getClass())
+        .addKeepClassRules(A.class)
+        .addKeepRuntimeVisibleAnnotations()
+        .addKeepMainRule(TestClass.class)
+        .setMinApi(parameters)
+        .run(parameters.getRuntime(), TestClass.class)
+        .inspect(inspector -> assertThat(inspector.clazz(B.class), isAbsent()))
+        .assertSuccessWithOutput(EXPECTED_OUTPUT);
+  }
+
+  @Retention(RetentionPolicy.RUNTIME)
+  @Target({ElementType.TYPE})
+  public @interface A {
+    B b();
+
+    B[] bs() default {};
+  }
+
+  @Retention(RetentionPolicy.RUNTIME)
+  public @interface B {
+    String x();
+  }
+
+  @A(
+      b = @B(x = "1"),
+      bs = {@B(x = "2"), @B(x = "3")})
+  static class TestClass {
+
+    public static void main(String[] args) {
+      System.out.println(TestClass.class.getAnnotation(A.class) != null ? "Found" : "Not found");
+    }
+  }
+}
diff --git a/src/test/java/com/android/tools/r8/annotations/NestedAnnotationsUsedTest.java b/src/test/java/com/android/tools/r8/annotations/NestedAnnotationsUsedTest.java
new file mode 100644
index 0000000..90ae5bf
--- /dev/null
+++ b/src/test/java/com/android/tools/r8/annotations/NestedAnnotationsUsedTest.java
@@ -0,0 +1,78 @@
+// Copyright (c) 2024, the R8 project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+package com.android.tools.r8.annotations;
+
+import static com.android.tools.r8.utils.codeinspector.Matchers.isPresentAndRenamed;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import com.android.tools.r8.TestBase;
+import com.android.tools.r8.TestParameters;
+import com.android.tools.r8.TestParametersCollection;
+import com.android.tools.r8.utils.StringUtils;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameter;
+import org.junit.runners.Parameterized.Parameters;
+
+// This is a regression test for b/359385828.
+@RunWith(Parameterized.class)
+public class NestedAnnotationsUsedTest extends TestBase {
+
+  @Parameter(0)
+  public TestParameters parameters;
+
+  @Parameters(name = "{0}")
+  public static TestParametersCollection data() {
+    return getTestParameters().withAllRuntimesAndApiLevels().build();
+  }
+
+  private static final String EXPECTED_OUTPUT = StringUtils.lines("1", "2", "3");
+
+  @Test
+  public void testR8() throws Exception {
+    testForR8(parameters.getBackend())
+        .addInnerClasses(getClass())
+        .addKeepClassRules(A.class)
+        .addKeepRuntimeVisibleAnnotations()
+        .addKeepMainRule(TestClass.class)
+        .setMinApi(parameters)
+        .run(parameters.getRuntime(), TestClass.class)
+        .inspect(
+            inspector -> {
+              assertThat(inspector.clazz(B.class), isPresentAndRenamed());
+            })
+        .assertSuccessWithOutput(EXPECTED_OUTPUT);
+  }
+
+  @Retention(RetentionPolicy.RUNTIME)
+  @Target({ElementType.TYPE})
+  public @interface A {
+    B b();
+
+    B[] bs() default {};
+  }
+
+  @Retention(RetentionPolicy.RUNTIME)
+  public @interface B {
+    String x();
+  }
+
+  @A(
+      b = @B(x = "1"),
+      bs = {@B(x = "2"), @B(x = "3")})
+  static class TestClass {
+    public static void main(String[] args) throws Exception {
+      System.out.println(TestClass.class.getAnnotation(A.class).b().x());
+      for (B b : TestClass.class.getAnnotation(A.class).bs()) {
+        System.out.println(b.x());
+      }
+    }
+  }
+}