Generate an empty zip file when no globals are synthesized

Bug: b/306120364
Change-Id: I60fefd198ebb0798fe5cc5a7476891ce874bc17f
diff --git a/src/main/java/com/android/tools/r8/dex/ApplicationWriter.java b/src/main/java/com/android/tools/r8/dex/ApplicationWriter.java
index 4fdbb35..4d1c64e 100644
--- a/src/main/java/com/android/tools/r8/dex/ApplicationWriter.java
+++ b/src/main/java/com/android/tools/r8/dex/ApplicationWriter.java
@@ -353,6 +353,9 @@
     merger.end();
     if (globalsSyntheticsConsumer != null) {
       globalsSyntheticsConsumer.finished(appView);
+    } else if (options.hasGlobalSyntheticsConsumer()) {
+      // Make sure to also call finished even if no global output was generated.
+      options.getGlobalSyntheticsConsumer().finished(appView.reporter());
     }
   }
 
diff --git a/src/main/java/com/android/tools/r8/synthesis/GlobalSyntheticsUtils.java b/src/main/java/com/android/tools/r8/synthesis/GlobalSyntheticsUtils.java
index e132952..0a90db4 100644
--- a/src/main/java/com/android/tools/r8/synthesis/GlobalSyntheticsUtils.java
+++ b/src/main/java/com/android/tools/r8/synthesis/GlobalSyntheticsUtils.java
@@ -68,6 +68,7 @@
           // If not global info was written, close the builder with empty content.
           if (!written) {
             builder.close(handler);
+            written = true;
           }
         }
       };
diff --git a/src/test/java/com/android/tools/r8/synthesis/globals/GlobalSyntheticOutputCliTest.java b/src/test/java/com/android/tools/r8/synthesis/globals/GlobalSyntheticOutputCliTest.java
index a07ca84..ba5d568 100644
--- a/src/test/java/com/android/tools/r8/synthesis/globals/GlobalSyntheticOutputCliTest.java
+++ b/src/test/java/com/android/tools/r8/synthesis/globals/GlobalSyntheticOutputCliTest.java
@@ -75,6 +75,33 @@
   }
 
   @Test
+  public void testDexNoGlobals() throws Exception {
+    Path input1 = ToolHelper.getClassFileForTestClass(TestClass1.class);
+    Path input2 = ToolHelper.getClassFileForTestClass(TestClass2.class);
+    Path dexOut = temp.newFolder().toPath().resolve("out.jar");
+    Path globalsOut = temp.newFolder().toPath().resolve("out.zip");
+    forkD8(
+        input1.toString(),
+        input2.toString(),
+        "--intermediate",
+        "--output",
+        dexOut.toString(),
+        "--globals-output",
+        globalsOut.toString());
+
+    assertTrue(Files.exists(dexOut));
+    assertTrue(Files.exists(globalsOut));
+
+    Path finalOut = temp.newFolder().toPath().resolve("out.jar");
+    forkD8(dexOut.toString(), "--globals", globalsOut.toString(), "--output", finalOut.toString());
+
+    testForD8()
+        .addProgramFiles(finalOut)
+        .run(parameters.getRuntime(), TestClass1.class)
+        .assertSuccessWithOutput(EXPECTED);
+  }
+
+  @Test
   public void testDexIndexedZip() throws Exception {
     Path input1 = transformClass(TestClass1.class);
     Path input2 = transformClass(TestClass2.class);