[lld] 5f627cc - [lld-macho] Fix symbol name returned from InputSection::getLocation

Nico Weber via llvm-commits llvm-commits at lists.llvm.org
Mon Jun 13 12:52:32 PDT 2022


Author: Daniel Bertalan
Date: 2022-06-13T15:49:27-04:00
New Revision: 5f627cc2251c17ed9362abd556b425e7d0a53437

URL: https://github.com/llvm/llvm-project/commit/5f627cc2251c17ed9362abd556b425e7d0a53437
DIFF: https://github.com/llvm/llvm-project/commit/5f627cc2251c17ed9362abd556b425e7d0a53437.diff

LOG: [lld-macho] Fix symbol name returned from InputSection::getLocation

This commit fixes the issue that getLocation always printed the name of
the first symbol in the section.

For clarity, upper_bound is used instead of a linear search for finding
the closest symbol name. Note that this change does not affect
performance: this function is only called when printing errors and
`symbols` typically contains a single symbol because of
.subsections_via_symbols.

Differential Revision: https://reviews.llvm.org/D127670

Added: 
    

Modified: 
    lld/MachO/InputSection.cpp
    lld/test/MachO/invalid/range-check.s

Removed: 
    


################################################################################
diff  --git a/lld/MachO/InputSection.cpp b/lld/MachO/InputSection.cpp
index 444a1e9b17c1..05ccf298044a 100644
--- a/lld/MachO/InputSection.cpp
+++ b/lld/MachO/InputSection.cpp
@@ -58,12 +58,14 @@ static uint64_t resolveSymbolVA(const Symbol *sym, uint8_t type) {
 std::string InputSection::getLocation(uint64_t off) const {
   // First, try to find a symbol that's near the offset. Use it as a reference
   // point.
-  for (size_t i = 0; i < symbols.size(); ++i)
-    if (symbols[i]->value <= off &&
-        (i + 1 == symbols.size() || symbols[i + 1]->value > off))
-      return (toString(getFile()) + ":(symbol " + symbols.front()->getName() +
-              "+0x" + Twine::utohexstr(off - symbols[i]->value) + ")")
-          .str();
+  auto *nextSym = llvm::upper_bound(
+      symbols, off, [](uint64_t a, const Defined *b) { return a < b->value; });
+  if (nextSym != symbols.begin()) {
+    auto &sym = *std::prev(nextSym);
+    return (toString(getFile()) + ":(symbol " + sym->getName() + "+0x" +
+            Twine::utohexstr(off - sym->value) + ")")
+        .str();
+  }
 
   // If that fails, use the section itself as a reference point.
   for (const Subsection &subsec : section.subsections) {

diff  --git a/lld/test/MachO/invalid/range-check.s b/lld/test/MachO/invalid/range-check.s
index 1ad719cfa31d..688499fec1c8 100644
--- a/lld/test/MachO/invalid/range-check.s
+++ b/lld/test/MachO/invalid/range-check.s
@@ -17,6 +17,11 @@
 _bar:
 
 #--- test.s
+
+# Added to ensure that the error mentions the right function.
+_baz:
+  ret
+
 .globl _main, _foo
 
 _main:


        


More information about the llvm-commits mailing list