DWARFLinker.cpp 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637
  1. //=== DWARFLinker.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 "llvm/DWARFLinker/DWARFLinker.h"
  9. #include "llvm/ADT/ArrayRef.h"
  10. #include "llvm/ADT/BitVector.h"
  11. #include "llvm/ADT/STLExtras.h"
  12. #include "llvm/ADT/Triple.h"
  13. #include "llvm/CodeGen/NonRelocatableStringpool.h"
  14. #include "llvm/DWARFLinker/DWARFLinkerDeclContext.h"
  15. #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
  16. #include "llvm/DebugInfo/DWARF/DWARFContext.h"
  17. #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
  18. #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
  19. #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
  20. #include "llvm/DebugInfo/DWARF/DWARFDie.h"
  21. #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
  22. #include "llvm/DebugInfo/DWARF/DWARFSection.h"
  23. #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
  24. #include "llvm/Support/DataExtractor.h"
  25. #include "llvm/Support/Error.h"
  26. #include "llvm/Support/ErrorHandling.h"
  27. #include "llvm/Support/ErrorOr.h"
  28. #include "llvm/Support/FormatVariadic.h"
  29. #include "llvm/Support/LEB128.h"
  30. #include "llvm/Support/Path.h"
  31. #include "llvm/Support/ThreadPool.h"
  32. #include <vector>
  33. namespace llvm {
  34. /// Hold the input and output of the debug info size in bytes.
  35. struct DebugInfoSize {
  36. uint64_t Input;
  37. uint64_t Output;
  38. };
  39. /// Compute the total size of the debug info.
  40. static uint64_t getDebugInfoSize(DWARFContext &Dwarf) {
  41. uint64_t Size = 0;
  42. for (auto &Unit : Dwarf.compile_units()) {
  43. Size += Unit->getLength();
  44. }
  45. return Size;
  46. }
  47. /// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
  48. /// CompileUnit object instead.
  49. static CompileUnit *getUnitForOffset(const UnitListTy &Units, uint64_t Offset) {
  50. auto CU = llvm::upper_bound(
  51. Units, Offset, [](uint64_t LHS, const std::unique_ptr<CompileUnit> &RHS) {
  52. return LHS < RHS->getOrigUnit().getNextUnitOffset();
  53. });
  54. return CU != Units.end() ? CU->get() : nullptr;
  55. }
  56. /// Resolve the DIE attribute reference that has been extracted in \p RefValue.
  57. /// The resulting DIE might be in another CompileUnit which is stored into \p
  58. /// ReferencedCU. \returns null if resolving fails for any reason.
  59. DWARFDie DWARFLinker::resolveDIEReference(const DWARFFile &File,
  60. const UnitListTy &Units,
  61. const DWARFFormValue &RefValue,
  62. const DWARFDie &DIE,
  63. CompileUnit *&RefCU) {
  64. assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
  65. uint64_t RefOffset = *RefValue.getAsReference();
  66. if ((RefCU = getUnitForOffset(Units, RefOffset)))
  67. if (const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset)) {
  68. // In a file with broken references, an attribute might point to a NULL
  69. // DIE.
  70. if (!RefDie.isNULL())
  71. return RefDie;
  72. }
  73. reportWarning("could not find referenced DIE", File, &DIE);
  74. return DWARFDie();
  75. }
  76. /// \returns whether the passed \a Attr type might contain a DIE reference
  77. /// suitable for ODR uniquing.
  78. static bool isODRAttribute(uint16_t Attr) {
  79. switch (Attr) {
  80. default:
  81. return false;
  82. case dwarf::DW_AT_type:
  83. case dwarf::DW_AT_containing_type:
  84. case dwarf::DW_AT_specification:
  85. case dwarf::DW_AT_abstract_origin:
  86. case dwarf::DW_AT_import:
  87. return true;
  88. }
  89. llvm_unreachable("Improper attribute.");
  90. }
  91. static bool isTypeTag(uint16_t Tag) {
  92. switch (Tag) {
  93. case dwarf::DW_TAG_array_type:
  94. case dwarf::DW_TAG_class_type:
  95. case dwarf::DW_TAG_enumeration_type:
  96. case dwarf::DW_TAG_pointer_type:
  97. case dwarf::DW_TAG_reference_type:
  98. case dwarf::DW_TAG_string_type:
  99. case dwarf::DW_TAG_structure_type:
  100. case dwarf::DW_TAG_subroutine_type:
  101. case dwarf::DW_TAG_typedef:
  102. case dwarf::DW_TAG_union_type:
  103. case dwarf::DW_TAG_ptr_to_member_type:
  104. case dwarf::DW_TAG_set_type:
  105. case dwarf::DW_TAG_subrange_type:
  106. case dwarf::DW_TAG_base_type:
  107. case dwarf::DW_TAG_const_type:
  108. case dwarf::DW_TAG_constant:
  109. case dwarf::DW_TAG_file_type:
  110. case dwarf::DW_TAG_namelist:
  111. case dwarf::DW_TAG_packed_type:
  112. case dwarf::DW_TAG_volatile_type:
  113. case dwarf::DW_TAG_restrict_type:
  114. case dwarf::DW_TAG_atomic_type:
  115. case dwarf::DW_TAG_interface_type:
  116. case dwarf::DW_TAG_unspecified_type:
  117. case dwarf::DW_TAG_shared_type:
  118. return true;
  119. default:
  120. break;
  121. }
  122. return false;
  123. }
  124. AddressesMap::~AddressesMap() {}
  125. DwarfEmitter::~DwarfEmitter() {}
  126. static Optional<StringRef> StripTemplateParameters(StringRef Name) {
  127. // We are looking for template parameters to strip from Name. e.g.
  128. //
  129. // operator<<B>
  130. //
  131. // We look for > at the end but if it does not contain any < then we
  132. // have something like operator>>. We check for the operator<=> case.
  133. if (!Name.endswith(">") || Name.count("<") == 0 || Name.endswith("<=>"))
  134. return {};
  135. // How many < until we have the start of the template parameters.
  136. size_t NumLeftAnglesToSkip = 1;
  137. // If we have operator<=> then we need to skip its < as well.
  138. NumLeftAnglesToSkip += Name.count("<=>");
  139. size_t RightAngleCount = Name.count('>');
  140. size_t LeftAngleCount = Name.count('<');
  141. // If we have more < than > we have operator< or operator<<
  142. // we to account for their < as well.
  143. if (LeftAngleCount > RightAngleCount)
  144. NumLeftAnglesToSkip += LeftAngleCount - RightAngleCount;
  145. size_t StartOfTemplate = 0;
  146. while (NumLeftAnglesToSkip--)
  147. StartOfTemplate = Name.find('<', StartOfTemplate) + 1;
  148. return Name.substr(0, StartOfTemplate - 1);
  149. }
  150. bool DWARFLinker::DIECloner::getDIENames(const DWARFDie &Die,
  151. AttributesInfo &Info,
  152. OffsetsStringPool &StringPool,
  153. bool StripTemplate) {
  154. // This function will be called on DIEs having low_pcs and
  155. // ranges. As getting the name might be more expansive, filter out
  156. // blocks directly.
  157. if (Die.getTag() == dwarf::DW_TAG_lexical_block)
  158. return false;
  159. if (!Info.MangledName)
  160. if (const char *MangledName = Die.getLinkageName())
  161. Info.MangledName = StringPool.getEntry(MangledName);
  162. if (!Info.Name)
  163. if (const char *Name = Die.getShortName())
  164. Info.Name = StringPool.getEntry(Name);
  165. if (!Info.MangledName)
  166. Info.MangledName = Info.Name;
  167. if (StripTemplate && Info.Name && Info.MangledName != Info.Name) {
  168. StringRef Name = Info.Name.getString();
  169. if (Optional<StringRef> StrippedName = StripTemplateParameters(Name))
  170. Info.NameWithoutTemplate = StringPool.getEntry(*StrippedName);
  171. }
  172. return Info.Name || Info.MangledName;
  173. }
  174. /// Resolve the relative path to a build artifact referenced by DWARF by
  175. /// applying DW_AT_comp_dir.
  176. static void resolveRelativeObjectPath(SmallVectorImpl<char> &Buf, DWARFDie CU) {
  177. sys::path::append(Buf, dwarf::toString(CU.find(dwarf::DW_AT_comp_dir), ""));
  178. }
  179. /// Collect references to parseable Swift interfaces in imported
  180. /// DW_TAG_module blocks.
  181. static void analyzeImportedModule(
  182. const DWARFDie &DIE, CompileUnit &CU,
  183. swiftInterfacesMap *ParseableSwiftInterfaces,
  184. std::function<void(const Twine &, const DWARFDie &)> ReportWarning) {
  185. if (CU.getLanguage() != dwarf::DW_LANG_Swift)
  186. return;
  187. if (!ParseableSwiftInterfaces)
  188. return;
  189. StringRef Path = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_include_path));
  190. if (!Path.endswith(".swiftinterface"))
  191. return;
  192. // Don't track interfaces that are part of the SDK.
  193. StringRef SysRoot = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_sysroot));
  194. if (SysRoot.empty())
  195. SysRoot = CU.getSysRoot();
  196. if (!SysRoot.empty() && Path.startswith(SysRoot))
  197. return;
  198. if (Optional<DWARFFormValue> Val = DIE.find(dwarf::DW_AT_name))
  199. if (Optional<const char *> Name = Val->getAsCString()) {
  200. auto &Entry = (*ParseableSwiftInterfaces)[*Name];
  201. // The prepend path is applied later when copying.
  202. DWARFDie CUDie = CU.getOrigUnit().getUnitDIE();
  203. SmallString<128> ResolvedPath;
  204. if (sys::path::is_relative(Path))
  205. resolveRelativeObjectPath(ResolvedPath, CUDie);
  206. sys::path::append(ResolvedPath, Path);
  207. if (!Entry.empty() && Entry != ResolvedPath)
  208. ReportWarning(
  209. Twine("Conflicting parseable interfaces for Swift Module ") +
  210. *Name + ": " + Entry + " and " + Path,
  211. DIE);
  212. Entry = std::string(ResolvedPath.str());
  213. }
  214. }
  215. /// The distinct types of work performed by the work loop in
  216. /// analyzeContextInfo.
  217. enum class ContextWorklistItemType : uint8_t {
  218. AnalyzeContextInfo,
  219. UpdateChildPruning,
  220. UpdatePruning,
  221. };
  222. /// This class represents an item in the work list. The type defines what kind
  223. /// of work needs to be performed when processing the current item. Everything
  224. /// but the Type and Die fields are optional based on the type.
  225. struct ContextWorklistItem {
  226. DWARFDie Die;
  227. unsigned ParentIdx;
  228. union {
  229. CompileUnit::DIEInfo *OtherInfo;
  230. DeclContext *Context;
  231. };
  232. ContextWorklistItemType Type;
  233. bool InImportedModule;
  234. ContextWorklistItem(DWARFDie Die, ContextWorklistItemType T,
  235. CompileUnit::DIEInfo *OtherInfo = nullptr)
  236. : Die(Die), ParentIdx(0), OtherInfo(OtherInfo), Type(T),
  237. InImportedModule(false) {}
  238. ContextWorklistItem(DWARFDie Die, DeclContext *Context, unsigned ParentIdx,
  239. bool InImportedModule)
  240. : Die(Die), ParentIdx(ParentIdx), Context(Context),
  241. Type(ContextWorklistItemType::AnalyzeContextInfo),
  242. InImportedModule(InImportedModule) {}
  243. };
  244. static bool updatePruning(const DWARFDie &Die, CompileUnit &CU,
  245. uint64_t ModulesEndOffset) {
  246. CompileUnit::DIEInfo &Info = CU.getInfo(Die);
  247. // Prune this DIE if it is either a forward declaration inside a
  248. // DW_TAG_module or a DW_TAG_module that contains nothing but
  249. // forward declarations.
  250. Info.Prune &= (Die.getTag() == dwarf::DW_TAG_module) ||
  251. (isTypeTag(Die.getTag()) &&
  252. dwarf::toUnsigned(Die.find(dwarf::DW_AT_declaration), 0));
  253. // Only prune forward declarations inside a DW_TAG_module for which a
  254. // definition exists elsewhere.
  255. if (ModulesEndOffset == 0)
  256. Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
  257. else
  258. Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() > 0 &&
  259. Info.Ctxt->getCanonicalDIEOffset() <= ModulesEndOffset;
  260. return Info.Prune;
  261. }
  262. static void updateChildPruning(const DWARFDie &Die, CompileUnit &CU,
  263. CompileUnit::DIEInfo &ChildInfo) {
  264. CompileUnit::DIEInfo &Info = CU.getInfo(Die);
  265. Info.Prune &= ChildInfo.Prune;
  266. }
  267. /// Recursive helper to build the global DeclContext information and
  268. /// gather the child->parent relationships in the original compile unit.
  269. ///
  270. /// This function uses the same work list approach as lookForDIEsToKeep.
  271. ///
  272. /// \return true when this DIE and all of its children are only
  273. /// forward declarations to types defined in external clang modules
  274. /// (i.e., forward declarations that are children of a DW_TAG_module).
  275. static bool analyzeContextInfo(
  276. const DWARFDie &DIE, unsigned ParentIdx, CompileUnit &CU,
  277. DeclContext *CurrentDeclContext, DeclContextTree &Contexts,
  278. uint64_t ModulesEndOffset, swiftInterfacesMap *ParseableSwiftInterfaces,
  279. std::function<void(const Twine &, const DWARFDie &)> ReportWarning,
  280. bool InImportedModule = false) {
  281. // LIFO work list.
  282. std::vector<ContextWorklistItem> Worklist;
  283. Worklist.emplace_back(DIE, CurrentDeclContext, ParentIdx, InImportedModule);
  284. while (!Worklist.empty()) {
  285. ContextWorklistItem Current = Worklist.back();
  286. Worklist.pop_back();
  287. switch (Current.Type) {
  288. case ContextWorklistItemType::UpdatePruning:
  289. updatePruning(Current.Die, CU, ModulesEndOffset);
  290. continue;
  291. case ContextWorklistItemType::UpdateChildPruning:
  292. updateChildPruning(Current.Die, CU, *Current.OtherInfo);
  293. continue;
  294. case ContextWorklistItemType::AnalyzeContextInfo:
  295. break;
  296. }
  297. unsigned Idx = CU.getOrigUnit().getDIEIndex(Current.Die);
  298. CompileUnit::DIEInfo &Info = CU.getInfo(Idx);
  299. // Clang imposes an ODR on modules(!) regardless of the language:
  300. // "The module-id should consist of only a single identifier,
  301. // which provides the name of the module being defined. Each
  302. // module shall have a single definition."
  303. //
  304. // This does not extend to the types inside the modules:
  305. // "[I]n C, this implies that if two structs are defined in
  306. // different submodules with the same name, those two types are
  307. // distinct types (but may be compatible types if their
  308. // definitions match)."
  309. //
  310. // We treat non-C++ modules like namespaces for this reason.
  311. if (Current.Die.getTag() == dwarf::DW_TAG_module &&
  312. Current.ParentIdx == 0 &&
  313. dwarf::toString(Current.Die.find(dwarf::DW_AT_name), "") !=
  314. CU.getClangModuleName()) {
  315. Current.InImportedModule = true;
  316. analyzeImportedModule(Current.Die, CU, ParseableSwiftInterfaces,
  317. ReportWarning);
  318. }
  319. Info.ParentIdx = Current.ParentIdx;
  320. bool InClangModule = CU.isClangModule() || Current.InImportedModule;
  321. if (CU.hasODR() || InClangModule) {
  322. if (Current.Context) {
  323. auto PtrInvalidPair = Contexts.getChildDeclContext(
  324. *Current.Context, Current.Die, CU, InClangModule);
  325. Current.Context = PtrInvalidPair.getPointer();
  326. Info.Ctxt =
  327. PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
  328. if (Info.Ctxt)
  329. Info.Ctxt->setDefinedInClangModule(InClangModule);
  330. } else
  331. Info.Ctxt = Current.Context = nullptr;
  332. }
  333. Info.Prune = Current.InImportedModule;
  334. // Add children in reverse order to the worklist to effectively process
  335. // them in order.
  336. Worklist.emplace_back(Current.Die, ContextWorklistItemType::UpdatePruning);
  337. for (auto Child : reverse(Current.Die.children())) {
  338. CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
  339. Worklist.emplace_back(
  340. Current.Die, ContextWorklistItemType::UpdateChildPruning, &ChildInfo);
  341. Worklist.emplace_back(Child, Current.Context, Idx,
  342. Current.InImportedModule);
  343. }
  344. }
  345. return CU.getInfo(DIE).Prune;
  346. }
  347. static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
  348. switch (Tag) {
  349. default:
  350. return false;
  351. case dwarf::DW_TAG_class_type:
  352. case dwarf::DW_TAG_common_block:
  353. case dwarf::DW_TAG_lexical_block:
  354. case dwarf::DW_TAG_structure_type:
  355. case dwarf::DW_TAG_subprogram:
  356. case dwarf::DW_TAG_subroutine_type:
  357. case dwarf::DW_TAG_union_type:
  358. return true;
  359. }
  360. llvm_unreachable("Invalid Tag");
  361. }
  362. void DWARFLinker::cleanupAuxiliarryData(LinkContext &Context) {
  363. Context.clear();
  364. for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
  365. (*I)->~DIEBlock();
  366. for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
  367. (*I)->~DIELoc();
  368. DIEBlocks.clear();
  369. DIELocs.clear();
  370. DIEAlloc.Reset();
  371. }
  372. /// Check if a variable describing DIE should be kept.
  373. /// \returns updated TraversalFlags.
  374. unsigned DWARFLinker::shouldKeepVariableDIE(AddressesMap &RelocMgr,
  375. const DWARFDie &DIE,
  376. CompileUnit::DIEInfo &MyInfo,
  377. unsigned Flags) {
  378. const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
  379. // Global variables with constant value can always be kept.
  380. if (!(Flags & TF_InFunctionScope) &&
  381. Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
  382. MyInfo.InDebugMap = true;
  383. return Flags | TF_Keep;
  384. }
  385. // See if there is a relocation to a valid debug map entry inside
  386. // this variable's location. The order is important here. We want to
  387. // always check if the variable has a valid relocation, so that the
  388. // DIEInfo is filled. However, we don't want a static variable in a
  389. // function to force us to keep the enclosing function.
  390. if (!RelocMgr.hasLiveMemoryLocation(DIE, MyInfo) ||
  391. (Flags & TF_InFunctionScope))
  392. return Flags;
  393. if (Options.Verbose) {
  394. outs() << "Keeping variable DIE:";
  395. DIDumpOptions DumpOpts;
  396. DumpOpts.ChildRecurseDepth = 0;
  397. DumpOpts.Verbose = Options.Verbose;
  398. DIE.dump(outs(), 8 /* Indent */, DumpOpts);
  399. }
  400. return Flags | TF_Keep;
  401. }
  402. /// Check if a function describing DIE should be kept.
  403. /// \returns updated TraversalFlags.
  404. unsigned DWARFLinker::shouldKeepSubprogramDIE(
  405. AddressesMap &RelocMgr, RangesTy &Ranges, const DWARFDie &DIE,
  406. const DWARFFile &File, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
  407. unsigned Flags) {
  408. Flags |= TF_InFunctionScope;
  409. auto LowPc = dwarf::toAddress(DIE.find(dwarf::DW_AT_low_pc));
  410. if (!LowPc)
  411. return Flags;
  412. assert(LowPc.hasValue() && "low_pc attribute is not an address.");
  413. if (!RelocMgr.hasLiveAddressRange(DIE, MyInfo))
  414. return Flags;
  415. if (Options.Verbose) {
  416. outs() << "Keeping subprogram DIE:";
  417. DIDumpOptions DumpOpts;
  418. DumpOpts.ChildRecurseDepth = 0;
  419. DumpOpts.Verbose = Options.Verbose;
  420. DIE.dump(outs(), 8 /* Indent */, DumpOpts);
  421. }
  422. if (DIE.getTag() == dwarf::DW_TAG_label) {
  423. if (Unit.hasLabelAt(*LowPc))
  424. return Flags;
  425. DWARFUnit &OrigUnit = Unit.getOrigUnit();
  426. // FIXME: dsymutil-classic compat. dsymutil-classic doesn't consider labels
  427. // that don't fall into the CU's aranges. This is wrong IMO. Debug info
  428. // generation bugs aside, this is really wrong in the case of labels, where
  429. // a label marking the end of a function will have a PC == CU's high_pc.
  430. if (dwarf::toAddress(OrigUnit.getUnitDIE().find(dwarf::DW_AT_high_pc))
  431. .getValueOr(UINT64_MAX) <= LowPc)
  432. return Flags;
  433. Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
  434. return Flags | TF_Keep;
  435. }
  436. Flags |= TF_Keep;
  437. Optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
  438. if (!HighPc) {
  439. reportWarning("Function without high_pc. Range will be discarded.\n", File,
  440. &DIE);
  441. return Flags;
  442. }
  443. // Replace the debug map range with a more accurate one.
  444. Ranges[*LowPc] = ObjFileAddressRange(*HighPc, MyInfo.AddrAdjust);
  445. Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust);
  446. return Flags;
  447. }
  448. /// Check if a DIE should be kept.
  449. /// \returns updated TraversalFlags.
  450. unsigned DWARFLinker::shouldKeepDIE(AddressesMap &RelocMgr, RangesTy &Ranges,
  451. const DWARFDie &DIE, const DWARFFile &File,
  452. CompileUnit &Unit,
  453. CompileUnit::DIEInfo &MyInfo,
  454. unsigned Flags) {
  455. switch (DIE.getTag()) {
  456. case dwarf::DW_TAG_constant:
  457. case dwarf::DW_TAG_variable:
  458. return shouldKeepVariableDIE(RelocMgr, DIE, MyInfo, Flags);
  459. case dwarf::DW_TAG_subprogram:
  460. case dwarf::DW_TAG_label:
  461. return shouldKeepSubprogramDIE(RelocMgr, Ranges, DIE, File, Unit, MyInfo,
  462. Flags);
  463. case dwarf::DW_TAG_base_type:
  464. // DWARF Expressions may reference basic types, but scanning them
  465. // is expensive. Basic types are tiny, so just keep all of them.
  466. case dwarf::DW_TAG_imported_module:
  467. case dwarf::DW_TAG_imported_declaration:
  468. case dwarf::DW_TAG_imported_unit:
  469. // We always want to keep these.
  470. return Flags | TF_Keep;
  471. default:
  472. break;
  473. }
  474. return Flags;
  475. }
  476. /// Helper that updates the completeness of the current DIE based on the
  477. /// completeness of one of its children. It depends on the incompleteness of
  478. /// the children already being computed.
  479. static void updateChildIncompleteness(const DWARFDie &Die, CompileUnit &CU,
  480. CompileUnit::DIEInfo &ChildInfo) {
  481. switch (Die.getTag()) {
  482. case dwarf::DW_TAG_structure_type:
  483. case dwarf::DW_TAG_class_type:
  484. break;
  485. default:
  486. return;
  487. }
  488. CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
  489. if (ChildInfo.Incomplete || ChildInfo.Prune)
  490. MyInfo.Incomplete = true;
  491. }
  492. /// Helper that updates the completeness of the current DIE based on the
  493. /// completeness of the DIEs it references. It depends on the incompleteness of
  494. /// the referenced DIE already being computed.
  495. static void updateRefIncompleteness(const DWARFDie &Die, CompileUnit &CU,
  496. CompileUnit::DIEInfo &RefInfo) {
  497. switch (Die.getTag()) {
  498. case dwarf::DW_TAG_typedef:
  499. case dwarf::DW_TAG_member:
  500. case dwarf::DW_TAG_reference_type:
  501. case dwarf::DW_TAG_ptr_to_member_type:
  502. case dwarf::DW_TAG_pointer_type:
  503. break;
  504. default:
  505. return;
  506. }
  507. CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
  508. if (MyInfo.Incomplete)
  509. return;
  510. if (RefInfo.Incomplete)
  511. MyInfo.Incomplete = true;
  512. }
  513. /// Look at the children of the given DIE and decide whether they should be
  514. /// kept.
  515. void DWARFLinker::lookForChildDIEsToKeep(
  516. const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
  517. SmallVectorImpl<WorklistItem> &Worklist) {
  518. // The TF_ParentWalk flag tells us that we are currently walking up the
  519. // parent chain of a required DIE, and we don't want to mark all the children
  520. // of the parents as kept (consider for example a DW_TAG_namespace node in
  521. // the parent chain). There are however a set of DIE types for which we want
  522. // to ignore that directive and still walk their children.
  523. if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
  524. Flags &= ~DWARFLinker::TF_ParentWalk;
  525. // We're finished if this DIE has no children or we're walking the parent
  526. // chain.
  527. if (!Die.hasChildren() || (Flags & DWARFLinker::TF_ParentWalk))
  528. return;
  529. // Add children in reverse order to the worklist to effectively process them
  530. // in order.
  531. for (auto Child : reverse(Die.children())) {
  532. // Add a worklist item before every child to calculate incompleteness right
  533. // after the current child is processed.
  534. CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
  535. Worklist.emplace_back(Die, CU, WorklistItemType::UpdateChildIncompleteness,
  536. &ChildInfo);
  537. Worklist.emplace_back(Child, CU, Flags);
  538. }
  539. }
  540. /// Look at DIEs referenced by the given DIE and decide whether they should be
  541. /// kept. All DIEs referenced though attributes should be kept.
  542. void DWARFLinker::lookForRefDIEsToKeep(
  543. const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
  544. const UnitListTy &Units, const DWARFFile &File,
  545. SmallVectorImpl<WorklistItem> &Worklist) {
  546. bool UseOdr = (Flags & DWARFLinker::TF_DependencyWalk)
  547. ? (Flags & DWARFLinker::TF_ODR)
  548. : CU.hasODR();
  549. DWARFUnit &Unit = CU.getOrigUnit();
  550. DWARFDataExtractor Data = Unit.getDebugInfoExtractor();
  551. const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
  552. uint64_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
  553. SmallVector<std::pair<DWARFDie, CompileUnit &>, 4> ReferencedDIEs;
  554. for (const auto &AttrSpec : Abbrev->attributes()) {
  555. DWARFFormValue Val(AttrSpec.Form);
  556. if (!Val.isFormClass(DWARFFormValue::FC_Reference) ||
  557. AttrSpec.Attr == dwarf::DW_AT_sibling) {
  558. DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
  559. Unit.getFormParams());
  560. continue;
  561. }
  562. Val.extractValue(Data, &Offset, Unit.getFormParams(), &Unit);
  563. CompileUnit *ReferencedCU;
  564. if (auto RefDie =
  565. resolveDIEReference(File, Units, Val, Die, ReferencedCU)) {
  566. CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefDie);
  567. bool IsModuleRef = Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() &&
  568. Info.Ctxt->isDefinedInClangModule();
  569. // If the referenced DIE has a DeclContext that has already been
  570. // emitted, then do not keep the one in this CU. We'll link to
  571. // the canonical DIE in cloneDieReferenceAttribute.
  572. //
  573. // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
  574. // be necessary and could be advantageously replaced by
  575. // ReferencedCU->hasODR() && CU.hasODR().
  576. //
  577. // FIXME: compatibility with dsymutil-classic. There is no
  578. // reason not to unique ref_addr references.
  579. if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && (UseOdr || IsModuleRef) &&
  580. Info.Ctxt &&
  581. Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
  582. Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
  583. continue;
  584. // Keep a module forward declaration if there is no definition.
  585. if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
  586. Info.Ctxt->getCanonicalDIEOffset()))
  587. Info.Prune = false;
  588. ReferencedDIEs.emplace_back(RefDie, *ReferencedCU);
  589. }
  590. }
  591. unsigned ODRFlag = UseOdr ? DWARFLinker::TF_ODR : 0;
  592. // Add referenced DIEs in reverse order to the worklist to effectively
  593. // process them in order.
  594. for (auto &P : reverse(ReferencedDIEs)) {
  595. // Add a worklist item before every child to calculate incompleteness right
  596. // after the current child is processed.
  597. CompileUnit::DIEInfo &Info = P.second.getInfo(P.first);
  598. Worklist.emplace_back(Die, CU, WorklistItemType::UpdateRefIncompleteness,
  599. &Info);
  600. Worklist.emplace_back(P.first, P.second,
  601. DWARFLinker::TF_Keep |
  602. DWARFLinker::TF_DependencyWalk | ODRFlag);
  603. }
  604. }
  605. /// Look at the parent of the given DIE and decide whether they should be kept.
  606. void DWARFLinker::lookForParentDIEsToKeep(
  607. unsigned AncestorIdx, CompileUnit &CU, unsigned Flags,
  608. SmallVectorImpl<WorklistItem> &Worklist) {
  609. // Stop if we encounter an ancestor that's already marked as kept.
  610. if (CU.getInfo(AncestorIdx).Keep)
  611. return;
  612. DWARFUnit &Unit = CU.getOrigUnit();
  613. DWARFDie ParentDIE = Unit.getDIEAtIndex(AncestorIdx);
  614. Worklist.emplace_back(CU.getInfo(AncestorIdx).ParentIdx, CU, Flags);
  615. Worklist.emplace_back(ParentDIE, CU, Flags);
  616. }
  617. /// Recursively walk the \p DIE tree and look for DIEs to keep. Store that
  618. /// information in \p CU's DIEInfo.
  619. ///
  620. /// This function is the entry point of the DIE selection algorithm. It is
  621. /// expected to walk the DIE tree in file order and (though the mediation of
  622. /// its helper) call hasValidRelocation() on each DIE that might be a 'root
  623. /// DIE' (See DwarfLinker class comment).
  624. ///
  625. /// While walking the dependencies of root DIEs, this function is also called,
  626. /// but during these dependency walks the file order is not respected. The
  627. /// TF_DependencyWalk flag tells us which kind of traversal we are currently
  628. /// doing.
  629. ///
  630. /// The recursive algorithm is implemented iteratively as a work list because
  631. /// very deep recursion could exhaust the stack for large projects. The work
  632. /// list acts as a scheduler for different types of work that need to be
  633. /// performed.
  634. ///
  635. /// The recursive nature of the algorithm is simulated by running the "main"
  636. /// algorithm (LookForDIEsToKeep) followed by either looking at more DIEs
  637. /// (LookForChildDIEsToKeep, LookForRefDIEsToKeep, LookForParentDIEsToKeep) or
  638. /// fixing up a computed property (UpdateChildIncompleteness,
  639. /// UpdateRefIncompleteness).
  640. ///
  641. /// The return value indicates whether the DIE is incomplete.
  642. void DWARFLinker::lookForDIEsToKeep(AddressesMap &AddressesMap,
  643. RangesTy &Ranges, const UnitListTy &Units,
  644. const DWARFDie &Die, const DWARFFile &File,
  645. CompileUnit &Cu, unsigned Flags) {
  646. // LIFO work list.
  647. SmallVector<WorklistItem, 4> Worklist;
  648. Worklist.emplace_back(Die, Cu, Flags);
  649. while (!Worklist.empty()) {
  650. WorklistItem Current = Worklist.pop_back_val();
  651. // Look at the worklist type to decide what kind of work to perform.
  652. switch (Current.Type) {
  653. case WorklistItemType::UpdateChildIncompleteness:
  654. updateChildIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
  655. continue;
  656. case WorklistItemType::UpdateRefIncompleteness:
  657. updateRefIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
  658. continue;
  659. case WorklistItemType::LookForChildDIEsToKeep:
  660. lookForChildDIEsToKeep(Current.Die, Current.CU, Current.Flags, Worklist);
  661. continue;
  662. case WorklistItemType::LookForRefDIEsToKeep:
  663. lookForRefDIEsToKeep(Current.Die, Current.CU, Current.Flags, Units, File,
  664. Worklist);
  665. continue;
  666. case WorklistItemType::LookForParentDIEsToKeep:
  667. lookForParentDIEsToKeep(Current.AncestorIdx, Current.CU, Current.Flags,
  668. Worklist);
  669. continue;
  670. case WorklistItemType::LookForDIEsToKeep:
  671. break;
  672. }
  673. unsigned Idx = Current.CU.getOrigUnit().getDIEIndex(Current.Die);
  674. CompileUnit::DIEInfo &MyInfo = Current.CU.getInfo(Idx);
  675. if (MyInfo.Prune)
  676. continue;
  677. // If the Keep flag is set, we are marking a required DIE's dependencies.
  678. // If our target is already marked as kept, we're all set.
  679. bool AlreadyKept = MyInfo.Keep;
  680. if ((Current.Flags & TF_DependencyWalk) && AlreadyKept)
  681. continue;
  682. // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
  683. // because it would screw up the relocation finding logic.
  684. if (!(Current.Flags & TF_DependencyWalk))
  685. Current.Flags = shouldKeepDIE(AddressesMap, Ranges, Current.Die, File,
  686. Current.CU, MyInfo, Current.Flags);
  687. // Finish by looking for child DIEs. Because of the LIFO worklist we need
  688. // to schedule that work before any subsequent items are added to the
  689. // worklist.
  690. Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
  691. WorklistItemType::LookForChildDIEsToKeep);
  692. if (AlreadyKept || !(Current.Flags & TF_Keep))
  693. continue;
  694. // If it is a newly kept DIE mark it as well as all its dependencies as
  695. // kept.
  696. MyInfo.Keep = true;
  697. // We're looking for incomplete types.
  698. MyInfo.Incomplete =
  699. Current.Die.getTag() != dwarf::DW_TAG_subprogram &&
  700. Current.Die.getTag() != dwarf::DW_TAG_member &&
  701. dwarf::toUnsigned(Current.Die.find(dwarf::DW_AT_declaration), 0);
  702. // After looking at the parent chain, look for referenced DIEs. Because of
  703. // the LIFO worklist we need to schedule that work before any subsequent
  704. // items are added to the worklist.
  705. Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
  706. WorklistItemType::LookForRefDIEsToKeep);
  707. bool UseOdr = (Current.Flags & TF_DependencyWalk) ? (Current.Flags & TF_ODR)
  708. : Current.CU.hasODR();
  709. unsigned ODRFlag = UseOdr ? TF_ODR : 0;
  710. unsigned ParFlags = TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag;
  711. // Now schedule the parent walk.
  712. Worklist.emplace_back(MyInfo.ParentIdx, Current.CU, ParFlags);
  713. }
  714. }
  715. /// Assign an abbreviation number to \p Abbrev.
  716. ///
  717. /// Our DIEs get freed after every DebugMapObject has been processed,
  718. /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
  719. /// the instances hold by the DIEs. When we encounter an abbreviation
  720. /// that we don't know, we create a permanent copy of it.
  721. void DWARFLinker::assignAbbrev(DIEAbbrev &Abbrev) {
  722. // Check the set for priors.
  723. FoldingSetNodeID ID;
  724. Abbrev.Profile(ID);
  725. void *InsertToken;
  726. DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
  727. // If it's newly added.
  728. if (InSet) {
  729. // Assign existing abbreviation number.
  730. Abbrev.setNumber(InSet->getNumber());
  731. } else {
  732. // Add to abbreviation list.
  733. Abbreviations.push_back(
  734. std::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
  735. for (const auto &Attr : Abbrev.getData())
  736. Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
  737. AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
  738. // Assign the unique abbreviation number.
  739. Abbrev.setNumber(Abbreviations.size());
  740. Abbreviations.back()->setNumber(Abbreviations.size());
  741. }
  742. }
  743. unsigned DWARFLinker::DIECloner::cloneStringAttribute(
  744. DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
  745. const DWARFUnit &U, OffsetsStringPool &StringPool, AttributesInfo &Info) {
  746. Optional<const char *> String = Val.getAsCString();
  747. if (!String)
  748. return 0;
  749. // Switch everything to out of line strings.
  750. auto StringEntry = StringPool.getEntry(*String);
  751. // Update attributes info.
  752. if (AttrSpec.Attr == dwarf::DW_AT_name)
  753. Info.Name = StringEntry;
  754. else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
  755. AttrSpec.Attr == dwarf::DW_AT_linkage_name)
  756. Info.MangledName = StringEntry;
  757. Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
  758. DIEInteger(StringEntry.getOffset()));
  759. return 4;
  760. }
  761. unsigned DWARFLinker::DIECloner::cloneDieReferenceAttribute(
  762. DIE &Die, const DWARFDie &InputDIE, AttributeSpec AttrSpec,
  763. unsigned AttrSize, const DWARFFormValue &Val, const DWARFFile &File,
  764. CompileUnit &Unit) {
  765. const DWARFUnit &U = Unit.getOrigUnit();
  766. uint64_t Ref = *Val.getAsReference();
  767. DIE *NewRefDie = nullptr;
  768. CompileUnit *RefUnit = nullptr;
  769. DeclContext *Ctxt = nullptr;
  770. DWARFDie RefDie =
  771. Linker.resolveDIEReference(File, CompileUnits, Val, InputDIE, RefUnit);
  772. // If the referenced DIE is not found, drop the attribute.
  773. if (!RefDie || AttrSpec.Attr == dwarf::DW_AT_sibling)
  774. return 0;
  775. CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(RefDie);
  776. // If we already have emitted an equivalent DeclContext, just point
  777. // at it.
  778. if (isODRAttribute(AttrSpec.Attr)) {
  779. Ctxt = RefInfo.Ctxt;
  780. if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
  781. DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
  782. Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
  783. dwarf::DW_FORM_ref_addr, Attr);
  784. return U.getRefAddrByteSize();
  785. }
  786. }
  787. if (!RefInfo.Clone) {
  788. assert(Ref > InputDIE.getOffset());
  789. // We haven't cloned this DIE yet. Just create an empty one and
  790. // store it. It'll get really cloned when we process it.
  791. RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag()));
  792. }
  793. NewRefDie = RefInfo.Clone;
  794. if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
  795. (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
  796. // We cannot currently rely on a DIEEntry to emit ref_addr
  797. // references, because the implementation calls back to DwarfDebug
  798. // to find the unit offset. (We don't have a DwarfDebug)
  799. // FIXME: we should be able to design DIEEntry reliance on
  800. // DwarfDebug away.
  801. uint64_t Attr;
  802. if (Ref < InputDIE.getOffset()) {
  803. // We must have already cloned that DIE.
  804. uint32_t NewRefOffset =
  805. RefUnit->getStartOffset() + NewRefDie->getOffset();
  806. Attr = NewRefOffset;
  807. Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
  808. dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
  809. } else {
  810. // A forward reference. Note and fixup later.
  811. Attr = 0xBADDEF;
  812. Unit.noteForwardReference(
  813. NewRefDie, RefUnit, Ctxt,
  814. Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
  815. dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
  816. }
  817. return U.getRefAddrByteSize();
  818. }
  819. Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
  820. dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
  821. return AttrSize;
  822. }
  823. void DWARFLinker::DIECloner::cloneExpression(
  824. DataExtractor &Data, DWARFExpression Expression, const DWARFFile &File,
  825. CompileUnit &Unit, SmallVectorImpl<uint8_t> &OutputBuffer) {
  826. using Encoding = DWARFExpression::Operation::Encoding;
  827. uint64_t OpOffset = 0;
  828. for (auto &Op : Expression) {
  829. auto Description = Op.getDescription();
  830. // DW_OP_const_type is variable-length and has 3
  831. // operands. DWARFExpression thus far only supports 2.
  832. auto Op0 = Description.Op[0];
  833. auto Op1 = Description.Op[1];
  834. if ((Op0 == Encoding::BaseTypeRef && Op1 != Encoding::SizeNA) ||
  835. (Op1 == Encoding::BaseTypeRef && Op0 != Encoding::Size1))
  836. Linker.reportWarning("Unsupported DW_OP encoding.", File);
  837. if ((Op0 == Encoding::BaseTypeRef && Op1 == Encoding::SizeNA) ||
  838. (Op1 == Encoding::BaseTypeRef && Op0 == Encoding::Size1)) {
  839. // This code assumes that the other non-typeref operand fits into 1 byte.
  840. assert(OpOffset < Op.getEndOffset());
  841. uint32_t ULEBsize = Op.getEndOffset() - OpOffset - 1;
  842. assert(ULEBsize <= 16);
  843. // Copy over the operation.
  844. OutputBuffer.push_back(Op.getCode());
  845. uint64_t RefOffset;
  846. if (Op1 == Encoding::SizeNA) {
  847. RefOffset = Op.getRawOperand(0);
  848. } else {
  849. OutputBuffer.push_back(Op.getRawOperand(0));
  850. RefOffset = Op.getRawOperand(1);
  851. }
  852. uint32_t Offset = 0;
  853. // Look up the base type. For DW_OP_convert, the operand may be 0 to
  854. // instead indicate the generic type. The same holds for
  855. // DW_OP_reinterpret, which is currently not supported.
  856. if (RefOffset > 0 || Op.getCode() != dwarf::DW_OP_convert) {
  857. auto RefDie = Unit.getOrigUnit().getDIEForOffset(RefOffset);
  858. CompileUnit::DIEInfo &Info = Unit.getInfo(RefDie);
  859. if (DIE *Clone = Info.Clone)
  860. Offset = Clone->getOffset();
  861. else
  862. Linker.reportWarning(
  863. "base type ref doesn't point to DW_TAG_base_type.", File);
  864. }
  865. uint8_t ULEB[16];
  866. unsigned RealSize = encodeULEB128(Offset, ULEB, ULEBsize);
  867. if (RealSize > ULEBsize) {
  868. // Emit the generic type as a fallback.
  869. RealSize = encodeULEB128(0, ULEB, ULEBsize);
  870. Linker.reportWarning("base type ref doesn't fit.", File);
  871. }
  872. assert(RealSize == ULEBsize && "padding failed");
  873. ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize);
  874. OutputBuffer.append(ULEBbytes.begin(), ULEBbytes.end());
  875. } else {
  876. // Copy over everything else unmodified.
  877. StringRef Bytes = Data.getData().slice(OpOffset, Op.getEndOffset());
  878. OutputBuffer.append(Bytes.begin(), Bytes.end());
  879. }
  880. OpOffset = Op.getEndOffset();
  881. }
  882. }
  883. unsigned DWARFLinker::DIECloner::cloneBlockAttribute(
  884. DIE &Die, const DWARFFile &File, CompileUnit &Unit, AttributeSpec AttrSpec,
  885. const DWARFFormValue &Val, unsigned AttrSize, bool IsLittleEndian) {
  886. DIEValueList *Attr;
  887. DIEValue Value;
  888. DIELoc *Loc = nullptr;
  889. DIEBlock *Block = nullptr;
  890. if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
  891. Loc = new (DIEAlloc) DIELoc;
  892. Linker.DIELocs.push_back(Loc);
  893. } else {
  894. Block = new (DIEAlloc) DIEBlock;
  895. Linker.DIEBlocks.push_back(Block);
  896. }
  897. Attr = Loc ? static_cast<DIEValueList *>(Loc)
  898. : static_cast<DIEValueList *>(Block);
  899. if (Loc)
  900. Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
  901. dwarf::Form(AttrSpec.Form), Loc);
  902. else
  903. Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
  904. dwarf::Form(AttrSpec.Form), Block);
  905. // If the block is a DWARF Expression, clone it into the temporary
  906. // buffer using cloneExpression(), otherwise copy the data directly.
  907. SmallVector<uint8_t, 32> Buffer;
  908. ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
  909. if (DWARFAttribute::mayHaveLocationDescription(AttrSpec.Attr) &&
  910. (Val.isFormClass(DWARFFormValue::FC_Block) ||
  911. Val.isFormClass(DWARFFormValue::FC_Exprloc))) {
  912. DWARFUnit &OrigUnit = Unit.getOrigUnit();
  913. DataExtractor Data(StringRef((const char *)Bytes.data(), Bytes.size()),
  914. IsLittleEndian, OrigUnit.getAddressByteSize());
  915. DWARFExpression Expr(Data, OrigUnit.getAddressByteSize(),
  916. OrigUnit.getFormParams().Format);
  917. cloneExpression(Data, Expr, File, Unit, Buffer);
  918. Bytes = Buffer;
  919. }
  920. for (auto Byte : Bytes)
  921. Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
  922. dwarf::DW_FORM_data1, DIEInteger(Byte));
  923. // FIXME: If DIEBlock and DIELoc just reuses the Size field of
  924. // the DIE class, this "if" could be replaced by
  925. // Attr->setSize(Bytes.size()).
  926. if (Loc)
  927. Loc->setSize(Bytes.size());
  928. else
  929. Block->setSize(Bytes.size());
  930. Die.addValue(DIEAlloc, Value);
  931. return AttrSize;
  932. }
  933. unsigned DWARFLinker::DIECloner::cloneAddressAttribute(
  934. DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
  935. const CompileUnit &Unit, AttributesInfo &Info) {
  936. dwarf::Form Form = AttrSpec.Form;
  937. uint64_t Addr = *Val.getAsAddress();
  938. if (LLVM_UNLIKELY(Linker.Options.Update)) {
  939. if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
  940. Info.HasLowPc = true;
  941. Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
  942. dwarf::Form(AttrSpec.Form), DIEInteger(Addr));
  943. return Unit.getOrigUnit().getAddressByteSize();
  944. }
  945. if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
  946. if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
  947. Die.getTag() == dwarf::DW_TAG_lexical_block)
  948. // The low_pc of a block or inline subroutine might get
  949. // relocated because it happens to match the low_pc of the
  950. // enclosing subprogram. To prevent issues with that, always use
  951. // the low_pc from the input DIE if relocations have been applied.
  952. Addr = (Info.OrigLowPc != std::numeric_limits<uint64_t>::max()
  953. ? Info.OrigLowPc
  954. : Addr) +
  955. Info.PCOffset;
  956. else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
  957. Addr = Unit.getLowPc();
  958. if (Addr == std::numeric_limits<uint64_t>::max())
  959. return 0;
  960. }
  961. Info.HasLowPc = true;
  962. } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
  963. if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
  964. if (uint64_t HighPc = Unit.getHighPc())
  965. Addr = HighPc;
  966. else
  967. return 0;
  968. } else
  969. // If we have a high_pc recorded for the input DIE, use
  970. // it. Otherwise (when no relocations where applied) just use the
  971. // one we just decoded.
  972. Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
  973. } else if (AttrSpec.Attr == dwarf::DW_AT_call_return_pc) {
  974. // Relocate a return PC address within a call site entry.
  975. if (Die.getTag() == dwarf::DW_TAG_call_site)
  976. Addr = (Info.OrigCallReturnPc ? Info.OrigCallReturnPc : Addr) +
  977. Info.PCOffset;
  978. } else if (AttrSpec.Attr == dwarf::DW_AT_call_pc) {
  979. // Relocate the address of a branch instruction within a call site entry.
  980. if (Die.getTag() == dwarf::DW_TAG_call_site)
  981. Addr = (Info.OrigCallPc ? Info.OrigCallPc : Addr) + Info.PCOffset;
  982. }
  983. // If this is an indexed address emit the relocated address.
  984. if (Form == dwarf::DW_FORM_addrx) {
  985. if (llvm::Expected<uint64_t> RelocAddr =
  986. ObjFile.Addresses->relocateIndexedAddr(Addr)) {
  987. Addr = *RelocAddr;
  988. Form = dwarf::DW_FORM_addr;
  989. } else {
  990. Linker.reportWarning(toString(RelocAddr.takeError()), ObjFile);
  991. }
  992. }
  993. Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
  994. static_cast<dwarf::Form>(Form), DIEInteger(Addr));
  995. return Unit.getOrigUnit().getAddressByteSize();
  996. }
  997. unsigned DWARFLinker::DIECloner::cloneScalarAttribute(
  998. DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
  999. CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val,
  1000. unsigned AttrSize, AttributesInfo &Info) {
  1001. uint64_t Value;
  1002. if (LLVM_UNLIKELY(Linker.Options.Update)) {
  1003. if (auto OptionalValue = Val.getAsUnsignedConstant())
  1004. Value = *OptionalValue;
  1005. else if (auto OptionalValue = Val.getAsSignedConstant())
  1006. Value = *OptionalValue;
  1007. else if (auto OptionalValue = Val.getAsSectionOffset())
  1008. Value = *OptionalValue;
  1009. else {
  1010. Linker.reportWarning(
  1011. "Unsupported scalar attribute form. Dropping attribute.", File,
  1012. &InputDIE);
  1013. return 0;
  1014. }
  1015. if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
  1016. Info.IsDeclaration = true;
  1017. Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
  1018. dwarf::Form(AttrSpec.Form), DIEInteger(Value));
  1019. return AttrSize;
  1020. }
  1021. if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
  1022. Die.getTag() == dwarf::DW_TAG_compile_unit) {
  1023. if (Unit.getLowPc() == -1ULL)
  1024. return 0;
  1025. // Dwarf >= 4 high_pc is an size, not an address.
  1026. Value = Unit.getHighPc() - Unit.getLowPc();
  1027. } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
  1028. Value = *Val.getAsSectionOffset();
  1029. else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
  1030. Value = *Val.getAsSignedConstant();
  1031. else if (auto OptionalValue = Val.getAsUnsignedConstant())
  1032. Value = *OptionalValue;
  1033. else {
  1034. Linker.reportWarning(
  1035. "Unsupported scalar attribute form. Dropping attribute.", File,
  1036. &InputDIE);
  1037. return 0;
  1038. }
  1039. PatchLocation Patch =
  1040. Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
  1041. dwarf::Form(AttrSpec.Form), DIEInteger(Value));
  1042. if (AttrSpec.Attr == dwarf::DW_AT_ranges) {
  1043. Unit.noteRangeAttribute(Die, Patch);
  1044. Info.HasRanges = true;
  1045. }
  1046. // A more generic way to check for location attributes would be
  1047. // nice, but it's very unlikely that any other attribute needs a
  1048. // location list.
  1049. // FIXME: use DWARFAttribute::mayHaveLocationDescription().
  1050. else if (AttrSpec.Attr == dwarf::DW_AT_location ||
  1051. AttrSpec.Attr == dwarf::DW_AT_frame_base) {
  1052. Unit.noteLocationAttribute(Patch, Info.PCOffset);
  1053. } else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
  1054. Info.IsDeclaration = true;
  1055. return AttrSize;
  1056. }
  1057. /// Clone \p InputDIE's attribute described by \p AttrSpec with
  1058. /// value \p Val, and add it to \p Die.
  1059. /// \returns the size of the cloned attribute.
  1060. unsigned DWARFLinker::DIECloner::cloneAttribute(
  1061. DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
  1062. CompileUnit &Unit, OffsetsStringPool &StringPool, const DWARFFormValue &Val,
  1063. const AttributeSpec AttrSpec, unsigned AttrSize, AttributesInfo &Info,
  1064. bool IsLittleEndian) {
  1065. const DWARFUnit &U = Unit.getOrigUnit();
  1066. switch (AttrSpec.Form) {
  1067. case dwarf::DW_FORM_strp:
  1068. case dwarf::DW_FORM_string:
  1069. case dwarf::DW_FORM_strx:
  1070. case dwarf::DW_FORM_strx1:
  1071. case dwarf::DW_FORM_strx2:
  1072. case dwarf::DW_FORM_strx3:
  1073. case dwarf::DW_FORM_strx4:
  1074. return cloneStringAttribute(Die, AttrSpec, Val, U, StringPool, Info);
  1075. case dwarf::DW_FORM_ref_addr:
  1076. case dwarf::DW_FORM_ref1:
  1077. case dwarf::DW_FORM_ref2:
  1078. case dwarf::DW_FORM_ref4:
  1079. case dwarf::DW_FORM_ref8:
  1080. return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
  1081. File, Unit);
  1082. case dwarf::DW_FORM_block:
  1083. case dwarf::DW_FORM_block1:
  1084. case dwarf::DW_FORM_block2:
  1085. case dwarf::DW_FORM_block4:
  1086. case dwarf::DW_FORM_exprloc:
  1087. return cloneBlockAttribute(Die, File, Unit, AttrSpec, Val, AttrSize,
  1088. IsLittleEndian);
  1089. case dwarf::DW_FORM_addr:
  1090. case dwarf::DW_FORM_addrx:
  1091. return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
  1092. case dwarf::DW_FORM_data1:
  1093. case dwarf::DW_FORM_data2:
  1094. case dwarf::DW_FORM_data4:
  1095. case dwarf::DW_FORM_data8:
  1096. case dwarf::DW_FORM_udata:
  1097. case dwarf::DW_FORM_sdata:
  1098. case dwarf::DW_FORM_sec_offset:
  1099. case dwarf::DW_FORM_flag:
  1100. case dwarf::DW_FORM_flag_present:
  1101. return cloneScalarAttribute(Die, InputDIE, File, Unit, AttrSpec, Val,
  1102. AttrSize, Info);
  1103. default:
  1104. Linker.reportWarning("Unsupported attribute form " +
  1105. dwarf::FormEncodingString(AttrSpec.Form) +
  1106. " in cloneAttribute. Dropping.",
  1107. File, &InputDIE);
  1108. }
  1109. return 0;
  1110. }
  1111. static bool isObjCSelector(StringRef Name) {
  1112. return Name.size() > 2 && (Name[0] == '-' || Name[0] == '+') &&
  1113. (Name[1] == '[');
  1114. }
  1115. void DWARFLinker::DIECloner::addObjCAccelerator(CompileUnit &Unit,
  1116. const DIE *Die,
  1117. DwarfStringPoolEntryRef Name,
  1118. OffsetsStringPool &StringPool,
  1119. bool SkipPubSection) {
  1120. assert(isObjCSelector(Name.getString()) && "not an objc selector");
  1121. // Objective C method or class function.
  1122. // "- [Class(Category) selector :withArg ...]"
  1123. StringRef ClassNameStart(Name.getString().drop_front(2));
  1124. size_t FirstSpace = ClassNameStart.find(' ');
  1125. if (FirstSpace == StringRef::npos)
  1126. return;
  1127. StringRef SelectorStart(ClassNameStart.data() + FirstSpace + 1);
  1128. if (!SelectorStart.size())
  1129. return;
  1130. StringRef Selector(SelectorStart.data(), SelectorStart.size() - 1);
  1131. Unit.addNameAccelerator(Die, StringPool.getEntry(Selector), SkipPubSection);
  1132. // Add an entry for the class name that points to this
  1133. // method/class function.
  1134. StringRef ClassName(ClassNameStart.data(), FirstSpace);
  1135. Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassName), SkipPubSection);
  1136. if (ClassName[ClassName.size() - 1] == ')') {
  1137. size_t OpenParens = ClassName.find('(');
  1138. if (OpenParens != StringRef::npos) {
  1139. StringRef ClassNameNoCategory(ClassName.data(), OpenParens);
  1140. Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassNameNoCategory),
  1141. SkipPubSection);
  1142. std::string MethodNameNoCategory(Name.getString().data(), OpenParens + 2);
  1143. // FIXME: The missing space here may be a bug, but
  1144. // dsymutil-classic also does it this way.
  1145. MethodNameNoCategory.append(std::string(SelectorStart));
  1146. Unit.addNameAccelerator(Die, StringPool.getEntry(MethodNameNoCategory),
  1147. SkipPubSection);
  1148. }
  1149. }
  1150. }
  1151. static bool
  1152. shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
  1153. uint16_t Tag, bool InDebugMap, bool SkipPC,
  1154. bool InFunctionScope) {
  1155. switch (AttrSpec.Attr) {
  1156. default:
  1157. return false;
  1158. case dwarf::DW_AT_low_pc:
  1159. case dwarf::DW_AT_high_pc:
  1160. case dwarf::DW_AT_ranges:
  1161. return SkipPC;
  1162. case dwarf::DW_AT_str_offsets_base:
  1163. // FIXME: Use the string offset table with Dwarf 5.
  1164. return true;
  1165. case dwarf::DW_AT_location:
  1166. case dwarf::DW_AT_frame_base:
  1167. // FIXME: for some reason dsymutil-classic keeps the location attributes
  1168. // when they are of block type (i.e. not location lists). This is totally
  1169. // wrong for globals where we will keep a wrong address. It is mostly
  1170. // harmless for locals, but there is no point in keeping these anyway when
  1171. // the function wasn't linked.
  1172. return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
  1173. !InDebugMap)) &&
  1174. !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
  1175. }
  1176. }
  1177. DIE *DWARFLinker::DIECloner::cloneDIE(const DWARFDie &InputDIE,
  1178. const DWARFFile &File, CompileUnit &Unit,
  1179. OffsetsStringPool &StringPool,
  1180. int64_t PCOffset, uint32_t OutOffset,
  1181. unsigned Flags, bool IsLittleEndian,
  1182. DIE *Die) {
  1183. DWARFUnit &U = Unit.getOrigUnit();
  1184. unsigned Idx = U.getDIEIndex(InputDIE);
  1185. CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
  1186. // Should the DIE appear in the output?
  1187. if (!Unit.getInfo(Idx).Keep)
  1188. return nullptr;
  1189. uint64_t Offset = InputDIE.getOffset();
  1190. assert(!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE");
  1191. if (!Die) {
  1192. // The DIE might have been already created by a forward reference
  1193. // (see cloneDieReferenceAttribute()).
  1194. if (!Info.Clone)
  1195. Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
  1196. Die = Info.Clone;
  1197. }
  1198. assert(Die->getTag() == InputDIE.getTag());
  1199. Die->setOffset(OutOffset);
  1200. if ((Unit.hasODR() || Unit.isClangModule()) && !Info.Incomplete &&
  1201. Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
  1202. Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
  1203. !Info.Ctxt->getCanonicalDIEOffset()) {
  1204. // We are about to emit a DIE that is the root of its own valid
  1205. // DeclContext tree. Make the current offset the canonical offset
  1206. // for this context.
  1207. Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
  1208. }
  1209. // Extract and clone every attribute.
  1210. DWARFDataExtractor Data = U.getDebugInfoExtractor();
  1211. // Point to the next DIE (generally there is always at least a NULL
  1212. // entry after the current one). If this is a lone
  1213. // DW_TAG_compile_unit without any children, point to the next unit.
  1214. uint64_t NextOffset = (Idx + 1 < U.getNumDIEs())
  1215. ? U.getDIEAtIndex(Idx + 1).getOffset()
  1216. : U.getNextUnitOffset();
  1217. AttributesInfo AttrInfo;
  1218. // We could copy the data only if we need to apply a relocation to it. After
  1219. // testing, it seems there is no performance downside to doing the copy
  1220. // unconditionally, and it makes the code simpler.
  1221. SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
  1222. Data =
  1223. DWARFDataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
  1224. // Modify the copy with relocated addresses.
  1225. if (ObjFile.Addresses->areRelocationsResolved() &&
  1226. ObjFile.Addresses->applyValidRelocs(DIECopy, Offset,
  1227. Data.isLittleEndian())) {
  1228. // If we applied relocations, we store the value of high_pc that was
  1229. // potentially stored in the input DIE. If high_pc is an address
  1230. // (Dwarf version == 2), then it might have been relocated to a
  1231. // totally unrelated value (because the end address in the object
  1232. // file might be start address of another function which got moved
  1233. // independently by the linker). The computation of the actual
  1234. // high_pc value is done in cloneAddressAttribute().
  1235. AttrInfo.OrigHighPc =
  1236. dwarf::toAddress(InputDIE.find(dwarf::DW_AT_high_pc), 0);
  1237. // Also store the low_pc. It might get relocated in an
  1238. // inline_subprogram that happens at the beginning of its
  1239. // inlining function.
  1240. AttrInfo.OrigLowPc = dwarf::toAddress(InputDIE.find(dwarf::DW_AT_low_pc),
  1241. std::numeric_limits<uint64_t>::max());
  1242. AttrInfo.OrigCallReturnPc =
  1243. dwarf::toAddress(InputDIE.find(dwarf::DW_AT_call_return_pc), 0);
  1244. AttrInfo.OrigCallPc =
  1245. dwarf::toAddress(InputDIE.find(dwarf::DW_AT_call_pc), 0);
  1246. }
  1247. // Reset the Offset to 0 as we will be working on the local copy of
  1248. // the data.
  1249. Offset = 0;
  1250. const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
  1251. Offset += getULEB128Size(Abbrev->getCode());
  1252. // We are entering a subprogram. Get and propagate the PCOffset.
  1253. if (Die->getTag() == dwarf::DW_TAG_subprogram)
  1254. PCOffset = Info.AddrAdjust;
  1255. AttrInfo.PCOffset = PCOffset;
  1256. if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
  1257. Flags |= TF_InFunctionScope;
  1258. if (!Info.InDebugMap && LLVM_LIKELY(!Update))
  1259. Flags |= TF_SkipPC;
  1260. }
  1261. bool Copied = false;
  1262. for (const auto &AttrSpec : Abbrev->attributes()) {
  1263. if (LLVM_LIKELY(!Update) &&
  1264. shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
  1265. Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
  1266. DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
  1267. U.getFormParams());
  1268. // FIXME: dsymutil-classic keeps the old abbreviation around
  1269. // even if it's not used. We can remove this (and the copyAbbrev
  1270. // helper) as soon as bit-for-bit compatibility is not a goal anymore.
  1271. if (!Copied) {
  1272. copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
  1273. Copied = true;
  1274. }
  1275. continue;
  1276. }
  1277. DWARFFormValue Val(AttrSpec.Form);
  1278. uint64_t AttrSize = Offset;
  1279. Val.extractValue(Data, &Offset, U.getFormParams(), &U);
  1280. AttrSize = Offset - AttrSize;
  1281. OutOffset += cloneAttribute(*Die, InputDIE, File, Unit, StringPool, Val,
  1282. AttrSpec, AttrSize, AttrInfo, IsLittleEndian);
  1283. }
  1284. // Look for accelerator entries.
  1285. uint16_t Tag = InputDIE.getTag();
  1286. // FIXME: This is slightly wrong. An inline_subroutine without a
  1287. // low_pc, but with AT_ranges might be interesting to get into the
  1288. // accelerator tables too. For now stick with dsymutil's behavior.
  1289. if ((Info.InDebugMap || AttrInfo.HasLowPc || AttrInfo.HasRanges) &&
  1290. Tag != dwarf::DW_TAG_compile_unit &&
  1291. getDIENames(InputDIE, AttrInfo, StringPool,
  1292. Tag != dwarf::DW_TAG_inlined_subroutine)) {
  1293. if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
  1294. Unit.addNameAccelerator(Die, AttrInfo.MangledName,
  1295. Tag == dwarf::DW_TAG_inlined_subroutine);
  1296. if (AttrInfo.Name) {
  1297. if (AttrInfo.NameWithoutTemplate)
  1298. Unit.addNameAccelerator(Die, AttrInfo.NameWithoutTemplate,
  1299. /* SkipPubSection */ true);
  1300. Unit.addNameAccelerator(Die, AttrInfo.Name,
  1301. Tag == dwarf::DW_TAG_inlined_subroutine);
  1302. }
  1303. if (AttrInfo.Name && isObjCSelector(AttrInfo.Name.getString()))
  1304. addObjCAccelerator(Unit, Die, AttrInfo.Name, StringPool,
  1305. /* SkipPubSection =*/true);
  1306. } else if (Tag == dwarf::DW_TAG_namespace) {
  1307. if (!AttrInfo.Name)
  1308. AttrInfo.Name = StringPool.getEntry("(anonymous namespace)");
  1309. Unit.addNamespaceAccelerator(Die, AttrInfo.Name);
  1310. } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
  1311. getDIENames(InputDIE, AttrInfo, StringPool) && AttrInfo.Name &&
  1312. AttrInfo.Name.getString()[0]) {
  1313. uint32_t Hash = hashFullyQualifiedName(InputDIE, Unit, File);
  1314. uint64_t RuntimeLang =
  1315. dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_runtime_class))
  1316. .getValueOr(0);
  1317. bool ObjCClassIsImplementation =
  1318. (RuntimeLang == dwarf::DW_LANG_ObjC ||
  1319. RuntimeLang == dwarf::DW_LANG_ObjC_plus_plus) &&
  1320. dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_objc_complete_type))
  1321. .getValueOr(0);
  1322. Unit.addTypeAccelerator(Die, AttrInfo.Name, ObjCClassIsImplementation,
  1323. Hash);
  1324. }
  1325. // Determine whether there are any children that we want to keep.
  1326. bool HasChildren = false;
  1327. for (auto Child : InputDIE.children()) {
  1328. unsigned Idx = U.getDIEIndex(Child);
  1329. if (Unit.getInfo(Idx).Keep) {
  1330. HasChildren = true;
  1331. break;
  1332. }
  1333. }
  1334. DIEAbbrev NewAbbrev = Die->generateAbbrev();
  1335. if (HasChildren)
  1336. NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
  1337. // Assign a permanent abbrev number
  1338. Linker.assignAbbrev(NewAbbrev);
  1339. Die->setAbbrevNumber(NewAbbrev.getNumber());
  1340. // Add the size of the abbreviation number to the output offset.
  1341. OutOffset += getULEB128Size(Die->getAbbrevNumber());
  1342. if (!HasChildren) {
  1343. // Update our size.
  1344. Die->setSize(OutOffset - Die->getOffset());
  1345. return Die;
  1346. }
  1347. // Recursively clone children.
  1348. for (auto Child : InputDIE.children()) {
  1349. if (DIE *Clone = cloneDIE(Child, File, Unit, StringPool, PCOffset,
  1350. OutOffset, Flags, IsLittleEndian)) {
  1351. Die->addChild(Clone);
  1352. OutOffset = Clone->getOffset() + Clone->getSize();
  1353. }
  1354. }
  1355. // Account for the end of children marker.
  1356. OutOffset += sizeof(int8_t);
  1357. // Update our size.
  1358. Die->setSize(OutOffset - Die->getOffset());
  1359. return Die;
  1360. }
  1361. /// Patch the input object file relevant debug_ranges entries
  1362. /// and emit them in the output file. Update the relevant attributes
  1363. /// to point at the new entries.
  1364. void DWARFLinker::patchRangesForUnit(const CompileUnit &Unit,
  1365. DWARFContext &OrigDwarf,
  1366. const DWARFFile &File) const {
  1367. DWARFDebugRangeList RangeList;
  1368. const auto &FunctionRanges = Unit.getFunctionRanges();
  1369. unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
  1370. DWARFDataExtractor RangeExtractor(OrigDwarf.getDWARFObj(),
  1371. OrigDwarf.getDWARFObj().getRangesSection(),
  1372. OrigDwarf.isLittleEndian(), AddressSize);
  1373. auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
  1374. DWARFUnit &OrigUnit = Unit.getOrigUnit();
  1375. auto OrigUnitDie = OrigUnit.getUnitDIE(false);
  1376. uint64_t OrigLowPc =
  1377. dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc), -1ULL);
  1378. // Ranges addresses are based on the unit's low_pc. Compute the
  1379. // offset we need to apply to adapt to the new unit's low_pc.
  1380. int64_t UnitPcOffset = 0;
  1381. if (OrigLowPc != -1ULL)
  1382. UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
  1383. for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
  1384. uint64_t Offset = RangeAttribute.get();
  1385. RangeAttribute.set(TheDwarfEmitter->getRangesSectionSize());
  1386. if (Error E = RangeList.extract(RangeExtractor, &Offset)) {
  1387. llvm::consumeError(std::move(E));
  1388. reportWarning("invalid range list ignored.", File);
  1389. RangeList.clear();
  1390. }
  1391. const auto &Entries = RangeList.getEntries();
  1392. if (!Entries.empty()) {
  1393. const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
  1394. if (CurrRange == InvalidRange ||
  1395. First.StartAddress + OrigLowPc < CurrRange.start() ||
  1396. First.StartAddress + OrigLowPc >= CurrRange.stop()) {
  1397. CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
  1398. if (CurrRange == InvalidRange ||
  1399. CurrRange.start() > First.StartAddress + OrigLowPc) {
  1400. reportWarning("no mapping for range.", File);
  1401. continue;
  1402. }
  1403. }
  1404. }
  1405. TheDwarfEmitter->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange,
  1406. Entries, AddressSize);
  1407. }
  1408. }
  1409. /// Generate the debug_aranges entries for \p Unit and if the
  1410. /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
  1411. /// contribution for this attribute.
  1412. /// FIXME: this could actually be done right in patchRangesForUnit,
  1413. /// but for the sake of initial bit-for-bit compatibility with legacy
  1414. /// dsymutil, we have to do it in a delayed pass.
  1415. void DWARFLinker::generateUnitRanges(CompileUnit &Unit) const {
  1416. auto Attr = Unit.getUnitRangesAttribute();
  1417. if (Attr)
  1418. Attr->set(TheDwarfEmitter->getRangesSectionSize());
  1419. TheDwarfEmitter->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
  1420. }
  1421. /// Insert the new line info sequence \p Seq into the current
  1422. /// set of already linked line info \p Rows.
  1423. static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
  1424. std::vector<DWARFDebugLine::Row> &Rows) {
  1425. if (Seq.empty())
  1426. return;
  1427. if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
  1428. llvm::append_range(Rows, Seq);
  1429. Seq.clear();
  1430. return;
  1431. }
  1432. object::SectionedAddress Front = Seq.front().Address;
  1433. auto InsertPoint = partition_point(
  1434. Rows, [=](const DWARFDebugLine::Row &O) { return O.Address < Front; });
  1435. // FIXME: this only removes the unneeded end_sequence if the
  1436. // sequences have been inserted in order. Using a global sort like
  1437. // described in patchLineTableForUnit() and delaying the end_sequene
  1438. // elimination to emitLineTableForUnit() we can get rid of all of them.
  1439. if (InsertPoint != Rows.end() && InsertPoint->Address == Front &&
  1440. InsertPoint->EndSequence) {
  1441. *InsertPoint = Seq.front();
  1442. Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
  1443. } else {
  1444. Rows.insert(InsertPoint, Seq.begin(), Seq.end());
  1445. }
  1446. Seq.clear();
  1447. }
  1448. static void patchStmtList(DIE &Die, DIEInteger Offset) {
  1449. for (auto &V : Die.values())
  1450. if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
  1451. V = DIEValue(V.getAttribute(), V.getForm(), Offset);
  1452. return;
  1453. }
  1454. llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
  1455. }
  1456. /// Extract the line table for \p Unit from \p OrigDwarf, and
  1457. /// recreate a relocated version of these for the address ranges that
  1458. /// are present in the binary.
  1459. void DWARFLinker::patchLineTableForUnit(CompileUnit &Unit,
  1460. DWARFContext &OrigDwarf,
  1461. const DWARFFile &File) {
  1462. DWARFDie CUDie = Unit.getOrigUnit().getUnitDIE();
  1463. auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list));
  1464. if (!StmtList)
  1465. return;
  1466. // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
  1467. if (auto *OutputDIE = Unit.getOutputUnitDIE())
  1468. patchStmtList(*OutputDIE,
  1469. DIEInteger(TheDwarfEmitter->getLineSectionSize()));
  1470. RangesTy &Ranges = File.Addresses->getValidAddressRanges();
  1471. // Parse the original line info for the unit.
  1472. DWARFDebugLine::LineTable LineTable;
  1473. uint64_t StmtOffset = *StmtList;
  1474. DWARFDataExtractor LineExtractor(
  1475. OrigDwarf.getDWARFObj(), OrigDwarf.getDWARFObj().getLineSection(),
  1476. OrigDwarf.isLittleEndian(), Unit.getOrigUnit().getAddressByteSize());
  1477. if (needToTranslateStrings())
  1478. return TheDwarfEmitter->translateLineTable(LineExtractor, StmtOffset);
  1479. if (Error Err =
  1480. LineTable.parse(LineExtractor, &StmtOffset, OrigDwarf,
  1481. &Unit.getOrigUnit(), OrigDwarf.getWarningHandler()))
  1482. OrigDwarf.getWarningHandler()(std::move(Err));
  1483. // This vector is the output line table.
  1484. std::vector<DWARFDebugLine::Row> NewRows;
  1485. NewRows.reserve(LineTable.Rows.size());
  1486. // Current sequence of rows being extracted, before being inserted
  1487. // in NewRows.
  1488. std::vector<DWARFDebugLine::Row> Seq;
  1489. const auto &FunctionRanges = Unit.getFunctionRanges();
  1490. auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
  1491. // FIXME: This logic is meant to generate exactly the same output as
  1492. // Darwin's classic dsymutil. There is a nicer way to implement this
  1493. // by simply putting all the relocated line info in NewRows and simply
  1494. // sorting NewRows before passing it to emitLineTableForUnit. This
  1495. // should be correct as sequences for a function should stay
  1496. // together in the sorted output. There are a few corner cases that
  1497. // look suspicious though, and that required to implement the logic
  1498. // this way. Revisit that once initial validation is finished.
  1499. // Iterate over the object file line info and extract the sequences
  1500. // that correspond to linked functions.
  1501. for (auto &Row : LineTable.Rows) {
  1502. // Check whether we stepped out of the range. The range is
  1503. // half-open, but consider accept the end address of the range if
  1504. // it is marked as end_sequence in the input (because in that
  1505. // case, the relocation offset is accurate and that entry won't
  1506. // serve as the start of another function).
  1507. if (CurrRange == InvalidRange || Row.Address.Address < CurrRange.start() ||
  1508. Row.Address.Address > CurrRange.stop() ||
  1509. (Row.Address.Address == CurrRange.stop() && !Row.EndSequence)) {
  1510. // We just stepped out of a known range. Insert a end_sequence
  1511. // corresponding to the end of the range.
  1512. uint64_t StopAddress = CurrRange != InvalidRange
  1513. ? CurrRange.stop() + CurrRange.value()
  1514. : -1ULL;
  1515. CurrRange = FunctionRanges.find(Row.Address.Address);
  1516. bool CurrRangeValid =
  1517. CurrRange != InvalidRange && CurrRange.start() <= Row.Address.Address;
  1518. if (!CurrRangeValid) {
  1519. CurrRange = InvalidRange;
  1520. if (StopAddress != -1ULL) {
  1521. // Try harder by looking in the Address ranges map.
  1522. // There are corner cases where this finds a
  1523. // valid entry. It's unclear if this is right or wrong, but
  1524. // for now do as dsymutil.
  1525. // FIXME: Understand exactly what cases this addresses and
  1526. // potentially remove it along with the Ranges map.
  1527. auto Range = Ranges.lower_bound(Row.Address.Address);
  1528. if (Range != Ranges.begin() && Range != Ranges.end())
  1529. --Range;
  1530. if (Range != Ranges.end() && Range->first <= Row.Address.Address &&
  1531. Range->second.HighPC >= Row.Address.Address) {
  1532. StopAddress = Row.Address.Address + Range->second.Offset;
  1533. }
  1534. }
  1535. }
  1536. if (StopAddress != -1ULL && !Seq.empty()) {
  1537. // Insert end sequence row with the computed end address, but
  1538. // the same line as the previous one.
  1539. auto NextLine = Seq.back();
  1540. NextLine.Address.Address = StopAddress;
  1541. NextLine.EndSequence = 1;
  1542. NextLine.PrologueEnd = 0;
  1543. NextLine.BasicBlock = 0;
  1544. NextLine.EpilogueBegin = 0;
  1545. Seq.push_back(NextLine);
  1546. insertLineSequence(Seq, NewRows);
  1547. }
  1548. if (!CurrRangeValid)
  1549. continue;
  1550. }
  1551. // Ignore empty sequences.
  1552. if (Row.EndSequence && Seq.empty())
  1553. continue;
  1554. // Relocate row address and add it to the current sequence.
  1555. Row.Address.Address += CurrRange.value();
  1556. Seq.emplace_back(Row);
  1557. if (Row.EndSequence)
  1558. insertLineSequence(Seq, NewRows);
  1559. }
  1560. // Finished extracting, now emit the line tables.
  1561. // FIXME: LLVM hard-codes its prologue values. We just copy the
  1562. // prologue over and that works because we act as both producer and
  1563. // consumer. It would be nicer to have a real configurable line
  1564. // table emitter.
  1565. if (LineTable.Prologue.getVersion() < 2 ||
  1566. LineTable.Prologue.getVersion() > 5 ||
  1567. LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
  1568. LineTable.Prologue.OpcodeBase > 13)
  1569. reportWarning("line table parameters mismatch. Cannot emit.", File);
  1570. else {
  1571. uint32_t PrologueEnd = *StmtList + 10 + LineTable.Prologue.PrologueLength;
  1572. // DWARF v5 has an extra 2 bytes of information before the header_length
  1573. // field.
  1574. if (LineTable.Prologue.getVersion() == 5)
  1575. PrologueEnd += 2;
  1576. StringRef LineData = OrigDwarf.getDWARFObj().getLineSection().Data;
  1577. MCDwarfLineTableParams Params;
  1578. Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
  1579. Params.DWARF2LineBase = LineTable.Prologue.LineBase;
  1580. Params.DWARF2LineRange = LineTable.Prologue.LineRange;
  1581. TheDwarfEmitter->emitLineTableForUnit(
  1582. Params, LineData.slice(*StmtList + 4, PrologueEnd),
  1583. LineTable.Prologue.MinInstLength, NewRows,
  1584. Unit.getOrigUnit().getAddressByteSize());
  1585. }
  1586. }
  1587. void DWARFLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
  1588. switch (Options.TheAccelTableKind) {
  1589. case AccelTableKind::Apple:
  1590. emitAppleAcceleratorEntriesForUnit(Unit);
  1591. break;
  1592. case AccelTableKind::Dwarf:
  1593. emitDwarfAcceleratorEntriesForUnit(Unit);
  1594. break;
  1595. case AccelTableKind::Default:
  1596. llvm_unreachable("The default must be updated to a concrete value.");
  1597. break;
  1598. }
  1599. }
  1600. void DWARFLinker::emitAppleAcceleratorEntriesForUnit(CompileUnit &Unit) {
  1601. // Add namespaces.
  1602. for (const auto &Namespace : Unit.getNamespaces())
  1603. AppleNamespaces.addName(Namespace.Name,
  1604. Namespace.Die->getOffset() + Unit.getStartOffset());
  1605. /// Add names.
  1606. TheDwarfEmitter->emitPubNamesForUnit(Unit);
  1607. for (const auto &Pubname : Unit.getPubnames())
  1608. AppleNames.addName(Pubname.Name,
  1609. Pubname.Die->getOffset() + Unit.getStartOffset());
  1610. /// Add types.
  1611. TheDwarfEmitter->emitPubTypesForUnit(Unit);
  1612. for (const auto &Pubtype : Unit.getPubtypes())
  1613. AppleTypes.addName(
  1614. Pubtype.Name, Pubtype.Die->getOffset() + Unit.getStartOffset(),
  1615. Pubtype.Die->getTag(),
  1616. Pubtype.ObjcClassImplementation ? dwarf::DW_FLAG_type_implementation
  1617. : 0,
  1618. Pubtype.QualifiedNameHash);
  1619. /// Add ObjC names.
  1620. for (const auto &ObjC : Unit.getObjC())
  1621. AppleObjc.addName(ObjC.Name, ObjC.Die->getOffset() + Unit.getStartOffset());
  1622. }
  1623. void DWARFLinker::emitDwarfAcceleratorEntriesForUnit(CompileUnit &Unit) {
  1624. for (const auto &Namespace : Unit.getNamespaces())
  1625. DebugNames.addName(Namespace.Name, Namespace.Die->getOffset(),
  1626. Namespace.Die->getTag(), Unit.getUniqueID());
  1627. for (const auto &Pubname : Unit.getPubnames())
  1628. DebugNames.addName(Pubname.Name, Pubname.Die->getOffset(),
  1629. Pubname.Die->getTag(), Unit.getUniqueID());
  1630. for (const auto &Pubtype : Unit.getPubtypes())
  1631. DebugNames.addName(Pubtype.Name, Pubtype.Die->getOffset(),
  1632. Pubtype.Die->getTag(), Unit.getUniqueID());
  1633. }
  1634. /// Read the frame info stored in the object, and emit the
  1635. /// patched frame descriptions for the resulting file.
  1636. ///
  1637. /// This is actually pretty easy as the data of the CIEs and FDEs can
  1638. /// be considered as black boxes and moved as is. The only thing to do
  1639. /// is to patch the addresses in the headers.
  1640. void DWARFLinker::patchFrameInfoForObject(const DWARFFile &File,
  1641. RangesTy &Ranges,
  1642. DWARFContext &OrigDwarf,
  1643. unsigned AddrSize) {
  1644. StringRef FrameData = OrigDwarf.getDWARFObj().getFrameSection().Data;
  1645. if (FrameData.empty())
  1646. return;
  1647. DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
  1648. uint64_t InputOffset = 0;
  1649. // Store the data of the CIEs defined in this object, keyed by their
  1650. // offsets.
  1651. DenseMap<uint64_t, StringRef> LocalCIES;
  1652. while (Data.isValidOffset(InputOffset)) {
  1653. uint64_t EntryOffset = InputOffset;
  1654. uint32_t InitialLength = Data.getU32(&InputOffset);
  1655. if (InitialLength == 0xFFFFFFFF)
  1656. return reportWarning("Dwarf64 bits no supported", File);
  1657. uint32_t CIEId = Data.getU32(&InputOffset);
  1658. if (CIEId == 0xFFFFFFFF) {
  1659. // This is a CIE, store it.
  1660. StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
  1661. LocalCIES[EntryOffset] = CIEData;
  1662. // The -4 is to account for the CIEId we just read.
  1663. InputOffset += InitialLength - 4;
  1664. continue;
  1665. }
  1666. uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
  1667. // Some compilers seem to emit frame info that doesn't start at
  1668. // the function entry point, thus we can't just lookup the address
  1669. // in the debug map. Use the AddressInfo's range map to see if the FDE
  1670. // describes something that we can relocate.
  1671. auto Range = Ranges.upper_bound(Loc);
  1672. if (Range != Ranges.begin())
  1673. --Range;
  1674. if (Range == Ranges.end() || Range->first > Loc ||
  1675. Range->second.HighPC <= Loc) {
  1676. // The +4 is to account for the size of the InitialLength field itself.
  1677. InputOffset = EntryOffset + InitialLength + 4;
  1678. continue;
  1679. }
  1680. // This is an FDE, and we have a mapping.
  1681. // Have we already emitted a corresponding CIE?
  1682. StringRef CIEData = LocalCIES[CIEId];
  1683. if (CIEData.empty())
  1684. return reportWarning("Inconsistent debug_frame content. Dropping.", File);
  1685. // Look if we already emitted a CIE that corresponds to the
  1686. // referenced one (the CIE data is the key of that lookup).
  1687. auto IteratorInserted = EmittedCIEs.insert(
  1688. std::make_pair(CIEData, TheDwarfEmitter->getFrameSectionSize()));
  1689. // If there is no CIE yet for this ID, emit it.
  1690. if (IteratorInserted.second ||
  1691. // FIXME: dsymutil-classic only caches the last used CIE for
  1692. // reuse. Mimic that behavior for now. Just removing that
  1693. // second half of the condition and the LastCIEOffset variable
  1694. // makes the code DTRT.
  1695. LastCIEOffset != IteratorInserted.first->getValue()) {
  1696. LastCIEOffset = TheDwarfEmitter->getFrameSectionSize();
  1697. IteratorInserted.first->getValue() = LastCIEOffset;
  1698. TheDwarfEmitter->emitCIE(CIEData);
  1699. }
  1700. // Emit the FDE with updated address and CIE pointer.
  1701. // (4 + AddrSize) is the size of the CIEId + initial_location
  1702. // fields that will get reconstructed by emitFDE().
  1703. unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
  1704. TheDwarfEmitter->emitFDE(IteratorInserted.first->getValue(), AddrSize,
  1705. Loc + Range->second.Offset,
  1706. FrameData.substr(InputOffset, FDERemainingBytes));
  1707. InputOffset += FDERemainingBytes;
  1708. }
  1709. }
  1710. void DWARFLinker::DIECloner::copyAbbrev(
  1711. const DWARFAbbreviationDeclaration &Abbrev, bool HasODR) {
  1712. DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
  1713. dwarf::Form(Abbrev.hasChildren()));
  1714. for (const auto &Attr : Abbrev.attributes()) {
  1715. uint16_t Form = Attr.Form;
  1716. if (HasODR && isODRAttribute(Attr.Attr))
  1717. Form = dwarf::DW_FORM_ref_addr;
  1718. Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
  1719. }
  1720. Linker.assignAbbrev(Copy);
  1721. }
  1722. uint32_t DWARFLinker::DIECloner::hashFullyQualifiedName(DWARFDie DIE,
  1723. CompileUnit &U,
  1724. const DWARFFile &File,
  1725. int ChildRecurseDepth) {
  1726. const char *Name = nullptr;
  1727. DWARFUnit *OrigUnit = &U.getOrigUnit();
  1728. CompileUnit *CU = &U;
  1729. Optional<DWARFFormValue> Ref;
  1730. while (1) {
  1731. if (const char *CurrentName = DIE.getName(DINameKind::ShortName))
  1732. Name = CurrentName;
  1733. if (!(Ref = DIE.find(dwarf::DW_AT_specification)) &&
  1734. !(Ref = DIE.find(dwarf::DW_AT_abstract_origin)))
  1735. break;
  1736. if (!Ref->isFormClass(DWARFFormValue::FC_Reference))
  1737. break;
  1738. CompileUnit *RefCU;
  1739. if (auto RefDIE =
  1740. Linker.resolveDIEReference(File, CompileUnits, *Ref, DIE, RefCU)) {
  1741. CU = RefCU;
  1742. OrigUnit = &RefCU->getOrigUnit();
  1743. DIE = RefDIE;
  1744. }
  1745. }
  1746. unsigned Idx = OrigUnit->getDIEIndex(DIE);
  1747. if (!Name && DIE.getTag() == dwarf::DW_TAG_namespace)
  1748. Name = "(anonymous namespace)";
  1749. if (CU->getInfo(Idx).ParentIdx == 0 ||
  1750. // FIXME: dsymutil-classic compatibility. Ignore modules.
  1751. CU->getOrigUnit().getDIEAtIndex(CU->getInfo(Idx).ParentIdx).getTag() ==
  1752. dwarf::DW_TAG_module)
  1753. return djbHash(Name ? Name : "", djbHash(ChildRecurseDepth ? "" : "::"));
  1754. DWARFDie Die = OrigUnit->getDIEAtIndex(CU->getInfo(Idx).ParentIdx);
  1755. return djbHash(
  1756. (Name ? Name : ""),
  1757. djbHash((Name ? "::" : ""),
  1758. hashFullyQualifiedName(Die, *CU, File, ++ChildRecurseDepth)));
  1759. }
  1760. static uint64_t getDwoId(const DWARFDie &CUDie, const DWARFUnit &Unit) {
  1761. auto DwoId = dwarf::toUnsigned(
  1762. CUDie.find({dwarf::DW_AT_dwo_id, dwarf::DW_AT_GNU_dwo_id}));
  1763. if (DwoId)
  1764. return *DwoId;
  1765. return 0;
  1766. }
  1767. static std::string remapPath(StringRef Path,
  1768. const objectPrefixMap &ObjectPrefixMap) {
  1769. if (ObjectPrefixMap.empty())
  1770. return Path.str();
  1771. SmallString<256> p = Path;
  1772. for (const auto &Entry : ObjectPrefixMap)
  1773. if (llvm::sys::path::replace_path_prefix(p, Entry.first, Entry.second))
  1774. break;
  1775. return p.str().str();
  1776. }
  1777. bool DWARFLinker::registerModuleReference(DWARFDie CUDie, const DWARFUnit &Unit,
  1778. const DWARFFile &File,
  1779. OffsetsStringPool &StringPool,
  1780. DeclContextTree &ODRContexts,
  1781. uint64_t ModulesEndOffset,
  1782. unsigned &UnitID, bool IsLittleEndian,
  1783. unsigned Indent, bool Quiet) {
  1784. std::string PCMfile = dwarf::toString(
  1785. CUDie.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
  1786. if (PCMfile.empty())
  1787. return false;
  1788. if (Options.ObjectPrefixMap)
  1789. PCMfile = remapPath(PCMfile, *Options.ObjectPrefixMap);
  1790. // Clang module DWARF skeleton CUs abuse this for the path to the module.
  1791. uint64_t DwoId = getDwoId(CUDie, Unit);
  1792. std::string Name = dwarf::toString(CUDie.find(dwarf::DW_AT_name), "");
  1793. if (Name.empty()) {
  1794. if (!Quiet)
  1795. reportWarning("Anonymous module skeleton CU for " + PCMfile, File);
  1796. return true;
  1797. }
  1798. if (!Quiet && Options.Verbose) {
  1799. outs().indent(Indent);
  1800. outs() << "Found clang module reference " << PCMfile;
  1801. }
  1802. auto Cached = ClangModules.find(PCMfile);
  1803. if (Cached != ClangModules.end()) {
  1804. // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
  1805. // fixed in clang, only warn about DWO_id mismatches in verbose mode.
  1806. // ASTFileSignatures will change randomly when a module is rebuilt.
  1807. if (!Quiet && Options.Verbose && (Cached->second != DwoId))
  1808. reportWarning(Twine("hash mismatch: this object file was built against a "
  1809. "different version of the module ") +
  1810. PCMfile,
  1811. File);
  1812. if (!Quiet && Options.Verbose)
  1813. outs() << " [cached].\n";
  1814. return true;
  1815. }
  1816. if (!Quiet && Options.Verbose)
  1817. outs() << " ...\n";
  1818. // Cyclic dependencies are disallowed by Clang, but we still
  1819. // shouldn't run into an infinite loop, so mark it as processed now.
  1820. ClangModules.insert({PCMfile, DwoId});
  1821. if (Error E = loadClangModule(CUDie, PCMfile, Name, DwoId, File, StringPool,
  1822. ODRContexts, ModulesEndOffset, UnitID,
  1823. IsLittleEndian, Indent + 2, Quiet)) {
  1824. consumeError(std::move(E));
  1825. return false;
  1826. }
  1827. return true;
  1828. }
  1829. Error DWARFLinker::loadClangModule(
  1830. DWARFDie CUDie, StringRef Filename, StringRef ModuleName, uint64_t DwoId,
  1831. const DWARFFile &File, OffsetsStringPool &StringPool,
  1832. DeclContextTree &ODRContexts, uint64_t ModulesEndOffset, unsigned &UnitID,
  1833. bool IsLittleEndian, unsigned Indent, bool Quiet) {
  1834. /// Using a SmallString<0> because loadClangModule() is recursive.
  1835. SmallString<0> Path(Options.PrependPath);
  1836. if (sys::path::is_relative(Filename))
  1837. resolveRelativeObjectPath(Path, CUDie);
  1838. sys::path::append(Path, Filename);
  1839. // Don't use the cached binary holder because we have no thread-safety
  1840. // guarantee and the lifetime is limited.
  1841. if (Options.ObjFileLoader == nullptr)
  1842. return Error::success();
  1843. auto ErrOrObj = Options.ObjFileLoader(File.FileName, Path);
  1844. if (!ErrOrObj)
  1845. return Error::success();
  1846. std::unique_ptr<CompileUnit> Unit;
  1847. for (const auto &CU : ErrOrObj->Dwarf->compile_units()) {
  1848. updateDwarfVersion(CU->getVersion());
  1849. // Recursively get all modules imported by this one.
  1850. auto CUDie = CU->getUnitDIE(false);
  1851. if (!CUDie)
  1852. continue;
  1853. if (!registerModuleReference(CUDie, *CU, File, StringPool, ODRContexts,
  1854. ModulesEndOffset, UnitID, IsLittleEndian,
  1855. Indent, Quiet)) {
  1856. if (Unit) {
  1857. std::string Err =
  1858. (Filename +
  1859. ": Clang modules are expected to have exactly 1 compile unit.\n")
  1860. .str();
  1861. reportError(Err, File);
  1862. return make_error<StringError>(Err, inconvertibleErrorCode());
  1863. }
  1864. // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
  1865. // fixed in clang, only warn about DWO_id mismatches in verbose mode.
  1866. // ASTFileSignatures will change randomly when a module is rebuilt.
  1867. uint64_t PCMDwoId = getDwoId(CUDie, *CU);
  1868. if (PCMDwoId != DwoId) {
  1869. if (!Quiet && Options.Verbose)
  1870. reportWarning(
  1871. Twine("hash mismatch: this object file was built against a "
  1872. "different version of the module ") +
  1873. Filename,
  1874. File);
  1875. // Update the cache entry with the DwoId of the module loaded from disk.
  1876. ClangModules[Filename] = PCMDwoId;
  1877. }
  1878. // Add this module.
  1879. Unit = std::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
  1880. ModuleName);
  1881. Unit->setHasInterestingContent();
  1882. analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), ODRContexts,
  1883. ModulesEndOffset, Options.ParseableSwiftInterfaces,
  1884. [&](const Twine &Warning, const DWARFDie &DIE) {
  1885. reportWarning(Warning, File, &DIE);
  1886. });
  1887. // Keep everything.
  1888. Unit->markEverythingAsKept();
  1889. }
  1890. }
  1891. if (!Unit->getOrigUnit().getUnitDIE().hasChildren())
  1892. return Error::success();
  1893. if (!Quiet && Options.Verbose) {
  1894. outs().indent(Indent);
  1895. outs() << "cloning .debug_info from " << Filename << "\n";
  1896. }
  1897. UnitListTy CompileUnits;
  1898. CompileUnits.push_back(std::move(Unit));
  1899. assert(TheDwarfEmitter);
  1900. DIECloner(*this, TheDwarfEmitter, *ErrOrObj, DIEAlloc, CompileUnits,
  1901. Options.Update)
  1902. .cloneAllCompileUnits(*(ErrOrObj->Dwarf), File, StringPool,
  1903. IsLittleEndian);
  1904. return Error::success();
  1905. }
  1906. uint64_t DWARFLinker::DIECloner::cloneAllCompileUnits(
  1907. DWARFContext &DwarfContext, const DWARFFile &File,
  1908. OffsetsStringPool &StringPool, bool IsLittleEndian) {
  1909. uint64_t OutputDebugInfoSize =
  1910. Linker.Options.NoOutput ? 0 : Emitter->getDebugInfoSectionSize();
  1911. const uint64_t StartOutputDebugInfoSize = OutputDebugInfoSize;
  1912. for (auto &CurrentUnit : CompileUnits) {
  1913. const uint16_t DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
  1914. const uint32_t UnitHeaderSize = DwarfVersion >= 5 ? 12 : 11;
  1915. auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE();
  1916. CurrentUnit->setStartOffset(OutputDebugInfoSize);
  1917. if (!InputDIE) {
  1918. OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
  1919. continue;
  1920. }
  1921. if (CurrentUnit->getInfo(0).Keep) {
  1922. // Clone the InputDIE into your Unit DIE in our compile unit since it
  1923. // already has a DIE inside of it.
  1924. CurrentUnit->createOutputDIE();
  1925. cloneDIE(InputDIE, File, *CurrentUnit, StringPool, 0 /* PC offset */,
  1926. UnitHeaderSize, 0, IsLittleEndian,
  1927. CurrentUnit->getOutputUnitDIE());
  1928. }
  1929. OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
  1930. if (!Linker.Options.NoOutput) {
  1931. assert(Emitter);
  1932. if (LLVM_LIKELY(!Linker.Options.Update) ||
  1933. Linker.needToTranslateStrings())
  1934. Linker.patchLineTableForUnit(*CurrentUnit, DwarfContext, File);
  1935. Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
  1936. if (LLVM_UNLIKELY(Linker.Options.Update))
  1937. continue;
  1938. Linker.patchRangesForUnit(*CurrentUnit, DwarfContext, File);
  1939. auto ProcessExpr = [&](StringRef Bytes,
  1940. SmallVectorImpl<uint8_t> &Buffer) {
  1941. DWARFUnit &OrigUnit = CurrentUnit->getOrigUnit();
  1942. DataExtractor Data(Bytes, IsLittleEndian,
  1943. OrigUnit.getAddressByteSize());
  1944. cloneExpression(Data,
  1945. DWARFExpression(Data, OrigUnit.getAddressByteSize(),
  1946. OrigUnit.getFormParams().Format),
  1947. File, *CurrentUnit, Buffer);
  1948. };
  1949. Emitter->emitLocationsForUnit(*CurrentUnit, DwarfContext, ProcessExpr);
  1950. }
  1951. }
  1952. if (!Linker.Options.NoOutput) {
  1953. assert(Emitter);
  1954. // Emit all the compile unit's debug information.
  1955. for (auto &CurrentUnit : CompileUnits) {
  1956. if (LLVM_LIKELY(!Linker.Options.Update))
  1957. Linker.generateUnitRanges(*CurrentUnit);
  1958. CurrentUnit->fixupForwardReferences();
  1959. if (!CurrentUnit->getOutputUnitDIE())
  1960. continue;
  1961. unsigned DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
  1962. assert(Emitter->getDebugInfoSectionSize() ==
  1963. CurrentUnit->getStartOffset());
  1964. Emitter->emitCompileUnitHeader(*CurrentUnit, DwarfVersion);
  1965. Emitter->emitDIE(*CurrentUnit->getOutputUnitDIE());
  1966. assert(Emitter->getDebugInfoSectionSize() ==
  1967. CurrentUnit->computeNextUnitOffset(DwarfVersion));
  1968. }
  1969. }
  1970. return OutputDebugInfoSize - StartOutputDebugInfoSize;
  1971. }
  1972. void DWARFLinker::updateAccelKind(DWARFContext &Dwarf) {
  1973. if (Options.TheAccelTableKind != AccelTableKind::Default)
  1974. return;
  1975. auto &DwarfObj = Dwarf.getDWARFObj();
  1976. if (!AtLeastOneDwarfAccelTable &&
  1977. (!DwarfObj.getAppleNamesSection().Data.empty() ||
  1978. !DwarfObj.getAppleTypesSection().Data.empty() ||
  1979. !DwarfObj.getAppleNamespacesSection().Data.empty() ||
  1980. !DwarfObj.getAppleObjCSection().Data.empty())) {
  1981. AtLeastOneAppleAccelTable = true;
  1982. }
  1983. if (!AtLeastOneDwarfAccelTable && !DwarfObj.getNamesSection().Data.empty()) {
  1984. AtLeastOneDwarfAccelTable = true;
  1985. }
  1986. }
  1987. bool DWARFLinker::emitPaperTrailWarnings(const DWARFFile &File,
  1988. OffsetsStringPool &StringPool) {
  1989. if (File.Warnings.empty())
  1990. return false;
  1991. DIE *CUDie = DIE::get(DIEAlloc, dwarf::DW_TAG_compile_unit);
  1992. CUDie->setOffset(11);
  1993. StringRef Producer;
  1994. StringRef WarningHeader;
  1995. switch (DwarfLinkerClientID) {
  1996. case DwarfLinkerClient::Dsymutil:
  1997. Producer = StringPool.internString("dsymutil");
  1998. WarningHeader = "dsymutil_warning";
  1999. break;
  2000. default:
  2001. Producer = StringPool.internString("dwarfopt");
  2002. WarningHeader = "dwarfopt_warning";
  2003. break;
  2004. }
  2005. StringRef FileName = StringPool.internString(File.FileName);
  2006. CUDie->addValue(DIEAlloc, dwarf::DW_AT_producer, dwarf::DW_FORM_strp,
  2007. DIEInteger(StringPool.getStringOffset(Producer)));
  2008. DIEBlock *String = new (DIEAlloc) DIEBlock();
  2009. DIEBlocks.push_back(String);
  2010. for (auto &C : FileName)
  2011. String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
  2012. DIEInteger(C));
  2013. String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
  2014. DIEInteger(0));
  2015. CUDie->addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_string, String);
  2016. for (const auto &Warning : File.Warnings) {
  2017. DIE &ConstDie = CUDie->addChild(DIE::get(DIEAlloc, dwarf::DW_TAG_constant));
  2018. ConstDie.addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp,
  2019. DIEInteger(StringPool.getStringOffset(WarningHeader)));
  2020. ConstDie.addValue(DIEAlloc, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag,
  2021. DIEInteger(1));
  2022. ConstDie.addValue(DIEAlloc, dwarf::DW_AT_const_value, dwarf::DW_FORM_strp,
  2023. DIEInteger(StringPool.getStringOffset(Warning)));
  2024. }
  2025. unsigned Size = 4 /* FORM_strp */ + FileName.size() + 1 +
  2026. File.Warnings.size() * (4 + 1 + 4) + 1 /* End of children */;
  2027. DIEAbbrev Abbrev = CUDie->generateAbbrev();
  2028. assignAbbrev(Abbrev);
  2029. CUDie->setAbbrevNumber(Abbrev.getNumber());
  2030. Size += getULEB128Size(Abbrev.getNumber());
  2031. // Abbreviation ordering needed for classic compatibility.
  2032. for (auto &Child : CUDie->children()) {
  2033. Abbrev = Child.generateAbbrev();
  2034. assignAbbrev(Abbrev);
  2035. Child.setAbbrevNumber(Abbrev.getNumber());
  2036. Size += getULEB128Size(Abbrev.getNumber());
  2037. }
  2038. CUDie->setSize(Size);
  2039. TheDwarfEmitter->emitPaperTrailWarningsDie(*CUDie);
  2040. return true;
  2041. }
  2042. void DWARFLinker::copyInvariantDebugSection(DWARFContext &Dwarf) {
  2043. if (!needToTranslateStrings())
  2044. TheDwarfEmitter->emitSectionContents(
  2045. Dwarf.getDWARFObj().getLineSection().Data, "debug_line");
  2046. TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getLocSection().Data,
  2047. "debug_loc");
  2048. TheDwarfEmitter->emitSectionContents(
  2049. Dwarf.getDWARFObj().getRangesSection().Data, "debug_ranges");
  2050. TheDwarfEmitter->emitSectionContents(
  2051. Dwarf.getDWARFObj().getFrameSection().Data, "debug_frame");
  2052. TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getArangesSection(),
  2053. "debug_aranges");
  2054. }
  2055. void DWARFLinker::addObjectFile(DWARFFile &File) {
  2056. ObjectContexts.emplace_back(LinkContext(File));
  2057. if (ObjectContexts.back().File.Dwarf)
  2058. updateAccelKind(*ObjectContexts.back().File.Dwarf);
  2059. }
  2060. bool DWARFLinker::link() {
  2061. assert(Options.NoOutput || TheDwarfEmitter);
  2062. // A unique ID that identifies each compile unit.
  2063. unsigned UnitID = 0;
  2064. // First populate the data structure we need for each iteration of the
  2065. // parallel loop.
  2066. unsigned NumObjects = ObjectContexts.size();
  2067. // This Dwarf string pool which is used for emission. It must be used
  2068. // serially as the order of calling getStringOffset matters for
  2069. // reproducibility.
  2070. OffsetsStringPool OffsetsStringPool(StringsTranslator, true);
  2071. // ODR Contexts for the optimize.
  2072. DeclContextTree ODRContexts;
  2073. // If we haven't decided on an accelerator table kind yet, we base ourselves
  2074. // on the DWARF we have seen so far. At this point we haven't pulled in debug
  2075. // information from modules yet, so it is technically possible that they
  2076. // would affect the decision. However, as they're built with the same
  2077. // compiler and flags, it is safe to assume that they will follow the
  2078. // decision made here.
  2079. if (Options.TheAccelTableKind == AccelTableKind::Default) {
  2080. if (AtLeastOneDwarfAccelTable && !AtLeastOneAppleAccelTable)
  2081. Options.TheAccelTableKind = AccelTableKind::Dwarf;
  2082. else
  2083. Options.TheAccelTableKind = AccelTableKind::Apple;
  2084. }
  2085. for (LinkContext &OptContext : ObjectContexts) {
  2086. if (Options.Verbose) {
  2087. if (DwarfLinkerClientID == DwarfLinkerClient::Dsymutil)
  2088. outs() << "DEBUG MAP OBJECT: " << OptContext.File.FileName << "\n";
  2089. else
  2090. outs() << "OBJECT FILE: " << OptContext.File.FileName << "\n";
  2091. }
  2092. if (emitPaperTrailWarnings(OptContext.File, OffsetsStringPool))
  2093. continue;
  2094. if (!OptContext.File.Dwarf)
  2095. continue;
  2096. // Look for relocations that correspond to address map entries.
  2097. // there was findvalidrelocations previously ... probably we need to gather
  2098. // info here
  2099. if (LLVM_LIKELY(!Options.Update) &&
  2100. !OptContext.File.Addresses->hasValidRelocs()) {
  2101. if (Options.Verbose)
  2102. outs() << "No valid relocations found. Skipping.\n";
  2103. // Set "Skip" flag as a signal to other loops that we should not
  2104. // process this iteration.
  2105. OptContext.Skip = true;
  2106. continue;
  2107. }
  2108. // Setup access to the debug info.
  2109. if (!OptContext.File.Dwarf)
  2110. continue;
  2111. // In a first phase, just read in the debug info and load all clang modules.
  2112. OptContext.CompileUnits.reserve(
  2113. OptContext.File.Dwarf->getNumCompileUnits());
  2114. for (const auto &CU : OptContext.File.Dwarf->compile_units()) {
  2115. updateDwarfVersion(CU->getVersion());
  2116. auto CUDie = CU->getUnitDIE(false);
  2117. if (Options.Verbose) {
  2118. outs() << "Input compilation unit:";
  2119. DIDumpOptions DumpOpts;
  2120. DumpOpts.ChildRecurseDepth = 0;
  2121. DumpOpts.Verbose = Options.Verbose;
  2122. CUDie.dump(outs(), 0, DumpOpts);
  2123. }
  2124. if (CUDie && !LLVM_UNLIKELY(Options.Update))
  2125. registerModuleReference(CUDie, *CU, OptContext.File, OffsetsStringPool,
  2126. ODRContexts, 0, UnitID,
  2127. OptContext.File.Dwarf->isLittleEndian());
  2128. }
  2129. }
  2130. // If we haven't seen any CUs, pick an arbitrary valid Dwarf version anyway.
  2131. if (MaxDwarfVersion == 0)
  2132. MaxDwarfVersion = 3;
  2133. // At this point we know how much data we have emitted. We use this value to
  2134. // compare canonical DIE offsets in analyzeContextInfo to see if a definition
  2135. // is already emitted, without being affected by canonical die offsets set
  2136. // later. This prevents undeterminism when analyze and clone execute
  2137. // concurrently, as clone set the canonical DIE offset and analyze reads it.
  2138. const uint64_t ModulesEndOffset =
  2139. Options.NoOutput ? 0 : TheDwarfEmitter->getDebugInfoSectionSize();
  2140. // These variables manage the list of processed object files.
  2141. // The mutex and condition variable are to ensure that this is thread safe.
  2142. std::mutex ProcessedFilesMutex;
  2143. std::condition_variable ProcessedFilesConditionVariable;
  2144. BitVector ProcessedFiles(NumObjects, false);
  2145. // Analyzing the context info is particularly expensive so it is executed in
  2146. // parallel with emitting the previous compile unit.
  2147. auto AnalyzeLambda = [&](size_t I) {
  2148. auto &Context = ObjectContexts[I];
  2149. if (Context.Skip || !Context.File.Dwarf)
  2150. return;
  2151. for (const auto &CU : Context.File.Dwarf->compile_units()) {
  2152. updateDwarfVersion(CU->getVersion());
  2153. // The !registerModuleReference() condition effectively skips
  2154. // over fully resolved skeleton units. This second pass of
  2155. // registerModuleReferences doesn't do any new work, but it
  2156. // will collect top-level errors, which are suppressed. Module
  2157. // warnings were already displayed in the first iteration.
  2158. bool Quiet = true;
  2159. auto CUDie = CU->getUnitDIE(false);
  2160. if (!CUDie || LLVM_UNLIKELY(Options.Update) ||
  2161. !registerModuleReference(CUDie, *CU, Context.File, OffsetsStringPool,
  2162. ODRContexts, ModulesEndOffset, UnitID,
  2163. Quiet)) {
  2164. Context.CompileUnits.push_back(std::make_unique<CompileUnit>(
  2165. *CU, UnitID++, !Options.NoODR && !Options.Update, ""));
  2166. }
  2167. }
  2168. // Now build the DIE parent links that we will use during the next phase.
  2169. for (auto &CurrentUnit : Context.CompileUnits) {
  2170. auto CUDie = CurrentUnit->getOrigUnit().getUnitDIE();
  2171. if (!CUDie)
  2172. continue;
  2173. analyzeContextInfo(CurrentUnit->getOrigUnit().getUnitDIE(), 0,
  2174. *CurrentUnit, &ODRContexts.getRoot(), ODRContexts,
  2175. ModulesEndOffset, Options.ParseableSwiftInterfaces,
  2176. [&](const Twine &Warning, const DWARFDie &DIE) {
  2177. reportWarning(Warning, Context.File, &DIE);
  2178. });
  2179. }
  2180. };
  2181. // For each object file map how many bytes were emitted.
  2182. StringMap<DebugInfoSize> SizeByObject;
  2183. // And then the remaining work in serial again.
  2184. // Note, although this loop runs in serial, it can run in parallel with
  2185. // the analyzeContextInfo loop so long as we process files with indices >=
  2186. // than those processed by analyzeContextInfo.
  2187. auto CloneLambda = [&](size_t I) {
  2188. auto &OptContext = ObjectContexts[I];
  2189. if (OptContext.Skip || !OptContext.File.Dwarf)
  2190. return;
  2191. // Then mark all the DIEs that need to be present in the generated output
  2192. // and collect some information about them.
  2193. // Note that this loop can not be merged with the previous one because
  2194. // cross-cu references require the ParentIdx to be setup for every CU in
  2195. // the object file before calling this.
  2196. if (LLVM_UNLIKELY(Options.Update)) {
  2197. for (auto &CurrentUnit : OptContext.CompileUnits)
  2198. CurrentUnit->markEverythingAsKept();
  2199. copyInvariantDebugSection(*OptContext.File.Dwarf);
  2200. } else {
  2201. for (auto &CurrentUnit : OptContext.CompileUnits)
  2202. lookForDIEsToKeep(*OptContext.File.Addresses,
  2203. OptContext.File.Addresses->getValidAddressRanges(),
  2204. OptContext.CompileUnits,
  2205. CurrentUnit->getOrigUnit().getUnitDIE(),
  2206. OptContext.File, *CurrentUnit, 0);
  2207. }
  2208. // The calls to applyValidRelocs inside cloneDIE will walk the reloc
  2209. // array again (in the same way findValidRelocsInDebugInfo() did). We
  2210. // need to reset the NextValidReloc index to the beginning.
  2211. if (OptContext.File.Addresses->hasValidRelocs() ||
  2212. LLVM_UNLIKELY(Options.Update)) {
  2213. SizeByObject[OptContext.File.FileName].Input =
  2214. getDebugInfoSize(*OptContext.File.Dwarf);
  2215. SizeByObject[OptContext.File.FileName].Output =
  2216. DIECloner(*this, TheDwarfEmitter, OptContext.File, DIEAlloc,
  2217. OptContext.CompileUnits, Options.Update)
  2218. .cloneAllCompileUnits(*OptContext.File.Dwarf, OptContext.File,
  2219. OffsetsStringPool,
  2220. OptContext.File.Dwarf->isLittleEndian());
  2221. }
  2222. if (!Options.NoOutput && !OptContext.CompileUnits.empty() &&
  2223. LLVM_LIKELY(!Options.Update))
  2224. patchFrameInfoForObject(
  2225. OptContext.File, OptContext.File.Addresses->getValidAddressRanges(),
  2226. *OptContext.File.Dwarf,
  2227. OptContext.CompileUnits[0]->getOrigUnit().getAddressByteSize());
  2228. // Clean-up before starting working on the next object.
  2229. cleanupAuxiliarryData(OptContext);
  2230. };
  2231. auto EmitLambda = [&]() {
  2232. // Emit everything that's global.
  2233. if (!Options.NoOutput) {
  2234. TheDwarfEmitter->emitAbbrevs(Abbreviations, MaxDwarfVersion);
  2235. TheDwarfEmitter->emitStrings(OffsetsStringPool);
  2236. switch (Options.TheAccelTableKind) {
  2237. case AccelTableKind::Apple:
  2238. TheDwarfEmitter->emitAppleNames(AppleNames);
  2239. TheDwarfEmitter->emitAppleNamespaces(AppleNamespaces);
  2240. TheDwarfEmitter->emitAppleTypes(AppleTypes);
  2241. TheDwarfEmitter->emitAppleObjc(AppleObjc);
  2242. break;
  2243. case AccelTableKind::Dwarf:
  2244. TheDwarfEmitter->emitDebugNames(DebugNames);
  2245. break;
  2246. case AccelTableKind::Default:
  2247. llvm_unreachable("Default should have already been resolved.");
  2248. break;
  2249. }
  2250. }
  2251. };
  2252. auto AnalyzeAll = [&]() {
  2253. for (unsigned I = 0, E = NumObjects; I != E; ++I) {
  2254. AnalyzeLambda(I);
  2255. std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
  2256. ProcessedFiles.set(I);
  2257. ProcessedFilesConditionVariable.notify_one();
  2258. }
  2259. };
  2260. auto CloneAll = [&]() {
  2261. for (unsigned I = 0, E = NumObjects; I != E; ++I) {
  2262. {
  2263. std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
  2264. if (!ProcessedFiles[I]) {
  2265. ProcessedFilesConditionVariable.wait(
  2266. LockGuard, [&]() { return ProcessedFiles[I]; });
  2267. }
  2268. }
  2269. CloneLambda(I);
  2270. }
  2271. EmitLambda();
  2272. };
  2273. // To limit memory usage in the single threaded case, analyze and clone are
  2274. // run sequentially so the OptContext is freed after processing each object
  2275. // in endDebugObject.
  2276. if (Options.Threads == 1) {
  2277. for (unsigned I = 0, E = NumObjects; I != E; ++I) {
  2278. AnalyzeLambda(I);
  2279. CloneLambda(I);
  2280. }
  2281. EmitLambda();
  2282. } else {
  2283. ThreadPool Pool(hardware_concurrency(2));
  2284. Pool.async(AnalyzeAll);
  2285. Pool.async(CloneAll);
  2286. Pool.wait();
  2287. }
  2288. if (Options.Statistics) {
  2289. // Create a vector sorted in descending order by output size.
  2290. std::vector<std::pair<StringRef, DebugInfoSize>> Sorted;
  2291. for (auto &E : SizeByObject)
  2292. Sorted.emplace_back(E.first(), E.second);
  2293. llvm::sort(Sorted, [](auto &LHS, auto &RHS) {
  2294. return LHS.second.Output > RHS.second.Output;
  2295. });
  2296. auto ComputePercentange = [](int64_t Input, int64_t Output) -> float {
  2297. const float Difference = Output - Input;
  2298. const float Sum = Input + Output;
  2299. if (Sum == 0)
  2300. return 0;
  2301. return (Difference / (Sum / 2));
  2302. };
  2303. int64_t InputTotal = 0;
  2304. int64_t OutputTotal = 0;
  2305. const char *FormatStr = "{0,-45} {1,10}b {2,10}b {3,8:P}\n";
  2306. // Print header.
  2307. outs() << ".debug_info section size (in bytes)\n";
  2308. outs() << "----------------------------------------------------------------"
  2309. "---------------\n";
  2310. outs() << "Filename Object "
  2311. " dSYM Change\n";
  2312. outs() << "----------------------------------------------------------------"
  2313. "---------------\n";
  2314. // Print body.
  2315. for (auto &E : Sorted) {
  2316. InputTotal += E.second.Input;
  2317. OutputTotal += E.second.Output;
  2318. llvm::outs() << formatv(
  2319. FormatStr, sys::path::filename(E.first).take_back(45), E.second.Input,
  2320. E.second.Output, ComputePercentange(E.second.Input, E.second.Output));
  2321. }
  2322. // Print total and footer.
  2323. outs() << "----------------------------------------------------------------"
  2324. "---------------\n";
  2325. llvm::outs() << formatv(FormatStr, "Total", InputTotal, OutputTotal,
  2326. ComputePercentange(InputTotal, OutputTotal));
  2327. outs() << "----------------------------------------------------------------"
  2328. "---------------\n\n";
  2329. }
  2330. return true;
  2331. }
  2332. } // namespace llvm