1 //===- tools/dsymutil/DwarfLinkerForBinary.cpp ----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "DwarfLinkerForBinary.h"
10 #include "BinaryHolder.h"
11 #include "DebugMap.h"
12 #include "MachOUtils.h"
13 #include "dsymutil.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DenseMapInfo.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/FoldingSet.h"
20 #include "llvm/ADT/Hashing.h"
21 #include "llvm/ADT/IntervalMap.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/PointerIntPair.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/Triple.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/BinaryFormat/Dwarf.h"
32 #include "llvm/BinaryFormat/MachO.h"
33 #include "llvm/CodeGen/AccelTable.h"
34 #include "llvm/CodeGen/AsmPrinter.h"
35 #include "llvm/CodeGen/DIE.h"
36 #include "llvm/CodeGen/NonRelocatableStringpool.h"
37 #include "llvm/Config/config.h"
38 #include "llvm/DWARFLinker/DWARFLinkerDeclContext.h"
39 #include "llvm/DebugInfo/DIContext.h"
40 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
41 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
42 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
43 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
44 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
45 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
46 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
47 #include "llvm/DebugInfo/DWARF/DWARFSection.h"
48 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
49 #include "llvm/MC/MCAsmBackend.h"
50 #include "llvm/MC/MCAsmInfo.h"
51 #include "llvm/MC/MCCodeEmitter.h"
52 #include "llvm/MC/MCContext.h"
53 #include "llvm/MC/MCDwarf.h"
54 #include "llvm/MC/MCInstrInfo.h"
55 #include "llvm/MC/MCObjectFileInfo.h"
56 #include "llvm/MC/MCObjectWriter.h"
57 #include "llvm/MC/MCRegisterInfo.h"
58 #include "llvm/MC/MCSection.h"
59 #include "llvm/MC/MCStreamer.h"
60 #include "llvm/MC/MCSubtargetInfo.h"
61 #include "llvm/MC/MCTargetOptions.h"
62 #include "llvm/Object/MachO.h"
63 #include "llvm/Object/ObjectFile.h"
64 #include "llvm/Object/SymbolicFile.h"
65 #include "llvm/Support/Allocator.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/Compiler.h"
68 #include "llvm/Support/DJB.h"
69 #include "llvm/Support/DataExtractor.h"
70 #include "llvm/Support/Error.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/ErrorOr.h"
73 #include "llvm/Support/FileSystem.h"
74 #include "llvm/Support/Format.h"
75 #include "llvm/Support/LEB128.h"
76 #include "llvm/Support/MathExtras.h"
77 #include "llvm/Support/MemoryBuffer.h"
78 #include "llvm/Support/Path.h"
79 #include "llvm/Support/TargetRegistry.h"
80 #include "llvm/Support/ThreadPool.h"
81 #include "llvm/Support/ToolOutputFile.h"
82 #include "llvm/Support/WithColor.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include "llvm/Target/TargetMachine.h"
85 #include "llvm/Target/TargetOptions.h"
86 #include "llvm/MC/MCTargetOptionsCommandFlags.h"
87 #include <algorithm>
88 #include <cassert>
89 #include <cinttypes>
90 #include <climits>
91 #include <cstdint>
92 #include <cstdlib>
93 #include <cstring>
94 #include <limits>
95 #include <map>
96 #include <memory>
97 #include <string>
98 #include <system_error>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 namespace llvm {
104 
105 static mc::RegisterMCTargetOptionsFlags MOF;
106 
107 namespace dsymutil {
108 
109 static Error copySwiftInterfaces(
110     const std::map<std::string, std::string> &ParseableSwiftInterfaces,
111     StringRef Architecture, const LinkOptions &Options) {
112   std::error_code EC;
113   SmallString<128> InputPath;
114   SmallString<128> Path;
115   sys::path::append(Path, *Options.ResourceDir, "Swift", Architecture);
116   if ((EC = sys::fs::create_directories(Path.str(), true,
117                                         sys::fs::perms::all_all)))
118     return make_error<StringError>(
119         "cannot create directory: " + toString(errorCodeToError(EC)), EC);
120   unsigned BaseLength = Path.size();
121 
122   for (auto &I : ParseableSwiftInterfaces) {
123     StringRef ModuleName = I.first;
124     StringRef InterfaceFile = I.second;
125     if (!Options.PrependPath.empty()) {
126       InputPath.clear();
127       sys::path::append(InputPath, Options.PrependPath, InterfaceFile);
128       InterfaceFile = InputPath;
129     }
130     sys::path::append(Path, ModuleName);
131     Path.append(".swiftinterface");
132     if (Options.Verbose)
133       outs() << "copy parseable Swift interface " << InterfaceFile << " -> "
134              << Path.str() << '\n';
135 
136     // copy_file attempts an APFS clone first, so this should be cheap.
137     if ((EC = sys::fs::copy_file(InterfaceFile, Path.str())))
138       warn(Twine("cannot copy parseable Swift interface ") + InterfaceFile +
139            ": " + toString(errorCodeToError(EC)));
140     Path.resize(BaseLength);
141   }
142   return Error::success();
143 }
144 
145 /// Report a warning to the user, optionally including information about a
146 /// specific \p DIE related to the warning.
147 void DwarfLinkerForBinary::reportWarning(const Twine &Warning,
148                                          StringRef Context,
149                                          const DWARFDie *DIE) const {
150 
151   warn(Warning, Context);
152 
153   if (!Options.Verbose || !DIE)
154     return;
155 
156   DIDumpOptions DumpOpts;
157   DumpOpts.ChildRecurseDepth = 0;
158   DumpOpts.Verbose = Options.Verbose;
159 
160   WithColor::note() << "    in DIE:\n";
161   DIE->dump(errs(), 6 /* Indent */, DumpOpts);
162 }
163 
164 bool DwarfLinkerForBinary::createStreamer(const Triple &TheTriple,
165                                           raw_fd_ostream &OutFile) {
166   if (Options.NoOutput)
167     return true;
168 
169   Streamer = std::make_unique<DwarfStreamer>(
170       Options.FileType, OutFile, Options.Translator, Options.Minimize,
171       [&](const Twine &Error, StringRef Context, const DWARFDie *) {
172         error(Error, Context);
173       },
174       [&](const Twine &Warning, StringRef Context, const DWARFDie *) {
175         warn(Warning, Context);
176       });
177   return Streamer->init(TheTriple);
178 }
179 
180 ErrorOr<const object::ObjectFile &>
181 DwarfLinkerForBinary::loadObject(const DebugMapObject &Obj,
182                                  const Triple &Triple) {
183   auto ObjectEntry =
184       BinHolder.getObjectEntry(Obj.getObjectFilename(), Obj.getTimestamp());
185   if (!ObjectEntry) {
186     auto Err = ObjectEntry.takeError();
187     reportWarning(Twine(Obj.getObjectFilename()) + ": " +
188                       toString(std::move(Err)),
189                   Obj.getObjectFilename());
190     return errorToErrorCode(std::move(Err));
191   }
192 
193   auto Object = ObjectEntry->getObject(Triple);
194   if (!Object) {
195     auto Err = Object.takeError();
196     reportWarning(Twine(Obj.getObjectFilename()) + ": " +
197                       toString(std::move(Err)),
198                   Obj.getObjectFilename());
199     return errorToErrorCode(std::move(Err));
200   }
201 
202   return *Object;
203 }
204 
205 static Error remarksErrorHandler(const DebugMapObject &DMO,
206                                  DwarfLinkerForBinary &Linker,
207                                  std::unique_ptr<FileError> FE) {
208   bool IsArchive = DMO.getObjectFilename().endswith(")");
209   // Don't report errors for missing remark files from static
210   // archives.
211   if (!IsArchive)
212     return Error(std::move(FE));
213 
214   std::string Message = FE->message();
215   Error E = FE->takeError();
216   Error NewE = handleErrors(std::move(E), [&](std::unique_ptr<ECError> EC) {
217     if (EC->convertToErrorCode() != std::errc::no_such_file_or_directory)
218       return Error(std::move(EC));
219 
220     Linker.reportWarning(Message, DMO.getObjectFilename());
221     return Error(Error::success());
222   });
223 
224   if (!NewE)
225     return Error::success();
226 
227   return createFileError(FE->getFileName(), std::move(NewE));
228 }
229 
230 static Error emitRemarks(const LinkOptions &Options, StringRef BinaryPath,
231                          StringRef ArchName, const remarks::RemarkLinker &RL) {
232   // Make sure we don't create the directories and the file if there is nothing
233   // to serialize.
234   if (RL.empty())
235     return Error::success();
236 
237   SmallString<128> InputPath;
238   SmallString<128> Path;
239   // Create the "Remarks" directory in the "Resources" directory.
240   sys::path::append(Path, *Options.ResourceDir, "Remarks");
241   if (std::error_code EC = sys::fs::create_directories(Path.str(), true,
242                                                        sys::fs::perms::all_all))
243     return errorCodeToError(EC);
244 
245   // Append the file name.
246   // For fat binaries, also append a dash and the architecture name.
247   sys::path::append(Path, sys::path::filename(BinaryPath));
248   if (Options.NumDebugMaps > 1) {
249     // More than one debug map means we have a fat binary.
250     Path += '-';
251     Path += ArchName;
252   }
253 
254   std::error_code EC;
255   raw_fd_ostream OS(Options.NoOutput ? "-" : Path.str(), EC, sys::fs::OF_None);
256   if (EC)
257     return errorCodeToError(EC);
258 
259   if (Error E = RL.serialize(OS, Options.RemarksFormat))
260     return E;
261 
262   return Error::success();
263 }
264 
265 ErrorOr<DwarfFile &>
266 DwarfLinkerForBinary::loadObject(const DebugMapObject &Obj,
267                                  const DebugMap &DebugMap,
268                                  remarks::RemarkLinker &RL) {
269   auto ErrorOrObj = loadObject(Obj, DebugMap.getTriple());
270 
271   if (ErrorOrObj) {
272     ContextForLinking.push_back(
273         std::unique_ptr<DWARFContext>(DWARFContext::create(*ErrorOrObj)));
274     AddressMapForLinking.push_back(
275         std::make_unique<AddressManager>(*this, *ErrorOrObj, Obj));
276 
277     ObjectsForLinking.push_back(std::make_unique<DwarfFile>(
278         Obj.getObjectFilename(), ContextForLinking.back().get(),
279         AddressMapForLinking.back().get(),
280         Obj.empty() ? Obj.getWarnings() : EmptyWarnings));
281 
282     Error E = RL.link(*ErrorOrObj);
283     if (Error NewE = handleErrors(
284             std::move(E), [&](std::unique_ptr<FileError> EC) -> Error {
285               return remarksErrorHandler(Obj, *this, std::move(EC));
286             }))
287       return errorToErrorCode(std::move(NewE));
288 
289     return *ObjectsForLinking.back();
290   }
291 
292   return ErrorOrObj.getError();
293 }
294 
295 bool DwarfLinkerForBinary::link(const DebugMap &Map) {
296   if (!createStreamer(Map.getTriple(), OutFile))
297     return false;
298 
299   ObjectsForLinking.clear();
300   ContextForLinking.clear();
301   AddressMapForLinking.clear();
302 
303   DebugMap DebugMap(Map.getTriple(), Map.getBinaryPath());
304 
305   DWARFLinker GeneralLinker(Streamer.get(), DwarfLinkerClient::Dsymutil);
306 
307   remarks::RemarkLinker RL;
308   if (!Options.RemarksPrependPath.empty())
309     RL.setExternalFilePrependPath(Options.RemarksPrependPath);
310   GeneralLinker.setObjectPrefixMap(&Options.ObjectPrefixMap);
311 
312   std::function<StringRef(StringRef)> TranslationLambda = [&](StringRef Input) {
313     assert(Options.Translator);
314     return Options.Translator(Input);
315   };
316 
317   GeneralLinker.setVerbosity(Options.Verbose);
318   GeneralLinker.setNoOutput(Options.NoOutput);
319   GeneralLinker.setNoODR(Options.NoODR);
320   GeneralLinker.setUpdate(Options.Update);
321   GeneralLinker.setNumThreads(Options.Threads);
322   GeneralLinker.setAccelTableKind(Options.TheAccelTableKind);
323   GeneralLinker.setPrependPath(Options.PrependPath);
324   if (Options.Translator)
325     GeneralLinker.setStringsTranslator(TranslationLambda);
326   GeneralLinker.setWarningHandler(
327       [&](const Twine &Warning, StringRef Context, const DWARFDie *DIE) {
328         reportWarning(Warning, Context, DIE);
329       });
330   GeneralLinker.setErrorHandler(
331       [&](const Twine &Error, StringRef Context, const DWARFDie *) {
332         error(Error, Context);
333       });
334   GeneralLinker.setObjFileLoader(
335       [&DebugMap, &RL, this](StringRef ContainerName,
336                              StringRef Path) -> ErrorOr<DwarfFile &> {
337         auto &Obj = DebugMap.addDebugMapObject(
338             Path, sys::TimePoint<std::chrono::seconds>(), MachO::N_OSO);
339 
340         if (auto ErrorOrObj = loadObject(Obj, DebugMap, RL)) {
341           return *ErrorOrObj;
342         } else {
343           // Try and emit more helpful warnings by applying some heuristics.
344           StringRef ObjFile = ContainerName;
345           bool IsClangModule = sys::path::extension(Path).equals(".pcm");
346           bool IsArchive = ObjFile.endswith(")");
347 
348           if (IsClangModule) {
349             StringRef ModuleCacheDir = sys::path::parent_path(Path);
350             if (sys::fs::exists(ModuleCacheDir)) {
351               // If the module's parent directory exists, we assume that the
352               // module cache has expired and was pruned by clang.  A more
353               // adventurous dsymutil would invoke clang to rebuild the module
354               // now.
355               if (!ModuleCacheHintDisplayed) {
356                 WithColor::note()
357                     << "The clang module cache may have expired since "
358                        "this object file was built. Rebuilding the "
359                        "object file will rebuild the module cache.\n";
360                 ModuleCacheHintDisplayed = true;
361               }
362             } else if (IsArchive) {
363               // If the module cache directory doesn't exist at all and the
364               // object file is inside a static library, we assume that the
365               // static library was built on a different machine. We don't want
366               // to discourage module debugging for convenience libraries within
367               // a project though.
368               if (!ArchiveHintDisplayed) {
369                 WithColor::note()
370                     << "Linking a static library that was built with "
371                        "-gmodules, but the module cache was not found.  "
372                        "Redistributable static libraries should never be "
373                        "built with module debugging enabled.  The debug "
374                        "experience will be degraded due to incomplete "
375                        "debug information.\n";
376                 ArchiveHintDisplayed = true;
377               }
378             }
379           }
380 
381           return ErrorOrObj.getError();
382         }
383 
384         llvm_unreachable("Unhandled DebugMap object");
385       });
386   GeneralLinker.setSwiftInterfacesMap(&ParseableSwiftInterfaces);
387 
388   for (const auto &Obj : Map.objects()) {
389     // N_AST objects (swiftmodule files) should get dumped directly into the
390     // appropriate DWARF section.
391     if (Obj->getType() == MachO::N_AST) {
392       if (Options.Verbose)
393         outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
394 
395       StringRef File = Obj->getObjectFilename();
396       auto ErrorOrMem = MemoryBuffer::getFile(File);
397       if (!ErrorOrMem) {
398         warn("Could not open '" + File + "'\n");
399         continue;
400       }
401       sys::fs::file_status Stat;
402       if (auto Err = sys::fs::status(File, Stat)) {
403         warn(Err.message());
404         continue;
405       }
406       if (!Options.NoTimestamp) {
407         // The modification can have sub-second precision so we need to cast
408         // away the extra precision that's not present in the debug map.
409         auto ModificationTime =
410             std::chrono::time_point_cast<std::chrono::seconds>(
411                 Stat.getLastModificationTime());
412         if (ModificationTime != Obj->getTimestamp()) {
413           // Not using the helper here as we can easily stream TimePoint<>.
414           WithColor::warning() << "Timestamp mismatch for " << File << ": "
415                                << Stat.getLastModificationTime() << " and "
416                                << sys::TimePoint<>(Obj->getTimestamp()) << "\n";
417           continue;
418         }
419       }
420 
421       // Copy the module into the .swift_ast section.
422       if (!Options.NoOutput)
423         Streamer->emitSwiftAST((*ErrorOrMem)->getBuffer());
424 
425       continue;
426     }
427 
428     if (auto ErrorOrObj = loadObject(*Obj, Map, RL))
429       GeneralLinker.addObjectFile(*ErrorOrObj);
430     else {
431       ObjectsForLinking.push_back(std::make_unique<DwarfFile>(
432           Obj->getObjectFilename(), nullptr, nullptr,
433           Obj->empty() ? Obj->getWarnings() : EmptyWarnings));
434       GeneralLinker.addObjectFile(*ObjectsForLinking.back());
435     }
436   }
437 
438   // link debug info for loaded object files.
439   GeneralLinker.link();
440 
441   StringRef ArchName = Map.getTriple().getArchName();
442   if (Error E = emitRemarks(Options, Map.getBinaryPath(), ArchName, RL))
443     return error(toString(std::move(E)));
444 
445   if (Options.NoOutput)
446     return true;
447 
448   if (Options.ResourceDir && !ParseableSwiftInterfaces.empty()) {
449     StringRef ArchName = Triple::getArchTypeName(Map.getTriple().getArch());
450     if (auto E =
451             copySwiftInterfaces(ParseableSwiftInterfaces, ArchName, Options))
452       return error(toString(std::move(E)));
453   }
454 
455   if (Map.getTriple().isOSDarwin() && !Map.getBinaryPath().empty() &&
456       Options.FileType == OutputFileType::Object)
457     return MachOUtils::generateDsymCompanion(
458         Map, Options.Translator, *Streamer->getAsmPrinter().OutStreamer,
459         OutFile);
460 
461   Streamer->finish();
462   return true;
463 }
464 
465 static bool isMachOPairedReloc(uint64_t RelocType, uint64_t Arch) {
466   switch (Arch) {
467   case Triple::x86:
468     return RelocType == MachO::GENERIC_RELOC_SECTDIFF ||
469            RelocType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF;
470   case Triple::x86_64:
471     return RelocType == MachO::X86_64_RELOC_SUBTRACTOR;
472   case Triple::arm:
473   case Triple::thumb:
474     return RelocType == MachO::ARM_RELOC_SECTDIFF ||
475            RelocType == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
476            RelocType == MachO::ARM_RELOC_HALF ||
477            RelocType == MachO::ARM_RELOC_HALF_SECTDIFF;
478   case Triple::aarch64:
479     return RelocType == MachO::ARM64_RELOC_SUBTRACTOR;
480   default:
481     return false;
482   }
483 }
484 
485 /// Iterate over the relocations of the given \p Section and
486 /// store the ones that correspond to debug map entries into the
487 /// ValidRelocs array.
488 void DwarfLinkerForBinary::AddressManager::findValidRelocsMachO(
489     const object::SectionRef &Section, const object::MachOObjectFile &Obj,
490     const DebugMapObject &DMO) {
491   Expected<StringRef> ContentsOrErr = Section.getContents();
492   if (!ContentsOrErr) {
493     consumeError(ContentsOrErr.takeError());
494     Linker.reportWarning("error reading section", DMO.getObjectFilename());
495     return;
496   }
497   DataExtractor Data(*ContentsOrErr, Obj.isLittleEndian(), 0);
498   bool SkipNext = false;
499 
500   for (const object::RelocationRef &Reloc : Section.relocations()) {
501     if (SkipNext) {
502       SkipNext = false;
503       continue;
504     }
505 
506     object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
507     MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
508 
509     if (isMachOPairedReloc(Obj.getAnyRelocationType(MachOReloc),
510                            Obj.getArch())) {
511       SkipNext = true;
512       Linker.reportWarning("unsupported relocation in debug_info section.",
513                            DMO.getObjectFilename());
514       continue;
515     }
516 
517     unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
518     uint64_t Offset64 = Reloc.getOffset();
519     if ((RelocSize != 4 && RelocSize != 8)) {
520       Linker.reportWarning("unsupported relocation in debug_info section.",
521                            DMO.getObjectFilename());
522       continue;
523     }
524     uint64_t OffsetCopy = Offset64;
525     // Mach-o uses REL relocations, the addend is at the relocation offset.
526     uint64_t Addend = Data.getUnsigned(&OffsetCopy, RelocSize);
527     uint64_t SymAddress;
528     int64_t SymOffset;
529 
530     if (Obj.isRelocationScattered(MachOReloc)) {
531       // The address of the base symbol for scattered relocations is
532       // stored in the reloc itself. The actual addend will store the
533       // base address plus the offset.
534       SymAddress = Obj.getScatteredRelocationValue(MachOReloc);
535       SymOffset = int64_t(Addend) - SymAddress;
536     } else {
537       SymAddress = Addend;
538       SymOffset = 0;
539     }
540 
541     auto Sym = Reloc.getSymbol();
542     if (Sym != Obj.symbol_end()) {
543       Expected<StringRef> SymbolName = Sym->getName();
544       if (!SymbolName) {
545         consumeError(SymbolName.takeError());
546         Linker.reportWarning("error getting relocation symbol name.",
547                              DMO.getObjectFilename());
548         continue;
549       }
550       if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
551         ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
552     } else if (const auto *Mapping = DMO.lookupObjectAddress(SymAddress)) {
553       // Do not store the addend. The addend was the address of the symbol in
554       // the object file, the address in the binary that is stored in the debug
555       // map doesn't need to be offset.
556       ValidRelocs.emplace_back(Offset64, RelocSize, SymOffset, Mapping);
557     }
558   }
559 }
560 
561 /// Dispatch the valid relocation finding logic to the
562 /// appropriate handler depending on the object file format.
563 bool DwarfLinkerForBinary::AddressManager::findValidRelocs(
564     const object::SectionRef &Section, const object::ObjectFile &Obj,
565     const DebugMapObject &DMO) {
566   // Dispatch to the right handler depending on the file type.
567   if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
568     findValidRelocsMachO(Section, *MachOObj, DMO);
569   else
570     Linker.reportWarning(Twine("unsupported object file type: ") +
571                              Obj.getFileName(),
572                          DMO.getObjectFilename());
573   if (ValidRelocs.empty())
574     return false;
575 
576   // Sort the relocations by offset. We will walk the DIEs linearly in
577   // the file, this allows us to just keep an index in the relocation
578   // array that we advance during our walk, rather than resorting to
579   // some associative container. See DwarfLinkerForBinary::NextValidReloc.
580   llvm::sort(ValidRelocs);
581   return true;
582 }
583 
584 /// Look for relocations in the debug_info section that match
585 /// entries in the debug map. These relocations will drive the Dwarf
586 /// link by indicating which DIEs refer to symbols present in the
587 /// linked binary.
588 /// \returns whether there are any valid relocations in the debug info.
589 bool DwarfLinkerForBinary::AddressManager::findValidRelocsInDebugInfo(
590     const object::ObjectFile &Obj, const DebugMapObject &DMO) {
591   // Find the debug_info section.
592   for (const object::SectionRef &Section : Obj.sections()) {
593     StringRef SectionName;
594     if (Expected<StringRef> NameOrErr = Section.getName())
595       SectionName = *NameOrErr;
596     else
597       consumeError(NameOrErr.takeError());
598 
599     SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
600     if (SectionName != "debug_info")
601       continue;
602     return findValidRelocs(Section, Obj, DMO);
603   }
604   return false;
605 }
606 
607 /// Checks that there is a relocation against an actual debug
608 /// map entry between \p StartOffset and \p NextOffset.
609 ///
610 /// This function must be called with offsets in strictly ascending
611 /// order because it never looks back at relocations it already 'went past'.
612 /// \returns true and sets Info.InDebugMap if it is the case.
613 bool DwarfLinkerForBinary::AddressManager::hasValidRelocationAt(
614     uint64_t StartOffset, uint64_t EndOffset, CompileUnit::DIEInfo &Info) {
615   assert(NextValidReloc == 0 ||
616          StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
617   if (NextValidReloc >= ValidRelocs.size())
618     return false;
619 
620   uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
621 
622   // We might need to skip some relocs that we didn't consider. For
623   // example the high_pc of a discarded DIE might contain a reloc that
624   // is in the list because it actually corresponds to the start of a
625   // function that is in the debug map.
626   while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
627     RelocOffset = ValidRelocs[++NextValidReloc].Offset;
628 
629   if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
630     return false;
631 
632   const auto &ValidReloc = ValidRelocs[NextValidReloc++];
633   const auto &Mapping = ValidReloc.Mapping->getValue();
634   const uint64_t BinaryAddress = Mapping.BinaryAddress;
635   const uint64_t ObjectAddress = Mapping.ObjectAddress
636                                      ? uint64_t(*Mapping.ObjectAddress)
637                                      : std::numeric_limits<uint64_t>::max();
638   if (Linker.Options.Verbose)
639     outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
640            << "\t"
641            << format("0x%016" PRIx64 " => 0x%016" PRIx64 "\n", ObjectAddress,
642                      BinaryAddress);
643 
644   Info.AddrAdjust = BinaryAddress + ValidReloc.Addend;
645   if (Mapping.ObjectAddress)
646     Info.AddrAdjust -= ObjectAddress;
647   Info.InDebugMap = true;
648   return true;
649 }
650 
651 /// Apply the valid relocations found by findValidRelocs() to
652 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
653 /// in the debug_info section.
654 ///
655 /// Like for findValidRelocs(), this function must be called with
656 /// monotonic \p BaseOffset values.
657 ///
658 /// \returns whether any reloc has been applied.
659 bool DwarfLinkerForBinary::AddressManager::applyValidRelocs(
660     MutableArrayRef<char> Data, uint64_t BaseOffset, bool IsLittleEndian) {
661   assert(areRelocationsResolved());
662   assert((NextValidReloc == 0 ||
663           BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
664          "BaseOffset should only be increasing.");
665   if (NextValidReloc >= ValidRelocs.size())
666     return false;
667 
668   // Skip relocs that haven't been applied.
669   while (NextValidReloc < ValidRelocs.size() &&
670          ValidRelocs[NextValidReloc].Offset < BaseOffset)
671     ++NextValidReloc;
672 
673   bool Applied = false;
674   uint64_t EndOffset = BaseOffset + Data.size();
675   while (NextValidReloc < ValidRelocs.size() &&
676          ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
677          ValidRelocs[NextValidReloc].Offset < EndOffset) {
678     const auto &ValidReloc = ValidRelocs[NextValidReloc++];
679     assert(ValidReloc.Offset - BaseOffset < Data.size());
680     assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
681     char Buf[8];
682     uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
683     Value += ValidReloc.Addend;
684     for (unsigned I = 0; I != ValidReloc.Size; ++I) {
685       unsigned Index = IsLittleEndian ? I : (ValidReloc.Size - I - 1);
686       Buf[I] = uint8_t(Value >> (Index * 8));
687     }
688     assert(ValidReloc.Size <= sizeof(Buf));
689     memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
690     Applied = true;
691   }
692 
693   return Applied;
694 }
695 
696 bool linkDwarf(raw_fd_ostream &OutFile, BinaryHolder &BinHolder,
697                const DebugMap &DM, LinkOptions Options) {
698   DwarfLinkerForBinary Linker(OutFile, BinHolder, std::move(Options));
699   return Linker.link(DM);
700 }
701 
702 } // namespace dsymutil
703 } // namespace llvm
704