[llvm] [MachO] Improve bounds check (PR #141083)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Thu May 22 07:59:48 PDT 2025


https://github.com/nikic created https://github.com/llvm/llvm-project/pull/141083

The current check may fail if the addition overflows. I've observed failures of macho-invalid.test on 32-bit due to this.

Instead, compare against the remaining bytes until the end of the object.

>From 14c56d8f5c90c13f382817e77a0b8db122c8b6d0 Mon Sep 17 00:00:00 2001
From: Nikita Popov <npopov at redhat.com>
Date: Thu, 22 May 2025 16:57:07 +0200
Subject: [PATCH] [MachO] Improve bounds check

The current check may fail if the addition overflows. I've observed
failures of macho-invalid.test on 32-bit due to this.

Instead, compare against the remaining bytes until the end of the
object.
---
 llvm/lib/Object/MachOObjectFile.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/Object/MachOObjectFile.cpp b/llvm/lib/Object/MachOObjectFile.cpp
index 69d36e6a77db7..5db264207ffb7 100644
--- a/llvm/lib/Object/MachOObjectFile.cpp
+++ b/llvm/lib/Object/MachOObjectFile.cpp
@@ -192,7 +192,8 @@ static Expected<MachOObjectFile::LoadCommandInfo>
 getLoadCommandInfo(const MachOObjectFile &Obj, const char *Ptr,
                    uint32_t LoadCommandIndex) {
   if (auto CmdOrErr = getStructOrErr<MachO::load_command>(Obj, Ptr)) {
-    if (CmdOrErr->cmdsize + Ptr > Obj.getData().end())
+    assert(Ptr <= Obj.getData().end() && "Start must be before end");
+    if (CmdOrErr->cmdsize > (uintptr_t)(Obj.getData().end() - Ptr))
       return malformedError("load command " + Twine(LoadCommandIndex) +
                             " extends past end of file");
     if (CmdOrErr->cmdsize < 8)



More information about the llvm-commits mailing list