[llvm-objcopy][MachO] Handle relocation entries where r_extern is zero

Fix handling of relocations with r_extern == 0.
If r_extern == 0 then r_symbolnum is an index of a section rather than a symbol index.

Patch by Seiya Nuta and Alexander Shaposhnikov.

Test plan: make check-all

Differential revision: https://reviews.llvm.org/D78946
diff --git a/llvm/tools/llvm-objcopy/MachO/MachOReader.cpp b/llvm/tools/llvm-objcopy/MachO/MachOReader.cpp
index b4662ec..b12e39c 100644
--- a/llvm/tools/llvm-objcopy/MachO/MachOReader.cpp
+++ b/llvm/tools/llvm-objcopy/MachO/MachOReader.cpp
@@ -103,6 +103,7 @@
       R.Symbol = nullptr; // We'll fill this field later.
       R.Info = MachOObj.getRelocation(RI->getRawDataRefImpl());
       R.Scattered = MachOObj.isRelocationScattered(R.Info);
+      R.Extern = !R.Scattered && MachOObj.getPlainRelocationExternal(R.Info);
       S.Relocations.push_back(R);
     }
 
@@ -203,12 +204,27 @@
 }
 
 void MachOReader::setSymbolInRelocationInfo(Object &O) const {
+  std::vector<const Section *> Sections;
+  for (auto &LC : O.LoadCommands)
+    for (std::unique_ptr<Section> &Sec : LC.Sections)
+      Sections.push_back(Sec.get());
+
   for (LoadCommand &LC : O.LoadCommands)
     for (std::unique_ptr<Section> &Sec : LC.Sections)
       for (auto &Reloc : Sec->Relocations)
-        if (!Reloc.Scattered)
-          Reloc.Symbol = O.SymTable.getSymbolByIndex(
-              Reloc.getPlainRelocationSymbolNum(MachOObj.isLittleEndian()));
+        if (!Reloc.Scattered) {
+          const uint32_t SymbolNum =
+              Reloc.getPlainRelocationSymbolNum(MachOObj.isLittleEndian());
+          if (Reloc.Extern) {
+            Reloc.Symbol = O.SymTable.getSymbolByIndex(SymbolNum);
+          } else {
+            // FIXME: Refactor error handling in MachOReader and report an error
+            // if we encounter an invalid relocation.
+            assert(SymbolNum >= 1 && SymbolNum <= Sections.size() &&
+                   "Invalid section index.");
+            Reloc.Section = Sections[SymbolNum - 1];
+          }
+        }
 }
 
 void MachOReader::readRebaseInfo(Object &O) const {
diff --git a/llvm/tools/llvm-objcopy/MachO/MachOWriter.cpp b/llvm/tools/llvm-objcopy/MachO/MachOWriter.cpp
index db31ef5..4a8d1ae 100644
--- a/llvm/tools/llvm-objcopy/MachO/MachOWriter.cpp
+++ b/llvm/tools/llvm-objcopy/MachO/MachOWriter.cpp
@@ -239,11 +239,13 @@
       memcpy(B.getBufferStart() + Sec->Offset, Sec->Content.data(),
              Sec->Content.size());
       for (size_t Index = 0; Index < Sec->Relocations.size(); ++Index) {
-        auto RelocInfo = Sec->Relocations[Index];
-        if (!RelocInfo.Scattered)
-          RelocInfo.setPlainRelocationSymbolNum(RelocInfo.Symbol->Index,
-                                                IsLittleEndian);
-
+        RelocationInfo RelocInfo = Sec->Relocations[Index];
+        if (!RelocInfo.Scattered) {
+          const uint32_t SymbolNum = RelocInfo.Extern
+                                         ? (*RelocInfo.Symbol)->Index
+                                         : (*RelocInfo.Section)->Index;
+          RelocInfo.setPlainRelocationSymbolNum(SymbolNum, IsLittleEndian);
+        }
         if (IsLittleEndian != sys::IsLittleEndianHost)
           MachO::swapStruct(
               reinterpret_cast<MachO::any_relocation_info &>(RelocInfo.Info));
diff --git a/llvm/tools/llvm-objcopy/MachO/Object.cpp b/llvm/tools/llvm-objcopy/MachO/Object.cpp
index 89fe994..0f28cb0 100644
--- a/llvm/tools/llvm-objcopy/MachO/Object.cpp
+++ b/llvm/tools/llvm-objcopy/MachO/Object.cpp
@@ -60,13 +60,13 @@
   for (const LoadCommand &LC : LoadCommands)
     for (const std::unique_ptr<Section> &Sec : LC.Sections)
       for (const RelocationInfo &R : Sec->Relocations)
-        if (R.Symbol && DeadSymbols.count(R.Symbol))
+        if (R.Symbol && *R.Symbol && DeadSymbols.count(*R.Symbol))
           return createStringError(std::errc::invalid_argument,
                                    "symbol '%s' defined in section with index "
                                    "'%u' cannot be removed because it is "
                                    "referenced by a relocation in section '%s'",
-                                   R.Symbol->Name.c_str(),
-                                   *(R.Symbol->section()),
+                                   (*R.Symbol)->Name.c_str(),
+                                   *((*R.Symbol)->section()),
                                    Sec->CanonicalName.c_str());
   SymTable.removeSymbols(IsDead);
   for (std::unique_ptr<SymbolEntry> &S : SymTable.Symbols)
diff --git a/llvm/tools/llvm-objcopy/MachO/Object.h b/llvm/tools/llvm-objcopy/MachO/Object.h
index dc828e6..703c31f 100644
--- a/llvm/tools/llvm-objcopy/MachO/Object.h
+++ b/llvm/tools/llvm-objcopy/MachO/Object.h
@@ -162,9 +162,14 @@
 };
 
 struct RelocationInfo {
-  const SymbolEntry *Symbol;
+  // The referenced symbol entry. Set if !Scattered && Extern.
+  Optional<const SymbolEntry *> Symbol;
+  // The referenced section. Set if !Scattered && !Extern.
+  Optional<const Section *> Section;
   // True if Info is a scattered_relocation_info.
   bool Scattered;
+  // True if the r_symbolnum points to a section number (i.e. r_extern=0).
+  bool Extern;
   MachO::any_relocation_info Info;
 
   unsigned getPlainRelocationSymbolNum(bool IsLittleEndian) {