[Lldb-commits] [lldb] [lldb] Bounds check minidump location descriptors (PR #223911)

Jonas Devlieghere via lldb-commits lldb-commits at lists.llvm.org
Thu Sep 17 08:46:05 PDT 2026


https://github.com/JDevlieghere updated https://github.com/llvm/llvm-project/pull/223911

>From ba51c5f96cb0a524a591152f348c9db4567db082 Mon Sep 17 00:00:00 2001
From: Jonas Devlieghere <jonas at devlieghere.com>
Date: Tue, 15 Sep 2026 22:29:20 -0700
Subject: [PATCH 1/2] [lldb] Detect cycles when following DIE references

A DW_TAG_subprogram whose DW_AT_specification points at its own offset
causes both GetDIENamesAndRanges and GetDeclContextDIEContainingDIE to
keep recursing

Track the DIEs already visited, the way the sibling GetAttributes
helper does. GetDIENamesAndRanges also moves to a worklist so a long
chain of distinct specifications no longer costs a stack frame per DIE.

rdar://186891786
---
 .../SymbolFile/DWARF/DWARFDebugInfoEntry.cpp  |  71 ++++++--
 .../SymbolFile/DWARF/SymbolFileDWARF.cpp      |  97 +++++-----
 .../DWARF/self-referential-specification.yaml |  77 ++++++++
 .../SymbolFile/DWARF/DWARFDIETest.cpp         | 172 ++++++++++++++++++
 4 files changed, 359 insertions(+), 58 deletions(-)
 create mode 100644 lldb/test/Shell/SymbolFile/DWARF/self-referential-specification.yaml

diff --git a/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp b/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp
index e5eae7207b7e7b..07017b00dd7a46 100644
--- a/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp
+++ b/lldb/source/Plugins/SymbolFile/DWARF/DWARFDebugInfoEntry.cpp
@@ -98,16 +98,17 @@ static void ExtractAttrAndFormValue(
     form_value.SetSigned(attr_spec.getImplicitConstValue());
 }
 
-// GetDIENamesAndRanges
-//
-// Gets the valid address ranges for a given DIE by looking for a
-// DW_AT_low_pc/DW_AT_high_pc pair, DW_AT_entry_pc, or DW_AT_ranges attributes.
-bool DWARFDebugInfoEntry::GetDIENamesAndRanges(
-    DWARFUnit *cu, const char *&name, const char *&mangled,
+/// Helper for the public \ref DWARFDebugInfoEntry::GetDIENamesAndRanges API.
+/// Fills in the output parameters that aren't set yet from \c die and appends
+/// the DIEs it elaborates on to \c elaborating_dies.
+static void GetDIENamesAndRanges(
+    const DWARFDIE &die, const char *&name, const char *&mangled,
     llvm::DWARFAddressRangesVector &ranges, std::optional<int> &decl_file,
     std::optional<int> &decl_line, std::optional<int> &decl_column,
     std::optional<int> &call_file, std::optional<int> &call_line,
-    std::optional<int> &call_column, DWARFExpressionList *frame_base) const {
+    std::optional<int> &call_column, DWARFExpressionList *frame_base,
+    llvm::SmallVectorImpl<DWARFDIE> &elaborating_dies) {
+  DWARFUnit *cu = die.GetCU();
   dw_addr_t lo_pc = LLDB_INVALID_ADDRESS;
   dw_addr_t hi_pc = LLDB_INVALID_ADDRESS;
   std::vector<DWARFDIE> dies;
@@ -116,12 +117,13 @@ bool DWARFDebugInfoEntry::GetDIENamesAndRanges(
   SymbolFileDWARF &dwarf = cu->GetSymbolFileDWARF();
   lldb::ModuleSP module = dwarf.GetObjectFile()->GetModule();
 
-  if (const auto *abbrevDecl = GetAbbreviationDeclarationPtr(cu)) {
+  if (const auto *abbrevDecl =
+          die.GetDIE()->GetAbbreviationDeclarationPtr(cu)) {
     const DWARFDataExtractor &data = cu->GetData();
-    lldb::offset_t offset = GetFirstAttributeOffset();
+    lldb::offset_t offset = die.GetDIE()->GetFirstAttributeOffset();
 
     if (!data.ValidOffset(offset))
-      return false;
+      return;
 
     bool do_offset = false;
 
@@ -168,7 +170,8 @@ bool DWARFDebugInfoEntry::GetDIENamesAndRanges(
                 "[{0:x16}]: DIE has DW_AT_ranges({1} {2:x16}) attribute, but "
                 "range extraction failed ({3}), please file a bug "
                 "and attach the file at the start of this error message",
-                GetOffset(), llvm::dwarf::FormEncodingString(form_value.Form()),
+                die.GetOffset(),
+                llvm::dwarf::FormEncodingString(form_value.Form()),
                 form_value.Unsigned(), fmt_consume(r.takeError()));
           }
           break;
@@ -270,13 +273,49 @@ bool DWARFDebugInfoEntry::GetDIENamesAndRanges(
 
   if (ranges.empty() || name == nullptr || mangled == nullptr) {
     for (const DWARFDIE &die : dies) {
-      if (die) {
-        die.GetDIE()->GetDIENamesAndRanges(die.GetCU(), name, mangled, ranges,
-                                           decl_file, decl_line, decl_column,
-                                           call_file, call_line, call_column);
-      }
+      if (die)
+        elaborating_dies.push_back(die);
+    }
+  }
+}
+
+// GetDIENamesAndRanges
+//
+// Gets the valid address ranges for a given DIE by looking for a
+// DW_AT_low_pc/DW_AT_high_pc pair, DW_AT_entry_pc, or DW_AT_ranges attributes.
+bool DWARFDebugInfoEntry::GetDIENamesAndRanges(
+    DWARFUnit *cu, const char *&name, const char *&mangled,
+    llvm::DWARFAddressRangesVector &ranges, std::optional<int> &decl_file,
+    std::optional<int> &decl_line, std::optional<int> &decl_column,
+    std::optional<int> &call_file, std::optional<int> &call_line,
+    std::optional<int> &call_column, DWARFExpressionList *frame_base) const {
+  llvm::SmallVector<DWARFDIE, 3> worklist;
+  worklist.emplace_back(cu, this);
+
+  // Keep track of the DIEs already seen to catch cycles.
+  llvm::SmallPtrSet<DWARFDebugInfoEntry const *, 3> seen;
+  seen.insert(this);
+
+  // The frame base is only taken from the DIE itself, not from the DIEs it
+  // elaborates on.
+  DWARFExpressionList *die_frame_base = frame_base;
+
+  while (!worklist.empty()) {
+    DWARFDIE current = worklist.pop_back_val();
+
+    llvm::SmallVector<DWARFDIE, 3> elaborating_dies;
+    ::GetDIENamesAndRanges(current, name, mangled, ranges, decl_file, decl_line,
+                           decl_column, call_file, call_line, call_column,
+                           die_frame_base, elaborating_dies);
+    die_frame_base = nullptr;
+
+    // Push in reverse so that the worklist handles them in the order.
+    for (const DWARFDIE &die : llvm::reverse(elaborating_dies)) {
+      if (seen.insert(die.GetDIE()).second)
+        worklist.push_back(die);
     }
   }
+
   return !ranges.empty();
 }
 
diff --git a/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp b/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp
index b0007f04a31abf..53e515cc180b59 100644
--- a/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp
+++ b/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp
@@ -9,6 +9,7 @@
 #include "SymbolFileDWARF.h"
 #include "clang/Basic/ABI.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/DebugInfo/DWARF/DWARFAddressRange.h"
@@ -3058,58 +3059,70 @@ TypeSP SymbolFileDWARF::GetTypeForDIE(const DWARFDIE &die,
   return type_sp;
 }
 
-DWARFDIE
-SymbolFileDWARF::GetDeclContextDIEContainingDIE(const DWARFDIE &orig_die) {
-  if (orig_die) {
-    DWARFDIE die = orig_die;
-
-    while (die) {
-      // If this is the original DIE that we are searching for a declaration
-      // for, then don't look in the cache as we don't want our own decl
-      // context to be our decl context...
-      if (orig_die != die) {
-        switch (die.Tag()) {
-        case DW_TAG_compile_unit:
-        case DW_TAG_partial_unit:
-        case DW_TAG_namespace:
-        case DW_TAG_structure_type:
-        case DW_TAG_union_type:
-        case DW_TAG_class_type:
-        case DW_TAG_lexical_block:
-        case DW_TAG_subprogram:
-          return die;
-        case DW_TAG_inlined_subroutine: {
-          DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
-          if (abs_die) {
-            return abs_die;
-          }
-          break;
-        }
-        default:
-          break;
+/// Helper for the public \ref SymbolFileDWARF::GetDeclContextDIEContainingDIE
+/// API. Specifications and abstract origins the walk has already descended
+/// into are in \c seen and are not followed again.
+static DWARFDIE GetDeclContextDIEContainingDIE(
+    const DWARFDIE &orig_die,
+    llvm::SmallPtrSetImpl<const DWARFDebugInfoEntry *> &seen) {
+  DWARFDIE die = orig_die;
+
+  while (die) {
+    // If this is the original DIE that we are searching for a declaration
+    // for, then don't look in the cache as we don't want our own decl
+    // context to be our decl context...
+    if (orig_die != die) {
+      switch (die.Tag()) {
+      case DW_TAG_compile_unit:
+      case DW_TAG_partial_unit:
+      case DW_TAG_namespace:
+      case DW_TAG_structure_type:
+      case DW_TAG_union_type:
+      case DW_TAG_class_type:
+      case DW_TAG_lexical_block:
+      case DW_TAG_subprogram:
+        return die;
+      case DW_TAG_inlined_subroutine: {
+        DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
+        if (abs_die) {
+          return abs_die;
         }
+        break;
       }
-
-      DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification);
-      if (spec_die) {
-        DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die);
-        if (decl_ctx_die)
-          return decl_ctx_die;
+      default:
+        break;
       }
+    }
 
-      DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
-      if (abs_die) {
-        DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die);
-        if (decl_ctx_die)
-          return decl_ctx_die;
-      }
+    DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification);
+    if (spec_die && seen.insert(spec_die.GetDIE()).second) {
+      DWARFDIE decl_ctx_die = ::GetDeclContextDIEContainingDIE(spec_die, seen);
+      if (decl_ctx_die)
+        return decl_ctx_die;
+    }
 
-      die = die.GetParent();
+    DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
+    if (abs_die && seen.insert(abs_die.GetDIE()).second) {
+      DWARFDIE decl_ctx_die = ::GetDeclContextDIEContainingDIE(abs_die, seen);
+      if (decl_ctx_die)
+        return decl_ctx_die;
     }
+
+    die = die.GetParent();
   }
+
   return DWARFDIE();
 }
 
+DWARFDIE
+SymbolFileDWARF::GetDeclContextDIEContainingDIE(const DWARFDIE &orig_die) {
+  if (!orig_die)
+    return DWARFDIE();
+
+  llvm::SmallPtrSet<const DWARFDebugInfoEntry *, 4> seen{orig_die.GetDIE()};
+  return ::GetDeclContextDIEContainingDIE(orig_die, seen);
+}
+
 Symbol *SymbolFileDWARF::GetObjCClassSymbol(ConstString objc_class_name) {
   Symbol *objc_class_symbol = nullptr;
   if (m_objfile_sp) {
diff --git a/lldb/test/Shell/SymbolFile/DWARF/self-referential-specification.yaml b/lldb/test/Shell/SymbolFile/DWARF/self-referential-specification.yaml
new file mode 100644
index 00000000000000..a0ea973c7e21de
--- /dev/null
+++ b/lldb/test/Shell/SymbolFile/DWARF/self-referential-specification.yaml
@@ -0,0 +1,77 @@
+# This is malformed DWARF where a subprogram is its own specification. Check
+# that parsing the function terminates instead of recursing forever.
+#
+# DW_TAG_compile_unit
+#   DW_AT_language    (DW_LANG_C99)
+#   DW_AT_low_pc      (0x1000)
+#   DW_AT_high_pc     (0x04)
+#
+#   DW_TAG_subprogram
+#     DW_AT_name           ("boom")
+#     DW_AT_low_pc         (0x1000)
+#     DW_AT_high_pc        (0x04)
+#     DW_AT_specification  (0x0000001a "boom")
+#
+#   NULL
+
+# RUN: yaml2obj %s > %t
+# RUN: %lldb %t -o "image lookup -v -n boom" -o exit | FileCheck %s
+
+# CHECK: 1 match found
+# CHECK: Function: id = {0x0000001a}, name = "boom"
+
+--- !ELF
+FileHeader:
+  Class:           ELFCLASS64
+  Data:            ELFDATA2LSB
+  Type:            ET_EXEC
+  Machine:         EM_X86_64
+Sections:
+  - Name:            .text
+    Type:            SHT_PROGBITS
+    Flags:           [ SHF_ALLOC, SHF_EXECINSTR ]
+    Address:         0x1000
+    AddressAlign:    0x10
+    Size:            0x4
+DWARF:
+  debug_abbrev:
+    - ID:              0
+      Table:
+        - Code:            0x1
+          Tag:             DW_TAG_compile_unit
+          Children:        DW_CHILDREN_yes
+          Attributes:
+            - Attribute:       DW_AT_language
+              Form:            DW_FORM_data2
+            - Attribute:       DW_AT_low_pc
+              Form:            DW_FORM_addr
+            - Attribute:       DW_AT_high_pc
+              Form:            DW_FORM_data4
+        - Code:            0x2
+          Tag:             DW_TAG_subprogram
+          Children:        DW_CHILDREN_no
+          Attributes:
+            - Attribute:       DW_AT_name
+              Form:            DW_FORM_string
+            - Attribute:       DW_AT_low_pc
+              Form:            DW_FORM_addr
+            - Attribute:       DW_AT_high_pc
+              Form:            DW_FORM_data4
+            - Attribute:       DW_AT_specification
+              Form:            DW_FORM_ref4
+  debug_info:
+    - Version:         4
+      AddrSize:        8
+      Entries:
+        - AbbrCode:        0x1
+          Values:
+            - Value:           0x0C
+            - Value:           0x1000
+            - Value:           0x04
+        - AbbrCode:        0x2
+          Values:
+            - CStr:            boom
+            - Value:           0x1000
+            - Value:           0x04
+            - Value:           0x1A
+        - AbbrCode:        0x0
diff --git a/lldb/unittests/SymbolFile/DWARF/DWARFDIETest.cpp b/lldb/unittests/SymbolFile/DWARF/DWARFDIETest.cpp
index 2611d105e286f4..4e36125dbfde54 100644
--- a/lldb/unittests/SymbolFile/DWARF/DWARFDIETest.cpp
+++ b/lldb/unittests/SymbolFile/DWARF/DWARFDIETest.cpp
@@ -1100,6 +1100,178 @@ INSTANTIATE_TEST_SUITE_P(GetAttributeTests, GetAttributesTestFixture,
                          testing::Values(DW_AT_specification,
                                          DW_AT_abstract_origin));
 
+struct GetDIENamesAndRangesTestFixture
+    : public testing::TestWithParam<dw_attr_t> {};
+
+TEST_P(GetDIENamesAndRangesTestFixture,
+       TestGetDIENamesAndRanges_SelfReference) {
+  // Tests that GetDIENamesAndRanges terminates on a DIE whose specification or
+  // abstract origin points at itself.
+
+  const char *yamldata = R"(
+--- !ELF
+FileHeader:
+  Class:   ELFCLASS64
+  Data:    ELFDATA2LSB
+  Type:    ET_EXEC
+  Machine: EM_AARCH64
+DWARF:
+  debug_abbrev:
+    - ID:              0
+      Table:
+        - Code:            0x1
+          Tag:             DW_TAG_compile_unit
+          Children:        DW_CHILDREN_yes
+          Attributes:
+            - Attribute:       DW_AT_language
+              Form:            DW_FORM_data2
+        - Code:            0x2
+          Tag:             DW_TAG_subprogram
+          Children:        DW_CHILDREN_no
+          Attributes:
+            - Attribute:       DW_AT_name
+              Form:            DW_FORM_string
+            - Attribute:       {0}
+              Form:            DW_FORM_ref4
+  debug_info:
+     - Version:         5
+       UnitType:        DW_UT_compile
+       AddrSize:        8
+       Entries:
+
+        - AbbrCode:        0x1
+          Values:
+            - Value:           0x04
+
+        - AbbrCode:        0x2
+          Values:
+            - CStr:            boom
+            - Value:           0xf
+
+        - AbbrCode: 0x0
+...
+)";
+  YAMLModuleTester t(llvm::formatv(yamldata, GetParam()).str());
+
+  DWARFUnit *unit = t.GetDwarfUnit();
+  ASSERT_NE(unit, nullptr);
+  const DWARFDebugInfoEntry *cu_entry = unit->DIE().GetDIE();
+  ASSERT_EQ(cu_entry->Tag(), DW_TAG_compile_unit);
+  DWARFDIE cu_die(unit, cu_entry);
+
+  DWARFDIE func = cu_die.GetFirstChild();
+  ASSERT_TRUE(func.IsValid());
+  ASSERT_EQ(func.Tag(), DW_TAG_subprogram);
+
+  const char *name = nullptr;
+  const char *mangled = nullptr;
+  llvm::DWARFAddressRangesVector ranges;
+  std::optional<int> decl_file, decl_line, decl_column;
+  std::optional<int> call_file, call_line, call_column;
+
+  EXPECT_FALSE(func.GetDIENamesAndRanges(
+      name, mangled, ranges, decl_file, decl_line, decl_column, call_file,
+      call_line, call_column, /*frame_base=*/nullptr));
+  EXPECT_STREQ(name, "boom");
+  EXPECT_EQ(mangled, nullptr);
+}
+
+TEST_P(GetDIENamesAndRangesTestFixture, TestGetDIENamesAndRanges_Cycle) {
+  // Tests that GetDIENamesAndRanges terminates on a cycle of specifications or
+  // abstract origins, after visiting every DIE in it.
+  //
+  // func1 -> func2 -> func3
+  //   ^                 |
+  //   +-----------------+
+
+  const char *yamldata = R"(
+--- !ELF
+FileHeader:
+  Class:   ELFCLASS64
+  Data:    ELFDATA2LSB
+  Type:    ET_EXEC
+  Machine: EM_AARCH64
+DWARF:
+  debug_abbrev:
+    - ID:              0
+      Table:
+        - Code:            0x1
+          Tag:             DW_TAG_compile_unit
+          Children:        DW_CHILDREN_yes
+          Attributes:
+            - Attribute:       DW_AT_language
+              Form:            DW_FORM_data2
+        - Code:            0x2
+          Tag:             DW_TAG_subprogram
+          Children:        DW_CHILDREN_no
+          Attributes:
+            - Attribute:       {0}
+              Form:            DW_FORM_ref4
+        - Code:            0x3
+          Tag:             DW_TAG_subprogram
+          Children:        DW_CHILDREN_no
+          Attributes:
+            - Attribute:       DW_AT_name
+              Form:            DW_FORM_string
+            - Attribute:       {0}
+              Form:            DW_FORM_ref4
+  debug_info:
+     - Version:         5
+       UnitType:        DW_UT_compile
+       AddrSize:        8
+       Entries:
+
+        - AbbrCode:        0x1
+          Values:
+            - Value:           0x04
+
+        - AbbrCode:        0x2
+          Values:
+            - Value:           0x14
+
+        - AbbrCode:        0x2
+          Values:
+            - Value:           0x19
+
+        - AbbrCode:        0x3
+          Values:
+            - CStr:            boom
+            - Value:           0xf
+
+        - AbbrCode: 0x0
+...
+)";
+  YAMLModuleTester t(llvm::formatv(yamldata, GetParam()).str());
+
+  DWARFUnit *unit = t.GetDwarfUnit();
+  ASSERT_NE(unit, nullptr);
+  const DWARFDebugInfoEntry *cu_entry = unit->DIE().GetDIE();
+  ASSERT_EQ(cu_entry->Tag(), DW_TAG_compile_unit);
+  DWARFDIE cu_die(unit, cu_entry);
+
+  DWARFDIE func1 = cu_die.GetFirstChild();
+  ASSERT_TRUE(func1.IsValid());
+  ASSERT_EQ(func1.Tag(), DW_TAG_subprogram);
+
+  const char *name = nullptr;
+  const char *mangled = nullptr;
+  llvm::DWARFAddressRangesVector ranges;
+  std::optional<int> decl_file, decl_line, decl_column;
+  std::optional<int> call_file, call_line, call_column;
+
+  EXPECT_FALSE(func1.GetDIENamesAndRanges(
+      name, mangled, ranges, decl_file, decl_line, decl_column, call_file,
+      call_line, call_column, /*frame_base=*/nullptr));
+  // The name comes from the last DIE in the cycle.
+  EXPECT_STREQ(name, "boom");
+  EXPECT_EQ(mangled, nullptr);
+}
+
+INSTANTIATE_TEST_SUITE_P(GetDIENamesAndRangesTests,
+                         GetDIENamesAndRangesTestFixture,
+                         testing::Values(DW_AT_specification,
+                                         DW_AT_abstract_origin));
+
 // Exercises fallback in SymbolFileDWARF::ParseVariableDIE (added for
 // Swift) that walks the type chain for DW_AT_byte_size when the
 // TypeSystem cannot determine the size of a variable's storage. The

>From 13eb118f7548422e268f057f5a5c0dffa186b531 Mon Sep 17 00:00:00 2001
From: Jonas Devlieghere <jonas at devlieghere.com>
Date: Tue, 15 Sep 2026 22:14:45 -0700
Subject: [PATCH 2/2] [lldb] Bounds check minidump location descriptors

MinidumpParser::GetModuleUUID sliced the file with the RVA and DataSize
taken straight from a module's CvRecord. ArrayRef::slice asserts, but a
build without assertions still reads out of bounds.

Route both through MinidumpFile::getRawData, which range checks in 64
bits, and log the error rather than returning a slice that looks valid.

rdar://186889966
---
 .../Process/minidump/MinidumpParser.cpp       | 20 ++++--
 .../Process/minidump/MinidumpParserTest.cpp   | 68 +++++++++++++++++++
 2 files changed, 84 insertions(+), 4 deletions(-)

diff --git a/lldb/source/Plugins/Process/minidump/MinidumpParser.cpp b/lldb/source/Plugins/Process/minidump/MinidumpParser.cpp
index 1334f69dad6dcd..f15e837cc006c6 100644
--- a/lldb/source/Plugins/Process/minidump/MinidumpParser.cpp
+++ b/lldb/source/Plugins/Process/minidump/MinidumpParser.cpp
@@ -55,8 +55,14 @@ MinidumpParser::GetRawStream(StreamType stream_type) {
 }
 
 UUID MinidumpParser::GetModuleUUID(const minidump::Module *module) {
-  auto cv_record =
-      GetData().slice(module->CvRecord.RVA, module->CvRecord.DataSize);
+  llvm::Expected<llvm::ArrayRef<uint8_t>> expected_cv_record =
+      GetMinidumpFile().getRawData(module->CvRecord);
+  if (!expected_cv_record) {
+    LLDB_LOG_ERROR(GetLog(LLDBLog::Modules), expected_cv_record.takeError(),
+                   "Failed to read the CodeView record: {0}");
+    return UUID();
+  }
+  llvm::ArrayRef<uint8_t> cv_record = *expected_cv_record;
 
   // Read the CV record signature
   const llvm::support::ulittle32_t *signature = nullptr;
@@ -96,9 +102,15 @@ llvm::ArrayRef<minidump::Thread> MinidumpParser::GetThreads() {
 
 llvm::ArrayRef<uint8_t>
 MinidumpParser::GetThreadContext(const LocationDescriptor &location) {
-  if (location.RVA + location.DataSize > GetData().size())
+  // Use getRawData to widen the two 32-bit fields and check for overflow.
+  llvm::Expected<llvm::ArrayRef<uint8_t>> expected_context =
+      GetMinidumpFile().getRawData(location);
+  if (!expected_context) {
+    LLDB_LOG_ERROR(GetLog(LLDBLog::Thread), expected_context.takeError(),
+                   "Failed to read the thread context: {0}");
     return {};
-  return GetData().slice(location.RVA, location.DataSize);
+  }
+  return *expected_context;
 }
 
 llvm::ArrayRef<uint8_t>
diff --git a/lldb/unittests/Process/minidump/MinidumpParserTest.cpp b/lldb/unittests/Process/minidump/MinidumpParserTest.cpp
index a5986eafda83ef..2121e3b7f9f979 100644
--- a/lldb/unittests/Process/minidump/MinidumpParserTest.cpp
+++ b/lldb/unittests/Process/minidump/MinidumpParserTest.cpp
@@ -36,6 +36,28 @@
 using namespace lldb_private;
 using namespace minidump;
 
+/// Wrap raw stream contents in a single-stream minidump. Unlike yaml2obj, this
+/// leaves the location descriptors inside the stream untouched, so they can
+/// point anywhere.
+static std::string MakeMinidump(StreamType type, llvm::StringRef contents) {
+  Header header = {};
+  header.Signature = Header::MagicSignature;
+  header.Version = Header::MagicVersion;
+  header.NumberOfStreams = 1;
+  header.StreamDirectoryRVA = sizeof(Header);
+
+  Directory directory = {};
+  directory.Type = type;
+  directory.Location.RVA = sizeof(Header) + sizeof(Directory);
+  directory.Location.DataSize = contents.size();
+
+  std::string data;
+  data.append(reinterpret_cast<const char *>(&header), sizeof(header));
+  data.append(reinterpret_cast<const char *>(&directory), sizeof(directory));
+  data.append(contents);
+  return data;
+}
+
 class MinidumpParserTest : public testing::Test {
 public:
   SubsystemRAII<FileSystem> subsystems;
@@ -59,6 +81,10 @@ class MinidumpParserTest : public testing::Test {
       return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                      "convertYAML() failed");
 
+    return SetUpFromData(data);
+  }
+
+  llvm::Error SetUpFromData(llvm::StringRef data) {
     auto data_buffer_sp =
         std::make_shared<DataBufferHeap>(data.data(), data.size());
     auto expected_parser = MinidumpParser::Create(std::move(data_buffer_sp));
@@ -911,3 +937,45 @@ TEST_F(MinidumpParserTest, MinidumpModuleOrder) {
       parser->GetMinidumpFile().getString(filtered_modules[1]->ModuleNameRVA),
       llvm::HasValue("/tmp/b"));
 }
+
+TEST_F(MinidumpParserTest, GetModuleUUIDOutOfRangeCvRecord) {
+  minidump::Module module = {};
+  module.BaseOfImage = 0x1000;
+  module.SizeOfImage = 0x1000;
+  module.CvRecord.RVA = 0xf0000000;
+  module.CvRecord.DataSize = sizeof(llvm::support::ulittle32_t);
+
+  std::string stream;
+  llvm::support::ulittle32_t module_count(1);
+  stream.append(reinterpret_cast<const char *>(&module_count),
+                sizeof(module_count));
+  stream.append(reinterpret_cast<const char *>(&module), sizeof(module));
+
+  ASSERT_THAT_ERROR(SetUpFromData(MakeMinidump(StreamType::ModuleList, stream)),
+                    llvm::Succeeded());
+
+  llvm::ArrayRef<minidump::Module> modules = parser->GetModuleList();
+  ASSERT_EQ(1u, modules.size());
+  EXPECT_FALSE(parser->GetModuleUUID(&modules[0]).IsValid());
+}
+
+TEST_F(MinidumpParserTest, GetThreadContextOutOfRange) {
+  minidump::Thread thread = {};
+  thread.ThreadId = 0x3e81;
+  // The sum of the two fields wraps around in 32 bits.
+  thread.Context.RVA = 0xfffffff0;
+  thread.Context.DataSize = 0x20;
+
+  std::string stream;
+  llvm::support::ulittle32_t thread_count(1);
+  stream.append(reinterpret_cast<const char *>(&thread_count),
+                sizeof(thread_count));
+  stream.append(reinterpret_cast<const char *>(&thread), sizeof(thread));
+
+  ASSERT_THAT_ERROR(SetUpFromData(MakeMinidump(StreamType::ThreadList, stream)),
+                    llvm::Succeeded());
+
+  llvm::ArrayRef<minidump::Thread> threads = parser->GetThreads();
+  ASSERT_EQ(1u, threads.size());
+  EXPECT_TRUE(parser->GetThreadContext(threads[0]).empty());
+}



More information about the lldb-commits mailing list