[MachO] Prevent heap overflow when load command extends past EOF

This patch fixes a heap-buffer-overflow when a malformed Mach-O has a
load command who's size extends past the end of the binary.

Fixes: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=3225

Differential revision: https://reviews.llvm.org/D37439

llvm-svn: 313145
diff --git a/llvm/lib/Object/MachOObjectFile.cpp b/llvm/lib/Object/MachOObjectFile.cpp
index a32533b..b943c40 100644
--- a/llvm/lib/Object/MachOObjectFile.cpp
+++ b/llvm/lib/Object/MachOObjectFile.cpp
@@ -183,6 +183,9 @@
 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())
+      return malformedError("load command " + Twine(LoadCommandIndex) +
+                            " extends past end of file");
     if (CmdOrErr->cmdsize < 8)
       return malformedError("load command " + Twine(LoadCommandIndex) +
                             " with size less than 8 bytes");
@@ -800,7 +803,7 @@
                               uint32_t LoadCommandIndex,
                               std::list<MachOElement> &Elements) {
   if (Load.C.cmdsize != sizeof(MachO::note_command))
-    return malformedError("load command " + Twine(LoadCommandIndex) + 
+    return malformedError("load command " + Twine(LoadCommandIndex) +
                           " LC_NOTE has incorrect cmdsize");
   MachO::note_command Nt = getStruct<MachO::note_command>(Obj, Load.Ptr);
   uint64_t FileSize = Obj.getData().size();