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,
256                     Options.RemarksFormat == remarks::Format::Bitstream
257                         ? sys::fs::OF_None
258                         : sys::fs::OF_Text);
259   if (EC)
260     return errorCodeToError(EC);
261 
262   if (Error E = RL.serialize(OS, Options.RemarksFormat))
263     return E;
264 
265   return Error::success();
266 }
267 
268 ErrorOr<DWARFFile &>
269 DwarfLinkerForBinary::loadObject(const DebugMapObject &Obj,
270                                  const DebugMap &DebugMap,
271                                  remarks::RemarkLinker &RL) {
272   auto ErrorOrObj = loadObject(Obj, DebugMap.getTriple());
273 
274   if (ErrorOrObj) {
275     ContextForLinking.push_back(
276         std::unique_ptr<DWARFContext>(DWARFContext::create(*ErrorOrObj)));
277     AddressMapForLinking.push_back(
278         std::make_unique<AddressManager>(*this, *ErrorOrObj, Obj));
279 
280     ObjectsForLinking.push_back(std::make_unique<DWARFFile>(
281         Obj.getObjectFilename(), ContextForLinking.back().get(),
282         AddressMapForLinking.back().get(),
283         Obj.empty() ? Obj.getWarnings() : EmptyWarnings));
284 
285     Error E = RL.link(*ErrorOrObj);
286     if (Error NewE = handleErrors(
287             std::move(E), [&](std::unique_ptr<FileError> EC) -> Error {
288               return remarksErrorHandler(Obj, *this, std::move(EC));
289             }))
290       return errorToErrorCode(std::move(NewE));
291 
292     return *ObjectsForLinking.back();
293   }
294 
295   return ErrorOrObj.getError();
296 }
297 
298 bool DwarfLinkerForBinary::link(const DebugMap &Map) {
299   if (!createStreamer(Map.getTriple(), OutFile))
300     return false;
301 
302   ObjectsForLinking.clear();
303   ContextForLinking.clear();
304   AddressMapForLinking.clear();
305 
306   DebugMap DebugMap(Map.getTriple(), Map.getBinaryPath());
307 
308   DWARFLinker GeneralLinker(Streamer.get(), DwarfLinkerClient::Dsymutil);
309 
310   remarks::RemarkLinker RL;
311   if (!Options.RemarksPrependPath.empty())
312     RL.setExternalFilePrependPath(Options.RemarksPrependPath);
313   GeneralLinker.setObjectPrefixMap(&Options.ObjectPrefixMap);
314 
315   std::function<StringRef(StringRef)> TranslationLambda = [&](StringRef Input) {
316     assert(Options.Translator);
317     return Options.Translator(Input);
318   };
319 
320   GeneralLinker.setVerbosity(Options.Verbose);
321   GeneralLinker.setStatistics(Options.Statistics);
322   GeneralLinker.setNoOutput(Options.NoOutput);
323   GeneralLinker.setNoODR(Options.NoODR);
324   GeneralLinker.setUpdate(Options.Update);
325   GeneralLinker.setNumThreads(Options.Threads);
326   GeneralLinker.setAccelTableKind(Options.TheAccelTableKind);
327   GeneralLinker.setPrependPath(Options.PrependPath);
328   if (Options.Translator)
329     GeneralLinker.setStringsTranslator(TranslationLambda);
330   GeneralLinker.setWarningHandler(
331       [&](const Twine &Warning, StringRef Context, const DWARFDie *DIE) {
332         reportWarning(Warning, Context, DIE);
333       });
334   GeneralLinker.setErrorHandler(
335       [&](const Twine &Error, StringRef Context, const DWARFDie *) {
336         error(Error, Context);
337       });
338   GeneralLinker.setObjFileLoader(
339       [&DebugMap, &RL, this](StringRef ContainerName,
340                              StringRef Path) -> ErrorOr<DWARFFile &> {
341         auto &Obj = DebugMap.addDebugMapObject(
342             Path, sys::TimePoint<std::chrono::seconds>(), MachO::N_OSO);
343 
344         if (auto ErrorOrObj = loadObject(Obj, DebugMap, RL)) {
345           return *ErrorOrObj;
346         } else {
347           // Try and emit more helpful warnings by applying some heuristics.
348           StringRef ObjFile = ContainerName;
349           bool IsClangModule = sys::path::extension(Path).equals(".pcm");
350           bool IsArchive = ObjFile.endswith(")");
351 
352           if (IsClangModule) {
353             StringRef ModuleCacheDir = sys::path::parent_path(Path);
354             if (sys::fs::exists(ModuleCacheDir)) {
355               // If the module's parent directory exists, we assume that the
356               // module cache has expired and was pruned by clang.  A more
357               // adventurous dsymutil would invoke clang to rebuild the module
358               // now.
359               if (!ModuleCacheHintDisplayed) {
360                 WithColor::note()
361                     << "The clang module cache may have expired since "
362                        "this object file was built. Rebuilding the "
363                        "object file will rebuild the module cache.\n";
364                 ModuleCacheHintDisplayed = true;
365               }
366             } else if (IsArchive) {
367               // If the module cache directory doesn't exist at all and the
368               // object file is inside a static library, we assume that the
369               // static library was built on a different machine. We don't want
370               // to discourage module debugging for convenience libraries within
371               // a project though.
372               if (!ArchiveHintDisplayed) {
373                 WithColor::note()
374                     << "Linking a static library that was built with "
375                        "-gmodules, but the module cache was not found.  "
376                        "Redistributable static libraries should never be "
377                        "built with module debugging enabled.  The debug "
378                        "experience will be degraded due to incomplete "
379                        "debug information.\n";
380                 ArchiveHintDisplayed = true;
381               }
382             }
383           }
384 
385           return ErrorOrObj.getError();
386         }
387 
388         llvm_unreachable("Unhandled DebugMap object");
389       });
390   GeneralLinker.setSwiftInterfacesMap(&ParseableSwiftInterfaces);
391 
392   for (const auto &Obj : Map.objects()) {
393     // N_AST objects (swiftmodule files) should get dumped directly into the
394     // appropriate DWARF section.
395     if (Obj->getType() == MachO::N_AST) {
396       if (Options.Verbose)
397         outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
398 
399       StringRef File = Obj->getObjectFilename();
400       auto ErrorOrMem = MemoryBuffer::getFile(File);
401       if (!ErrorOrMem) {
402         warn("Could not open '" + File + "'\n");
403         continue;
404       }
405       sys::fs::file_status Stat;
406       if (auto Err = sys::fs::status(File, Stat)) {
407         warn(Err.message());
408         continue;
409       }
410       if (!Options.NoTimestamp) {
411         // The modification can have sub-second precision so we need to cast
412         // away the extra precision that's not present in the debug map.
413         auto ModificationTime =
414             std::chrono::time_point_cast<std::chrono::seconds>(
415                 Stat.getLastModificationTime());
416         if (ModificationTime != Obj->getTimestamp()) {
417           // Not using the helper here as we can easily stream TimePoint<>.
418           WithColor::warning()
419               << File << ": timestamp mismatch between swift interface file ("
420               << sys::TimePoint<>(Obj->getTimestamp()) << ") and debug map ("
421               << sys::TimePoint<>(Obj->getTimestamp()) << ")\n";
422           continue;
423         }
424       }
425 
426       // Copy the module into the .swift_ast section.
427       if (!Options.NoOutput)
428         Streamer->emitSwiftAST((*ErrorOrMem)->getBuffer());
429 
430       continue;
431     }
432 
433     if (auto ErrorOrObj = loadObject(*Obj, Map, RL))
434       GeneralLinker.addObjectFile(*ErrorOrObj);
435     else {
436       ObjectsForLinking.push_back(std::make_unique<DWARFFile>(
437           Obj->getObjectFilename(), nullptr, nullptr,
438           Obj->empty() ? Obj->getWarnings() : EmptyWarnings));
439       GeneralLinker.addObjectFile(*ObjectsForLinking.back());
440     }
441   }
442 
443   // link debug info for loaded object files.
444   GeneralLinker.link();
445 
446   StringRef ArchName = Map.getTriple().getArchName();
447   if (Error E = emitRemarks(Options, Map.getBinaryPath(), ArchName, RL))
448     return error(toString(std::move(E)));
449 
450   if (Options.NoOutput)
451     return true;
452 
453   if (Options.ResourceDir && !ParseableSwiftInterfaces.empty()) {
454     StringRef ArchName = Triple::getArchTypeName(Map.getTriple().getArch());
455     if (auto E =
456             copySwiftInterfaces(ParseableSwiftInterfaces, ArchName, Options))
457       return error(toString(std::move(E)));
458   }
459 
460   if (Map.getTriple().isOSDarwin() && !Map.getBinaryPath().empty() &&
461       Options.FileType == OutputFileType::Object)
462     return MachOUtils::generateDsymCompanion(
463         Options.VFS, Map, Options.Translator,
464         *Streamer->getAsmPrinter().OutStreamer, OutFile);
465 
466   Streamer->finish();
467   return true;
468 }
469 
470 static bool isMachOPairedReloc(uint64_t RelocType, uint64_t Arch) {
471   switch (Arch) {
472   case Triple::x86:
473     return RelocType == MachO::GENERIC_RELOC_SECTDIFF ||
474            RelocType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF;
475   case Triple::x86_64:
476     return RelocType == MachO::X86_64_RELOC_SUBTRACTOR;
477   case Triple::arm:
478   case Triple::thumb:
479     return RelocType == MachO::ARM_RELOC_SECTDIFF ||
480            RelocType == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
481            RelocType == MachO::ARM_RELOC_HALF ||
482            RelocType == MachO::ARM_RELOC_HALF_SECTDIFF;
483   case Triple::aarch64:
484     return RelocType == MachO::ARM64_RELOC_SUBTRACTOR;
485   default:
486     return false;
487   }
488 }
489 
490 /// Iterate over the relocations of the given \p Section and
491 /// store the ones that correspond to debug map entries into the
492 /// ValidRelocs array.
493 void DwarfLinkerForBinary::AddressManager::findValidRelocsMachO(
494     const object::SectionRef &Section, const object::MachOObjectFile &Obj,
495     const DebugMapObject &DMO, std::vector<ValidReloc> &ValidRelocs) {
496   Expected<StringRef> ContentsOrErr = Section.getContents();
497   if (!ContentsOrErr) {
498     consumeError(ContentsOrErr.takeError());
499     Linker.reportWarning("error reading section", DMO.getObjectFilename());
500     return;
501   }
502   DataExtractor Data(*ContentsOrErr, Obj.isLittleEndian(), 0);
503   bool SkipNext = false;
504 
505   for (const object::RelocationRef &Reloc : Section.relocations()) {
506     if (SkipNext) {
507       SkipNext = false;
508       continue;
509     }
510 
511     object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
512     MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
513 
514     if (isMachOPairedReloc(Obj.getAnyRelocationType(MachOReloc),
515                            Obj.getArch())) {
516       SkipNext = true;
517       Linker.reportWarning("unsupported relocation in " + *Section.getName() +
518                                " section.",
519                            DMO.getObjectFilename());
520       continue;
521     }
522 
523     unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
524     uint64_t Offset64 = Reloc.getOffset();
525     if ((RelocSize != 4 && RelocSize != 8)) {
526       Linker.reportWarning("unsupported relocation in " + *Section.getName() +
527                                " section.",
528                            DMO.getObjectFilename());
529       continue;
530     }
531     uint64_t OffsetCopy = Offset64;
532     // Mach-o uses REL relocations, the addend is at the relocation offset.
533     uint64_t Addend = Data.getUnsigned(&OffsetCopy, RelocSize);
534     uint64_t SymAddress;
535     int64_t SymOffset;
536 
537     if (Obj.isRelocationScattered(MachOReloc)) {
538       // The address of the base symbol for scattered relocations is
539       // stored in the reloc itself. The actual addend will store the
540       // base address plus the offset.
541       SymAddress = Obj.getScatteredRelocationValue(MachOReloc);
542       SymOffset = int64_t(Addend) - SymAddress;
543     } else {
544       SymAddress = Addend;
545       SymOffset = 0;
546     }
547 
548     auto Sym = Reloc.getSymbol();
549     if (Sym != Obj.symbol_end()) {
550       Expected<StringRef> SymbolName = Sym->getName();
551       if (!SymbolName) {
552         consumeError(SymbolName.takeError());
553         Linker.reportWarning("error getting relocation symbol name.",
554                              DMO.getObjectFilename());
555         continue;
556       }
557       if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
558         ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
559     } else if (const auto *Mapping = DMO.lookupObjectAddress(SymAddress)) {
560       // Do not store the addend. The addend was the address of the symbol in
561       // the object file, the address in the binary that is stored in the debug
562       // map doesn't need to be offset.
563       ValidRelocs.emplace_back(Offset64, RelocSize, SymOffset, Mapping);
564     }
565   }
566 }
567 
568 /// Dispatch the valid relocation finding logic to the
569 /// appropriate handler depending on the object file format.
570 bool DwarfLinkerForBinary::AddressManager::findValidRelocs(
571     const object::SectionRef &Section, const object::ObjectFile &Obj,
572     const DebugMapObject &DMO, std::vector<ValidReloc> &Relocs) {
573   // Dispatch to the right handler depending on the file type.
574   if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
575     findValidRelocsMachO(Section, *MachOObj, DMO, Relocs);
576   else
577     Linker.reportWarning(Twine("unsupported object file type: ") +
578                              Obj.getFileName(),
579                          DMO.getObjectFilename());
580   if (Relocs.empty())
581     return false;
582 
583   // Sort the relocations by offset. We will walk the DIEs linearly in
584   // the file, this allows us to just keep an index in the relocation
585   // array that we advance during our walk, rather than resorting to
586   // some associative container. See DwarfLinkerForBinary::NextValidReloc.
587   llvm::sort(Relocs);
588   return true;
589 }
590 
591 /// Look for relocations in the debug_info and debug_addr section that match
592 /// entries in the debug map. These relocations will drive the Dwarf link by
593 /// indicating which DIEs refer to symbols present in the linked binary.
594 /// \returns whether there are any valid relocations in the debug info.
595 bool DwarfLinkerForBinary::AddressManager::findValidRelocsInDebugSections(
596     const object::ObjectFile &Obj, const DebugMapObject &DMO) {
597   // Find the debug_info section.
598   bool FoundValidRelocs = false;
599   for (const object::SectionRef &Section : Obj.sections()) {
600     StringRef SectionName;
601     if (Expected<StringRef> NameOrErr = Section.getName())
602       SectionName = *NameOrErr;
603     else
604       consumeError(NameOrErr.takeError());
605 
606     SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
607     if (SectionName == "debug_info")
608       FoundValidRelocs |=
609           findValidRelocs(Section, Obj, DMO, ValidDebugInfoRelocs);
610     if (SectionName == "debug_addr")
611       FoundValidRelocs |=
612           findValidRelocs(Section, Obj, DMO, ValidDebugAddrRelocs);
613   }
614   return FoundValidRelocs;
615 }
616 
617 std::vector<DwarfLinkerForBinary::AddressManager::ValidReloc>
618 DwarfLinkerForBinary::AddressManager::getRelocations(
619     const std::vector<ValidReloc> &Relocs, uint64_t StartPos, uint64_t EndPos) {
620   std::vector<DwarfLinkerForBinary::AddressManager::ValidReloc> Res;
621 
622   auto CurReloc = partition_point(Relocs, [StartPos](const ValidReloc &Reloc) {
623     return Reloc.Offset < StartPos;
624   });
625 
626   while (CurReloc != Relocs.end() && CurReloc->Offset >= StartPos &&
627          CurReloc->Offset < EndPos) {
628     Res.push_back(*CurReloc);
629     CurReloc++;
630   }
631 
632   return Res;
633 }
634 
635 void DwarfLinkerForBinary::AddressManager::printReloc(const ValidReloc &Reloc) {
636   const auto &Mapping = Reloc.Mapping->getValue();
637   const uint64_t ObjectAddress = Mapping.ObjectAddress
638                                      ? uint64_t(*Mapping.ObjectAddress)
639                                      : std::numeric_limits<uint64_t>::max();
640 
641   outs() << "Found valid debug map entry: " << Reloc.Mapping->getKey() << "\t"
642          << format("0x%016" PRIx64 " => 0x%016" PRIx64 "\n", ObjectAddress,
643                    uint64_t(Mapping.BinaryAddress));
644 }
645 
646 void DwarfLinkerForBinary::AddressManager::fillDieInfo(
647     const ValidReloc &Reloc, CompileUnit::DIEInfo &Info) {
648   Info.AddrAdjust = relocate(Reloc);
649   if (Reloc.Mapping->getValue().ObjectAddress)
650     Info.AddrAdjust -= uint64_t(*Reloc.Mapping->getValue().ObjectAddress);
651   Info.InDebugMap = true;
652 }
653 
654 bool DwarfLinkerForBinary::AddressManager::hasValidRelocationAt(
655     const std::vector<ValidReloc> &AllRelocs, uint64_t StartOffset,
656     uint64_t EndOffset, CompileUnit::DIEInfo &Info) {
657   std::vector<ValidReloc> Relocs =
658       getRelocations(AllRelocs, StartOffset, EndOffset);
659 
660   if (Relocs.size() == 0)
661     return false;
662 
663   if (Linker.Options.Verbose)
664     printReloc(Relocs[0]);
665   fillDieInfo(Relocs[0], Info);
666 
667   return true;
668 }
669 
670 /// Get the starting and ending (exclusive) offset for the
671 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
672 /// supposed to point to the position of the first attribute described
673 /// by \p Abbrev.
674 /// \return [StartOffset, EndOffset) as a pair.
675 static std::pair<uint64_t, uint64_t>
676 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
677                     uint64_t Offset, const DWARFUnit &Unit) {
678   DataExtractor Data = Unit.getDebugInfoExtractor();
679 
680   for (unsigned I = 0; I < Idx; ++I)
681     DWARFFormValue::skipValue(Abbrev->getFormByIndex(I), Data, &Offset,
682                               Unit.getFormParams());
683 
684   uint64_t End = Offset;
685   DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End,
686                             Unit.getFormParams());
687 
688   return std::make_pair(Offset, End);
689 }
690 
691 bool DwarfLinkerForBinary::AddressManager::hasLiveMemoryLocation(
692     const DWARFDie &DIE, CompileUnit::DIEInfo &MyInfo) {
693   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
694 
695   Optional<uint32_t> LocationIdx =
696       Abbrev->findAttributeIndex(dwarf::DW_AT_location);
697   if (!LocationIdx)
698     return false;
699 
700   uint64_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
701   uint64_t LocationOffset, LocationEndOffset;
702   std::tie(LocationOffset, LocationEndOffset) =
703       getAttributeOffsets(Abbrev, *LocationIdx, Offset, *DIE.getDwarfUnit());
704 
705   // FIXME: Support relocations debug_addr.
706   return hasValidRelocationAt(ValidDebugInfoRelocs, LocationOffset,
707                               LocationEndOffset, MyInfo);
708 }
709 
710 bool DwarfLinkerForBinary::AddressManager::hasLiveAddressRange(
711     const DWARFDie &DIE, CompileUnit::DIEInfo &MyInfo) {
712   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
713 
714   Optional<uint32_t> LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
715   if (!LowPcIdx)
716     return false;
717 
718   dwarf::Form Form = Abbrev->getFormByIndex(*LowPcIdx);
719 
720   if (Form == dwarf::DW_FORM_addr) {
721     uint64_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
722     uint64_t LowPcOffset, LowPcEndOffset;
723     std::tie(LowPcOffset, LowPcEndOffset) =
724         getAttributeOffsets(Abbrev, *LowPcIdx, Offset, *DIE.getDwarfUnit());
725     return hasValidRelocationAt(ValidDebugInfoRelocs, LowPcOffset,
726                                 LowPcEndOffset, MyInfo);
727   }
728 
729   if (Form == dwarf::DW_FORM_addrx) {
730     Optional<DWARFFormValue> AddrValue = DIE.find(dwarf::DW_AT_low_pc);
731     if (Optional<uint64_t> AddrOffsetSectionBase =
732             DIE.getDwarfUnit()->getAddrOffsetSectionBase()) {
733       uint64_t StartOffset = *AddrOffsetSectionBase + AddrValue->getRawUValue();
734       uint64_t EndOffset =
735           StartOffset + DIE.getDwarfUnit()->getAddressByteSize();
736       return hasValidRelocationAt(ValidDebugAddrRelocs, StartOffset, EndOffset,
737                                   MyInfo);
738     } else
739       Linker.reportWarning("no base offset for address table", SrcFileName);
740   }
741 
742   return false;
743 }
744 
745 uint64_t
746 DwarfLinkerForBinary::AddressManager::relocate(const ValidReloc &Reloc) const {
747   return Reloc.Mapping->getValue().BinaryAddress + Reloc.Addend;
748 }
749 
750 /// Apply the valid relocations found by findValidRelocs() to
751 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
752 /// in the debug_info section.
753 ///
754 /// Like for findValidRelocs(), this function must be called with
755 /// monotonic \p BaseOffset values.
756 ///
757 /// \returns whether any reloc has been applied.
758 bool DwarfLinkerForBinary::AddressManager::applyValidRelocs(
759     MutableArrayRef<char> Data, uint64_t BaseOffset, bool IsLittleEndian) {
760   assert(areRelocationsResolved());
761   std::vector<ValidReloc> Relocs = getRelocations(
762       ValidDebugInfoRelocs, BaseOffset, BaseOffset + Data.size());
763 
764   for (const ValidReloc &CurReloc : Relocs) {
765     assert(CurReloc.Offset - BaseOffset < Data.size());
766     assert(CurReloc.Offset - BaseOffset + CurReloc.Size <= Data.size());
767     char Buf[8];
768     uint64_t Value = relocate(CurReloc);
769     for (unsigned I = 0; I != CurReloc.Size; ++I) {
770       unsigned Index = IsLittleEndian ? I : (CurReloc.Size - I - 1);
771       Buf[I] = uint8_t(Value >> (Index * 8));
772     }
773     assert(CurReloc.Size <= sizeof(Buf));
774     memcpy(&Data[CurReloc.Offset - BaseOffset], Buf, CurReloc.Size);
775   }
776 
777   return Relocs.size() > 0;
778 }
779 
780 llvm::Expected<uint64_t>
781 DwarfLinkerForBinary::AddressManager::relocateIndexedAddr(uint64_t StartOffset,
782                                                           uint64_t EndOffset) {
783   std::vector<ValidReloc> Relocs =
784       getRelocations(ValidDebugAddrRelocs, StartOffset, EndOffset);
785   if (Relocs.size() == 0)
786     return createStringError(
787         std::make_error_code(std::errc::invalid_argument),
788         "no relocation for offset %llu in debug_addr section", StartOffset);
789 
790   return relocate(Relocs[0]);
791 }
792 
793 bool linkDwarf(raw_fd_ostream &OutFile, BinaryHolder &BinHolder,
794                const DebugMap &DM, LinkOptions Options) {
795   DwarfLinkerForBinary Linker(OutFile, BinHolder, std::move(Options));
796   return Linker.link(DM);
797 }
798 
799 } // namespace dsymutil
800 } // namespace llvm
801