simpleperf: add more checks when parsing profile data.

Bug: 258284440
Bug: 258284074
Bug: 258284156

Test: run simpleperf manually
Test: run simpleperf_unit_test
Change-Id: I1b8b05ab6fefbe26c54be35d6e8bfc77fb1e37df
diff --git a/simpleperf/record.cpp b/simpleperf/record.cpp
index 2d21a7c..9662b6f 100644
--- a/simpleperf/record.cpp
+++ b/simpleperf/record.cpp
@@ -1084,6 +1084,7 @@
     return false;
   }
   for (uint32_t i = 0; i < data->nr_cpu; ++i) {
+    CHECK_SIZE(p, end, sizeof(uint64_t));
     uint64_t magic = *reinterpret_cast<uint64_t*>(p);
     if (magic == MAGIC_ETM4) {
       CHECK_SIZE(p, end, sizeof(ETM4Info));
diff --git a/simpleperf/record_file_reader.cpp b/simpleperf/record_file_reader.cpp
index 8fb592e..7fe8a89 100644
--- a/simpleperf/record_file_reader.cpp
+++ b/simpleperf/record_file_reader.cpp
@@ -149,6 +149,10 @@
 bool RecordFileReader::ReadAttrSection() {
   size_t attr_count = header_.attrs.size / header_.attr_size;
   if (header_.attr_size != sizeof(FileAttr)) {
+    if (header_.attr_size <= sizeof(SectionDesc)) {
+      LOG(ERROR) << "invalid attr section in " << filename_;
+      return false;
+    }
     LOG(DEBUG) << "attr size (" << header_.attr_size << ") in " << filename_
                << " doesn't match expected size (" << sizeof(FileAttr) << ")";
   }
@@ -474,9 +478,9 @@
   const char* p = buf.data();
   const char* end = buf.data() + buf.size();
   std::vector<BuildIdRecord> result;
-  while (p < end) {
+  while (p + sizeof(perf_event_header) < end) {
     auto header = reinterpret_cast<const perf_event_header*>(p);
-    if (p + header->size > end) {
+    if ((header->size <= sizeof(perf_event_header)) || (header->size > end - p)) {
       return {};
     }
     std::unique_ptr<char[]> binary(new char[header->size]);