DwarfLinkerForBinary.cpp 29 KB

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