DWARFLinker.h 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- DWARFLinker.h --------------------------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_DWARFLINKER_DWARFLINKER_H
  14. #define LLVM_DWARFLINKER_DWARFLINKER_H
  15. #include "llvm/ADT/AddressRanges.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/CodeGen/AccelTable.h"
  18. #include "llvm/CodeGen/NonRelocatableStringpool.h"
  19. #include "llvm/DWARFLinker/DWARFLinkerCompileUnit.h"
  20. #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
  21. #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
  22. #include "llvm/DebugInfo/DWARF/DWARFDie.h"
  23. #include <map>
  24. namespace llvm {
  25. class DWARFContext;
  26. class DWARFExpression;
  27. class DWARFUnit;
  28. class DataExtractor;
  29. class DeclContextTree;
  30. struct MCDwarfLineTableParams;
  31. template <typename T> class SmallVectorImpl;
  32. enum class DwarfLinkerClient { Dsymutil, LLD, General };
  33. /// The kind of accelerator tables we should emit.
  34. enum class DwarfLinkerAccelTableKind : uint8_t {
  35. Apple, ///< .apple_names, .apple_namespaces, .apple_types, .apple_objc.
  36. Pub, ///< .debug_pubnames, .debug_pubtypes
  37. DebugNames ///< .debug_names.
  38. };
  39. /// AddressesMap represents information about valid addresses used
  40. /// by debug information. Valid addresses are those which points to
  41. /// live code sections. i.e. relocations for these addresses point
  42. /// into sections which would be/are placed into resulting binary.
  43. class AddressesMap {
  44. public:
  45. virtual ~AddressesMap();
  46. /// Checks that there are valid relocations against a .debug_info
  47. /// section.
  48. virtual bool hasValidRelocs() = 0;
  49. /// Checks that the specified variable \p DIE references live code section.
  50. /// Allowed kind of input die: DW_TAG_variable, DW_TAG_constant.
  51. /// \returns true and sets Info.InDebugMap if it is the case.
  52. virtual bool isLiveVariable(const DWARFDie &DIE,
  53. CompileUnit::DIEInfo &Info) = 0;
  54. /// Checks that the specified subprogram \p DIE references live code section.
  55. /// Allowed kind of input die: DW_TAG_subprogram, DW_TAG_label.
  56. /// \returns true and sets Info.InDebugMap if it is the case.
  57. virtual bool isLiveSubprogram(const DWARFDie &DIE,
  58. CompileUnit::DIEInfo &Info) = 0;
  59. /// Apply the valid relocations to the buffer \p Data, taking into
  60. /// account that Data is at \p BaseOffset in the .debug_info section.
  61. ///
  62. /// \returns true whether any reloc has been applied.
  63. virtual bool applyValidRelocs(MutableArrayRef<char> Data, uint64_t BaseOffset,
  64. bool IsLittleEndian) = 0;
  65. /// Relocate the given address offset if a valid relocation exists.
  66. virtual llvm::Expected<uint64_t> relocateIndexedAddr(uint64_t StartOffset,
  67. uint64_t EndOffset) = 0;
  68. /// Returns all valid functions address ranges(i.e., those ranges
  69. /// which points to sections with code).
  70. virtual RangesTy &getValidAddressRanges() = 0;
  71. /// Erases all data.
  72. virtual void clear() = 0;
  73. };
  74. using Offset2UnitMap = DenseMap<uint64_t, CompileUnit *>;
  75. /// DwarfEmitter presents interface to generate all debug info tables.
  76. class DwarfEmitter {
  77. public:
  78. virtual ~DwarfEmitter();
  79. /// Emit DIE containing warnings.
  80. virtual void emitPaperTrailWarningsDie(DIE &Die) = 0;
  81. /// Emit section named SecName with data SecData.
  82. virtual void emitSectionContents(StringRef SecData, StringRef SecName) = 0;
  83. /// Emit the abbreviation table \p Abbrevs to the .debug_abbrev section.
  84. virtual void
  85. emitAbbrevs(const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs,
  86. unsigned DwarfVersion) = 0;
  87. /// Emit the string table described by \p Pool.
  88. virtual void emitStrings(const NonRelocatableStringpool &Pool) = 0;
  89. /// Emit DWARF debug names.
  90. virtual void
  91. emitDebugNames(AccelTable<DWARF5AccelTableStaticData> &Table) = 0;
  92. /// Emit Apple namespaces accelerator table.
  93. virtual void
  94. emitAppleNamespaces(AccelTable<AppleAccelTableStaticOffsetData> &Table) = 0;
  95. /// Emit Apple names accelerator table.
  96. virtual void
  97. emitAppleNames(AccelTable<AppleAccelTableStaticOffsetData> &Table) = 0;
  98. /// Emit Apple Objective-C accelerator table.
  99. virtual void
  100. emitAppleObjc(AccelTable<AppleAccelTableStaticOffsetData> &Table) = 0;
  101. /// Emit Apple type accelerator table.
  102. virtual void
  103. emitAppleTypes(AccelTable<AppleAccelTableStaticTypeData> &Table) = 0;
  104. /// Emit piece of .debug_ranges for \p Ranges.
  105. virtual void
  106. emitDwarfDebugRangesTableFragment(const CompileUnit &Unit,
  107. const AddressRanges &LinkedRanges) = 0;
  108. /// Emit .debug_aranges entries for \p Unit and if \p DoRangesSection is true,
  109. /// also emit the .debug_ranges entries for the DW_TAG_compile_unit's
  110. /// DW_AT_ranges attribute.
  111. virtual void emitUnitRangesEntries(CompileUnit &Unit,
  112. bool DoRangesSection) = 0;
  113. /// Copy the .debug_line over to the updated binary while unobfuscating the
  114. /// file names and directories.
  115. virtual void translateLineTable(DataExtractor LineData, uint64_t Offset) = 0;
  116. /// Emit the line table described in \p Rows into the .debug_line section.
  117. virtual void emitLineTableForUnit(MCDwarfLineTableParams Params,
  118. StringRef PrologueBytes,
  119. unsigned MinInstLength,
  120. std::vector<DWARFDebugLine::Row> &Rows,
  121. unsigned AdddressSize) = 0;
  122. /// Emit the .debug_pubnames contribution for \p Unit.
  123. virtual void emitPubNamesForUnit(const CompileUnit &Unit) = 0;
  124. /// Emit the .debug_pubtypes contribution for \p Unit.
  125. virtual void emitPubTypesForUnit(const CompileUnit &Unit) = 0;
  126. /// Emit a CIE.
  127. virtual void emitCIE(StringRef CIEBytes) = 0;
  128. /// Emit an FDE with data \p Bytes.
  129. virtual void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint64_t Address,
  130. StringRef Bytes) = 0;
  131. /// Emit the .debug_loc contribution for \p Unit by copying the entries from
  132. /// \p Dwarf and offsetting them. Update the location attributes to point to
  133. /// the new entries.
  134. virtual void emitLocationsForUnit(
  135. const CompileUnit &Unit, DWARFContext &Dwarf,
  136. std::function<void(StringRef, SmallVectorImpl<uint8_t> &)>
  137. ProcessExpr) = 0;
  138. /// Emit the compilation unit header for \p Unit in the
  139. /// .debug_info section.
  140. ///
  141. /// As a side effect, this also switches the current Dwarf version
  142. /// of the MC layer to the one of U.getOrigUnit().
  143. virtual void emitCompileUnitHeader(CompileUnit &Unit,
  144. unsigned DwarfVersion) = 0;
  145. /// Recursively emit the DIE tree rooted at \p Die.
  146. virtual void emitDIE(DIE &Die) = 0;
  147. /// Emit all available macro tables(DWARFv4 and DWARFv5).
  148. /// Use \p UnitMacroMap to get compilation unit by macro table offset.
  149. /// Side effects: Fill \p StringPool with macro strings, update
  150. /// DW_AT_macro_info, DW_AT_macros attributes for corresponding compile
  151. /// units.
  152. virtual void emitMacroTables(DWARFContext *Context,
  153. const Offset2UnitMap &UnitMacroMap,
  154. OffsetsStringPool &StringPool) = 0;
  155. /// Returns size of generated .debug_line section.
  156. virtual uint64_t getLineSectionSize() const = 0;
  157. /// Returns size of generated .debug_frame section.
  158. virtual uint64_t getFrameSectionSize() const = 0;
  159. /// Returns size of generated .debug_ranges section.
  160. virtual uint64_t getRangesSectionSize() const = 0;
  161. /// Returns size of generated .debug_info section.
  162. virtual uint64_t getDebugInfoSectionSize() const = 0;
  163. /// Returns size of generated .debug_macinfo section.
  164. virtual uint64_t getDebugMacInfoSectionSize() const = 0;
  165. /// Returns size of generated .debug_macro section.
  166. virtual uint64_t getDebugMacroSectionSize() const = 0;
  167. };
  168. using UnitListTy = std::vector<std::unique_ptr<CompileUnit>>;
  169. /// this class represents DWARF information for source file
  170. /// and it`s address map.
  171. class DWARFFile {
  172. public:
  173. DWARFFile(StringRef Name, DWARFContext *Dwarf, AddressesMap *Addresses,
  174. const std::vector<std::string> &Warnings)
  175. : FileName(Name), Dwarf(Dwarf), Addresses(Addresses), Warnings(Warnings) {
  176. }
  177. /// object file name.
  178. StringRef FileName;
  179. /// source DWARF information.
  180. DWARFContext *Dwarf = nullptr;
  181. /// helpful address information(list of valid address ranges, relocations).
  182. AddressesMap *Addresses = nullptr;
  183. /// warnings for object file.
  184. const std::vector<std::string> &Warnings;
  185. };
  186. typedef std::function<void(const Twine &Warning, StringRef Context,
  187. const DWARFDie *DIE)>
  188. messageHandler;
  189. typedef std::function<ErrorOr<DWARFFile &>(StringRef ContainerName,
  190. StringRef Path)>
  191. objFileLoader;
  192. typedef std::map<std::string, std::string> swiftInterfacesMap;
  193. typedef std::map<std::string, std::string> objectPrefixMap;
  194. typedef function_ref<void(const DWARFUnit &Unit)> CompileUnitHandler;
  195. /// The core of the Dwarf linking logic.
  196. ///
  197. /// The generation of the dwarf information from the object files will be
  198. /// driven by the selection of 'root DIEs', which are DIEs that
  199. /// describe variables or functions that resolves to the corresponding
  200. /// code section(and thus have entries in the Addresses map). All the debug
  201. /// information that will be generated(the DIEs, but also the line
  202. /// tables, ranges, ...) is derived from that set of root DIEs.
  203. ///
  204. /// The root DIEs are identified because they contain relocations that
  205. /// points to code section(the low_pc for a function, the location for
  206. /// a variable). These relocations are called ValidRelocs in the
  207. /// AddressesInfo and are gathered as a very first step when we start
  208. /// processing a object file.
  209. class DWARFLinker {
  210. public:
  211. DWARFLinker(DwarfEmitter *Emitter,
  212. DwarfLinkerClient ClientID = DwarfLinkerClient::General)
  213. : TheDwarfEmitter(Emitter), DwarfLinkerClientID(ClientID) {}
  214. /// Add object file to be linked. Pre-load compile unit die. Call
  215. /// \p OnCUDieLoaded for each compile unit die. If specified \p File
  216. /// has reference to the Clang module then such module would be
  217. /// pre-loaded by \p Loader for !Update case.
  218. ///
  219. /// \pre NoODR, Update options should be set before call to addObjectFile.
  220. void addObjectFile(
  221. DWARFFile &File, objFileLoader Loader = nullptr,
  222. CompileUnitHandler OnCUDieLoaded = [](const DWARFUnit &) {});
  223. /// Link debug info for added objFiles. Object
  224. /// files are linked all together.
  225. Error link();
  226. /// A number of methods setting various linking options:
  227. /// Allows to generate log of linking process to the standard output.
  228. void setVerbosity(bool Verbose) { Options.Verbose = Verbose; }
  229. /// Print statistics to standard output.
  230. void setStatistics(bool Statistics) { Options.Statistics = Statistics; }
  231. /// Verify the input DWARF.
  232. void setVerifyInputDWARF(bool Verify) { Options.VerifyInputDWARF = Verify; }
  233. /// Do not emit linked dwarf info.
  234. void setNoOutput(bool NoOut) { Options.NoOutput = NoOut; }
  235. /// Do not unique types according to ODR.
  236. void setNoODR(bool NoODR) { Options.NoODR = NoODR; }
  237. /// update existing DWARF info(for the linked binary).
  238. void setUpdate(bool Update) { Options.Update = Update; }
  239. /// Set whether to keep the enclosing function for a static variable.
  240. void setKeepFunctionForStatic(bool KeepFunctionForStatic) {
  241. Options.KeepFunctionForStatic = KeepFunctionForStatic;
  242. }
  243. /// Use specified number of threads for parallel files linking.
  244. void setNumThreads(unsigned NumThreads) { Options.Threads = NumThreads; }
  245. /// Add kind of accelerator tables to be generated.
  246. void addAccelTableKind(DwarfLinkerAccelTableKind Kind) {
  247. assert(std::find(Options.AccelTables.begin(), Options.AccelTables.end(),
  248. Kind) == Options.AccelTables.end());
  249. Options.AccelTables.emplace_back(Kind);
  250. }
  251. /// Set prepend path for clang modules.
  252. void setPrependPath(const std::string &Ppath) { Options.PrependPath = Ppath; }
  253. /// Set translator which would be used for strings.
  254. void
  255. setStringsTranslator(std::function<StringRef(StringRef)> StringsTranslator) {
  256. this->StringsTranslator = StringsTranslator;
  257. }
  258. /// Set estimated objects files amount, for preliminary data allocation.
  259. void setEstimatedObjfilesAmount(unsigned ObjFilesNum) {
  260. ObjectContexts.reserve(ObjFilesNum);
  261. }
  262. /// Set warning handler which would be used to report warnings.
  263. void setWarningHandler(messageHandler Handler) {
  264. Options.WarningHandler = Handler;
  265. }
  266. /// Set error handler which would be used to report errors.
  267. void setErrorHandler(messageHandler Handler) {
  268. Options.ErrorHandler = Handler;
  269. }
  270. /// Set map for Swift interfaces.
  271. void setSwiftInterfacesMap(swiftInterfacesMap *Map) {
  272. Options.ParseableSwiftInterfaces = Map;
  273. }
  274. /// Set prefix map for objects.
  275. void setObjectPrefixMap(objectPrefixMap *Map) {
  276. Options.ObjectPrefixMap = Map;
  277. }
  278. /// Set target DWARF version.
  279. Error setTargetDWARFVersion(uint16_t TargetDWARFVersion) {
  280. if (TargetDWARFVersion < 1 || TargetDWARFVersion > 5)
  281. return createStringError(std::errc::invalid_argument,
  282. "unsupported DWARF version: %d",
  283. TargetDWARFVersion);
  284. Options.TargetDWARFVersion = TargetDWARFVersion;
  285. return Error::success();
  286. }
  287. private:
  288. /// Flags passed to DwarfLinker::lookForDIEsToKeep
  289. enum TraversalFlags {
  290. TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
  291. TF_InFunctionScope = 1 << 1, ///< Current scope is a function scope.
  292. TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
  293. TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
  294. TF_ODR = 1 << 4, ///< Use the ODR while keeping dependents.
  295. TF_SkipPC = 1 << 5, ///< Skip all location attributes.
  296. };
  297. /// The distinct types of work performed by the work loop.
  298. enum class WorklistItemType {
  299. /// Given a DIE, look for DIEs to be kept.
  300. LookForDIEsToKeep,
  301. /// Given a DIE, look for children of this DIE to be kept.
  302. LookForChildDIEsToKeep,
  303. /// Given a DIE, look for DIEs referencing this DIE to be kept.
  304. LookForRefDIEsToKeep,
  305. /// Given a DIE, look for parent DIEs to be kept.
  306. LookForParentDIEsToKeep,
  307. /// Given a DIE, update its incompleteness based on whether its children are
  308. /// incomplete.
  309. UpdateChildIncompleteness,
  310. /// Given a DIE, update its incompleteness based on whether the DIEs it
  311. /// references are incomplete.
  312. UpdateRefIncompleteness,
  313. /// Given a DIE, mark it as ODR Canonical if applicable.
  314. MarkODRCanonicalDie,
  315. };
  316. /// This class represents an item in the work list. The type defines what kind
  317. /// of work needs to be performed when processing the current item. The flags
  318. /// and info fields are optional based on the type.
  319. struct WorklistItem {
  320. DWARFDie Die;
  321. WorklistItemType Type;
  322. CompileUnit &CU;
  323. unsigned Flags;
  324. union {
  325. const unsigned AncestorIdx;
  326. CompileUnit::DIEInfo *OtherInfo;
  327. };
  328. WorklistItem(DWARFDie Die, CompileUnit &CU, unsigned Flags,
  329. WorklistItemType T = WorklistItemType::LookForDIEsToKeep)
  330. : Die(Die), Type(T), CU(CU), Flags(Flags), AncestorIdx(0) {}
  331. WorklistItem(DWARFDie Die, CompileUnit &CU, WorklistItemType T,
  332. CompileUnit::DIEInfo *OtherInfo = nullptr)
  333. : Die(Die), Type(T), CU(CU), Flags(0), OtherInfo(OtherInfo) {}
  334. WorklistItem(unsigned AncestorIdx, CompileUnit &CU, unsigned Flags)
  335. : Type(WorklistItemType::LookForParentDIEsToKeep), CU(CU), Flags(Flags),
  336. AncestorIdx(AncestorIdx) {}
  337. };
  338. /// Verify the given DWARF file.
  339. bool verify(const DWARFFile &File);
  340. /// returns true if we need to translate strings.
  341. bool needToTranslateStrings() { return StringsTranslator != nullptr; }
  342. void reportWarning(const Twine &Warning, const DWARFFile &File,
  343. const DWARFDie *DIE = nullptr) const {
  344. if (Options.WarningHandler != nullptr)
  345. Options.WarningHandler(Warning, File.FileName, DIE);
  346. }
  347. void reportError(const Twine &Warning, const DWARFFile &File,
  348. const DWARFDie *DIE = nullptr) const {
  349. if (Options.ErrorHandler != nullptr)
  350. Options.ErrorHandler(Warning, File.FileName, DIE);
  351. }
  352. /// Emit warnings as Dwarf compile units to leave a trail after linking.
  353. bool emitPaperTrailWarnings(const DWARFFile &File,
  354. OffsetsStringPool &StringPool);
  355. void copyInvariantDebugSection(DWARFContext &Dwarf);
  356. /// Keep information for referenced clang module: already loaded DWARF info
  357. /// of the clang module and a CompileUnit of the module.
  358. struct RefModuleUnit {
  359. RefModuleUnit(DWARFFile &File, std::unique_ptr<CompileUnit> Unit)
  360. : File(File), Unit(std::move(Unit)) {}
  361. RefModuleUnit(RefModuleUnit &&Other)
  362. : File(Other.File), Unit(std::move(Other.Unit)) {}
  363. RefModuleUnit(const RefModuleUnit &) = delete;
  364. DWARFFile &File;
  365. std::unique_ptr<CompileUnit> Unit;
  366. };
  367. using ModuleUnitListTy = std::vector<RefModuleUnit>;
  368. /// Keeps track of data associated with one object during linking.
  369. struct LinkContext {
  370. DWARFFile &File;
  371. UnitListTy CompileUnits;
  372. ModuleUnitListTy ModuleUnits;
  373. bool Skip = false;
  374. LinkContext(DWARFFile &File) : File(File) {}
  375. /// Clear part of the context that's no longer needed when we're done with
  376. /// the debug object.
  377. void clear() {
  378. CompileUnits.clear();
  379. File.Addresses->clear();
  380. }
  381. };
  382. /// Called before emitting object data
  383. void cleanupAuxiliarryData(LinkContext &Context);
  384. /// Look at the parent of the given DIE and decide whether they should be
  385. /// kept.
  386. void lookForParentDIEsToKeep(unsigned AncestorIdx, CompileUnit &CU,
  387. unsigned Flags,
  388. SmallVectorImpl<WorklistItem> &Worklist);
  389. /// Look at the children of the given DIE and decide whether they should be
  390. /// kept.
  391. void lookForChildDIEsToKeep(const DWARFDie &Die, CompileUnit &CU,
  392. unsigned Flags,
  393. SmallVectorImpl<WorklistItem> &Worklist);
  394. /// Look at DIEs referenced by the given DIE and decide whether they should be
  395. /// kept. All DIEs referenced though attributes should be kept.
  396. void lookForRefDIEsToKeep(const DWARFDie &Die, CompileUnit &CU,
  397. unsigned Flags, const UnitListTy &Units,
  398. const DWARFFile &File,
  399. SmallVectorImpl<WorklistItem> &Worklist);
  400. /// Mark context corresponding to the specified \p Die as having canonical
  401. /// die, if applicable.
  402. void markODRCanonicalDie(const DWARFDie &Die, CompileUnit &CU);
  403. /// \defgroup FindRootDIEs Find DIEs corresponding to Address map entries.
  404. ///
  405. /// @{
  406. /// Recursively walk the \p DIE tree and look for DIEs to
  407. /// keep. Store that information in \p CU's DIEInfo.
  408. ///
  409. /// The return value indicates whether the DIE is incomplete.
  410. void lookForDIEsToKeep(AddressesMap &RelocMgr, RangesTy &Ranges,
  411. const UnitListTy &Units, const DWARFDie &DIE,
  412. const DWARFFile &File, CompileUnit &CU,
  413. unsigned Flags);
  414. /// Check whether specified \p CUDie is a Clang module reference.
  415. /// if \p Quiet is false then display error messages.
  416. /// \return first == true if CUDie is a Clang module reference.
  417. /// second == true if module is already loaded.
  418. std::pair<bool, bool> isClangModuleRef(const DWARFDie &CUDie,
  419. std::string &PCMFile,
  420. LinkContext &Context, unsigned Indent,
  421. bool Quiet);
  422. /// If this compile unit is really a skeleton CU that points to a
  423. /// clang module, register it in ClangModules and return true.
  424. ///
  425. /// A skeleton CU is a CU without children, a DW_AT_gnu_dwo_name
  426. /// pointing to the module, and a DW_AT_gnu_dwo_id with the module
  427. /// hash.
  428. bool registerModuleReference(const DWARFDie &CUDie, LinkContext &Context,
  429. objFileLoader Loader,
  430. CompileUnitHandler OnCUDieLoaded,
  431. unsigned Indent = 0);
  432. /// Recursively add the debug info in this clang module .pcm
  433. /// file (and all the modules imported by it in a bottom-up fashion)
  434. /// to ModuleUnits.
  435. Error loadClangModule(objFileLoader Loader, const DWARFDie &CUDie,
  436. const std::string &PCMFile, LinkContext &Context,
  437. CompileUnitHandler OnCUDieLoaded, unsigned Indent = 0);
  438. /// Clone specified Clang module unit \p Unit.
  439. Error cloneModuleUnit(LinkContext &Context, RefModuleUnit &Unit,
  440. DeclContextTree &ODRContexts,
  441. OffsetsStringPool &OffsetsStringPool,
  442. unsigned Indent = 0);
  443. /// Mark the passed DIE as well as all the ones it depends on as kept.
  444. void keepDIEAndDependencies(AddressesMap &RelocMgr, RangesTy &Ranges,
  445. const UnitListTy &Units, const DWARFDie &DIE,
  446. CompileUnit::DIEInfo &MyInfo,
  447. const DWARFFile &File, CompileUnit &CU,
  448. bool UseODR);
  449. unsigned shouldKeepDIE(AddressesMap &RelocMgr, RangesTy &Ranges,
  450. const DWARFDie &DIE, const DWARFFile &File,
  451. CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
  452. unsigned Flags);
  453. /// Check if a variable describing DIE should be kept.
  454. /// \returns updated TraversalFlags.
  455. unsigned shouldKeepVariableDIE(AddressesMap &RelocMgr, const DWARFDie &DIE,
  456. CompileUnit::DIEInfo &MyInfo, unsigned Flags);
  457. unsigned shouldKeepSubprogramDIE(AddressesMap &RelocMgr, RangesTy &Ranges,
  458. const DWARFDie &DIE, const DWARFFile &File,
  459. CompileUnit &Unit,
  460. CompileUnit::DIEInfo &MyInfo,
  461. unsigned Flags);
  462. /// Resolve the DIE attribute reference that has been extracted in \p
  463. /// RefValue. The resulting DIE might be in another CompileUnit which is
  464. /// stored into \p ReferencedCU. \returns null if resolving fails for any
  465. /// reason.
  466. DWARFDie resolveDIEReference(const DWARFFile &File, const UnitListTy &Units,
  467. const DWARFFormValue &RefValue,
  468. const DWARFDie &DIE, CompileUnit *&RefCU);
  469. /// @}
  470. /// \defgroup Methods used to link the debug information
  471. ///
  472. /// @{
  473. struct DWARFLinkerOptions;
  474. class DIECloner {
  475. DWARFLinker &Linker;
  476. DwarfEmitter *Emitter;
  477. DWARFFile &ObjFile;
  478. /// Allocator used for all the DIEValue objects.
  479. BumpPtrAllocator &DIEAlloc;
  480. std::vector<std::unique_ptr<CompileUnit>> &CompileUnits;
  481. /// Keeps mapping from offset of the macro table to corresponding
  482. /// compile unit.
  483. Offset2UnitMap UnitMacroMap;
  484. bool Update;
  485. public:
  486. DIECloner(DWARFLinker &Linker, DwarfEmitter *Emitter, DWARFFile &ObjFile,
  487. BumpPtrAllocator &DIEAlloc,
  488. std::vector<std::unique_ptr<CompileUnit>> &CompileUnits,
  489. bool Update)
  490. : Linker(Linker), Emitter(Emitter), ObjFile(ObjFile),
  491. DIEAlloc(DIEAlloc), CompileUnits(CompileUnits), Update(Update) {}
  492. /// Recursively clone \p InputDIE into an tree of DIE objects
  493. /// where useless (as decided by lookForDIEsToKeep()) bits have been
  494. /// stripped out and addresses have been rewritten according to the
  495. /// address map.
  496. ///
  497. /// \param OutOffset is the offset the cloned DIE in the output
  498. /// compile unit.
  499. /// \param PCOffset (while cloning a function scope) is the offset
  500. /// applied to the entry point of the function to get the linked address.
  501. /// \param Die the output DIE to use, pass NULL to create one.
  502. /// \returns the root of the cloned tree or null if nothing was selected.
  503. DIE *cloneDIE(const DWARFDie &InputDIE, const DWARFFile &File,
  504. CompileUnit &U, OffsetsStringPool &StringPool,
  505. int64_t PCOffset, uint32_t OutOffset, unsigned Flags,
  506. bool IsLittleEndian, DIE *Die = nullptr);
  507. /// Construct the output DIE tree by cloning the DIEs we
  508. /// chose to keep above. If there are no valid relocs, then there's
  509. /// nothing to clone/emit.
  510. uint64_t cloneAllCompileUnits(DWARFContext &DwarfContext,
  511. const DWARFFile &File,
  512. OffsetsStringPool &StringPool,
  513. bool IsLittleEndian);
  514. private:
  515. using AttributeSpec = DWARFAbbreviationDeclaration::AttributeSpec;
  516. /// Information gathered and exchanged between the various
  517. /// clone*Attributes helpers about the attributes of a particular DIE.
  518. struct AttributesInfo {
  519. /// Names.
  520. DwarfStringPoolEntryRef Name, MangledName, NameWithoutTemplate;
  521. /// Offsets in the string pool.
  522. uint32_t NameOffset = 0;
  523. uint32_t MangledNameOffset = 0;
  524. /// Value of AT_low_pc in the input DIE
  525. uint64_t OrigLowPc = std::numeric_limits<uint64_t>::max();
  526. /// Value of AT_high_pc in the input DIE
  527. uint64_t OrigHighPc = 0;
  528. /// Value of DW_AT_call_return_pc in the input DIE
  529. uint64_t OrigCallReturnPc = 0;
  530. /// Value of DW_AT_call_pc in the input DIE
  531. uint64_t OrigCallPc = 0;
  532. /// Offset to apply to PC addresses inside a function.
  533. int64_t PCOffset = 0;
  534. /// Does the DIE have a low_pc attribute?
  535. bool HasLowPc = false;
  536. /// Does the DIE have a ranges attribute?
  537. bool HasRanges = false;
  538. /// Is this DIE only a declaration?
  539. bool IsDeclaration = false;
  540. AttributesInfo() = default;
  541. };
  542. /// Helper for cloneDIE.
  543. unsigned cloneAttribute(DIE &Die, const DWARFDie &InputDIE,
  544. const DWARFFile &File, CompileUnit &U,
  545. OffsetsStringPool &StringPool,
  546. const DWARFFormValue &Val,
  547. const AttributeSpec AttrSpec, unsigned AttrSize,
  548. AttributesInfo &AttrInfo, bool IsLittleEndian);
  549. /// Clone a string attribute described by \p AttrSpec and add
  550. /// it to \p Die.
  551. /// \returns the size of the new attribute.
  552. unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
  553. const DWARFFormValue &Val, const DWARFUnit &U,
  554. OffsetsStringPool &StringPool,
  555. AttributesInfo &Info);
  556. /// Clone an attribute referencing another DIE and add
  557. /// it to \p Die.
  558. /// \returns the size of the new attribute.
  559. unsigned cloneDieReferenceAttribute(DIE &Die, const DWARFDie &InputDIE,
  560. AttributeSpec AttrSpec,
  561. unsigned AttrSize,
  562. const DWARFFormValue &Val,
  563. const DWARFFile &File,
  564. CompileUnit &Unit);
  565. /// Clone a DWARF expression that may be referencing another DIE.
  566. void cloneExpression(DataExtractor &Data, DWARFExpression Expression,
  567. const DWARFFile &File, CompileUnit &Unit,
  568. SmallVectorImpl<uint8_t> &OutputBuffer);
  569. /// Clone an attribute referencing another DIE and add
  570. /// it to \p Die.
  571. /// \returns the size of the new attribute.
  572. unsigned cloneBlockAttribute(DIE &Die, const DWARFFile &File,
  573. CompileUnit &Unit, AttributeSpec AttrSpec,
  574. const DWARFFormValue &Val, unsigned AttrSize,
  575. bool IsLittleEndian);
  576. /// Clone an attribute referencing another DIE and add
  577. /// it to \p Die.
  578. /// \returns the size of the new attribute.
  579. unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
  580. unsigned AttrSize, const DWARFFormValue &Val,
  581. const CompileUnit &Unit,
  582. AttributesInfo &Info);
  583. /// Clone a scalar attribute and add it to \p Die.
  584. /// \returns the size of the new attribute.
  585. unsigned cloneScalarAttribute(DIE &Die, const DWARFDie &InputDIE,
  586. const DWARFFile &File, CompileUnit &U,
  587. AttributeSpec AttrSpec,
  588. const DWARFFormValue &Val, unsigned AttrSize,
  589. AttributesInfo &Info);
  590. /// Get the potential name and mangled name for the entity
  591. /// described by \p Die and store them in \Info if they are not
  592. /// already there.
  593. /// \returns is a name was found.
  594. bool getDIENames(const DWARFDie &Die, AttributesInfo &Info,
  595. OffsetsStringPool &StringPool, bool StripTemplate = false);
  596. uint32_t hashFullyQualifiedName(DWARFDie DIE, CompileUnit &U,
  597. const DWARFFile &File,
  598. int RecurseDepth = 0);
  599. /// Helper for cloneDIE.
  600. void addObjCAccelerator(CompileUnit &Unit, const DIE *Die,
  601. DwarfStringPoolEntryRef Name,
  602. OffsetsStringPool &StringPool, bool SkipPubSection);
  603. void rememberUnitForMacroOffset(CompileUnit &Unit);
  604. };
  605. /// Assign an abbreviation number to \p Abbrev
  606. void assignAbbrev(DIEAbbrev &Abbrev);
  607. /// Compute and emit .debug_ranges section for \p Unit, and
  608. /// patch the attributes referencing it.
  609. void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf,
  610. const DWARFFile &File) const;
  611. /// Generate and emit the DW_AT_ranges attribute for a compile_unit if it had
  612. /// one.
  613. void generateUnitRanges(CompileUnit &Unit) const;
  614. /// Extract the line tables from the original dwarf, extract the relevant
  615. /// parts according to the linked function ranges and emit the result in the
  616. /// .debug_line section.
  617. void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf,
  618. const DWARFFile &File);
  619. /// Emit the accelerator entries for \p Unit.
  620. void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
  621. /// Patch the frame info for an object file and emit it.
  622. void patchFrameInfoForObject(const DWARFFile &, RangesTy &Ranges,
  623. DWARFContext &, unsigned AddressSize);
  624. /// FoldingSet that uniques the abbreviations.
  625. FoldingSet<DIEAbbrev> AbbreviationsSet;
  626. /// Storage for the unique Abbreviations.
  627. /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot be
  628. /// changed to a vector of unique_ptrs.
  629. std::vector<std::unique_ptr<DIEAbbrev>> Abbreviations;
  630. /// DIELoc objects that need to be destructed (but not freed!).
  631. std::vector<DIELoc *> DIELocs;
  632. /// DIEBlock objects that need to be destructed (but not freed!).
  633. std::vector<DIEBlock *> DIEBlocks;
  634. /// Allocator used for all the DIEValue objects.
  635. BumpPtrAllocator DIEAlloc;
  636. /// @}
  637. DwarfEmitter *TheDwarfEmitter;
  638. std::vector<LinkContext> ObjectContexts;
  639. /// The CIEs that have been emitted in the output section. The actual CIE
  640. /// data serves a the key to this StringMap, this takes care of comparing the
  641. /// semantics of CIEs defined in different object files.
  642. StringMap<uint32_t> EmittedCIEs;
  643. /// Offset of the last CIE that has been emitted in the output
  644. /// .debug_frame section.
  645. uint32_t LastCIEOffset = 0;
  646. /// Apple accelerator tables.
  647. AccelTable<DWARF5AccelTableStaticData> DebugNames;
  648. AccelTable<AppleAccelTableStaticOffsetData> AppleNames;
  649. AccelTable<AppleAccelTableStaticOffsetData> AppleNamespaces;
  650. AccelTable<AppleAccelTableStaticOffsetData> AppleObjc;
  651. AccelTable<AppleAccelTableStaticTypeData> AppleTypes;
  652. /// Mapping the PCM filename to the DwoId.
  653. StringMap<uint64_t> ClangModules;
  654. DwarfLinkerClient DwarfLinkerClientID;
  655. std::function<StringRef(StringRef)> StringsTranslator = nullptr;
  656. /// A unique ID that identifies each compile unit.
  657. unsigned UniqueUnitID = 0;
  658. /// linking options
  659. struct DWARFLinkerOptions {
  660. /// DWARF version for the output.
  661. uint16_t TargetDWARFVersion = 0;
  662. /// Generate processing log to the standard output.
  663. bool Verbose = false;
  664. /// Print statistics.
  665. bool Statistics = false;
  666. /// Verify the input DWARF.
  667. bool VerifyInputDWARF = false;
  668. /// Skip emitting output
  669. bool NoOutput = false;
  670. /// Do not unique types according to ODR
  671. bool NoODR = false;
  672. /// Update
  673. bool Update = false;
  674. /// Whether we want a static variable to force us to keep its enclosing
  675. /// function.
  676. bool KeepFunctionForStatic = false;
  677. /// Number of threads.
  678. unsigned Threads = 1;
  679. /// The accelerator table kinds
  680. SmallVector<DwarfLinkerAccelTableKind, 1> AccelTables;
  681. /// Prepend path for the clang modules.
  682. std::string PrependPath;
  683. // warning handler
  684. messageHandler WarningHandler = nullptr;
  685. // error handler
  686. messageHandler ErrorHandler = nullptr;
  687. /// A list of all .swiftinterface files referenced by the debug
  688. /// info, mapping Module name to path on disk. The entries need to
  689. /// be uniqued and sorted and there are only few entries expected
  690. /// per compile unit, which is why this is a std::map.
  691. /// this is dsymutil specific fag.
  692. swiftInterfacesMap *ParseableSwiftInterfaces = nullptr;
  693. /// A list of remappings to apply to file paths.
  694. objectPrefixMap *ObjectPrefixMap = nullptr;
  695. } Options;
  696. };
  697. } // end namespace llvm
  698. #endif // LLVM_DWARFLINKER_DWARFLINKER_H
  699. #ifdef __GNUC__
  700. #pragma GCC diagnostic pop
  701. #endif