[llvm] [MachO] Detect overflow in section offset. (PR #98685)

Eli Friedman via llvm-commits llvm-commits at lists.llvm.org
Fri Jul 12 13:05:01 PDT 2024


https://github.com/efriedma-quic updated https://github.com/llvm/llvm-project/pull/98685

>From 8d428dd919d2e081e25c102c571a7ca4790b81f5 Mon Sep 17 00:00:00 2001
From: Eli Friedman <efriedma at quicinc.com>
Date: Fri, 12 Jul 2024 12:18:25 -0700
Subject: [PATCH 1/2] [MachO] Detect overflow in section offset.

The section offset field is only 32 bits; if the computed section offset
is larger, make sure we don't emit a corrupt object file.
---
 llvm/lib/MC/MachObjectWriter.cpp             | 2 ++
 llvm/test/MC/MachO/section-offset-overflow.s | 9 +++++++++
 2 files changed, 11 insertions(+)
 create mode 100644 llvm/test/MC/MachO/section-offset-overflow.s

diff --git a/llvm/lib/MC/MachObjectWriter.cpp b/llvm/lib/MC/MachObjectWriter.cpp
index 53eed0092a5b4..f890ecc1d20ee 100644
--- a/llvm/lib/MC/MachObjectWriter.cpp
+++ b/llvm/lib/MC/MachObjectWriter.cpp
@@ -277,6 +277,8 @@ void MachObjectWriter::writeSection(const MCAssembler &Asm,
     W.write<uint32_t>(VMAddr);      // address
     W.write<uint32_t>(SectionSize); // size
   }
+  if (!isUInt<32>(FileOffset))
+    report_fatal_error("Cannot encode offset of section");
   W.write<uint32_t>(FileOffset);
 
   W.write<uint32_t>(Log2(Section.getAlign()));
diff --git a/llvm/test/MC/MachO/section-offset-overflow.s b/llvm/test/MC/MachO/section-offset-overflow.s
new file mode 100644
index 0000000000000..51fc90c2e3479
--- /dev/null
+++ b/llvm/test/MC/MachO/section-offset-overflow.s
@@ -0,0 +1,9 @@
+// RUN: not --crash llvm-mc -triple x86_64-apple-macosx -filetype=obj -o /dev/null %s 2>&1 | FileCheck  %s
+
+// CHECK: Cannot encode offset of section
+
+        .data
+        .long 1
+        .zero 0x100000000
+        .const
+        .long 1

>From a72cfa1dce6b2dbf7718943ec321ae7eafe678f8 Mon Sep 17 00:00:00 2001
From: Eli Friedman <efriedma at quicinc.com>
Date: Fri, 12 Jul 2024 13:04:29 -0700
Subject: [PATCH 2/2] fixup! Also check offset of relocations.

---
 llvm/lib/MC/MachObjectWriter.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/llvm/lib/MC/MachObjectWriter.cpp b/llvm/lib/MC/MachObjectWriter.cpp
index f890ecc1d20ee..4418f68050cd5 100644
--- a/llvm/lib/MC/MachObjectWriter.cpp
+++ b/llvm/lib/MC/MachObjectWriter.cpp
@@ -282,6 +282,8 @@ void MachObjectWriter::writeSection(const MCAssembler &Asm,
   W.write<uint32_t>(FileOffset);
 
   W.write<uint32_t>(Log2(Section.getAlign()));
+  if (NumRelocations && !isUInt<32>(RelocationsStart))
+    report_fatal_error("Cannot encode offset of relocations");
   W.write<uint32_t>(NumRelocations ? RelocationsStart : 0);
   W.write<uint32_t>(NumRelocations);
   W.write<uint32_t>(Flags);



More information about the llvm-commits mailing list