From 87e3849ee95678fc9bff01e807b3e9f9ea2aea3f Mon Sep 17 00:00:00 2001
From: Robert O'Callahan <robert@ocallahan.org>
Date: Mon, 5 Aug 2024 10:05:25 +1200
Subject: [PATCH] Update the tail only after we've finished reading the packet.

Currently the kernel might overwrite the packet data we're reading.
---
 src/PerfCounters.cc | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/src/PerfCounters.cc b/src/PerfCounters.cc
index dc414f15f79..3aca0b8155a 100644
--- a/src/PerfCounters.cc
+++ b/src/PerfCounters.cc
@@ -828,7 +828,6 @@ size_t PerfCounters::PTState::flush() {
         mmap_header->data_size - start_offset);
     memcpy(packet.data(), const_cast<perf_event_header*>(header), first_chunk_size);
     memcpy(packet.data() + first_chunk_size, const_cast<char*>(data_buf), header->size - first_chunk_size);
-    mmap_header->data_tail += header->size;
 
     switch (header->type) {
       case PERF_RECORD_LOST:
@@ -857,6 +856,8 @@ size_t PerfCounters::PTState::flush() {
         FATAL() << "Unknown record " << header->type;
         break;
     }
+
+    mmap_header->data_tail += header->size;
   }
   return ret;
 }