blob: e5079005c006c0192d05c5f797abf1c8267b186a [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());
75 assert(Die->getValues()[Index].getType() == DIEValue::isInteger);
76 Die->setValue(Index, DIEInteger(New));
77 }
78
79 uint64_t get() const {
80 assert(Die);
81 assert(Index < Die->getValues().size());
82 assert(Die->getValues()[Index].getType() == DIEValue::isInteger);
83 return Die->getValues()[Index].getDIEInteger().getValue();
84 }
85};
86
Frederic Riss563cba62015-01-28 22:15:14 +000087/// \brief Stores all information relating to a compile unit, be it in
88/// its original instance in the object file to its brand new cloned
89/// and linked DIE tree.
90class CompileUnit {
91public:
92 /// \brief Information gathered about a DIE in the object file.
93 struct DIEInfo {
Frederic Riss31da3242015-03-11 18:45:52 +000094 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
Frederic Riss9833de62015-03-06 23:22:53 +000095 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +000096 uint32_t ParentIdx; ///< The index of this DIE's parent.
97 bool Keep; ///< Is the DIE part of the linked output?
98 bool InDebugMap; ///< Was this DIE's entity found in the map?
Frederic Riss563cba62015-01-28 22:15:14 +000099 };
100
Frederic Riss3cced052015-03-14 03:46:40 +0000101 CompileUnit(DWARFUnit &OrigUnit, unsigned ID)
102 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000103 Ranges(RangeAlloc) {
Frederic Riss563cba62015-01-28 22:15:14 +0000104 Info.resize(OrigUnit.getNumDIEs());
105 }
106
Frederic Riss2838f9e2015-03-05 05:29:05 +0000107 CompileUnit(CompileUnit &&RHS)
108 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
109 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
Frederic Riss1af75f72015-03-12 18:45:10 +0000110 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
111 // The CompileUnit container has been 'reserve()'d with the right
112 // size. We cannot move the IntervalMap anyway.
113 llvm_unreachable("CompileUnits should not be moved.");
114 }
David Blaikiea8adc132015-03-04 22:20:52 +0000115
Frederic Rissc3349d42015-02-13 23:18:27 +0000116 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +0000117
Frederic Riss3cced052015-03-14 03:46:40 +0000118 unsigned getUniqueID() const { return ID; }
119
Frederic Rissb8b43d52015-03-04 22:07:44 +0000120 DIE *getOutputUnitDIE() const { return CUDie.get(); }
121 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
122
Frederic Riss563cba62015-01-28 22:15:14 +0000123 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
124 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
125
Frederic Rissb8b43d52015-03-04 22:07:44 +0000126 uint64_t getStartOffset() const { return StartOffset; }
127 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000128 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000129
Frederic Riss5a62dc32015-03-13 18:35:54 +0000130 uint64_t getLowPc() const { return LowPc; }
131 uint64_t getHighPc() const { return HighPc; }
132
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000133 Optional<PatchLocation> getUnitRangesAttribute() const {
134 return UnitRangeAttribute;
135 }
Frederic Riss25440872015-03-13 23:30:31 +0000136 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000137 const std::vector<PatchLocation> &getRangesAttributes() const {
Frederic Riss25440872015-03-13 23:30:31 +0000138 return RangeAttributes;
139 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000140
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000141 const std::vector<std::pair<PatchLocation, int64_t>> &
Frederic Rissdfb97902015-03-14 15:49:07 +0000142 getLocationAttributes() const {
143 return LocationAttributes;
144 }
145
Frederic Riss9d441b62015-03-06 23:22:50 +0000146 /// \brief Compute the end offset for this unit. Must be
147 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000148 /// \returns the next unit offset (which is also the current
149 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000150 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000151
Frederic Riss6afcfce2015-03-13 18:35:57 +0000152 /// \brief Keep track of a forward reference to DIE \p Die in \p
153 /// RefUnit by \p Attr. The attribute should be fixed up later to
154 /// point to the absolute offset of \p Die in the debug_info section.
155 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000156 PatchLocation Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000157
158 /// \brief Apply all fixups recored by noteForwardReference().
159 void fixupForwardReferences();
160
Frederic Riss1af75f72015-03-12 18:45:10 +0000161 /// \brief Add a function range [\p LowPC, \p HighPC) that is
162 /// relocatad by applying offset \p PCOffset.
163 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
164
Frederic Riss5c9c7062015-03-13 23:55:29 +0000165 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000166 /// patch up later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000167 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
Frederic Riss25440872015-03-13 23:30:31 +0000168
Frederic Rissdfb97902015-03-14 15:49:07 +0000169 /// \brief Keep track of a location attribute pointing to a location
170 /// list in the debug_loc section.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000171 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
Frederic Rissdfb97902015-03-14 15:49:07 +0000172
Frederic Rissbce93ff2015-03-16 02:05:10 +0000173 /// \brief Add a name accelerator entry for \p Die with \p Name
174 /// which is stored in the string table at \p Offset.
175 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
176 bool SkipPubnamesSection = false);
177
178 /// \brief Add a type accelerator entry for \p Die with \p Name
179 /// which is stored in the string table at \p Offset.
180 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
181
182 struct AccelInfo {
183 StringRef Name; ///< Name of the entry.
184 const DIE *Die; ///< DIE this entry describes.
185 uint32_t NameOffset; ///< Offset of Name in the string pool.
186 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
187
188 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
189 bool SkipPubSection = false)
190 : Name(Name), Die(Die), NameOffset(NameOffset),
191 SkipPubSection(SkipPubSection) {}
192 };
193
194 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
195 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
196
Frederic Riss563cba62015-01-28 22:15:14 +0000197private:
198 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000199 unsigned ID;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000200 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
201 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
202
203 uint64_t StartOffset;
204 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000205
Frederic Riss5a62dc32015-03-13 18:35:54 +0000206 uint64_t LowPc;
207 uint64_t HighPc;
208
Frederic Riss9833de62015-03-06 23:22:53 +0000209 /// \brief A list of attributes to fixup with the absolute offset of
210 /// a DIE in the debug_info section.
211 ///
212 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000213 /// cloning because for cross-cu forward refences the target DIE's
214 /// offset isn't known you emit the reference attribute.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000215 std::vector<std::tuple<DIE *, const CompileUnit *, PatchLocation>>
Frederic Riss6afcfce2015-03-13 18:35:57 +0000216 ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000217
Frederic Riss25440872015-03-13 23:30:31 +0000218 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000219 /// \brief The ranges in that interval map are the PC ranges for
220 /// functions in this unit, associated with the PC offset to apply
221 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000222 FunctionIntervals Ranges;
223
224 /// \brief DW_AT_ranges attributes to patch after we have gathered
225 /// all the unit's function addresses.
226 /// @{
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000227 std::vector<PatchLocation> RangeAttributes;
228 Optional<PatchLocation> UnitRangeAttribute;
Frederic Riss25440872015-03-13 23:30:31 +0000229 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000230
231 /// \brief Location attributes that need to be transfered from th
232 /// original debug_loc section to the liked one. They are stored
233 /// along with the PC offset that is to be applied to their
234 /// function's address.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000235 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
Frederic Rissbce93ff2015-03-16 02:05:10 +0000236
237 /// \brief Accelerator entries for the unit, both for the pub*
238 /// sections and the apple* ones.
239 /// @{
240 std::vector<AccelInfo> Pubnames;
241 std::vector<AccelInfo> Pubtypes;
242 /// @}
Frederic Riss563cba62015-01-28 22:15:14 +0000243};
244
Frederic Riss9d441b62015-03-06 23:22:50 +0000245uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000246 NextUnitOffset = StartOffset + 11 /* Header size */;
247 // The root DIE might be null, meaning that the Unit had nothing to
248 // contribute to the linked output. In that case, we will emit the
249 // unit header without any actual DIE.
250 if (CUDie)
251 NextUnitOffset += CUDie->getSize();
252 return NextUnitOffset;
253}
254
Frederic Riss6afcfce2015-03-13 18:35:57 +0000255/// \brief Keep track of a forward cross-cu reference from this unit
256/// to \p Die that lives in \p RefUnit.
257void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000258 PatchLocation Attr) {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000259 ForwardDIEReferences.emplace_back(Die, RefUnit, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000260}
261
262/// \brief Apply all fixups recorded by noteForwardReference().
263void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000264 for (const auto &Ref : ForwardDIEReferences) {
265 DIE *RefDie;
266 const CompileUnit *RefUnit;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000267 PatchLocation Attr;
Frederic Riss6afcfce2015-03-13 18:35:57 +0000268 std::tie(RefDie, RefUnit, Attr) = Ref;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000269 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
Frederic Riss6afcfce2015-03-13 18:35:57 +0000270 }
Frederic Riss9833de62015-03-06 23:22:53 +0000271}
272
Frederic Riss5a62dc32015-03-13 18:35:54 +0000273void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
274 int64_t PcOffset) {
275 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
276 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
277 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000278}
279
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000280void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
Frederic Riss25440872015-03-13 23:30:31 +0000281 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
282 RangeAttributes.push_back(Attr);
283 else
284 UnitRangeAttribute = Attr;
285}
286
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000287void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
Frederic Rissdfb97902015-03-14 15:49:07 +0000288 LocationAttributes.emplace_back(Attr, PcOffset);
289}
290
Frederic Rissbce93ff2015-03-16 02:05:10 +0000291/// \brief Add a name accelerator entry for \p Die with \p Name
292/// which is stored in the string table at \p Offset.
293void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
294 uint32_t Offset, bool SkipPubSection) {
295 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
296}
297
298/// \brief Add a type accelerator entry for \p Die with \p Name
299/// which is stored in the string table at \p Offset.
300void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
301 uint32_t Offset) {
302 Pubtypes.emplace_back(Name, Die, Offset, false);
303}
304
Frederic Rissef648462015-03-06 17:56:30 +0000305/// \brief A string table that doesn't need relocations.
306///
307/// We are doing a final link, no need for a string table that
308/// has relocation entries for every reference to it. This class
309/// provides this ablitity by just associating offsets with
310/// strings.
311class NonRelocatableStringpool {
312public:
313 /// \brief Entries are stored into the StringMap and simply linked
314 /// together through the second element of this pair in order to
315 /// keep track of insertion order.
316 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
317 MapTy;
318
319 NonRelocatableStringpool()
320 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
321 // Legacy dsymutil puts an empty string at the start of the line
322 // table.
323 getStringOffset("");
324 }
325
326 /// \brief Get the offset of string \p S in the string table. This
327 /// can insert a new element or return the offset of a preexisitng
328 /// one.
329 uint32_t getStringOffset(StringRef S);
330
331 /// \brief Get permanent storage for \p S (but do not necessarily
332 /// emit \p S in the output section).
333 /// \returns The StringRef that points to permanent storage to use
334 /// in place of \p S.
335 StringRef internString(StringRef S);
336
337 // \brief Return the first entry of the string table.
338 const MapTy::MapEntryTy *getFirstEntry() const {
339 return getNextEntry(&Sentinel);
340 }
341
342 // \brief Get the entry following \p E in the string table or null
343 // if \p E was the last entry.
344 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
345 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
346 }
347
348 uint64_t getSize() { return CurrentEndOffset; }
349
350private:
351 MapTy Strings;
352 uint32_t CurrentEndOffset;
353 MapTy::MapEntryTy Sentinel, *Last;
354};
355
356/// \brief Get the offset of string \p S in the string table. This
357/// can insert a new element or return the offset of a preexisitng
358/// one.
359uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
360 if (S.empty() && !Strings.empty())
361 return 0;
362
363 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
364 MapTy::iterator It;
365 bool Inserted;
366
367 // A non-empty string can't be at offset 0, so if we have an entry
368 // with a 0 offset, it must be a previously interned string.
369 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
370 if (Inserted || It->getValue().first == 0) {
371 // Set offset and chain at the end of the entries list.
372 It->getValue().first = CurrentEndOffset;
373 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
374 Last->getValue().second = &*It;
375 Last = &*It;
376 }
377 return It->getValue().first;
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000378}
Frederic Rissef648462015-03-06 17:56:30 +0000379
380/// \brief Put \p S into the StringMap so that it gets permanent
381/// storage, but do not actually link it in the chain of elements
382/// that go into the output section. A latter call to
383/// getStringOffset() with the same string will chain it though.
384StringRef NonRelocatableStringpool::internString(StringRef S) {
385 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
386 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
387 return InsertResult.first->getKey();
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000388}
Frederic Rissef648462015-03-06 17:56:30 +0000389
Frederic Rissc99ea202015-02-28 00:29:11 +0000390/// \brief The Dwarf streaming logic
391///
392/// All interactions with the MC layer that is used to build the debug
393/// information binary representation are handled in this class.
394class DwarfStreamer {
395 /// \defgroup MCObjects MC layer objects constructed by the streamer
396 /// @{
397 std::unique_ptr<MCRegisterInfo> MRI;
398 std::unique_ptr<MCAsmInfo> MAI;
399 std::unique_ptr<MCObjectFileInfo> MOFI;
400 std::unique_ptr<MCContext> MC;
401 MCAsmBackend *MAB; // Owned by MCStreamer
402 std::unique_ptr<MCInstrInfo> MII;
403 std::unique_ptr<MCSubtargetInfo> MSTI;
404 MCCodeEmitter *MCE; // Owned by MCStreamer
405 MCStreamer *MS; // Owned by AsmPrinter
406 std::unique_ptr<TargetMachine> TM;
407 std::unique_ptr<AsmPrinter> Asm;
408 /// @}
409
410 /// \brief the file we stream the linked Dwarf to.
411 std::unique_ptr<raw_fd_ostream> OutFile;
412
Frederic Riss25440872015-03-13 23:30:31 +0000413 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000414 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000415 uint32_t LineSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000416
Frederic Rissbce93ff2015-03-16 02:05:10 +0000417 /// \brief Emit the pubnames or pubtypes section contribution for \p
418 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000419 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000420 const CompileUnit &Unit,
421 const std::vector<CompileUnit::AccelInfo> &Names);
422
Frederic Rissc99ea202015-02-28 00:29:11 +0000423public:
424 /// \brief Actually create the streamer and the ouptut file.
425 ///
426 /// This could be done directly in the constructor, but it feels
427 /// more natural to handle errors through return value.
428 bool init(Triple TheTriple, StringRef OutputFilename);
429
Frederic Rissb8b43d52015-03-04 22:07:44 +0000430 /// \brief Dump the file to the disk.
Frederic Rissc99ea202015-02-28 00:29:11 +0000431 bool finish();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000432
433 AsmPrinter &getAsmPrinter() const { return *Asm; }
434
435 /// \brief Set the current output section to debug_info and change
436 /// the MC Dwarf version to \p DwarfVersion.
437 void switchToDebugInfoSection(unsigned DwarfVersion);
438
439 /// \brief Emit the compilation unit header for \p Unit in the
440 /// debug_info section.
441 ///
442 /// As a side effect, this also switches the current Dwarf version
443 /// of the MC layer to the one of U.getOrigUnit().
444 void emitCompileUnitHeader(CompileUnit &Unit);
445
446 /// \brief Recursively emit the DIE tree rooted at \p Die.
447 void emitDIE(DIE &Die);
448
449 /// \brief Emit the abbreviation table \p Abbrevs to the
450 /// debug_abbrev section.
451 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000452
453 /// \brief Emit the string table described by \p Pool.
454 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000455
456 /// \brief Emit debug_ranges for \p FuncRange by translating the
457 /// original \p Entries.
458 void emitRangesEntries(
459 int64_t UnitPcOffset, uint64_t OrigLowPc,
460 FunctionIntervals::const_iterator FuncRange,
461 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
462 unsigned AddressSize);
463
Frederic Riss563b1b02015-03-14 03:46:51 +0000464 /// \brief Emit debug_aranges entries for \p Unit and if \p
465 /// DoRangesSection is true, also emit the debug_ranges entries for
466 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
467 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000468
469 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000470
471 /// \brief Emit the debug_loc contribution for \p Unit by copying
472 /// the entries from \p Dwarf and offseting them. Update the
473 /// location attributes to point to the new entries.
474 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000475
476 /// \brief Emit the line table described in \p Rows into the
477 /// debug_line section.
478 void emitLineTableForUnit(StringRef PrologueBytes, unsigned MinInstLength,
479 std::vector<DWARFDebugLine::Row> &Rows,
480 unsigned AdddressSize);
481
482 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000483
484 /// \brief Emit the .debug_pubnames contribution for \p Unit.
485 void emitPubNamesForUnit(const CompileUnit &Unit);
486
487 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
488 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Rissc99ea202015-02-28 00:29:11 +0000489};
490
491bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
492 std::string ErrorStr;
493 std::string TripleName;
494 StringRef Context = "dwarf streamer init";
495
496 // Get the target.
497 const Target *TheTarget =
498 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
499 if (!TheTarget)
500 return error(ErrorStr, Context);
501 TripleName = TheTriple.getTriple();
502
503 // Create all the MC Objects.
504 MRI.reset(TheTarget->createMCRegInfo(TripleName));
505 if (!MRI)
506 return error(Twine("no register info for target ") + TripleName, Context);
507
508 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
509 if (!MAI)
510 return error("no asm info for target " + TripleName, Context);
511
512 MOFI.reset(new MCObjectFileInfo);
513 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
514 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
515 *MC);
516
517 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
518 if (!MAB)
519 return error("no asm backend for target " + TripleName, Context);
520
521 MII.reset(TheTarget->createMCInstrInfo());
522 if (!MII)
523 return error("no instr info info for target " + TripleName, Context);
524
525 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
526 if (!MSTI)
527 return error("no subtarget info for target " + TripleName, Context);
528
Eric Christopher0169e422015-03-10 22:03:14 +0000529 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000530 if (!MCE)
531 return error("no code emitter for target " + TripleName, Context);
532
533 // Create the output file.
534 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000535 OutFile =
536 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000537 if (EC)
538 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
539
Rafael Espindolaf696df12015-03-16 22:29:29 +0000540 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
Rafael Espindola36a15cb2015-03-20 20:00:01 +0000541 *MSTI, false,
542 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000543 if (!MS)
544 return error("no object streamer for target " + TripleName, Context);
545
546 // Finally create the AsmPrinter we'll use to emit the DIEs.
547 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
548 if (!TM)
549 return error("no target machine for target " + TripleName, Context);
550
551 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
552 if (!Asm)
553 return error("no asm printer for target " + TripleName, Context);
554
Frederic Riss25440872015-03-13 23:30:31 +0000555 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000556 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000557 LineSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000558
Frederic Rissc99ea202015-02-28 00:29:11 +0000559 return true;
560}
561
562bool DwarfStreamer::finish() {
563 MS->Finish();
564 return true;
565}
566
Frederic Rissb8b43d52015-03-04 22:07:44 +0000567/// \brief Set the current output section to debug_info and change
568/// the MC Dwarf version to \p DwarfVersion.
569void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
570 MS->SwitchSection(MOFI->getDwarfInfoSection());
571 MC->setDwarfVersion(DwarfVersion);
572}
573
574/// \brief Emit the compilation unit header for \p Unit in the
575/// debug_info section.
576///
577/// A Dwarf scetion header is encoded as:
578/// uint32_t Unit length (omiting this field)
579/// uint16_t Version
580/// uint32_t Abbreviation table offset
581/// uint8_t Address size
582///
583/// Leading to a total of 11 bytes.
584void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
585 unsigned Version = Unit.getOrigUnit().getVersion();
586 switchToDebugInfoSection(Version);
587
588 // Emit size of content not including length itself. The size has
589 // already been computed in CompileUnit::computeOffsets(). Substract
590 // 4 to that size to account for the length field.
591 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
592 Asm->EmitInt16(Version);
593 // We share one abbreviations table across all units so it's always at the
594 // start of the section.
595 Asm->EmitInt32(0);
596 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
597}
598
599/// \brief Emit the \p Abbrevs array as the shared abbreviation table
600/// for the linked Dwarf file.
601void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
602 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
603 Asm->emitDwarfAbbrevs(Abbrevs);
604}
605
606/// \brief Recursively emit the DIE tree rooted at \p Die.
607void DwarfStreamer::emitDIE(DIE &Die) {
608 MS->SwitchSection(MOFI->getDwarfInfoSection());
609 Asm->emitDwarfDIE(Die);
610}
611
Frederic Rissef648462015-03-06 17:56:30 +0000612/// \brief Emit the debug_str section stored in \p Pool.
613void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000614 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000615 for (auto *Entry = Pool.getFirstEntry(); Entry;
616 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000617 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000618 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
619}
620
Frederic Riss25440872015-03-13 23:30:31 +0000621/// \brief Emit the debug_range section contents for \p FuncRange by
622/// translating the original \p Entries. The debug_range section
623/// format is totally trivial, consisting just of pairs of address
624/// sized addresses describing the ranges.
625void DwarfStreamer::emitRangesEntries(
626 int64_t UnitPcOffset, uint64_t OrigLowPc,
627 FunctionIntervals::const_iterator FuncRange,
628 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
629 unsigned AddressSize) {
630 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
631
632 // Offset each range by the right amount.
633 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
634 for (const auto &Range : Entries) {
635 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
636 warn("unsupported base address selection operation",
637 "emitting debug_ranges");
638 break;
639 }
640 // Do not emit empty ranges.
641 if (Range.StartAddress == Range.EndAddress)
642 continue;
643
644 // All range entries should lie in the function range.
645 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
646 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
647 warn("inconsistent range data.", "emitting debug_ranges");
648 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
649 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
650 RangesSectionSize += 2 * AddressSize;
651 }
652
653 // Add the terminator entry.
654 MS->EmitIntValue(0, AddressSize);
655 MS->EmitIntValue(0, AddressSize);
656 RangesSectionSize += 2 * AddressSize;
657}
658
Frederic Riss563b1b02015-03-14 03:46:51 +0000659/// \brief Emit the debug_aranges contribution of a unit and
660/// if \p DoDebugRanges is true the debug_range contents for a
661/// compile_unit level DW_AT_ranges attribute (Which are basically the
662/// same thing with a different base address).
663/// Just aggregate all the ranges gathered inside that unit.
664void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
665 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000666 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
667 // Gather the ranges in a vector, so that we can simplify them. The
668 // IntervalMap will have coalesced the non-linked ranges, but here
669 // we want to coalesce the linked addresses.
670 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
671 const auto &FunctionRanges = Unit.getFunctionRanges();
672 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
673 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000674 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
675 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000676
677 // The object addresses where sorted, but again, the linked
678 // addresses might end up in a different order.
679 std::sort(Ranges.begin(), Ranges.end());
680
Frederic Riss563b1b02015-03-14 03:46:51 +0000681 if (!Ranges.empty()) {
682 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
683
Rafael Espindola9ab09232015-03-17 20:07:06 +0000684 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
685 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000686
687 unsigned HeaderSize =
688 sizeof(int32_t) + // Size of contents (w/o this field
689 sizeof(int16_t) + // DWARF ARange version number
690 sizeof(int32_t) + // Offset of CU in the .debug_info section
691 sizeof(int8_t) + // Pointer Size (in bytes)
692 sizeof(int8_t); // Segment Size (in bytes)
693
694 unsigned TupleSize = AddressSize * 2;
695 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
696
697 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000698 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000699 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
700 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
701 Asm->EmitInt8(AddressSize); // Address size
702 Asm->EmitInt8(0); // Segment size
703
Lang Hames9ff69c82015-04-24 19:11:51 +0000704 Asm->OutStreamer->EmitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000705
706 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
707 ++Range) {
708 uint64_t RangeStart = Range->first;
709 MS->EmitIntValue(RangeStart, AddressSize);
710 while ((Range + 1) != End && Range->second == (Range + 1)->first)
711 ++Range;
712 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
713 }
714
715 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000716 Asm->OutStreamer->EmitIntValue(0, AddressSize);
717 Asm->OutStreamer->EmitIntValue(0, AddressSize);
718 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000719 }
720
721 if (!DoDebugRanges)
722 return;
723
724 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
725 // Offset each range by the right amount.
726 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000727 // Emit coalesced ranges.
728 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000729 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000730 while (Range + 1 != End && Range->second == (Range + 1)->first)
731 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000732 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000733 RangesSectionSize += 2 * AddressSize;
734 }
735
736 // Add the terminator entry.
737 MS->EmitIntValue(0, AddressSize);
738 MS->EmitIntValue(0, AddressSize);
739 RangesSectionSize += 2 * AddressSize;
740}
741
Frederic Rissdfb97902015-03-14 15:49:07 +0000742/// \brief Emit location lists for \p Unit and update attribtues to
743/// point to the new entries.
744void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
745 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000746 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000747
748 if (Attributes.empty())
749 return;
750
751 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
752
753 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
754 const DWARFSection &InputSec = Dwarf.getLocSection();
755 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
756 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000757 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000758 int64_t UnitPcOffset = 0;
759 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
760 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
761 if (OrigLowPc != -1ULL)
762 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
763
764 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000765 uint32_t Offset = Attr.first.get();
766 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000767 // This is the quantity to add to the old location address to get
768 // the correct address for the new one.
769 int64_t LocPcOffset = Attr.second + UnitPcOffset;
770 while (Data.isValidOffset(Offset)) {
771 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
772 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
773 LocSectionSize += 2 * AddressSize;
774 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000775 Asm->OutStreamer->EmitIntValue(0, AddressSize);
776 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000777 break;
778 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000779 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
780 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000781 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000782 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000783 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000784 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000785 StringRef(InputSec.Data.substr(Offset, Length)));
786 Offset += Length;
787 LocSectionSize += Length + 2;
788 }
789 }
790}
791
Frederic Riss63786b02015-03-15 20:45:43 +0000792void DwarfStreamer::emitLineTableForUnit(StringRef PrologueBytes,
793 unsigned MinInstLength,
794 std::vector<DWARFDebugLine::Row> &Rows,
795 unsigned PointerSize) {
796 // Switch to the section where the table will be emitted into.
797 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000798 MCSymbol *LineStartSym = MC->createTempSymbol();
799 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000800
801 // The first 4 bytes is the total length of the information for this
802 // compilation unit (not including these 4 bytes for the length).
803 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000804 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000805 // Copy Prologue.
806 MS->EmitBytes(PrologueBytes);
807 LineSectionSize += PrologueBytes.size() + 4;
808
Frederic Rissc3820d02015-03-15 22:20:28 +0000809 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000810 raw_svector_ostream EncodingOS(EncodingBuffer);
811
812 if (Rows.empty()) {
813 // We only have the dummy entry, dsymutil emits an entry with a 0
814 // address in that case.
815 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
816 MS->EmitBytes(EncodingOS.str());
817 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000818 MS->EmitLabel(LineEndSym);
819 return;
820 }
821
822 // Line table state machine fields
823 unsigned FileNum = 1;
824 unsigned LastLine = 1;
825 unsigned Column = 0;
826 unsigned IsStatement = 1;
827 unsigned Isa = 0;
828 uint64_t Address = -1ULL;
829
830 unsigned RowsSinceLastSequence = 0;
831
832 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
833 auto &Row = Rows[Idx];
834
835 int64_t AddressDelta;
836 if (Address == -1ULL) {
837 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
838 MS->EmitULEB128IntValue(PointerSize + 1);
839 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
840 MS->EmitIntValue(Row.Address, PointerSize);
841 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
842 AddressDelta = 0;
843 } else {
844 AddressDelta = (Row.Address - Address) / MinInstLength;
845 }
846
847 // FIXME: code copied and transfromed from
848 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
849 // this code, but the current compatibility requirement with
850 // classic dsymutil makes it hard. Revisit that once this
851 // requirement is dropped.
852
853 if (FileNum != Row.File) {
854 FileNum = Row.File;
855 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
856 MS->EmitULEB128IntValue(FileNum);
857 LineSectionSize += 1 + getULEB128Size(FileNum);
858 }
859 if (Column != Row.Column) {
860 Column = Row.Column;
861 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
862 MS->EmitULEB128IntValue(Column);
863 LineSectionSize += 1 + getULEB128Size(Column);
864 }
865
866 // FIXME: We should handle the discriminator here, but dsymutil
867 // doesn' consider it, thus ignore it for now.
868
869 if (Isa != Row.Isa) {
870 Isa = Row.Isa;
871 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
872 MS->EmitULEB128IntValue(Isa);
873 LineSectionSize += 1 + getULEB128Size(Isa);
874 }
875 if (IsStatement != Row.IsStmt) {
876 IsStatement = Row.IsStmt;
877 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
878 LineSectionSize += 1;
879 }
880 if (Row.BasicBlock) {
881 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
882 LineSectionSize += 1;
883 }
884
885 if (Row.PrologueEnd) {
886 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
887 LineSectionSize += 1;
888 }
889
890 if (Row.EpilogueBegin) {
891 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
892 LineSectionSize += 1;
893 }
894
895 int64_t LineDelta = int64_t(Row.Line) - LastLine;
896 if (!Row.EndSequence) {
897 MCDwarfLineAddr::Encode(*MC, LineDelta, AddressDelta, EncodingOS);
898 MS->EmitBytes(EncodingOS.str());
899 LineSectionSize += EncodingBuffer.size();
900 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000901 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000902 Address = Row.Address;
903 LastLine = Row.Line;
904 RowsSinceLastSequence++;
905 } else {
906 if (LineDelta) {
907 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
908 MS->EmitSLEB128IntValue(LineDelta);
909 LineSectionSize += 1 + getSLEB128Size(LineDelta);
910 }
911 if (AddressDelta) {
912 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
913 MS->EmitULEB128IntValue(AddressDelta);
914 LineSectionSize += 1 + getULEB128Size(AddressDelta);
915 }
916 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
917 MS->EmitBytes(EncodingOS.str());
918 LineSectionSize += EncodingBuffer.size();
919 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000920 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000921 Address = -1ULL;
922 LastLine = FileNum = IsStatement = 1;
923 RowsSinceLastSequence = Column = Isa = 0;
924 }
925 }
926
927 if (RowsSinceLastSequence) {
928 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
929 MS->EmitBytes(EncodingOS.str());
930 LineSectionSize += EncodingBuffer.size();
931 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000932 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000933 }
934
935 MS->EmitLabel(LineEndSym);
936}
937
Frederic Rissbce93ff2015-03-16 02:05:10 +0000938/// \brief Emit the pubnames or pubtypes section contribution for \p
939/// Unit into \p Sec. The data is provided in \p Names.
940void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000941 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000942 const std::vector<CompileUnit::AccelInfo> &Names) {
943 if (Names.empty())
944 return;
945
946 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +0000947 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +0000948 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
949 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +0000950
951 bool HeaderEmitted = false;
952 // Emit the pubnames for this compilation unit.
953 for (const auto &Name : Names) {
954 if (Name.SkipPubSection)
955 continue;
956
957 if (!HeaderEmitted) {
958 // Emit the header.
959 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +0000960 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +0000961 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
962 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
963 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
964 HeaderEmitted = true;
965 }
966 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +0000967 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +0000968 StringRef(Name.Name.data(), Name.Name.size() + 1));
969 }
970
971 if (!HeaderEmitted)
972 return;
973 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +0000974 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +0000975}
976
977/// \brief Emit .debug_pubnames for \p Unit.
978void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
979 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
980 "names", Unit, Unit.getPubnames());
981}
982
983/// \brief Emit .debug_pubtypes for \p Unit.
984void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
985 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
986 "types", Unit, Unit.getPubtypes());
987}
988
Frederic Rissd3455182015-01-28 18:27:01 +0000989/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +0000990///
991/// The link of the dwarf information from the object files will be
992/// driven by the selection of 'root DIEs', which are DIEs that
993/// describe variables or functions that are present in the linked
994/// binary (and thus have entries in the debug map). All the debug
995/// information that will be linked (the DIEs, but also the line
996/// tables, ranges, ...) is derived from that set of root DIEs.
997///
998/// The root DIEs are identified because they contain relocations that
999/// correspond to a debug map entry at specific places (the low_pc for
1000/// a function, the location for a variable). These relocations are
1001/// called ValidRelocs in the DwarfLinker and are gathered as a very
1002/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001003class DwarfLinker {
1004public:
Frederic Rissb9818322015-02-28 00:29:07 +00001005 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1006 : OutputFilename(OutputFilename), Options(Options),
1007 BinHolder(Options.Verbose) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001008
Frederic Rissb8b43d52015-03-04 22:07:44 +00001009 ~DwarfLinker() {
1010 for (auto *Abbrev : Abbreviations)
1011 delete Abbrev;
1012 }
1013
Frederic Rissd3455182015-01-28 18:27:01 +00001014 /// \brief Link the contents of the DebugMap.
1015 bool link(const DebugMap &);
1016
1017private:
Frederic Riss563cba62015-01-28 22:15:14 +00001018 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001019 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001020
1021 /// \brief Called at the end of a debug object link.
1022 void endDebugObject();
1023
Frederic Riss1036e642015-02-13 23:18:22 +00001024 /// \defgroup FindValidRelocations Translate debug map into a list
1025 /// of relevant relocations
1026 ///
1027 /// @{
1028 struct ValidReloc {
1029 uint32_t Offset;
1030 uint32_t Size;
1031 uint64_t Addend;
1032 const DebugMapObject::DebugMapEntry *Mapping;
1033
1034 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1035 const DebugMapObject::DebugMapEntry *Mapping)
1036 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1037
1038 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1039 };
1040
1041 /// \brief The valid relocations for the current DebugMapObject.
1042 /// This vector is sorted by relocation offset.
1043 std::vector<ValidReloc> ValidRelocs;
1044
1045 /// \brief Index into ValidRelocs of the next relocation to
1046 /// consider. As we walk the DIEs in acsending file offset and as
1047 /// ValidRelocs is sorted by file offset, keeping this index
1048 /// uptodate is all we have to do to have a cheap lookup during the
Frederic Riss23e20e92015-03-07 01:25:09 +00001049 /// root DIE selection and during DIE cloning.
Frederic Riss1036e642015-02-13 23:18:22 +00001050 unsigned NextValidReloc;
1051
1052 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1053 const DebugMapObject &DMO);
1054
1055 bool findValidRelocs(const object::SectionRef &Section,
1056 const object::ObjectFile &Obj,
1057 const DebugMapObject &DMO);
1058
1059 void findValidRelocsMachO(const object::SectionRef &Section,
1060 const object::MachOObjectFile &Obj,
1061 const DebugMapObject &DMO);
1062 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +00001063
Frederic Riss84c09a52015-02-13 23:18:34 +00001064 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1065 ///
1066 /// @{
1067 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1068 /// keep. Store that information in \p CU's DIEInfo.
1069 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1070 const DebugMapObject &DMO, CompileUnit &CU,
1071 unsigned Flags);
1072
1073 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1074 enum TravesalFlags {
1075 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1076 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1077 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1078 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
1079 };
1080
1081 /// \brief Mark the passed DIE as well as all the ones it depends on
1082 /// as kept.
1083 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1084 CompileUnit::DIEInfo &MyInfo,
1085 const DebugMapObject &DMO, CompileUnit &CU,
1086 unsigned Flags);
1087
1088 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1089 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1090 unsigned Flags);
1091
1092 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1093 CompileUnit &Unit,
1094 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1095
1096 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1097 CompileUnit &Unit,
1098 CompileUnit::DIEInfo &MyInfo,
1099 unsigned Flags);
1100
1101 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1102 CompileUnit::DIEInfo &Info);
1103 /// @}
1104
Frederic Rissb8b43d52015-03-04 22:07:44 +00001105 /// \defgroup Linking Methods used to link the debug information
1106 ///
1107 /// @{
1108 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1109 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1110 /// stripped out and addresses have been rewritten according to the
1111 /// debug map.
1112 ///
1113 /// \param OutOffset is the offset the cloned DIE in the output
1114 /// compile unit.
Frederic Riss31da3242015-03-11 18:45:52 +00001115 /// \param PCOffset (while cloning a function scope) is the offset
1116 /// applied to the entry point of the function to get the linked address.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001117 ///
1118 /// \returns the root of the cloned tree.
1119 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Frederic Riss31da3242015-03-11 18:45:52 +00001120 int64_t PCOffset, uint32_t OutOffset);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001121
1122 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1123
Frederic Riss31da3242015-03-11 18:45:52 +00001124 /// \brief Information gathered and exchanged between the various
1125 /// clone*Attributes helpers about the attributes of a particular DIE.
1126 struct AttributesInfo {
Frederic Rissbce93ff2015-03-16 02:05:10 +00001127 const char *Name, *MangledName; ///< Names.
1128 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1129
Frederic Riss31da3242015-03-11 18:45:52 +00001130 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1131 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1132
Frederic Rissbce93ff2015-03-16 02:05:10 +00001133 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1134 bool IsDeclaration; ///< Is this DIE only a declaration?
1135
1136 AttributesInfo()
1137 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1138 MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1139 IsDeclaration(false) {}
Frederic Riss31da3242015-03-11 18:45:52 +00001140 };
1141
Frederic Rissb8b43d52015-03-04 22:07:44 +00001142 /// \brief Helper for cloneDIE.
1143 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1144 CompileUnit &U, const DWARFFormValue &Val,
Frederic Riss31da3242015-03-11 18:45:52 +00001145 const AttributeSpec AttrSpec, unsigned AttrSize,
1146 AttributesInfo &AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001147
1148 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +00001149 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1150 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001151
1152 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +00001153 unsigned
1154 cloneDieReferenceAttribute(DIE &Die,
1155 const DWARFDebugInfoEntryMinimal &InputDIE,
1156 AttributeSpec AttrSpec, unsigned AttrSize,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001157 const DWARFFormValue &Val, CompileUnit &Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001158
1159 /// \brief Helper for cloneDIE.
1160 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1161 const DWARFFormValue &Val, unsigned AttrSize);
1162
1163 /// \brief Helper for cloneDIE.
Frederic Riss31da3242015-03-11 18:45:52 +00001164 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1165 const DWARFFormValue &Val,
1166 const CompileUnit &Unit, AttributesInfo &Info);
1167
1168 /// \brief Helper for cloneDIE.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001169 unsigned cloneScalarAttribute(DIE &Die,
1170 const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss25440872015-03-13 23:30:31 +00001171 CompileUnit &U, AttributeSpec AttrSpec,
Frederic Rissdfb97902015-03-14 15:49:07 +00001172 const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001173 AttributesInfo &Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001174
Frederic Riss23e20e92015-03-07 01:25:09 +00001175 /// \brief Helper for cloneDIE.
1176 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1177 bool isLittleEndian);
1178
Frederic Rissb8b43d52015-03-04 22:07:44 +00001179 /// \brief Assign an abbreviation number to \p Abbrev
1180 void AssignAbbrev(DIEAbbrev &Abbrev);
1181
1182 /// \brief FoldingSet that uniques the abbreviations.
1183 FoldingSet<DIEAbbrev> AbbreviationsSet;
1184 /// \brief Storage for the unique Abbreviations.
1185 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1186 /// be changed to a vecot of unique_ptrs.
1187 std::vector<DIEAbbrev *> Abbreviations;
1188
Frederic Riss25440872015-03-13 23:30:31 +00001189 /// \brief Compute and emit debug_ranges section for \p Unit, and
1190 /// patch the attributes referencing it.
1191 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1192
1193 /// \brief Generate and emit the DW_AT_ranges attribute for a
1194 /// compile_unit if it had one.
1195 void generateUnitRanges(CompileUnit &Unit) const;
1196
Frederic Riss63786b02015-03-15 20:45:43 +00001197 /// \brief Extract the line tables fromt he original dwarf, extract
1198 /// the relevant parts according to the linked function ranges and
1199 /// emit the result in the debug_line section.
1200 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1201
Frederic Rissbce93ff2015-03-16 02:05:10 +00001202 /// \brief Emit the accelerator entries for \p Unit.
1203 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1204
Frederic Rissb8b43d52015-03-04 22:07:44 +00001205 /// \brief DIELoc objects that need to be destructed (but not freed!).
1206 std::vector<DIELoc *> DIELocs;
1207 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1208 std::vector<DIEBlock *> DIEBlocks;
1209 /// \brief Allocator used for all the DIEValue objects.
1210 BumpPtrAllocator DIEAlloc;
1211 /// @}
1212
Frederic Riss1b9da422015-02-13 23:18:29 +00001213 /// \defgroup Helpers Various helper methods.
1214 ///
1215 /// @{
1216 const DWARFDebugInfoEntryMinimal *
1217 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
1218 const DWARFDebugInfoEntryMinimal &DIE,
1219 CompileUnit *&ReferencedCU);
1220
1221 CompileUnit *getUnitForOffset(unsigned Offset);
1222
Frederic Rissbce93ff2015-03-16 02:05:10 +00001223 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1224 AttributesInfo &Info);
1225
Frederic Riss1b9da422015-02-13 23:18:29 +00001226 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
Frederic Riss25440872015-03-13 23:30:31 +00001227 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
Frederic Rissc99ea202015-02-28 00:29:11 +00001228
1229 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Riss1b9da422015-02-13 23:18:29 +00001230 /// @}
1231
Frederic Riss563cba62015-01-28 22:15:14 +00001232private:
Frederic Rissd3455182015-01-28 18:27:01 +00001233 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001234 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001235 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001236 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +00001237
1238 /// The units of the current debug map object.
1239 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001240
1241 /// The debug map object curently under consideration.
1242 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001243
1244 /// \brief The Dwarf string pool
1245 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001246
1247 /// \brief This map is keyed by the entry PC of functions in that
1248 /// debug object and the associated value is a pair storing the
1249 /// corresponding end PC and the offset to apply to get the linked
1250 /// address.
1251 ///
1252 /// See startDebugObject() for a more complete description of its use.
1253 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Rissd3455182015-01-28 18:27:01 +00001254};
1255
Frederic Riss1b9da422015-02-13 23:18:29 +00001256/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1257/// returning our CompileUnit object instead.
1258CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1259 auto CU =
1260 std::upper_bound(Units.begin(), Units.end(), Offset,
1261 [](uint32_t LHS, const CompileUnit &RHS) {
1262 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1263 });
1264 return CU != Units.end() ? &*CU : nullptr;
1265}
1266
1267/// \brief Resolve the DIE attribute reference that has been
1268/// extracted in \p RefValue. The resulting DIE migh be in another
1269/// CompileUnit which is stored into \p ReferencedCU.
1270/// \returns null if resolving fails for any reason.
1271const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1272 DWARFFormValue &RefValue, const DWARFUnit &Unit,
1273 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1274 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1275 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1276
1277 if ((RefCU = getUnitForOffset(RefOffset)))
1278 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1279 return RefDie;
1280
1281 reportWarning("could not find referenced DIE", &Unit, &DIE);
1282 return nullptr;
1283}
1284
Frederic Rissbce93ff2015-03-16 02:05:10 +00001285/// \brief Get the potential name and mangled name for the entity
1286/// described by \p Die and store them in \Info if they are not
1287/// already there.
1288/// \returns is a name was found.
1289bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1290 DWARFUnit &U, AttributesInfo &Info) {
1291 // FIXME: a bit wastefull as the first getName might return the
1292 // short name.
1293 if (!Info.MangledName &&
1294 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1295 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1296
1297 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1298 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1299
1300 return Info.Name || Info.MangledName;
1301}
1302
Frederic Riss1b9da422015-02-13 23:18:29 +00001303/// \brief Report a warning to the user, optionaly including
1304/// information about a specific \p DIE related to the warning.
1305void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001306 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001307 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001308 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001309 Context = CurrentDebugObject->getObjectFilename();
1310 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001311
Frederic Rissb9818322015-02-28 00:29:07 +00001312 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001313 return;
1314
1315 errs() << " in DIE:\n";
1316 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1317 6 /* Indent */);
1318}
1319
Frederic Rissc99ea202015-02-28 00:29:11 +00001320bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1321 if (Options.NoOutput)
1322 return true;
1323
Frederic Rissb52cf522015-02-28 00:42:37 +00001324 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001325 return Streamer->init(TheTriple, OutputFilename);
1326}
1327
Frederic Riss563cba62015-01-28 22:15:14 +00001328/// \brief Recursive helper to gather the child->parent relationships in the
1329/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +00001330static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1331 unsigned ParentIdx, CompileUnit &CU) {
Frederic Riss563cba62015-01-28 22:15:14 +00001332 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1333 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
1334
1335 if (DIE->hasChildren())
1336 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1337 Child = Child->getSibling())
Frederic Riss9aa725b2015-02-13 23:18:31 +00001338 gatherDIEParents(Child, MyIdx, CU);
Frederic Riss563cba62015-01-28 22:15:14 +00001339}
1340
Frederic Riss84c09a52015-02-13 23:18:34 +00001341static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1342 switch (Tag) {
1343 default:
1344 return false;
1345 case dwarf::DW_TAG_subprogram:
1346 case dwarf::DW_TAG_lexical_block:
1347 case dwarf::DW_TAG_subroutine_type:
1348 case dwarf::DW_TAG_structure_type:
1349 case dwarf::DW_TAG_class_type:
1350 case dwarf::DW_TAG_union_type:
1351 return true;
1352 }
1353 llvm_unreachable("Invalid Tag");
1354}
1355
Frederic Riss63786b02015-03-15 20:45:43 +00001356void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001357 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +00001358 NextValidReloc = 0;
Frederic Riss63786b02015-03-15 20:45:43 +00001359 // Iterate over the debug map entries and put all the ones that are
1360 // functions (because they have a size) into the Ranges map. This
1361 // map is very similar to the FunctionRanges that are stored in each
1362 // unit, with 2 notable differences:
1363 // - obviously this one is global, while the other ones are per-unit.
1364 // - this one contains not only the functions described in the DIE
1365 // tree, but also the ones that are only in the debug map.
1366 // The latter information is required to reproduce dsymutil's logic
1367 // while linking line tables. The cases where this information
1368 // matters look like bugs that need to be investigated, but for now
1369 // we need to reproduce dsymutil's behavior.
1370 // FIXME: Once we understood exactly if that information is needed,
1371 // maybe totally remove this (or try to use it to do a real
1372 // -gline-tables-only on Darwin.
1373 for (const auto &Entry : Obj.symbols()) {
1374 const auto &Mapping = Entry.getValue();
1375 if (Mapping.Size)
1376 Ranges[Mapping.ObjectAddress] = std::make_pair(
1377 Mapping.ObjectAddress + Mapping.Size,
1378 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1379 }
Frederic Riss563cba62015-01-28 22:15:14 +00001380}
1381
Frederic Riss1036e642015-02-13 23:18:22 +00001382void DwarfLinker::endDebugObject() {
1383 Units.clear();
1384 ValidRelocs.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001385 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001386
1387 for (auto *Block : DIEBlocks)
1388 Block->~DIEBlock();
1389 for (auto *Loc : DIELocs)
1390 Loc->~DIELoc();
1391
1392 DIEBlocks.clear();
1393 DIELocs.clear();
1394 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001395}
1396
1397/// \brief Iterate over the relocations of the given \p Section and
1398/// store the ones that correspond to debug map entries into the
1399/// ValidRelocs array.
1400void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1401 const object::MachOObjectFile &Obj,
1402 const DebugMapObject &DMO) {
1403 StringRef Contents;
1404 Section.getContents(Contents);
1405 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1406
1407 for (const object::RelocationRef &Reloc : Section.relocations()) {
1408 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1409 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1410 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1411 uint64_t Offset64;
1412 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001413 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001414 continue;
1415 }
1416 uint32_t Offset = Offset64;
1417 // Mach-o uses REL relocations, the addend is at the relocation offset.
1418 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1419
1420 auto Sym = Reloc.getSymbol();
1421 if (Sym != Obj.symbol_end()) {
1422 StringRef SymbolName;
1423 if (Sym->getName(SymbolName)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001424 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001425 continue;
1426 }
1427 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
1428 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1429 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1430 // Do not store the addend. The addend was the address of the
1431 // symbol in the object file, the address in the binary that is
1432 // stored in the debug map doesn't need to be offseted.
1433 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1434 }
1435 }
1436}
1437
1438/// \brief Dispatch the valid relocation finding logic to the
1439/// appropriate handler depending on the object file format.
1440bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1441 const object::ObjectFile &Obj,
1442 const DebugMapObject &DMO) {
1443 // Dispatch to the right handler depending on the file type.
1444 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1445 findValidRelocsMachO(Section, *MachOObj, DMO);
1446 else
Frederic Riss1b9da422015-02-13 23:18:29 +00001447 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001448
1449 if (ValidRelocs.empty())
1450 return false;
1451
1452 // Sort the relocations by offset. We will walk the DIEs linearly in
1453 // the file, this allows us to just keep an index in the relocation
1454 // array that we advance during our walk, rather than resorting to
1455 // some associative container. See DwarfLinker::NextValidReloc.
1456 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1457 return true;
1458}
1459
1460/// \brief Look for relocations in the debug_info section that match
1461/// entries in the debug map. These relocations will drive the Dwarf
1462/// link by indicating which DIEs refer to symbols present in the
1463/// linked binary.
1464/// \returns wether there are any valid relocations in the debug info.
1465bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1466 const DebugMapObject &DMO) {
1467 // Find the debug_info section.
1468 for (const object::SectionRef &Section : Obj.sections()) {
1469 StringRef SectionName;
1470 Section.getName(SectionName);
1471 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1472 if (SectionName != "debug_info")
1473 continue;
1474 return findValidRelocs(Section, Obj, DMO);
1475 }
1476 return false;
1477}
Frederic Riss563cba62015-01-28 22:15:14 +00001478
Frederic Riss84c09a52015-02-13 23:18:34 +00001479/// \brief Checks that there is a relocation against an actual debug
1480/// map entry between \p StartOffset and \p NextOffset.
1481///
1482/// This function must be called with offsets in strictly ascending
1483/// order because it never looks back at relocations it already 'went past'.
1484/// \returns true and sets Info.InDebugMap if it is the case.
1485bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1486 CompileUnit::DIEInfo &Info) {
1487 assert(NextValidReloc == 0 ||
1488 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1489 if (NextValidReloc >= ValidRelocs.size())
1490 return false;
1491
1492 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1493
1494 // We might need to skip some relocs that we didn't consider. For
1495 // example the high_pc of a discarded DIE might contain a reloc that
1496 // is in the list because it actually corresponds to the start of a
1497 // function that is in the debug map.
1498 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1499 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1500
1501 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1502 return false;
1503
1504 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Rissb9818322015-02-28 00:29:07 +00001505 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001506 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1507 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1508 ValidReloc.Mapping->getValue().ObjectAddress,
1509 ValidReloc.Mapping->getValue().BinaryAddress);
1510
Frederic Riss31da3242015-03-11 18:45:52 +00001511 Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
1512 ValidReloc.Addend -
1513 ValidReloc.Mapping->getValue().ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001514 Info.InDebugMap = true;
1515 return true;
1516}
1517
1518/// \brief Get the starting and ending (exclusive) offset for the
1519/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1520/// supposed to point to the position of the first attribute described
1521/// by \p Abbrev.
1522/// \return [StartOffset, EndOffset) as a pair.
1523static std::pair<uint32_t, uint32_t>
1524getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1525 unsigned Offset, const DWARFUnit &Unit) {
1526 DataExtractor Data = Unit.getDebugInfoExtractor();
1527
1528 for (unsigned i = 0; i < Idx; ++i)
1529 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1530
1531 uint32_t End = Offset;
1532 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1533
1534 return std::make_pair(Offset, End);
1535}
1536
1537/// \brief Check if a variable describing DIE should be kept.
1538/// \returns updated TraversalFlags.
1539unsigned DwarfLinker::shouldKeepVariableDIE(
1540 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1541 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1542 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1543
1544 // Global variables with constant value can always be kept.
1545 if (!(Flags & TF_InFunctionScope) &&
1546 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1547 MyInfo.InDebugMap = true;
1548 return Flags | TF_Keep;
1549 }
1550
1551 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1552 if (LocationIdx == -1U)
1553 return Flags;
1554
1555 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1556 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1557 uint32_t LocationOffset, LocationEndOffset;
1558 std::tie(LocationOffset, LocationEndOffset) =
1559 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1560
1561 // See if there is a relocation to a valid debug map entry inside
1562 // this variable's location. The order is important here. We want to
1563 // always check in the variable has a valid relocation, so that the
1564 // DIEInfo is filled. However, we don't want a static variable in a
1565 // function to force us to keep the enclosing function.
1566 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1567 (Flags & TF_InFunctionScope))
1568 return Flags;
1569
Frederic Rissb9818322015-02-28 00:29:07 +00001570 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001571 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1572
1573 return Flags | TF_Keep;
1574}
1575
1576/// \brief Check if a function describing DIE should be kept.
1577/// \returns updated TraversalFlags.
1578unsigned DwarfLinker::shouldKeepSubprogramDIE(
1579 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1580 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1581 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1582
1583 Flags |= TF_InFunctionScope;
1584
1585 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1586 if (LowPcIdx == -1U)
1587 return Flags;
1588
1589 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1590 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1591 uint32_t LowPcOffset, LowPcEndOffset;
1592 std::tie(LowPcOffset, LowPcEndOffset) =
1593 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1594
1595 uint64_t LowPc =
1596 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1597 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1598 if (LowPc == -1ULL ||
1599 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1600 return Flags;
1601
Frederic Rissb9818322015-02-28 00:29:07 +00001602 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001603 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1604
Frederic Riss1af75f72015-03-12 18:45:10 +00001605 Flags |= TF_Keep;
1606
1607 DWARFFormValue HighPcValue;
1608 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1609 reportWarning("Function without high_pc. Range will be discarded.\n",
1610 &OrigUnit, &DIE);
1611 return Flags;
1612 }
1613
1614 uint64_t HighPc;
1615 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1616 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1617 } else {
1618 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1619 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1620 }
1621
Frederic Riss63786b02015-03-15 20:45:43 +00001622 // Replace the debug map range with a more accurate one.
1623 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00001624 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1625 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00001626}
1627
1628/// \brief Check if a DIE should be kept.
1629/// \returns updated TraversalFlags.
1630unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1631 CompileUnit &Unit,
1632 CompileUnit::DIEInfo &MyInfo,
1633 unsigned Flags) {
1634 switch (DIE.getTag()) {
1635 case dwarf::DW_TAG_constant:
1636 case dwarf::DW_TAG_variable:
1637 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1638 case dwarf::DW_TAG_subprogram:
1639 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1640 case dwarf::DW_TAG_module:
1641 case dwarf::DW_TAG_imported_module:
1642 case dwarf::DW_TAG_imported_declaration:
1643 case dwarf::DW_TAG_imported_unit:
1644 // We always want to keep these.
1645 return Flags | TF_Keep;
1646 }
1647
1648 return Flags;
1649}
1650
Frederic Riss84c09a52015-02-13 23:18:34 +00001651/// \brief Mark the passed DIE as well as all the ones it depends on
1652/// as kept.
1653///
1654/// This function is called by lookForDIEsToKeep on DIEs that are
1655/// newly discovered to be needed in the link. It recursively calls
1656/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1657/// TraversalFlags to inform it that it's not doing the primary DIE
1658/// tree walk.
1659void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1660 CompileUnit::DIEInfo &MyInfo,
1661 const DebugMapObject &DMO,
1662 CompileUnit &CU, unsigned Flags) {
1663 const DWARFUnit &Unit = CU.getOrigUnit();
1664 MyInfo.Keep = true;
1665
1666 // First mark all the parent chain as kept.
1667 unsigned AncestorIdx = MyInfo.ParentIdx;
1668 while (!CU.getInfo(AncestorIdx).Keep) {
1669 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1670 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1671 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1672 }
1673
1674 // Then we need to mark all the DIEs referenced by this DIE's
1675 // attributes as kept.
1676 DataExtractor Data = Unit.getDebugInfoExtractor();
1677 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1678 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1679
1680 // Mark all DIEs referenced through atttributes as kept.
1681 for (const auto &AttrSpec : Abbrev->attributes()) {
1682 DWARFFormValue Val(AttrSpec.Form);
1683
1684 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1685 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1686 continue;
1687 }
1688
1689 Val.extractValue(Data, &Offset, &Unit);
1690 CompileUnit *ReferencedCU;
1691 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1692 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1693 TF_Keep | TF_DependencyWalk);
1694 }
1695}
1696
1697/// \brief Recursively walk the \p DIE tree and look for DIEs to
1698/// keep. Store that information in \p CU's DIEInfo.
1699///
1700/// This function is the entry point of the DIE selection
1701/// algorithm. It is expected to walk the DIE tree in file order and
1702/// (though the mediation of its helper) call hasValidRelocation() on
1703/// each DIE that might be a 'root DIE' (See DwarfLinker class
1704/// comment).
1705/// While walking the dependencies of root DIEs, this function is
1706/// also called, but during these dependency walks the file order is
1707/// not respected. The TF_DependencyWalk flag tells us which kind of
1708/// traversal we are currently doing.
1709void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1710 const DebugMapObject &DMO, CompileUnit &CU,
1711 unsigned Flags) {
1712 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1713 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1714 bool AlreadyKept = MyInfo.Keep;
1715
1716 // If the Keep flag is set, we are marking a required DIE's
1717 // dependencies. If our target is already marked as kept, we're all
1718 // set.
1719 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1720 return;
1721
1722 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1723 // because it would screw up the relocation finding logic.
1724 if (!(Flags & TF_DependencyWalk))
1725 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1726
1727 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1728 if (!AlreadyKept && (Flags & TF_Keep))
1729 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1730
1731 // The TF_ParentWalk flag tells us that we are currently walking up
1732 // the parent chain of a required DIE, and we don't want to mark all
1733 // the children of the parents as kept (consider for example a
1734 // DW_TAG_namespace node in the parent chain). There are however a
1735 // set of DIE types for which we want to ignore that directive and still
1736 // walk their children.
1737 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1738 Flags &= ~TF_ParentWalk;
1739
1740 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1741 return;
1742
1743 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1744 Child = Child->getSibling())
1745 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1746}
1747
Frederic Rissb8b43d52015-03-04 22:07:44 +00001748/// \brief Assign an abbreviation numer to \p Abbrev.
1749///
1750/// Our DIEs get freed after every DebugMapObject has been processed,
1751/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1752/// the instances hold by the DIEs. When we encounter an abbreviation
1753/// that we don't know, we create a permanent copy of it.
1754void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1755 // Check the set for priors.
1756 FoldingSetNodeID ID;
1757 Abbrev.Profile(ID);
1758 void *InsertToken;
1759 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1760
1761 // If it's newly added.
1762 if (InSet) {
1763 // Assign existing abbreviation number.
1764 Abbrev.setNumber(InSet->getNumber());
1765 } else {
1766 // Add to abbreviation list.
1767 Abbreviations.push_back(
1768 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1769 for (const auto &Attr : Abbrev.getData())
1770 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1771 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1772 // Assign the unique abbreviation number.
1773 Abbrev.setNumber(Abbreviations.size());
1774 Abbreviations.back()->setNumber(Abbreviations.size());
1775 }
1776}
1777
1778/// \brief Clone a string attribute described by \p AttrSpec and add
1779/// it to \p Die.
1780/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00001781unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1782 const DWARFFormValue &Val,
1783 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001784 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00001785 const char *String = *Val.getAsCString(&U);
1786 unsigned Offset = StringPool.getStringOffset(String);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001787 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001788 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001789 return 4;
1790}
1791
1792/// \brief Clone an attribute referencing another DIE and add
1793/// it to \p Die.
1794/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00001795unsigned DwarfLinker::cloneDieReferenceAttribute(
1796 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1797 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001798 CompileUnit &Unit) {
1799 uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
Frederic Riss9833de62015-03-06 23:22:53 +00001800 DIE *NewRefDie = nullptr;
1801 CompileUnit *RefUnit = nullptr;
1802 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1803
1804 if (!(RefUnit = getUnitForOffset(Ref)) ||
1805 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1806 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1807 if (!AttributeString)
1808 AttributeString = "DW_AT_???";
1809 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1810 ". Dropping.",
Frederic Riss6afcfce2015-03-13 18:35:57 +00001811 &Unit.getOrigUnit(), &InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00001812 return 0;
1813 }
1814
1815 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1816 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1817 if (!RefInfo.Clone) {
1818 assert(Ref > InputDIE.getOffset());
1819 // We haven't cloned this DIE yet. Just create an empty one and
1820 // store it. It'll get really cloned when we process it.
1821 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1822 }
1823 NewRefDie = RefInfo.Clone;
1824
1825 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1826 // We cannot currently rely on a DIEEntry to emit ref_addr
1827 // references, because the implementation calls back to DwarfDebug
1828 // to find the unit offset. (We don't have a DwarfDebug)
1829 // FIXME: we should be able to design DIEEntry reliance on
1830 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001831 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00001832 if (Ref < InputDIE.getOffset()) {
1833 // We must have already cloned that DIE.
1834 uint32_t NewRefOffset =
1835 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001836 Attr = NewRefOffset;
Frederic Riss9833de62015-03-06 23:22:53 +00001837 } else {
1838 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001839 Attr = 0xBADDEF;
1840 Unit.noteForwardReference(NewRefDie, RefUnit,
1841 PatchLocation(Die, Die.getValues().size()));
Frederic Riss9833de62015-03-06 23:22:53 +00001842 }
1843 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001844 DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00001845 return AttrSize;
1846 }
1847
Frederic Rissb8b43d52015-03-04 22:07:44 +00001848 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001849 DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001850 return AttrSize;
1851}
1852
1853/// \brief Clone an attribute of block form (locations, constants) and add
1854/// it to \p Die.
1855/// \returns the size of the new attribute.
1856unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1857 const DWARFFormValue &Val,
1858 unsigned AttrSize) {
1859 DIE *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001860 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001861 DIELoc *Loc = nullptr;
1862 DIEBlock *Block = nullptr;
1863 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00001864 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001865 Loc = new (DIEAlloc) DIELoc;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001866 DIELocs.push_back(Loc);
1867 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001868 Block = new (DIEAlloc) DIEBlock;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001869 DIEBlocks.push_back(Block);
1870 }
1871 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001872 Value = Loc ? DIEValue(Loc) : DIEValue(Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001873 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1874 for (auto Byte : Bytes)
1875 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001876 DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001877 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1878 // the DIE class, this if could be replaced by
1879 // Attr->setSize(Bytes.size()).
1880 if (Streamer) {
1881 if (Loc)
1882 Loc->ComputeSize(&Streamer->getAsmPrinter());
1883 else
1884 Block->ComputeSize(&Streamer->getAsmPrinter());
1885 }
1886 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1887 Value);
1888 return AttrSize;
1889}
1890
Frederic Riss31da3242015-03-11 18:45:52 +00001891/// \brief Clone an address attribute and add it to \p Die.
1892/// \returns the size of the new attribute.
1893unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1894 const DWARFFormValue &Val,
1895 const CompileUnit &Unit,
1896 AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001897 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00001898 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1899 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1900 Die.getTag() == dwarf::DW_TAG_lexical_block)
1901 Addr += Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001902 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1903 Addr = Unit.getLowPc();
1904 if (Addr == UINT64_MAX)
1905 return 0;
1906 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00001907 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00001908 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001909 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1910 if (uint64_t HighPc = Unit.getHighPc())
1911 Addr = HighPc;
1912 else
1913 return 0;
1914 } else
1915 // If we have a high_pc recorded for the input DIE, use
1916 // it. Otherwise (when no relocations where applied) just use the
1917 // one we just decoded.
1918 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00001919 }
1920
1921 Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001922 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00001923 return Unit.getOrigUnit().getAddressByteSize();
1924}
1925
Frederic Rissb8b43d52015-03-04 22:07:44 +00001926/// \brief Clone a scalar attribute and add it to \p Die.
1927/// \returns the size of the new attribute.
1928unsigned DwarfLinker::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00001929 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00001930 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001931 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001932 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001933 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1934 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1935 if (Unit.getLowPc() == -1ULL)
1936 return 0;
1937 // Dwarf >= 4 high_pc is an size, not an address.
1938 Value = Unit.getHighPc() - Unit.getLowPc();
1939 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00001940 Value = *Val.getAsSectionOffset();
1941 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1942 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001943 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1944 Value = *OptionalValue;
1945 else {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001946 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1947 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001948 return 0;
1949 }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001950 DIEInteger Attr(Value);
Frederic Riss25440872015-03-13 23:30:31 +00001951 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001952 Unit.noteRangeAttribute(Die, PatchLocation(Die, Die.getValues().size()));
Frederic Rissdfb97902015-03-14 15:49:07 +00001953 // A more generic way to check for location attributes would be
1954 // nice, but it's very unlikely that any other attribute needs a
1955 // location list.
1956 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1957 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001958 Unit.noteLocationAttribute(PatchLocation(Die, Die.getValues().size()),
1959 Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001960 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1961 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00001962
Frederic Rissb8b43d52015-03-04 22:07:44 +00001963 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Frederic Riss25440872015-03-13 23:30:31 +00001964 Attr);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001965 return AttrSize;
1966}
1967
1968/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1969/// value \p Val, and add it to \p Die.
1970/// \returns the size of the cloned attribute.
1971unsigned DwarfLinker::cloneAttribute(DIE &Die,
1972 const DWARFDebugInfoEntryMinimal &InputDIE,
1973 CompileUnit &Unit,
1974 const DWARFFormValue &Val,
1975 const AttributeSpec AttrSpec,
Frederic Riss31da3242015-03-11 18:45:52 +00001976 unsigned AttrSize, AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001977 const DWARFUnit &U = Unit.getOrigUnit();
1978
1979 switch (AttrSpec.Form) {
1980 case dwarf::DW_FORM_strp:
1981 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00001982 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001983 case dwarf::DW_FORM_ref_addr:
1984 case dwarf::DW_FORM_ref1:
1985 case dwarf::DW_FORM_ref2:
1986 case dwarf::DW_FORM_ref4:
1987 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00001988 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001989 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001990 case dwarf::DW_FORM_block:
1991 case dwarf::DW_FORM_block1:
1992 case dwarf::DW_FORM_block2:
1993 case dwarf::DW_FORM_block4:
1994 case dwarf::DW_FORM_exprloc:
1995 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1996 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00001997 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001998 case dwarf::DW_FORM_data1:
1999 case dwarf::DW_FORM_data2:
2000 case dwarf::DW_FORM_data4:
2001 case dwarf::DW_FORM_data8:
2002 case dwarf::DW_FORM_udata:
2003 case dwarf::DW_FORM_sdata:
2004 case dwarf::DW_FORM_sec_offset:
2005 case dwarf::DW_FORM_flag:
2006 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002007 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2008 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002009 default:
2010 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2011 &InputDIE);
2012 }
2013
2014 return 0;
2015}
2016
Frederic Riss23e20e92015-03-07 01:25:09 +00002017/// \brief Apply the valid relocations found by findValidRelocs() to
2018/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2019/// in the debug_info section.
2020///
2021/// Like for findValidRelocs(), this function must be called with
2022/// monotonic \p BaseOffset values.
2023///
2024/// \returns wether any reloc has been applied.
2025bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2026 uint32_t BaseOffset, bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002027 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002028 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2029 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002030 if (NextValidReloc >= ValidRelocs.size())
2031 return false;
2032
2033 // Skip relocs that haven't been applied.
2034 while (NextValidReloc < ValidRelocs.size() &&
2035 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2036 ++NextValidReloc;
2037
2038 bool Applied = false;
2039 uint64_t EndOffset = BaseOffset + Data.size();
2040 while (NextValidReloc < ValidRelocs.size() &&
2041 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2042 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2043 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2044 assert(ValidReloc.Offset - BaseOffset < Data.size());
2045 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2046 char Buf[8];
2047 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2048 Value += ValidReloc.Addend;
2049 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2050 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2051 Buf[i] = uint8_t(Value >> (Index * 8));
2052 }
2053 assert(ValidReloc.Size <= sizeof(Buf));
2054 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2055 Applied = true;
2056 }
2057
2058 return Applied;
2059}
2060
Frederic Rissbce93ff2015-03-16 02:05:10 +00002061static bool isTypeTag(uint16_t Tag) {
2062 switch (Tag) {
2063 case dwarf::DW_TAG_array_type:
2064 case dwarf::DW_TAG_class_type:
2065 case dwarf::DW_TAG_enumeration_type:
2066 case dwarf::DW_TAG_pointer_type:
2067 case dwarf::DW_TAG_reference_type:
2068 case dwarf::DW_TAG_string_type:
2069 case dwarf::DW_TAG_structure_type:
2070 case dwarf::DW_TAG_subroutine_type:
2071 case dwarf::DW_TAG_typedef:
2072 case dwarf::DW_TAG_union_type:
2073 case dwarf::DW_TAG_ptr_to_member_type:
2074 case dwarf::DW_TAG_set_type:
2075 case dwarf::DW_TAG_subrange_type:
2076 case dwarf::DW_TAG_base_type:
2077 case dwarf::DW_TAG_const_type:
2078 case dwarf::DW_TAG_constant:
2079 case dwarf::DW_TAG_file_type:
2080 case dwarf::DW_TAG_namelist:
2081 case dwarf::DW_TAG_packed_type:
2082 case dwarf::DW_TAG_volatile_type:
2083 case dwarf::DW_TAG_restrict_type:
2084 case dwarf::DW_TAG_interface_type:
2085 case dwarf::DW_TAG_unspecified_type:
2086 case dwarf::DW_TAG_shared_type:
2087 return true;
2088 default:
2089 break;
2090 }
2091 return false;
2092}
2093
Frederic Rissb8b43d52015-03-04 22:07:44 +00002094/// \brief Recursively clone \p InputDIE's subtrees that have been
2095/// selected to appear in the linked output.
2096///
2097/// \param OutOffset is the Offset where the newly created DIE will
2098/// lie in the linked compile unit.
2099///
2100/// \returns the cloned DIE object or null if nothing was selected.
2101DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss31da3242015-03-11 18:45:52 +00002102 CompileUnit &Unit, int64_t PCOffset,
2103 uint32_t OutOffset) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002104 DWARFUnit &U = Unit.getOrigUnit();
2105 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002106 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002107
2108 // Should the DIE appear in the output?
2109 if (!Unit.getInfo(Idx).Keep)
2110 return nullptr;
2111
2112 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002113 // The DIE might have been already created by a forward reference
2114 // (see cloneDieReferenceAttribute()).
2115 DIE *Die = Info.Clone;
2116 if (!Die)
2117 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
2118 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002119 Die->setOffset(OutOffset);
2120
2121 // Extract and clone every attribute.
2122 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00002123 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002124 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002125
2126 // We could copy the data only if we need to aply a relocation to
2127 // it. After testing, it seems there is no performance downside to
2128 // doing the copy unconditionally, and it makes the code simpler.
2129 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2130 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2131 // Modify the copy with relocated addresses.
Frederic Riss31da3242015-03-11 18:45:52 +00002132 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2133 // If we applied relocations, we store the value of high_pc that was
2134 // potentially stored in the input DIE. If high_pc is an address
2135 // (Dwarf version == 2), then it might have been relocated to a
2136 // totally unrelated value (because the end address in the object
2137 // file might be start address of another function which got moved
2138 // independantly by the linker). The computation of the actual
2139 // high_pc value is done in cloneAddressAttribute().
2140 AttrInfo.OrigHighPc =
2141 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2142 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002143
2144 // Reset the Offset to 0 as we will be working on the local copy of
2145 // the data.
2146 Offset = 0;
2147
Frederic Rissb8b43d52015-03-04 22:07:44 +00002148 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2149 Offset += getULEB128Size(Abbrev->getCode());
2150
Frederic Riss31da3242015-03-11 18:45:52 +00002151 // We are entering a subprogram. Get and propagate the PCOffset.
2152 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2153 PCOffset = Info.AddrAdjust;
2154 AttrInfo.PCOffset = PCOffset;
2155
Frederic Rissb8b43d52015-03-04 22:07:44 +00002156 for (const auto &AttrSpec : Abbrev->attributes()) {
2157 DWARFFormValue Val(AttrSpec.Form);
2158 uint32_t AttrSize = Offset;
2159 Val.extractValue(Data, &Offset, &U);
2160 AttrSize = Offset - AttrSize;
2161
Frederic Riss31da3242015-03-11 18:45:52 +00002162 OutOffset +=
2163 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002164 }
2165
Frederic Rissbce93ff2015-03-16 02:05:10 +00002166 // Look for accelerator entries.
2167 uint16_t Tag = InputDIE.getTag();
2168 // FIXME: This is slightly wrong. An inline_subroutine without a
2169 // low_pc, but with AT_ranges might be interesting to get into the
2170 // accelerator tables too. For now stick with dsymutil's behavior.
2171 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2172 Tag != dwarf::DW_TAG_compile_unit &&
2173 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2174 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2175 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2176 AttrInfo.MangledNameOffset,
2177 Tag == dwarf::DW_TAG_inlined_subroutine);
2178 if (AttrInfo.Name)
2179 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2180 Tag == dwarf::DW_TAG_inlined_subroutine);
2181 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2182 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2183 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2184 }
2185
Frederic Rissb8b43d52015-03-04 22:07:44 +00002186 DIEAbbrev &NewAbbrev = Die->getAbbrev();
2187 // If a scope DIE is kept, we must have kept at least one child. If
2188 // it's not the case, we'll just be emitting one wasteful end of
2189 // children marker, but things won't break.
2190 if (InputDIE.hasChildren())
2191 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2192 // Assign a permanent abbrev number
2193 AssignAbbrev(Die->getAbbrev());
2194
2195 // Add the size of the abbreviation number to the output offset.
2196 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2197
2198 if (!Abbrev->hasChildren()) {
2199 // Update our size.
2200 Die->setSize(OutOffset - Die->getOffset());
2201 return Die;
2202 }
2203
2204 // Recursively clone children.
2205 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2206 Child = Child->getSibling()) {
Frederic Riss31da3242015-03-11 18:45:52 +00002207 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002208 Die->addChild(std::unique_ptr<DIE>(Clone));
2209 OutOffset = Clone->getOffset() + Clone->getSize();
2210 }
2211 }
2212
2213 // Account for the end of children marker.
2214 OutOffset += sizeof(int8_t);
2215 // Update our size.
2216 Die->setSize(OutOffset - Die->getOffset());
2217 return Die;
2218}
2219
Frederic Riss25440872015-03-13 23:30:31 +00002220/// \brief Patch the input object file relevant debug_ranges entries
2221/// and emit them in the output file. Update the relevant attributes
2222/// to point at the new entries.
2223void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2224 DWARFContext &OrigDwarf) const {
2225 DWARFDebugRangeList RangeList;
2226 const auto &FunctionRanges = Unit.getFunctionRanges();
2227 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2228 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2229 OrigDwarf.isLittleEndian(), AddressSize);
2230 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2231 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002232 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002233 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2234 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2235 // Ranges addresses are based on the unit's low_pc. Compute the
2236 // offset we need to apply to adapt to the the new unit's low_pc.
2237 int64_t UnitPcOffset = 0;
2238 if (OrigLowPc != -1ULL)
2239 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2240
2241 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002242 uint32_t Offset = RangeAttribute.get();
2243 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002244 RangeList.extract(RangeExtractor, &Offset);
2245 const auto &Entries = RangeList.getEntries();
2246 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2247
2248 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2249 First.StartAddress >= CurrRange.stop()) {
2250 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2251 if (CurrRange == InvalidRange ||
2252 CurrRange.start() > First.StartAddress + OrigLowPc) {
2253 reportWarning("no mapping for range.");
2254 continue;
2255 }
2256 }
2257
2258 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2259 AddressSize);
2260 }
2261}
2262
Frederic Riss563b1b02015-03-14 03:46:51 +00002263/// \brief Generate the debug_aranges entries for \p Unit and if the
2264/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2265/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002266/// FIXME: this could actually be done right in patchRangesForUnit,
2267/// but for the sake of initial bit-for-bit compatibility with legacy
2268/// dsymutil, we have to do it in a delayed pass.
2269void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002270 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002271 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002272 Attr->set(Streamer->getRangesSectionSize());
2273 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002274}
2275
Frederic Riss63786b02015-03-15 20:45:43 +00002276/// \brief Insert the new line info sequence \p Seq into the current
2277/// set of already linked line info \p Rows.
2278static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2279 std::vector<DWARFDebugLine::Row> &Rows) {
2280 if (Seq.empty())
2281 return;
2282
2283 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2284 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2285 Seq.clear();
2286 return;
2287 }
2288
2289 auto InsertPoint = std::lower_bound(
2290 Rows.begin(), Rows.end(), Seq.front(),
2291 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2292 return LHS.Address < RHS.Address;
2293 });
2294
2295 // FIXME: this only removes the unneeded end_sequence if the
2296 // sequences have been inserted in order. using a global sort like
2297 // described in patchLineTableForUnit() and delaying the end_sequene
2298 // elimination to emitLineTableForUnit() we can get rid of all of them.
2299 if (InsertPoint != Rows.end() &&
2300 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2301 *InsertPoint = Seq.front();
2302 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2303 } else {
2304 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2305 }
2306
2307 Seq.clear();
2308}
2309
2310/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2311/// recreate a relocated version of these for the address ranges that
2312/// are present in the binary.
2313void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2314 DWARFContext &OrigDwarf) {
2315 const DWARFDebugInfoEntryMinimal *CUDie =
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002316 Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002317 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2318 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2319 if (StmtList == -1ULL)
2320 return;
2321
2322 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2323 if (auto *OutputDIE = Unit.getOutputUnitDIE()) {
2324 const auto &Abbrev = OutputDIE->getAbbrev().getData();
2325 auto Stmt = std::find_if(
2326 Abbrev.begin(), Abbrev.end(), [](const DIEAbbrevData &AbbrevData) {
2327 return AbbrevData.getAttribute() == dwarf::DW_AT_stmt_list;
2328 });
2329 assert(Stmt < Abbrev.end() && "Didn't find DW_AT_stmt_list in cloned DIE!");
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002330 OutputDIE->setValue(Stmt - Abbrev.begin(),
2331 DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002332 }
2333
2334 // Parse the original line info for the unit.
2335 DWARFDebugLine::LineTable LineTable;
2336 uint32_t StmtOffset = StmtList;
2337 StringRef LineData = OrigDwarf.getLineSection().Data;
2338 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2339 Unit.getOrigUnit().getAddressByteSize());
2340 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2341 &StmtOffset);
2342
2343 // This vector is the output line table.
2344 std::vector<DWARFDebugLine::Row> NewRows;
2345 NewRows.reserve(LineTable.Rows.size());
2346
2347 // Current sequence of rows being extracted, before being inserted
2348 // in NewRows.
2349 std::vector<DWARFDebugLine::Row> Seq;
2350 const auto &FunctionRanges = Unit.getFunctionRanges();
2351 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2352
2353 // FIXME: This logic is meant to generate exactly the same output as
2354 // Darwin's classic dsynutil. There is a nicer way to implement this
2355 // by simply putting all the relocated line info in NewRows and simply
2356 // sorting NewRows before passing it to emitLineTableForUnit. This
2357 // should be correct as sequences for a function should stay
2358 // together in the sorted output. There are a few corner cases that
2359 // look suspicious though, and that required to implement the logic
2360 // this way. Revisit that once initial validation is finished.
2361
2362 // Iterate over the object file line info and extract the sequences
2363 // that correspond to linked functions.
2364 for (auto &Row : LineTable.Rows) {
2365 // Check wether we stepped out of the range. The range is
2366 // half-open, but consider accept the end address of the range if
2367 // it is marked as end_sequence in the input (because in that
2368 // case, the relocation offset is accurate and that entry won't
2369 // serve as the start of another function).
2370 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2371 Row.Address > CurrRange.stop() ||
2372 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2373 // We just stepped out of a known range. Insert a end_sequence
2374 // corresponding to the end of the range.
2375 uint64_t StopAddress = CurrRange != InvalidRange
2376 ? CurrRange.stop() + CurrRange.value()
2377 : -1ULL;
2378 CurrRange = FunctionRanges.find(Row.Address);
2379 bool CurrRangeValid =
2380 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2381 if (!CurrRangeValid) {
2382 CurrRange = InvalidRange;
2383 if (StopAddress != -1ULL) {
2384 // Try harder by looking in the DebugMapObject function
2385 // ranges map. There are corner cases where this finds a
2386 // valid entry. It's unclear if this is right or wrong, but
2387 // for now do as dsymutil.
2388 // FIXME: Understand exactly what cases this addresses and
2389 // potentially remove it along with the Ranges map.
2390 auto Range = Ranges.lower_bound(Row.Address);
2391 if (Range != Ranges.begin() && Range != Ranges.end())
2392 --Range;
2393
2394 if (Range != Ranges.end() && Range->first <= Row.Address &&
2395 Range->second.first >= Row.Address) {
2396 StopAddress = Row.Address + Range->second.second;
2397 }
2398 }
2399 }
2400 if (StopAddress != -1ULL && !Seq.empty()) {
2401 // Insert end sequence row with the computed end address, but
2402 // the same line as the previous one.
2403 Seq.emplace_back(Seq.back());
2404 Seq.back().Address = StopAddress;
2405 Seq.back().EndSequence = 1;
2406 Seq.back().PrologueEnd = 0;
2407 Seq.back().BasicBlock = 0;
2408 Seq.back().EpilogueBegin = 0;
2409 insertLineSequence(Seq, NewRows);
2410 }
2411
2412 if (!CurrRangeValid)
2413 continue;
2414 }
2415
2416 // Ignore empty sequences.
2417 if (Row.EndSequence && Seq.empty())
2418 continue;
2419
2420 // Relocate row address and add it to the current sequence.
2421 Row.Address += CurrRange.value();
2422 Seq.emplace_back(Row);
2423
2424 if (Row.EndSequence)
2425 insertLineSequence(Seq, NewRows);
2426 }
2427
2428 // Finished extracting, now emit the line tables.
2429 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2430 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2431 // prologue over and that works because we act as both producer and
2432 // consumer. It would be nicer to have a real configurable line
2433 // table emitter.
2434 if (LineTable.Prologue.Version != 2 ||
2435 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2436 LineTable.Prologue.LineBase != -5 || LineTable.Prologue.LineRange != 14 ||
2437 LineTable.Prologue.OpcodeBase != 13)
2438 reportWarning("line table paramters mismatch. Cannot emit.");
2439 else
2440 Streamer->emitLineTableForUnit(LineData.slice(StmtList + 4, PrologueEnd),
2441 LineTable.Prologue.MinInstLength, NewRows,
2442 Unit.getOrigUnit().getAddressByteSize());
2443}
2444
Frederic Rissbce93ff2015-03-16 02:05:10 +00002445void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2446 Streamer->emitPubNamesForUnit(Unit);
2447 Streamer->emitPubTypesForUnit(Unit);
2448}
2449
Frederic Rissd3455182015-01-28 18:27:01 +00002450bool DwarfLinker::link(const DebugMap &Map) {
2451
2452 if (Map.begin() == Map.end()) {
2453 errs() << "Empty debug map.\n";
2454 return false;
2455 }
2456
Frederic Rissc99ea202015-02-28 00:29:11 +00002457 if (!createStreamer(Map.getTriple(), OutputFilename))
2458 return false;
2459
Frederic Rissb8b43d52015-03-04 22:07:44 +00002460 // Size of the DIEs (and headers) generated for the linked output.
2461 uint64_t OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00002462 // A unique ID that identifies each compile unit.
2463 unsigned UnitID = 0;
Frederic Rissd3455182015-01-28 18:27:01 +00002464 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002465 CurrentDebugObject = Obj.get();
2466
Frederic Rissb9818322015-02-28 00:29:07 +00002467 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00002468 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
2469 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
2470 if (std::error_code EC = ErrOrObj.getError()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002471 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
Frederic Rissd3455182015-01-28 18:27:01 +00002472 continue;
2473 }
2474
Frederic Riss1036e642015-02-13 23:18:22 +00002475 // Look for relocations that correspond to debug map entries.
2476 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00002477 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00002478 outs() << "No valid relocations found. Skipping.\n";
2479 continue;
2480 }
2481
Frederic Riss563cba62015-01-28 22:15:14 +00002482 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00002483 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00002484 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00002485
Frederic Riss563cba62015-01-28 22:15:14 +00002486 // In a first phase, just read in the debug info and store the DIE
2487 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00002488 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002489 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00002490 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00002491 outs() << "Input compilation unit:";
2492 CUDie->dump(outs(), CU.get(), 0);
2493 }
Frederic Riss3cced052015-03-14 03:46:40 +00002494 Units.emplace_back(*CU, UnitID++);
Frederic Riss9aa725b2015-02-13 23:18:31 +00002495 gatherDIEParents(CUDie, 0, Units.back());
Frederic Rissd3455182015-01-28 18:27:01 +00002496 }
Frederic Riss563cba62015-01-28 22:15:14 +00002497
Frederic Riss84c09a52015-02-13 23:18:34 +00002498 // Then mark all the DIEs that need to be present in the linked
2499 // output and collect some information about them. Note that this
2500 // loop can not be merged with the previous one becaue cross-cu
2501 // references require the ParentIdx to be setup for every CU in
2502 // the object file before calling this.
2503 for (auto &CurrentUnit : Units)
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002504 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00002505 CurrentUnit, 0);
2506
Frederic Riss23e20e92015-03-07 01:25:09 +00002507 // The calls to applyValidRelocs inside cloneDIE will walk the
2508 // reloc array again (in the same way findValidRelocsInDebugInfo()
2509 // did). We need to reset the NextValidReloc index to the beginning.
2510 NextValidReloc = 0;
2511
Frederic Rissb8b43d52015-03-04 22:07:44 +00002512 // Construct the output DIE tree by cloning the DIEs we chose to
2513 // keep above. If there are no valid relocs, then there's nothing
2514 // to clone/emit.
2515 if (!ValidRelocs.empty())
2516 for (auto &CurrentUnit : Units) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002517 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00002518 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Riss31da3242015-03-11 18:45:52 +00002519 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
2520 11 /* Unit Header size */);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002521 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00002522 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Riss63786b02015-03-15 20:45:43 +00002523 if (Options.NoOutput)
2524 continue;
2525 // FIXME: for compatibility with the classic dsymutil, we emit
2526 // an empty line table for the unit, even if the unit doesn't
2527 // actually exist in the DIE tree.
2528 patchLineTableForUnit(CurrentUnit, DwarfContext);
2529 if (!OutputDIE)
Frederic Riss25440872015-03-13 23:30:31 +00002530 continue;
2531 patchRangesForUnit(CurrentUnit, DwarfContext);
Frederic Rissdfb97902015-03-14 15:49:07 +00002532 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002533 emitAcceleratorEntriesForUnit(CurrentUnit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002534 }
2535
2536 // Emit all the compile unit's debug information.
2537 if (!ValidRelocs.empty() && !Options.NoOutput)
2538 for (auto &CurrentUnit : Units) {
Frederic Riss25440872015-03-13 23:30:31 +00002539 generateUnitRanges(CurrentUnit);
Frederic Riss9833de62015-03-06 23:22:53 +00002540 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002541 Streamer->emitCompileUnitHeader(CurrentUnit);
2542 if (!CurrentUnit.getOutputUnitDIE())
2543 continue;
2544 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
2545 }
2546
Frederic Riss563cba62015-01-28 22:15:14 +00002547 // Clean-up before starting working on the next object.
2548 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00002549 }
2550
Frederic Rissb8b43d52015-03-04 22:07:44 +00002551 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00002552 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002553 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00002554 Streamer->emitStrings(StringPool);
2555 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002556
Frederic Rissc99ea202015-02-28 00:29:11 +00002557 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00002558}
2559}
Frederic Rissd3455182015-01-28 18:27:01 +00002560
Frederic Rissb9818322015-02-28 00:29:07 +00002561bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
2562 const LinkOptions &Options) {
2563 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00002564 return Linker.link(DM);
2565}
2566}
Frederic Riss231f7142014-12-12 17:31:24 +00002567}