simpleperf: Fix reading old branch list files

We have moved to a new branch list file format (in aosp/3341393).
But we want to keep the ability of reading old branch list file
format for some time. This patch fixes the support, and adds a
test for it.

Bug: 345410289
Test: run simpleperf_unit_test
Change-Id: If4c190e61347be8cebea84fa28bc83a599dc41cd
diff --git a/simpleperf/BranchListFile.cpp b/simpleperf/BranchListFile.cpp
index 5e2e4d1..13ab72e 100644
--- a/simpleperf/BranchListFile.cpp
+++ b/simpleperf/BranchListFile.cpp
@@ -615,6 +615,14 @@
   return true;
 }
 
+void BranchListProtoReader::Rewind() {
+  if (input_fp_) {
+    rewind(input_fp_.get());
+  } else {
+    input_str_pos_ = 0;
+  }
+}
+
 bool BranchListProtoReader::ReadData(void* data, size_t size) {
   if (input_fp_) {
     if (fread(data, size, 1, input_fp_.get()) != 1) {
@@ -642,6 +650,7 @@
   } else {
     size = input_str_.size();
   }
+  Rewind();
   proto::BranchList proto_branch_list;
   if (!ReadProtoBranchList(size, proto_branch_list)) {
     return false;
diff --git a/simpleperf/BranchListFile.h b/simpleperf/BranchListFile.h
index 2b9c07c..64a00ab 100644
--- a/simpleperf/BranchListFile.h
+++ b/simpleperf/BranchListFile.h
@@ -225,6 +225,7 @@
   bool ReadProtoBranchList(uint32_t size, proto::BranchList& proto_branch_list);
   bool AddETMBinary(const proto::ETMBinary& proto_binary, ETMBinaryMap& etm_data);
   void AddLBRData(const proto::LBRData& proto_lbr_data, LBRData& lbr_data);
+  void Rewind();
   bool ReadData(void* data, size_t size);
   bool ReadOldFileFormat(ETMBinaryMap& etm_data, LBRData& lbr_data);
 
diff --git a/simpleperf/BranchListFile_test.cpp b/simpleperf/BranchListFile_test.cpp
index af278a0..b5c7ec6 100644
--- a/simpleperf/BranchListFile_test.cpp
+++ b/simpleperf/BranchListFile_test.cpp
@@ -17,6 +17,7 @@
 #include <gtest/gtest.h>
 
 #include "BranchListFile.h"
+#include "get_test_data.h"
 
 using namespace simpleperf;
 
@@ -149,3 +150,14 @@
     }
   }
 }
+
+// @CddTest = 6.1/C-0-2
+TEST(BranchListProtoReaderWriter, read_old_branch_list_file) {
+  std::string path = GetTestData("etm/old_branch_list.data");
+  auto reader = BranchListProtoReader::CreateForFile(path);
+  ASSERT_TRUE(reader);
+  ETMBinaryMap etm_data;
+  LBRData lbr_data;
+  ASSERT_TRUE(reader->Read(etm_data, lbr_data));
+  ASSERT_EQ(etm_data.size(), 1u);
+}
diff --git a/simpleperf/testdata/etm/old_branch_list.data b/simpleperf/testdata/etm/old_branch_list.data
new file mode 100644
index 0000000..434f417
--- /dev/null
+++ b/simpleperf/testdata/etm/old_branch_list.data
Binary files differ