blob: 4e5cb735122d24e1196789076e8d00c2221e7126 [file] [log] [blame]
Frederic Riss231f7142014-12-12 17:31:24 +00001//===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#include "DebugMap.h"
Frederic Rissd3455182015-01-28 18:27:01 +000010#include "BinaryHolder.h"
11#include "DebugMap.h"
Frederic Riss231f7142014-12-12 17:31:24 +000012#include "dsymutil.h"
Frederic Riss1af75f72015-03-12 18:45:10 +000013#include "llvm/ADT/IntervalMap.h"
Frederic Riss1b9be2c2015-03-11 18:46:01 +000014#include "llvm/ADT/StringMap.h"
15#include "llvm/ADT/STLExtras.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000016#include "llvm/CodeGen/AsmPrinter.h"
Frederic Rissb8b43d52015-03-04 22:07:44 +000017#include "llvm/CodeGen/DIE.h"
Zachary Turner82af9432015-01-30 18:07:45 +000018#include "llvm/DebugInfo/DWARF/DWARFContext.h"
19#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
Frederic Riss1b9da422015-02-13 23:18:29 +000020#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000021#include "llvm/MC/MCAsmBackend.h"
22#include "llvm/MC/MCAsmInfo.h"
23#include "llvm/MC/MCContext.h"
24#include "llvm/MC/MCCodeEmitter.h"
Frederic Riss63786b02015-03-15 20:45:43 +000025#include "llvm/MC/MCDwarf.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000026#include "llvm/MC/MCInstrInfo.h"
27#include "llvm/MC/MCObjectFileInfo.h"
28#include "llvm/MC/MCRegisterInfo.h"
29#include "llvm/MC/MCStreamer.h"
Pete Cooper81902a32015-05-15 22:19:42 +000030#include "llvm/MC/MCSubtargetInfo.h"
Frederic Riss1036e642015-02-13 23:18:22 +000031#include "llvm/Object/MachO.h"
Frederic Riss84c09a52015-02-13 23:18:34 +000032#include "llvm/Support/Dwarf.h"
33#include "llvm/Support/LEB128.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000034#include "llvm/Support/TargetRegistry.h"
35#include "llvm/Target/TargetMachine.h"
36#include "llvm/Target/TargetOptions.h"
Frederic Rissd3455182015-01-28 18:27:01 +000037#include <string>
Frederic Riss6afcfce2015-03-13 18:35:57 +000038#include <tuple>
Frederic Riss231f7142014-12-12 17:31:24 +000039
40namespace llvm {
41namespace dsymutil {
42
Frederic Rissd3455182015-01-28 18:27:01 +000043namespace {
44
Frederic Rissdef4fb72015-02-28 00:29:01 +000045void warn(const Twine &Warning, const Twine &Context) {
46 errs() << Twine("while processing ") + Context + ":\n";
47 errs() << Twine("warning: ") + Warning + "\n";
48}
49
Frederic Rissc99ea202015-02-28 00:29:11 +000050bool error(const Twine &Error, const Twine &Context) {
51 errs() << Twine("while processing ") + Context + ":\n";
52 errs() << Twine("error: ") + Error + "\n";
53 return false;
54}
55
Frederic Riss1af75f72015-03-12 18:45:10 +000056template <typename KeyT, typename ValT>
57using HalfOpenIntervalMap =
58 IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
59 IntervalMapHalfOpenInfo<KeyT>>;
60
Frederic Riss25440872015-03-13 23:30:31 +000061typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
62
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000063// FIXME: Delete this structure once DIE::Values has a stable iterator we can
64// use instead.
65struct PatchLocation {
66 DIE *Die;
67 unsigned Index;
68
69 PatchLocation() : Die(nullptr), Index(0) {}
70 PatchLocation(DIE &Die, unsigned Index) : Die(&Die), Index(Index) {}
71
72 void set(uint64_t New) const {
73 assert(Die);
74 assert(Index < Die->getValues().size());
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +000075 const auto &Old = Die->getValues()[Index];
76 assert(Old.getType() == DIEValue::isInteger);
77 Die->setValue(Index,
78 DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New)));
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000079 }
80
81 uint64_t get() const {
82 assert(Die);
83 assert(Index < Die->getValues().size());
84 assert(Die->getValues()[Index].getType() == DIEValue::isInteger);
85 return Die->getValues()[Index].getDIEInteger().getValue();
86 }
87};
88
Frederic Riss563cba62015-01-28 22:15:14 +000089/// \brief Stores all information relating to a compile unit, be it in
90/// its original instance in the object file to its brand new cloned
91/// and linked DIE tree.
92class CompileUnit {
93public:
94 /// \brief Information gathered about a DIE in the object file.
95 struct DIEInfo {
Frederic Riss31da3242015-03-11 18:45:52 +000096 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
Frederic Riss9833de62015-03-06 23:22:53 +000097 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +000098 uint32_t ParentIdx; ///< The index of this DIE's parent.
99 bool Keep; ///< Is the DIE part of the linked output?
100 bool InDebugMap; ///< Was this DIE's entity found in the map?
Frederic Riss563cba62015-01-28 22:15:14 +0000101 };
102
Frederic Riss3cced052015-03-14 03:46:40 +0000103 CompileUnit(DWARFUnit &OrigUnit, unsigned ID)
104 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000105 Ranges(RangeAlloc) {
Frederic Riss563cba62015-01-28 22:15:14 +0000106 Info.resize(OrigUnit.getNumDIEs());
107 }
108
Frederic Riss2838f9e2015-03-05 05:29:05 +0000109 CompileUnit(CompileUnit &&RHS)
110 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
111 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
Frederic Riss1af75f72015-03-12 18:45:10 +0000112 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
113 // The CompileUnit container has been 'reserve()'d with the right
114 // size. We cannot move the IntervalMap anyway.
115 llvm_unreachable("CompileUnits should not be moved.");
116 }
David Blaikiea8adc132015-03-04 22:20:52 +0000117
Frederic Rissc3349d42015-02-13 23:18:27 +0000118 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +0000119
Frederic Riss3cced052015-03-14 03:46:40 +0000120 unsigned getUniqueID() const { return ID; }
121
Frederic Rissb8b43d52015-03-04 22:07:44 +0000122 DIE *getOutputUnitDIE() const { return CUDie.get(); }
123 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
124
Frederic Riss563cba62015-01-28 22:15:14 +0000125 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
126 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
127
Frederic Rissb8b43d52015-03-04 22:07:44 +0000128 uint64_t getStartOffset() const { return StartOffset; }
129 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000130 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000131
Frederic Riss5a62dc32015-03-13 18:35:54 +0000132 uint64_t getLowPc() const { return LowPc; }
133 uint64_t getHighPc() const { return HighPc; }
134
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000135 Optional<PatchLocation> getUnitRangesAttribute() const {
136 return UnitRangeAttribute;
137 }
Frederic Riss25440872015-03-13 23:30:31 +0000138 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000139 const std::vector<PatchLocation> &getRangesAttributes() const {
Frederic Riss25440872015-03-13 23:30:31 +0000140 return RangeAttributes;
141 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000142
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000143 const std::vector<std::pair<PatchLocation, int64_t>> &
Frederic Rissdfb97902015-03-14 15:49:07 +0000144 getLocationAttributes() const {
145 return LocationAttributes;
146 }
147
Frederic Riss9d441b62015-03-06 23:22:50 +0000148 /// \brief Compute the end offset for this unit. Must be
149 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000150 /// \returns the next unit offset (which is also the current
151 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000152 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000153
Frederic Riss6afcfce2015-03-13 18:35:57 +0000154 /// \brief Keep track of a forward reference to DIE \p Die in \p
155 /// RefUnit by \p Attr. The attribute should be fixed up later to
156 /// point to the absolute offset of \p Die in the debug_info section.
157 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000158 PatchLocation Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000159
160 /// \brief Apply all fixups recored by noteForwardReference().
161 void fixupForwardReferences();
162
Frederic Riss1af75f72015-03-12 18:45:10 +0000163 /// \brief Add a function range [\p LowPC, \p HighPC) that is
164 /// relocatad by applying offset \p PCOffset.
165 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
166
Frederic Riss5c9c7062015-03-13 23:55:29 +0000167 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000168 /// patch up later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000169 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
Frederic Riss25440872015-03-13 23:30:31 +0000170
Frederic Rissdfb97902015-03-14 15:49:07 +0000171 /// \brief Keep track of a location attribute pointing to a location
172 /// list in the debug_loc section.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000173 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
Frederic Rissdfb97902015-03-14 15:49:07 +0000174
Frederic Rissbce93ff2015-03-16 02:05:10 +0000175 /// \brief Add a name accelerator entry for \p Die with \p Name
176 /// which is stored in the string table at \p Offset.
177 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
178 bool SkipPubnamesSection = false);
179
180 /// \brief Add a type accelerator entry for \p Die with \p Name
181 /// which is stored in the string table at \p Offset.
182 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
183
184 struct AccelInfo {
185 StringRef Name; ///< Name of the entry.
186 const DIE *Die; ///< DIE this entry describes.
187 uint32_t NameOffset; ///< Offset of Name in the string pool.
188 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
189
190 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
191 bool SkipPubSection = false)
192 : Name(Name), Die(Die), NameOffset(NameOffset),
193 SkipPubSection(SkipPubSection) {}
194 };
195
196 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
197 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
198
Frederic Riss563cba62015-01-28 22:15:14 +0000199private:
200 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000201 unsigned ID;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000202 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
203 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
204
205 uint64_t StartOffset;
206 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000207
Frederic Riss5a62dc32015-03-13 18:35:54 +0000208 uint64_t LowPc;
209 uint64_t HighPc;
210
Frederic Riss9833de62015-03-06 23:22:53 +0000211 /// \brief A list of attributes to fixup with the absolute offset of
212 /// a DIE in the debug_info section.
213 ///
214 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000215 /// cloning because for cross-cu forward refences the target DIE's
216 /// offset isn't known you emit the reference attribute.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000217 std::vector<std::tuple<DIE *, const CompileUnit *, PatchLocation>>
Frederic Riss6afcfce2015-03-13 18:35:57 +0000218 ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000219
Frederic Riss25440872015-03-13 23:30:31 +0000220 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000221 /// \brief The ranges in that interval map are the PC ranges for
222 /// functions in this unit, associated with the PC offset to apply
223 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000224 FunctionIntervals Ranges;
225
226 /// \brief DW_AT_ranges attributes to patch after we have gathered
227 /// all the unit's function addresses.
228 /// @{
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000229 std::vector<PatchLocation> RangeAttributes;
230 Optional<PatchLocation> UnitRangeAttribute;
Frederic Riss25440872015-03-13 23:30:31 +0000231 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000232
233 /// \brief Location attributes that need to be transfered from th
234 /// original debug_loc section to the liked one. They are stored
235 /// along with the PC offset that is to be applied to their
236 /// function's address.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000237 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
Frederic Rissbce93ff2015-03-16 02:05:10 +0000238
239 /// \brief Accelerator entries for the unit, both for the pub*
240 /// sections and the apple* ones.
241 /// @{
242 std::vector<AccelInfo> Pubnames;
243 std::vector<AccelInfo> Pubtypes;
244 /// @}
Frederic Riss563cba62015-01-28 22:15:14 +0000245};
246
Frederic Riss9d441b62015-03-06 23:22:50 +0000247uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000248 NextUnitOffset = StartOffset + 11 /* Header size */;
249 // The root DIE might be null, meaning that the Unit had nothing to
250 // contribute to the linked output. In that case, we will emit the
251 // unit header without any actual DIE.
252 if (CUDie)
253 NextUnitOffset += CUDie->getSize();
254 return NextUnitOffset;
255}
256
Frederic Riss6afcfce2015-03-13 18:35:57 +0000257/// \brief Keep track of a forward cross-cu reference from this unit
258/// to \p Die that lives in \p RefUnit.
259void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000260 PatchLocation Attr) {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000261 ForwardDIEReferences.emplace_back(Die, RefUnit, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000262}
263
264/// \brief Apply all fixups recorded by noteForwardReference().
265void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000266 for (const auto &Ref : ForwardDIEReferences) {
267 DIE *RefDie;
268 const CompileUnit *RefUnit;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000269 PatchLocation Attr;
Frederic Riss6afcfce2015-03-13 18:35:57 +0000270 std::tie(RefDie, RefUnit, Attr) = Ref;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000271 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
Frederic Riss6afcfce2015-03-13 18:35:57 +0000272 }
Frederic Riss9833de62015-03-06 23:22:53 +0000273}
274
Frederic Riss5a62dc32015-03-13 18:35:54 +0000275void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
276 int64_t PcOffset) {
277 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
278 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
279 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000280}
281
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000282void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
Frederic Riss25440872015-03-13 23:30:31 +0000283 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
284 RangeAttributes.push_back(Attr);
285 else
286 UnitRangeAttribute = Attr;
287}
288
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000289void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
Frederic Rissdfb97902015-03-14 15:49:07 +0000290 LocationAttributes.emplace_back(Attr, PcOffset);
291}
292
Frederic Rissbce93ff2015-03-16 02:05:10 +0000293/// \brief Add a name accelerator entry for \p Die with \p Name
294/// which is stored in the string table at \p Offset.
295void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
296 uint32_t Offset, bool SkipPubSection) {
297 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
298}
299
300/// \brief Add a type accelerator entry for \p Die with \p Name
301/// which is stored in the string table at \p Offset.
302void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
303 uint32_t Offset) {
304 Pubtypes.emplace_back(Name, Die, Offset, false);
305}
306
Frederic Rissef648462015-03-06 17:56:30 +0000307/// \brief A string table that doesn't need relocations.
308///
309/// We are doing a final link, no need for a string table that
310/// has relocation entries for every reference to it. This class
311/// provides this ablitity by just associating offsets with
312/// strings.
313class NonRelocatableStringpool {
314public:
315 /// \brief Entries are stored into the StringMap and simply linked
316 /// together through the second element of this pair in order to
317 /// keep track of insertion order.
318 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
319 MapTy;
320
321 NonRelocatableStringpool()
322 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
323 // Legacy dsymutil puts an empty string at the start of the line
324 // table.
325 getStringOffset("");
326 }
327
328 /// \brief Get the offset of string \p S in the string table. This
329 /// can insert a new element or return the offset of a preexisitng
330 /// one.
331 uint32_t getStringOffset(StringRef S);
332
333 /// \brief Get permanent storage for \p S (but do not necessarily
334 /// emit \p S in the output section).
335 /// \returns The StringRef that points to permanent storage to use
336 /// in place of \p S.
337 StringRef internString(StringRef S);
338
339 // \brief Return the first entry of the string table.
340 const MapTy::MapEntryTy *getFirstEntry() const {
341 return getNextEntry(&Sentinel);
342 }
343
344 // \brief Get the entry following \p E in the string table or null
345 // if \p E was the last entry.
346 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
347 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
348 }
349
350 uint64_t getSize() { return CurrentEndOffset; }
351
352private:
353 MapTy Strings;
354 uint32_t CurrentEndOffset;
355 MapTy::MapEntryTy Sentinel, *Last;
356};
357
358/// \brief Get the offset of string \p S in the string table. This
359/// can insert a new element or return the offset of a preexisitng
360/// one.
361uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
362 if (S.empty() && !Strings.empty())
363 return 0;
364
365 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
366 MapTy::iterator It;
367 bool Inserted;
368
369 // A non-empty string can't be at offset 0, so if we have an entry
370 // with a 0 offset, it must be a previously interned string.
371 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
372 if (Inserted || It->getValue().first == 0) {
373 // Set offset and chain at the end of the entries list.
374 It->getValue().first = CurrentEndOffset;
375 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
376 Last->getValue().second = &*It;
377 Last = &*It;
378 }
379 return It->getValue().first;
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000380}
Frederic Rissef648462015-03-06 17:56:30 +0000381
382/// \brief Put \p S into the StringMap so that it gets permanent
383/// storage, but do not actually link it in the chain of elements
384/// that go into the output section. A latter call to
385/// getStringOffset() with the same string will chain it though.
386StringRef NonRelocatableStringpool::internString(StringRef S) {
387 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
388 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
389 return InsertResult.first->getKey();
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000390}
Frederic Rissef648462015-03-06 17:56:30 +0000391
Frederic Rissc99ea202015-02-28 00:29:11 +0000392/// \brief The Dwarf streaming logic
393///
394/// All interactions with the MC layer that is used to build the debug
395/// information binary representation are handled in this class.
396class DwarfStreamer {
397 /// \defgroup MCObjects MC layer objects constructed by the streamer
398 /// @{
399 std::unique_ptr<MCRegisterInfo> MRI;
400 std::unique_ptr<MCAsmInfo> MAI;
401 std::unique_ptr<MCObjectFileInfo> MOFI;
402 std::unique_ptr<MCContext> MC;
403 MCAsmBackend *MAB; // Owned by MCStreamer
404 std::unique_ptr<MCInstrInfo> MII;
405 std::unique_ptr<MCSubtargetInfo> MSTI;
406 MCCodeEmitter *MCE; // Owned by MCStreamer
407 MCStreamer *MS; // Owned by AsmPrinter
408 std::unique_ptr<TargetMachine> TM;
409 std::unique_ptr<AsmPrinter> Asm;
410 /// @}
411
412 /// \brief the file we stream the linked Dwarf to.
413 std::unique_ptr<raw_fd_ostream> OutFile;
414
Frederic Riss25440872015-03-13 23:30:31 +0000415 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000416 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000417 uint32_t LineSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000418
Frederic Rissbce93ff2015-03-16 02:05:10 +0000419 /// \brief Emit the pubnames or pubtypes section contribution for \p
420 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000421 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000422 const CompileUnit &Unit,
423 const std::vector<CompileUnit::AccelInfo> &Names);
424
Frederic Rissc99ea202015-02-28 00:29:11 +0000425public:
426 /// \brief Actually create the streamer and the ouptut file.
427 ///
428 /// This could be done directly in the constructor, but it feels
429 /// more natural to handle errors through return value.
430 bool init(Triple TheTriple, StringRef OutputFilename);
431
Frederic Rissb8b43d52015-03-04 22:07:44 +0000432 /// \brief Dump the file to the disk.
Frederic Rissc99ea202015-02-28 00:29:11 +0000433 bool finish();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000434
435 AsmPrinter &getAsmPrinter() const { return *Asm; }
436
437 /// \brief Set the current output section to debug_info and change
438 /// the MC Dwarf version to \p DwarfVersion.
439 void switchToDebugInfoSection(unsigned DwarfVersion);
440
441 /// \brief Emit the compilation unit header for \p Unit in the
442 /// debug_info section.
443 ///
444 /// As a side effect, this also switches the current Dwarf version
445 /// of the MC layer to the one of U.getOrigUnit().
446 void emitCompileUnitHeader(CompileUnit &Unit);
447
448 /// \brief Recursively emit the DIE tree rooted at \p Die.
449 void emitDIE(DIE &Die);
450
451 /// \brief Emit the abbreviation table \p Abbrevs to the
452 /// debug_abbrev section.
453 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000454
455 /// \brief Emit the string table described by \p Pool.
456 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000457
458 /// \brief Emit debug_ranges for \p FuncRange by translating the
459 /// original \p Entries.
460 void emitRangesEntries(
461 int64_t UnitPcOffset, uint64_t OrigLowPc,
462 FunctionIntervals::const_iterator FuncRange,
463 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
464 unsigned AddressSize);
465
Frederic Riss563b1b02015-03-14 03:46:51 +0000466 /// \brief Emit debug_aranges entries for \p Unit and if \p
467 /// DoRangesSection is true, also emit the debug_ranges entries for
468 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
469 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000470
471 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000472
473 /// \brief Emit the debug_loc contribution for \p Unit by copying
474 /// the entries from \p Dwarf and offseting them. Update the
475 /// location attributes to point to the new entries.
476 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000477
478 /// \brief Emit the line table described in \p Rows into the
479 /// debug_line section.
480 void emitLineTableForUnit(StringRef PrologueBytes, unsigned MinInstLength,
481 std::vector<DWARFDebugLine::Row> &Rows,
482 unsigned AdddressSize);
483
484 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000485
486 /// \brief Emit the .debug_pubnames contribution for \p Unit.
487 void emitPubNamesForUnit(const CompileUnit &Unit);
488
489 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
490 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Rissc99ea202015-02-28 00:29:11 +0000491};
492
493bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
494 std::string ErrorStr;
495 std::string TripleName;
496 StringRef Context = "dwarf streamer init";
497
498 // Get the target.
499 const Target *TheTarget =
500 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
501 if (!TheTarget)
502 return error(ErrorStr, Context);
503 TripleName = TheTriple.getTriple();
504
505 // Create all the MC Objects.
506 MRI.reset(TheTarget->createMCRegInfo(TripleName));
507 if (!MRI)
508 return error(Twine("no register info for target ") + TripleName, Context);
509
510 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
511 if (!MAI)
512 return error("no asm info for target " + TripleName, Context);
513
514 MOFI.reset(new MCObjectFileInfo);
515 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
516 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
517 *MC);
518
519 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
520 if (!MAB)
521 return error("no asm backend for target " + TripleName, Context);
522
523 MII.reset(TheTarget->createMCInstrInfo());
524 if (!MII)
525 return error("no instr info info for target " + TripleName, Context);
526
527 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
528 if (!MSTI)
529 return error("no subtarget info for target " + TripleName, Context);
530
Eric Christopher0169e422015-03-10 22:03:14 +0000531 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000532 if (!MCE)
533 return error("no code emitter for target " + TripleName, Context);
534
535 // Create the output file.
536 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000537 OutFile =
538 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000539 if (EC)
540 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
541
Rafael Espindolaf696df12015-03-16 22:29:29 +0000542 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
Rafael Espindola36a15cb2015-03-20 20:00:01 +0000543 *MSTI, false,
544 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000545 if (!MS)
546 return error("no object streamer for target " + TripleName, Context);
547
548 // Finally create the AsmPrinter we'll use to emit the DIEs.
549 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
550 if (!TM)
551 return error("no target machine for target " + TripleName, Context);
552
553 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
554 if (!Asm)
555 return error("no asm printer for target " + TripleName, Context);
556
Frederic Riss25440872015-03-13 23:30:31 +0000557 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000558 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000559 LineSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000560
Frederic Rissc99ea202015-02-28 00:29:11 +0000561 return true;
562}
563
564bool DwarfStreamer::finish() {
565 MS->Finish();
566 return true;
567}
568
Frederic Rissb8b43d52015-03-04 22:07:44 +0000569/// \brief Set the current output section to debug_info and change
570/// the MC Dwarf version to \p DwarfVersion.
571void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
572 MS->SwitchSection(MOFI->getDwarfInfoSection());
573 MC->setDwarfVersion(DwarfVersion);
574}
575
576/// \brief Emit the compilation unit header for \p Unit in the
577/// debug_info section.
578///
579/// A Dwarf scetion header is encoded as:
580/// uint32_t Unit length (omiting this field)
581/// uint16_t Version
582/// uint32_t Abbreviation table offset
583/// uint8_t Address size
584///
585/// Leading to a total of 11 bytes.
586void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
587 unsigned Version = Unit.getOrigUnit().getVersion();
588 switchToDebugInfoSection(Version);
589
590 // Emit size of content not including length itself. The size has
591 // already been computed in CompileUnit::computeOffsets(). Substract
592 // 4 to that size to account for the length field.
593 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
594 Asm->EmitInt16(Version);
595 // We share one abbreviations table across all units so it's always at the
596 // start of the section.
597 Asm->EmitInt32(0);
598 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
599}
600
601/// \brief Emit the \p Abbrevs array as the shared abbreviation table
602/// for the linked Dwarf file.
603void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
604 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
605 Asm->emitDwarfAbbrevs(Abbrevs);
606}
607
608/// \brief Recursively emit the DIE tree rooted at \p Die.
609void DwarfStreamer::emitDIE(DIE &Die) {
610 MS->SwitchSection(MOFI->getDwarfInfoSection());
611 Asm->emitDwarfDIE(Die);
612}
613
Frederic Rissef648462015-03-06 17:56:30 +0000614/// \brief Emit the debug_str section stored in \p Pool.
615void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000616 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000617 for (auto *Entry = Pool.getFirstEntry(); Entry;
618 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000619 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000620 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
621}
622
Frederic Riss25440872015-03-13 23:30:31 +0000623/// \brief Emit the debug_range section contents for \p FuncRange by
624/// translating the original \p Entries. The debug_range section
625/// format is totally trivial, consisting just of pairs of address
626/// sized addresses describing the ranges.
627void DwarfStreamer::emitRangesEntries(
628 int64_t UnitPcOffset, uint64_t OrigLowPc,
629 FunctionIntervals::const_iterator FuncRange,
630 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
631 unsigned AddressSize) {
632 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
633
634 // Offset each range by the right amount.
635 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
636 for (const auto &Range : Entries) {
637 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
638 warn("unsupported base address selection operation",
639 "emitting debug_ranges");
640 break;
641 }
642 // Do not emit empty ranges.
643 if (Range.StartAddress == Range.EndAddress)
644 continue;
645
646 // All range entries should lie in the function range.
647 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
648 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
649 warn("inconsistent range data.", "emitting debug_ranges");
650 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
651 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
652 RangesSectionSize += 2 * AddressSize;
653 }
654
655 // Add the terminator entry.
656 MS->EmitIntValue(0, AddressSize);
657 MS->EmitIntValue(0, AddressSize);
658 RangesSectionSize += 2 * AddressSize;
659}
660
Frederic Riss563b1b02015-03-14 03:46:51 +0000661/// \brief Emit the debug_aranges contribution of a unit and
662/// if \p DoDebugRanges is true the debug_range contents for a
663/// compile_unit level DW_AT_ranges attribute (Which are basically the
664/// same thing with a different base address).
665/// Just aggregate all the ranges gathered inside that unit.
666void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
667 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000668 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
669 // Gather the ranges in a vector, so that we can simplify them. The
670 // IntervalMap will have coalesced the non-linked ranges, but here
671 // we want to coalesce the linked addresses.
672 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
673 const auto &FunctionRanges = Unit.getFunctionRanges();
674 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
675 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000676 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
677 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000678
679 // The object addresses where sorted, but again, the linked
680 // addresses might end up in a different order.
681 std::sort(Ranges.begin(), Ranges.end());
682
Frederic Riss563b1b02015-03-14 03:46:51 +0000683 if (!Ranges.empty()) {
684 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
685
Rafael Espindola9ab09232015-03-17 20:07:06 +0000686 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
687 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000688
689 unsigned HeaderSize =
690 sizeof(int32_t) + // Size of contents (w/o this field
691 sizeof(int16_t) + // DWARF ARange version number
692 sizeof(int32_t) + // Offset of CU in the .debug_info section
693 sizeof(int8_t) + // Pointer Size (in bytes)
694 sizeof(int8_t); // Segment Size (in bytes)
695
696 unsigned TupleSize = AddressSize * 2;
697 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
698
699 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000700 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000701 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
702 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
703 Asm->EmitInt8(AddressSize); // Address size
704 Asm->EmitInt8(0); // Segment size
705
Lang Hames9ff69c82015-04-24 19:11:51 +0000706 Asm->OutStreamer->EmitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000707
708 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
709 ++Range) {
710 uint64_t RangeStart = Range->first;
711 MS->EmitIntValue(RangeStart, AddressSize);
712 while ((Range + 1) != End && Range->second == (Range + 1)->first)
713 ++Range;
714 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
715 }
716
717 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000718 Asm->OutStreamer->EmitIntValue(0, AddressSize);
719 Asm->OutStreamer->EmitIntValue(0, AddressSize);
720 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000721 }
722
723 if (!DoDebugRanges)
724 return;
725
726 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
727 // Offset each range by the right amount.
728 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000729 // Emit coalesced ranges.
730 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000731 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000732 while (Range + 1 != End && Range->second == (Range + 1)->first)
733 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000734 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000735 RangesSectionSize += 2 * AddressSize;
736 }
737
738 // Add the terminator entry.
739 MS->EmitIntValue(0, AddressSize);
740 MS->EmitIntValue(0, AddressSize);
741 RangesSectionSize += 2 * AddressSize;
742}
743
Frederic Rissdfb97902015-03-14 15:49:07 +0000744/// \brief Emit location lists for \p Unit and update attribtues to
745/// point to the new entries.
746void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
747 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000748 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000749
750 if (Attributes.empty())
751 return;
752
753 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
754
755 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
756 const DWARFSection &InputSec = Dwarf.getLocSection();
757 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
758 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000759 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000760 int64_t UnitPcOffset = 0;
761 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
762 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
763 if (OrigLowPc != -1ULL)
764 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
765
766 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000767 uint32_t Offset = Attr.first.get();
768 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000769 // This is the quantity to add to the old location address to get
770 // the correct address for the new one.
771 int64_t LocPcOffset = Attr.second + UnitPcOffset;
772 while (Data.isValidOffset(Offset)) {
773 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
774 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
775 LocSectionSize += 2 * AddressSize;
776 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000777 Asm->OutStreamer->EmitIntValue(0, AddressSize);
778 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000779 break;
780 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000781 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
782 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000783 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000784 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000785 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000786 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000787 StringRef(InputSec.Data.substr(Offset, Length)));
788 Offset += Length;
789 LocSectionSize += Length + 2;
790 }
791 }
792}
793
Frederic Riss63786b02015-03-15 20:45:43 +0000794void DwarfStreamer::emitLineTableForUnit(StringRef PrologueBytes,
795 unsigned MinInstLength,
796 std::vector<DWARFDebugLine::Row> &Rows,
797 unsigned PointerSize) {
798 // Switch to the section where the table will be emitted into.
799 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000800 MCSymbol *LineStartSym = MC->createTempSymbol();
801 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000802
803 // The first 4 bytes is the total length of the information for this
804 // compilation unit (not including these 4 bytes for the length).
805 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000806 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000807 // Copy Prologue.
808 MS->EmitBytes(PrologueBytes);
809 LineSectionSize += PrologueBytes.size() + 4;
810
Frederic Rissc3820d02015-03-15 22:20:28 +0000811 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000812 raw_svector_ostream EncodingOS(EncodingBuffer);
813
814 if (Rows.empty()) {
815 // We only have the dummy entry, dsymutil emits an entry with a 0
816 // address in that case.
817 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
818 MS->EmitBytes(EncodingOS.str());
819 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000820 MS->EmitLabel(LineEndSym);
821 return;
822 }
823
824 // Line table state machine fields
825 unsigned FileNum = 1;
826 unsigned LastLine = 1;
827 unsigned Column = 0;
828 unsigned IsStatement = 1;
829 unsigned Isa = 0;
830 uint64_t Address = -1ULL;
831
832 unsigned RowsSinceLastSequence = 0;
833
834 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
835 auto &Row = Rows[Idx];
836
837 int64_t AddressDelta;
838 if (Address == -1ULL) {
839 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
840 MS->EmitULEB128IntValue(PointerSize + 1);
841 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
842 MS->EmitIntValue(Row.Address, PointerSize);
843 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
844 AddressDelta = 0;
845 } else {
846 AddressDelta = (Row.Address - Address) / MinInstLength;
847 }
848
849 // FIXME: code copied and transfromed from
850 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
851 // this code, but the current compatibility requirement with
852 // classic dsymutil makes it hard. Revisit that once this
853 // requirement is dropped.
854
855 if (FileNum != Row.File) {
856 FileNum = Row.File;
857 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
858 MS->EmitULEB128IntValue(FileNum);
859 LineSectionSize += 1 + getULEB128Size(FileNum);
860 }
861 if (Column != Row.Column) {
862 Column = Row.Column;
863 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
864 MS->EmitULEB128IntValue(Column);
865 LineSectionSize += 1 + getULEB128Size(Column);
866 }
867
868 // FIXME: We should handle the discriminator here, but dsymutil
869 // doesn' consider it, thus ignore it for now.
870
871 if (Isa != Row.Isa) {
872 Isa = Row.Isa;
873 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
874 MS->EmitULEB128IntValue(Isa);
875 LineSectionSize += 1 + getULEB128Size(Isa);
876 }
877 if (IsStatement != Row.IsStmt) {
878 IsStatement = Row.IsStmt;
879 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
880 LineSectionSize += 1;
881 }
882 if (Row.BasicBlock) {
883 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
884 LineSectionSize += 1;
885 }
886
887 if (Row.PrologueEnd) {
888 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
889 LineSectionSize += 1;
890 }
891
892 if (Row.EpilogueBegin) {
893 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
894 LineSectionSize += 1;
895 }
896
897 int64_t LineDelta = int64_t(Row.Line) - LastLine;
898 if (!Row.EndSequence) {
899 MCDwarfLineAddr::Encode(*MC, LineDelta, AddressDelta, EncodingOS);
900 MS->EmitBytes(EncodingOS.str());
901 LineSectionSize += EncodingBuffer.size();
902 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000903 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000904 Address = Row.Address;
905 LastLine = Row.Line;
906 RowsSinceLastSequence++;
907 } else {
908 if (LineDelta) {
909 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
910 MS->EmitSLEB128IntValue(LineDelta);
911 LineSectionSize += 1 + getSLEB128Size(LineDelta);
912 }
913 if (AddressDelta) {
914 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
915 MS->EmitULEB128IntValue(AddressDelta);
916 LineSectionSize += 1 + getULEB128Size(AddressDelta);
917 }
918 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
919 MS->EmitBytes(EncodingOS.str());
920 LineSectionSize += EncodingBuffer.size();
921 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000922 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000923 Address = -1ULL;
924 LastLine = FileNum = IsStatement = 1;
925 RowsSinceLastSequence = Column = Isa = 0;
926 }
927 }
928
929 if (RowsSinceLastSequence) {
930 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
931 MS->EmitBytes(EncodingOS.str());
932 LineSectionSize += EncodingBuffer.size();
933 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000934 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000935 }
936
937 MS->EmitLabel(LineEndSym);
938}
939
Frederic Rissbce93ff2015-03-16 02:05:10 +0000940/// \brief Emit the pubnames or pubtypes section contribution for \p
941/// Unit into \p Sec. The data is provided in \p Names.
942void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000943 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000944 const std::vector<CompileUnit::AccelInfo> &Names) {
945 if (Names.empty())
946 return;
947
948 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +0000949 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +0000950 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
951 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +0000952
953 bool HeaderEmitted = false;
954 // Emit the pubnames for this compilation unit.
955 for (const auto &Name : Names) {
956 if (Name.SkipPubSection)
957 continue;
958
959 if (!HeaderEmitted) {
960 // Emit the header.
961 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +0000962 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +0000963 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
964 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
965 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
966 HeaderEmitted = true;
967 }
968 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +0000969 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +0000970 StringRef(Name.Name.data(), Name.Name.size() + 1));
971 }
972
973 if (!HeaderEmitted)
974 return;
975 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +0000976 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +0000977}
978
979/// \brief Emit .debug_pubnames for \p Unit.
980void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
981 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
982 "names", Unit, Unit.getPubnames());
983}
984
985/// \brief Emit .debug_pubtypes for \p Unit.
986void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
987 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
988 "types", Unit, Unit.getPubtypes());
989}
990
Frederic Rissd3455182015-01-28 18:27:01 +0000991/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +0000992///
993/// The link of the dwarf information from the object files will be
994/// driven by the selection of 'root DIEs', which are DIEs that
995/// describe variables or functions that are present in the linked
996/// binary (and thus have entries in the debug map). All the debug
997/// information that will be linked (the DIEs, but also the line
998/// tables, ranges, ...) is derived from that set of root DIEs.
999///
1000/// The root DIEs are identified because they contain relocations that
1001/// correspond to a debug map entry at specific places (the low_pc for
1002/// a function, the location for a variable). These relocations are
1003/// called ValidRelocs in the DwarfLinker and are gathered as a very
1004/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001005class DwarfLinker {
1006public:
Frederic Rissb9818322015-02-28 00:29:07 +00001007 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1008 : OutputFilename(OutputFilename), Options(Options),
1009 BinHolder(Options.Verbose) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001010
Frederic Rissb8b43d52015-03-04 22:07:44 +00001011 ~DwarfLinker() {
1012 for (auto *Abbrev : Abbreviations)
1013 delete Abbrev;
1014 }
1015
Frederic Rissd3455182015-01-28 18:27:01 +00001016 /// \brief Link the contents of the DebugMap.
1017 bool link(const DebugMap &);
1018
1019private:
Frederic Riss563cba62015-01-28 22:15:14 +00001020 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001021 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001022
1023 /// \brief Called at the end of a debug object link.
1024 void endDebugObject();
1025
Frederic Riss1036e642015-02-13 23:18:22 +00001026 /// \defgroup FindValidRelocations Translate debug map into a list
1027 /// of relevant relocations
1028 ///
1029 /// @{
1030 struct ValidReloc {
1031 uint32_t Offset;
1032 uint32_t Size;
1033 uint64_t Addend;
1034 const DebugMapObject::DebugMapEntry *Mapping;
1035
1036 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1037 const DebugMapObject::DebugMapEntry *Mapping)
1038 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1039
1040 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1041 };
1042
1043 /// \brief The valid relocations for the current DebugMapObject.
1044 /// This vector is sorted by relocation offset.
1045 std::vector<ValidReloc> ValidRelocs;
1046
1047 /// \brief Index into ValidRelocs of the next relocation to
1048 /// consider. As we walk the DIEs in acsending file offset and as
1049 /// ValidRelocs is sorted by file offset, keeping this index
1050 /// uptodate is all we have to do to have a cheap lookup during the
Frederic Riss23e20e92015-03-07 01:25:09 +00001051 /// root DIE selection and during DIE cloning.
Frederic Riss1036e642015-02-13 23:18:22 +00001052 unsigned NextValidReloc;
1053
1054 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1055 const DebugMapObject &DMO);
1056
1057 bool findValidRelocs(const object::SectionRef &Section,
1058 const object::ObjectFile &Obj,
1059 const DebugMapObject &DMO);
1060
1061 void findValidRelocsMachO(const object::SectionRef &Section,
1062 const object::MachOObjectFile &Obj,
1063 const DebugMapObject &DMO);
1064 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +00001065
Frederic Riss84c09a52015-02-13 23:18:34 +00001066 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1067 ///
1068 /// @{
1069 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1070 /// keep. Store that information in \p CU's DIEInfo.
1071 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1072 const DebugMapObject &DMO, CompileUnit &CU,
1073 unsigned Flags);
1074
1075 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1076 enum TravesalFlags {
1077 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1078 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1079 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1080 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
1081 };
1082
1083 /// \brief Mark the passed DIE as well as all the ones it depends on
1084 /// as kept.
1085 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1086 CompileUnit::DIEInfo &MyInfo,
1087 const DebugMapObject &DMO, CompileUnit &CU,
1088 unsigned Flags);
1089
1090 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1091 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1092 unsigned Flags);
1093
1094 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1095 CompileUnit &Unit,
1096 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1097
1098 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1099 CompileUnit &Unit,
1100 CompileUnit::DIEInfo &MyInfo,
1101 unsigned Flags);
1102
1103 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1104 CompileUnit::DIEInfo &Info);
1105 /// @}
1106
Frederic Rissb8b43d52015-03-04 22:07:44 +00001107 /// \defgroup Linking Methods used to link the debug information
1108 ///
1109 /// @{
1110 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1111 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1112 /// stripped out and addresses have been rewritten according to the
1113 /// debug map.
1114 ///
1115 /// \param OutOffset is the offset the cloned DIE in the output
1116 /// compile unit.
Frederic Riss31da3242015-03-11 18:45:52 +00001117 /// \param PCOffset (while cloning a function scope) is the offset
1118 /// applied to the entry point of the function to get the linked address.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001119 ///
1120 /// \returns the root of the cloned tree.
1121 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Frederic Riss31da3242015-03-11 18:45:52 +00001122 int64_t PCOffset, uint32_t OutOffset);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001123
1124 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1125
Frederic Riss31da3242015-03-11 18:45:52 +00001126 /// \brief Information gathered and exchanged between the various
1127 /// clone*Attributes helpers about the attributes of a particular DIE.
1128 struct AttributesInfo {
Frederic Rissbce93ff2015-03-16 02:05:10 +00001129 const char *Name, *MangledName; ///< Names.
1130 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1131
Frederic Riss31da3242015-03-11 18:45:52 +00001132 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1133 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1134
Frederic Rissbce93ff2015-03-16 02:05:10 +00001135 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1136 bool IsDeclaration; ///< Is this DIE only a declaration?
1137
1138 AttributesInfo()
1139 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1140 MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1141 IsDeclaration(false) {}
Frederic Riss31da3242015-03-11 18:45:52 +00001142 };
1143
Frederic Rissb8b43d52015-03-04 22:07:44 +00001144 /// \brief Helper for cloneDIE.
1145 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1146 CompileUnit &U, const DWARFFormValue &Val,
Frederic Riss31da3242015-03-11 18:45:52 +00001147 const AttributeSpec AttrSpec, unsigned AttrSize,
1148 AttributesInfo &AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001149
1150 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +00001151 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1152 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001153
1154 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +00001155 unsigned
1156 cloneDieReferenceAttribute(DIE &Die,
1157 const DWARFDebugInfoEntryMinimal &InputDIE,
1158 AttributeSpec AttrSpec, unsigned AttrSize,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001159 const DWARFFormValue &Val, CompileUnit &Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001160
1161 /// \brief Helper for cloneDIE.
1162 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1163 const DWARFFormValue &Val, unsigned AttrSize);
1164
1165 /// \brief Helper for cloneDIE.
Frederic Riss31da3242015-03-11 18:45:52 +00001166 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1167 const DWARFFormValue &Val,
1168 const CompileUnit &Unit, AttributesInfo &Info);
1169
1170 /// \brief Helper for cloneDIE.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001171 unsigned cloneScalarAttribute(DIE &Die,
1172 const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss25440872015-03-13 23:30:31 +00001173 CompileUnit &U, AttributeSpec AttrSpec,
Frederic Rissdfb97902015-03-14 15:49:07 +00001174 const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001175 AttributesInfo &Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001176
Frederic Riss23e20e92015-03-07 01:25:09 +00001177 /// \brief Helper for cloneDIE.
1178 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1179 bool isLittleEndian);
1180
Frederic Rissb8b43d52015-03-04 22:07:44 +00001181 /// \brief Assign an abbreviation number to \p Abbrev
1182 void AssignAbbrev(DIEAbbrev &Abbrev);
1183
1184 /// \brief FoldingSet that uniques the abbreviations.
1185 FoldingSet<DIEAbbrev> AbbreviationsSet;
1186 /// \brief Storage for the unique Abbreviations.
1187 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1188 /// be changed to a vecot of unique_ptrs.
1189 std::vector<DIEAbbrev *> Abbreviations;
1190
Frederic Riss25440872015-03-13 23:30:31 +00001191 /// \brief Compute and emit debug_ranges section for \p Unit, and
1192 /// patch the attributes referencing it.
1193 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1194
1195 /// \brief Generate and emit the DW_AT_ranges attribute for a
1196 /// compile_unit if it had one.
1197 void generateUnitRanges(CompileUnit &Unit) const;
1198
Frederic Riss63786b02015-03-15 20:45:43 +00001199 /// \brief Extract the line tables fromt he original dwarf, extract
1200 /// the relevant parts according to the linked function ranges and
1201 /// emit the result in the debug_line section.
1202 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1203
Frederic Rissbce93ff2015-03-16 02:05:10 +00001204 /// \brief Emit the accelerator entries for \p Unit.
1205 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1206
Frederic Rissb8b43d52015-03-04 22:07:44 +00001207 /// \brief DIELoc objects that need to be destructed (but not freed!).
1208 std::vector<DIELoc *> DIELocs;
1209 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1210 std::vector<DIEBlock *> DIEBlocks;
1211 /// \brief Allocator used for all the DIEValue objects.
1212 BumpPtrAllocator DIEAlloc;
1213 /// @}
1214
Frederic Riss1b9da422015-02-13 23:18:29 +00001215 /// \defgroup Helpers Various helper methods.
1216 ///
1217 /// @{
1218 const DWARFDebugInfoEntryMinimal *
1219 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
1220 const DWARFDebugInfoEntryMinimal &DIE,
1221 CompileUnit *&ReferencedCU);
1222
1223 CompileUnit *getUnitForOffset(unsigned Offset);
1224
Frederic Rissbce93ff2015-03-16 02:05:10 +00001225 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1226 AttributesInfo &Info);
1227
Frederic Riss1b9da422015-02-13 23:18:29 +00001228 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
Frederic Riss25440872015-03-13 23:30:31 +00001229 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
Frederic Rissc99ea202015-02-28 00:29:11 +00001230
1231 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Riss1b9da422015-02-13 23:18:29 +00001232 /// @}
1233
Frederic Riss563cba62015-01-28 22:15:14 +00001234private:
Frederic Rissd3455182015-01-28 18:27:01 +00001235 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001236 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001237 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001238 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +00001239
1240 /// The units of the current debug map object.
1241 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001242
1243 /// The debug map object curently under consideration.
1244 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001245
1246 /// \brief The Dwarf string pool
1247 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001248
1249 /// \brief This map is keyed by the entry PC of functions in that
1250 /// debug object and the associated value is a pair storing the
1251 /// corresponding end PC and the offset to apply to get the linked
1252 /// address.
1253 ///
1254 /// See startDebugObject() for a more complete description of its use.
1255 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Rissd3455182015-01-28 18:27:01 +00001256};
1257
Frederic Riss1b9da422015-02-13 23:18:29 +00001258/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1259/// returning our CompileUnit object instead.
1260CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1261 auto CU =
1262 std::upper_bound(Units.begin(), Units.end(), Offset,
1263 [](uint32_t LHS, const CompileUnit &RHS) {
1264 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1265 });
1266 return CU != Units.end() ? &*CU : nullptr;
1267}
1268
1269/// \brief Resolve the DIE attribute reference that has been
1270/// extracted in \p RefValue. The resulting DIE migh be in another
1271/// CompileUnit which is stored into \p ReferencedCU.
1272/// \returns null if resolving fails for any reason.
1273const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1274 DWARFFormValue &RefValue, const DWARFUnit &Unit,
1275 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1276 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1277 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1278
1279 if ((RefCU = getUnitForOffset(RefOffset)))
1280 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1281 return RefDie;
1282
1283 reportWarning("could not find referenced DIE", &Unit, &DIE);
1284 return nullptr;
1285}
1286
Frederic Rissbce93ff2015-03-16 02:05:10 +00001287/// \brief Get the potential name and mangled name for the entity
1288/// described by \p Die and store them in \Info if they are not
1289/// already there.
1290/// \returns is a name was found.
1291bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1292 DWARFUnit &U, AttributesInfo &Info) {
1293 // FIXME: a bit wastefull as the first getName might return the
1294 // short name.
1295 if (!Info.MangledName &&
1296 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1297 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1298
1299 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1300 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1301
1302 return Info.Name || Info.MangledName;
1303}
1304
Frederic Riss1b9da422015-02-13 23:18:29 +00001305/// \brief Report a warning to the user, optionaly including
1306/// information about a specific \p DIE related to the warning.
1307void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001308 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001309 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001310 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001311 Context = CurrentDebugObject->getObjectFilename();
1312 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001313
Frederic Rissb9818322015-02-28 00:29:07 +00001314 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001315 return;
1316
1317 errs() << " in DIE:\n";
1318 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1319 6 /* Indent */);
1320}
1321
Frederic Rissc99ea202015-02-28 00:29:11 +00001322bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1323 if (Options.NoOutput)
1324 return true;
1325
Frederic Rissb52cf522015-02-28 00:42:37 +00001326 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001327 return Streamer->init(TheTriple, OutputFilename);
1328}
1329
Frederic Riss563cba62015-01-28 22:15:14 +00001330/// \brief Recursive helper to gather the child->parent relationships in the
1331/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +00001332static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1333 unsigned ParentIdx, CompileUnit &CU) {
Frederic Riss563cba62015-01-28 22:15:14 +00001334 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1335 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
1336
1337 if (DIE->hasChildren())
1338 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1339 Child = Child->getSibling())
Frederic Riss9aa725b2015-02-13 23:18:31 +00001340 gatherDIEParents(Child, MyIdx, CU);
Frederic Riss563cba62015-01-28 22:15:14 +00001341}
1342
Frederic Riss84c09a52015-02-13 23:18:34 +00001343static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1344 switch (Tag) {
1345 default:
1346 return false;
1347 case dwarf::DW_TAG_subprogram:
1348 case dwarf::DW_TAG_lexical_block:
1349 case dwarf::DW_TAG_subroutine_type:
1350 case dwarf::DW_TAG_structure_type:
1351 case dwarf::DW_TAG_class_type:
1352 case dwarf::DW_TAG_union_type:
1353 return true;
1354 }
1355 llvm_unreachable("Invalid Tag");
1356}
1357
Frederic Riss63786b02015-03-15 20:45:43 +00001358void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001359 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +00001360 NextValidReloc = 0;
Frederic Riss63786b02015-03-15 20:45:43 +00001361 // Iterate over the debug map entries and put all the ones that are
1362 // functions (because they have a size) into the Ranges map. This
1363 // map is very similar to the FunctionRanges that are stored in each
1364 // unit, with 2 notable differences:
1365 // - obviously this one is global, while the other ones are per-unit.
1366 // - this one contains not only the functions described in the DIE
1367 // tree, but also the ones that are only in the debug map.
1368 // The latter information is required to reproduce dsymutil's logic
1369 // while linking line tables. The cases where this information
1370 // matters look like bugs that need to be investigated, but for now
1371 // we need to reproduce dsymutil's behavior.
1372 // FIXME: Once we understood exactly if that information is needed,
1373 // maybe totally remove this (or try to use it to do a real
1374 // -gline-tables-only on Darwin.
1375 for (const auto &Entry : Obj.symbols()) {
1376 const auto &Mapping = Entry.getValue();
1377 if (Mapping.Size)
1378 Ranges[Mapping.ObjectAddress] = std::make_pair(
1379 Mapping.ObjectAddress + Mapping.Size,
1380 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1381 }
Frederic Riss563cba62015-01-28 22:15:14 +00001382}
1383
Frederic Riss1036e642015-02-13 23:18:22 +00001384void DwarfLinker::endDebugObject() {
1385 Units.clear();
1386 ValidRelocs.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001387 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001388
1389 for (auto *Block : DIEBlocks)
1390 Block->~DIEBlock();
1391 for (auto *Loc : DIELocs)
1392 Loc->~DIELoc();
1393
1394 DIEBlocks.clear();
1395 DIELocs.clear();
1396 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001397}
1398
1399/// \brief Iterate over the relocations of the given \p Section and
1400/// store the ones that correspond to debug map entries into the
1401/// ValidRelocs array.
1402void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1403 const object::MachOObjectFile &Obj,
1404 const DebugMapObject &DMO) {
1405 StringRef Contents;
1406 Section.getContents(Contents);
1407 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1408
1409 for (const object::RelocationRef &Reloc : Section.relocations()) {
1410 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1411 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1412 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1413 uint64_t Offset64;
1414 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001415 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001416 continue;
1417 }
1418 uint32_t Offset = Offset64;
1419 // Mach-o uses REL relocations, the addend is at the relocation offset.
1420 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1421
1422 auto Sym = Reloc.getSymbol();
1423 if (Sym != Obj.symbol_end()) {
1424 StringRef SymbolName;
1425 if (Sym->getName(SymbolName)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001426 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001427 continue;
1428 }
1429 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
1430 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1431 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1432 // Do not store the addend. The addend was the address of the
1433 // symbol in the object file, the address in the binary that is
1434 // stored in the debug map doesn't need to be offseted.
1435 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1436 }
1437 }
1438}
1439
1440/// \brief Dispatch the valid relocation finding logic to the
1441/// appropriate handler depending on the object file format.
1442bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1443 const object::ObjectFile &Obj,
1444 const DebugMapObject &DMO) {
1445 // Dispatch to the right handler depending on the file type.
1446 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1447 findValidRelocsMachO(Section, *MachOObj, DMO);
1448 else
Frederic Riss1b9da422015-02-13 23:18:29 +00001449 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001450
1451 if (ValidRelocs.empty())
1452 return false;
1453
1454 // Sort the relocations by offset. We will walk the DIEs linearly in
1455 // the file, this allows us to just keep an index in the relocation
1456 // array that we advance during our walk, rather than resorting to
1457 // some associative container. See DwarfLinker::NextValidReloc.
1458 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1459 return true;
1460}
1461
1462/// \brief Look for relocations in the debug_info section that match
1463/// entries in the debug map. These relocations will drive the Dwarf
1464/// link by indicating which DIEs refer to symbols present in the
1465/// linked binary.
1466/// \returns wether there are any valid relocations in the debug info.
1467bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1468 const DebugMapObject &DMO) {
1469 // Find the debug_info section.
1470 for (const object::SectionRef &Section : Obj.sections()) {
1471 StringRef SectionName;
1472 Section.getName(SectionName);
1473 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1474 if (SectionName != "debug_info")
1475 continue;
1476 return findValidRelocs(Section, Obj, DMO);
1477 }
1478 return false;
1479}
Frederic Riss563cba62015-01-28 22:15:14 +00001480
Frederic Riss84c09a52015-02-13 23:18:34 +00001481/// \brief Checks that there is a relocation against an actual debug
1482/// map entry between \p StartOffset and \p NextOffset.
1483///
1484/// This function must be called with offsets in strictly ascending
1485/// order because it never looks back at relocations it already 'went past'.
1486/// \returns true and sets Info.InDebugMap if it is the case.
1487bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1488 CompileUnit::DIEInfo &Info) {
1489 assert(NextValidReloc == 0 ||
1490 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1491 if (NextValidReloc >= ValidRelocs.size())
1492 return false;
1493
1494 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1495
1496 // We might need to skip some relocs that we didn't consider. For
1497 // example the high_pc of a discarded DIE might contain a reloc that
1498 // is in the list because it actually corresponds to the start of a
1499 // function that is in the debug map.
1500 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1501 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1502
1503 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1504 return false;
1505
1506 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Rissb9818322015-02-28 00:29:07 +00001507 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001508 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1509 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1510 ValidReloc.Mapping->getValue().ObjectAddress,
1511 ValidReloc.Mapping->getValue().BinaryAddress);
1512
Frederic Riss31da3242015-03-11 18:45:52 +00001513 Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
1514 ValidReloc.Addend -
1515 ValidReloc.Mapping->getValue().ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001516 Info.InDebugMap = true;
1517 return true;
1518}
1519
1520/// \brief Get the starting and ending (exclusive) offset for the
1521/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1522/// supposed to point to the position of the first attribute described
1523/// by \p Abbrev.
1524/// \return [StartOffset, EndOffset) as a pair.
1525static std::pair<uint32_t, uint32_t>
1526getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1527 unsigned Offset, const DWARFUnit &Unit) {
1528 DataExtractor Data = Unit.getDebugInfoExtractor();
1529
1530 for (unsigned i = 0; i < Idx; ++i)
1531 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1532
1533 uint32_t End = Offset;
1534 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1535
1536 return std::make_pair(Offset, End);
1537}
1538
1539/// \brief Check if a variable describing DIE should be kept.
1540/// \returns updated TraversalFlags.
1541unsigned DwarfLinker::shouldKeepVariableDIE(
1542 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1543 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1544 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1545
1546 // Global variables with constant value can always be kept.
1547 if (!(Flags & TF_InFunctionScope) &&
1548 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1549 MyInfo.InDebugMap = true;
1550 return Flags | TF_Keep;
1551 }
1552
1553 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1554 if (LocationIdx == -1U)
1555 return Flags;
1556
1557 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1558 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1559 uint32_t LocationOffset, LocationEndOffset;
1560 std::tie(LocationOffset, LocationEndOffset) =
1561 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1562
1563 // See if there is a relocation to a valid debug map entry inside
1564 // this variable's location. The order is important here. We want to
1565 // always check in the variable has a valid relocation, so that the
1566 // DIEInfo is filled. However, we don't want a static variable in a
1567 // function to force us to keep the enclosing function.
1568 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1569 (Flags & TF_InFunctionScope))
1570 return Flags;
1571
Frederic Rissb9818322015-02-28 00:29:07 +00001572 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001573 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1574
1575 return Flags | TF_Keep;
1576}
1577
1578/// \brief Check if a function describing DIE should be kept.
1579/// \returns updated TraversalFlags.
1580unsigned DwarfLinker::shouldKeepSubprogramDIE(
1581 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1582 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1583 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1584
1585 Flags |= TF_InFunctionScope;
1586
1587 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1588 if (LowPcIdx == -1U)
1589 return Flags;
1590
1591 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1592 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1593 uint32_t LowPcOffset, LowPcEndOffset;
1594 std::tie(LowPcOffset, LowPcEndOffset) =
1595 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1596
1597 uint64_t LowPc =
1598 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1599 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1600 if (LowPc == -1ULL ||
1601 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1602 return Flags;
1603
Frederic Rissb9818322015-02-28 00:29:07 +00001604 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001605 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1606
Frederic Riss1af75f72015-03-12 18:45:10 +00001607 Flags |= TF_Keep;
1608
1609 DWARFFormValue HighPcValue;
1610 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1611 reportWarning("Function without high_pc. Range will be discarded.\n",
1612 &OrigUnit, &DIE);
1613 return Flags;
1614 }
1615
1616 uint64_t HighPc;
1617 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1618 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1619 } else {
1620 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1621 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1622 }
1623
Frederic Riss63786b02015-03-15 20:45:43 +00001624 // Replace the debug map range with a more accurate one.
1625 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00001626 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1627 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00001628}
1629
1630/// \brief Check if a DIE should be kept.
1631/// \returns updated TraversalFlags.
1632unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1633 CompileUnit &Unit,
1634 CompileUnit::DIEInfo &MyInfo,
1635 unsigned Flags) {
1636 switch (DIE.getTag()) {
1637 case dwarf::DW_TAG_constant:
1638 case dwarf::DW_TAG_variable:
1639 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1640 case dwarf::DW_TAG_subprogram:
1641 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1642 case dwarf::DW_TAG_module:
1643 case dwarf::DW_TAG_imported_module:
1644 case dwarf::DW_TAG_imported_declaration:
1645 case dwarf::DW_TAG_imported_unit:
1646 // We always want to keep these.
1647 return Flags | TF_Keep;
1648 }
1649
1650 return Flags;
1651}
1652
Frederic Riss84c09a52015-02-13 23:18:34 +00001653/// \brief Mark the passed DIE as well as all the ones it depends on
1654/// as kept.
1655///
1656/// This function is called by lookForDIEsToKeep on DIEs that are
1657/// newly discovered to be needed in the link. It recursively calls
1658/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1659/// TraversalFlags to inform it that it's not doing the primary DIE
1660/// tree walk.
1661void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1662 CompileUnit::DIEInfo &MyInfo,
1663 const DebugMapObject &DMO,
1664 CompileUnit &CU, unsigned Flags) {
1665 const DWARFUnit &Unit = CU.getOrigUnit();
1666 MyInfo.Keep = true;
1667
1668 // First mark all the parent chain as kept.
1669 unsigned AncestorIdx = MyInfo.ParentIdx;
1670 while (!CU.getInfo(AncestorIdx).Keep) {
1671 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1672 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1673 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1674 }
1675
1676 // Then we need to mark all the DIEs referenced by this DIE's
1677 // attributes as kept.
1678 DataExtractor Data = Unit.getDebugInfoExtractor();
1679 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1680 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1681
1682 // Mark all DIEs referenced through atttributes as kept.
1683 for (const auto &AttrSpec : Abbrev->attributes()) {
1684 DWARFFormValue Val(AttrSpec.Form);
1685
1686 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1687 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1688 continue;
1689 }
1690
1691 Val.extractValue(Data, &Offset, &Unit);
1692 CompileUnit *ReferencedCU;
1693 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1694 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1695 TF_Keep | TF_DependencyWalk);
1696 }
1697}
1698
1699/// \brief Recursively walk the \p DIE tree and look for DIEs to
1700/// keep. Store that information in \p CU's DIEInfo.
1701///
1702/// This function is the entry point of the DIE selection
1703/// algorithm. It is expected to walk the DIE tree in file order and
1704/// (though the mediation of its helper) call hasValidRelocation() on
1705/// each DIE that might be a 'root DIE' (See DwarfLinker class
1706/// comment).
1707/// While walking the dependencies of root DIEs, this function is
1708/// also called, but during these dependency walks the file order is
1709/// not respected. The TF_DependencyWalk flag tells us which kind of
1710/// traversal we are currently doing.
1711void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1712 const DebugMapObject &DMO, CompileUnit &CU,
1713 unsigned Flags) {
1714 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1715 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1716 bool AlreadyKept = MyInfo.Keep;
1717
1718 // If the Keep flag is set, we are marking a required DIE's
1719 // dependencies. If our target is already marked as kept, we're all
1720 // set.
1721 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1722 return;
1723
1724 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1725 // because it would screw up the relocation finding logic.
1726 if (!(Flags & TF_DependencyWalk))
1727 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1728
1729 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1730 if (!AlreadyKept && (Flags & TF_Keep))
1731 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1732
1733 // The TF_ParentWalk flag tells us that we are currently walking up
1734 // the parent chain of a required DIE, and we don't want to mark all
1735 // the children of the parents as kept (consider for example a
1736 // DW_TAG_namespace node in the parent chain). There are however a
1737 // set of DIE types for which we want to ignore that directive and still
1738 // walk their children.
1739 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1740 Flags &= ~TF_ParentWalk;
1741
1742 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1743 return;
1744
1745 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1746 Child = Child->getSibling())
1747 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1748}
1749
Frederic Rissb8b43d52015-03-04 22:07:44 +00001750/// \brief Assign an abbreviation numer to \p Abbrev.
1751///
1752/// Our DIEs get freed after every DebugMapObject has been processed,
1753/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1754/// the instances hold by the DIEs. When we encounter an abbreviation
1755/// that we don't know, we create a permanent copy of it.
1756void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1757 // Check the set for priors.
1758 FoldingSetNodeID ID;
1759 Abbrev.Profile(ID);
1760 void *InsertToken;
1761 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1762
1763 // If it's newly added.
1764 if (InSet) {
1765 // Assign existing abbreviation number.
1766 Abbrev.setNumber(InSet->getNumber());
1767 } else {
1768 // Add to abbreviation list.
1769 Abbreviations.push_back(
1770 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1771 for (const auto &Attr : Abbrev.getData())
1772 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1773 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1774 // Assign the unique abbreviation number.
1775 Abbrev.setNumber(Abbreviations.size());
1776 Abbreviations.back()->setNumber(Abbreviations.size());
1777 }
1778}
1779
1780/// \brief Clone a string attribute described by \p AttrSpec and add
1781/// it to \p Die.
1782/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00001783unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1784 const DWARFFormValue &Val,
1785 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001786 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00001787 const char *String = *Val.getAsCString(&U);
1788 unsigned Offset = StringPool.getStringOffset(String);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001789 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001790 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001791 return 4;
1792}
1793
1794/// \brief Clone an attribute referencing another DIE and add
1795/// it to \p Die.
1796/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00001797unsigned DwarfLinker::cloneDieReferenceAttribute(
1798 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1799 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001800 CompileUnit &Unit) {
1801 uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
Frederic Riss9833de62015-03-06 23:22:53 +00001802 DIE *NewRefDie = nullptr;
1803 CompileUnit *RefUnit = nullptr;
1804 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1805
1806 if (!(RefUnit = getUnitForOffset(Ref)) ||
1807 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1808 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1809 if (!AttributeString)
1810 AttributeString = "DW_AT_???";
1811 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1812 ". Dropping.",
Frederic Riss6afcfce2015-03-13 18:35:57 +00001813 &Unit.getOrigUnit(), &InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00001814 return 0;
1815 }
1816
1817 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1818 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1819 if (!RefInfo.Clone) {
1820 assert(Ref > InputDIE.getOffset());
1821 // We haven't cloned this DIE yet. Just create an empty one and
1822 // store it. It'll get really cloned when we process it.
1823 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1824 }
1825 NewRefDie = RefInfo.Clone;
1826
1827 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1828 // We cannot currently rely on a DIEEntry to emit ref_addr
1829 // references, because the implementation calls back to DwarfDebug
1830 // to find the unit offset. (We don't have a DwarfDebug)
1831 // FIXME: we should be able to design DIEEntry reliance on
1832 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001833 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00001834 if (Ref < InputDIE.getOffset()) {
1835 // We must have already cloned that DIE.
1836 uint32_t NewRefOffset =
1837 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001838 Attr = NewRefOffset;
Frederic Riss9833de62015-03-06 23:22:53 +00001839 } else {
1840 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001841 Attr = 0xBADDEF;
1842 Unit.noteForwardReference(NewRefDie, RefUnit,
1843 PatchLocation(Die, Die.getValues().size()));
Frederic Riss9833de62015-03-06 23:22:53 +00001844 }
1845 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001846 DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00001847 return AttrSize;
1848 }
1849
Frederic Rissb8b43d52015-03-04 22:07:44 +00001850 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001851 DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001852 return AttrSize;
1853}
1854
1855/// \brief Clone an attribute of block form (locations, constants) and add
1856/// it to \p Die.
1857/// \returns the size of the new attribute.
1858unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1859 const DWARFFormValue &Val,
1860 unsigned AttrSize) {
1861 DIE *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001862 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001863 DIELoc *Loc = nullptr;
1864 DIEBlock *Block = nullptr;
1865 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00001866 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001867 Loc = new (DIEAlloc) DIELoc;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001868 DIELocs.push_back(Loc);
1869 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001870 Block = new (DIEAlloc) DIEBlock;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001871 DIEBlocks.push_back(Block);
1872 }
1873 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00001874
1875 if (Loc)
1876 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1877 dwarf::Form(AttrSpec.Form), Loc);
1878 else
1879 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1880 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001881 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1882 for (auto Byte : Bytes)
1883 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001884 DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001885 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1886 // the DIE class, this if could be replaced by
1887 // Attr->setSize(Bytes.size()).
1888 if (Streamer) {
1889 if (Loc)
1890 Loc->ComputeSize(&Streamer->getAsmPrinter());
1891 else
1892 Block->ComputeSize(&Streamer->getAsmPrinter());
1893 }
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00001894 Die.addValue(Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001895 return AttrSize;
1896}
1897
Frederic Riss31da3242015-03-11 18:45:52 +00001898/// \brief Clone an address attribute and add it to \p Die.
1899/// \returns the size of the new attribute.
1900unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1901 const DWARFFormValue &Val,
1902 const CompileUnit &Unit,
1903 AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001904 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00001905 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1906 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1907 Die.getTag() == dwarf::DW_TAG_lexical_block)
1908 Addr += Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001909 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1910 Addr = Unit.getLowPc();
1911 if (Addr == UINT64_MAX)
1912 return 0;
1913 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00001914 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00001915 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001916 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1917 if (uint64_t HighPc = Unit.getHighPc())
1918 Addr = HighPc;
1919 else
1920 return 0;
1921 } else
1922 // If we have a high_pc recorded for the input DIE, use
1923 // it. Otherwise (when no relocations where applied) just use the
1924 // one we just decoded.
1925 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00001926 }
1927
1928 Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001929 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00001930 return Unit.getOrigUnit().getAddressByteSize();
1931}
1932
Frederic Rissb8b43d52015-03-04 22:07:44 +00001933/// \brief Clone a scalar attribute and add it to \p Die.
1934/// \returns the size of the new attribute.
1935unsigned DwarfLinker::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00001936 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00001937 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001938 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001939 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001940 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1941 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1942 if (Unit.getLowPc() == -1ULL)
1943 return 0;
1944 // Dwarf >= 4 high_pc is an size, not an address.
1945 Value = Unit.getHighPc() - Unit.getLowPc();
1946 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00001947 Value = *Val.getAsSectionOffset();
1948 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1949 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001950 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1951 Value = *OptionalValue;
1952 else {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001953 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1954 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001955 return 0;
1956 }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001957 DIEInteger Attr(Value);
Frederic Riss25440872015-03-13 23:30:31 +00001958 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001959 Unit.noteRangeAttribute(Die, PatchLocation(Die, Die.getValues().size()));
Frederic Rissdfb97902015-03-14 15:49:07 +00001960 // A more generic way to check for location attributes would be
1961 // nice, but it's very unlikely that any other attribute needs a
1962 // location list.
1963 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1964 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001965 Unit.noteLocationAttribute(PatchLocation(Die, Die.getValues().size()),
1966 Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001967 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1968 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00001969
Frederic Rissb8b43d52015-03-04 22:07:44 +00001970 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Frederic Riss25440872015-03-13 23:30:31 +00001971 Attr);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001972 return AttrSize;
1973}
1974
1975/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1976/// value \p Val, and add it to \p Die.
1977/// \returns the size of the cloned attribute.
1978unsigned DwarfLinker::cloneAttribute(DIE &Die,
1979 const DWARFDebugInfoEntryMinimal &InputDIE,
1980 CompileUnit &Unit,
1981 const DWARFFormValue &Val,
1982 const AttributeSpec AttrSpec,
Frederic Riss31da3242015-03-11 18:45:52 +00001983 unsigned AttrSize, AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001984 const DWARFUnit &U = Unit.getOrigUnit();
1985
1986 switch (AttrSpec.Form) {
1987 case dwarf::DW_FORM_strp:
1988 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00001989 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001990 case dwarf::DW_FORM_ref_addr:
1991 case dwarf::DW_FORM_ref1:
1992 case dwarf::DW_FORM_ref2:
1993 case dwarf::DW_FORM_ref4:
1994 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00001995 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001996 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001997 case dwarf::DW_FORM_block:
1998 case dwarf::DW_FORM_block1:
1999 case dwarf::DW_FORM_block2:
2000 case dwarf::DW_FORM_block4:
2001 case dwarf::DW_FORM_exprloc:
2002 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2003 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002004 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002005 case dwarf::DW_FORM_data1:
2006 case dwarf::DW_FORM_data2:
2007 case dwarf::DW_FORM_data4:
2008 case dwarf::DW_FORM_data8:
2009 case dwarf::DW_FORM_udata:
2010 case dwarf::DW_FORM_sdata:
2011 case dwarf::DW_FORM_sec_offset:
2012 case dwarf::DW_FORM_flag:
2013 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002014 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2015 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002016 default:
2017 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2018 &InputDIE);
2019 }
2020
2021 return 0;
2022}
2023
Frederic Riss23e20e92015-03-07 01:25:09 +00002024/// \brief Apply the valid relocations found by findValidRelocs() to
2025/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2026/// in the debug_info section.
2027///
2028/// Like for findValidRelocs(), this function must be called with
2029/// monotonic \p BaseOffset values.
2030///
2031/// \returns wether any reloc has been applied.
2032bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2033 uint32_t BaseOffset, bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002034 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002035 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2036 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002037 if (NextValidReloc >= ValidRelocs.size())
2038 return false;
2039
2040 // Skip relocs that haven't been applied.
2041 while (NextValidReloc < ValidRelocs.size() &&
2042 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2043 ++NextValidReloc;
2044
2045 bool Applied = false;
2046 uint64_t EndOffset = BaseOffset + Data.size();
2047 while (NextValidReloc < ValidRelocs.size() &&
2048 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2049 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2050 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2051 assert(ValidReloc.Offset - BaseOffset < Data.size());
2052 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2053 char Buf[8];
2054 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2055 Value += ValidReloc.Addend;
2056 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2057 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2058 Buf[i] = uint8_t(Value >> (Index * 8));
2059 }
2060 assert(ValidReloc.Size <= sizeof(Buf));
2061 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2062 Applied = true;
2063 }
2064
2065 return Applied;
2066}
2067
Frederic Rissbce93ff2015-03-16 02:05:10 +00002068static bool isTypeTag(uint16_t Tag) {
2069 switch (Tag) {
2070 case dwarf::DW_TAG_array_type:
2071 case dwarf::DW_TAG_class_type:
2072 case dwarf::DW_TAG_enumeration_type:
2073 case dwarf::DW_TAG_pointer_type:
2074 case dwarf::DW_TAG_reference_type:
2075 case dwarf::DW_TAG_string_type:
2076 case dwarf::DW_TAG_structure_type:
2077 case dwarf::DW_TAG_subroutine_type:
2078 case dwarf::DW_TAG_typedef:
2079 case dwarf::DW_TAG_union_type:
2080 case dwarf::DW_TAG_ptr_to_member_type:
2081 case dwarf::DW_TAG_set_type:
2082 case dwarf::DW_TAG_subrange_type:
2083 case dwarf::DW_TAG_base_type:
2084 case dwarf::DW_TAG_const_type:
2085 case dwarf::DW_TAG_constant:
2086 case dwarf::DW_TAG_file_type:
2087 case dwarf::DW_TAG_namelist:
2088 case dwarf::DW_TAG_packed_type:
2089 case dwarf::DW_TAG_volatile_type:
2090 case dwarf::DW_TAG_restrict_type:
2091 case dwarf::DW_TAG_interface_type:
2092 case dwarf::DW_TAG_unspecified_type:
2093 case dwarf::DW_TAG_shared_type:
2094 return true;
2095 default:
2096 break;
2097 }
2098 return false;
2099}
2100
Frederic Rissb8b43d52015-03-04 22:07:44 +00002101/// \brief Recursively clone \p InputDIE's subtrees that have been
2102/// selected to appear in the linked output.
2103///
2104/// \param OutOffset is the Offset where the newly created DIE will
2105/// lie in the linked compile unit.
2106///
2107/// \returns the cloned DIE object or null if nothing was selected.
2108DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss31da3242015-03-11 18:45:52 +00002109 CompileUnit &Unit, int64_t PCOffset,
2110 uint32_t OutOffset) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002111 DWARFUnit &U = Unit.getOrigUnit();
2112 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002113 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002114
2115 // Should the DIE appear in the output?
2116 if (!Unit.getInfo(Idx).Keep)
2117 return nullptr;
2118
2119 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002120 // The DIE might have been already created by a forward reference
2121 // (see cloneDieReferenceAttribute()).
2122 DIE *Die = Info.Clone;
2123 if (!Die)
2124 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
2125 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002126 Die->setOffset(OutOffset);
2127
2128 // Extract and clone every attribute.
2129 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00002130 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002131 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002132
2133 // We could copy the data only if we need to aply a relocation to
2134 // it. After testing, it seems there is no performance downside to
2135 // doing the copy unconditionally, and it makes the code simpler.
2136 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2137 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2138 // Modify the copy with relocated addresses.
Frederic Riss31da3242015-03-11 18:45:52 +00002139 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2140 // If we applied relocations, we store the value of high_pc that was
2141 // potentially stored in the input DIE. If high_pc is an address
2142 // (Dwarf version == 2), then it might have been relocated to a
2143 // totally unrelated value (because the end address in the object
2144 // file might be start address of another function which got moved
2145 // independantly by the linker). The computation of the actual
2146 // high_pc value is done in cloneAddressAttribute().
2147 AttrInfo.OrigHighPc =
2148 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2149 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002150
2151 // Reset the Offset to 0 as we will be working on the local copy of
2152 // the data.
2153 Offset = 0;
2154
Frederic Rissb8b43d52015-03-04 22:07:44 +00002155 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2156 Offset += getULEB128Size(Abbrev->getCode());
2157
Frederic Riss31da3242015-03-11 18:45:52 +00002158 // We are entering a subprogram. Get and propagate the PCOffset.
2159 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2160 PCOffset = Info.AddrAdjust;
2161 AttrInfo.PCOffset = PCOffset;
2162
Frederic Rissb8b43d52015-03-04 22:07:44 +00002163 for (const auto &AttrSpec : Abbrev->attributes()) {
2164 DWARFFormValue Val(AttrSpec.Form);
2165 uint32_t AttrSize = Offset;
2166 Val.extractValue(Data, &Offset, &U);
2167 AttrSize = Offset - AttrSize;
2168
Frederic Riss31da3242015-03-11 18:45:52 +00002169 OutOffset +=
2170 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002171 }
2172
Frederic Rissbce93ff2015-03-16 02:05:10 +00002173 // Look for accelerator entries.
2174 uint16_t Tag = InputDIE.getTag();
2175 // FIXME: This is slightly wrong. An inline_subroutine without a
2176 // low_pc, but with AT_ranges might be interesting to get into the
2177 // accelerator tables too. For now stick with dsymutil's behavior.
2178 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2179 Tag != dwarf::DW_TAG_compile_unit &&
2180 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2181 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2182 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2183 AttrInfo.MangledNameOffset,
2184 Tag == dwarf::DW_TAG_inlined_subroutine);
2185 if (AttrInfo.Name)
2186 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2187 Tag == dwarf::DW_TAG_inlined_subroutine);
2188 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2189 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2190 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2191 }
2192
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002193 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002194 // If a scope DIE is kept, we must have kept at least one child. If
2195 // it's not the case, we'll just be emitting one wasteful end of
2196 // children marker, but things won't break.
2197 if (InputDIE.hasChildren())
2198 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2199 // Assign a permanent abbrev number
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002200 AssignAbbrev(NewAbbrev);
2201 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002202
2203 // Add the size of the abbreviation number to the output offset.
2204 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2205
2206 if (!Abbrev->hasChildren()) {
2207 // Update our size.
2208 Die->setSize(OutOffset - Die->getOffset());
2209 return Die;
2210 }
2211
2212 // Recursively clone children.
2213 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2214 Child = Child->getSibling()) {
Frederic Riss31da3242015-03-11 18:45:52 +00002215 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002216 Die->addChild(std::unique_ptr<DIE>(Clone));
2217 OutOffset = Clone->getOffset() + Clone->getSize();
2218 }
2219 }
2220
2221 // Account for the end of children marker.
2222 OutOffset += sizeof(int8_t);
2223 // Update our size.
2224 Die->setSize(OutOffset - Die->getOffset());
2225 return Die;
2226}
2227
Frederic Riss25440872015-03-13 23:30:31 +00002228/// \brief Patch the input object file relevant debug_ranges entries
2229/// and emit them in the output file. Update the relevant attributes
2230/// to point at the new entries.
2231void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2232 DWARFContext &OrigDwarf) const {
2233 DWARFDebugRangeList RangeList;
2234 const auto &FunctionRanges = Unit.getFunctionRanges();
2235 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2236 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2237 OrigDwarf.isLittleEndian(), AddressSize);
2238 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2239 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002240 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002241 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2242 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2243 // Ranges addresses are based on the unit's low_pc. Compute the
2244 // offset we need to apply to adapt to the the new unit's low_pc.
2245 int64_t UnitPcOffset = 0;
2246 if (OrigLowPc != -1ULL)
2247 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2248
2249 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002250 uint32_t Offset = RangeAttribute.get();
2251 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002252 RangeList.extract(RangeExtractor, &Offset);
2253 const auto &Entries = RangeList.getEntries();
2254 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2255
2256 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2257 First.StartAddress >= CurrRange.stop()) {
2258 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2259 if (CurrRange == InvalidRange ||
2260 CurrRange.start() > First.StartAddress + OrigLowPc) {
2261 reportWarning("no mapping for range.");
2262 continue;
2263 }
2264 }
2265
2266 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2267 AddressSize);
2268 }
2269}
2270
Frederic Riss563b1b02015-03-14 03:46:51 +00002271/// \brief Generate the debug_aranges entries for \p Unit and if the
2272/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2273/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002274/// FIXME: this could actually be done right in patchRangesForUnit,
2275/// but for the sake of initial bit-for-bit compatibility with legacy
2276/// dsymutil, we have to do it in a delayed pass.
2277void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002278 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002279 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002280 Attr->set(Streamer->getRangesSectionSize());
2281 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002282}
2283
Frederic Riss63786b02015-03-15 20:45:43 +00002284/// \brief Insert the new line info sequence \p Seq into the current
2285/// set of already linked line info \p Rows.
2286static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2287 std::vector<DWARFDebugLine::Row> &Rows) {
2288 if (Seq.empty())
2289 return;
2290
2291 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2292 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2293 Seq.clear();
2294 return;
2295 }
2296
2297 auto InsertPoint = std::lower_bound(
2298 Rows.begin(), Rows.end(), Seq.front(),
2299 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2300 return LHS.Address < RHS.Address;
2301 });
2302
2303 // FIXME: this only removes the unneeded end_sequence if the
2304 // sequences have been inserted in order. using a global sort like
2305 // described in patchLineTableForUnit() and delaying the end_sequene
2306 // elimination to emitLineTableForUnit() we can get rid of all of them.
2307 if (InsertPoint != Rows.end() &&
2308 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2309 *InsertPoint = Seq.front();
2310 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2311 } else {
2312 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2313 }
2314
2315 Seq.clear();
2316}
2317
2318/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2319/// recreate a relocated version of these for the address ranges that
2320/// are present in the binary.
2321void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2322 DWARFContext &OrigDwarf) {
2323 const DWARFDebugInfoEntryMinimal *CUDie =
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002324 Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002325 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2326 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2327 if (StmtList == -1ULL)
2328 return;
2329
2330 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2331 if (auto *OutputDIE = Unit.getOutputUnitDIE()) {
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002332 const auto &Values = OutputDIE->getValues();
2333 auto Stmt =
2334 std::find_if(Values.begin(), Values.end(), [](const DIEValue &Value) {
2335 return Value.getAttribute() == dwarf::DW_AT_stmt_list;
Frederic Riss63786b02015-03-15 20:45:43 +00002336 });
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002337 assert(Stmt < Values.end() && "Didn't find DW_AT_stmt_list in cloned DIE!");
2338 OutputDIE->setValue(Stmt - Values.begin(),
2339 DIEValue(Stmt->getAttribute(), Stmt->getForm(),
2340 DIEInteger(Streamer->getLineSectionSize())));
Frederic Riss63786b02015-03-15 20:45:43 +00002341 }
2342
2343 // Parse the original line info for the unit.
2344 DWARFDebugLine::LineTable LineTable;
2345 uint32_t StmtOffset = StmtList;
2346 StringRef LineData = OrigDwarf.getLineSection().Data;
2347 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2348 Unit.getOrigUnit().getAddressByteSize());
2349 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2350 &StmtOffset);
2351
2352 // This vector is the output line table.
2353 std::vector<DWARFDebugLine::Row> NewRows;
2354 NewRows.reserve(LineTable.Rows.size());
2355
2356 // Current sequence of rows being extracted, before being inserted
2357 // in NewRows.
2358 std::vector<DWARFDebugLine::Row> Seq;
2359 const auto &FunctionRanges = Unit.getFunctionRanges();
2360 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2361
2362 // FIXME: This logic is meant to generate exactly the same output as
2363 // Darwin's classic dsynutil. There is a nicer way to implement this
2364 // by simply putting all the relocated line info in NewRows and simply
2365 // sorting NewRows before passing it to emitLineTableForUnit. This
2366 // should be correct as sequences for a function should stay
2367 // together in the sorted output. There are a few corner cases that
2368 // look suspicious though, and that required to implement the logic
2369 // this way. Revisit that once initial validation is finished.
2370
2371 // Iterate over the object file line info and extract the sequences
2372 // that correspond to linked functions.
2373 for (auto &Row : LineTable.Rows) {
2374 // Check wether we stepped out of the range. The range is
2375 // half-open, but consider accept the end address of the range if
2376 // it is marked as end_sequence in the input (because in that
2377 // case, the relocation offset is accurate and that entry won't
2378 // serve as the start of another function).
2379 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2380 Row.Address > CurrRange.stop() ||
2381 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2382 // We just stepped out of a known range. Insert a end_sequence
2383 // corresponding to the end of the range.
2384 uint64_t StopAddress = CurrRange != InvalidRange
2385 ? CurrRange.stop() + CurrRange.value()
2386 : -1ULL;
2387 CurrRange = FunctionRanges.find(Row.Address);
2388 bool CurrRangeValid =
2389 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2390 if (!CurrRangeValid) {
2391 CurrRange = InvalidRange;
2392 if (StopAddress != -1ULL) {
2393 // Try harder by looking in the DebugMapObject function
2394 // ranges map. There are corner cases where this finds a
2395 // valid entry. It's unclear if this is right or wrong, but
2396 // for now do as dsymutil.
2397 // FIXME: Understand exactly what cases this addresses and
2398 // potentially remove it along with the Ranges map.
2399 auto Range = Ranges.lower_bound(Row.Address);
2400 if (Range != Ranges.begin() && Range != Ranges.end())
2401 --Range;
2402
2403 if (Range != Ranges.end() && Range->first <= Row.Address &&
2404 Range->second.first >= Row.Address) {
2405 StopAddress = Row.Address + Range->second.second;
2406 }
2407 }
2408 }
2409 if (StopAddress != -1ULL && !Seq.empty()) {
2410 // Insert end sequence row with the computed end address, but
2411 // the same line as the previous one.
2412 Seq.emplace_back(Seq.back());
2413 Seq.back().Address = StopAddress;
2414 Seq.back().EndSequence = 1;
2415 Seq.back().PrologueEnd = 0;
2416 Seq.back().BasicBlock = 0;
2417 Seq.back().EpilogueBegin = 0;
2418 insertLineSequence(Seq, NewRows);
2419 }
2420
2421 if (!CurrRangeValid)
2422 continue;
2423 }
2424
2425 // Ignore empty sequences.
2426 if (Row.EndSequence && Seq.empty())
2427 continue;
2428
2429 // Relocate row address and add it to the current sequence.
2430 Row.Address += CurrRange.value();
2431 Seq.emplace_back(Row);
2432
2433 if (Row.EndSequence)
2434 insertLineSequence(Seq, NewRows);
2435 }
2436
2437 // Finished extracting, now emit the line tables.
2438 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2439 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2440 // prologue over and that works because we act as both producer and
2441 // consumer. It would be nicer to have a real configurable line
2442 // table emitter.
2443 if (LineTable.Prologue.Version != 2 ||
2444 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2445 LineTable.Prologue.LineBase != -5 || LineTable.Prologue.LineRange != 14 ||
2446 LineTable.Prologue.OpcodeBase != 13)
2447 reportWarning("line table paramters mismatch. Cannot emit.");
2448 else
2449 Streamer->emitLineTableForUnit(LineData.slice(StmtList + 4, PrologueEnd),
2450 LineTable.Prologue.MinInstLength, NewRows,
2451 Unit.getOrigUnit().getAddressByteSize());
2452}
2453
Frederic Rissbce93ff2015-03-16 02:05:10 +00002454void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2455 Streamer->emitPubNamesForUnit(Unit);
2456 Streamer->emitPubTypesForUnit(Unit);
2457}
2458
Frederic Rissd3455182015-01-28 18:27:01 +00002459bool DwarfLinker::link(const DebugMap &Map) {
2460
2461 if (Map.begin() == Map.end()) {
2462 errs() << "Empty debug map.\n";
2463 return false;
2464 }
2465
Frederic Rissc99ea202015-02-28 00:29:11 +00002466 if (!createStreamer(Map.getTriple(), OutputFilename))
2467 return false;
2468
Frederic Rissb8b43d52015-03-04 22:07:44 +00002469 // Size of the DIEs (and headers) generated for the linked output.
2470 uint64_t OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00002471 // A unique ID that identifies each compile unit.
2472 unsigned UnitID = 0;
Frederic Rissd3455182015-01-28 18:27:01 +00002473 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002474 CurrentDebugObject = Obj.get();
2475
Frederic Rissb9818322015-02-28 00:29:07 +00002476 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00002477 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
2478 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
2479 if (std::error_code EC = ErrOrObj.getError()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002480 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
Frederic Rissd3455182015-01-28 18:27:01 +00002481 continue;
2482 }
2483
Frederic Riss1036e642015-02-13 23:18:22 +00002484 // Look for relocations that correspond to debug map entries.
2485 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00002486 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00002487 outs() << "No valid relocations found. Skipping.\n";
2488 continue;
2489 }
2490
Frederic Riss563cba62015-01-28 22:15:14 +00002491 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00002492 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00002493 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00002494
Frederic Riss563cba62015-01-28 22:15:14 +00002495 // In a first phase, just read in the debug info and store the DIE
2496 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00002497 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002498 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00002499 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00002500 outs() << "Input compilation unit:";
2501 CUDie->dump(outs(), CU.get(), 0);
2502 }
Frederic Riss3cced052015-03-14 03:46:40 +00002503 Units.emplace_back(*CU, UnitID++);
Frederic Riss9aa725b2015-02-13 23:18:31 +00002504 gatherDIEParents(CUDie, 0, Units.back());
Frederic Rissd3455182015-01-28 18:27:01 +00002505 }
Frederic Riss563cba62015-01-28 22:15:14 +00002506
Frederic Riss84c09a52015-02-13 23:18:34 +00002507 // Then mark all the DIEs that need to be present in the linked
2508 // output and collect some information about them. Note that this
2509 // loop can not be merged with the previous one becaue cross-cu
2510 // references require the ParentIdx to be setup for every CU in
2511 // the object file before calling this.
2512 for (auto &CurrentUnit : Units)
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002513 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00002514 CurrentUnit, 0);
2515
Frederic Riss23e20e92015-03-07 01:25:09 +00002516 // The calls to applyValidRelocs inside cloneDIE will walk the
2517 // reloc array again (in the same way findValidRelocsInDebugInfo()
2518 // did). We need to reset the NextValidReloc index to the beginning.
2519 NextValidReloc = 0;
2520
Frederic Rissb8b43d52015-03-04 22:07:44 +00002521 // Construct the output DIE tree by cloning the DIEs we chose to
2522 // keep above. If there are no valid relocs, then there's nothing
2523 // to clone/emit.
2524 if (!ValidRelocs.empty())
2525 for (auto &CurrentUnit : Units) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002526 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00002527 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Riss31da3242015-03-11 18:45:52 +00002528 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
2529 11 /* Unit Header size */);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002530 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00002531 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Riss63786b02015-03-15 20:45:43 +00002532 if (Options.NoOutput)
2533 continue;
2534 // FIXME: for compatibility with the classic dsymutil, we emit
2535 // an empty line table for the unit, even if the unit doesn't
2536 // actually exist in the DIE tree.
2537 patchLineTableForUnit(CurrentUnit, DwarfContext);
2538 if (!OutputDIE)
Frederic Riss25440872015-03-13 23:30:31 +00002539 continue;
2540 patchRangesForUnit(CurrentUnit, DwarfContext);
Frederic Rissdfb97902015-03-14 15:49:07 +00002541 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002542 emitAcceleratorEntriesForUnit(CurrentUnit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002543 }
2544
2545 // Emit all the compile unit's debug information.
2546 if (!ValidRelocs.empty() && !Options.NoOutput)
2547 for (auto &CurrentUnit : Units) {
Frederic Riss25440872015-03-13 23:30:31 +00002548 generateUnitRanges(CurrentUnit);
Frederic Riss9833de62015-03-06 23:22:53 +00002549 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002550 Streamer->emitCompileUnitHeader(CurrentUnit);
2551 if (!CurrentUnit.getOutputUnitDIE())
2552 continue;
2553 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
2554 }
2555
Frederic Riss563cba62015-01-28 22:15:14 +00002556 // Clean-up before starting working on the next object.
2557 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00002558 }
2559
Frederic Rissb8b43d52015-03-04 22:07:44 +00002560 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00002561 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002562 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00002563 Streamer->emitStrings(StringPool);
2564 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002565
Frederic Rissc99ea202015-02-28 00:29:11 +00002566 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00002567}
2568}
Frederic Rissd3455182015-01-28 18:27:01 +00002569
Frederic Rissb9818322015-02-28 00:29:07 +00002570bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
2571 const LinkOptions &Options) {
2572 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00002573 return Linker.link(DM);
2574}
2575}
Frederic Riss231f7142014-12-12 17:31:24 +00002576}