blob: e3e7e82eab62527bf54d1838559a2d8669154306 [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)
Duncan P. N. Exon Smithb04fb5e2015-05-28 18:55:38 +000072 : Die(&Die), Index(std::distance(Die.values_begin(), Die.values_end())) {}
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000073
74 void set(uint64_t New) const {
75 assert(Die);
Aaron Ballmane08537f2015-05-28 12:55:59 +000076 assert((signed)Index <
Duncan P. N. Exon Smithb04fb5e2015-05-28 18:55:38 +000077 std::distance(Die->values_begin(), Die->values_end()));
78 const auto &Old = Die->values_begin()[Index];
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +000079 assert(Old.getType() == DIEValue::isInteger);
80 Die->setValue(Index,
81 DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New)));
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000082 }
83
84 uint64_t get() const {
85 assert(Die);
Aaron Ballmane08537f2015-05-28 12:55:59 +000086 assert((signed)Index <
Duncan P. N. Exon Smithb04fb5e2015-05-28 18:55:38 +000087 std::distance(Die->values_begin(), Die->values_end()));
88 assert(Die->values_begin()[Index].getType() == DIEValue::isInteger);
89 return Die->values_begin()[Index].getDIEInteger().getValue();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +000090 }
91};
92
Frederic Riss563cba62015-01-28 22:15:14 +000093/// \brief Stores all information relating to a compile unit, be it in
94/// its original instance in the object file to its brand new cloned
95/// and linked DIE tree.
96class CompileUnit {
97public:
98 /// \brief Information gathered about a DIE in the object file.
99 struct DIEInfo {
Frederic Riss31da3242015-03-11 18:45:52 +0000100 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
Frederic Riss9833de62015-03-06 23:22:53 +0000101 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +0000102 uint32_t ParentIdx; ///< The index of this DIE's parent.
103 bool Keep; ///< Is the DIE part of the linked output?
104 bool InDebugMap; ///< Was this DIE's entity found in the map?
Frederic Riss563cba62015-01-28 22:15:14 +0000105 };
106
Frederic Riss3cced052015-03-14 03:46:40 +0000107 CompileUnit(DWARFUnit &OrigUnit, unsigned ID)
108 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000109 Ranges(RangeAlloc) {
Frederic Riss563cba62015-01-28 22:15:14 +0000110 Info.resize(OrigUnit.getNumDIEs());
111 }
112
Frederic Riss2838f9e2015-03-05 05:29:05 +0000113 CompileUnit(CompileUnit &&RHS)
114 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
115 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
Frederic Riss1af75f72015-03-12 18:45:10 +0000116 NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
117 // The CompileUnit container has been 'reserve()'d with the right
118 // size. We cannot move the IntervalMap anyway.
119 llvm_unreachable("CompileUnits should not be moved.");
120 }
David Blaikiea8adc132015-03-04 22:20:52 +0000121
Frederic Rissc3349d42015-02-13 23:18:27 +0000122 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +0000123
Frederic Riss3cced052015-03-14 03:46:40 +0000124 unsigned getUniqueID() const { return ID; }
125
Frederic Rissb8b43d52015-03-04 22:07:44 +0000126 DIE *getOutputUnitDIE() const { return CUDie.get(); }
127 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
128
Frederic Riss563cba62015-01-28 22:15:14 +0000129 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
130 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
131
Frederic Rissb8b43d52015-03-04 22:07:44 +0000132 uint64_t getStartOffset() const { return StartOffset; }
133 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
Frederic Riss95529482015-03-13 23:30:27 +0000134 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
Frederic Rissb8b43d52015-03-04 22:07:44 +0000135
Frederic Riss5a62dc32015-03-13 18:35:54 +0000136 uint64_t getLowPc() const { return LowPc; }
137 uint64_t getHighPc() const { return HighPc; }
138
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000139 Optional<PatchLocation> getUnitRangesAttribute() const {
140 return UnitRangeAttribute;
141 }
Frederic Riss25440872015-03-13 23:30:31 +0000142 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000143 const std::vector<PatchLocation> &getRangesAttributes() const {
Frederic Riss25440872015-03-13 23:30:31 +0000144 return RangeAttributes;
145 }
Frederic Riss9d441b62015-03-06 23:22:50 +0000146
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000147 const std::vector<std::pair<PatchLocation, int64_t>> &
Frederic Rissdfb97902015-03-14 15:49:07 +0000148 getLocationAttributes() const {
149 return LocationAttributes;
150 }
151
Frederic Riss9d441b62015-03-06 23:22:50 +0000152 /// \brief Compute the end offset for this unit. Must be
153 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +0000154 /// \returns the next unit offset (which is also the current
155 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +0000156 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000157
Frederic Riss6afcfce2015-03-13 18:35:57 +0000158 /// \brief Keep track of a forward reference to DIE \p Die in \p
159 /// RefUnit by \p Attr. The attribute should be fixed up later to
160 /// point to the absolute offset of \p Die in the debug_info section.
161 void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000162 PatchLocation Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000163
164 /// \brief Apply all fixups recored by noteForwardReference().
165 void fixupForwardReferences();
166
Frederic Riss1af75f72015-03-12 18:45:10 +0000167 /// \brief Add a function range [\p LowPC, \p HighPC) that is
168 /// relocatad by applying offset \p PCOffset.
169 void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
170
Frederic Riss5c9c7062015-03-13 23:55:29 +0000171 /// \brief Keep track of a DW_AT_range attribute that we will need to
Frederic Riss25440872015-03-13 23:30:31 +0000172 /// patch up later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000173 void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
Frederic Riss25440872015-03-13 23:30:31 +0000174
Frederic Rissdfb97902015-03-14 15:49:07 +0000175 /// \brief Keep track of a location attribute pointing to a location
176 /// list in the debug_loc section.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000177 void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
Frederic Rissdfb97902015-03-14 15:49:07 +0000178
Frederic Rissbce93ff2015-03-16 02:05:10 +0000179 /// \brief Add a name accelerator entry for \p Die with \p Name
180 /// which is stored in the string table at \p Offset.
181 void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
182 bool SkipPubnamesSection = false);
183
184 /// \brief Add a type accelerator entry for \p Die with \p Name
185 /// which is stored in the string table at \p Offset.
186 void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
187
188 struct AccelInfo {
189 StringRef Name; ///< Name of the entry.
190 const DIE *Die; ///< DIE this entry describes.
191 uint32_t NameOffset; ///< Offset of Name in the string pool.
192 bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
193
194 AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
195 bool SkipPubSection = false)
196 : Name(Name), Die(Die), NameOffset(NameOffset),
197 SkipPubSection(SkipPubSection) {}
198 };
199
200 const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
201 const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
202
Frederic Riss563cba62015-01-28 22:15:14 +0000203private:
204 DWARFUnit &OrigUnit;
Frederic Riss3cced052015-03-14 03:46:40 +0000205 unsigned ID;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000206 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
207 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
208
209 uint64_t StartOffset;
210 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000211
Frederic Riss5a62dc32015-03-13 18:35:54 +0000212 uint64_t LowPc;
213 uint64_t HighPc;
214
Frederic Riss9833de62015-03-06 23:22:53 +0000215 /// \brief A list of attributes to fixup with the absolute offset of
216 /// a DIE in the debug_info section.
217 ///
218 /// The offsets for the attributes in this array couldn't be set while
Frederic Riss6afcfce2015-03-13 18:35:57 +0000219 /// cloning because for cross-cu forward refences the target DIE's
220 /// offset isn't known you emit the reference attribute.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000221 std::vector<std::tuple<DIE *, const CompileUnit *, PatchLocation>>
Frederic Riss6afcfce2015-03-13 18:35:57 +0000222 ForwardDIEReferences;
Frederic Riss1af75f72015-03-12 18:45:10 +0000223
Frederic Riss25440872015-03-13 23:30:31 +0000224 FunctionIntervals::Allocator RangeAlloc;
Frederic Riss1af75f72015-03-12 18:45:10 +0000225 /// \brief The ranges in that interval map are the PC ranges for
226 /// functions in this unit, associated with the PC offset to apply
227 /// to the addresses to get the linked address.
Frederic Riss25440872015-03-13 23:30:31 +0000228 FunctionIntervals Ranges;
229
230 /// \brief DW_AT_ranges attributes to patch after we have gathered
231 /// all the unit's function addresses.
232 /// @{
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000233 std::vector<PatchLocation> RangeAttributes;
234 Optional<PatchLocation> UnitRangeAttribute;
Frederic Riss25440872015-03-13 23:30:31 +0000235 /// @}
Frederic Rissdfb97902015-03-14 15:49:07 +0000236
237 /// \brief Location attributes that need to be transfered from th
238 /// original debug_loc section to the liked one. They are stored
239 /// along with the PC offset that is to be applied to their
240 /// function's address.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000241 std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
Frederic Rissbce93ff2015-03-16 02:05:10 +0000242
243 /// \brief Accelerator entries for the unit, both for the pub*
244 /// sections and the apple* ones.
245 /// @{
246 std::vector<AccelInfo> Pubnames;
247 std::vector<AccelInfo> Pubtypes;
248 /// @}
Frederic Riss563cba62015-01-28 22:15:14 +0000249};
250
Frederic Riss9d441b62015-03-06 23:22:50 +0000251uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000252 NextUnitOffset = StartOffset + 11 /* Header size */;
253 // The root DIE might be null, meaning that the Unit had nothing to
254 // contribute to the linked output. In that case, we will emit the
255 // unit header without any actual DIE.
256 if (CUDie)
257 NextUnitOffset += CUDie->getSize();
258 return NextUnitOffset;
259}
260
Frederic Riss6afcfce2015-03-13 18:35:57 +0000261/// \brief Keep track of a forward cross-cu reference from this unit
262/// to \p Die that lives in \p RefUnit.
263void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000264 PatchLocation Attr) {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000265 ForwardDIEReferences.emplace_back(Die, RefUnit, Attr);
Frederic Riss9833de62015-03-06 23:22:53 +0000266}
267
268/// \brief Apply all fixups recorded by noteForwardReference().
269void CompileUnit::fixupForwardReferences() {
Frederic Riss6afcfce2015-03-13 18:35:57 +0000270 for (const auto &Ref : ForwardDIEReferences) {
271 DIE *RefDie;
272 const CompileUnit *RefUnit;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000273 PatchLocation Attr;
Frederic Riss6afcfce2015-03-13 18:35:57 +0000274 std::tie(RefDie, RefUnit, Attr) = Ref;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000275 Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
Frederic Riss6afcfce2015-03-13 18:35:57 +0000276 }
Frederic Riss9833de62015-03-06 23:22:53 +0000277}
278
Frederic Riss5a62dc32015-03-13 18:35:54 +0000279void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
280 int64_t PcOffset) {
281 Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
282 this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
283 this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
Frederic Riss1af75f72015-03-12 18:45:10 +0000284}
285
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000286void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
Frederic Riss25440872015-03-13 23:30:31 +0000287 if (Die.getTag() != dwarf::DW_TAG_compile_unit)
288 RangeAttributes.push_back(Attr);
289 else
290 UnitRangeAttribute = Attr;
291}
292
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000293void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
Frederic Rissdfb97902015-03-14 15:49:07 +0000294 LocationAttributes.emplace_back(Attr, PcOffset);
295}
296
Frederic Rissbce93ff2015-03-16 02:05:10 +0000297/// \brief Add a name accelerator entry for \p Die with \p Name
298/// which is stored in the string table at \p Offset.
299void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
300 uint32_t Offset, bool SkipPubSection) {
301 Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
302}
303
304/// \brief Add a type accelerator entry for \p Die with \p Name
305/// which is stored in the string table at \p Offset.
306void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
307 uint32_t Offset) {
308 Pubtypes.emplace_back(Name, Die, Offset, false);
309}
310
Frederic Rissef648462015-03-06 17:56:30 +0000311/// \brief A string table that doesn't need relocations.
312///
313/// We are doing a final link, no need for a string table that
314/// has relocation entries for every reference to it. This class
315/// provides this ablitity by just associating offsets with
316/// strings.
317class NonRelocatableStringpool {
318public:
319 /// \brief Entries are stored into the StringMap and simply linked
320 /// together through the second element of this pair in order to
321 /// keep track of insertion order.
322 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
323 MapTy;
324
325 NonRelocatableStringpool()
326 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
327 // Legacy dsymutil puts an empty string at the start of the line
328 // table.
329 getStringOffset("");
330 }
331
332 /// \brief Get the offset of string \p S in the string table. This
333 /// can insert a new element or return the offset of a preexisitng
334 /// one.
335 uint32_t getStringOffset(StringRef S);
336
337 /// \brief Get permanent storage for \p S (but do not necessarily
338 /// emit \p S in the output section).
339 /// \returns The StringRef that points to permanent storage to use
340 /// in place of \p S.
341 StringRef internString(StringRef S);
342
343 // \brief Return the first entry of the string table.
344 const MapTy::MapEntryTy *getFirstEntry() const {
345 return getNextEntry(&Sentinel);
346 }
347
348 // \brief Get the entry following \p E in the string table or null
349 // if \p E was the last entry.
350 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
351 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
352 }
353
354 uint64_t getSize() { return CurrentEndOffset; }
355
356private:
357 MapTy Strings;
358 uint32_t CurrentEndOffset;
359 MapTy::MapEntryTy Sentinel, *Last;
360};
361
362/// \brief Get the offset of string \p S in the string table. This
363/// can insert a new element or return the offset of a preexisitng
364/// one.
365uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
366 if (S.empty() && !Strings.empty())
367 return 0;
368
369 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
370 MapTy::iterator It;
371 bool Inserted;
372
373 // A non-empty string can't be at offset 0, so if we have an entry
374 // with a 0 offset, it must be a previously interned string.
375 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
376 if (Inserted || It->getValue().first == 0) {
377 // Set offset and chain at the end of the entries list.
378 It->getValue().first = CurrentEndOffset;
379 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
380 Last->getValue().second = &*It;
381 Last = &*It;
382 }
383 return It->getValue().first;
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000384}
Frederic Rissef648462015-03-06 17:56:30 +0000385
386/// \brief Put \p S into the StringMap so that it gets permanent
387/// storage, but do not actually link it in the chain of elements
388/// that go into the output section. A latter call to
389/// getStringOffset() with the same string will chain it though.
390StringRef NonRelocatableStringpool::internString(StringRef S) {
391 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
392 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
393 return InsertResult.first->getKey();
Aaron Ballman5287f0c2015-03-07 15:10:32 +0000394}
Frederic Rissef648462015-03-06 17:56:30 +0000395
Frederic Rissc99ea202015-02-28 00:29:11 +0000396/// \brief The Dwarf streaming logic
397///
398/// All interactions with the MC layer that is used to build the debug
399/// information binary representation are handled in this class.
400class DwarfStreamer {
401 /// \defgroup MCObjects MC layer objects constructed by the streamer
402 /// @{
403 std::unique_ptr<MCRegisterInfo> MRI;
404 std::unique_ptr<MCAsmInfo> MAI;
405 std::unique_ptr<MCObjectFileInfo> MOFI;
406 std::unique_ptr<MCContext> MC;
407 MCAsmBackend *MAB; // Owned by MCStreamer
408 std::unique_ptr<MCInstrInfo> MII;
409 std::unique_ptr<MCSubtargetInfo> MSTI;
410 MCCodeEmitter *MCE; // Owned by MCStreamer
411 MCStreamer *MS; // Owned by AsmPrinter
412 std::unique_ptr<TargetMachine> TM;
413 std::unique_ptr<AsmPrinter> Asm;
414 /// @}
415
416 /// \brief the file we stream the linked Dwarf to.
417 std::unique_ptr<raw_fd_ostream> OutFile;
418
Frederic Riss25440872015-03-13 23:30:31 +0000419 uint32_t RangesSectionSize;
Frederic Rissdfb97902015-03-14 15:49:07 +0000420 uint32_t LocSectionSize;
Frederic Riss63786b02015-03-15 20:45:43 +0000421 uint32_t LineSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000422
Frederic Rissbce93ff2015-03-16 02:05:10 +0000423 /// \brief Emit the pubnames or pubtypes section contribution for \p
424 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000425 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000426 const CompileUnit &Unit,
427 const std::vector<CompileUnit::AccelInfo> &Names);
428
Frederic Rissc99ea202015-02-28 00:29:11 +0000429public:
430 /// \brief Actually create the streamer and the ouptut file.
431 ///
432 /// This could be done directly in the constructor, but it feels
433 /// more natural to handle errors through return value.
434 bool init(Triple TheTriple, StringRef OutputFilename);
435
Frederic Rissb8b43d52015-03-04 22:07:44 +0000436 /// \brief Dump the file to the disk.
Frederic Rissc99ea202015-02-28 00:29:11 +0000437 bool finish();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000438
439 AsmPrinter &getAsmPrinter() const { return *Asm; }
440
441 /// \brief Set the current output section to debug_info and change
442 /// the MC Dwarf version to \p DwarfVersion.
443 void switchToDebugInfoSection(unsigned DwarfVersion);
444
445 /// \brief Emit the compilation unit header for \p Unit in the
446 /// debug_info section.
447 ///
448 /// As a side effect, this also switches the current Dwarf version
449 /// of the MC layer to the one of U.getOrigUnit().
450 void emitCompileUnitHeader(CompileUnit &Unit);
451
452 /// \brief Recursively emit the DIE tree rooted at \p Die.
453 void emitDIE(DIE &Die);
454
455 /// \brief Emit the abbreviation table \p Abbrevs to the
456 /// debug_abbrev section.
457 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000458
459 /// \brief Emit the string table described by \p Pool.
460 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000461
462 /// \brief Emit debug_ranges for \p FuncRange by translating the
463 /// original \p Entries.
464 void emitRangesEntries(
465 int64_t UnitPcOffset, uint64_t OrigLowPc,
466 FunctionIntervals::const_iterator FuncRange,
467 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
468 unsigned AddressSize);
469
Frederic Riss563b1b02015-03-14 03:46:51 +0000470 /// \brief Emit debug_aranges entries for \p Unit and if \p
471 /// DoRangesSection is true, also emit the debug_ranges entries for
472 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
473 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000474
475 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000476
477 /// \brief Emit the debug_loc contribution for \p Unit by copying
478 /// the entries from \p Dwarf and offseting them. Update the
479 /// location attributes to point to the new entries.
480 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000481
482 /// \brief Emit the line table described in \p Rows into the
483 /// debug_line section.
484 void emitLineTableForUnit(StringRef PrologueBytes, unsigned MinInstLength,
485 std::vector<DWARFDebugLine::Row> &Rows,
486 unsigned AdddressSize);
487
488 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000489
490 /// \brief Emit the .debug_pubnames contribution for \p Unit.
491 void emitPubNamesForUnit(const CompileUnit &Unit);
492
493 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
494 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Rissc99ea202015-02-28 00:29:11 +0000495};
496
497bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
498 std::string ErrorStr;
499 std::string TripleName;
500 StringRef Context = "dwarf streamer init";
501
502 // Get the target.
503 const Target *TheTarget =
504 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
505 if (!TheTarget)
506 return error(ErrorStr, Context);
507 TripleName = TheTriple.getTriple();
508
509 // Create all the MC Objects.
510 MRI.reset(TheTarget->createMCRegInfo(TripleName));
511 if (!MRI)
512 return error(Twine("no register info for target ") + TripleName, Context);
513
514 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
515 if (!MAI)
516 return error("no asm info for target " + TripleName, Context);
517
518 MOFI.reset(new MCObjectFileInfo);
519 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
520 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
521 *MC);
522
523 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
524 if (!MAB)
525 return error("no asm backend for target " + TripleName, Context);
526
527 MII.reset(TheTarget->createMCInstrInfo());
528 if (!MII)
529 return error("no instr info info for target " + TripleName, Context);
530
531 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
532 if (!MSTI)
533 return error("no subtarget info for target " + TripleName, Context);
534
Eric Christopher0169e422015-03-10 22:03:14 +0000535 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000536 if (!MCE)
537 return error("no code emitter for target " + TripleName, Context);
538
539 // Create the output file.
540 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000541 OutFile =
542 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000543 if (EC)
544 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
545
Rafael Espindolaf696df12015-03-16 22:29:29 +0000546 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
Rafael Espindola36a15cb2015-03-20 20:00:01 +0000547 *MSTI, false,
548 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000549 if (!MS)
550 return error("no object streamer for target " + TripleName, Context);
551
552 // Finally create the AsmPrinter we'll use to emit the DIEs.
553 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
554 if (!TM)
555 return error("no target machine for target " + TripleName, Context);
556
557 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
558 if (!Asm)
559 return error("no asm printer for target " + TripleName, Context);
560
Frederic Riss25440872015-03-13 23:30:31 +0000561 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000562 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000563 LineSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000564
Frederic Rissc99ea202015-02-28 00:29:11 +0000565 return true;
566}
567
568bool DwarfStreamer::finish() {
569 MS->Finish();
570 return true;
571}
572
Frederic Rissb8b43d52015-03-04 22:07:44 +0000573/// \brief Set the current output section to debug_info and change
574/// the MC Dwarf version to \p DwarfVersion.
575void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
576 MS->SwitchSection(MOFI->getDwarfInfoSection());
577 MC->setDwarfVersion(DwarfVersion);
578}
579
580/// \brief Emit the compilation unit header for \p Unit in the
581/// debug_info section.
582///
583/// A Dwarf scetion header is encoded as:
584/// uint32_t Unit length (omiting this field)
585/// uint16_t Version
586/// uint32_t Abbreviation table offset
587/// uint8_t Address size
588///
589/// Leading to a total of 11 bytes.
590void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
591 unsigned Version = Unit.getOrigUnit().getVersion();
592 switchToDebugInfoSection(Version);
593
594 // Emit size of content not including length itself. The size has
595 // already been computed in CompileUnit::computeOffsets(). Substract
596 // 4 to that size to account for the length field.
597 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
598 Asm->EmitInt16(Version);
599 // We share one abbreviations table across all units so it's always at the
600 // start of the section.
601 Asm->EmitInt32(0);
602 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
603}
604
605/// \brief Emit the \p Abbrevs array as the shared abbreviation table
606/// for the linked Dwarf file.
607void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
608 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
609 Asm->emitDwarfAbbrevs(Abbrevs);
610}
611
612/// \brief Recursively emit the DIE tree rooted at \p Die.
613void DwarfStreamer::emitDIE(DIE &Die) {
614 MS->SwitchSection(MOFI->getDwarfInfoSection());
615 Asm->emitDwarfDIE(Die);
616}
617
Frederic Rissef648462015-03-06 17:56:30 +0000618/// \brief Emit the debug_str section stored in \p Pool.
619void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000620 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000621 for (auto *Entry = Pool.getFirstEntry(); Entry;
622 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000623 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000624 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
625}
626
Frederic Riss25440872015-03-13 23:30:31 +0000627/// \brief Emit the debug_range section contents for \p FuncRange by
628/// translating the original \p Entries. The debug_range section
629/// format is totally trivial, consisting just of pairs of address
630/// sized addresses describing the ranges.
631void DwarfStreamer::emitRangesEntries(
632 int64_t UnitPcOffset, uint64_t OrigLowPc,
633 FunctionIntervals::const_iterator FuncRange,
634 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
635 unsigned AddressSize) {
636 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
637
638 // Offset each range by the right amount.
639 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
640 for (const auto &Range : Entries) {
641 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
642 warn("unsupported base address selection operation",
643 "emitting debug_ranges");
644 break;
645 }
646 // Do not emit empty ranges.
647 if (Range.StartAddress == Range.EndAddress)
648 continue;
649
650 // All range entries should lie in the function range.
651 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
652 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
653 warn("inconsistent range data.", "emitting debug_ranges");
654 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
655 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
656 RangesSectionSize += 2 * AddressSize;
657 }
658
659 // Add the terminator entry.
660 MS->EmitIntValue(0, AddressSize);
661 MS->EmitIntValue(0, AddressSize);
662 RangesSectionSize += 2 * AddressSize;
663}
664
Frederic Riss563b1b02015-03-14 03:46:51 +0000665/// \brief Emit the debug_aranges contribution of a unit and
666/// if \p DoDebugRanges is true the debug_range contents for a
667/// compile_unit level DW_AT_ranges attribute (Which are basically the
668/// same thing with a different base address).
669/// Just aggregate all the ranges gathered inside that unit.
670void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
671 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000672 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
673 // Gather the ranges in a vector, so that we can simplify them. The
674 // IntervalMap will have coalesced the non-linked ranges, but here
675 // we want to coalesce the linked addresses.
676 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
677 const auto &FunctionRanges = Unit.getFunctionRanges();
678 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
679 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000680 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
681 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000682
683 // The object addresses where sorted, but again, the linked
684 // addresses might end up in a different order.
685 std::sort(Ranges.begin(), Ranges.end());
686
Frederic Riss563b1b02015-03-14 03:46:51 +0000687 if (!Ranges.empty()) {
688 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
689
Rafael Espindola9ab09232015-03-17 20:07:06 +0000690 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
691 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000692
693 unsigned HeaderSize =
694 sizeof(int32_t) + // Size of contents (w/o this field
695 sizeof(int16_t) + // DWARF ARange version number
696 sizeof(int32_t) + // Offset of CU in the .debug_info section
697 sizeof(int8_t) + // Pointer Size (in bytes)
698 sizeof(int8_t); // Segment Size (in bytes)
699
700 unsigned TupleSize = AddressSize * 2;
701 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
702
703 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000704 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000705 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
706 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
707 Asm->EmitInt8(AddressSize); // Address size
708 Asm->EmitInt8(0); // Segment size
709
Lang Hames9ff69c82015-04-24 19:11:51 +0000710 Asm->OutStreamer->EmitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000711
712 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
713 ++Range) {
714 uint64_t RangeStart = Range->first;
715 MS->EmitIntValue(RangeStart, AddressSize);
716 while ((Range + 1) != End && Range->second == (Range + 1)->first)
717 ++Range;
718 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
719 }
720
721 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000722 Asm->OutStreamer->EmitIntValue(0, AddressSize);
723 Asm->OutStreamer->EmitIntValue(0, AddressSize);
724 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000725 }
726
727 if (!DoDebugRanges)
728 return;
729
730 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
731 // Offset each range by the right amount.
732 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000733 // Emit coalesced ranges.
734 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000735 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000736 while (Range + 1 != End && Range->second == (Range + 1)->first)
737 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000738 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000739 RangesSectionSize += 2 * AddressSize;
740 }
741
742 // Add the terminator entry.
743 MS->EmitIntValue(0, AddressSize);
744 MS->EmitIntValue(0, AddressSize);
745 RangesSectionSize += 2 * AddressSize;
746}
747
Frederic Rissdfb97902015-03-14 15:49:07 +0000748/// \brief Emit location lists for \p Unit and update attribtues to
749/// point to the new entries.
750void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
751 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000752 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000753
754 if (Attributes.empty())
755 return;
756
757 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
758
759 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
760 const DWARFSection &InputSec = Dwarf.getLocSection();
761 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
762 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000763 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000764 int64_t UnitPcOffset = 0;
765 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
766 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
767 if (OrigLowPc != -1ULL)
768 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
769
770 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000771 uint32_t Offset = Attr.first.get();
772 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000773 // This is the quantity to add to the old location address to get
774 // the correct address for the new one.
775 int64_t LocPcOffset = Attr.second + UnitPcOffset;
776 while (Data.isValidOffset(Offset)) {
777 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
778 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
779 LocSectionSize += 2 * AddressSize;
780 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000781 Asm->OutStreamer->EmitIntValue(0, AddressSize);
782 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000783 break;
784 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000785 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
786 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000787 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000788 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000789 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000790 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000791 StringRef(InputSec.Data.substr(Offset, Length)));
792 Offset += Length;
793 LocSectionSize += Length + 2;
794 }
795 }
796}
797
Frederic Riss63786b02015-03-15 20:45:43 +0000798void DwarfStreamer::emitLineTableForUnit(StringRef PrologueBytes,
799 unsigned MinInstLength,
800 std::vector<DWARFDebugLine::Row> &Rows,
801 unsigned PointerSize) {
802 // Switch to the section where the table will be emitted into.
803 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000804 MCSymbol *LineStartSym = MC->createTempSymbol();
805 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000806
807 // The first 4 bytes is the total length of the information for this
808 // compilation unit (not including these 4 bytes for the length).
809 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000810 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000811 // Copy Prologue.
812 MS->EmitBytes(PrologueBytes);
813 LineSectionSize += PrologueBytes.size() + 4;
814
Frederic Rissc3820d02015-03-15 22:20:28 +0000815 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000816 raw_svector_ostream EncodingOS(EncodingBuffer);
817
818 if (Rows.empty()) {
819 // We only have the dummy entry, dsymutil emits an entry with a 0
820 // address in that case.
821 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
822 MS->EmitBytes(EncodingOS.str());
823 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000824 MS->EmitLabel(LineEndSym);
825 return;
826 }
827
828 // Line table state machine fields
829 unsigned FileNum = 1;
830 unsigned LastLine = 1;
831 unsigned Column = 0;
832 unsigned IsStatement = 1;
833 unsigned Isa = 0;
834 uint64_t Address = -1ULL;
835
836 unsigned RowsSinceLastSequence = 0;
837
838 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
839 auto &Row = Rows[Idx];
840
841 int64_t AddressDelta;
842 if (Address == -1ULL) {
843 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
844 MS->EmitULEB128IntValue(PointerSize + 1);
845 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
846 MS->EmitIntValue(Row.Address, PointerSize);
847 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
848 AddressDelta = 0;
849 } else {
850 AddressDelta = (Row.Address - Address) / MinInstLength;
851 }
852
853 // FIXME: code copied and transfromed from
854 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
855 // this code, but the current compatibility requirement with
856 // classic dsymutil makes it hard. Revisit that once this
857 // requirement is dropped.
858
859 if (FileNum != Row.File) {
860 FileNum = Row.File;
861 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
862 MS->EmitULEB128IntValue(FileNum);
863 LineSectionSize += 1 + getULEB128Size(FileNum);
864 }
865 if (Column != Row.Column) {
866 Column = Row.Column;
867 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
868 MS->EmitULEB128IntValue(Column);
869 LineSectionSize += 1 + getULEB128Size(Column);
870 }
871
872 // FIXME: We should handle the discriminator here, but dsymutil
873 // doesn' consider it, thus ignore it for now.
874
875 if (Isa != Row.Isa) {
876 Isa = Row.Isa;
877 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
878 MS->EmitULEB128IntValue(Isa);
879 LineSectionSize += 1 + getULEB128Size(Isa);
880 }
881 if (IsStatement != Row.IsStmt) {
882 IsStatement = Row.IsStmt;
883 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
884 LineSectionSize += 1;
885 }
886 if (Row.BasicBlock) {
887 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
888 LineSectionSize += 1;
889 }
890
891 if (Row.PrologueEnd) {
892 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
893 LineSectionSize += 1;
894 }
895
896 if (Row.EpilogueBegin) {
897 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
898 LineSectionSize += 1;
899 }
900
901 int64_t LineDelta = int64_t(Row.Line) - LastLine;
902 if (!Row.EndSequence) {
903 MCDwarfLineAddr::Encode(*MC, LineDelta, AddressDelta, EncodingOS);
904 MS->EmitBytes(EncodingOS.str());
905 LineSectionSize += EncodingBuffer.size();
906 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000907 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000908 Address = Row.Address;
909 LastLine = Row.Line;
910 RowsSinceLastSequence++;
911 } else {
912 if (LineDelta) {
913 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
914 MS->EmitSLEB128IntValue(LineDelta);
915 LineSectionSize += 1 + getSLEB128Size(LineDelta);
916 }
917 if (AddressDelta) {
918 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
919 MS->EmitULEB128IntValue(AddressDelta);
920 LineSectionSize += 1 + getULEB128Size(AddressDelta);
921 }
922 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
923 MS->EmitBytes(EncodingOS.str());
924 LineSectionSize += EncodingBuffer.size();
925 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000926 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000927 Address = -1ULL;
928 LastLine = FileNum = IsStatement = 1;
929 RowsSinceLastSequence = Column = Isa = 0;
930 }
931 }
932
933 if (RowsSinceLastSequence) {
934 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
935 MS->EmitBytes(EncodingOS.str());
936 LineSectionSize += EncodingBuffer.size();
937 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000938 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000939 }
940
941 MS->EmitLabel(LineEndSym);
942}
943
Frederic Rissbce93ff2015-03-16 02:05:10 +0000944/// \brief Emit the pubnames or pubtypes section contribution for \p
945/// Unit into \p Sec. The data is provided in \p Names.
946void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000947 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000948 const std::vector<CompileUnit::AccelInfo> &Names) {
949 if (Names.empty())
950 return;
951
952 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +0000953 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +0000954 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
955 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +0000956
957 bool HeaderEmitted = false;
958 // Emit the pubnames for this compilation unit.
959 for (const auto &Name : Names) {
960 if (Name.SkipPubSection)
961 continue;
962
963 if (!HeaderEmitted) {
964 // Emit the header.
965 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +0000966 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +0000967 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
968 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
969 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
970 HeaderEmitted = true;
971 }
972 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +0000973 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +0000974 StringRef(Name.Name.data(), Name.Name.size() + 1));
975 }
976
977 if (!HeaderEmitted)
978 return;
979 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +0000980 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +0000981}
982
983/// \brief Emit .debug_pubnames for \p Unit.
984void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
985 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
986 "names", Unit, Unit.getPubnames());
987}
988
989/// \brief Emit .debug_pubtypes for \p Unit.
990void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
991 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
992 "types", Unit, Unit.getPubtypes());
993}
994
Frederic Rissd3455182015-01-28 18:27:01 +0000995/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +0000996///
997/// The link of the dwarf information from the object files will be
998/// driven by the selection of 'root DIEs', which are DIEs that
999/// describe variables or functions that are present in the linked
1000/// binary (and thus have entries in the debug map). All the debug
1001/// information that will be linked (the DIEs, but also the line
1002/// tables, ranges, ...) is derived from that set of root DIEs.
1003///
1004/// The root DIEs are identified because they contain relocations that
1005/// correspond to a debug map entry at specific places (the low_pc for
1006/// a function, the location for a variable). These relocations are
1007/// called ValidRelocs in the DwarfLinker and are gathered as a very
1008/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001009class DwarfLinker {
1010public:
Frederic Rissb9818322015-02-28 00:29:07 +00001011 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1012 : OutputFilename(OutputFilename), Options(Options),
1013 BinHolder(Options.Verbose) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001014
Frederic Rissb8b43d52015-03-04 22:07:44 +00001015 ~DwarfLinker() {
1016 for (auto *Abbrev : Abbreviations)
1017 delete Abbrev;
1018 }
1019
Frederic Rissd3455182015-01-28 18:27:01 +00001020 /// \brief Link the contents of the DebugMap.
1021 bool link(const DebugMap &);
1022
1023private:
Frederic Riss563cba62015-01-28 22:15:14 +00001024 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001025 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001026
1027 /// \brief Called at the end of a debug object link.
1028 void endDebugObject();
1029
Frederic Riss1036e642015-02-13 23:18:22 +00001030 /// \defgroup FindValidRelocations Translate debug map into a list
1031 /// of relevant relocations
1032 ///
1033 /// @{
1034 struct ValidReloc {
1035 uint32_t Offset;
1036 uint32_t Size;
1037 uint64_t Addend;
1038 const DebugMapObject::DebugMapEntry *Mapping;
1039
1040 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1041 const DebugMapObject::DebugMapEntry *Mapping)
1042 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1043
1044 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1045 };
1046
1047 /// \brief The valid relocations for the current DebugMapObject.
1048 /// This vector is sorted by relocation offset.
1049 std::vector<ValidReloc> ValidRelocs;
1050
1051 /// \brief Index into ValidRelocs of the next relocation to
1052 /// consider. As we walk the DIEs in acsending file offset and as
1053 /// ValidRelocs is sorted by file offset, keeping this index
1054 /// uptodate is all we have to do to have a cheap lookup during the
Frederic Riss23e20e92015-03-07 01:25:09 +00001055 /// root DIE selection and during DIE cloning.
Frederic Riss1036e642015-02-13 23:18:22 +00001056 unsigned NextValidReloc;
1057
1058 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1059 const DebugMapObject &DMO);
1060
1061 bool findValidRelocs(const object::SectionRef &Section,
1062 const object::ObjectFile &Obj,
1063 const DebugMapObject &DMO);
1064
1065 void findValidRelocsMachO(const object::SectionRef &Section,
1066 const object::MachOObjectFile &Obj,
1067 const DebugMapObject &DMO);
1068 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +00001069
Frederic Riss84c09a52015-02-13 23:18:34 +00001070 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1071 ///
1072 /// @{
1073 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1074 /// keep. Store that information in \p CU's DIEInfo.
1075 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1076 const DebugMapObject &DMO, CompileUnit &CU,
1077 unsigned Flags);
1078
1079 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1080 enum TravesalFlags {
1081 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1082 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1083 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1084 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
1085 };
1086
1087 /// \brief Mark the passed DIE as well as all the ones it depends on
1088 /// as kept.
1089 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1090 CompileUnit::DIEInfo &MyInfo,
1091 const DebugMapObject &DMO, CompileUnit &CU,
1092 unsigned Flags);
1093
1094 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1095 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1096 unsigned Flags);
1097
1098 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1099 CompileUnit &Unit,
1100 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1101
1102 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1103 CompileUnit &Unit,
1104 CompileUnit::DIEInfo &MyInfo,
1105 unsigned Flags);
1106
1107 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1108 CompileUnit::DIEInfo &Info);
1109 /// @}
1110
Frederic Rissb8b43d52015-03-04 22:07:44 +00001111 /// \defgroup Linking Methods used to link the debug information
1112 ///
1113 /// @{
1114 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1115 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1116 /// stripped out and addresses have been rewritten according to the
1117 /// debug map.
1118 ///
1119 /// \param OutOffset is the offset the cloned DIE in the output
1120 /// compile unit.
Frederic Riss31da3242015-03-11 18:45:52 +00001121 /// \param PCOffset (while cloning a function scope) is the offset
1122 /// applied to the entry point of the function to get the linked address.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001123 ///
1124 /// \returns the root of the cloned tree.
1125 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Frederic Riss31da3242015-03-11 18:45:52 +00001126 int64_t PCOffset, uint32_t OutOffset);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001127
1128 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1129
Frederic Riss31da3242015-03-11 18:45:52 +00001130 /// \brief Information gathered and exchanged between the various
1131 /// clone*Attributes helpers about the attributes of a particular DIE.
1132 struct AttributesInfo {
Frederic Rissbce93ff2015-03-16 02:05:10 +00001133 const char *Name, *MangledName; ///< Names.
1134 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1135
Frederic Riss31da3242015-03-11 18:45:52 +00001136 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1137 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1138
Frederic Rissbce93ff2015-03-16 02:05:10 +00001139 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1140 bool IsDeclaration; ///< Is this DIE only a declaration?
1141
1142 AttributesInfo()
1143 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1144 MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1145 IsDeclaration(false) {}
Frederic Riss31da3242015-03-11 18:45:52 +00001146 };
1147
Frederic Rissb8b43d52015-03-04 22:07:44 +00001148 /// \brief Helper for cloneDIE.
1149 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1150 CompileUnit &U, const DWARFFormValue &Val,
Frederic Riss31da3242015-03-11 18:45:52 +00001151 const AttributeSpec AttrSpec, unsigned AttrSize,
1152 AttributesInfo &AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001153
1154 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +00001155 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1156 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001157
1158 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +00001159 unsigned
1160 cloneDieReferenceAttribute(DIE &Die,
1161 const DWARFDebugInfoEntryMinimal &InputDIE,
1162 AttributeSpec AttrSpec, unsigned AttrSize,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001163 const DWARFFormValue &Val, CompileUnit &Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001164
1165 /// \brief Helper for cloneDIE.
1166 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1167 const DWARFFormValue &Val, unsigned AttrSize);
1168
1169 /// \brief Helper for cloneDIE.
Frederic Riss31da3242015-03-11 18:45:52 +00001170 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1171 const DWARFFormValue &Val,
1172 const CompileUnit &Unit, AttributesInfo &Info);
1173
1174 /// \brief Helper for cloneDIE.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001175 unsigned cloneScalarAttribute(DIE &Die,
1176 const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss25440872015-03-13 23:30:31 +00001177 CompileUnit &U, AttributeSpec AttrSpec,
Frederic Rissdfb97902015-03-14 15:49:07 +00001178 const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001179 AttributesInfo &Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001180
Frederic Riss23e20e92015-03-07 01:25:09 +00001181 /// \brief Helper for cloneDIE.
1182 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1183 bool isLittleEndian);
1184
Frederic Rissb8b43d52015-03-04 22:07:44 +00001185 /// \brief Assign an abbreviation number to \p Abbrev
1186 void AssignAbbrev(DIEAbbrev &Abbrev);
1187
1188 /// \brief FoldingSet that uniques the abbreviations.
1189 FoldingSet<DIEAbbrev> AbbreviationsSet;
1190 /// \brief Storage for the unique Abbreviations.
1191 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1192 /// be changed to a vecot of unique_ptrs.
1193 std::vector<DIEAbbrev *> Abbreviations;
1194
Frederic Riss25440872015-03-13 23:30:31 +00001195 /// \brief Compute and emit debug_ranges section for \p Unit, and
1196 /// patch the attributes referencing it.
1197 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1198
1199 /// \brief Generate and emit the DW_AT_ranges attribute for a
1200 /// compile_unit if it had one.
1201 void generateUnitRanges(CompileUnit &Unit) const;
1202
Frederic Riss63786b02015-03-15 20:45:43 +00001203 /// \brief Extract the line tables fromt he original dwarf, extract
1204 /// the relevant parts according to the linked function ranges and
1205 /// emit the result in the debug_line section.
1206 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1207
Frederic Rissbce93ff2015-03-16 02:05:10 +00001208 /// \brief Emit the accelerator entries for \p Unit.
1209 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1210
Frederic Rissb8b43d52015-03-04 22:07:44 +00001211 /// \brief DIELoc objects that need to be destructed (but not freed!).
1212 std::vector<DIELoc *> DIELocs;
1213 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1214 std::vector<DIEBlock *> DIEBlocks;
1215 /// \brief Allocator used for all the DIEValue objects.
1216 BumpPtrAllocator DIEAlloc;
1217 /// @}
1218
Frederic Riss1b9da422015-02-13 23:18:29 +00001219 /// \defgroup Helpers Various helper methods.
1220 ///
1221 /// @{
1222 const DWARFDebugInfoEntryMinimal *
1223 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
1224 const DWARFDebugInfoEntryMinimal &DIE,
1225 CompileUnit *&ReferencedCU);
1226
1227 CompileUnit *getUnitForOffset(unsigned Offset);
1228
Frederic Rissbce93ff2015-03-16 02:05:10 +00001229 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1230 AttributesInfo &Info);
1231
Frederic Riss1b9da422015-02-13 23:18:29 +00001232 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
Frederic Riss25440872015-03-13 23:30:31 +00001233 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
Frederic Rissc99ea202015-02-28 00:29:11 +00001234
1235 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Riss1b9da422015-02-13 23:18:29 +00001236 /// @}
1237
Frederic Riss563cba62015-01-28 22:15:14 +00001238private:
Frederic Rissd3455182015-01-28 18:27:01 +00001239 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001240 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001241 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001242 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +00001243
1244 /// The units of the current debug map object.
1245 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001246
1247 /// The debug map object curently under consideration.
1248 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001249
1250 /// \brief The Dwarf string pool
1251 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001252
1253 /// \brief This map is keyed by the entry PC of functions in that
1254 /// debug object and the associated value is a pair storing the
1255 /// corresponding end PC and the offset to apply to get the linked
1256 /// address.
1257 ///
1258 /// See startDebugObject() for a more complete description of its use.
1259 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Rissd3455182015-01-28 18:27:01 +00001260};
1261
Frederic Riss1b9da422015-02-13 23:18:29 +00001262/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1263/// returning our CompileUnit object instead.
1264CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1265 auto CU =
1266 std::upper_bound(Units.begin(), Units.end(), Offset,
1267 [](uint32_t LHS, const CompileUnit &RHS) {
1268 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1269 });
1270 return CU != Units.end() ? &*CU : nullptr;
1271}
1272
1273/// \brief Resolve the DIE attribute reference that has been
1274/// extracted in \p RefValue. The resulting DIE migh be in another
1275/// CompileUnit which is stored into \p ReferencedCU.
1276/// \returns null if resolving fails for any reason.
1277const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1278 DWARFFormValue &RefValue, const DWARFUnit &Unit,
1279 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1280 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1281 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1282
1283 if ((RefCU = getUnitForOffset(RefOffset)))
1284 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1285 return RefDie;
1286
1287 reportWarning("could not find referenced DIE", &Unit, &DIE);
1288 return nullptr;
1289}
1290
Frederic Rissbce93ff2015-03-16 02:05:10 +00001291/// \brief Get the potential name and mangled name for the entity
1292/// described by \p Die and store them in \Info if they are not
1293/// already there.
1294/// \returns is a name was found.
1295bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1296 DWARFUnit &U, AttributesInfo &Info) {
1297 // FIXME: a bit wastefull as the first getName might return the
1298 // short name.
1299 if (!Info.MangledName &&
1300 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1301 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1302
1303 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1304 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1305
1306 return Info.Name || Info.MangledName;
1307}
1308
Frederic Riss1b9da422015-02-13 23:18:29 +00001309/// \brief Report a warning to the user, optionaly including
1310/// information about a specific \p DIE related to the warning.
1311void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001312 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001313 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001314 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001315 Context = CurrentDebugObject->getObjectFilename();
1316 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001317
Frederic Rissb9818322015-02-28 00:29:07 +00001318 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001319 return;
1320
1321 errs() << " in DIE:\n";
1322 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1323 6 /* Indent */);
1324}
1325
Frederic Rissc99ea202015-02-28 00:29:11 +00001326bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1327 if (Options.NoOutput)
1328 return true;
1329
Frederic Rissb52cf522015-02-28 00:42:37 +00001330 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001331 return Streamer->init(TheTriple, OutputFilename);
1332}
1333
Frederic Riss563cba62015-01-28 22:15:14 +00001334/// \brief Recursive helper to gather the child->parent relationships in the
1335/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +00001336static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1337 unsigned ParentIdx, CompileUnit &CU) {
Frederic Riss563cba62015-01-28 22:15:14 +00001338 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1339 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
1340
1341 if (DIE->hasChildren())
1342 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1343 Child = Child->getSibling())
Frederic Riss9aa725b2015-02-13 23:18:31 +00001344 gatherDIEParents(Child, MyIdx, CU);
Frederic Riss563cba62015-01-28 22:15:14 +00001345}
1346
Frederic Riss84c09a52015-02-13 23:18:34 +00001347static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1348 switch (Tag) {
1349 default:
1350 return false;
1351 case dwarf::DW_TAG_subprogram:
1352 case dwarf::DW_TAG_lexical_block:
1353 case dwarf::DW_TAG_subroutine_type:
1354 case dwarf::DW_TAG_structure_type:
1355 case dwarf::DW_TAG_class_type:
1356 case dwarf::DW_TAG_union_type:
1357 return true;
1358 }
1359 llvm_unreachable("Invalid Tag");
1360}
1361
Frederic Riss63786b02015-03-15 20:45:43 +00001362void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001363 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +00001364 NextValidReloc = 0;
Frederic Riss63786b02015-03-15 20:45:43 +00001365 // Iterate over the debug map entries and put all the ones that are
1366 // functions (because they have a size) into the Ranges map. This
1367 // map is very similar to the FunctionRanges that are stored in each
1368 // unit, with 2 notable differences:
1369 // - obviously this one is global, while the other ones are per-unit.
1370 // - this one contains not only the functions described in the DIE
1371 // tree, but also the ones that are only in the debug map.
1372 // The latter information is required to reproduce dsymutil's logic
1373 // while linking line tables. The cases where this information
1374 // matters look like bugs that need to be investigated, but for now
1375 // we need to reproduce dsymutil's behavior.
1376 // FIXME: Once we understood exactly if that information is needed,
1377 // maybe totally remove this (or try to use it to do a real
1378 // -gline-tables-only on Darwin.
1379 for (const auto &Entry : Obj.symbols()) {
1380 const auto &Mapping = Entry.getValue();
1381 if (Mapping.Size)
1382 Ranges[Mapping.ObjectAddress] = std::make_pair(
1383 Mapping.ObjectAddress + Mapping.Size,
1384 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1385 }
Frederic Riss563cba62015-01-28 22:15:14 +00001386}
1387
Frederic Riss1036e642015-02-13 23:18:22 +00001388void DwarfLinker::endDebugObject() {
1389 Units.clear();
1390 ValidRelocs.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001391 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001392
1393 for (auto *Block : DIEBlocks)
1394 Block->~DIEBlock();
1395 for (auto *Loc : DIELocs)
1396 Loc->~DIELoc();
1397
1398 DIEBlocks.clear();
1399 DIELocs.clear();
1400 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001401}
1402
1403/// \brief Iterate over the relocations of the given \p Section and
1404/// store the ones that correspond to debug map entries into the
1405/// ValidRelocs array.
1406void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1407 const object::MachOObjectFile &Obj,
1408 const DebugMapObject &DMO) {
1409 StringRef Contents;
1410 Section.getContents(Contents);
1411 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1412
1413 for (const object::RelocationRef &Reloc : Section.relocations()) {
1414 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1415 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1416 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1417 uint64_t Offset64;
1418 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001419 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001420 continue;
1421 }
1422 uint32_t Offset = Offset64;
1423 // Mach-o uses REL relocations, the addend is at the relocation offset.
1424 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1425
1426 auto Sym = Reloc.getSymbol();
1427 if (Sym != Obj.symbol_end()) {
1428 StringRef SymbolName;
1429 if (Sym->getName(SymbolName)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001430 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001431 continue;
1432 }
1433 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
1434 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1435 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1436 // Do not store the addend. The addend was the address of the
1437 // symbol in the object file, the address in the binary that is
1438 // stored in the debug map doesn't need to be offseted.
1439 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1440 }
1441 }
1442}
1443
1444/// \brief Dispatch the valid relocation finding logic to the
1445/// appropriate handler depending on the object file format.
1446bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1447 const object::ObjectFile &Obj,
1448 const DebugMapObject &DMO) {
1449 // Dispatch to the right handler depending on the file type.
1450 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1451 findValidRelocsMachO(Section, *MachOObj, DMO);
1452 else
Frederic Riss1b9da422015-02-13 23:18:29 +00001453 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001454
1455 if (ValidRelocs.empty())
1456 return false;
1457
1458 // Sort the relocations by offset. We will walk the DIEs linearly in
1459 // the file, this allows us to just keep an index in the relocation
1460 // array that we advance during our walk, rather than resorting to
1461 // some associative container. See DwarfLinker::NextValidReloc.
1462 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1463 return true;
1464}
1465
1466/// \brief Look for relocations in the debug_info section that match
1467/// entries in the debug map. These relocations will drive the Dwarf
1468/// link by indicating which DIEs refer to symbols present in the
1469/// linked binary.
1470/// \returns wether there are any valid relocations in the debug info.
1471bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1472 const DebugMapObject &DMO) {
1473 // Find the debug_info section.
1474 for (const object::SectionRef &Section : Obj.sections()) {
1475 StringRef SectionName;
1476 Section.getName(SectionName);
1477 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1478 if (SectionName != "debug_info")
1479 continue;
1480 return findValidRelocs(Section, Obj, DMO);
1481 }
1482 return false;
1483}
Frederic Riss563cba62015-01-28 22:15:14 +00001484
Frederic Riss84c09a52015-02-13 23:18:34 +00001485/// \brief Checks that there is a relocation against an actual debug
1486/// map entry between \p StartOffset and \p NextOffset.
1487///
1488/// This function must be called with offsets in strictly ascending
1489/// order because it never looks back at relocations it already 'went past'.
1490/// \returns true and sets Info.InDebugMap if it is the case.
1491bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1492 CompileUnit::DIEInfo &Info) {
1493 assert(NextValidReloc == 0 ||
1494 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1495 if (NextValidReloc >= ValidRelocs.size())
1496 return false;
1497
1498 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1499
1500 // We might need to skip some relocs that we didn't consider. For
1501 // example the high_pc of a discarded DIE might contain a reloc that
1502 // is in the list because it actually corresponds to the start of a
1503 // function that is in the debug map.
1504 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1505 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1506
1507 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1508 return false;
1509
1510 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Rissb9818322015-02-28 00:29:07 +00001511 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001512 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1513 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1514 ValidReloc.Mapping->getValue().ObjectAddress,
1515 ValidReloc.Mapping->getValue().BinaryAddress);
1516
Frederic Riss31da3242015-03-11 18:45:52 +00001517 Info.AddrAdjust = int64_t(ValidReloc.Mapping->getValue().BinaryAddress) +
1518 ValidReloc.Addend -
1519 ValidReloc.Mapping->getValue().ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001520 Info.InDebugMap = true;
1521 return true;
1522}
1523
1524/// \brief Get the starting and ending (exclusive) offset for the
1525/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1526/// supposed to point to the position of the first attribute described
1527/// by \p Abbrev.
1528/// \return [StartOffset, EndOffset) as a pair.
1529static std::pair<uint32_t, uint32_t>
1530getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1531 unsigned Offset, const DWARFUnit &Unit) {
1532 DataExtractor Data = Unit.getDebugInfoExtractor();
1533
1534 for (unsigned i = 0; i < Idx; ++i)
1535 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1536
1537 uint32_t End = Offset;
1538 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1539
1540 return std::make_pair(Offset, End);
1541}
1542
1543/// \brief Check if a variable describing DIE should be kept.
1544/// \returns updated TraversalFlags.
1545unsigned DwarfLinker::shouldKeepVariableDIE(
1546 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1547 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1548 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1549
1550 // Global variables with constant value can always be kept.
1551 if (!(Flags & TF_InFunctionScope) &&
1552 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1553 MyInfo.InDebugMap = true;
1554 return Flags | TF_Keep;
1555 }
1556
1557 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1558 if (LocationIdx == -1U)
1559 return Flags;
1560
1561 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1562 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1563 uint32_t LocationOffset, LocationEndOffset;
1564 std::tie(LocationOffset, LocationEndOffset) =
1565 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1566
1567 // See if there is a relocation to a valid debug map entry inside
1568 // this variable's location. The order is important here. We want to
1569 // always check in the variable has a valid relocation, so that the
1570 // DIEInfo is filled. However, we don't want a static variable in a
1571 // function to force us to keep the enclosing function.
1572 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1573 (Flags & TF_InFunctionScope))
1574 return Flags;
1575
Frederic Rissb9818322015-02-28 00:29:07 +00001576 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001577 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1578
1579 return Flags | TF_Keep;
1580}
1581
1582/// \brief Check if a function describing DIE should be kept.
1583/// \returns updated TraversalFlags.
1584unsigned DwarfLinker::shouldKeepSubprogramDIE(
1585 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1586 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1587 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1588
1589 Flags |= TF_InFunctionScope;
1590
1591 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1592 if (LowPcIdx == -1U)
1593 return Flags;
1594
1595 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1596 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1597 uint32_t LowPcOffset, LowPcEndOffset;
1598 std::tie(LowPcOffset, LowPcEndOffset) =
1599 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1600
1601 uint64_t LowPc =
1602 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1603 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1604 if (LowPc == -1ULL ||
1605 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1606 return Flags;
1607
Frederic Rissb9818322015-02-28 00:29:07 +00001608 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001609 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1610
Frederic Riss1af75f72015-03-12 18:45:10 +00001611 Flags |= TF_Keep;
1612
1613 DWARFFormValue HighPcValue;
1614 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1615 reportWarning("Function without high_pc. Range will be discarded.\n",
1616 &OrigUnit, &DIE);
1617 return Flags;
1618 }
1619
1620 uint64_t HighPc;
1621 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1622 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1623 } else {
1624 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1625 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1626 }
1627
Frederic Riss63786b02015-03-15 20:45:43 +00001628 // Replace the debug map range with a more accurate one.
1629 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00001630 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1631 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00001632}
1633
1634/// \brief Check if a DIE should be kept.
1635/// \returns updated TraversalFlags.
1636unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1637 CompileUnit &Unit,
1638 CompileUnit::DIEInfo &MyInfo,
1639 unsigned Flags) {
1640 switch (DIE.getTag()) {
1641 case dwarf::DW_TAG_constant:
1642 case dwarf::DW_TAG_variable:
1643 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1644 case dwarf::DW_TAG_subprogram:
1645 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1646 case dwarf::DW_TAG_module:
1647 case dwarf::DW_TAG_imported_module:
1648 case dwarf::DW_TAG_imported_declaration:
1649 case dwarf::DW_TAG_imported_unit:
1650 // We always want to keep these.
1651 return Flags | TF_Keep;
1652 }
1653
1654 return Flags;
1655}
1656
Frederic Riss84c09a52015-02-13 23:18:34 +00001657/// \brief Mark the passed DIE as well as all the ones it depends on
1658/// as kept.
1659///
1660/// This function is called by lookForDIEsToKeep on DIEs that are
1661/// newly discovered to be needed in the link. It recursively calls
1662/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1663/// TraversalFlags to inform it that it's not doing the primary DIE
1664/// tree walk.
1665void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1666 CompileUnit::DIEInfo &MyInfo,
1667 const DebugMapObject &DMO,
1668 CompileUnit &CU, unsigned Flags) {
1669 const DWARFUnit &Unit = CU.getOrigUnit();
1670 MyInfo.Keep = true;
1671
1672 // First mark all the parent chain as kept.
1673 unsigned AncestorIdx = MyInfo.ParentIdx;
1674 while (!CU.getInfo(AncestorIdx).Keep) {
1675 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1676 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1677 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1678 }
1679
1680 // Then we need to mark all the DIEs referenced by this DIE's
1681 // attributes as kept.
1682 DataExtractor Data = Unit.getDebugInfoExtractor();
1683 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1684 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1685
1686 // Mark all DIEs referenced through atttributes as kept.
1687 for (const auto &AttrSpec : Abbrev->attributes()) {
1688 DWARFFormValue Val(AttrSpec.Form);
1689
1690 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1691 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1692 continue;
1693 }
1694
1695 Val.extractValue(Data, &Offset, &Unit);
1696 CompileUnit *ReferencedCU;
1697 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1698 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1699 TF_Keep | TF_DependencyWalk);
1700 }
1701}
1702
1703/// \brief Recursively walk the \p DIE tree and look for DIEs to
1704/// keep. Store that information in \p CU's DIEInfo.
1705///
1706/// This function is the entry point of the DIE selection
1707/// algorithm. It is expected to walk the DIE tree in file order and
1708/// (though the mediation of its helper) call hasValidRelocation() on
1709/// each DIE that might be a 'root DIE' (See DwarfLinker class
1710/// comment).
1711/// While walking the dependencies of root DIEs, this function is
1712/// also called, but during these dependency walks the file order is
1713/// not respected. The TF_DependencyWalk flag tells us which kind of
1714/// traversal we are currently doing.
1715void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1716 const DebugMapObject &DMO, CompileUnit &CU,
1717 unsigned Flags) {
1718 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1719 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1720 bool AlreadyKept = MyInfo.Keep;
1721
1722 // If the Keep flag is set, we are marking a required DIE's
1723 // dependencies. If our target is already marked as kept, we're all
1724 // set.
1725 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1726 return;
1727
1728 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1729 // because it would screw up the relocation finding logic.
1730 if (!(Flags & TF_DependencyWalk))
1731 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1732
1733 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1734 if (!AlreadyKept && (Flags & TF_Keep))
1735 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1736
1737 // The TF_ParentWalk flag tells us that we are currently walking up
1738 // the parent chain of a required DIE, and we don't want to mark all
1739 // the children of the parents as kept (consider for example a
1740 // DW_TAG_namespace node in the parent chain). There are however a
1741 // set of DIE types for which we want to ignore that directive and still
1742 // walk their children.
1743 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1744 Flags &= ~TF_ParentWalk;
1745
1746 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1747 return;
1748
1749 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1750 Child = Child->getSibling())
1751 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1752}
1753
Frederic Rissb8b43d52015-03-04 22:07:44 +00001754/// \brief Assign an abbreviation numer to \p Abbrev.
1755///
1756/// Our DIEs get freed after every DebugMapObject has been processed,
1757/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1758/// the instances hold by the DIEs. When we encounter an abbreviation
1759/// that we don't know, we create a permanent copy of it.
1760void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1761 // Check the set for priors.
1762 FoldingSetNodeID ID;
1763 Abbrev.Profile(ID);
1764 void *InsertToken;
1765 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1766
1767 // If it's newly added.
1768 if (InSet) {
1769 // Assign existing abbreviation number.
1770 Abbrev.setNumber(InSet->getNumber());
1771 } else {
1772 // Add to abbreviation list.
1773 Abbreviations.push_back(
1774 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1775 for (const auto &Attr : Abbrev.getData())
1776 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1777 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1778 // Assign the unique abbreviation number.
1779 Abbrev.setNumber(Abbreviations.size());
1780 Abbreviations.back()->setNumber(Abbreviations.size());
1781 }
1782}
1783
1784/// \brief Clone a string attribute described by \p AttrSpec and add
1785/// it to \p Die.
1786/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00001787unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1788 const DWARFFormValue &Val,
1789 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001790 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00001791 const char *String = *Val.getAsCString(&U);
1792 unsigned Offset = StringPool.getStringOffset(String);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001793 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001794 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001795 return 4;
1796}
1797
1798/// \brief Clone an attribute referencing another DIE and add
1799/// it to \p Die.
1800/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00001801unsigned DwarfLinker::cloneDieReferenceAttribute(
1802 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1803 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001804 CompileUnit &Unit) {
1805 uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
Frederic Riss9833de62015-03-06 23:22:53 +00001806 DIE *NewRefDie = nullptr;
1807 CompileUnit *RefUnit = nullptr;
1808 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1809
1810 if (!(RefUnit = getUnitForOffset(Ref)) ||
1811 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1812 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1813 if (!AttributeString)
1814 AttributeString = "DW_AT_???";
1815 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1816 ". Dropping.",
Frederic Riss6afcfce2015-03-13 18:35:57 +00001817 &Unit.getOrigUnit(), &InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00001818 return 0;
1819 }
1820
1821 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1822 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1823 if (!RefInfo.Clone) {
1824 assert(Ref > InputDIE.getOffset());
1825 // We haven't cloned this DIE yet. Just create an empty one and
1826 // store it. It'll get really cloned when we process it.
1827 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1828 }
1829 NewRefDie = RefInfo.Clone;
1830
1831 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1832 // We cannot currently rely on a DIEEntry to emit ref_addr
1833 // references, because the implementation calls back to DwarfDebug
1834 // to find the unit offset. (We don't have a DwarfDebug)
1835 // FIXME: we should be able to design DIEEntry reliance on
1836 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001837 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00001838 if (Ref < InputDIE.getOffset()) {
1839 // We must have already cloned that DIE.
1840 uint32_t NewRefOffset =
1841 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001842 Attr = NewRefOffset;
Frederic Riss9833de62015-03-06 23:22:53 +00001843 } else {
1844 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001845 Attr = 0xBADDEF;
Duncan P. N. Exon Smith88a8fc52015-05-27 22:44:06 +00001846 Unit.noteForwardReference(NewRefDie, RefUnit, PatchLocation(Die));
Frederic Riss9833de62015-03-06 23:22:53 +00001847 }
1848 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001849 DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00001850 return AttrSize;
1851 }
1852
Frederic Rissb8b43d52015-03-04 22:07:44 +00001853 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001854 DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001855 return AttrSize;
1856}
1857
1858/// \brief Clone an attribute of block form (locations, constants) and add
1859/// it to \p Die.
1860/// \returns the size of the new attribute.
1861unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1862 const DWARFFormValue &Val,
1863 unsigned AttrSize) {
1864 DIE *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001865 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001866 DIELoc *Loc = nullptr;
1867 DIEBlock *Block = nullptr;
1868 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00001869 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001870 Loc = new (DIEAlloc) DIELoc;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001871 DIELocs.push_back(Loc);
1872 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001873 Block = new (DIEAlloc) DIEBlock;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001874 DIEBlocks.push_back(Block);
1875 }
1876 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00001877
1878 if (Loc)
1879 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1880 dwarf::Form(AttrSpec.Form), Loc);
1881 else
1882 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1883 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001884 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1885 for (auto Byte : Bytes)
1886 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001887 DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001888 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1889 // the DIE class, this if could be replaced by
1890 // Attr->setSize(Bytes.size()).
1891 if (Streamer) {
1892 if (Loc)
1893 Loc->ComputeSize(&Streamer->getAsmPrinter());
1894 else
1895 Block->ComputeSize(&Streamer->getAsmPrinter());
1896 }
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00001897 Die.addValue(Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001898 return AttrSize;
1899}
1900
Frederic Riss31da3242015-03-11 18:45:52 +00001901/// \brief Clone an address attribute and add it to \p Die.
1902/// \returns the size of the new attribute.
1903unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1904 const DWARFFormValue &Val,
1905 const CompileUnit &Unit,
1906 AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001907 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00001908 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1909 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1910 Die.getTag() == dwarf::DW_TAG_lexical_block)
1911 Addr += Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001912 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1913 Addr = Unit.getLowPc();
1914 if (Addr == UINT64_MAX)
1915 return 0;
1916 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00001917 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00001918 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001919 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1920 if (uint64_t HighPc = Unit.getHighPc())
1921 Addr = HighPc;
1922 else
1923 return 0;
1924 } else
1925 // If we have a high_pc recorded for the input DIE, use
1926 // it. Otherwise (when no relocations where applied) just use the
1927 // one we just decoded.
1928 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00001929 }
1930
1931 Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001932 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00001933 return Unit.getOrigUnit().getAddressByteSize();
1934}
1935
Frederic Rissb8b43d52015-03-04 22:07:44 +00001936/// \brief Clone a scalar attribute and add it to \p Die.
1937/// \returns the size of the new attribute.
1938unsigned DwarfLinker::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00001939 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00001940 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001941 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001942 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001943 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1944 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1945 if (Unit.getLowPc() == -1ULL)
1946 return 0;
1947 // Dwarf >= 4 high_pc is an size, not an address.
1948 Value = Unit.getHighPc() - Unit.getLowPc();
1949 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00001950 Value = *Val.getAsSectionOffset();
1951 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1952 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001953 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1954 Value = *OptionalValue;
1955 else {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001956 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
1957 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001958 return 0;
1959 }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001960 DIEInteger Attr(Value);
Frederic Riss25440872015-03-13 23:30:31 +00001961 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith88a8fc52015-05-27 22:44:06 +00001962 Unit.noteRangeAttribute(Die, PatchLocation(Die));
Frederic Rissdfb97902015-03-14 15:49:07 +00001963 // A more generic way to check for location attributes would be
1964 // nice, but it's very unlikely that any other attribute needs a
1965 // location list.
1966 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1967 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith88a8fc52015-05-27 22:44:06 +00001968 Unit.noteLocationAttribute(PatchLocation(Die), Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00001969 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1970 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00001971
Frederic Rissb8b43d52015-03-04 22:07:44 +00001972 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Frederic Riss25440872015-03-13 23:30:31 +00001973 Attr);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001974 return AttrSize;
1975}
1976
1977/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1978/// value \p Val, and add it to \p Die.
1979/// \returns the size of the cloned attribute.
1980unsigned DwarfLinker::cloneAttribute(DIE &Die,
1981 const DWARFDebugInfoEntryMinimal &InputDIE,
1982 CompileUnit &Unit,
1983 const DWARFFormValue &Val,
1984 const AttributeSpec AttrSpec,
Frederic Riss31da3242015-03-11 18:45:52 +00001985 unsigned AttrSize, AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001986 const DWARFUnit &U = Unit.getOrigUnit();
1987
1988 switch (AttrSpec.Form) {
1989 case dwarf::DW_FORM_strp:
1990 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00001991 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001992 case dwarf::DW_FORM_ref_addr:
1993 case dwarf::DW_FORM_ref1:
1994 case dwarf::DW_FORM_ref2:
1995 case dwarf::DW_FORM_ref4:
1996 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00001997 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001998 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001999 case dwarf::DW_FORM_block:
2000 case dwarf::DW_FORM_block1:
2001 case dwarf::DW_FORM_block2:
2002 case dwarf::DW_FORM_block4:
2003 case dwarf::DW_FORM_exprloc:
2004 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2005 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002006 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002007 case dwarf::DW_FORM_data1:
2008 case dwarf::DW_FORM_data2:
2009 case dwarf::DW_FORM_data4:
2010 case dwarf::DW_FORM_data8:
2011 case dwarf::DW_FORM_udata:
2012 case dwarf::DW_FORM_sdata:
2013 case dwarf::DW_FORM_sec_offset:
2014 case dwarf::DW_FORM_flag:
2015 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002016 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2017 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002018 default:
2019 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2020 &InputDIE);
2021 }
2022
2023 return 0;
2024}
2025
Frederic Riss23e20e92015-03-07 01:25:09 +00002026/// \brief Apply the valid relocations found by findValidRelocs() to
2027/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2028/// in the debug_info section.
2029///
2030/// Like for findValidRelocs(), this function must be called with
2031/// monotonic \p BaseOffset values.
2032///
2033/// \returns wether any reloc has been applied.
2034bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2035 uint32_t BaseOffset, bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002036 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002037 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2038 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002039 if (NextValidReloc >= ValidRelocs.size())
2040 return false;
2041
2042 // Skip relocs that haven't been applied.
2043 while (NextValidReloc < ValidRelocs.size() &&
2044 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2045 ++NextValidReloc;
2046
2047 bool Applied = false;
2048 uint64_t EndOffset = BaseOffset + Data.size();
2049 while (NextValidReloc < ValidRelocs.size() &&
2050 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2051 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2052 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2053 assert(ValidReloc.Offset - BaseOffset < Data.size());
2054 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2055 char Buf[8];
2056 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2057 Value += ValidReloc.Addend;
2058 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2059 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2060 Buf[i] = uint8_t(Value >> (Index * 8));
2061 }
2062 assert(ValidReloc.Size <= sizeof(Buf));
2063 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2064 Applied = true;
2065 }
2066
2067 return Applied;
2068}
2069
Frederic Rissbce93ff2015-03-16 02:05:10 +00002070static bool isTypeTag(uint16_t Tag) {
2071 switch (Tag) {
2072 case dwarf::DW_TAG_array_type:
2073 case dwarf::DW_TAG_class_type:
2074 case dwarf::DW_TAG_enumeration_type:
2075 case dwarf::DW_TAG_pointer_type:
2076 case dwarf::DW_TAG_reference_type:
2077 case dwarf::DW_TAG_string_type:
2078 case dwarf::DW_TAG_structure_type:
2079 case dwarf::DW_TAG_subroutine_type:
2080 case dwarf::DW_TAG_typedef:
2081 case dwarf::DW_TAG_union_type:
2082 case dwarf::DW_TAG_ptr_to_member_type:
2083 case dwarf::DW_TAG_set_type:
2084 case dwarf::DW_TAG_subrange_type:
2085 case dwarf::DW_TAG_base_type:
2086 case dwarf::DW_TAG_const_type:
2087 case dwarf::DW_TAG_constant:
2088 case dwarf::DW_TAG_file_type:
2089 case dwarf::DW_TAG_namelist:
2090 case dwarf::DW_TAG_packed_type:
2091 case dwarf::DW_TAG_volatile_type:
2092 case dwarf::DW_TAG_restrict_type:
2093 case dwarf::DW_TAG_interface_type:
2094 case dwarf::DW_TAG_unspecified_type:
2095 case dwarf::DW_TAG_shared_type:
2096 return true;
2097 default:
2098 break;
2099 }
2100 return false;
2101}
2102
Frederic Rissb8b43d52015-03-04 22:07:44 +00002103/// \brief Recursively clone \p InputDIE's subtrees that have been
2104/// selected to appear in the linked output.
2105///
2106/// \param OutOffset is the Offset where the newly created DIE will
2107/// lie in the linked compile unit.
2108///
2109/// \returns the cloned DIE object or null if nothing was selected.
2110DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss31da3242015-03-11 18:45:52 +00002111 CompileUnit &Unit, int64_t PCOffset,
2112 uint32_t OutOffset) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002113 DWARFUnit &U = Unit.getOrigUnit();
2114 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002115 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002116
2117 // Should the DIE appear in the output?
2118 if (!Unit.getInfo(Idx).Keep)
2119 return nullptr;
2120
2121 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002122 // The DIE might have been already created by a forward reference
2123 // (see cloneDieReferenceAttribute()).
2124 DIE *Die = Info.Clone;
2125 if (!Die)
2126 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
2127 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002128 Die->setOffset(OutOffset);
2129
2130 // Extract and clone every attribute.
2131 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00002132 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002133 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002134
2135 // We could copy the data only if we need to aply a relocation to
2136 // it. After testing, it seems there is no performance downside to
2137 // doing the copy unconditionally, and it makes the code simpler.
2138 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2139 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2140 // Modify the copy with relocated addresses.
Frederic Riss31da3242015-03-11 18:45:52 +00002141 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2142 // If we applied relocations, we store the value of high_pc that was
2143 // potentially stored in the input DIE. If high_pc is an address
2144 // (Dwarf version == 2), then it might have been relocated to a
2145 // totally unrelated value (because the end address in the object
2146 // file might be start address of another function which got moved
2147 // independantly by the linker). The computation of the actual
2148 // high_pc value is done in cloneAddressAttribute().
2149 AttrInfo.OrigHighPc =
2150 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2151 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002152
2153 // Reset the Offset to 0 as we will be working on the local copy of
2154 // the data.
2155 Offset = 0;
2156
Frederic Rissb8b43d52015-03-04 22:07:44 +00002157 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2158 Offset += getULEB128Size(Abbrev->getCode());
2159
Frederic Riss31da3242015-03-11 18:45:52 +00002160 // We are entering a subprogram. Get and propagate the PCOffset.
2161 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2162 PCOffset = Info.AddrAdjust;
2163 AttrInfo.PCOffset = PCOffset;
2164
Frederic Rissb8b43d52015-03-04 22:07:44 +00002165 for (const auto &AttrSpec : Abbrev->attributes()) {
2166 DWARFFormValue Val(AttrSpec.Form);
2167 uint32_t AttrSize = Offset;
2168 Val.extractValue(Data, &Offset, &U);
2169 AttrSize = Offset - AttrSize;
2170
Frederic Riss31da3242015-03-11 18:45:52 +00002171 OutOffset +=
2172 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002173 }
2174
Frederic Rissbce93ff2015-03-16 02:05:10 +00002175 // Look for accelerator entries.
2176 uint16_t Tag = InputDIE.getTag();
2177 // FIXME: This is slightly wrong. An inline_subroutine without a
2178 // low_pc, but with AT_ranges might be interesting to get into the
2179 // accelerator tables too. For now stick with dsymutil's behavior.
2180 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2181 Tag != dwarf::DW_TAG_compile_unit &&
2182 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2183 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2184 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2185 AttrInfo.MangledNameOffset,
2186 Tag == dwarf::DW_TAG_inlined_subroutine);
2187 if (AttrInfo.Name)
2188 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2189 Tag == dwarf::DW_TAG_inlined_subroutine);
2190 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2191 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2192 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2193 }
2194
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002195 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002196 // If a scope DIE is kept, we must have kept at least one child. If
2197 // it's not the case, we'll just be emitting one wasteful end of
2198 // children marker, but things won't break.
2199 if (InputDIE.hasChildren())
2200 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2201 // Assign a permanent abbrev number
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002202 AssignAbbrev(NewAbbrev);
2203 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002204
2205 // Add the size of the abbreviation number to the output offset.
2206 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2207
2208 if (!Abbrev->hasChildren()) {
2209 // Update our size.
2210 Die->setSize(OutOffset - Die->getOffset());
2211 return Die;
2212 }
2213
2214 // Recursively clone children.
2215 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2216 Child = Child->getSibling()) {
Frederic Riss31da3242015-03-11 18:45:52 +00002217 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002218 Die->addChild(std::unique_ptr<DIE>(Clone));
2219 OutOffset = Clone->getOffset() + Clone->getSize();
2220 }
2221 }
2222
2223 // Account for the end of children marker.
2224 OutOffset += sizeof(int8_t);
2225 // Update our size.
2226 Die->setSize(OutOffset - Die->getOffset());
2227 return Die;
2228}
2229
Frederic Riss25440872015-03-13 23:30:31 +00002230/// \brief Patch the input object file relevant debug_ranges entries
2231/// and emit them in the output file. Update the relevant attributes
2232/// to point at the new entries.
2233void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2234 DWARFContext &OrigDwarf) const {
2235 DWARFDebugRangeList RangeList;
2236 const auto &FunctionRanges = Unit.getFunctionRanges();
2237 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2238 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2239 OrigDwarf.isLittleEndian(), AddressSize);
2240 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2241 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002242 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002243 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2244 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2245 // Ranges addresses are based on the unit's low_pc. Compute the
2246 // offset we need to apply to adapt to the the new unit's low_pc.
2247 int64_t UnitPcOffset = 0;
2248 if (OrigLowPc != -1ULL)
2249 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2250
2251 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002252 uint32_t Offset = RangeAttribute.get();
2253 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002254 RangeList.extract(RangeExtractor, &Offset);
2255 const auto &Entries = RangeList.getEntries();
2256 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2257
2258 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2259 First.StartAddress >= CurrRange.stop()) {
2260 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2261 if (CurrRange == InvalidRange ||
2262 CurrRange.start() > First.StartAddress + OrigLowPc) {
2263 reportWarning("no mapping for range.");
2264 continue;
2265 }
2266 }
2267
2268 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2269 AddressSize);
2270 }
2271}
2272
Frederic Riss563b1b02015-03-14 03:46:51 +00002273/// \brief Generate the debug_aranges entries for \p Unit and if the
2274/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2275/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002276/// FIXME: this could actually be done right in patchRangesForUnit,
2277/// but for the sake of initial bit-for-bit compatibility with legacy
2278/// dsymutil, we have to do it in a delayed pass.
2279void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002280 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002281 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002282 Attr->set(Streamer->getRangesSectionSize());
2283 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002284}
2285
Frederic Riss63786b02015-03-15 20:45:43 +00002286/// \brief Insert the new line info sequence \p Seq into the current
2287/// set of already linked line info \p Rows.
2288static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2289 std::vector<DWARFDebugLine::Row> &Rows) {
2290 if (Seq.empty())
2291 return;
2292
2293 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2294 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2295 Seq.clear();
2296 return;
2297 }
2298
2299 auto InsertPoint = std::lower_bound(
2300 Rows.begin(), Rows.end(), Seq.front(),
2301 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2302 return LHS.Address < RHS.Address;
2303 });
2304
2305 // FIXME: this only removes the unneeded end_sequence if the
2306 // sequences have been inserted in order. using a global sort like
2307 // described in patchLineTableForUnit() and delaying the end_sequene
2308 // elimination to emitLineTableForUnit() we can get rid of all of them.
2309 if (InsertPoint != Rows.end() &&
2310 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2311 *InsertPoint = Seq.front();
2312 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2313 } else {
2314 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2315 }
2316
2317 Seq.clear();
2318}
2319
2320/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2321/// recreate a relocated version of these for the address ranges that
2322/// are present in the binary.
2323void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2324 DWARFContext &OrigDwarf) {
2325 const DWARFDebugInfoEntryMinimal *CUDie =
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002326 Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002327 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2328 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2329 if (StmtList == -1ULL)
2330 return;
2331
2332 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2333 if (auto *OutputDIE = Unit.getOutputUnitDIE()) {
Duncan P. N. Exon Smithb04fb5e2015-05-28 18:55:38 +00002334 auto Stmt = std::find_if(OutputDIE->values_begin(), OutputDIE->values_end(),
Duncan P. N. Exon Smith88a8fc52015-05-27 22:44:06 +00002335 [](const DIEValue &Value) {
2336 return Value.getAttribute() == dwarf::DW_AT_stmt_list;
2337 });
Duncan P. N. Exon Smithb04fb5e2015-05-28 18:55:38 +00002338 assert(Stmt != OutputDIE->values_end() &&
Duncan P. N. Exon Smith88a8fc52015-05-27 22:44:06 +00002339 "Didn't find DW_AT_stmt_list in cloned DIE!");
Duncan P. N. Exon Smithb04fb5e2015-05-28 18:55:38 +00002340 OutputDIE->setValue(Stmt - OutputDIE->values_begin(),
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002341 DIEValue(Stmt->getAttribute(), Stmt->getForm(),
2342 DIEInteger(Streamer->getLineSectionSize())));
Frederic Riss63786b02015-03-15 20:45:43 +00002343 }
2344
2345 // Parse the original line info for the unit.
2346 DWARFDebugLine::LineTable LineTable;
2347 uint32_t StmtOffset = StmtList;
2348 StringRef LineData = OrigDwarf.getLineSection().Data;
2349 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2350 Unit.getOrigUnit().getAddressByteSize());
2351 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2352 &StmtOffset);
2353
2354 // This vector is the output line table.
2355 std::vector<DWARFDebugLine::Row> NewRows;
2356 NewRows.reserve(LineTable.Rows.size());
2357
2358 // Current sequence of rows being extracted, before being inserted
2359 // in NewRows.
2360 std::vector<DWARFDebugLine::Row> Seq;
2361 const auto &FunctionRanges = Unit.getFunctionRanges();
2362 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2363
2364 // FIXME: This logic is meant to generate exactly the same output as
2365 // Darwin's classic dsynutil. There is a nicer way to implement this
2366 // by simply putting all the relocated line info in NewRows and simply
2367 // sorting NewRows before passing it to emitLineTableForUnit. This
2368 // should be correct as sequences for a function should stay
2369 // together in the sorted output. There are a few corner cases that
2370 // look suspicious though, and that required to implement the logic
2371 // this way. Revisit that once initial validation is finished.
2372
2373 // Iterate over the object file line info and extract the sequences
2374 // that correspond to linked functions.
2375 for (auto &Row : LineTable.Rows) {
2376 // Check wether we stepped out of the range. The range is
2377 // half-open, but consider accept the end address of the range if
2378 // it is marked as end_sequence in the input (because in that
2379 // case, the relocation offset is accurate and that entry won't
2380 // serve as the start of another function).
2381 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2382 Row.Address > CurrRange.stop() ||
2383 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2384 // We just stepped out of a known range. Insert a end_sequence
2385 // corresponding to the end of the range.
2386 uint64_t StopAddress = CurrRange != InvalidRange
2387 ? CurrRange.stop() + CurrRange.value()
2388 : -1ULL;
2389 CurrRange = FunctionRanges.find(Row.Address);
2390 bool CurrRangeValid =
2391 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2392 if (!CurrRangeValid) {
2393 CurrRange = InvalidRange;
2394 if (StopAddress != -1ULL) {
2395 // Try harder by looking in the DebugMapObject function
2396 // ranges map. There are corner cases where this finds a
2397 // valid entry. It's unclear if this is right or wrong, but
2398 // for now do as dsymutil.
2399 // FIXME: Understand exactly what cases this addresses and
2400 // potentially remove it along with the Ranges map.
2401 auto Range = Ranges.lower_bound(Row.Address);
2402 if (Range != Ranges.begin() && Range != Ranges.end())
2403 --Range;
2404
2405 if (Range != Ranges.end() && Range->first <= Row.Address &&
2406 Range->second.first >= Row.Address) {
2407 StopAddress = Row.Address + Range->second.second;
2408 }
2409 }
2410 }
2411 if (StopAddress != -1ULL && !Seq.empty()) {
2412 // Insert end sequence row with the computed end address, but
2413 // the same line as the previous one.
2414 Seq.emplace_back(Seq.back());
2415 Seq.back().Address = StopAddress;
2416 Seq.back().EndSequence = 1;
2417 Seq.back().PrologueEnd = 0;
2418 Seq.back().BasicBlock = 0;
2419 Seq.back().EpilogueBegin = 0;
2420 insertLineSequence(Seq, NewRows);
2421 }
2422
2423 if (!CurrRangeValid)
2424 continue;
2425 }
2426
2427 // Ignore empty sequences.
2428 if (Row.EndSequence && Seq.empty())
2429 continue;
2430
2431 // Relocate row address and add it to the current sequence.
2432 Row.Address += CurrRange.value();
2433 Seq.emplace_back(Row);
2434
2435 if (Row.EndSequence)
2436 insertLineSequence(Seq, NewRows);
2437 }
2438
2439 // Finished extracting, now emit the line tables.
2440 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2441 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2442 // prologue over and that works because we act as both producer and
2443 // consumer. It would be nicer to have a real configurable line
2444 // table emitter.
2445 if (LineTable.Prologue.Version != 2 ||
2446 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2447 LineTable.Prologue.LineBase != -5 || LineTable.Prologue.LineRange != 14 ||
2448 LineTable.Prologue.OpcodeBase != 13)
2449 reportWarning("line table paramters mismatch. Cannot emit.");
2450 else
2451 Streamer->emitLineTableForUnit(LineData.slice(StmtList + 4, PrologueEnd),
2452 LineTable.Prologue.MinInstLength, NewRows,
2453 Unit.getOrigUnit().getAddressByteSize());
2454}
2455
Frederic Rissbce93ff2015-03-16 02:05:10 +00002456void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2457 Streamer->emitPubNamesForUnit(Unit);
2458 Streamer->emitPubTypesForUnit(Unit);
2459}
2460
Frederic Rissd3455182015-01-28 18:27:01 +00002461bool DwarfLinker::link(const DebugMap &Map) {
2462
2463 if (Map.begin() == Map.end()) {
2464 errs() << "Empty debug map.\n";
2465 return false;
2466 }
2467
Frederic Rissc99ea202015-02-28 00:29:11 +00002468 if (!createStreamer(Map.getTriple(), OutputFilename))
2469 return false;
2470
Frederic Rissb8b43d52015-03-04 22:07:44 +00002471 // Size of the DIEs (and headers) generated for the linked output.
2472 uint64_t OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00002473 // A unique ID that identifies each compile unit.
2474 unsigned UnitID = 0;
Frederic Rissd3455182015-01-28 18:27:01 +00002475 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002476 CurrentDebugObject = Obj.get();
2477
Frederic Rissb9818322015-02-28 00:29:07 +00002478 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00002479 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
2480 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
2481 if (std::error_code EC = ErrOrObj.getError()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002482 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
Frederic Rissd3455182015-01-28 18:27:01 +00002483 continue;
2484 }
2485
Frederic Riss1036e642015-02-13 23:18:22 +00002486 // Look for relocations that correspond to debug map entries.
2487 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00002488 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00002489 outs() << "No valid relocations found. Skipping.\n";
2490 continue;
2491 }
2492
Frederic Riss563cba62015-01-28 22:15:14 +00002493 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00002494 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00002495 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00002496
Frederic Riss563cba62015-01-28 22:15:14 +00002497 // In a first phase, just read in the debug info and store the DIE
2498 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00002499 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002500 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00002501 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00002502 outs() << "Input compilation unit:";
2503 CUDie->dump(outs(), CU.get(), 0);
2504 }
Frederic Riss3cced052015-03-14 03:46:40 +00002505 Units.emplace_back(*CU, UnitID++);
Frederic Riss9aa725b2015-02-13 23:18:31 +00002506 gatherDIEParents(CUDie, 0, Units.back());
Frederic Rissd3455182015-01-28 18:27:01 +00002507 }
Frederic Riss563cba62015-01-28 22:15:14 +00002508
Frederic Riss84c09a52015-02-13 23:18:34 +00002509 // Then mark all the DIEs that need to be present in the linked
2510 // output and collect some information about them. Note that this
2511 // loop can not be merged with the previous one becaue cross-cu
2512 // references require the ParentIdx to be setup for every CU in
2513 // the object file before calling this.
2514 for (auto &CurrentUnit : Units)
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002515 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00002516 CurrentUnit, 0);
2517
Frederic Riss23e20e92015-03-07 01:25:09 +00002518 // The calls to applyValidRelocs inside cloneDIE will walk the
2519 // reloc array again (in the same way findValidRelocsInDebugInfo()
2520 // did). We need to reset the NextValidReloc index to the beginning.
2521 NextValidReloc = 0;
2522
Frederic Rissb8b43d52015-03-04 22:07:44 +00002523 // Construct the output DIE tree by cloning the DIEs we chose to
2524 // keep above. If there are no valid relocs, then there's nothing
2525 // to clone/emit.
2526 if (!ValidRelocs.empty())
2527 for (auto &CurrentUnit : Units) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002528 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00002529 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Riss31da3242015-03-11 18:45:52 +00002530 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
2531 11 /* Unit Header size */);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002532 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00002533 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Riss63786b02015-03-15 20:45:43 +00002534 if (Options.NoOutput)
2535 continue;
2536 // FIXME: for compatibility with the classic dsymutil, we emit
2537 // an empty line table for the unit, even if the unit doesn't
2538 // actually exist in the DIE tree.
2539 patchLineTableForUnit(CurrentUnit, DwarfContext);
2540 if (!OutputDIE)
Frederic Riss25440872015-03-13 23:30:31 +00002541 continue;
2542 patchRangesForUnit(CurrentUnit, DwarfContext);
Frederic Rissdfb97902015-03-14 15:49:07 +00002543 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002544 emitAcceleratorEntriesForUnit(CurrentUnit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002545 }
2546
2547 // Emit all the compile unit's debug information.
2548 if (!ValidRelocs.empty() && !Options.NoOutput)
2549 for (auto &CurrentUnit : Units) {
Frederic Riss25440872015-03-13 23:30:31 +00002550 generateUnitRanges(CurrentUnit);
Frederic Riss9833de62015-03-06 23:22:53 +00002551 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002552 Streamer->emitCompileUnitHeader(CurrentUnit);
2553 if (!CurrentUnit.getOutputUnitDIE())
2554 continue;
2555 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
2556 }
2557
Frederic Riss563cba62015-01-28 22:15:14 +00002558 // Clean-up before starting working on the next object.
2559 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00002560 }
2561
Frederic Rissb8b43d52015-03-04 22:07:44 +00002562 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00002563 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002564 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00002565 Streamer->emitStrings(StringPool);
2566 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002567
Frederic Rissc99ea202015-02-28 00:29:11 +00002568 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00002569}
2570}
Frederic Rissd3455182015-01-28 18:27:01 +00002571
Frederic Rissb9818322015-02-28 00:29:07 +00002572bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
2573 const LinkOptions &Options) {
2574 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00002575 return Linker.link(DM);
2576}
2577}
Frederic Riss231f7142014-12-12 17:31:24 +00002578}