Reference the JSON profile as build tool log in the BEP.

RELNOTES: None

Closes #9159.

PiperOrigin-RevId: 263132427
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/BuildSummaryStatsModule.java b/src/main/java/com/google/devtools/build/lib/runtime/BuildSummaryStatsModule.java
index f906215..f2c55b7 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/BuildSummaryStatsModule.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/BuildSummaryStatsModule.java
@@ -22,6 +22,7 @@
 import com.google.devtools.build.lib.buildtool.BuildRequest;
 import com.google.devtools.build.lib.buildtool.buildevent.BuildCompleteEvent;
 import com.google.devtools.build.lib.buildtool.buildevent.ExecutionStartingEvent;
+import com.google.devtools.build.lib.buildtool.buildevent.ProfilerStartedEvent;
 import com.google.devtools.build.lib.clock.BlazeClock;
 import com.google.devtools.build.lib.events.Event;
 import com.google.devtools.build.lib.events.Reporter;
@@ -31,6 +32,8 @@
 import com.google.devtools.build.lib.profiler.ProfilerTask;
 import com.google.devtools.build.lib.profiler.SilentCloseable;
 import com.google.devtools.build.lib.skyframe.ExecutionFinishedEvent;
+import com.google.devtools.build.lib.vfs.Path;
+import java.io.IOException;
 import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.List;
@@ -54,6 +57,7 @@
   private long executionStartMillis;
   private long executionEndMillis;
   private SpawnStats spawnStats;
+  private Path profilePath;
 
   @Override
   public void beforeCommand(CommandEnvironment env) {
@@ -89,6 +93,11 @@
   }
 
   @Subscribe
+  public void profileStarting(ProfilerStartedEvent event) {
+    this.profilePath = event.getProfilePath();
+  }
+
+  @Subscribe
   public void executionPhaseFinish(@SuppressWarnings("unused") ExecutionFinishedEvent event) {
     executionEndMillis = BlazeClock.instance().currentTimeMillis();
   }
@@ -137,6 +146,20 @@
           }
         }
       }
+      if (profilePath != null) {
+        // This leads to missing the afterCommand profiles of the other modules in the profile.
+        // Since the BEP currently shuts down at the BuildCompleteEvent, we cannot just move posting
+        // the BuildToolLogs to afterCommand of this module.
+        try {
+          Profiler.instance().stop();
+          event
+              .getResult()
+              .getBuildToolLogCollection()
+              .addLocalFile(profilePath.getBaseName(), profilePath);
+        } catch (IOException e) {
+          reporter.handle(Event.error("Error while writing profile file: " + e.getMessage()));
+        }
+      }
 
       String spawnSummary = spawnStats.getSummary();
       if (statsSummary) {
@@ -167,6 +190,7 @@
           .addDirectValue("process stats", spawnSummary.getBytes(StandardCharsets.UTF_8));
     } finally {
       criticalPathComputer = null;
+      profilePath = null;
     }
   }
 }