From 2acc55815c60a15723cbbb4db5ede9c3c77b3cad Mon Sep 17 00:00:00 2001
From: Dave Watson <davejwatson@fb.com>
Date: Wed, 16 Aug 2017 10:59:32 -0700
Subject: [PATCH] elf: Don't use .gnu_debuglink if it doesn't exist

Some binaries contain a gnu_debuglink, even though the actual
file it points to doesn't exist.  In those cases, continue
to use the existing binary instead of trying to load the debuglink file.
---
 src/elfxx.c | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)

diff --git a/src/elfxx.c b/src/elfxx.c
index 685cf2f5..48a08cdc 100644
--- a/src/elfxx.c
+++ b/src/elfxx.c
@@ -386,6 +386,8 @@ elf_w (load_debuglink) (const char* file, struct elf_image *ei, int is_local)
 {
   int ret;
   Elf_W (Shdr) *shdr;
+  Elf_W (Ehdr) *prev_image = ei->image;
+  off_t prev_size = ei->size;
 
   if (!ei->image)
     {
@@ -420,7 +422,6 @@ elf_w (load_debuglink) (const char* file, struct elf_image *ei, int is_local)
       if (memchr (linkbuf, 0, shdr->sh_size) == NULL)
 	return 0;
 
-      munmap (ei->image, ei->size);
       ei->image = NULL;
 
       Debug(1, "Found debuglink section, following %s\n", linkbuf);
@@ -456,6 +457,19 @@ elf_w (load_debuglink) (const char* file, struct elf_image *ei, int is_local)
 	  ret = elf_w (load_debuglink) (newname, ei, -1);
 	}
 
+      if (ret == -1)
+        {
+          /* No debuglink file found even though .gnu_debuglink existed */
+          ei->image = prev_image;
+          ei->size = prev_size;
+
+          return 0;
+        }
+      else
+        {
+          munmap (prev_image, prev_size);
+        }
+
       return ret;
     }
   }