blob: 62f177008f08fcdf8e041c65b7569695510545f5 [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) {}
Duncan P. N. Exon Smith88a8fc52015-05-27 22:44:06 +000071 PatchLocation(DIE &Die)
72 : Die(&Die), Index(std::distance(Die.begin_values(), Die.end_values())) {}
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000073
74 void set(uint64_t New) const {
75 assert(Die);
Duncan P. N. Exon Smith88a8fc52015-05-27 22:44:06 +000076 assert(Index < std::distance(Die->begin_values(), Die->end_values()));
77 const auto &Old = Die->begin_values()[Index];
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +000078 assert(Old.getType() == DIEValue::isInteger);
79 Die->setValue(Index,
80 DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New)));
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000081 }
82
83 uint64_t get() const {
84 assert(Die);
Duncan P. N. Exon Smith88a8fc52015-05-27 22:44:06 +000085 assert(Index < std::distance(Die->begin_values(), Die->end_values()));
86 assert(Die->begin_values()[Index].getType() == DIEValue::isInteger);
87 return Die->begin_values()[Index].getDIEInteger().getValue();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000088 }
89};
90
Frederic Riss563cba62015-01-28 22:15:14 +000091/// \brief Stores all information relating to a compile unit, be it in
92/// its original instance in the object file to its brand new cloned
93/// and linked DIE tree.
94class CompileUnit {
95public:
96 /// \brief Information gathered about a DIE in the object file.
97 struct DIEInfo {
Frederic Riss31da3242015-03-11 18:45:52 +000098 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
Frederic Riss9833de62015-03-06 23:22:53 +000099 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +0000100 uint32_t ParentIdx; ///< The index of this DIE's parent.
101 bool Keep; ///< Is the DIE part of the linked output?
102 bool InDebugMap; ///< Was this DIE's entity found in the map?
Frederic Riss563cba62015-01-28 22:15:14 +0000103 };
104
Frederic Riss3cced052015-03-14 03:46:40 +0000105 CompileUnit(DWARFUnit &OrigUnit, unsigned ID)
106 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000107 Ranges(RangeAlloc) {
Frederic Riss563cba62015-01-28 22:15:14 +0000108 Info.resize(OrigUnit.getNumDIEs());
109 }
110
Frederic Riss2838f9e2015-03-05 05:29:05 +0000111 CompileUnit(CompileUnit &&RHS)
112 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
113 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
Frederic Riss1af75f72015-03-12 18:45:10 +0000114 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
115 // The CompileUnit container has been 'reserve()'d with the right
116 // size. We cannot move the IntervalMap anyway.
117 llvm_unreachable("CompileUnits should not be moved.");
118 }
David Blaikiea8adc132015-03-04 22:20:52 +0000119
Frederic Rissc3349d42015-02-13 23:18:27 +0000120 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +0000121
Frederic Riss3cced052015-03-14 03:46:40 +0000122 unsigned getUniqueID() const { return ID; }
123
Frederic Rissb8b43d52015-03-04 22:07:44 +0000124 DIE *getOutputUnitDIE() const { return CUDie.get(); }
125 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
126
Frederic Riss563cba62015-01-28 22:15:14 +0000127 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
128 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
129
Frederic Rissb8b43d52015-03-04 22:07:44 +0000130 uint64_t getStartOffset() const { return StartOffset; }
131 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000132 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000133
Frederic Riss5a62dc32015-03-13 18:35:54 +0000134 uint64_t getLowPc() const { return LowPc; }
135 uint64_t getHighPc() const { return HighPc; }
136
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000137 Optional<PatchLocation> getUnitRangesAttribute() const {
138 return UnitRangeAttribute;
139 }
Frederic Riss25440872015-03-13 23:30:31 +0000140 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000141 const std::vector<PatchLocation> &getRangesAttributes() const {
Frederic Riss25440872015-03-13 23:30:31 +0000142 return RangeAttributes;
143 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000144
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000145 const std::vector<std::pair<PatchLocation, int64_t>> &
Frederic Rissdfb97902015-03-14 15:49:07 +0000146 getLocationAttributes() const {
147 return LocationAttributes;
148 }
149
Frederic Riss9d441b62015-03-06 23:22:50 +0000150 /// \brief Compute the end offset for this unit. Must be
151 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000152 /// \returns the next unit offset (which is also the current
153 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000154 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000155
Frederic Riss6afcfce2015-03-13 18:35:57 +0000156 /// \brief Keep track of a forward reference to DIE \p Die in \p
157 /// RefUnit by \p Attr. The attribute should be fixed up later to
158 /// point to the absolute offset of \p Die in the debug_info section.
159 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000160 PatchLocation Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000161
162 /// \brief Apply all fixups recored by noteForwardReference().
163 void fixupForwardReferences();
164
Frederic Riss1af75f72015-03-12 18:45:10 +0000165 /// \brief Add a function range [\p LowPC, \p HighPC) that is
166 /// relocatad by applying offset \p PCOffset.
167 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
168
Frederic Riss5c9c7062015-03-13 23:55:29 +0000169 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000170 /// patch up later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000171 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
Frederic Riss25440872015-03-13 23:30:31 +0000172
Frederic Rissdfb97902015-03-14 15:49:07 +0000173 /// \brief Keep track of a location attribute pointing to a location
174 /// list in the debug_loc section.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000175 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
Frederic Rissdfb97902015-03-14 15:49:07 +0000176
Frederic Rissbce93ff2015-03-16 02:05:10 +0000177 /// \brief Add a name accelerator entry for \p Die with \p Name
178 /// which is stored in the string table at \p Offset.
179 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
180 bool SkipPubnamesSection = false);
181
182 /// \brief Add a type accelerator entry for \p Die with \p Name
183 /// which is stored in the string table at \p Offset.
184 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
185
186 struct AccelInfo {
187 StringRef Name; ///< Name of the entry.
188 const DIE *Die; ///< DIE this entry describes.
189 uint32_t NameOffset; ///< Offset of Name in the string pool.
190 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
191
192 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
193 bool SkipPubSection = false)
194 : Name(Name), Die(Die), NameOffset(NameOffset),
195 SkipPubSection(SkipPubSection) {}
196 };
197
198 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
199 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
200
Frederic Riss563cba62015-01-28 22:15:14 +0000201private:
202 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000203 unsigned ID;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000204 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
205 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
206
207 uint64_t StartOffset;
208 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000209
Frederic Riss5a62dc32015-03-13 18:35:54 +0000210 uint64_t LowPc;
211 uint64_t HighPc;
212
Frederic Riss9833de62015-03-06 23:22:53 +0000213 /// \brief A list of attributes to fixup with the absolute offset of
214 /// a DIE in the debug_info section.
215 ///
216 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000217 /// cloning because for cross-cu forward refences the target DIE's
218 /// offset isn't known you emit the reference attribute.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000219 std::vector<std::tuple<DIE *, const CompileUnit *, PatchLocation>>
Frederic Riss6afcfce2015-03-13 18:35:57 +0000220 ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000221
Frederic Riss25440872015-03-13 23:30:31 +0000222 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000223 /// \brief The ranges in that interval map are the PC ranges for
224 /// functions in this unit, associated with the PC offset to apply
225 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000226 FunctionIntervals Ranges;
227
228 /// \brief DW_AT_ranges attributes to patch after we have gathered
229 /// all the unit's function addresses.
230 /// @{
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000231 std::vector<PatchLocation> RangeAttributes;
232 Optional<PatchLocation> UnitRangeAttribute;
Frederic Riss25440872015-03-13 23:30:31 +0000233 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000234
235 /// \brief Location attributes that need to be transfered from th
236 /// original debug_loc section to the liked one. They are stored
237 /// along with the PC offset that is to be applied to their
238 /// function's address.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000239 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
Frederic Rissbce93ff2015-03-16 02:05:10 +0000240
241 /// \brief Accelerator entries for the unit, both for the pub*
242 /// sections and the apple* ones.
243 /// @{
244 std::vector<AccelInfo> Pubnames;
245 std::vector<AccelInfo> Pubtypes;
246 /// @}
Frederic Riss563cba62015-01-28 22:15:14 +0000247};
248
Frederic Riss9d441b62015-03-06 23:22:50 +0000249uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000250 NextUnitOffset = StartOffset + 11 /* Header size */;
251 // The root DIE might be null, meaning that the Unit had nothing to
252 // contribute to the linked output. In that case, we will emit the
253 // unit header without any actual DIE.
254 if (CUDie)
255 NextUnitOffset += CUDie->getSize();
256 return NextUnitOffset;
257}
258
Frederic Riss6afcfce2015-03-13 18:35:57 +0000259/// \brief Keep track of a forward cross-cu reference from this unit
260/// to \p Die that lives in \p RefUnit.
261void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000262 PatchLocation Attr) {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000263 ForwardDIEReferences.emplace_back(Die, RefUnit, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000264}
265
266/// \brief Apply all fixups recorded by noteForwardReference().
267void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000268 for (const auto &Ref : ForwardDIEReferences) {
269 DIE *RefDie;
270 const CompileUnit *RefUnit;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000271 PatchLocation Attr;
Frederic Riss6afcfce2015-03-13 18:35:57 +0000272 std::tie(RefDie, RefUnit, Attr) = Ref;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000273 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
Frederic Riss6afcfce2015-03-13 18:35:57 +0000274 }
Frederic Riss9833de62015-03-06 23:22:53 +0000275}
276
Frederic Riss5a62dc32015-03-13 18:35:54 +0000277void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
278 int64_t PcOffset) {
279 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
280 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
281 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000282}
283
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000284void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
Frederic Riss25440872015-03-13 23:30:31 +0000285 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
286 RangeAttributes.push_back(Attr);
287 else
288 UnitRangeAttribute = Attr;
289}
290
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000291void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
Frederic Rissdfb97902015-03-14 15:49:07 +0000292 LocationAttributes.emplace_back(Attr, PcOffset);
293}
294
Frederic Rissbce93ff2015-03-16 02:05:10 +0000295/// \brief Add a name accelerator entry for \p Die with \p Name
296/// which is stored in the string table at \p Offset.
297void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
298 uint32_t Offset, bool SkipPubSection) {
299 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
300}
301
302/// \brief Add a type accelerator entry for \p Die with \p Name
303/// which is stored in the string table at \p Offset.
304void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
305 uint32_t Offset) {
306 Pubtypes.emplace_back(Name, Die, Offset, false);
307}
308
Frederic Rissef648462015-03-06 17:56:30 +0000309/// \brief A string table that doesn't need relocations.
310///
311/// We are doing a final link, no need for a string table that
312/// has relocation entries for every reference to it. This class
313/// provides this ablitity by just associating offsets with
314/// strings.
315class NonRelocatableStringpool {
316public:
317 /// \brief Entries are stored into the StringMap and simply linked
318 /// together through the second element of this pair in order to
319 /// keep track of insertion order.
320 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
321 MapTy;
322
323 NonRelocatableStringpool()
324 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
325 // Legacy dsymutil puts an empty string at the start of the line
326 // table.
327 getStringOffset("");
328 }
329
330 /// \brief Get the offset of string \p S in the string table. This
331 /// can insert a new element or return the offset of a preexisitng
332 /// one.
333 uint32_t getStringOffset(StringRef S);
334
335 /// \brief Get permanent storage for \p S (but do not necessarily
336 /// emit \p S in the output section).
337 /// \returns The StringRef that points to permanent storage to use
338 /// in place of \p S.
339 StringRef internString(StringRef S);
340
341 // \brief Return the first entry of the string table.
342 const MapTy::MapEntryTy *getFirstEntry() const {
343 return getNextEntry(&Sentinel);
344 }
345
346 // \brief Get the entry following \p E in the string table or null
347 // if \p E was the last entry.
348 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
349 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
350 }
351
352 uint64_t getSize() { return CurrentEndOffset; }
353
354private:
355 MapTy Strings;
356 uint32_t CurrentEndOffset;
357 MapTy::MapEntryTy Sentinel, *Last;
358};
359
360/// \brief Get the offset of string \p S in the string table. This
361/// can insert a new element or return the offset of a preexisitng
362/// one.
363uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
364 if (S.empty() && !Strings.empty())
365 return 0;
366
367 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
368 MapTy::iterator It;
369 bool Inserted;
370
371 // A non-empty string can't be at offset 0, so if we have an entry
372 // with a 0 offset, it must be a previously interned string.
373 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
374 if (Inserted || It->getValue().first == 0) {
375 // Set offset and chain at the end of the entries list.
376 It->getValue().first = CurrentEndOffset;
377 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
378 Last->getValue().second = &*It;
379 Last = &*It;
380 }
381 return It->getValue().first;
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000382}
Frederic Rissef648462015-03-06 17:56:30 +0000383
384/// \brief Put \p S into the StringMap so that it gets permanent
385/// storage, but do not actually link it in the chain of elements
386/// that go into the output section. A latter call to
387/// getStringOffset() with the same string will chain it though.
388StringRef NonRelocatableStringpool::internString(StringRef S) {
389 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
390 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
391 return InsertResult.first->getKey();
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000392}
Frederic Rissef648462015-03-06 17:56:30 +0000393
Frederic Rissc99ea202015-02-28 00:29:11 +0000394/// \brief The Dwarf streaming logic
395///
396/// All interactions with the MC layer that is used to build the debug
397/// information binary representation are handled in this class.
398class DwarfStreamer {
399 /// \defgroup MCObjects MC layer objects constructed by the streamer
400 /// @{
401 std::unique_ptr<MCRegisterInfo> MRI;
402 std::unique_ptr<MCAsmInfo> MAI;
403 std::unique_ptr<MCObjectFileInfo> MOFI;
404 std::unique_ptr<MCContext> MC;
405 MCAsmBackend *MAB; // Owned by MCStreamer
406 std::unique_ptr<MCInstrInfo> MII;
407 std::unique_ptr<MCSubtargetInfo> MSTI;
408 MCCodeEmitter *MCE; // Owned by MCStreamer
409 MCStreamer *MS; // Owned by AsmPrinter
410 std::unique_ptr<TargetMachine> TM;
411 std::unique_ptr<AsmPrinter> Asm;
412 /// @}
413
414 /// \brief the file we stream the linked Dwarf to.
415 std::unique_ptr<raw_fd_ostream> OutFile;
416
Frederic Riss25440872015-03-13 23:30:31 +0000417 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000418 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000419 uint32_t LineSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000420
Frederic Rissbce93ff2015-03-16 02:05:10 +0000421 /// \brief Emit the pubnames or pubtypes section contribution for \p
422 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000423 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000424 const CompileUnit &Unit,
425 const std::vector<CompileUnit::AccelInfo> &Names);
426
Frederic Rissc99ea202015-02-28 00:29:11 +0000427public:
428 /// \brief Actually create the streamer and the ouptut file.
429 ///
430 /// This could be done directly in the constructor, but it feels
431 /// more natural to handle errors through return value.
432 bool init(Triple TheTriple, StringRef OutputFilename);
433
Frederic Rissb8b43d52015-03-04 22:07:44 +0000434 /// \brief Dump the file to the disk.
Frederic Rissc99ea202015-02-28 00:29:11 +0000435 bool finish();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000436
437 AsmPrinter &getAsmPrinter() const { return *Asm; }
438
439 /// \brief Set the current output section to debug_info and change
440 /// the MC Dwarf version to \p DwarfVersion.
441 void switchToDebugInfoSection(unsigned DwarfVersion);
442
443 /// \brief Emit the compilation unit header for \p Unit in the
444 /// debug_info section.
445 ///
446 /// As a side effect, this also switches the current Dwarf version
447 /// of the MC layer to the one of U.getOrigUnit().
448 void emitCompileUnitHeader(CompileUnit &Unit);
449
450 /// \brief Recursively emit the DIE tree rooted at \p Die.
451 void emitDIE(DIE &Die);
452
453 /// \brief Emit the abbreviation table \p Abbrevs to the
454 /// debug_abbrev section.
455 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000456
457 /// \brief Emit the string table described by \p Pool.
458 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000459
460 /// \brief Emit debug_ranges for \p FuncRange by translating the
461 /// original \p Entries.
462 void emitRangesEntries(
463 int64_t UnitPcOffset, uint64_t OrigLowPc,
464 FunctionIntervals::const_iterator FuncRange,
465 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
466 unsigned AddressSize);
467
Frederic Riss563b1b02015-03-14 03:46:51 +0000468 /// \brief Emit debug_aranges entries for \p Unit and if \p
469 /// DoRangesSection is true, also emit the debug_ranges entries for
470 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
471 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000472
473 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000474
475 /// \brief Emit the debug_loc contribution for \p Unit by copying
476 /// the entries from \p Dwarf and offseting them. Update the
477 /// location attributes to point to the new entries.
478 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000479
480 /// \brief Emit the line table described in \p Rows into the
481 /// debug_line section.
482 void emitLineTableForUnit(StringRef PrologueBytes, unsigned MinInstLength,
483 std::vector<DWARFDebugLine::Row> &Rows,
484 unsigned AdddressSize);
485
486 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000487
488 /// \brief Emit the .debug_pubnames contribution for \p Unit.
489 void emitPubNamesForUnit(const CompileUnit &Unit);
490
491 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
492 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Rissc99ea202015-02-28 00:29:11 +0000493};
494
495bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
496 std::string ErrorStr;
497 std::string TripleName;
498 StringRef Context = "dwarf streamer init";
499
500 // Get the target.
501 const Target *TheTarget =
502 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
503 if (!TheTarget)
504 return error(ErrorStr, Context);
505 TripleName = TheTriple.getTriple();
506
507 // Create all the MC Objects.
508 MRI.reset(TheTarget->createMCRegInfo(TripleName));
509 if (!MRI)
510 return error(Twine("no register info for target ") + TripleName, Context);
511
512 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
513 if (!MAI)
514 return error("no asm info for target " + TripleName, Context);
515
516 MOFI.reset(new MCObjectFileInfo);
517 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
518 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
519 *MC);
520
521 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
522 if (!MAB)
523 return error("no asm backend for target " + TripleName, Context);
524
525 MII.reset(TheTarget->createMCInstrInfo());
526 if (!MII)
527 return error("no instr info info for target " + TripleName, Context);
528
529 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
530 if (!MSTI)
531 return error("no subtarget info for target " + TripleName, Context);
532
Eric Christopher0169e422015-03-10 22:03:14 +0000533 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000534 if (!MCE)
535 return error("no code emitter for target " + TripleName, Context);
536
537 // Create the output file.
538 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000539 OutFile =
540 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000541 if (EC)
542 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
543
Rafael Espindolaf696df12015-03-16 22:29:29 +0000544 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
Rafael Espindola36a15cb2015-03-20 20:00:01 +0000545 *MSTI, false,
546 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000547 if (!MS)
548 return error("no object streamer for target " + TripleName, Context);
549
550 // Finally create the AsmPrinter we'll use to emit the DIEs.
551 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
552 if (!TM)
553 return error("no target machine for target " + TripleName, Context);
554
555 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
556 if (!Asm)
557 return error("no asm printer for target " + TripleName, Context);
558
Frederic Riss25440872015-03-13 23:30:31 +0000559 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000560 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000561 LineSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000562
Frederic Rissc99ea202015-02-28 00:29:11 +0000563 return true;
564}
565
566bool DwarfStreamer::finish() {
567 MS->Finish();
568 return true;
569}
570
Frederic Rissb8b43d52015-03-04 22:07:44 +0000571/// \brief Set the current output section to debug_info and change
572/// the MC Dwarf version to \p DwarfVersion.
573void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
574 MS->SwitchSection(MOFI->getDwarfInfoSection());
575 MC->setDwarfVersion(DwarfVersion);
576}
577
578/// \brief Emit the compilation unit header for \p Unit in the
579/// debug_info section.
580///
581/// A Dwarf scetion header is encoded as:
582/// uint32_t Unit length (omiting this field)
583/// uint16_t Version
584/// uint32_t Abbreviation table offset
585/// uint8_t Address size
586///
587/// Leading to a total of 11 bytes.
588void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
589 unsigned Version = Unit.getOrigUnit().getVersion();
590 switchToDebugInfoSection(Version);
591
592 // Emit size of content not including length itself. The size has
593 // already been computed in CompileUnit::computeOffsets(). Substract
594 // 4 to that size to account for the length field.
595 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
596 Asm->EmitInt16(Version);
597 // We share one abbreviations table across all units so it's always at the
598 // start of the section.
599 Asm->EmitInt32(0);
600 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
601}
602
603/// \brief Emit the \p Abbrevs array as the shared abbreviation table
604/// for the linked Dwarf file.
605void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
606 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
607 Asm->emitDwarfAbbrevs(Abbrevs);
608}
609
610/// \brief Recursively emit the DIE tree rooted at \p Die.
611void DwarfStreamer::emitDIE(DIE &Die) {
612 MS->SwitchSection(MOFI->getDwarfInfoSection());
613 Asm->emitDwarfDIE(Die);
614}
615
Frederic Rissef648462015-03-06 17:56:30 +0000616/// \brief Emit the debug_str section stored in \p Pool.
617void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000618 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000619 for (auto *Entry = Pool.getFirstEntry(); Entry;
620 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000621 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000622 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
623}
624
Frederic Riss25440872015-03-13 23:30:31 +0000625/// \brief Emit the debug_range section contents for \p FuncRange by
626/// translating the original \p Entries. The debug_range section
627/// format is totally trivial, consisting just of pairs of address
628/// sized addresses describing the ranges.
629void DwarfStreamer::emitRangesEntries(
630 int64_t UnitPcOffset, uint64_t OrigLowPc,
631 FunctionIntervals::const_iterator FuncRange,
632 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
633 unsigned AddressSize) {
634 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
635
636 // Offset each range by the right amount.
637 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
638 for (const auto &Range : Entries) {
639 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
640 warn("unsupported base address selection operation",
641 "emitting debug_ranges");
642 break;
643 }
644 // Do not emit empty ranges.
645 if (Range.StartAddress == Range.EndAddress)
646 continue;
647
648 // All range entries should lie in the function range.
649 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
650 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
651 warn("inconsistent range data.", "emitting debug_ranges");
652 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
653 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
654 RangesSectionSize += 2 * AddressSize;
655 }
656
657 // Add the terminator entry.
658 MS->EmitIntValue(0, AddressSize);
659 MS->EmitIntValue(0, AddressSize);
660 RangesSectionSize += 2 * AddressSize;
661}
662
Frederic Riss563b1b02015-03-14 03:46:51 +0000663/// \brief Emit the debug_aranges contribution of a unit and
664/// if \p DoDebugRanges is true the debug_range contents for a
665/// compile_unit level DW_AT_ranges attribute (Which are basically the
666/// same thing with a different base address).
667/// Just aggregate all the ranges gathered inside that unit.
668void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
669 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000670 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
671 // Gather the ranges in a vector, so that we can simplify them. The
672 // IntervalMap will have coalesced the non-linked ranges, but here
673 // we want to coalesce the linked addresses.
674 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
675 const auto &FunctionRanges = Unit.getFunctionRanges();
676 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
677 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000678 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
679 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000680
681 // The object addresses where sorted, but again, the linked
682 // addresses might end up in a different order.
683 std::sort(Ranges.begin(), Ranges.end());
684
Frederic Riss563b1b02015-03-14 03:46:51 +0000685 if (!Ranges.empty()) {
686 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
687
Rafael Espindola9ab09232015-03-17 20:07:06 +0000688 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
689 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000690
691 unsigned HeaderSize =
692 sizeof(int32_t) + // Size of contents (w/o this field
693 sizeof(int16_t) + // DWARF ARange version number
694 sizeof(int32_t) + // Offset of CU in the .debug_info section
695 sizeof(int8_t) + // Pointer Size (in bytes)
696 sizeof(int8_t); // Segment Size (in bytes)
697
698 unsigned TupleSize = AddressSize * 2;
699 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
700
701 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000702 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000703 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
704 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
705 Asm->EmitInt8(AddressSize); // Address size
706 Asm->EmitInt8(0); // Segment size
707
Lang Hames9ff69c82015-04-24 19:11:51 +0000708 Asm->OutStreamer->EmitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000709
710 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
711 ++Range) {
712 uint64_t RangeStart = Range->first;
713 MS->EmitIntValue(RangeStart, AddressSize);
714 while ((Range + 1) != End && Range->second == (Range + 1)->first)
715 ++Range;
716 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
717 }
718
719 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000720 Asm->OutStreamer->EmitIntValue(0, AddressSize);
721 Asm->OutStreamer->EmitIntValue(0, AddressSize);
722 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000723 }
724
725 if (!DoDebugRanges)
726 return;
727
728 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
729 // Offset each range by the right amount.
730 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000731 // Emit coalesced ranges.
732 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000733 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000734 while (Range + 1 != End && Range->second == (Range + 1)->first)
735 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000736 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000737 RangesSectionSize += 2 * AddressSize;
738 }
739
740 // Add the terminator entry.
741 MS->EmitIntValue(0, AddressSize);
742 MS->EmitIntValue(0, AddressSize);
743 RangesSectionSize += 2 * AddressSize;
744}
745
Frederic Rissdfb97902015-03-14 15:49:07 +0000746/// \brief Emit location lists for \p Unit and update attribtues to
747/// point to the new entries.
748void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
749 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000750 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000751
752 if (Attributes.empty())
753 return;
754
755 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
756
757 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
758 const DWARFSection &InputSec = Dwarf.getLocSection();
759 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
760 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000761 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000762 int64_t UnitPcOffset = 0;
763 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
764 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
765 if (OrigLowPc != -1ULL)
766 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
767
768 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000769 uint32_t Offset = Attr.first.get();
770 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000771 // This is the quantity to add to the old location address to get
772 // the correct address for the new one.
773 int64_t LocPcOffset = Attr.second + UnitPcOffset;
774 while (Data.isValidOffset(Offset)) {
775 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
776 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
777 LocSectionSize += 2 * AddressSize;
778 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000779 Asm->OutStreamer->EmitIntValue(0, AddressSize);
780 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000781 break;
782 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000783 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
784 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000785 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000786 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000787 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000788 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000789 StringRef(InputSec.Data.substr(Offset, Length)));
790 Offset += Length;
791 LocSectionSize += Length + 2;
792 }
793 }
794}
795
Frederic Riss63786b02015-03-15 20:45:43 +0000796void DwarfStreamer::emitLineTableForUnit(StringRef PrologueBytes,
797 unsigned MinInstLength,
798 std::vector<DWARFDebugLine::Row> &Rows,
799 unsigned PointerSize) {
800 // Switch to the section where the table will be emitted into.
801 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000802 MCSymbol *LineStartSym = MC->createTempSymbol();
803 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000804
805 // The first 4 bytes is the total length of the information for this
806 // compilation unit (not including these 4 bytes for the length).
807 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000808 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000809 // Copy Prologue.
810 MS->EmitBytes(PrologueBytes);
811 LineSectionSize += PrologueBytes.size() + 4;
812
Frederic Rissc3820d02015-03-15 22:20:28 +0000813 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000814 raw_svector_ostream EncodingOS(EncodingBuffer);
815
816 if (Rows.empty()) {
817 // We only have the dummy entry, dsymutil emits an entry with a 0
818 // address in that case.
819 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
820 MS->EmitBytes(EncodingOS.str());
821 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000822 MS->EmitLabel(LineEndSym);
823 return;
824 }
825
826 // Line table state machine fields
827 unsigned FileNum = 1;
828 unsigned LastLine = 1;
829 unsigned Column = 0;
830 unsigned IsStatement = 1;
831 unsigned Isa = 0;
832 uint64_t Address = -1ULL;
833
834 unsigned RowsSinceLastSequence = 0;
835
836 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
837 auto &Row = Rows[Idx];
838
839 int64_t AddressDelta;
840 if (Address == -1ULL) {
841 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
842 MS->EmitULEB128IntValue(PointerSize + 1);
843 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
844 MS->EmitIntValue(Row.Address, PointerSize);
845 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
846 AddressDelta = 0;
847 } else {
848 AddressDelta = (Row.Address - Address) / MinInstLength;
849 }
850
851 // FIXME: code copied and transfromed from
852 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
853 // this code, but the current compatibility requirement with
854 // classic dsymutil makes it hard. Revisit that once this
855 // requirement is dropped.
856
857 if (FileNum != Row.File) {
858 FileNum = Row.File;
859 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
860 MS->EmitULEB128IntValue(FileNum);
861 LineSectionSize += 1 + getULEB128Size(FileNum);
862 }
863 if (Column != Row.Column) {
864 Column = Row.Column;
865 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
866 MS->EmitULEB128IntValue(Column);
867 LineSectionSize += 1 + getULEB128Size(Column);
868 }
869
870 // FIXME: We should handle the discriminator here, but dsymutil
871 // doesn' consider it, thus ignore it for now.
872
873 if (Isa != Row.Isa) {
874 Isa = Row.Isa;
875 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
876 MS->EmitULEB128IntValue(Isa);
877 LineSectionSize += 1 + getULEB128Size(Isa);
878 }
879 if (IsStatement != Row.IsStmt) {
880 IsStatement = Row.IsStmt;
881 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
882 LineSectionSize += 1;
883 }
884 if (Row.BasicBlock) {
885 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
886 LineSectionSize += 1;
887 }
888
889 if (Row.PrologueEnd) {
890 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
891 LineSectionSize += 1;
892 }
893
894 if (Row.EpilogueBegin) {
895 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
896 LineSectionSize += 1;
897 }
898
899 int64_t LineDelta = int64_t(Row.Line) - LastLine;
900 if (!Row.EndSequence) {
901 MCDwarfLineAddr::Encode(*MC, LineDelta, AddressDelta, EncodingOS);
902 MS->EmitBytes(EncodingOS.str());
903 LineSectionSize += EncodingBuffer.size();
904 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000905 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000906 Address = Row.Address;
907 LastLine = Row.Line;
908 RowsSinceLastSequence++;
909 } else {
910 if (LineDelta) {
911 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
912 MS->EmitSLEB128IntValue(LineDelta);
913 LineSectionSize += 1 + getSLEB128Size(LineDelta);
914 }
915 if (AddressDelta) {
916 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
917 MS->EmitULEB128IntValue(AddressDelta);
918 LineSectionSize += 1 + getULEB128Size(AddressDelta);
919 }
920 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
921 MS->EmitBytes(EncodingOS.str());
922 LineSectionSize += EncodingBuffer.size();
923 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000924 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000925 Address = -1ULL;
926 LastLine = FileNum = IsStatement = 1;
927 RowsSinceLastSequence = Column = Isa = 0;
928 }
929 }
930
931 if (RowsSinceLastSequence) {
932 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
933 MS->EmitBytes(EncodingOS.str());
934 LineSectionSize += EncodingBuffer.size();
935 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000936 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000937 }
938
939 MS->EmitLabel(LineEndSym);
940}
941
Frederic Rissbce93ff2015-03-16 02:05:10 +0000942/// \brief Emit the pubnames or pubtypes section contribution for \p
943/// Unit into \p Sec. The data is provided in \p Names.
944void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000945 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000946 const std::vector<CompileUnit::AccelInfo> &Names) {
947 if (Names.empty())
948 return;
949
950 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +0000951 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +0000952 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
953 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +0000954
955 bool HeaderEmitted = false;
956 // Emit the pubnames for this compilation unit.
957 for (const auto &Name : Names) {
958 if (Name.SkipPubSection)
959 continue;
960
961 if (!HeaderEmitted) {
962 // Emit the header.
963 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +0000964 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +0000965 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
966 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
967 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
968 HeaderEmitted = true;
969 }
970 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +0000971 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +0000972 StringRef(Name.Name.data(), Name.Name.size() + 1));
973 }
974
975 if (!HeaderEmitted)
976 return;
977 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +0000978 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +0000979}
980
981/// \brief Emit .debug_pubnames for \p Unit.
982void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
983 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
984 "names", Unit, Unit.getPubnames());
985}
986
987/// \brief Emit .debug_pubtypes for \p Unit.
988void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
989 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
990 "types", Unit, Unit.getPubtypes());
991}
992
Frederic Rissd3455182015-01-28 18:27:01 +0000993/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +0000994///
995/// The link of the dwarf information from the object files will be
996/// driven by the selection of 'root DIEs', which are DIEs that
997/// describe variables or functions that are present in the linked
998/// binary (and thus have entries in the debug map). All the debug
999/// information that will be linked (the DIEs, but also the line
1000/// tables, ranges, ...) is derived from that set of root DIEs.
1001///
1002/// The root DIEs are identified because they contain relocations that
1003/// correspond to a debug map entry at specific places (the low_pc for
1004/// a function, the location for a variable). These relocations are
1005/// called ValidRelocs in the DwarfLinker and are gathered as a very
1006/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001007class DwarfLinker {
1008public:
Frederic Rissb9818322015-02-28 00:29:07 +00001009 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1010 : OutputFilename(OutputFilename), Options(Options),
1011 BinHolder(Options.Verbose) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001012
Frederic Rissb8b43d52015-03-04 22:07:44 +00001013 ~DwarfLinker() {
1014 for (auto *Abbrev : Abbreviations)
1015 delete Abbrev;
1016 }
1017
Frederic Rissd3455182015-01-28 18:27:01 +00001018 /// \brief Link the contents of the DebugMap.
1019 bool link(const DebugMap &);
1020
1021private:
Frederic Riss563cba62015-01-28 22:15:14 +00001022 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001023 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001024
1025 /// \brief Called at the end of a debug object link.
1026 void endDebugObject();
1027
Frederic Riss1036e642015-02-13 23:18:22 +00001028 /// \defgroup FindValidRelocations Translate debug map into a list
1029 /// of relevant relocations
1030 ///
1031 /// @{
1032 struct ValidReloc {
1033 uint32_t Offset;
1034 uint32_t Size;
1035 uint64_t Addend;
1036 const DebugMapObject::DebugMapEntry *Mapping;
1037
1038 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1039 const DebugMapObject::DebugMapEntry *Mapping)
1040 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1041
1042 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1043 };
1044
1045 /// \brief The valid relocations for the current DebugMapObject.
1046 /// This vector is sorted by relocation offset.
1047 std::vector<ValidReloc> ValidRelocs;
1048
1049 /// \brief Index into ValidRelocs of the next relocation to
1050 /// consider. As we walk the DIEs in acsending file offset and as
1051 /// ValidRelocs is sorted by file offset, keeping this index
1052 /// uptodate is all we have to do to have a cheap lookup during the
Frederic Riss23e20e92015-03-07 01:25:09 +00001053 /// root DIE selection and during DIE cloning.
Frederic Riss1036e642015-02-13 23:18:22 +00001054 unsigned NextValidReloc;
1055
1056 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1057 const DebugMapObject &DMO);
1058
1059 bool findValidRelocs(const object::SectionRef &Section,
1060 const object::ObjectFile &Obj,
1061 const DebugMapObject &DMO);
1062
1063 void findValidRelocsMachO(const object::SectionRef &Section,
1064 const object::MachOObjectFile &Obj,
1065 const DebugMapObject &DMO);
1066 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +00001067
Frederic Riss84c09a52015-02-13 23:18:34 +00001068 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1069 ///
1070 /// @{
1071 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1072 /// keep. Store that information in \p CU's DIEInfo.
1073 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1074 const DebugMapObject &DMO, CompileUnit &CU,
1075 unsigned Flags);
1076
1077 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1078 enum TravesalFlags {
1079 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1080 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1081 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1082 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
1083 };
1084
1085 /// \brief Mark the passed DIE as well as all the ones it depends on
1086 /// as kept.
1087 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1088 CompileUnit::DIEInfo &MyInfo,
1089 const DebugMapObject &DMO, CompileUnit &CU,
1090 unsigned Flags);
1091
1092 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1093 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1094 unsigned Flags);
1095
1096 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1097 CompileUnit &Unit,
1098 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1099
1100 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1101 CompileUnit &Unit,
1102 CompileUnit::DIEInfo &MyInfo,
1103 unsigned Flags);
1104
1105 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1106 CompileUnit::DIEInfo &Info);
1107 /// @}
1108
Frederic Rissb8b43d52015-03-04 22:07:44 +00001109 /// \defgroup Linking Methods used to link the debug information
1110 ///
1111 /// @{
1112 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1113 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1114 /// stripped out and addresses have been rewritten according to the
1115 /// debug map.
1116 ///
1117 /// \param OutOffset is the offset the cloned DIE in the output
1118 /// compile unit.
Frederic Riss31da3242015-03-11 18:45:52 +00001119 /// \param PCOffset (while cloning a function scope) is the offset
1120 /// applied to the entry point of the function to get the linked address.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001121 ///
1122 /// \returns the root of the cloned tree.
1123 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Frederic Riss31da3242015-03-11 18:45:52 +00001124 int64_t PCOffset, uint32_t OutOffset);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001125
1126 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1127
Frederic Riss31da3242015-03-11 18:45:52 +00001128 /// \brief Information gathered and exchanged between the various
1129 /// clone*Attributes helpers about the attributes of a particular DIE.
1130 struct AttributesInfo {
Frederic Rissbce93ff2015-03-16 02:05:10 +00001131 const char *Name, *MangledName; ///< Names.
1132 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1133
Frederic Riss31da3242015-03-11 18:45:52 +00001134 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1135 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1136
Frederic Rissbce93ff2015-03-16 02:05:10 +00001137 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1138 bool IsDeclaration; ///< Is this DIE only a declaration?
1139
1140 AttributesInfo()
1141 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1142 MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1143 IsDeclaration(false) {}
Frederic Riss31da3242015-03-11 18:45:52 +00001144 };
1145
Frederic Rissb8b43d52015-03-04 22:07:44 +00001146 /// \brief Helper for cloneDIE.
1147 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1148 CompileUnit &U, const DWARFFormValue &Val,
Frederic Riss31da3242015-03-11 18:45:52 +00001149 const AttributeSpec AttrSpec, unsigned AttrSize,
1150 AttributesInfo &AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001151
1152 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +00001153 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1154 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001155
1156 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +00001157 unsigned
1158 cloneDieReferenceAttribute(DIE &Die,
1159 const DWARFDebugInfoEntryMinimal &InputDIE,
1160 AttributeSpec AttrSpec, unsigned AttrSize,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001161 const DWARFFormValue &Val, CompileUnit &Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001162
1163 /// \brief Helper for cloneDIE.
1164 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1165 const DWARFFormValue &Val, unsigned AttrSize);
1166
1167 /// \brief Helper for cloneDIE.
Frederic Riss31da3242015-03-11 18:45:52 +00001168 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1169 const DWARFFormValue &Val,
1170 const CompileUnit &Unit, AttributesInfo &Info);
1171
1172 /// \brief Helper for cloneDIE.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001173 unsigned cloneScalarAttribute(DIE &Die,
1174 const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss25440872015-03-13 23:30:31 +00001175 CompileUnit &U, AttributeSpec AttrSpec,
Frederic Rissdfb97902015-03-14 15:49:07 +00001176 const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001177 AttributesInfo &Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001178
Frederic Riss23e20e92015-03-07 01:25:09 +00001179 /// \brief Helper for cloneDIE.
1180 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1181 bool isLittleEndian);
1182
Frederic Rissb8b43d52015-03-04 22:07:44 +00001183 /// \brief Assign an abbreviation number to \p Abbrev
1184 void AssignAbbrev(DIEAbbrev &Abbrev);
1185
1186 /// \brief FoldingSet that uniques the abbreviations.
1187 FoldingSet<DIEAbbrev> AbbreviationsSet;
1188 /// \brief Storage for the unique Abbreviations.
1189 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1190 /// be changed to a vecot of unique_ptrs.
1191 std::vector<DIEAbbrev *> Abbreviations;
1192
Frederic Riss25440872015-03-13 23:30:31 +00001193 /// \brief Compute and emit debug_ranges section for \p Unit, and
1194 /// patch the attributes referencing it.
1195 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1196
1197 /// \brief Generate and emit the DW_AT_ranges attribute for a
1198 /// compile_unit if it had one.
1199 void generateUnitRanges(CompileUnit &Unit) const;
1200
Frederic Riss63786b02015-03-15 20:45:43 +00001201 /// \brief Extract the line tables fromt he original dwarf, extract
1202 /// the relevant parts according to the linked function ranges and
1203 /// emit the result in the debug_line section.
1204 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1205
Frederic Rissbce93ff2015-03-16 02:05:10 +00001206 /// \brief Emit the accelerator entries for \p Unit.
1207 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1208
Frederic Rissb8b43d52015-03-04 22:07:44 +00001209 /// \brief DIELoc objects that need to be destructed (but not freed!).
1210 std::vector<DIELoc *> DIELocs;
1211 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1212 std::vector<DIEBlock *> DIEBlocks;
1213 /// \brief Allocator used for all the DIEValue objects.
1214 BumpPtrAllocator DIEAlloc;
1215 /// @}
1216
Frederic Riss1b9da422015-02-13 23:18:29 +00001217 /// \defgroup Helpers Various helper methods.
1218 ///
1219 /// @{
1220 const DWARFDebugInfoEntryMinimal *
1221 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
1222 const DWARFDebugInfoEntryMinimal &DIE,
1223 CompileUnit *&ReferencedCU);
1224
1225 CompileUnit *getUnitForOffset(unsigned Offset);
1226
Frederic Rissbce93ff2015-03-16 02:05:10 +00001227 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1228 AttributesInfo &Info);
1229
Frederic Riss1b9da422015-02-13 23:18:29 +00001230 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
Frederic Riss25440872015-03-13 23:30:31 +00001231 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
Frederic Rissc99ea202015-02-28 00:29:11 +00001232
1233 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Riss1b9da422015-02-13 23:18:29 +00001234 /// @}
1235
Frederic Riss563cba62015-01-28 22:15:14 +00001236private:
Frederic Rissd3455182015-01-28 18:27:01 +00001237 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001238 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001239 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001240 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +00001241
1242 /// The units of the current debug map object.
1243 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001244
1245 /// The debug map object curently under consideration.
1246 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001247
1248 /// \brief The Dwarf string pool
1249 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001250
1251 /// \brief This map is keyed by the entry PC of functions in that
1252 /// debug object and the associated value is a pair storing the
1253 /// corresponding end PC and the offset to apply to get the linked
1254 /// address.
1255 ///
1256 /// See startDebugObject() for a more complete description of its use.
1257 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Rissd3455182015-01-28 18:27:01 +00001258};
1259
Frederic Riss1b9da422015-02-13 23:18:29 +00001260/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1261/// returning our CompileUnit object instead.
1262CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1263 auto CU =
1264 std::upper_bound(Units.begin(), Units.end(), Offset,
1265 [](uint32_t LHS, const CompileUnit &RHS) {
1266 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1267 });
1268 return CU != Units.end() ? &*CU : nullptr;
1269}
1270
1271/// \brief Resolve the DIE attribute reference that has been
1272/// extracted in \p RefValue. The resulting DIE migh be in another
1273/// CompileUnit which is stored into \p ReferencedCU.
1274/// \returns null if resolving fails for any reason.
1275const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1276 DWARFFormValue &RefValue, const DWARFUnit &Unit,
1277 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1278 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1279 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1280
1281 if ((RefCU = getUnitForOffset(RefOffset)))
1282 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1283 return RefDie;
1284
1285 reportWarning("could not find referenced DIE", &Unit, &DIE);
1286 return nullptr;
1287}
1288
Frederic Rissbce93ff2015-03-16 02:05:10 +00001289/// \brief Get the potential name and mangled name for the entity
1290/// described by \p Die and store them in \Info if they are not
1291/// already there.
1292/// \returns is a name was found.
1293bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1294 DWARFUnit &U, AttributesInfo &Info) {
1295 // FIXME: a bit wastefull as the first getName might return the
1296 // short name.
1297 if (!Info.MangledName &&
1298 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1299 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1300
1301 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1302 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1303
1304 return Info.Name || Info.MangledName;
1305}
1306
Frederic Riss1b9da422015-02-13 23:18:29 +00001307/// \brief Report a warning to the user, optionaly including
1308/// information about a specific \p DIE related to the warning.
1309void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001310 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001311 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001312 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001313 Context = CurrentDebugObject->getObjectFilename();
1314 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001315
Frederic Rissb9818322015-02-28 00:29:07 +00001316 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001317 return;
1318
1319 errs() << " in DIE:\n";
1320 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1321 6 /* Indent */);
1322}
1323
Frederic Rissc99ea202015-02-28 00:29:11 +00001324bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1325 if (Options.NoOutput)
1326 return true;
1327
Frederic Rissb52cf522015-02-28 00:42:37 +00001328 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001329 return Streamer->init(TheTriple, OutputFilename);
1330}
1331
Frederic Riss563cba62015-01-28 22:15:14 +00001332/// \brief Recursive helper to gather the child->parent relationships in the
1333/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +00001334static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1335 unsigned ParentIdx, CompileUnit &CU) {
Frederic Riss563cba62015-01-28 22:15:14 +00001336 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1337 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
1338
1339 if (DIE->hasChildren())
1340 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1341 Child = Child->getSibling())
Frederic Riss9aa725b2015-02-13 23:18:31 +00001342 gatherDIEParents(Child, MyIdx, CU);
Frederic Riss563cba62015-01-28 22:15:14 +00001343}
1344
Frederic Riss84c09a52015-02-13 23:18:34 +00001345static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1346 switch (Tag) {
1347 default:
1348 return false;
1349 case dwarf::DW_TAG_subprogram:
1350 case dwarf::DW_TAG_lexical_block:
1351 case dwarf::DW_TAG_subroutine_type:
1352 case dwarf::DW_TAG_structure_type:
1353 case dwarf::DW_TAG_class_type:
1354 case dwarf::DW_TAG_union_type:
1355 return true;
1356 }
1357 llvm_unreachable("Invalid Tag");
1358}
1359
Frederic Riss63786b02015-03-15 20:45:43 +00001360void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001361 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +00001362 NextValidReloc = 0;
Frederic Riss63786b02015-03-15 20:45:43 +00001363 // Iterate over the debug map entries and put all the ones that are
1364 // functions (because they have a size) into the Ranges map. This
1365 // map is very similar to the FunctionRanges that are stored in each
1366 // unit, with 2 notable differences:
1367 // - obviously this one is global, while the other ones are per-unit.
1368 // - this one contains not only the functions described in the DIE
1369 // tree, but also the ones that are only in the debug map.
1370 // The latter information is required to reproduce dsymutil's logic
1371 // while linking line tables. The cases where this information
1372 // matters look like bugs that need to be investigated, but for now
1373 // we need to reproduce dsymutil's behavior.
1374 // FIXME: Once we understood exactly if that information is needed,
1375 // maybe totally remove this (or try to use it to do a real
1376 // -gline-tables-only on Darwin.
1377 for (const auto &Entry : Obj.symbols()) {
1378 const auto &Mapping = Entry.getValue();
1379 if (Mapping.Size)
1380 Ranges[Mapping.ObjectAddress] = std::make_pair(
1381 Mapping.ObjectAddress + Mapping.Size,
1382 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1383 }
Frederic Riss563cba62015-01-28 22:15:14 +00001384}
1385
Frederic Riss1036e642015-02-13 23:18:22 +00001386void DwarfLinker::endDebugObject() {
1387 Units.clear();
1388 ValidRelocs.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001389 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001390
1391 for (auto *Block : DIEBlocks)
1392 Block->~DIEBlock();
1393 for (auto *Loc : DIELocs)
1394 Loc->~DIELoc();
1395
1396 DIEBlocks.clear();
1397 DIELocs.clear();
1398 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001399}
1400
1401/// \brief Iterate over the relocations of the given \p Section and
1402/// store the ones that correspond to debug map entries into the
1403/// ValidRelocs array.
1404void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1405 const object::MachOObjectFile &Obj,
1406 const DebugMapObject &DMO) {
1407 StringRef Contents;
1408 Section.getContents(Contents);
1409 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1410
1411 for (const object::RelocationRef &Reloc : Section.relocations()) {
1412 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1413 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1414 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1415 uint64_t Offset64;
1416 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001417 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001418 continue;
1419 }
1420 uint32_t Offset = Offset64;
1421 // Mach-o uses REL relocations, the addend is at the relocation offset.
1422 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1423
1424 auto Sym = Reloc.getSymbol();
1425 if (Sym != Obj.symbol_end()) {
1426 StringRef SymbolName;
1427 if (Sym->getName(SymbolName)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001428 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001429 continue;
1430 }
1431 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
1432 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1433 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1434 // Do not store the addend. The addend was the address of the
1435 // symbol in the object file, the address in the binary that is
1436 // stored in the debug map doesn't need to be offseted.
1437 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1438 }
1439 }
1440}
1441
1442/// \brief Dispatch the valid relocation finding logic to the
1443/// appropriate handler depending on the object file format.
1444bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1445 const object::ObjectFile &Obj,
1446 const DebugMapObject &DMO) {
1447 // Dispatch to the right handler depending on the file type.
1448 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1449 findValidRelocsMachO(Section, *MachOObj, DMO);
1450 else
Frederic Riss1b9da422015-02-13 23:18:29 +00001451 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001452
1453 if (ValidRelocs.empty())
1454 return false;
1455
1456 // Sort the relocations by offset. We will walk the DIEs linearly in
1457 // the file, this allows us to just keep an index in the relocation
1458 // array that we advance during our walk, rather than resorting to
1459 // some associative container. See DwarfLinker::NextValidReloc.
1460 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1461 return true;
1462}
1463
1464/// \brief Look for relocations in the debug_info section that match
1465/// entries in the debug map. These relocations will drive the Dwarf
1466/// link by indicating which DIEs refer to symbols present in the
1467/// linked binary.
1468/// \returns wether there are any valid relocations in the debug info.
1469bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1470 const DebugMapObject &DMO) {
1471 // Find the debug_info section.
1472 for (const object::SectionRef &Section : Obj.sections()) {
1473 StringRef SectionName;
1474 Section.getName(SectionName);
1475 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1476 if (SectionName != "debug_info")
1477 continue;
1478 return findValidRelocs(Section, Obj, DMO);
1479 }
1480 return false;
1481}
Frederic Riss563cba62015-01-28 22:15:14 +00001482
Frederic Riss84c09a52015-02-13 23:18:34 +00001483/// \brief Checks that there is a relocation against an actual debug
1484/// map entry between \p StartOffset and \p NextOffset.
1485///
1486/// This function must be called with offsets in strictly ascending
1487/// order because it never looks back at relocations it already 'went past'.
1488/// \returns true and sets Info.InDebugMap if it is the case.
1489bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1490 CompileUnit::DIEInfo &Info) {
1491 assert(NextValidReloc == 0 ||
1492 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1493 if (NextValidReloc >= ValidRelocs.size())
1494 return false;
1495
1496 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1497
1498 // We might need to skip some relocs that we didn't consider. For
1499 // example the high_pc of a discarded DIE might contain a reloc that
1500 // is in the list because it actually corresponds to the start of a
1501 // function that is in the debug map.
1502 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1503 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1504
1505 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1506 return false;
1507
1508 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Rissb9818322015-02-28 00:29:07 +00001509 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001510 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1511 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1512 ValidReloc.Mapping->getValue().ObjectAddress,
1513 ValidReloc.Mapping->getValue().BinaryAddress);
1514
Frederic Riss31da3242015-03-11 18:45:52 +00001515 Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
1516 ValidReloc.Addend -
1517 ValidReloc.Mapping->getValue().ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001518 Info.InDebugMap = true;
1519 return true;
1520}
1521
1522/// \brief Get the starting and ending (exclusive) offset for the
1523/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1524/// supposed to point to the position of the first attribute described
1525/// by \p Abbrev.
1526/// \return [StartOffset, EndOffset) as a pair.
1527static std::pair<uint32_t, uint32_t>
1528getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1529 unsigned Offset, const DWARFUnit &Unit) {
1530 DataExtractor Data = Unit.getDebugInfoExtractor();
1531
1532 for (unsigned i = 0; i < Idx; ++i)
1533 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1534
1535 uint32_t End = Offset;
1536 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1537
1538 return std::make_pair(Offset, End);
1539}
1540
1541/// \brief Check if a variable describing DIE should be kept.
1542/// \returns updated TraversalFlags.
1543unsigned DwarfLinker::shouldKeepVariableDIE(
1544 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1545 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1546 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1547
1548 // Global variables with constant value can always be kept.
1549 if (!(Flags & TF_InFunctionScope) &&
1550 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1551 MyInfo.InDebugMap = true;
1552 return Flags | TF_Keep;
1553 }
1554
1555 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1556 if (LocationIdx == -1U)
1557 return Flags;
1558
1559 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1560 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1561 uint32_t LocationOffset, LocationEndOffset;
1562 std::tie(LocationOffset, LocationEndOffset) =
1563 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1564
1565 // See if there is a relocation to a valid debug map entry inside
1566 // this variable's location. The order is important here. We want to
1567 // always check in the variable has a valid relocation, so that the
1568 // DIEInfo is filled. However, we don't want a static variable in a
1569 // function to force us to keep the enclosing function.
1570 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1571 (Flags & TF_InFunctionScope))
1572 return Flags;
1573
Frederic Rissb9818322015-02-28 00:29:07 +00001574 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001575 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1576
1577 return Flags | TF_Keep;
1578}
1579
1580/// \brief Check if a function describing DIE should be kept.
1581/// \returns updated TraversalFlags.
1582unsigned DwarfLinker::shouldKeepSubprogramDIE(
1583 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1584 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1585 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1586
1587 Flags |= TF_InFunctionScope;
1588
1589 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1590 if (LowPcIdx == -1U)
1591 return Flags;
1592
1593 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1594 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1595 uint32_t LowPcOffset, LowPcEndOffset;
1596 std::tie(LowPcOffset, LowPcEndOffset) =
1597 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1598
1599 uint64_t LowPc =
1600 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1601 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1602 if (LowPc == -1ULL ||
1603 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1604 return Flags;
1605
Frederic Rissb9818322015-02-28 00:29:07 +00001606 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001607 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1608
Frederic Riss1af75f72015-03-12 18:45:10 +00001609 Flags |= TF_Keep;
1610
1611 DWARFFormValue HighPcValue;
1612 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1613 reportWarning("Function without high_pc. Range will be discarded.\n",
1614 &OrigUnit, &DIE);
1615 return Flags;
1616 }
1617
1618 uint64_t HighPc;
1619 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1620 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1621 } else {
1622 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1623 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1624 }
1625
Frederic Riss63786b02015-03-15 20:45:43 +00001626 // Replace the debug map range with a more accurate one.
1627 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00001628 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1629 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00001630}
1631
1632/// \brief Check if a DIE should be kept.
1633/// \returns updated TraversalFlags.
1634unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1635 CompileUnit &Unit,
1636 CompileUnit::DIEInfo &MyInfo,
1637 unsigned Flags) {
1638 switch (DIE.getTag()) {
1639 case dwarf::DW_TAG_constant:
1640 case dwarf::DW_TAG_variable:
1641 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1642 case dwarf::DW_TAG_subprogram:
1643 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1644 case dwarf::DW_TAG_module:
1645 case dwarf::DW_TAG_imported_module:
1646 case dwarf::DW_TAG_imported_declaration:
1647 case dwarf::DW_TAG_imported_unit:
1648 // We always want to keep these.
1649 return Flags | TF_Keep;
1650 }
1651
1652 return Flags;
1653}
1654
Frederic Riss84c09a52015-02-13 23:18:34 +00001655/// \brief Mark the passed DIE as well as all the ones it depends on
1656/// as kept.
1657///
1658/// This function is called by lookForDIEsToKeep on DIEs that are
1659/// newly discovered to be needed in the link. It recursively calls
1660/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1661/// TraversalFlags to inform it that it's not doing the primary DIE
1662/// tree walk.
1663void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1664 CompileUnit::DIEInfo &MyInfo,
1665 const DebugMapObject &DMO,
1666 CompileUnit &CU, unsigned Flags) {
1667 const DWARFUnit &Unit = CU.getOrigUnit();
1668 MyInfo.Keep = true;
1669
1670 // First mark all the parent chain as kept.
1671 unsigned AncestorIdx = MyInfo.ParentIdx;
1672 while (!CU.getInfo(AncestorIdx).Keep) {
1673 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1674 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1675 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1676 }
1677
1678 // Then we need to mark all the DIEs referenced by this DIE's
1679 // attributes as kept.
1680 DataExtractor Data = Unit.getDebugInfoExtractor();
1681 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1682 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1683
1684 // Mark all DIEs referenced through atttributes as kept.
1685 for (const auto &AttrSpec : Abbrev->attributes()) {
1686 DWARFFormValue Val(AttrSpec.Form);
1687
1688 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1689 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1690 continue;
1691 }
1692
1693 Val.extractValue(Data, &Offset, &Unit);
1694 CompileUnit *ReferencedCU;
1695 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1696 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1697 TF_Keep | TF_DependencyWalk);
1698 }
1699}
1700
1701/// \brief Recursively walk the \p DIE tree and look for DIEs to
1702/// keep. Store that information in \p CU's DIEInfo.
1703///
1704/// This function is the entry point of the DIE selection
1705/// algorithm. It is expected to walk the DIE tree in file order and
1706/// (though the mediation of its helper) call hasValidRelocation() on
1707/// each DIE that might be a 'root DIE' (See DwarfLinker class
1708/// comment).
1709/// While walking the dependencies of root DIEs, this function is
1710/// also called, but during these dependency walks the file order is
1711/// not respected. The TF_DependencyWalk flag tells us which kind of
1712/// traversal we are currently doing.
1713void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1714 const DebugMapObject &DMO, CompileUnit &CU,
1715 unsigned Flags) {
1716 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1717 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1718 bool AlreadyKept = MyInfo.Keep;
1719
1720 // If the Keep flag is set, we are marking a required DIE's
1721 // dependencies. If our target is already marked as kept, we're all
1722 // set.
1723 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1724 return;
1725
1726 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1727 // because it would screw up the relocation finding logic.
1728 if (!(Flags & TF_DependencyWalk))
1729 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1730
1731 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1732 if (!AlreadyKept && (Flags & TF_Keep))
1733 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1734
1735 // The TF_ParentWalk flag tells us that we are currently walking up
1736 // the parent chain of a required DIE, and we don't want to mark all
1737 // the children of the parents as kept (consider for example a
1738 // DW_TAG_namespace node in the parent chain). There are however a
1739 // set of DIE types for which we want to ignore that directive and still
1740 // walk their children.
1741 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1742 Flags &= ~TF_ParentWalk;
1743
1744 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1745 return;
1746
1747 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1748 Child = Child->getSibling())
1749 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1750}
1751
Frederic Rissb8b43d52015-03-04 22:07:44 +00001752/// \brief Assign an abbreviation numer to \p Abbrev.
1753///
1754/// Our DIEs get freed after every DebugMapObject has been processed,
1755/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1756/// the instances hold by the DIEs. When we encounter an abbreviation
1757/// that we don't know, we create a permanent copy of it.
1758void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1759 // Check the set for priors.
1760 FoldingSetNodeID ID;
1761 Abbrev.Profile(ID);
1762 void *InsertToken;
1763 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1764
1765 // If it's newly added.
1766 if (InSet) {
1767 // Assign existing abbreviation number.
1768 Abbrev.setNumber(InSet->getNumber());
1769 } else {
1770 // Add to abbreviation list.
1771 Abbreviations.push_back(
1772 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1773 for (const auto &Attr : Abbrev.getData())
1774 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1775 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1776 // Assign the unique abbreviation number.
1777 Abbrev.setNumber(Abbreviations.size());
1778 Abbreviations.back()->setNumber(Abbreviations.size());
1779 }
1780}
1781
1782/// \brief Clone a string attribute described by \p AttrSpec and add
1783/// it to \p Die.
1784/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00001785unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1786 const DWARFFormValue &Val,
1787 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001788 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00001789 const char *String = *Val.getAsCString(&U);
1790 unsigned Offset = StringPool.getStringOffset(String);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001791 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001792 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001793 return 4;
1794}
1795
1796/// \brief Clone an attribute referencing another DIE and add
1797/// it to \p Die.
1798/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00001799unsigned DwarfLinker::cloneDieReferenceAttribute(
1800 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1801 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001802 CompileUnit &Unit) {
1803 uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
Frederic Riss9833de62015-03-06 23:22:53 +00001804 DIE *NewRefDie = nullptr;
1805 CompileUnit *RefUnit = nullptr;
1806 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1807
1808 if (!(RefUnit = getUnitForOffset(Ref)) ||
1809 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1810 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1811 if (!AttributeString)
1812 AttributeString = "DW_AT_???";
1813 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1814 ". Dropping.",
Frederic Riss6afcfce2015-03-13 18:35:57 +00001815 &Unit.getOrigUnit(), &InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00001816 return 0;
1817 }
1818
1819 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1820 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1821 if (!RefInfo.Clone) {
1822 assert(Ref > InputDIE.getOffset());
1823 // We haven't cloned this DIE yet. Just create an empty one and
1824 // store it. It'll get really cloned when we process it.
1825 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1826 }
1827 NewRefDie = RefInfo.Clone;
1828
1829 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1830 // We cannot currently rely on a DIEEntry to emit ref_addr
1831 // references, because the implementation calls back to DwarfDebug
1832 // to find the unit offset. (We don't have a DwarfDebug)
1833 // FIXME: we should be able to design DIEEntry reliance on
1834 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001835 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00001836 if (Ref < InputDIE.getOffset()) {
1837 // We must have already cloned that DIE.
1838 uint32_t NewRefOffset =
1839 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001840 Attr = NewRefOffset;
Frederic Riss9833de62015-03-06 23:22:53 +00001841 } else {
1842 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001843 Attr = 0xBADDEF;
Duncan P. N. Exon Smith88a8fc52015-05-27 22:44:06 +00001844 Unit.noteForwardReference(NewRefDie, RefUnit, PatchLocation(Die));
Frederic Riss9833de62015-03-06 23:22:53 +00001845 }
1846 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001847 DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00001848 return AttrSize;
1849 }
1850
Frederic Rissb8b43d52015-03-04 22:07:44 +00001851 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001852 DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001853 return AttrSize;
1854}
1855
1856/// \brief Clone an attribute of block form (locations, constants) and add
1857/// it to \p Die.
1858/// \returns the size of the new attribute.
1859unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1860 const DWARFFormValue &Val,
1861 unsigned AttrSize) {
1862 DIE *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001863 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001864 DIELoc *Loc = nullptr;
1865 DIEBlock *Block = nullptr;
1866 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00001867 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001868 Loc = new (DIEAlloc) DIELoc;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001869 DIELocs.push_back(Loc);
1870 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001871 Block = new (DIEAlloc) DIEBlock;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001872 DIEBlocks.push_back(Block);
1873 }
1874 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00001875
1876 if (Loc)
1877 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1878 dwarf::Form(AttrSpec.Form), Loc);
1879 else
1880 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1881 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001882 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1883 for (auto Byte : Bytes)
1884 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001885 DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001886 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1887 // the DIE class, this if could be replaced by
1888 // Attr->setSize(Bytes.size()).
1889 if (Streamer) {
1890 if (Loc)
1891 Loc->ComputeSize(&Streamer->getAsmPrinter());
1892 else
1893 Block->ComputeSize(&Streamer->getAsmPrinter());
1894 }
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00001895 Die.addValue(Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001896 return AttrSize;
1897}
1898
Frederic Riss31da3242015-03-11 18:45:52 +00001899/// \brief Clone an address attribute and add it to \p Die.
1900/// \returns the size of the new attribute.
1901unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1902 const DWARFFormValue &Val,
1903 const CompileUnit &Unit,
1904 AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001905 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00001906 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1907 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1908 Die.getTag() == dwarf::DW_TAG_lexical_block)
1909 Addr += Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001910 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1911 Addr = Unit.getLowPc();
1912 if (Addr == UINT64_MAX)
1913 return 0;
1914 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00001915 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00001916 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001917 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1918 if (uint64_t HighPc = Unit.getHighPc())
1919 Addr = HighPc;
1920 else
1921 return 0;
1922 } else
1923 // If we have a high_pc recorded for the input DIE, use
1924 // it. Otherwise (when no relocations where applied) just use the
1925 // one we just decoded.
1926 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00001927 }
1928
1929 Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001930 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00001931 return Unit.getOrigUnit().getAddressByteSize();
1932}
1933
Frederic Rissb8b43d52015-03-04 22:07:44 +00001934/// \brief Clone a scalar attribute and add it to \p Die.
1935/// \returns the size of the new attribute.
1936unsigned DwarfLinker::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00001937 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00001938 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001939 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001940 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001941 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1942 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1943 if (Unit.getLowPc() == -1ULL)
1944 return 0;
1945 // Dwarf >= 4 high_pc is an size, not an address.
1946 Value = Unit.getHighPc() - Unit.getLowPc();
1947 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00001948 Value = *Val.getAsSectionOffset();
1949 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1950 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001951 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1952 Value = *OptionalValue;
1953 else {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001954 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1955 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001956 return 0;
1957 }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001958 DIEInteger Attr(Value);
Frederic Riss25440872015-03-13 23:30:31 +00001959 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith88a8fc52015-05-27 22:44:06 +00001960 Unit.noteRangeAttribute(Die, PatchLocation(Die));
Frederic Rissdfb97902015-03-14 15:49:07 +00001961 // A more generic way to check for location attributes would be
1962 // nice, but it's very unlikely that any other attribute needs a
1963 // location list.
1964 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1965 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith88a8fc52015-05-27 22:44:06 +00001966 Unit.noteLocationAttribute(PatchLocation(Die), Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001967 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1968 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00001969
Frederic Rissb8b43d52015-03-04 22:07:44 +00001970 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Frederic Riss25440872015-03-13 23:30:31 +00001971 Attr);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001972 return AttrSize;
1973}
1974
1975/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1976/// value \p Val, and add it to \p Die.
1977/// \returns the size of the cloned attribute.
1978unsigned DwarfLinker::cloneAttribute(DIE &Die,
1979 const DWARFDebugInfoEntryMinimal &InputDIE,
1980 CompileUnit &Unit,
1981 const DWARFFormValue &Val,
1982 const AttributeSpec AttrSpec,
Frederic Riss31da3242015-03-11 18:45:52 +00001983 unsigned AttrSize, AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001984 const DWARFUnit &U = Unit.getOrigUnit();
1985
1986 switch (AttrSpec.Form) {
1987 case dwarf::DW_FORM_strp:
1988 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00001989 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001990 case dwarf::DW_FORM_ref_addr:
1991 case dwarf::DW_FORM_ref1:
1992 case dwarf::DW_FORM_ref2:
1993 case dwarf::DW_FORM_ref4:
1994 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00001995 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001996 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001997 case dwarf::DW_FORM_block:
1998 case dwarf::DW_FORM_block1:
1999 case dwarf::DW_FORM_block2:
2000 case dwarf::DW_FORM_block4:
2001 case dwarf::DW_FORM_exprloc:
2002 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2003 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002004 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002005 case dwarf::DW_FORM_data1:
2006 case dwarf::DW_FORM_data2:
2007 case dwarf::DW_FORM_data4:
2008 case dwarf::DW_FORM_data8:
2009 case dwarf::DW_FORM_udata:
2010 case dwarf::DW_FORM_sdata:
2011 case dwarf::DW_FORM_sec_offset:
2012 case dwarf::DW_FORM_flag:
2013 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002014 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2015 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002016 default:
2017 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2018 &InputDIE);
2019 }
2020
2021 return 0;
2022}
2023
Frederic Riss23e20e92015-03-07 01:25:09 +00002024/// \brief Apply the valid relocations found by findValidRelocs() to
2025/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2026/// in the debug_info section.
2027///
2028/// Like for findValidRelocs(), this function must be called with
2029/// monotonic \p BaseOffset values.
2030///
2031/// \returns wether any reloc has been applied.
2032bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2033 uint32_t BaseOffset, bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002034 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002035 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2036 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002037 if (NextValidReloc >= ValidRelocs.size())
2038 return false;
2039
2040 // Skip relocs that haven't been applied.
2041 while (NextValidReloc < ValidRelocs.size() &&
2042 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2043 ++NextValidReloc;
2044
2045 bool Applied = false;
2046 uint64_t EndOffset = BaseOffset + Data.size();
2047 while (NextValidReloc < ValidRelocs.size() &&
2048 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2049 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2050 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2051 assert(ValidReloc.Offset - BaseOffset < Data.size());
2052 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2053 char Buf[8];
2054 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2055 Value += ValidReloc.Addend;
2056 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2057 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2058 Buf[i] = uint8_t(Value >> (Index * 8));
2059 }
2060 assert(ValidReloc.Size <= sizeof(Buf));
2061 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2062 Applied = true;
2063 }
2064
2065 return Applied;
2066}
2067
Frederic Rissbce93ff2015-03-16 02:05:10 +00002068static bool isTypeTag(uint16_t Tag) {
2069 switch (Tag) {
2070 case dwarf::DW_TAG_array_type:
2071 case dwarf::DW_TAG_class_type:
2072 case dwarf::DW_TAG_enumeration_type:
2073 case dwarf::DW_TAG_pointer_type:
2074 case dwarf::DW_TAG_reference_type:
2075 case dwarf::DW_TAG_string_type:
2076 case dwarf::DW_TAG_structure_type:
2077 case dwarf::DW_TAG_subroutine_type:
2078 case dwarf::DW_TAG_typedef:
2079 case dwarf::DW_TAG_union_type:
2080 case dwarf::DW_TAG_ptr_to_member_type:
2081 case dwarf::DW_TAG_set_type:
2082 case dwarf::DW_TAG_subrange_type:
2083 case dwarf::DW_TAG_base_type:
2084 case dwarf::DW_TAG_const_type:
2085 case dwarf::DW_TAG_constant:
2086 case dwarf::DW_TAG_file_type:
2087 case dwarf::DW_TAG_namelist:
2088 case dwarf::DW_TAG_packed_type:
2089 case dwarf::DW_TAG_volatile_type:
2090 case dwarf::DW_TAG_restrict_type:
2091 case dwarf::DW_TAG_interface_type:
2092 case dwarf::DW_TAG_unspecified_type:
2093 case dwarf::DW_TAG_shared_type:
2094 return true;
2095 default:
2096 break;
2097 }
2098 return false;
2099}
2100
Frederic Rissb8b43d52015-03-04 22:07:44 +00002101/// \brief Recursively clone \p InputDIE's subtrees that have been
2102/// selected to appear in the linked output.
2103///
2104/// \param OutOffset is the Offset where the newly created DIE will
2105/// lie in the linked compile unit.
2106///
2107/// \returns the cloned DIE object or null if nothing was selected.
2108DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss31da3242015-03-11 18:45:52 +00002109 CompileUnit &Unit, int64_t PCOffset,
2110 uint32_t OutOffset) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002111 DWARFUnit &U = Unit.getOrigUnit();
2112 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002113 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002114
2115 // Should the DIE appear in the output?
2116 if (!Unit.getInfo(Idx).Keep)
2117 return nullptr;
2118
2119 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002120 // The DIE might have been already created by a forward reference
2121 // (see cloneDieReferenceAttribute()).
2122 DIE *Die = Info.Clone;
2123 if (!Die)
2124 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
2125 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002126 Die->setOffset(OutOffset);
2127
2128 // Extract and clone every attribute.
2129 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00002130 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002131 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002132
2133 // We could copy the data only if we need to aply a relocation to
2134 // it. After testing, it seems there is no performance downside to
2135 // doing the copy unconditionally, and it makes the code simpler.
2136 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2137 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2138 // Modify the copy with relocated addresses.
Frederic Riss31da3242015-03-11 18:45:52 +00002139 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2140 // If we applied relocations, we store the value of high_pc that was
2141 // potentially stored in the input DIE. If high_pc is an address
2142 // (Dwarf version == 2), then it might have been relocated to a
2143 // totally unrelated value (because the end address in the object
2144 // file might be start address of another function which got moved
2145 // independantly by the linker). The computation of the actual
2146 // high_pc value is done in cloneAddressAttribute().
2147 AttrInfo.OrigHighPc =
2148 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2149 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002150
2151 // Reset the Offset to 0 as we will be working on the local copy of
2152 // the data.
2153 Offset = 0;
2154
Frederic Rissb8b43d52015-03-04 22:07:44 +00002155 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2156 Offset += getULEB128Size(Abbrev->getCode());
2157
Frederic Riss31da3242015-03-11 18:45:52 +00002158 // We are entering a subprogram. Get and propagate the PCOffset.
2159 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2160 PCOffset = Info.AddrAdjust;
2161 AttrInfo.PCOffset = PCOffset;
2162
Frederic Rissb8b43d52015-03-04 22:07:44 +00002163 for (const auto &AttrSpec : Abbrev->attributes()) {
2164 DWARFFormValue Val(AttrSpec.Form);
2165 uint32_t AttrSize = Offset;
2166 Val.extractValue(Data, &Offset, &U);
2167 AttrSize = Offset - AttrSize;
2168
Frederic Riss31da3242015-03-11 18:45:52 +00002169 OutOffset +=
2170 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002171 }
2172
Frederic Rissbce93ff2015-03-16 02:05:10 +00002173 // Look for accelerator entries.
2174 uint16_t Tag = InputDIE.getTag();
2175 // FIXME: This is slightly wrong. An inline_subroutine without a
2176 // low_pc, but with AT_ranges might be interesting to get into the
2177 // accelerator tables too. For now stick with dsymutil's behavior.
2178 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2179 Tag != dwarf::DW_TAG_compile_unit &&
2180 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2181 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2182 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2183 AttrInfo.MangledNameOffset,
2184 Tag == dwarf::DW_TAG_inlined_subroutine);
2185 if (AttrInfo.Name)
2186 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2187 Tag == dwarf::DW_TAG_inlined_subroutine);
2188 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2189 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2190 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2191 }
2192
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002193 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002194 // If a scope DIE is kept, we must have kept at least one child. If
2195 // it's not the case, we'll just be emitting one wasteful end of
2196 // children marker, but things won't break.
2197 if (InputDIE.hasChildren())
2198 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2199 // Assign a permanent abbrev number
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002200 AssignAbbrev(NewAbbrev);
2201 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002202
2203 // Add the size of the abbreviation number to the output offset.
2204 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2205
2206 if (!Abbrev->hasChildren()) {
2207 // Update our size.
2208 Die->setSize(OutOffset - Die->getOffset());
2209 return Die;
2210 }
2211
2212 // Recursively clone children.
2213 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2214 Child = Child->getSibling()) {
Frederic Riss31da3242015-03-11 18:45:52 +00002215 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002216 Die->addChild(std::unique_ptr<DIE>(Clone));
2217 OutOffset = Clone->getOffset() + Clone->getSize();
2218 }
2219 }
2220
2221 // Account for the end of children marker.
2222 OutOffset += sizeof(int8_t);
2223 // Update our size.
2224 Die->setSize(OutOffset - Die->getOffset());
2225 return Die;
2226}
2227
Frederic Riss25440872015-03-13 23:30:31 +00002228/// \brief Patch the input object file relevant debug_ranges entries
2229/// and emit them in the output file. Update the relevant attributes
2230/// to point at the new entries.
2231void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2232 DWARFContext &OrigDwarf) const {
2233 DWARFDebugRangeList RangeList;
2234 const auto &FunctionRanges = Unit.getFunctionRanges();
2235 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2236 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2237 OrigDwarf.isLittleEndian(), AddressSize);
2238 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2239 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002240 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002241 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2242 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2243 // Ranges addresses are based on the unit's low_pc. Compute the
2244 // offset we need to apply to adapt to the the new unit's low_pc.
2245 int64_t UnitPcOffset = 0;
2246 if (OrigLowPc != -1ULL)
2247 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2248
2249 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002250 uint32_t Offset = RangeAttribute.get();
2251 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002252 RangeList.extract(RangeExtractor, &Offset);
2253 const auto &Entries = RangeList.getEntries();
2254 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2255
2256 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2257 First.StartAddress >= CurrRange.stop()) {
2258 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2259 if (CurrRange == InvalidRange ||
2260 CurrRange.start() > First.StartAddress + OrigLowPc) {
2261 reportWarning("no mapping for range.");
2262 continue;
2263 }
2264 }
2265
2266 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2267 AddressSize);
2268 }
2269}
2270
Frederic Riss563b1b02015-03-14 03:46:51 +00002271/// \brief Generate the debug_aranges entries for \p Unit and if the
2272/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2273/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002274/// FIXME: this could actually be done right in patchRangesForUnit,
2275/// but for the sake of initial bit-for-bit compatibility with legacy
2276/// dsymutil, we have to do it in a delayed pass.
2277void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002278 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002279 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002280 Attr->set(Streamer->getRangesSectionSize());
2281 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002282}
2283
Frederic Riss63786b02015-03-15 20:45:43 +00002284/// \brief Insert the new line info sequence \p Seq into the current
2285/// set of already linked line info \p Rows.
2286static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2287 std::vector<DWARFDebugLine::Row> &Rows) {
2288 if (Seq.empty())
2289 return;
2290
2291 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2292 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2293 Seq.clear();
2294 return;
2295 }
2296
2297 auto InsertPoint = std::lower_bound(
2298 Rows.begin(), Rows.end(), Seq.front(),
2299 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2300 return LHS.Address < RHS.Address;
2301 });
2302
2303 // FIXME: this only removes the unneeded end_sequence if the
2304 // sequences have been inserted in order. using a global sort like
2305 // described in patchLineTableForUnit() and delaying the end_sequene
2306 // elimination to emitLineTableForUnit() we can get rid of all of them.
2307 if (InsertPoint != Rows.end() &&
2308 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2309 *InsertPoint = Seq.front();
2310 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2311 } else {
2312 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2313 }
2314
2315 Seq.clear();
2316}
2317
2318/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2319/// recreate a relocated version of these for the address ranges that
2320/// are present in the binary.
2321void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2322 DWARFContext &OrigDwarf) {
2323 const DWARFDebugInfoEntryMinimal *CUDie =
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002324 Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002325 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2326 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2327 if (StmtList == -1ULL)
2328 return;
2329
2330 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2331 if (auto *OutputDIE = Unit.getOutputUnitDIE()) {
Duncan P. N. Exon Smith88a8fc52015-05-27 22:44:06 +00002332 auto Stmt = std::find_if(OutputDIE->begin_values(), OutputDIE->end_values(),
2333 [](const DIEValue &Value) {
2334 return Value.getAttribute() == dwarf::DW_AT_stmt_list;
2335 });
2336 assert(Stmt != OutputDIE->end_values() &&
2337 "Didn't find DW_AT_stmt_list in cloned DIE!");
2338 OutputDIE->setValue(Stmt - OutputDIE->begin_values(),
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002339 DIEValue(Stmt->getAttribute(), Stmt->getForm(),
2340 DIEInteger(Streamer->getLineSectionSize())));
Frederic Riss63786b02015-03-15 20:45:43 +00002341 }
2342
2343 // Parse the original line info for the unit.
2344 DWARFDebugLine::LineTable LineTable;
2345 uint32_t StmtOffset = StmtList;
2346 StringRef LineData = OrigDwarf.getLineSection().Data;
2347 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2348 Unit.getOrigUnit().getAddressByteSize());
2349 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2350 &StmtOffset);
2351
2352 // This vector is the output line table.
2353 std::vector<DWARFDebugLine::Row> NewRows;
2354 NewRows.reserve(LineTable.Rows.size());
2355
2356 // Current sequence of rows being extracted, before being inserted
2357 // in NewRows.
2358 std::vector<DWARFDebugLine::Row> Seq;
2359 const auto &FunctionRanges = Unit.getFunctionRanges();
2360 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2361
2362 // FIXME: This logic is meant to generate exactly the same output as
2363 // Darwin's classic dsynutil. There is a nicer way to implement this
2364 // by simply putting all the relocated line info in NewRows and simply
2365 // sorting NewRows before passing it to emitLineTableForUnit. This
2366 // should be correct as sequences for a function should stay
2367 // together in the sorted output. There are a few corner cases that
2368 // look suspicious though, and that required to implement the logic
2369 // this way. Revisit that once initial validation is finished.
2370
2371 // Iterate over the object file line info and extract the sequences
2372 // that correspond to linked functions.
2373 for (auto &Row : LineTable.Rows) {
2374 // Check wether we stepped out of the range. The range is
2375 // half-open, but consider accept the end address of the range if
2376 // it is marked as end_sequence in the input (because in that
2377 // case, the relocation offset is accurate and that entry won't
2378 // serve as the start of another function).
2379 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2380 Row.Address > CurrRange.stop() ||
2381 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2382 // We just stepped out of a known range. Insert a end_sequence
2383 // corresponding to the end of the range.
2384 uint64_t StopAddress = CurrRange != InvalidRange
2385 ? CurrRange.stop() + CurrRange.value()
2386 : -1ULL;
2387 CurrRange = FunctionRanges.find(Row.Address);
2388 bool CurrRangeValid =
2389 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2390 if (!CurrRangeValid) {
2391 CurrRange = InvalidRange;
2392 if (StopAddress != -1ULL) {
2393 // Try harder by looking in the DebugMapObject function
2394 // ranges map. There are corner cases where this finds a
2395 // valid entry. It's unclear if this is right or wrong, but
2396 // for now do as dsymutil.
2397 // FIXME: Understand exactly what cases this addresses and
2398 // potentially remove it along with the Ranges map.
2399 auto Range = Ranges.lower_bound(Row.Address);
2400 if (Range != Ranges.begin() && Range != Ranges.end())
2401 --Range;
2402
2403 if (Range != Ranges.end() && Range->first <= Row.Address &&
2404 Range->second.first >= Row.Address) {
2405 StopAddress = Row.Address + Range->second.second;
2406 }
2407 }
2408 }
2409 if (StopAddress != -1ULL && !Seq.empty()) {
2410 // Insert end sequence row with the computed end address, but
2411 // the same line as the previous one.
2412 Seq.emplace_back(Seq.back());
2413 Seq.back().Address = StopAddress;
2414 Seq.back().EndSequence = 1;
2415 Seq.back().PrologueEnd = 0;
2416 Seq.back().BasicBlock = 0;
2417 Seq.back().EpilogueBegin = 0;
2418 insertLineSequence(Seq, NewRows);
2419 }
2420
2421 if (!CurrRangeValid)
2422 continue;
2423 }
2424
2425 // Ignore empty sequences.
2426 if (Row.EndSequence && Seq.empty())
2427 continue;
2428
2429 // Relocate row address and add it to the current sequence.
2430 Row.Address += CurrRange.value();
2431 Seq.emplace_back(Row);
2432
2433 if (Row.EndSequence)
2434 insertLineSequence(Seq, NewRows);
2435 }
2436
2437 // Finished extracting, now emit the line tables.
2438 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2439 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2440 // prologue over and that works because we act as both producer and
2441 // consumer. It would be nicer to have a real configurable line
2442 // table emitter.
2443 if (LineTable.Prologue.Version != 2 ||
2444 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2445 LineTable.Prologue.LineBase != -5 || LineTable.Prologue.LineRange != 14 ||
2446 LineTable.Prologue.OpcodeBase != 13)
2447 reportWarning("line table paramters mismatch. Cannot emit.");
2448 else
2449 Streamer->emitLineTableForUnit(LineData.slice(StmtList + 4, PrologueEnd),
2450 LineTable.Prologue.MinInstLength, NewRows,
2451 Unit.getOrigUnit().getAddressByteSize());
2452}
2453
Frederic Rissbce93ff2015-03-16 02:05:10 +00002454void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2455 Streamer->emitPubNamesForUnit(Unit);
2456 Streamer->emitPubTypesForUnit(Unit);
2457}
2458
Frederic Rissd3455182015-01-28 18:27:01 +00002459bool DwarfLinker::link(const DebugMap &Map) {
2460
2461 if (Map.begin() == Map.end()) {
2462 errs() << "Empty debug map.\n";
2463 return false;
2464 }
2465
Frederic Rissc99ea202015-02-28 00:29:11 +00002466 if (!createStreamer(Map.getTriple(), OutputFilename))
2467 return false;
2468
Frederic Rissb8b43d52015-03-04 22:07:44 +00002469 // Size of the DIEs (and headers) generated for the linked output.
2470 uint64_t OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00002471 // A unique ID that identifies each compile unit.
2472 unsigned UnitID = 0;
Frederic Rissd3455182015-01-28 18:27:01 +00002473 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002474 CurrentDebugObject = Obj.get();
2475
Frederic Rissb9818322015-02-28 00:29:07 +00002476 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00002477 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
2478 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
2479 if (std::error_code EC = ErrOrObj.getError()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002480 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
Frederic Rissd3455182015-01-28 18:27:01 +00002481 continue;
2482 }
2483
Frederic Riss1036e642015-02-13 23:18:22 +00002484 // Look for relocations that correspond to debug map entries.
2485 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00002486 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00002487 outs() << "No valid relocations found. Skipping.\n";
2488 continue;
2489 }
2490
Frederic Riss563cba62015-01-28 22:15:14 +00002491 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00002492 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00002493 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00002494
Frederic Riss563cba62015-01-28 22:15:14 +00002495 // In a first phase, just read in the debug info and store the DIE
2496 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00002497 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002498 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00002499 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00002500 outs() << "Input compilation unit:";
2501 CUDie->dump(outs(), CU.get(), 0);
2502 }
Frederic Riss3cced052015-03-14 03:46:40 +00002503 Units.emplace_back(*CU, UnitID++);
Frederic Riss9aa725b2015-02-13 23:18:31 +00002504 gatherDIEParents(CUDie, 0, Units.back());
Frederic Rissd3455182015-01-28 18:27:01 +00002505 }
Frederic Riss563cba62015-01-28 22:15:14 +00002506
Frederic Riss84c09a52015-02-13 23:18:34 +00002507 // Then mark all the DIEs that need to be present in the linked
2508 // output and collect some information about them. Note that this
2509 // loop can not be merged with the previous one becaue cross-cu
2510 // references require the ParentIdx to be setup for every CU in
2511 // the object file before calling this.
2512 for (auto &CurrentUnit : Units)
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002513 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00002514 CurrentUnit, 0);
2515
Frederic Riss23e20e92015-03-07 01:25:09 +00002516 // The calls to applyValidRelocs inside cloneDIE will walk the
2517 // reloc array again (in the same way findValidRelocsInDebugInfo()
2518 // did). We need to reset the NextValidReloc index to the beginning.
2519 NextValidReloc = 0;
2520
Frederic Rissb8b43d52015-03-04 22:07:44 +00002521 // Construct the output DIE tree by cloning the DIEs we chose to
2522 // keep above. If there are no valid relocs, then there's nothing
2523 // to clone/emit.
2524 if (!ValidRelocs.empty())
2525 for (auto &CurrentUnit : Units) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002526 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00002527 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Riss31da3242015-03-11 18:45:52 +00002528 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
2529 11 /* Unit Header size */);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002530 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00002531 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Riss63786b02015-03-15 20:45:43 +00002532 if (Options.NoOutput)
2533 continue;
2534 // FIXME: for compatibility with the classic dsymutil, we emit
2535 // an empty line table for the unit, even if the unit doesn't
2536 // actually exist in the DIE tree.
2537 patchLineTableForUnit(CurrentUnit, DwarfContext);
2538 if (!OutputDIE)
Frederic Riss25440872015-03-13 23:30:31 +00002539 continue;
2540 patchRangesForUnit(CurrentUnit, DwarfContext);
Frederic Rissdfb97902015-03-14 15:49:07 +00002541 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002542 emitAcceleratorEntriesForUnit(CurrentUnit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002543 }
2544
2545 // Emit all the compile unit's debug information.
2546 if (!ValidRelocs.empty() && !Options.NoOutput)
2547 for (auto &CurrentUnit : Units) {
Frederic Riss25440872015-03-13 23:30:31 +00002548 generateUnitRanges(CurrentUnit);
Frederic Riss9833de62015-03-06 23:22:53 +00002549 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002550 Streamer->emitCompileUnitHeader(CurrentUnit);
2551 if (!CurrentUnit.getOutputUnitDIE())
2552 continue;
2553 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
2554 }
2555
Frederic Riss563cba62015-01-28 22:15:14 +00002556 // Clean-up before starting working on the next object.
2557 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00002558 }
2559
Frederic Rissb8b43d52015-03-04 22:07:44 +00002560 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00002561 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002562 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00002563 Streamer->emitStrings(StringPool);
2564 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002565
Frederic Rissc99ea202015-02-28 00:29:11 +00002566 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00002567}
2568}
Frederic Rissd3455182015-01-28 18:27:01 +00002569
Frederic Rissb9818322015-02-28 00:29:07 +00002570bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
2571 const LinkOptions &Options) {
2572 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00002573 return Linker.link(DM);
2574}
2575}
Frederic Riss231f7142014-12-12 17:31:24 +00002576}