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/BinaryFormat/Swift.h"
34 #include "llvm/CodeGen/AccelTable.h"
35 #include "llvm/CodeGen/AsmPrinter.h"
36 #include "llvm/CodeGen/DIE.h"
37 #include "llvm/CodeGen/NonRelocatableStringpool.h"
38 #include "llvm/Config/config.h"
39 #include "llvm/DWARFLinker/DWARFLinkerDeclContext.h"
40 #include "llvm/DebugInfo/DIContext.h"
41 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
42 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
43 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
44 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
45 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
46 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
47 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
48 #include "llvm/DebugInfo/DWARF/DWARFSection.h"
49 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
50 #include "llvm/MC/MCAsmBackend.h"
51 #include "llvm/MC/MCAsmInfo.h"
52 #include "llvm/MC/MCCodeEmitter.h"
53 #include "llvm/MC/MCContext.h"
54 #include "llvm/MC/MCDwarf.h"
55 #include "llvm/MC/MCInstrInfo.h"
56 #include "llvm/MC/MCObjectFileInfo.h"
57 #include "llvm/MC/MCObjectWriter.h"
58 #include "llvm/MC/MCRegisterInfo.h"
59 #include "llvm/MC/MCSection.h"
60 #include "llvm/MC/MCStreamer.h"
61 #include "llvm/MC/MCSubtargetInfo.h"
62 #include "llvm/MC/MCTargetOptions.h"
63 #include "llvm/MC/MCTargetOptionsCommandFlags.h"
64 #include "llvm/MC/TargetRegistry.h"
65 #include "llvm/Object/MachO.h"
66 #include "llvm/Object/ObjectFile.h"
67 #include "llvm/Object/SymbolicFile.h"
68 #include "llvm/Support/Allocator.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/Compiler.h"
71 #include "llvm/Support/DJB.h"
72 #include "llvm/Support/DataExtractor.h"
73 #include "llvm/Support/Error.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/ErrorOr.h"
76 #include "llvm/Support/FileSystem.h"
77 #include "llvm/Support/Format.h"
78 #include "llvm/Support/LEB128.h"
79 #include "llvm/Support/MathExtras.h"
80 #include "llvm/Support/MemoryBuffer.h"
81 #include "llvm/Support/Path.h"
82 #include "llvm/Support/ThreadPool.h"
83 #include "llvm/Support/ToolOutputFile.h"
84 #include "llvm/Support/WithColor.h"
85 #include "llvm/Support/raw_ostream.h"
86 #include "llvm/Target/TargetMachine.h"
87 #include "llvm/Target/TargetOptions.h"
88 #include <algorithm>
89 #include <cassert>
90 #include <cinttypes>
91 #include <climits>
92 #include <cstdint>
93 #include <cstdlib>
94 #include <cstring>
95 #include <limits>
96 #include <map>
97 #include <memory>
98 #include <string>
99 #include <system_error>
100 #include <tuple>
101 #include <utility>
102 #include <vector>
103 
104 namespace llvm {
105 
106 static mc::RegisterMCTargetOptionsFlags MOF;
107 
108 namespace dsymutil {
109 
110 static Error copySwiftInterfaces(
111     const std::map<std::string, std::string> &ParseableSwiftInterfaces,
112     StringRef Architecture, const LinkOptions &Options) {
113   std::error_code EC;
114   SmallString<128> InputPath;
115   SmallString<128> Path;
116   sys::path::append(Path, *Options.ResourceDir, "Swift", Architecture);
117   if ((EC = sys::fs::create_directories(Path.str(), true,
118                                         sys::fs::perms::all_all)))
119     return make_error<StringError>(
120         "cannot create directory: " + toString(errorCodeToError(EC)), EC);
121   unsigned BaseLength = Path.size();
122 
123   for (auto &I : ParseableSwiftInterfaces) {
124     StringRef ModuleName = I.first;
125     StringRef InterfaceFile = I.second;
126     if (!Options.PrependPath.empty()) {
127       InputPath.clear();
128       sys::path::append(InputPath, Options.PrependPath, InterfaceFile);
129       InterfaceFile = InputPath;
130     }
131     sys::path::append(Path, ModuleName);
132     Path.append(".swiftinterface");
133     if (Options.Verbose)
134       outs() << "copy parseable Swift interface " << InterfaceFile << " -> "
135              << Path.str() << '\n';
136 
137     // copy_file attempts an APFS clone first, so this should be cheap.
138     if ((EC = sys::fs::copy_file(InterfaceFile, Path.str())))
139       warn(Twine("cannot copy parseable Swift interface ") + InterfaceFile +
140            ": " + toString(errorCodeToError(EC)));
141     Path.resize(BaseLength);
142   }
143   return Error::success();
144 }
145 
146 /// Report a warning to the user, optionally including information about a
147 /// specific \p DIE related to the warning.
148 void DwarfLinkerForBinary::reportWarning(const Twine &Warning,
149                                          StringRef Context,
150                                          const DWARFDie *DIE) const {
151 
152   warn(Warning, Context);
153 
154   if (!Options.Verbose || !DIE)
155     return;
156 
157   DIDumpOptions DumpOpts;
158   DumpOpts.ChildRecurseDepth = 0;
159   DumpOpts.Verbose = Options.Verbose;
160 
161   WithColor::note() << "    in DIE:\n";
162   DIE->dump(errs(), 6 /* Indent */, DumpOpts);
163 }
164 
165 bool DwarfLinkerForBinary::createStreamer(const Triple &TheTriple,
166                                           raw_fd_ostream &OutFile) {
167   if (Options.NoOutput)
168     return true;
169 
170   Streamer = std::make_unique<DwarfStreamer>(
171       Options.FileType, OutFile, Options.Translator,
172       [&](const Twine &Error, StringRef Context, const DWARFDie *) {
173         error(Error, Context);
174       },
175       [&](const Twine &Warning, StringRef Context, const DWARFDie *) {
176         warn(Warning, Context);
177       });
178   return Streamer->init(TheTriple, "__DWARF");
179 }
180 
181 ErrorOr<const object::ObjectFile &>
182 DwarfLinkerForBinary::loadObject(const DebugMapObject &Obj,
183                                  const Triple &Triple) {
184   auto ObjectEntry =
185       BinHolder.getObjectEntry(Obj.getObjectFilename(), Obj.getTimestamp());
186   if (!ObjectEntry) {
187     auto Err = ObjectEntry.takeError();
188     reportWarning(Twine(Obj.getObjectFilename()) + ": " +
189                       toString(std::move(Err)),
190                   Obj.getObjectFilename());
191     return errorToErrorCode(std::move(Err));
192   }
193 
194   auto Object = ObjectEntry->getObject(Triple);
195   if (!Object) {
196     auto Err = Object.takeError();
197     reportWarning(Twine(Obj.getObjectFilename()) + ": " +
198                       toString(std::move(Err)),
199                   Obj.getObjectFilename());
200     return errorToErrorCode(std::move(Err));
201   }
202 
203   return *Object;
204 }
205 
206 static Error remarksErrorHandler(const DebugMapObject &DMO,
207                                  DwarfLinkerForBinary &Linker,
208                                  std::unique_ptr<FileError> FE) {
209   bool IsArchive = DMO.getObjectFilename().endswith(")");
210   // Don't report errors for missing remark files from static
211   // archives.
212   if (!IsArchive)
213     return Error(std::move(FE));
214 
215   std::string Message = FE->message();
216   Error E = FE->takeError();
217   Error NewE = handleErrors(std::move(E), [&](std::unique_ptr<ECError> EC) {
218     if (EC->convertToErrorCode() != std::errc::no_such_file_or_directory)
219       return Error(std::move(EC));
220 
221     Linker.reportWarning(Message, DMO.getObjectFilename());
222     return Error(Error::success());
223   });
224 
225   if (!NewE)
226     return Error::success();
227 
228   return createFileError(FE->getFileName(), std::move(NewE));
229 }
230 
231 static Error emitRemarks(const LinkOptions &Options, StringRef BinaryPath,
232                          StringRef ArchName, const remarks::RemarkLinker &RL) {
233   // Make sure we don't create the directories and the file if there is nothing
234   // to serialize.
235   if (RL.empty())
236     return Error::success();
237 
238   SmallString<128> InputPath;
239   SmallString<128> Path;
240   // Create the "Remarks" directory in the "Resources" directory.
241   sys::path::append(Path, *Options.ResourceDir, "Remarks");
242   if (std::error_code EC = sys::fs::create_directories(Path.str(), true,
243                                                        sys::fs::perms::all_all))
244     return errorCodeToError(EC);
245 
246   // Append the file name.
247   // For fat binaries, also append a dash and the architecture name.
248   sys::path::append(Path, sys::path::filename(BinaryPath));
249   if (Options.NumDebugMaps > 1) {
250     // More than one debug map means we have a fat binary.
251     Path += '-';
252     Path += ArchName;
253   }
254 
255   std::error_code EC;
256   raw_fd_ostream OS(Options.NoOutput ? "-" : Path.str(), EC,
257                     Options.RemarksFormat == remarks::Format::Bitstream
258                         ? sys::fs::OF_None
259                         : sys::fs::OF_Text);
260   if (EC)
261     return errorCodeToError(EC);
262 
263   if (Error E = RL.serialize(OS, Options.RemarksFormat))
264     return E;
265 
266   return Error::success();
267 }
268 
269 ErrorOr<DWARFFile &>
270 DwarfLinkerForBinary::loadObject(const DebugMapObject &Obj,
271                                  const DebugMap &DebugMap,
272                                  remarks::RemarkLinker &RL) {
273   auto ErrorOrObj = loadObject(Obj, DebugMap.getTriple());
274 
275   if (ErrorOrObj) {
276     ContextForLinking.push_back(
277         std::unique_ptr<DWARFContext>(DWARFContext::create(*ErrorOrObj)));
278     AddressMapForLinking.push_back(
279         std::make_unique<AddressManager>(*this, *ErrorOrObj, Obj));
280 
281     ObjectsForLinking.push_back(std::make_unique<DWARFFile>(
282         Obj.getObjectFilename(), ContextForLinking.back().get(),
283         AddressMapForLinking.back().get(),
284         Obj.empty() ? Obj.getWarnings() : EmptyWarnings));
285 
286     Error E = RL.link(*ErrorOrObj);
287     if (Error NewE = handleErrors(
288             std::move(E), [&](std::unique_ptr<FileError> EC) -> Error {
289               return remarksErrorHandler(Obj, *this, std::move(EC));
290             }))
291       return errorToErrorCode(std::move(NewE));
292 
293     return *ObjectsForLinking.back();
294   }
295 
296   return ErrorOrObj.getError();
297 }
298 
299 static bool binaryHasSwiftReflectionSections(const DebugMap &Map,
300                                              const LinkOptions &Options,
301                                              BinaryHolder &BinHolder) {
302   // If the input binary has swift5 reflection sections, there is no need to
303   // copy them to the .dSYM. Only copy them for binaries where the linker
304   // omitted the reflection metadata.
305   if (!Map.getBinaryPath().empty() &&
306       Options.FileType == OutputFileType::Object) {
307 
308     auto ObjectEntry = BinHolder.getObjectEntry(Map.getBinaryPath());
309     // If ObjectEntry or Object has an error, no binary exists, therefore no
310     // reflection sections exist.
311     if (!ObjectEntry) {
312       // Any errors will be diagnosed later in the main loop, ignore them here.
313       llvm::consumeError(ObjectEntry.takeError());
314       return false;
315     }
316 
317     auto Object =
318         ObjectEntry->getObjectAs<object::MachOObjectFile>(Map.getTriple());
319     if (!Object) {
320       // Any errors will be diagnosed later in the main loop, ignore them here.
321       llvm::consumeError(Object.takeError());
322       return false;
323     }
324 
325     for (auto &Section : Object->sections()) {
326       llvm::Expected<llvm::StringRef> NameOrErr =
327           Object->getSectionName(Section.getRawDataRefImpl());
328       if (!NameOrErr) {
329         llvm::consumeError(NameOrErr.takeError());
330         continue;
331       }
332       NameOrErr->consume_back("__TEXT");
333       if (Object->mapReflectionSectionNameToEnumValue(*NameOrErr) !=
334           llvm::swift::Swift5ReflectionSectionKind::unknown) {
335         return true;
336       }
337     }
338   }
339   return false;
340 }
341 
342 static void
343 copySwiftReflectionMetadata(const llvm::dsymutil::DebugMapObject *Obj,
344                             DwarfStreamer *Streamer) {
345   auto OF =
346       llvm::object::ObjectFile::createObjectFile(Obj->getObjectFilename());
347   if (!OF) {
348     llvm::consumeError(OF.takeError());
349     return;
350   } else if (auto *MO =
351                  dyn_cast<llvm::object::MachOObjectFile>(OF->getBinary())) {
352     for (auto &Section : OF->getBinary()->sections()) {
353       llvm::Expected<llvm::StringRef> NameOrErr =
354           MO->getSectionName(Section.getRawDataRefImpl());
355       if (!NameOrErr) {
356         llvm::consumeError(NameOrErr.takeError());
357         continue;
358       }
359       llvm::Expected<llvm::StringRef> SectionContents = Section.getContents();
360       if (SectionContents) {
361         NameOrErr->consume_back("__TEXT");
362         Streamer->emitSwiftReflectionSection(
363             MO->mapReflectionSectionNameToEnumValue(*NameOrErr),
364             *SectionContents, Section.getAlignment(), Section.getSize());
365       }
366     }
367   }
368 }
369 
370 bool DwarfLinkerForBinary::link(const DebugMap &Map) {
371   if (!createStreamer(Map.getTriple(), OutFile))
372     return false;
373 
374   ObjectsForLinking.clear();
375   ContextForLinking.clear();
376   AddressMapForLinking.clear();
377 
378   DebugMap DebugMap(Map.getTriple(), Map.getBinaryPath());
379 
380   DWARFLinker GeneralLinker(Streamer.get(), DwarfLinkerClient::Dsymutil);
381 
382   remarks::RemarkLinker RL;
383   if (!Options.RemarksPrependPath.empty())
384     RL.setExternalFilePrependPath(Options.RemarksPrependPath);
385   GeneralLinker.setObjectPrefixMap(&Options.ObjectPrefixMap);
386 
387   std::function<StringRef(StringRef)> TranslationLambda = [&](StringRef Input) {
388     assert(Options.Translator);
389     return Options.Translator(Input);
390   };
391 
392   GeneralLinker.setVerbosity(Options.Verbose);
393   GeneralLinker.setStatistics(Options.Statistics);
394   GeneralLinker.setNoOutput(Options.NoOutput);
395   GeneralLinker.setNoODR(Options.NoODR);
396   GeneralLinker.setUpdate(Options.Update);
397   GeneralLinker.setNumThreads(Options.Threads);
398   GeneralLinker.setAccelTableKind(Options.TheAccelTableKind);
399   GeneralLinker.setPrependPath(Options.PrependPath);
400   GeneralLinker.setKeepFunctionForStatic(Options.KeepFunctionForStatic);
401   if (Options.Translator)
402     GeneralLinker.setStringsTranslator(TranslationLambda);
403   GeneralLinker.setWarningHandler(
404       [&](const Twine &Warning, StringRef Context, const DWARFDie *DIE) {
405         reportWarning(Warning, Context, DIE);
406       });
407   GeneralLinker.setErrorHandler(
408       [&](const Twine &Error, StringRef Context, const DWARFDie *) {
409         error(Error, Context);
410       });
411   GeneralLinker.setObjFileLoader(
412       [&DebugMap, &RL, this](StringRef ContainerName,
413                              StringRef Path) -> ErrorOr<DWARFFile &> {
414         auto &Obj = DebugMap.addDebugMapObject(
415             Path, sys::TimePoint<std::chrono::seconds>(), MachO::N_OSO);
416 
417         if (auto ErrorOrObj = loadObject(Obj, DebugMap, RL)) {
418           return *ErrorOrObj;
419         } else {
420           // Try and emit more helpful warnings by applying some heuristics.
421           StringRef ObjFile = ContainerName;
422           bool IsClangModule = sys::path::extension(Path).equals(".pcm");
423           bool IsArchive = ObjFile.endswith(")");
424 
425           if (IsClangModule) {
426             StringRef ModuleCacheDir = sys::path::parent_path(Path);
427             if (sys::fs::exists(ModuleCacheDir)) {
428               // If the module's parent directory exists, we assume that the
429               // module cache has expired and was pruned by clang.  A more
430               // adventurous dsymutil would invoke clang to rebuild the module
431               // now.
432               if (!ModuleCacheHintDisplayed) {
433                 WithColor::note()
434                     << "The clang module cache may have expired since "
435                        "this object file was built. Rebuilding the "
436                        "object file will rebuild the module cache.\n";
437                 ModuleCacheHintDisplayed = true;
438               }
439             } else if (IsArchive) {
440               // If the module cache directory doesn't exist at all and the
441               // object file is inside a static library, we assume that the
442               // static library was built on a different machine. We don't want
443               // to discourage module debugging for convenience libraries within
444               // a project though.
445               if (!ArchiveHintDisplayed) {
446                 WithColor::note()
447                     << "Linking a static library that was built with "
448                        "-gmodules, but the module cache was not found.  "
449                        "Redistributable static libraries should never be "
450                        "built with module debugging enabled.  The debug "
451                        "experience will be degraded due to incomplete "
452                        "debug information.\n";
453                 ArchiveHintDisplayed = true;
454               }
455             }
456           }
457 
458           return ErrorOrObj.getError();
459         }
460 
461         llvm_unreachable("Unhandled DebugMap object");
462       });
463   GeneralLinker.setSwiftInterfacesMap(&ParseableSwiftInterfaces);
464   bool ReflectionSectionsPresentInBinary = false;
465   // If there is no output specified, no point in checking the binary for swift5
466   // reflection sections.
467   if (!Options.NoOutput) {
468     ReflectionSectionsPresentInBinary =
469         binaryHasSwiftReflectionSections(Map, Options, BinHolder);
470   }
471 
472   for (const auto &Obj : Map.objects()) {
473     // If there is no output specified or the reflection sections are present in
474     // the Input binary, there is no need to copy the Swift Reflection Metadata
475     if (!Options.NoOutput && !ReflectionSectionsPresentInBinary)
476       copySwiftReflectionMetadata(Obj.get(), Streamer.get());
477 
478     // N_AST objects (swiftmodule files) should get dumped directly into the
479     // appropriate DWARF section.
480     if (Obj->getType() == MachO::N_AST) {
481       if (Options.Verbose)
482         outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
483 
484       StringRef File = Obj->getObjectFilename();
485       auto ErrorOrMem = MemoryBuffer::getFile(File);
486       if (!ErrorOrMem) {
487         warn("Could not open '" + File + "'\n");
488         continue;
489       }
490       sys::fs::file_status Stat;
491       if (auto Err = sys::fs::status(File, Stat)) {
492         warn(Err.message());
493         continue;
494       }
495       if (!Options.NoTimestamp) {
496         // The modification can have sub-second precision so we need to cast
497         // away the extra precision that's not present in the debug map.
498         auto ModificationTime =
499             std::chrono::time_point_cast<std::chrono::seconds>(
500                 Stat.getLastModificationTime());
501         if (Obj->getTimestamp() != sys::TimePoint<>() &&
502             ModificationTime != Obj->getTimestamp()) {
503           // Not using the helper here as we can easily stream TimePoint<>.
504           WithColor::warning()
505               << File << ": timestamp mismatch between swift interface file ("
506               << sys::TimePoint<>(ModificationTime) << ") and debug map ("
507               << sys::TimePoint<>(Obj->getTimestamp()) << ")\n";
508           continue;
509         }
510       }
511 
512       // Copy the module into the .swift_ast section.
513       if (!Options.NoOutput)
514         Streamer->emitSwiftAST((*ErrorOrMem)->getBuffer());
515 
516       continue;
517     }
518     if (auto ErrorOrObj = loadObject(*Obj, Map, RL))
519       GeneralLinker.addObjectFile(*ErrorOrObj);
520     else {
521       ObjectsForLinking.push_back(std::make_unique<DWARFFile>(
522           Obj->getObjectFilename(), nullptr, nullptr,
523           Obj->empty() ? Obj->getWarnings() : EmptyWarnings));
524       GeneralLinker.addObjectFile(*ObjectsForLinking.back());
525     }
526   }
527 
528   // link debug info for loaded object files.
529   GeneralLinker.link();
530 
531   StringRef ArchName = Map.getTriple().getArchName();
532   if (Error E = emitRemarks(Options, Map.getBinaryPath(), ArchName, RL))
533     return error(toString(std::move(E)));
534 
535   if (Options.NoOutput)
536     return true;
537 
538   if (Options.ResourceDir && !ParseableSwiftInterfaces.empty()) {
539     StringRef ArchName = Triple::getArchTypeName(Map.getTriple().getArch());
540     if (auto E =
541             copySwiftInterfaces(ParseableSwiftInterfaces, ArchName, Options))
542       return error(toString(std::move(E)));
543   }
544 
545   if (Map.getTriple().isOSDarwin() && !Map.getBinaryPath().empty() &&
546       Options.FileType == OutputFileType::Object)
547     return MachOUtils::generateDsymCompanion(
548         Options.VFS, Map, Options.Translator,
549         *Streamer->getAsmPrinter().OutStreamer, OutFile);
550 
551   Streamer->finish();
552   return true;
553 }
554 
555 static bool isMachOPairedReloc(uint64_t RelocType, uint64_t Arch) {
556   switch (Arch) {
557   case Triple::x86:
558     return RelocType == MachO::GENERIC_RELOC_SECTDIFF ||
559            RelocType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF;
560   case Triple::x86_64:
561     return RelocType == MachO::X86_64_RELOC_SUBTRACTOR;
562   case Triple::arm:
563   case Triple::thumb:
564     return RelocType == MachO::ARM_RELOC_SECTDIFF ||
565            RelocType == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
566            RelocType == MachO::ARM_RELOC_HALF ||
567            RelocType == MachO::ARM_RELOC_HALF_SECTDIFF;
568   case Triple::aarch64:
569     return RelocType == MachO::ARM64_RELOC_SUBTRACTOR;
570   default:
571     return false;
572   }
573 }
574 
575 /// Iterate over the relocations of the given \p Section and
576 /// store the ones that correspond to debug map entries into the
577 /// ValidRelocs array.
578 void DwarfLinkerForBinary::AddressManager::findValidRelocsMachO(
579     const object::SectionRef &Section, const object::MachOObjectFile &Obj,
580     const DebugMapObject &DMO, std::vector<ValidReloc> &ValidRelocs) {
581   Expected<StringRef> ContentsOrErr = Section.getContents();
582   if (!ContentsOrErr) {
583     consumeError(ContentsOrErr.takeError());
584     Linker.reportWarning("error reading section", DMO.getObjectFilename());
585     return;
586   }
587   DataExtractor Data(*ContentsOrErr, Obj.isLittleEndian(), 0);
588   bool SkipNext = false;
589 
590   for (const object::RelocationRef &Reloc : Section.relocations()) {
591     if (SkipNext) {
592       SkipNext = false;
593       continue;
594     }
595 
596     object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
597     MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
598 
599     if (isMachOPairedReloc(Obj.getAnyRelocationType(MachOReloc),
600                            Obj.getArch())) {
601       SkipNext = true;
602       Linker.reportWarning("unsupported relocation in " + *Section.getName() +
603                                " section.",
604                            DMO.getObjectFilename());
605       continue;
606     }
607 
608     unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
609     uint64_t Offset64 = Reloc.getOffset();
610     if ((RelocSize != 4 && RelocSize != 8)) {
611       Linker.reportWarning("unsupported relocation in " + *Section.getName() +
612                                " section.",
613                            DMO.getObjectFilename());
614       continue;
615     }
616     uint64_t OffsetCopy = Offset64;
617     // Mach-o uses REL relocations, the addend is at the relocation offset.
618     uint64_t Addend = Data.getUnsigned(&OffsetCopy, RelocSize);
619     uint64_t SymAddress;
620     int64_t SymOffset;
621 
622     if (Obj.isRelocationScattered(MachOReloc)) {
623       // The address of the base symbol for scattered relocations is
624       // stored in the reloc itself. The actual addend will store the
625       // base address plus the offset.
626       SymAddress = Obj.getScatteredRelocationValue(MachOReloc);
627       SymOffset = int64_t(Addend) - SymAddress;
628     } else {
629       SymAddress = Addend;
630       SymOffset = 0;
631     }
632 
633     auto Sym = Reloc.getSymbol();
634     if (Sym != Obj.symbol_end()) {
635       Expected<StringRef> SymbolName = Sym->getName();
636       if (!SymbolName) {
637         consumeError(SymbolName.takeError());
638         Linker.reportWarning("error getting relocation symbol name.",
639                              DMO.getObjectFilename());
640         continue;
641       }
642       if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
643         ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
644     } else if (const auto *Mapping = DMO.lookupObjectAddress(SymAddress)) {
645       // Do not store the addend. The addend was the address of the symbol in
646       // the object file, the address in the binary that is stored in the debug
647       // map doesn't need to be offset.
648       ValidRelocs.emplace_back(Offset64, RelocSize, SymOffset, Mapping);
649     }
650   }
651 }
652 
653 /// Dispatch the valid relocation finding logic to the
654 /// appropriate handler depending on the object file format.
655 bool DwarfLinkerForBinary::AddressManager::findValidRelocs(
656     const object::SectionRef &Section, const object::ObjectFile &Obj,
657     const DebugMapObject &DMO, std::vector<ValidReloc> &Relocs) {
658   // Dispatch to the right handler depending on the file type.
659   if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
660     findValidRelocsMachO(Section, *MachOObj, DMO, Relocs);
661   else
662     Linker.reportWarning(Twine("unsupported object file type: ") +
663                              Obj.getFileName(),
664                          DMO.getObjectFilename());
665   if (Relocs.empty())
666     return false;
667 
668   // Sort the relocations by offset. We will walk the DIEs linearly in
669   // the file, this allows us to just keep an index in the relocation
670   // array that we advance during our walk, rather than resorting to
671   // some associative container. See DwarfLinkerForBinary::NextValidReloc.
672   llvm::sort(Relocs);
673   return true;
674 }
675 
676 /// Look for relocations in the debug_info and debug_addr section that match
677 /// entries in the debug map. These relocations will drive the Dwarf link by
678 /// indicating which DIEs refer to symbols present in the linked binary.
679 /// \returns whether there are any valid relocations in the debug info.
680 bool DwarfLinkerForBinary::AddressManager::findValidRelocsInDebugSections(
681     const object::ObjectFile &Obj, const DebugMapObject &DMO) {
682   // Find the debug_info section.
683   bool FoundValidRelocs = false;
684   for (const object::SectionRef &Section : Obj.sections()) {
685     StringRef SectionName;
686     if (Expected<StringRef> NameOrErr = Section.getName())
687       SectionName = *NameOrErr;
688     else
689       consumeError(NameOrErr.takeError());
690 
691     SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
692     if (SectionName == "debug_info")
693       FoundValidRelocs |=
694           findValidRelocs(Section, Obj, DMO, ValidDebugInfoRelocs);
695     if (SectionName == "debug_addr")
696       FoundValidRelocs |=
697           findValidRelocs(Section, Obj, DMO, ValidDebugAddrRelocs);
698   }
699   return FoundValidRelocs;
700 }
701 
702 std::vector<DwarfLinkerForBinary::AddressManager::ValidReloc>
703 DwarfLinkerForBinary::AddressManager::getRelocations(
704     const std::vector<ValidReloc> &Relocs, uint64_t StartPos, uint64_t EndPos) {
705   std::vector<DwarfLinkerForBinary::AddressManager::ValidReloc> Res;
706 
707   auto CurReloc = partition_point(Relocs, [StartPos](const ValidReloc &Reloc) {
708     return Reloc.Offset < StartPos;
709   });
710 
711   while (CurReloc != Relocs.end() && CurReloc->Offset >= StartPos &&
712          CurReloc->Offset < EndPos) {
713     Res.push_back(*CurReloc);
714     CurReloc++;
715   }
716 
717   return Res;
718 }
719 
720 void DwarfLinkerForBinary::AddressManager::printReloc(const ValidReloc &Reloc) {
721   const auto &Mapping = Reloc.Mapping->getValue();
722   const uint64_t ObjectAddress = Mapping.ObjectAddress
723                                      ? uint64_t(*Mapping.ObjectAddress)
724                                      : std::numeric_limits<uint64_t>::max();
725 
726   outs() << "Found valid debug map entry: " << Reloc.Mapping->getKey() << "\t"
727          << format("0x%016" PRIx64 " => 0x%016" PRIx64 "\n", ObjectAddress,
728                    uint64_t(Mapping.BinaryAddress));
729 }
730 
731 void DwarfLinkerForBinary::AddressManager::fillDieInfo(
732     const ValidReloc &Reloc, CompileUnit::DIEInfo &Info) {
733   Info.AddrAdjust = relocate(Reloc);
734   if (Reloc.Mapping->getValue().ObjectAddress)
735     Info.AddrAdjust -= uint64_t(*Reloc.Mapping->getValue().ObjectAddress);
736   Info.InDebugMap = true;
737 }
738 
739 bool DwarfLinkerForBinary::AddressManager::hasValidRelocationAt(
740     const std::vector<ValidReloc> &AllRelocs, uint64_t StartOffset,
741     uint64_t EndOffset, CompileUnit::DIEInfo &Info) {
742   std::vector<ValidReloc> Relocs =
743       getRelocations(AllRelocs, StartOffset, EndOffset);
744 
745   if (Relocs.size() == 0)
746     return false;
747 
748   if (Linker.Options.Verbose)
749     printReloc(Relocs[0]);
750   fillDieInfo(Relocs[0], Info);
751 
752   return true;
753 }
754 
755 /// Get the starting and ending (exclusive) offset for the
756 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
757 /// supposed to point to the position of the first attribute described
758 /// by \p Abbrev.
759 /// \return [StartOffset, EndOffset) as a pair.
760 static std::pair<uint64_t, uint64_t>
761 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
762                     uint64_t Offset, const DWARFUnit &Unit) {
763   DataExtractor Data = Unit.getDebugInfoExtractor();
764 
765   for (unsigned I = 0; I < Idx; ++I)
766     DWARFFormValue::skipValue(Abbrev->getFormByIndex(I), Data, &Offset,
767                               Unit.getFormParams());
768 
769   uint64_t End = Offset;
770   DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End,
771                             Unit.getFormParams());
772 
773   return std::make_pair(Offset, End);
774 }
775 
776 bool DwarfLinkerForBinary::AddressManager::hasLiveMemoryLocation(
777     const DWARFDie &DIE, CompileUnit::DIEInfo &MyInfo) {
778   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
779 
780   Optional<uint32_t> LocationIdx =
781       Abbrev->findAttributeIndex(dwarf::DW_AT_location);
782   if (!LocationIdx)
783     return false;
784 
785   uint64_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
786   uint64_t LocationOffset, LocationEndOffset;
787   std::tie(LocationOffset, LocationEndOffset) =
788       getAttributeOffsets(Abbrev, *LocationIdx, Offset, *DIE.getDwarfUnit());
789 
790   // FIXME: Support relocations debug_addr.
791   return hasValidRelocationAt(ValidDebugInfoRelocs, LocationOffset,
792                               LocationEndOffset, MyInfo);
793 }
794 
795 bool DwarfLinkerForBinary::AddressManager::hasLiveAddressRange(
796     const DWARFDie &DIE, CompileUnit::DIEInfo &MyInfo) {
797   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
798 
799   Optional<uint32_t> LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
800   if (!LowPcIdx)
801     return false;
802 
803   dwarf::Form Form = Abbrev->getFormByIndex(*LowPcIdx);
804 
805   if (Form == dwarf::DW_FORM_addr) {
806     uint64_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
807     uint64_t LowPcOffset, LowPcEndOffset;
808     std::tie(LowPcOffset, LowPcEndOffset) =
809         getAttributeOffsets(Abbrev, *LowPcIdx, Offset, *DIE.getDwarfUnit());
810     return hasValidRelocationAt(ValidDebugInfoRelocs, LowPcOffset,
811                                 LowPcEndOffset, MyInfo);
812   }
813 
814   if (Form == dwarf::DW_FORM_addrx) {
815     Optional<DWARFFormValue> AddrValue = DIE.find(dwarf::DW_AT_low_pc);
816     if (Optional<uint64_t> AddrOffsetSectionBase =
817             DIE.getDwarfUnit()->getAddrOffsetSectionBase()) {
818       uint64_t StartOffset = *AddrOffsetSectionBase + AddrValue->getRawUValue();
819       uint64_t EndOffset =
820           StartOffset + DIE.getDwarfUnit()->getAddressByteSize();
821       return hasValidRelocationAt(ValidDebugAddrRelocs, StartOffset, EndOffset,
822                                   MyInfo);
823     } else
824       Linker.reportWarning("no base offset for address table", SrcFileName);
825   }
826 
827   return false;
828 }
829 
830 uint64_t
831 DwarfLinkerForBinary::AddressManager::relocate(const ValidReloc &Reloc) const {
832   return Reloc.Mapping->getValue().BinaryAddress + Reloc.Addend;
833 }
834 
835 /// Apply the valid relocations found by findValidRelocs() to
836 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
837 /// in the debug_info section.
838 ///
839 /// Like for findValidRelocs(), this function must be called with
840 /// monotonic \p BaseOffset values.
841 ///
842 /// \returns whether any reloc has been applied.
843 bool DwarfLinkerForBinary::AddressManager::applyValidRelocs(
844     MutableArrayRef<char> Data, uint64_t BaseOffset, bool IsLittleEndian) {
845   assert(areRelocationsResolved());
846   std::vector<ValidReloc> Relocs = getRelocations(
847       ValidDebugInfoRelocs, BaseOffset, BaseOffset + Data.size());
848 
849   for (const ValidReloc &CurReloc : Relocs) {
850     assert(CurReloc.Offset - BaseOffset < Data.size());
851     assert(CurReloc.Offset - BaseOffset + CurReloc.Size <= Data.size());
852     char Buf[8];
853     uint64_t Value = relocate(CurReloc);
854     for (unsigned I = 0; I != CurReloc.Size; ++I) {
855       unsigned Index = IsLittleEndian ? I : (CurReloc.Size - I - 1);
856       Buf[I] = uint8_t(Value >> (Index * 8));
857     }
858     assert(CurReloc.Size <= sizeof(Buf));
859     memcpy(&Data[CurReloc.Offset - BaseOffset], Buf, CurReloc.Size);
860   }
861 
862   return Relocs.size() > 0;
863 }
864 
865 llvm::Expected<uint64_t>
866 DwarfLinkerForBinary::AddressManager::relocateIndexedAddr(uint64_t StartOffset,
867                                                           uint64_t EndOffset) {
868   std::vector<ValidReloc> Relocs =
869       getRelocations(ValidDebugAddrRelocs, StartOffset, EndOffset);
870   if (Relocs.size() == 0)
871     return createStringError(
872         std::make_error_code(std::errc::invalid_argument),
873         "no relocation for offset %llu in debug_addr section", StartOffset);
874 
875   return relocate(Relocs[0]);
876 }
877 
878 bool linkDwarf(raw_fd_ostream &OutFile, BinaryHolder &BinHolder,
879                const DebugMap &DM, LinkOptions Options) {
880   DwarfLinkerForBinary Linker(OutFile, BinHolder, std::move(Options));
881   return Linker.link(DM);
882 }
883 
884 } // namespace dsymutil
885 } // namespace llvm
886