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