base: Avoid dereferencing end() in findNearest

When used with next_addr, findNearest will return the
next (even larger) address than the nearest larger
address. The problem is that when there is no valid
next, the function was dereferencing addrMap.end().

Fix this by marking next address as 0, since 0 is
not larger than any other address.

Places that use this function should be revisited
to make sure they account for this behavior, as
reported in the following Jira issue:
https://gem5.atlassian.net/browse/GEM5-936

Change-Id: I29ed80ff921b205209aeb5db05ffd3019d8595ce
Signed-off-by: Daniel R. Carvalho <odanrc@yahoo.com.br>
Reviewed-on: https://gem5-review.googlesource.com/c/public/gem5/+/43591
Tested-by: kokoro <noreply+kokoro@google.com>
Reviewed-by: Gabe Black <gabe.black@gmail.com>
Maintainer: Bobby R. Bruce <bbruce@ucdavis.edu>
diff --git a/src/base/loader/symtab.hh b/src/base/loader/symtab.hh
index 200accc..e48e400 100644
--- a/src/base/loader/symtab.hh
+++ b/src/base/loader/symtab.hh
@@ -348,8 +348,9 @@
     }
 
     /**
-     * Find the nearest symbol equal to or less than the supplied
-     * address (e.g., the label for the enclosing function).
+     * Find the nearest symbol equal to or less than the supplied address
+     * (e.g., the label for the enclosing function). If there is no valid
+     * next address, next_addr is assigned 0.
      *
      * @param addr      The address to look up.
      * @param next_addr Address of following symbol (to determine the valid
@@ -363,7 +364,13 @@
         if (!upperBound(addr, i))
             return end();
 
-        next_addr = i->first;
+        // If there is no next address, make it 0 since 0 is not larger than
+        // any other address, so it is clear that next is not valid
+        if (i == addrMap.end()) {
+            next_addr = 0;
+        } else {
+            next_addr = i->first;
+        }
         --i;
         return symbols.begin() + i->second;
     }