blob: a678a01f8dab1b5af87c728c1ea043c286256537 [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 {
Frederic Rissf37964c2015-06-05 20:27:07 +0000189 StringRef Name; ///< Name of the entry.
190 const DIE *Die; ///< DIE this entry describes.
Frederic Rissbce93ff2015-03-16 02:05:10 +0000191 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 Riss5a642072015-06-05 23:06:11 +0000422 uint32_t FrameSectionSize;
Frederic Riss25440872015-03-13 23:30:31 +0000423
Frederic Rissbce93ff2015-03-16 02:05:10 +0000424 /// \brief Emit the pubnames or pubtypes section contribution for \p
425 /// Unit into \p Sec. The data is provided in \p Names.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000426 void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000427 const CompileUnit &Unit,
428 const std::vector<CompileUnit::AccelInfo> &Names);
429
Frederic Rissc99ea202015-02-28 00:29:11 +0000430public:
431 /// \brief Actually create the streamer and the ouptut file.
432 ///
433 /// This could be done directly in the constructor, but it feels
434 /// more natural to handle errors through return value.
435 bool init(Triple TheTriple, StringRef OutputFilename);
436
Frederic Rissb8b43d52015-03-04 22:07:44 +0000437 /// \brief Dump the file to the disk.
Frederic Rissc99ea202015-02-28 00:29:11 +0000438 bool finish();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000439
440 AsmPrinter &getAsmPrinter() const { return *Asm; }
441
442 /// \brief Set the current output section to debug_info and change
443 /// the MC Dwarf version to \p DwarfVersion.
444 void switchToDebugInfoSection(unsigned DwarfVersion);
445
446 /// \brief Emit the compilation unit header for \p Unit in the
447 /// debug_info section.
448 ///
449 /// As a side effect, this also switches the current Dwarf version
450 /// of the MC layer to the one of U.getOrigUnit().
451 void emitCompileUnitHeader(CompileUnit &Unit);
452
453 /// \brief Recursively emit the DIE tree rooted at \p Die.
454 void emitDIE(DIE &Die);
455
456 /// \brief Emit the abbreviation table \p Abbrevs to the
457 /// debug_abbrev section.
458 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000459
460 /// \brief Emit the string table described by \p Pool.
461 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Riss25440872015-03-13 23:30:31 +0000462
463 /// \brief Emit debug_ranges for \p FuncRange by translating the
464 /// original \p Entries.
465 void emitRangesEntries(
466 int64_t UnitPcOffset, uint64_t OrigLowPc,
467 FunctionIntervals::const_iterator FuncRange,
468 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
469 unsigned AddressSize);
470
Frederic Riss563b1b02015-03-14 03:46:51 +0000471 /// \brief Emit debug_aranges entries for \p Unit and if \p
472 /// DoRangesSection is true, also emit the debug_ranges entries for
473 /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
474 void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
Frederic Riss25440872015-03-13 23:30:31 +0000475
476 uint32_t getRangesSectionSize() const { return RangesSectionSize; }
Frederic Rissdfb97902015-03-14 15:49:07 +0000477
478 /// \brief Emit the debug_loc contribution for \p Unit by copying
479 /// the entries from \p Dwarf and offseting them. Update the
480 /// location attributes to point to the new entries.
481 void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
Frederic Riss63786b02015-03-15 20:45:43 +0000482
483 /// \brief Emit the line table described in \p Rows into the
484 /// debug_line section.
485 void emitLineTableForUnit(StringRef PrologueBytes, unsigned MinInstLength,
486 std::vector<DWARFDebugLine::Row> &Rows,
487 unsigned AdddressSize);
488
489 uint32_t getLineSectionSize() const { return LineSectionSize; }
Frederic Rissbce93ff2015-03-16 02:05:10 +0000490
491 /// \brief Emit the .debug_pubnames contribution for \p Unit.
492 void emitPubNamesForUnit(const CompileUnit &Unit);
493
494 /// \brief Emit the .debug_pubtypes contribution for \p Unit.
495 void emitPubTypesForUnit(const CompileUnit &Unit);
Frederic Riss5a642072015-06-05 23:06:11 +0000496
497 /// \brief Emit a CIE.
498 void emitCIE(StringRef CIEBytes);
499
500 /// \brief Emit an FDE with data \p Bytes.
501 void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
502 StringRef Bytes);
503
504 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
Frederic Rissc99ea202015-02-28 00:29:11 +0000505};
506
507bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
508 std::string ErrorStr;
509 std::string TripleName;
510 StringRef Context = "dwarf streamer init";
511
512 // Get the target.
513 const Target *TheTarget =
514 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
515 if (!TheTarget)
516 return error(ErrorStr, Context);
517 TripleName = TheTriple.getTriple();
518
519 // Create all the MC Objects.
520 MRI.reset(TheTarget->createMCRegInfo(TripleName));
521 if (!MRI)
522 return error(Twine("no register info for target ") + TripleName, Context);
523
524 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
525 if (!MAI)
526 return error("no asm info for target " + TripleName, Context);
527
528 MOFI.reset(new MCObjectFileInfo);
529 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
Daniel Sanders8d8b13d2015-06-16 12:18:07 +0000530 MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
Frederic Rissc99ea202015-02-28 00:29:11 +0000531 *MC);
532
533 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
534 if (!MAB)
535 return error("no asm backend for target " + TripleName, Context);
536
537 MII.reset(TheTarget->createMCInstrInfo());
538 if (!MII)
539 return error("no instr info info for target " + TripleName, Context);
540
541 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
542 if (!MSTI)
543 return error("no subtarget info for target " + TripleName, Context);
544
Eric Christopher0169e422015-03-10 22:03:14 +0000545 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
Frederic Rissc99ea202015-02-28 00:29:11 +0000546 if (!MCE)
547 return error("no code emitter for target " + TripleName, Context);
548
549 // Create the output file.
550 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000551 OutFile =
552 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000553 if (EC)
554 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
555
Rafael Espindolaf696df12015-03-16 22:29:29 +0000556 MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
Rafael Espindola36a15cb2015-03-20 20:00:01 +0000557 *MSTI, false,
558 /*DWARFMustBeAtTheEnd*/ false);
Frederic Rissc99ea202015-02-28 00:29:11 +0000559 if (!MS)
560 return error("no object streamer for target " + TripleName, Context);
561
562 // Finally create the AsmPrinter we'll use to emit the DIEs.
563 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
564 if (!TM)
565 return error("no target machine for target " + TripleName, Context);
566
567 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
568 if (!Asm)
569 return error("no asm printer for target " + TripleName, Context);
570
Frederic Riss25440872015-03-13 23:30:31 +0000571 RangesSectionSize = 0;
Frederic Rissdfb97902015-03-14 15:49:07 +0000572 LocSectionSize = 0;
Frederic Riss63786b02015-03-15 20:45:43 +0000573 LineSectionSize = 0;
Frederic Riss5a642072015-06-05 23:06:11 +0000574 FrameSectionSize = 0;
Frederic Riss25440872015-03-13 23:30:31 +0000575
Frederic Rissc99ea202015-02-28 00:29:11 +0000576 return true;
577}
578
579bool DwarfStreamer::finish() {
580 MS->Finish();
581 return true;
582}
583
Frederic Rissb8b43d52015-03-04 22:07:44 +0000584/// \brief Set the current output section to debug_info and change
585/// the MC Dwarf version to \p DwarfVersion.
586void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
587 MS->SwitchSection(MOFI->getDwarfInfoSection());
588 MC->setDwarfVersion(DwarfVersion);
589}
590
591/// \brief Emit the compilation unit header for \p Unit in the
592/// debug_info section.
593///
594/// A Dwarf scetion header is encoded as:
595/// uint32_t Unit length (omiting this field)
596/// uint16_t Version
597/// uint32_t Abbreviation table offset
598/// uint8_t Address size
599///
600/// Leading to a total of 11 bytes.
601void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
602 unsigned Version = Unit.getOrigUnit().getVersion();
603 switchToDebugInfoSection(Version);
604
605 // Emit size of content not including length itself. The size has
606 // already been computed in CompileUnit::computeOffsets(). Substract
607 // 4 to that size to account for the length field.
608 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
609 Asm->EmitInt16(Version);
610 // We share one abbreviations table across all units so it's always at the
611 // start of the section.
612 Asm->EmitInt32(0);
613 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
614}
615
616/// \brief Emit the \p Abbrevs array as the shared abbreviation table
617/// for the linked Dwarf file.
618void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
619 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
620 Asm->emitDwarfAbbrevs(Abbrevs);
621}
622
623/// \brief Recursively emit the DIE tree rooted at \p Die.
624void DwarfStreamer::emitDIE(DIE &Die) {
625 MS->SwitchSection(MOFI->getDwarfInfoSection());
626 Asm->emitDwarfDIE(Die);
627}
628
Frederic Rissef648462015-03-06 17:56:30 +0000629/// \brief Emit the debug_str section stored in \p Pool.
630void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000631 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
Frederic Rissef648462015-03-06 17:56:30 +0000632 for (auto *Entry = Pool.getFirstEntry(); Entry;
633 Entry = Pool.getNextEntry(Entry))
Lang Hames9ff69c82015-04-24 19:11:51 +0000634 Asm->OutStreamer->EmitBytes(
Frederic Rissef648462015-03-06 17:56:30 +0000635 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
636}
637
Frederic Riss25440872015-03-13 23:30:31 +0000638/// \brief Emit the debug_range section contents for \p FuncRange by
639/// translating the original \p Entries. The debug_range section
640/// format is totally trivial, consisting just of pairs of address
641/// sized addresses describing the ranges.
642void DwarfStreamer::emitRangesEntries(
643 int64_t UnitPcOffset, uint64_t OrigLowPc,
644 FunctionIntervals::const_iterator FuncRange,
645 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
646 unsigned AddressSize) {
647 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
648
649 // Offset each range by the right amount.
650 int64_t PcOffset = FuncRange.value() + UnitPcOffset;
651 for (const auto &Range : Entries) {
652 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
653 warn("unsupported base address selection operation",
654 "emitting debug_ranges");
655 break;
656 }
657 // Do not emit empty ranges.
658 if (Range.StartAddress == Range.EndAddress)
659 continue;
660
661 // All range entries should lie in the function range.
662 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
663 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
664 warn("inconsistent range data.", "emitting debug_ranges");
665 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
666 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
667 RangesSectionSize += 2 * AddressSize;
668 }
669
670 // Add the terminator entry.
671 MS->EmitIntValue(0, AddressSize);
672 MS->EmitIntValue(0, AddressSize);
673 RangesSectionSize += 2 * AddressSize;
674}
675
Frederic Riss563b1b02015-03-14 03:46:51 +0000676/// \brief Emit the debug_aranges contribution of a unit and
677/// if \p DoDebugRanges is true the debug_range contents for a
678/// compile_unit level DW_AT_ranges attribute (Which are basically the
679/// same thing with a different base address).
680/// Just aggregate all the ranges gathered inside that unit.
681void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
682 bool DoDebugRanges) {
Frederic Riss25440872015-03-13 23:30:31 +0000683 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
684 // Gather the ranges in a vector, so that we can simplify them. The
685 // IntervalMap will have coalesced the non-linked ranges, but here
686 // we want to coalesce the linked addresses.
687 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
688 const auto &FunctionRanges = Unit.getFunctionRanges();
689 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
690 Range != End; ++Range)
Frederic Riss563b1b02015-03-14 03:46:51 +0000691 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
692 Range.stop() + Range.value()));
Frederic Riss25440872015-03-13 23:30:31 +0000693
694 // The object addresses where sorted, but again, the linked
695 // addresses might end up in a different order.
696 std::sort(Ranges.begin(), Ranges.end());
697
Frederic Riss563b1b02015-03-14 03:46:51 +0000698 if (!Ranges.empty()) {
699 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
700
Rafael Espindola9ab09232015-03-17 20:07:06 +0000701 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
702 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
Frederic Riss563b1b02015-03-14 03:46:51 +0000703
704 unsigned HeaderSize =
705 sizeof(int32_t) + // Size of contents (w/o this field
706 sizeof(int16_t) + // DWARF ARange version number
707 sizeof(int32_t) + // Offset of CU in the .debug_info section
708 sizeof(int8_t) + // Pointer Size (in bytes)
709 sizeof(int8_t); // Segment Size (in bytes)
710
711 unsigned TupleSize = AddressSize * 2;
712 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
713
714 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
Lang Hames9ff69c82015-04-24 19:11:51 +0000715 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000716 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
717 Asm->EmitInt32(Unit.getStartOffset()); // Corresponding unit's offset
718 Asm->EmitInt8(AddressSize); // Address size
719 Asm->EmitInt8(0); // Segment size
720
Lang Hames9ff69c82015-04-24 19:11:51 +0000721 Asm->OutStreamer->EmitFill(Padding, 0x0);
Frederic Riss563b1b02015-03-14 03:46:51 +0000722
723 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
724 ++Range) {
725 uint64_t RangeStart = Range->first;
726 MS->EmitIntValue(RangeStart, AddressSize);
727 while ((Range + 1) != End && Range->second == (Range + 1)->first)
728 ++Range;
729 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
730 }
731
732 // Emit terminator
Lang Hames9ff69c82015-04-24 19:11:51 +0000733 Asm->OutStreamer->EmitIntValue(0, AddressSize);
734 Asm->OutStreamer->EmitIntValue(0, AddressSize);
735 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Riss563b1b02015-03-14 03:46:51 +0000736 }
737
738 if (!DoDebugRanges)
739 return;
740
741 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
742 // Offset each range by the right amount.
743 int64_t PcOffset = -Unit.getLowPc();
Frederic Riss25440872015-03-13 23:30:31 +0000744 // Emit coalesced ranges.
745 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
Frederic Riss563b1b02015-03-14 03:46:51 +0000746 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000747 while (Range + 1 != End && Range->second == (Range + 1)->first)
748 ++Range;
Frederic Riss563b1b02015-03-14 03:46:51 +0000749 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
Frederic Riss25440872015-03-13 23:30:31 +0000750 RangesSectionSize += 2 * AddressSize;
751 }
752
753 // Add the terminator entry.
754 MS->EmitIntValue(0, AddressSize);
755 MS->EmitIntValue(0, AddressSize);
756 RangesSectionSize += 2 * AddressSize;
757}
758
Frederic Rissdfb97902015-03-14 15:49:07 +0000759/// \brief Emit location lists for \p Unit and update attribtues to
760/// point to the new entries.
761void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
762 DWARFContext &Dwarf) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000763 const auto &Attributes = Unit.getLocationAttributes();
Frederic Rissdfb97902015-03-14 15:49:07 +0000764
765 if (Attributes.empty())
766 return;
767
768 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
769
770 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
771 const DWARFSection &InputSec = Dwarf.getLocSection();
772 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
773 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000774 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Rissdfb97902015-03-14 15:49:07 +0000775 int64_t UnitPcOffset = 0;
776 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
777 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
778 if (OrigLowPc != -1ULL)
779 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
780
781 for (const auto &Attr : Attributes) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +0000782 uint32_t Offset = Attr.first.get();
783 Attr.first.set(LocSectionSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000784 // This is the quantity to add to the old location address to get
785 // the correct address for the new one.
786 int64_t LocPcOffset = Attr.second + UnitPcOffset;
787 while (Data.isValidOffset(Offset)) {
788 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
789 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
790 LocSectionSize += 2 * AddressSize;
791 if (Low == 0 && High == 0) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000792 Asm->OutStreamer->EmitIntValue(0, AddressSize);
793 Asm->OutStreamer->EmitIntValue(0, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000794 break;
795 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000796 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
797 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
Frederic Rissdfb97902015-03-14 15:49:07 +0000798 uint64_t Length = Data.getU16(&Offset);
Lang Hames9ff69c82015-04-24 19:11:51 +0000799 Asm->OutStreamer->EmitIntValue(Length, 2);
Frederic Rissdfb97902015-03-14 15:49:07 +0000800 // Just copy the bytes over.
Lang Hames9ff69c82015-04-24 19:11:51 +0000801 Asm->OutStreamer->EmitBytes(
Frederic Rissdfb97902015-03-14 15:49:07 +0000802 StringRef(InputSec.Data.substr(Offset, Length)));
803 Offset += Length;
804 LocSectionSize += Length + 2;
805 }
806 }
807}
808
Frederic Riss63786b02015-03-15 20:45:43 +0000809void DwarfStreamer::emitLineTableForUnit(StringRef PrologueBytes,
810 unsigned MinInstLength,
811 std::vector<DWARFDebugLine::Row> &Rows,
812 unsigned PointerSize) {
813 // Switch to the section where the table will be emitted into.
814 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
Jim Grosbach6f482002015-05-18 18:43:14 +0000815 MCSymbol *LineStartSym = MC->createTempSymbol();
816 MCSymbol *LineEndSym = MC->createTempSymbol();
Frederic Riss63786b02015-03-15 20:45:43 +0000817
818 // The first 4 bytes is the total length of the information for this
819 // compilation unit (not including these 4 bytes for the length).
820 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
Lang Hames9ff69c82015-04-24 19:11:51 +0000821 Asm->OutStreamer->EmitLabel(LineStartSym);
Frederic Riss63786b02015-03-15 20:45:43 +0000822 // Copy Prologue.
823 MS->EmitBytes(PrologueBytes);
824 LineSectionSize += PrologueBytes.size() + 4;
825
Frederic Rissc3820d02015-03-15 22:20:28 +0000826 SmallString<128> EncodingBuffer;
Frederic Riss63786b02015-03-15 20:45:43 +0000827 raw_svector_ostream EncodingOS(EncodingBuffer);
828
829 if (Rows.empty()) {
830 // We only have the dummy entry, dsymutil emits an entry with a 0
831 // address in that case.
832 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
833 MS->EmitBytes(EncodingOS.str());
834 LineSectionSize += EncodingBuffer.size();
Frederic Riss63786b02015-03-15 20:45:43 +0000835 MS->EmitLabel(LineEndSym);
836 return;
837 }
838
839 // Line table state machine fields
840 unsigned FileNum = 1;
841 unsigned LastLine = 1;
842 unsigned Column = 0;
843 unsigned IsStatement = 1;
844 unsigned Isa = 0;
845 uint64_t Address = -1ULL;
846
847 unsigned RowsSinceLastSequence = 0;
848
849 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
850 auto &Row = Rows[Idx];
851
852 int64_t AddressDelta;
853 if (Address == -1ULL) {
854 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
855 MS->EmitULEB128IntValue(PointerSize + 1);
856 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
857 MS->EmitIntValue(Row.Address, PointerSize);
858 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
859 AddressDelta = 0;
860 } else {
861 AddressDelta = (Row.Address - Address) / MinInstLength;
862 }
863
864 // FIXME: code copied and transfromed from
865 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
866 // this code, but the current compatibility requirement with
867 // classic dsymutil makes it hard. Revisit that once this
868 // requirement is dropped.
869
870 if (FileNum != Row.File) {
871 FileNum = Row.File;
872 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
873 MS->EmitULEB128IntValue(FileNum);
874 LineSectionSize += 1 + getULEB128Size(FileNum);
875 }
876 if (Column != Row.Column) {
877 Column = Row.Column;
878 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
879 MS->EmitULEB128IntValue(Column);
880 LineSectionSize += 1 + getULEB128Size(Column);
881 }
882
883 // FIXME: We should handle the discriminator here, but dsymutil
884 // doesn' consider it, thus ignore it for now.
885
886 if (Isa != Row.Isa) {
887 Isa = Row.Isa;
888 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
889 MS->EmitULEB128IntValue(Isa);
890 LineSectionSize += 1 + getULEB128Size(Isa);
891 }
892 if (IsStatement != Row.IsStmt) {
893 IsStatement = Row.IsStmt;
894 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
895 LineSectionSize += 1;
896 }
897 if (Row.BasicBlock) {
898 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
899 LineSectionSize += 1;
900 }
901
902 if (Row.PrologueEnd) {
903 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
904 LineSectionSize += 1;
905 }
906
907 if (Row.EpilogueBegin) {
908 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
909 LineSectionSize += 1;
910 }
911
912 int64_t LineDelta = int64_t(Row.Line) - LastLine;
913 if (!Row.EndSequence) {
914 MCDwarfLineAddr::Encode(*MC, LineDelta, AddressDelta, EncodingOS);
915 MS->EmitBytes(EncodingOS.str());
916 LineSectionSize += EncodingBuffer.size();
917 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000918 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000919 Address = Row.Address;
920 LastLine = Row.Line;
921 RowsSinceLastSequence++;
922 } else {
923 if (LineDelta) {
924 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
925 MS->EmitSLEB128IntValue(LineDelta);
926 LineSectionSize += 1 + getSLEB128Size(LineDelta);
927 }
928 if (AddressDelta) {
929 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
930 MS->EmitULEB128IntValue(AddressDelta);
931 LineSectionSize += 1 + getULEB128Size(AddressDelta);
932 }
933 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
934 MS->EmitBytes(EncodingOS.str());
935 LineSectionSize += EncodingBuffer.size();
936 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000937 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000938 Address = -1ULL;
939 LastLine = FileNum = IsStatement = 1;
940 RowsSinceLastSequence = Column = Isa = 0;
941 }
942 }
943
944 if (RowsSinceLastSequence) {
945 MCDwarfLineAddr::Encode(*MC, INT64_MAX, 0, EncodingOS);
946 MS->EmitBytes(EncodingOS.str());
947 LineSectionSize += EncodingBuffer.size();
948 EncodingBuffer.resize(0);
Frederic Rissc3820d02015-03-15 22:20:28 +0000949 EncodingOS.resync();
Frederic Riss63786b02015-03-15 20:45:43 +0000950 }
951
952 MS->EmitLabel(LineEndSym);
953}
954
Frederic Rissbce93ff2015-03-16 02:05:10 +0000955/// \brief Emit the pubnames or pubtypes section contribution for \p
956/// Unit into \p Sec. The data is provided in \p Names.
957void DwarfStreamer::emitPubSectionForUnit(
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000958 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
Frederic Rissbce93ff2015-03-16 02:05:10 +0000959 const std::vector<CompileUnit::AccelInfo> &Names) {
960 if (Names.empty())
961 return;
962
963 // Start the dwarf pubnames section.
Lang Hames9ff69c82015-04-24 19:11:51 +0000964 Asm->OutStreamer->SwitchSection(Sec);
Rafael Espindola9ab09232015-03-17 20:07:06 +0000965 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
966 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
Frederic Rissbce93ff2015-03-16 02:05:10 +0000967
968 bool HeaderEmitted = false;
969 // Emit the pubnames for this compilation unit.
970 for (const auto &Name : Names) {
971 if (Name.SkipPubSection)
972 continue;
973
974 if (!HeaderEmitted) {
975 // Emit the header.
976 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
Lang Hames9ff69c82015-04-24 19:11:51 +0000977 Asm->OutStreamer->EmitLabel(BeginLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +0000978 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
Frederic Rissf37964c2015-06-05 20:27:07 +0000979 Asm->EmitInt32(Unit.getStartOffset()); // Unit offset
Frederic Rissbce93ff2015-03-16 02:05:10 +0000980 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
981 HeaderEmitted = true;
982 }
983 Asm->EmitInt32(Name.Die->getOffset());
Lang Hames9ff69c82015-04-24 19:11:51 +0000984 Asm->OutStreamer->EmitBytes(
Frederic Rissbce93ff2015-03-16 02:05:10 +0000985 StringRef(Name.Name.data(), Name.Name.size() + 1));
986 }
987
988 if (!HeaderEmitted)
989 return;
990 Asm->EmitInt32(0); // End marker.
Lang Hames9ff69c82015-04-24 19:11:51 +0000991 Asm->OutStreamer->EmitLabel(EndLabel);
Frederic Rissbce93ff2015-03-16 02:05:10 +0000992}
993
994/// \brief Emit .debug_pubnames for \p Unit.
995void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
996 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
997 "names", Unit, Unit.getPubnames());
998}
999
1000/// \brief Emit .debug_pubtypes for \p Unit.
1001void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1002 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1003 "types", Unit, Unit.getPubtypes());
1004}
1005
Frederic Riss5a642072015-06-05 23:06:11 +00001006/// \brief Emit a CIE into the debug_frame section.
1007void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1008 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1009
1010 MS->EmitBytes(CIEBytes);
1011 FrameSectionSize += CIEBytes.size();
1012}
1013
1014/// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1015/// contains the FDE data without the length, CIE offset and address
1016/// which will be replaced with the paramter values.
1017void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1018 uint32_t Address, StringRef FDEBytes) {
1019 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1020
1021 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1022 MS->EmitIntValue(CIEOffset, 4);
1023 MS->EmitIntValue(Address, AddrSize);
1024 MS->EmitBytes(FDEBytes);
1025 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1026}
1027
Frederic Rissd3455182015-01-28 18:27:01 +00001028/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +00001029///
1030/// The link of the dwarf information from the object files will be
1031/// driven by the selection of 'root DIEs', which are DIEs that
1032/// describe variables or functions that are present in the linked
1033/// binary (and thus have entries in the debug map). All the debug
1034/// information that will be linked (the DIEs, but also the line
1035/// tables, ranges, ...) is derived from that set of root DIEs.
1036///
1037/// The root DIEs are identified because they contain relocations that
1038/// correspond to a debug map entry at specific places (the low_pc for
1039/// a function, the location for a variable). These relocations are
1040/// called ValidRelocs in the DwarfLinker and are gathered as a very
1041/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +00001042class DwarfLinker {
1043public:
Frederic Rissb9818322015-02-28 00:29:07 +00001044 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1045 : OutputFilename(OutputFilename), Options(Options),
Frederic Riss5a642072015-06-05 23:06:11 +00001046 BinHolder(Options.Verbose), LastCIEOffset(0) {}
Frederic Rissd3455182015-01-28 18:27:01 +00001047
Frederic Rissb8b43d52015-03-04 22:07:44 +00001048 ~DwarfLinker() {
1049 for (auto *Abbrev : Abbreviations)
1050 delete Abbrev;
1051 }
1052
Frederic Rissd3455182015-01-28 18:27:01 +00001053 /// \brief Link the contents of the DebugMap.
1054 bool link(const DebugMap &);
1055
1056private:
Frederic Riss563cba62015-01-28 22:15:14 +00001057 /// \brief Called at the start of a debug object link.
Frederic Riss63786b02015-03-15 20:45:43 +00001058 void startDebugObject(DWARFContext &, DebugMapObject &);
Frederic Riss563cba62015-01-28 22:15:14 +00001059
1060 /// \brief Called at the end of a debug object link.
1061 void endDebugObject();
1062
Frederic Riss1036e642015-02-13 23:18:22 +00001063 /// \defgroup FindValidRelocations Translate debug map into a list
1064 /// of relevant relocations
1065 ///
1066 /// @{
1067 struct ValidReloc {
1068 uint32_t Offset;
1069 uint32_t Size;
1070 uint64_t Addend;
1071 const DebugMapObject::DebugMapEntry *Mapping;
1072
1073 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1074 const DebugMapObject::DebugMapEntry *Mapping)
1075 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1076
1077 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1078 };
1079
1080 /// \brief The valid relocations for the current DebugMapObject.
1081 /// This vector is sorted by relocation offset.
1082 std::vector<ValidReloc> ValidRelocs;
1083
1084 /// \brief Index into ValidRelocs of the next relocation to
1085 /// consider. As we walk the DIEs in acsending file offset and as
1086 /// ValidRelocs is sorted by file offset, keeping this index
1087 /// uptodate is all we have to do to have a cheap lookup during the
Frederic Riss23e20e92015-03-07 01:25:09 +00001088 /// root DIE selection and during DIE cloning.
Frederic Riss1036e642015-02-13 23:18:22 +00001089 unsigned NextValidReloc;
1090
1091 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1092 const DebugMapObject &DMO);
1093
1094 bool findValidRelocs(const object::SectionRef &Section,
1095 const object::ObjectFile &Obj,
1096 const DebugMapObject &DMO);
1097
1098 void findValidRelocsMachO(const object::SectionRef &Section,
1099 const object::MachOObjectFile &Obj,
1100 const DebugMapObject &DMO);
1101 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +00001102
Frederic Riss84c09a52015-02-13 23:18:34 +00001103 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1104 ///
1105 /// @{
1106 /// \brief Recursively walk the \p DIE tree and look for DIEs to
1107 /// keep. Store that information in \p CU's DIEInfo.
1108 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1109 const DebugMapObject &DMO, CompileUnit &CU,
1110 unsigned Flags);
1111
1112 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1113 enum TravesalFlags {
1114 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
1115 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1116 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
1117 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
1118 };
1119
1120 /// \brief Mark the passed DIE as well as all the ones it depends on
1121 /// as kept.
1122 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1123 CompileUnit::DIEInfo &MyInfo,
1124 const DebugMapObject &DMO, CompileUnit &CU,
1125 unsigned Flags);
1126
1127 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1128 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1129 unsigned Flags);
1130
1131 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1132 CompileUnit &Unit,
1133 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1134
1135 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1136 CompileUnit &Unit,
1137 CompileUnit::DIEInfo &MyInfo,
1138 unsigned Flags);
1139
1140 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1141 CompileUnit::DIEInfo &Info);
1142 /// @}
1143
Frederic Rissb8b43d52015-03-04 22:07:44 +00001144 /// \defgroup Linking Methods used to link the debug information
1145 ///
1146 /// @{
1147 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1148 /// where useless (as decided by lookForDIEsToKeep()) bits have been
1149 /// stripped out and addresses have been rewritten according to the
1150 /// debug map.
1151 ///
1152 /// \param OutOffset is the offset the cloned DIE in the output
1153 /// compile unit.
Frederic Riss31da3242015-03-11 18:45:52 +00001154 /// \param PCOffset (while cloning a function scope) is the offset
1155 /// applied to the entry point of the function to get the linked address.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001156 ///
1157 /// \returns the root of the cloned tree.
1158 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
Frederic Riss31da3242015-03-11 18:45:52 +00001159 int64_t PCOffset, uint32_t OutOffset);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001160
1161 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1162
Frederic Riss31da3242015-03-11 18:45:52 +00001163 /// \brief Information gathered and exchanged between the various
1164 /// clone*Attributes helpers about the attributes of a particular DIE.
1165 struct AttributesInfo {
Frederic Rissbce93ff2015-03-16 02:05:10 +00001166 const char *Name, *MangledName; ///< Names.
1167 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1168
Frederic Riss31da3242015-03-11 18:45:52 +00001169 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1170 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1171
Frederic Rissbce93ff2015-03-16 02:05:10 +00001172 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1173 bool IsDeclaration; ///< Is this DIE only a declaration?
1174
1175 AttributesInfo()
1176 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1177 MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1178 IsDeclaration(false) {}
Frederic Riss31da3242015-03-11 18:45:52 +00001179 };
1180
Frederic Rissb8b43d52015-03-04 22:07:44 +00001181 /// \brief Helper for cloneDIE.
1182 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1183 CompileUnit &U, const DWARFFormValue &Val,
Frederic Riss31da3242015-03-11 18:45:52 +00001184 const AttributeSpec AttrSpec, unsigned AttrSize,
1185 AttributesInfo &AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001186
1187 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +00001188 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1189 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001190
1191 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +00001192 unsigned
1193 cloneDieReferenceAttribute(DIE &Die,
1194 const DWARFDebugInfoEntryMinimal &InputDIE,
1195 AttributeSpec AttrSpec, unsigned AttrSize,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001196 const DWARFFormValue &Val, CompileUnit &Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001197
1198 /// \brief Helper for cloneDIE.
1199 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1200 const DWARFFormValue &Val, unsigned AttrSize);
1201
1202 /// \brief Helper for cloneDIE.
Frederic Riss31da3242015-03-11 18:45:52 +00001203 unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1204 const DWARFFormValue &Val,
1205 const CompileUnit &Unit, AttributesInfo &Info);
1206
1207 /// \brief Helper for cloneDIE.
Frederic Rissb8b43d52015-03-04 22:07:44 +00001208 unsigned cloneScalarAttribute(DIE &Die,
1209 const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss25440872015-03-13 23:30:31 +00001210 CompileUnit &U, AttributeSpec AttrSpec,
Frederic Rissdfb97902015-03-14 15:49:07 +00001211 const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001212 AttributesInfo &Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001213
Frederic Riss23e20e92015-03-07 01:25:09 +00001214 /// \brief Helper for cloneDIE.
1215 bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1216 bool isLittleEndian);
1217
Frederic Rissb8b43d52015-03-04 22:07:44 +00001218 /// \brief Assign an abbreviation number to \p Abbrev
1219 void AssignAbbrev(DIEAbbrev &Abbrev);
1220
1221 /// \brief FoldingSet that uniques the abbreviations.
1222 FoldingSet<DIEAbbrev> AbbreviationsSet;
1223 /// \brief Storage for the unique Abbreviations.
1224 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1225 /// be changed to a vecot of unique_ptrs.
1226 std::vector<DIEAbbrev *> Abbreviations;
1227
Frederic Riss25440872015-03-13 23:30:31 +00001228 /// \brief Compute and emit debug_ranges section for \p Unit, and
1229 /// patch the attributes referencing it.
1230 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1231
1232 /// \brief Generate and emit the DW_AT_ranges attribute for a
1233 /// compile_unit if it had one.
1234 void generateUnitRanges(CompileUnit &Unit) const;
1235
Frederic Riss63786b02015-03-15 20:45:43 +00001236 /// \brief Extract the line tables fromt he original dwarf, extract
1237 /// the relevant parts according to the linked function ranges and
1238 /// emit the result in the debug_line section.
1239 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1240
Frederic Rissbce93ff2015-03-16 02:05:10 +00001241 /// \brief Emit the accelerator entries for \p Unit.
1242 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1243
Frederic Riss5a642072015-06-05 23:06:11 +00001244 /// \brief Patch the frame info for an object file and emit it.
1245 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1246 unsigned AddressSize);
1247
Frederic Rissb8b43d52015-03-04 22:07:44 +00001248 /// \brief DIELoc objects that need to be destructed (but not freed!).
1249 std::vector<DIELoc *> DIELocs;
1250 /// \brief DIEBlock objects that need to be destructed (but not freed!).
1251 std::vector<DIEBlock *> DIEBlocks;
1252 /// \brief Allocator used for all the DIEValue objects.
1253 BumpPtrAllocator DIEAlloc;
1254 /// @}
1255
Frederic Riss1b9da422015-02-13 23:18:29 +00001256 /// \defgroup Helpers Various helper methods.
1257 ///
1258 /// @{
1259 const DWARFDebugInfoEntryMinimal *
1260 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
1261 const DWARFDebugInfoEntryMinimal &DIE,
1262 CompileUnit *&ReferencedCU);
1263
1264 CompileUnit *getUnitForOffset(unsigned Offset);
1265
Frederic Rissbce93ff2015-03-16 02:05:10 +00001266 bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1267 AttributesInfo &Info);
1268
Frederic Riss1b9da422015-02-13 23:18:29 +00001269 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
Frederic Riss25440872015-03-13 23:30:31 +00001270 const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
Frederic Rissc99ea202015-02-28 00:29:11 +00001271
1272 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Riss1b9da422015-02-13 23:18:29 +00001273 /// @}
1274
Frederic Riss563cba62015-01-28 22:15:14 +00001275private:
Frederic Rissd3455182015-01-28 18:27:01 +00001276 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +00001277 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +00001278 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +00001279 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +00001280
1281 /// The units of the current debug map object.
1282 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +00001283
1284 /// The debug map object curently under consideration.
1285 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +00001286
1287 /// \brief The Dwarf string pool
1288 NonRelocatableStringpool StringPool;
Frederic Riss63786b02015-03-15 20:45:43 +00001289
1290 /// \brief This map is keyed by the entry PC of functions in that
1291 /// debug object and the associated value is a pair storing the
1292 /// corresponding end PC and the offset to apply to get the linked
1293 /// address.
1294 ///
1295 /// See startDebugObject() for a more complete description of its use.
1296 std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
Frederic Riss5a642072015-06-05 23:06:11 +00001297
1298 /// \brief The CIEs that have been emitted in the output
1299 /// section. The actual CIE data serves a the key to this StringMap,
1300 /// this takes care of comparing the semantics of CIEs defined in
1301 /// different object files.
1302 StringMap<uint32_t> EmittedCIEs;
1303
1304 /// Offset of the last CIE that has been emitted in the output
1305 /// debug_frame section.
1306 uint32_t LastCIEOffset;
Frederic Rissd3455182015-01-28 18:27:01 +00001307};
1308
Frederic Riss1b9da422015-02-13 23:18:29 +00001309/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1310/// returning our CompileUnit object instead.
1311CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1312 auto CU =
1313 std::upper_bound(Units.begin(), Units.end(), Offset,
1314 [](uint32_t LHS, const CompileUnit &RHS) {
1315 return LHS < RHS.getOrigUnit().getNextUnitOffset();
1316 });
1317 return CU != Units.end() ? &*CU : nullptr;
1318}
1319
1320/// \brief Resolve the DIE attribute reference that has been
1321/// extracted in \p RefValue. The resulting DIE migh be in another
1322/// CompileUnit which is stored into \p ReferencedCU.
1323/// \returns null if resolving fails for any reason.
1324const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1325 DWARFFormValue &RefValue, const DWARFUnit &Unit,
1326 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1327 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1328 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1329
1330 if ((RefCU = getUnitForOffset(RefOffset)))
1331 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1332 return RefDie;
1333
1334 reportWarning("could not find referenced DIE", &Unit, &DIE);
1335 return nullptr;
1336}
1337
Frederic Rissbce93ff2015-03-16 02:05:10 +00001338/// \brief Get the potential name and mangled name for the entity
1339/// described by \p Die and store them in \Info if they are not
1340/// already there.
1341/// \returns is a name was found.
1342bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1343 DWARFUnit &U, AttributesInfo &Info) {
1344 // FIXME: a bit wastefull as the first getName might return the
1345 // short name.
1346 if (!Info.MangledName &&
1347 (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1348 Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1349
1350 if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1351 Info.NameOffset = StringPool.getStringOffset(Info.Name);
1352
1353 return Info.Name || Info.MangledName;
1354}
1355
Frederic Riss1b9da422015-02-13 23:18:29 +00001356/// \brief Report a warning to the user, optionaly including
1357/// information about a specific \p DIE related to the warning.
1358void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
Frederic Riss25440872015-03-13 23:30:31 +00001359 const DWARFDebugInfoEntryMinimal *DIE) const {
Frederic Rissdef4fb72015-02-28 00:29:01 +00001360 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +00001361 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +00001362 Context = CurrentDebugObject->getObjectFilename();
1363 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +00001364
Frederic Rissb9818322015-02-28 00:29:07 +00001365 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +00001366 return;
1367
1368 errs() << " in DIE:\n";
1369 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1370 6 /* Indent */);
1371}
1372
Frederic Rissc99ea202015-02-28 00:29:11 +00001373bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1374 if (Options.NoOutput)
1375 return true;
1376
Frederic Rissb52cf522015-02-28 00:42:37 +00001377 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +00001378 return Streamer->init(TheTriple, OutputFilename);
1379}
1380
Frederic Riss563cba62015-01-28 22:15:14 +00001381/// \brief Recursive helper to gather the child->parent relationships in the
1382/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +00001383static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1384 unsigned ParentIdx, CompileUnit &CU) {
Frederic Riss563cba62015-01-28 22:15:14 +00001385 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1386 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
1387
1388 if (DIE->hasChildren())
1389 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1390 Child = Child->getSibling())
Frederic Riss9aa725b2015-02-13 23:18:31 +00001391 gatherDIEParents(Child, MyIdx, CU);
Frederic Riss563cba62015-01-28 22:15:14 +00001392}
1393
Frederic Riss84c09a52015-02-13 23:18:34 +00001394static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1395 switch (Tag) {
1396 default:
1397 return false;
1398 case dwarf::DW_TAG_subprogram:
1399 case dwarf::DW_TAG_lexical_block:
1400 case dwarf::DW_TAG_subroutine_type:
1401 case dwarf::DW_TAG_structure_type:
1402 case dwarf::DW_TAG_class_type:
1403 case dwarf::DW_TAG_union_type:
1404 return true;
1405 }
1406 llvm_unreachable("Invalid Tag");
1407}
1408
Frederic Riss63786b02015-03-15 20:45:43 +00001409void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
Frederic Riss563cba62015-01-28 22:15:14 +00001410 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +00001411 NextValidReloc = 0;
Frederic Riss63786b02015-03-15 20:45:43 +00001412 // Iterate over the debug map entries and put all the ones that are
1413 // functions (because they have a size) into the Ranges map. This
1414 // map is very similar to the FunctionRanges that are stored in each
1415 // unit, with 2 notable differences:
1416 // - obviously this one is global, while the other ones are per-unit.
1417 // - this one contains not only the functions described in the DIE
1418 // tree, but also the ones that are only in the debug map.
1419 // The latter information is required to reproduce dsymutil's logic
1420 // while linking line tables. The cases where this information
1421 // matters look like bugs that need to be investigated, but for now
1422 // we need to reproduce dsymutil's behavior.
1423 // FIXME: Once we understood exactly if that information is needed,
1424 // maybe totally remove this (or try to use it to do a real
1425 // -gline-tables-only on Darwin.
1426 for (const auto &Entry : Obj.symbols()) {
1427 const auto &Mapping = Entry.getValue();
1428 if (Mapping.Size)
1429 Ranges[Mapping.ObjectAddress] = std::make_pair(
1430 Mapping.ObjectAddress + Mapping.Size,
1431 int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1432 }
Frederic Riss563cba62015-01-28 22:15:14 +00001433}
1434
Frederic Riss1036e642015-02-13 23:18:22 +00001435void DwarfLinker::endDebugObject() {
1436 Units.clear();
1437 ValidRelocs.clear();
Frederic Riss63786b02015-03-15 20:45:43 +00001438 Ranges.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001439
1440 for (auto *Block : DIEBlocks)
1441 Block->~DIEBlock();
1442 for (auto *Loc : DIELocs)
1443 Loc->~DIELoc();
1444
1445 DIEBlocks.clear();
1446 DIELocs.clear();
1447 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +00001448}
1449
1450/// \brief Iterate over the relocations of the given \p Section and
1451/// store the ones that correspond to debug map entries into the
1452/// ValidRelocs array.
1453void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1454 const object::MachOObjectFile &Obj,
1455 const DebugMapObject &DMO) {
1456 StringRef Contents;
1457 Section.getContents(Contents);
1458 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1459
1460 for (const object::RelocationRef &Reloc : Section.relocations()) {
1461 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1462 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1463 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1464 uint64_t Offset64;
1465 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001466 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +00001467 continue;
1468 }
1469 uint32_t Offset = Offset64;
1470 // Mach-o uses REL relocations, the addend is at the relocation offset.
1471 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1472
1473 auto Sym = Reloc.getSymbol();
1474 if (Sym != Obj.symbol_end()) {
1475 StringRef SymbolName;
1476 if (Sym->getName(SymbolName)) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001477 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +00001478 continue;
1479 }
1480 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
1481 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1482 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1483 // Do not store the addend. The addend was the address of the
1484 // symbol in the object file, the address in the binary that is
1485 // stored in the debug map doesn't need to be offseted.
1486 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1487 }
1488 }
1489}
1490
1491/// \brief Dispatch the valid relocation finding logic to the
1492/// appropriate handler depending on the object file format.
1493bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1494 const object::ObjectFile &Obj,
1495 const DebugMapObject &DMO) {
1496 // Dispatch to the right handler depending on the file type.
1497 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1498 findValidRelocsMachO(Section, *MachOObj, DMO);
1499 else
Frederic Riss1b9da422015-02-13 23:18:29 +00001500 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +00001501
1502 if (ValidRelocs.empty())
1503 return false;
1504
1505 // Sort the relocations by offset. We will walk the DIEs linearly in
1506 // the file, this allows us to just keep an index in the relocation
1507 // array that we advance during our walk, rather than resorting to
1508 // some associative container. See DwarfLinker::NextValidReloc.
1509 std::sort(ValidRelocs.begin(), ValidRelocs.end());
1510 return true;
1511}
1512
1513/// \brief Look for relocations in the debug_info section that match
1514/// entries in the debug map. These relocations will drive the Dwarf
1515/// link by indicating which DIEs refer to symbols present in the
1516/// linked binary.
1517/// \returns wether there are any valid relocations in the debug info.
1518bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1519 const DebugMapObject &DMO) {
1520 // Find the debug_info section.
1521 for (const object::SectionRef &Section : Obj.sections()) {
1522 StringRef SectionName;
1523 Section.getName(SectionName);
1524 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1525 if (SectionName != "debug_info")
1526 continue;
1527 return findValidRelocs(Section, Obj, DMO);
1528 }
1529 return false;
1530}
Frederic Riss563cba62015-01-28 22:15:14 +00001531
Frederic Riss84c09a52015-02-13 23:18:34 +00001532/// \brief Checks that there is a relocation against an actual debug
1533/// map entry between \p StartOffset and \p NextOffset.
1534///
1535/// This function must be called with offsets in strictly ascending
1536/// order because it never looks back at relocations it already 'went past'.
1537/// \returns true and sets Info.InDebugMap if it is the case.
1538bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1539 CompileUnit::DIEInfo &Info) {
1540 assert(NextValidReloc == 0 ||
1541 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1542 if (NextValidReloc >= ValidRelocs.size())
1543 return false;
1544
1545 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1546
1547 // We might need to skip some relocs that we didn't consider. For
1548 // example the high_pc of a discarded DIE might contain a reloc that
1549 // is in the list because it actually corresponds to the start of a
1550 // function that is in the debug map.
1551 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1552 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1553
1554 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1555 return false;
1556
1557 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Riss08462f72015-06-01 21:12:45 +00001558 const auto &Mapping = ValidReloc.Mapping->getValue();
Frederic Rissb9818322015-02-28 00:29:07 +00001559 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001560 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1561 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
Frederic Riss08462f72015-06-01 21:12:45 +00001562 uint64_t(Mapping.ObjectAddress),
1563 uint64_t(Mapping.BinaryAddress));
Frederic Riss84c09a52015-02-13 23:18:34 +00001564
Frederic Rissf37964c2015-06-05 20:27:07 +00001565 Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1566 Mapping.ObjectAddress;
Frederic Riss84c09a52015-02-13 23:18:34 +00001567 Info.InDebugMap = true;
1568 return true;
1569}
1570
1571/// \brief Get the starting and ending (exclusive) offset for the
1572/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1573/// supposed to point to the position of the first attribute described
1574/// by \p Abbrev.
1575/// \return [StartOffset, EndOffset) as a pair.
1576static std::pair<uint32_t, uint32_t>
1577getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1578 unsigned Offset, const DWARFUnit &Unit) {
1579 DataExtractor Data = Unit.getDebugInfoExtractor();
1580
1581 for (unsigned i = 0; i < Idx; ++i)
1582 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1583
1584 uint32_t End = Offset;
1585 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1586
1587 return std::make_pair(Offset, End);
1588}
1589
1590/// \brief Check if a variable describing DIE should be kept.
1591/// \returns updated TraversalFlags.
1592unsigned DwarfLinker::shouldKeepVariableDIE(
1593 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1594 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1595 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1596
1597 // Global variables with constant value can always be kept.
1598 if (!(Flags & TF_InFunctionScope) &&
1599 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1600 MyInfo.InDebugMap = true;
1601 return Flags | TF_Keep;
1602 }
1603
1604 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1605 if (LocationIdx == -1U)
1606 return Flags;
1607
1608 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1609 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1610 uint32_t LocationOffset, LocationEndOffset;
1611 std::tie(LocationOffset, LocationEndOffset) =
1612 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1613
1614 // See if there is a relocation to a valid debug map entry inside
1615 // this variable's location. The order is important here. We want to
1616 // always check in the variable has a valid relocation, so that the
1617 // DIEInfo is filled. However, we don't want a static variable in a
1618 // function to force us to keep the enclosing function.
1619 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1620 (Flags & TF_InFunctionScope))
1621 return Flags;
1622
Frederic Rissb9818322015-02-28 00:29:07 +00001623 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001624 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1625
1626 return Flags | TF_Keep;
1627}
1628
1629/// \brief Check if a function describing DIE should be kept.
1630/// \returns updated TraversalFlags.
1631unsigned DwarfLinker::shouldKeepSubprogramDIE(
1632 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1633 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1634 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1635
1636 Flags |= TF_InFunctionScope;
1637
1638 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
1639 if (LowPcIdx == -1U)
1640 return Flags;
1641
1642 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1643 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1644 uint32_t LowPcOffset, LowPcEndOffset;
1645 std::tie(LowPcOffset, LowPcEndOffset) =
1646 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
1647
1648 uint64_t LowPc =
1649 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
1650 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
1651 if (LowPc == -1ULL ||
1652 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
1653 return Flags;
1654
Frederic Rissb9818322015-02-28 00:29:07 +00001655 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +00001656 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
1657
Frederic Riss1af75f72015-03-12 18:45:10 +00001658 Flags |= TF_Keep;
1659
1660 DWARFFormValue HighPcValue;
1661 if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
1662 reportWarning("Function without high_pc. Range will be discarded.\n",
1663 &OrigUnit, &DIE);
1664 return Flags;
1665 }
1666
1667 uint64_t HighPc;
1668 if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
1669 HighPc = *HighPcValue.getAsAddress(&OrigUnit);
1670 } else {
1671 assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
1672 HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
1673 }
1674
Frederic Riss63786b02015-03-15 20:45:43 +00001675 // Replace the debug map range with a more accurate one.
1676 Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
Frederic Riss1af75f72015-03-12 18:45:10 +00001677 Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
1678 return Flags;
Frederic Riss84c09a52015-02-13 23:18:34 +00001679}
1680
1681/// \brief Check if a DIE should be kept.
1682/// \returns updated TraversalFlags.
1683unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1684 CompileUnit &Unit,
1685 CompileUnit::DIEInfo &MyInfo,
1686 unsigned Flags) {
1687 switch (DIE.getTag()) {
1688 case dwarf::DW_TAG_constant:
1689 case dwarf::DW_TAG_variable:
1690 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
1691 case dwarf::DW_TAG_subprogram:
1692 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
1693 case dwarf::DW_TAG_module:
1694 case dwarf::DW_TAG_imported_module:
1695 case dwarf::DW_TAG_imported_declaration:
1696 case dwarf::DW_TAG_imported_unit:
1697 // We always want to keep these.
1698 return Flags | TF_Keep;
1699 }
1700
1701 return Flags;
1702}
1703
Frederic Riss84c09a52015-02-13 23:18:34 +00001704/// \brief Mark the passed DIE as well as all the ones it depends on
1705/// as kept.
1706///
1707/// This function is called by lookForDIEsToKeep on DIEs that are
1708/// newly discovered to be needed in the link. It recursively calls
1709/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
1710/// TraversalFlags to inform it that it's not doing the primary DIE
1711/// tree walk.
1712void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1713 CompileUnit::DIEInfo &MyInfo,
1714 const DebugMapObject &DMO,
1715 CompileUnit &CU, unsigned Flags) {
1716 const DWARFUnit &Unit = CU.getOrigUnit();
1717 MyInfo.Keep = true;
1718
1719 // First mark all the parent chain as kept.
1720 unsigned AncestorIdx = MyInfo.ParentIdx;
1721 while (!CU.getInfo(AncestorIdx).Keep) {
1722 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
1723 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
1724 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
1725 }
1726
1727 // Then we need to mark all the DIEs referenced by this DIE's
1728 // attributes as kept.
1729 DataExtractor Data = Unit.getDebugInfoExtractor();
1730 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1731 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1732
1733 // Mark all DIEs referenced through atttributes as kept.
1734 for (const auto &AttrSpec : Abbrev->attributes()) {
1735 DWARFFormValue Val(AttrSpec.Form);
1736
1737 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
1738 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
1739 continue;
1740 }
1741
1742 Val.extractValue(Data, &Offset, &Unit);
1743 CompileUnit *ReferencedCU;
1744 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
1745 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
1746 TF_Keep | TF_DependencyWalk);
1747 }
1748}
1749
1750/// \brief Recursively walk the \p DIE tree and look for DIEs to
1751/// keep. Store that information in \p CU's DIEInfo.
1752///
1753/// This function is the entry point of the DIE selection
1754/// algorithm. It is expected to walk the DIE tree in file order and
1755/// (though the mediation of its helper) call hasValidRelocation() on
1756/// each DIE that might be a 'root DIE' (See DwarfLinker class
1757/// comment).
1758/// While walking the dependencies of root DIEs, this function is
1759/// also called, but during these dependency walks the file order is
1760/// not respected. The TF_DependencyWalk flag tells us which kind of
1761/// traversal we are currently doing.
1762void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1763 const DebugMapObject &DMO, CompileUnit &CU,
1764 unsigned Flags) {
1765 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1766 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1767 bool AlreadyKept = MyInfo.Keep;
1768
1769 // If the Keep flag is set, we are marking a required DIE's
1770 // dependencies. If our target is already marked as kept, we're all
1771 // set.
1772 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1773 return;
1774
1775 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1776 // because it would screw up the relocation finding logic.
1777 if (!(Flags & TF_DependencyWalk))
1778 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1779
1780 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1781 if (!AlreadyKept && (Flags & TF_Keep))
1782 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1783
1784 // The TF_ParentWalk flag tells us that we are currently walking up
1785 // the parent chain of a required DIE, and we don't want to mark all
1786 // the children of the parents as kept (consider for example a
1787 // DW_TAG_namespace node in the parent chain). There are however a
1788 // set of DIE types for which we want to ignore that directive and still
1789 // walk their children.
1790 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1791 Flags &= ~TF_ParentWalk;
1792
1793 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1794 return;
1795
1796 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1797 Child = Child->getSibling())
1798 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1799}
1800
Frederic Rissb8b43d52015-03-04 22:07:44 +00001801/// \brief Assign an abbreviation numer to \p Abbrev.
1802///
1803/// Our DIEs get freed after every DebugMapObject has been processed,
1804/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1805/// the instances hold by the DIEs. When we encounter an abbreviation
1806/// that we don't know, we create a permanent copy of it.
1807void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1808 // Check the set for priors.
1809 FoldingSetNodeID ID;
1810 Abbrev.Profile(ID);
1811 void *InsertToken;
1812 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1813
1814 // If it's newly added.
1815 if (InSet) {
1816 // Assign existing abbreviation number.
1817 Abbrev.setNumber(InSet->getNumber());
1818 } else {
1819 // Add to abbreviation list.
1820 Abbreviations.push_back(
1821 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1822 for (const auto &Attr : Abbrev.getData())
1823 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1824 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1825 // Assign the unique abbreviation number.
1826 Abbrev.setNumber(Abbreviations.size());
1827 Abbreviations.back()->setNumber(Abbreviations.size());
1828 }
1829}
1830
1831/// \brief Clone a string attribute described by \p AttrSpec and add
1832/// it to \p Die.
1833/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00001834unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1835 const DWARFFormValue &Val,
1836 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001837 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00001838 const char *String = *Val.getAsCString(&U);
1839 unsigned Offset = StringPool.getStringOffset(String);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001840 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001841 DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001842 return 4;
1843}
1844
1845/// \brief Clone an attribute referencing another DIE and add
1846/// it to \p Die.
1847/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00001848unsigned DwarfLinker::cloneDieReferenceAttribute(
1849 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1850 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00001851 CompileUnit &Unit) {
1852 uint32_t Ref = *Val.getAsReference(&Unit.getOrigUnit());
Frederic Riss9833de62015-03-06 23:22:53 +00001853 DIE *NewRefDie = nullptr;
1854 CompileUnit *RefUnit = nullptr;
1855 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1856
1857 if (!(RefUnit = getUnitForOffset(Ref)) ||
1858 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1859 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1860 if (!AttributeString)
1861 AttributeString = "DW_AT_???";
1862 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1863 ". Dropping.",
Frederic Riss6afcfce2015-03-13 18:35:57 +00001864 &Unit.getOrigUnit(), &InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00001865 return 0;
1866 }
1867
1868 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1869 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1870 if (!RefInfo.Clone) {
1871 assert(Ref > InputDIE.getOffset());
1872 // We haven't cloned this DIE yet. Just create an empty one and
1873 // store it. It'll get really cloned when we process it.
1874 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1875 }
1876 NewRefDie = RefInfo.Clone;
1877
1878 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1879 // We cannot currently rely on a DIEEntry to emit ref_addr
1880 // references, because the implementation calls back to DwarfDebug
1881 // to find the unit offset. (We don't have a DwarfDebug)
1882 // FIXME: we should be able to design DIEEntry reliance on
1883 // DwarfDebug away.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001884 uint64_t Attr;
Frederic Riss9833de62015-03-06 23:22:53 +00001885 if (Ref < InputDIE.getOffset()) {
1886 // We must have already cloned that DIE.
1887 uint32_t NewRefOffset =
1888 RefUnit->getStartOffset() + NewRefDie->getOffset();
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001889 Attr = NewRefOffset;
Frederic Riss9833de62015-03-06 23:22:53 +00001890 } else {
1891 // A forward reference. Note and fixup later.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001892 Attr = 0xBADDEF;
Duncan P. N. Exon Smith88a8fc52015-05-27 22:44:06 +00001893 Unit.noteForwardReference(NewRefDie, RefUnit, PatchLocation(Die));
Frederic Riss9833de62015-03-06 23:22:53 +00001894 }
1895 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001896 DIEInteger(Attr));
Frederic Riss9833de62015-03-06 23:22:53 +00001897 return AttrSize;
1898 }
1899
Frederic Rissb8b43d52015-03-04 22:07:44 +00001900 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001901 DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001902 return AttrSize;
1903}
1904
1905/// \brief Clone an attribute of block form (locations, constants) and add
1906/// it to \p Die.
1907/// \returns the size of the new attribute.
1908unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1909 const DWARFFormValue &Val,
1910 unsigned AttrSize) {
1911 DIE *Attr;
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001912 DIEValue Value;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001913 DIELoc *Loc = nullptr;
1914 DIEBlock *Block = nullptr;
1915 // Just copy the block data over.
Frederic Riss111a0a82015-03-13 18:35:39 +00001916 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001917 Loc = new (DIEAlloc) DIELoc;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001918 DIELocs.push_back(Loc);
1919 } else {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001920 Block = new (DIEAlloc) DIEBlock;
Frederic Rissb8b43d52015-03-04 22:07:44 +00001921 DIEBlocks.push_back(Block);
1922 }
1923 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00001924
1925 if (Loc)
1926 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1927 dwarf::Form(AttrSpec.Form), Loc);
1928 else
1929 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1930 dwarf::Form(AttrSpec.Form), Block);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001931 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1932 for (auto Byte : Bytes)
1933 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001934 DIEInteger(Byte));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001935 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1936 // the DIE class, this if could be replaced by
1937 // Attr->setSize(Bytes.size()).
1938 if (Streamer) {
1939 if (Loc)
1940 Loc->ComputeSize(&Streamer->getAsmPrinter());
1941 else
1942 Block->ComputeSize(&Streamer->getAsmPrinter());
1943 }
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00001944 Die.addValue(Value);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001945 return AttrSize;
1946}
1947
Frederic Riss31da3242015-03-11 18:45:52 +00001948/// \brief Clone an address attribute and add it to \p Die.
1949/// \returns the size of the new attribute.
1950unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1951 const DWARFFormValue &Val,
1952 const CompileUnit &Unit,
1953 AttributesInfo &Info) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001954 uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
Frederic Riss31da3242015-03-11 18:45:52 +00001955 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1956 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1957 Die.getTag() == dwarf::DW_TAG_lexical_block)
1958 Addr += Info.PCOffset;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001959 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1960 Addr = Unit.getLowPc();
1961 if (Addr == UINT64_MAX)
1962 return 0;
1963 }
Frederic Rissbce93ff2015-03-16 02:05:10 +00001964 Info.HasLowPc = true;
Frederic Riss31da3242015-03-11 18:45:52 +00001965 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
Frederic Riss5a62dc32015-03-13 18:35:54 +00001966 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1967 if (uint64_t HighPc = Unit.getHighPc())
1968 Addr = HighPc;
1969 else
1970 return 0;
1971 } else
1972 // If we have a high_pc recorded for the input DIE, use
1973 // it. Otherwise (when no relocations where applied) just use the
1974 // one we just decoded.
1975 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
Frederic Riss31da3242015-03-11 18:45:52 +00001976 }
1977
1978 Die.addValue(static_cast<dwarf::Attribute>(AttrSpec.Attr),
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001979 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
Frederic Riss31da3242015-03-11 18:45:52 +00001980 return Unit.getOrigUnit().getAddressByteSize();
1981}
1982
Frederic Rissb8b43d52015-03-04 22:07:44 +00001983/// \brief Clone a scalar attribute and add it to \p Die.
1984/// \returns the size of the new attribute.
1985unsigned DwarfLinker::cloneScalarAttribute(
Frederic Riss25440872015-03-13 23:30:31 +00001986 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
Frederic Rissdfb97902015-03-14 15:49:07 +00001987 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
Frederic Rissbce93ff2015-03-16 02:05:10 +00001988 AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001989 uint64_t Value;
Frederic Riss5a62dc32015-03-13 18:35:54 +00001990 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1991 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1992 if (Unit.getLowPc() == -1ULL)
1993 return 0;
1994 // Dwarf >= 4 high_pc is an size, not an address.
1995 Value = Unit.getHighPc() - Unit.getLowPc();
1996 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
Frederic Rissb8b43d52015-03-04 22:07:44 +00001997 Value = *Val.getAsSectionOffset();
1998 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1999 Value = *Val.getAsSignedConstant();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002000 else if (auto OptionalValue = Val.getAsUnsignedConstant())
2001 Value = *OptionalValue;
2002 else {
Frederic Riss5a62dc32015-03-13 18:35:54 +00002003 reportWarning("Unsupported scalar attribute form. Dropping attribute.",
2004 &Unit.getOrigUnit(), &InputDIE);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002005 return 0;
2006 }
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002007 DIEInteger Attr(Value);
Frederic Riss25440872015-03-13 23:30:31 +00002008 if (AttrSpec.Attr == dwarf::DW_AT_ranges)
Duncan P. N. Exon Smith88a8fc52015-05-27 22:44:06 +00002009 Unit.noteRangeAttribute(Die, PatchLocation(Die));
Frederic Rissdfb97902015-03-14 15:49:07 +00002010 // A more generic way to check for location attributes would be
2011 // nice, but it's very unlikely that any other attribute needs a
2012 // location list.
2013 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2014 AttrSpec.Attr == dwarf::DW_AT_frame_base)
Duncan P. N. Exon Smith88a8fc52015-05-27 22:44:06 +00002015 Unit.noteLocationAttribute(PatchLocation(Die), Info.PCOffset);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002016 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2017 Info.IsDeclaration = true;
Frederic Rissdfb97902015-03-14 15:49:07 +00002018
Frederic Rissb8b43d52015-03-04 22:07:44 +00002019 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Frederic Riss25440872015-03-13 23:30:31 +00002020 Attr);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002021 return AttrSize;
2022}
2023
2024/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2025/// value \p Val, and add it to \p Die.
2026/// \returns the size of the cloned attribute.
2027unsigned DwarfLinker::cloneAttribute(DIE &Die,
2028 const DWARFDebugInfoEntryMinimal &InputDIE,
2029 CompileUnit &Unit,
2030 const DWARFFormValue &Val,
2031 const AttributeSpec AttrSpec,
Frederic Riss31da3242015-03-11 18:45:52 +00002032 unsigned AttrSize, AttributesInfo &Info) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002033 const DWARFUnit &U = Unit.getOrigUnit();
2034
2035 switch (AttrSpec.Form) {
2036 case dwarf::DW_FORM_strp:
2037 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00002038 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002039 case dwarf::DW_FORM_ref_addr:
2040 case dwarf::DW_FORM_ref1:
2041 case dwarf::DW_FORM_ref2:
2042 case dwarf::DW_FORM_ref4:
2043 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00002044 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
Frederic Riss6afcfce2015-03-13 18:35:57 +00002045 Unit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002046 case dwarf::DW_FORM_block:
2047 case dwarf::DW_FORM_block1:
2048 case dwarf::DW_FORM_block2:
2049 case dwarf::DW_FORM_block4:
2050 case dwarf::DW_FORM_exprloc:
2051 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2052 case dwarf::DW_FORM_addr:
Frederic Riss31da3242015-03-11 18:45:52 +00002053 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002054 case dwarf::DW_FORM_data1:
2055 case dwarf::DW_FORM_data2:
2056 case dwarf::DW_FORM_data4:
2057 case dwarf::DW_FORM_data8:
2058 case dwarf::DW_FORM_udata:
2059 case dwarf::DW_FORM_sdata:
2060 case dwarf::DW_FORM_sec_offset:
2061 case dwarf::DW_FORM_flag:
2062 case dwarf::DW_FORM_flag_present:
Frederic Rissdfb97902015-03-14 15:49:07 +00002063 return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2064 Info);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002065 default:
2066 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2067 &InputDIE);
2068 }
2069
2070 return 0;
2071}
2072
Frederic Riss23e20e92015-03-07 01:25:09 +00002073/// \brief Apply the valid relocations found by findValidRelocs() to
2074/// the buffer \p Data, taking into account that Data is at \p BaseOffset
2075/// in the debug_info section.
2076///
2077/// Like for findValidRelocs(), this function must be called with
2078/// monotonic \p BaseOffset values.
2079///
2080/// \returns wether any reloc has been applied.
2081bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2082 uint32_t BaseOffset, bool isLittleEndian) {
Aaron Ballman6b329f52015-03-07 15:16:27 +00002083 assert((NextValidReloc == 0 ||
Frederic Rissaa983ce2015-03-11 18:45:57 +00002084 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2085 "BaseOffset should only be increasing.");
Frederic Riss23e20e92015-03-07 01:25:09 +00002086 if (NextValidReloc >= ValidRelocs.size())
2087 return false;
2088
2089 // Skip relocs that haven't been applied.
2090 while (NextValidReloc < ValidRelocs.size() &&
2091 ValidRelocs[NextValidReloc].Offset < BaseOffset)
2092 ++NextValidReloc;
2093
2094 bool Applied = false;
2095 uint64_t EndOffset = BaseOffset + Data.size();
2096 while (NextValidReloc < ValidRelocs.size() &&
2097 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2098 ValidRelocs[NextValidReloc].Offset < EndOffset) {
2099 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2100 assert(ValidReloc.Offset - BaseOffset < Data.size());
2101 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2102 char Buf[8];
2103 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2104 Value += ValidReloc.Addend;
2105 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2106 unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2107 Buf[i] = uint8_t(Value >> (Index * 8));
2108 }
2109 assert(ValidReloc.Size <= sizeof(Buf));
2110 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2111 Applied = true;
2112 }
2113
2114 return Applied;
2115}
2116
Frederic Rissbce93ff2015-03-16 02:05:10 +00002117static bool isTypeTag(uint16_t Tag) {
2118 switch (Tag) {
2119 case dwarf::DW_TAG_array_type:
2120 case dwarf::DW_TAG_class_type:
2121 case dwarf::DW_TAG_enumeration_type:
2122 case dwarf::DW_TAG_pointer_type:
2123 case dwarf::DW_TAG_reference_type:
2124 case dwarf::DW_TAG_string_type:
2125 case dwarf::DW_TAG_structure_type:
2126 case dwarf::DW_TAG_subroutine_type:
2127 case dwarf::DW_TAG_typedef:
2128 case dwarf::DW_TAG_union_type:
2129 case dwarf::DW_TAG_ptr_to_member_type:
2130 case dwarf::DW_TAG_set_type:
2131 case dwarf::DW_TAG_subrange_type:
2132 case dwarf::DW_TAG_base_type:
2133 case dwarf::DW_TAG_const_type:
2134 case dwarf::DW_TAG_constant:
2135 case dwarf::DW_TAG_file_type:
2136 case dwarf::DW_TAG_namelist:
2137 case dwarf::DW_TAG_packed_type:
2138 case dwarf::DW_TAG_volatile_type:
2139 case dwarf::DW_TAG_restrict_type:
2140 case dwarf::DW_TAG_interface_type:
2141 case dwarf::DW_TAG_unspecified_type:
2142 case dwarf::DW_TAG_shared_type:
2143 return true;
2144 default:
2145 break;
2146 }
2147 return false;
2148}
2149
Frederic Rissb8b43d52015-03-04 22:07:44 +00002150/// \brief Recursively clone \p InputDIE's subtrees that have been
2151/// selected to appear in the linked output.
2152///
2153/// \param OutOffset is the Offset where the newly created DIE will
2154/// lie in the linked compile unit.
2155///
2156/// \returns the cloned DIE object or null if nothing was selected.
2157DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
Frederic Riss31da3242015-03-11 18:45:52 +00002158 CompileUnit &Unit, int64_t PCOffset,
2159 uint32_t OutOffset) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002160 DWARFUnit &U = Unit.getOrigUnit();
2161 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00002162 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002163
2164 // Should the DIE appear in the output?
2165 if (!Unit.getInfo(Idx).Keep)
2166 return nullptr;
2167
2168 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00002169 // The DIE might have been already created by a forward reference
2170 // (see cloneDieReferenceAttribute()).
2171 DIE *Die = Info.Clone;
2172 if (!Die)
2173 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
2174 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002175 Die->setOffset(OutOffset);
2176
2177 // Extract and clone every attribute.
2178 DataExtractor Data = U.getDebugInfoExtractor();
Frederic Riss23e20e92015-03-07 01:25:09 +00002179 uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
Frederic Riss31da3242015-03-11 18:45:52 +00002180 AttributesInfo AttrInfo;
Frederic Riss23e20e92015-03-07 01:25:09 +00002181
2182 // We could copy the data only if we need to aply a relocation to
2183 // it. After testing, it seems there is no performance downside to
2184 // doing the copy unconditionally, and it makes the code simpler.
2185 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2186 Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2187 // Modify the copy with relocated addresses.
Frederic Riss31da3242015-03-11 18:45:52 +00002188 if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2189 // If we applied relocations, we store the value of high_pc that was
2190 // potentially stored in the input DIE. If high_pc is an address
2191 // (Dwarf version == 2), then it might have been relocated to a
2192 // totally unrelated value (because the end address in the object
2193 // file might be start address of another function which got moved
2194 // independantly by the linker). The computation of the actual
2195 // high_pc value is done in cloneAddressAttribute().
2196 AttrInfo.OrigHighPc =
2197 InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2198 }
Frederic Riss23e20e92015-03-07 01:25:09 +00002199
2200 // Reset the Offset to 0 as we will be working on the local copy of
2201 // the data.
2202 Offset = 0;
2203
Frederic Rissb8b43d52015-03-04 22:07:44 +00002204 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2205 Offset += getULEB128Size(Abbrev->getCode());
2206
Frederic Riss31da3242015-03-11 18:45:52 +00002207 // We are entering a subprogram. Get and propagate the PCOffset.
2208 if (Die->getTag() == dwarf::DW_TAG_subprogram)
2209 PCOffset = Info.AddrAdjust;
2210 AttrInfo.PCOffset = PCOffset;
2211
Frederic Rissb8b43d52015-03-04 22:07:44 +00002212 for (const auto &AttrSpec : Abbrev->attributes()) {
2213 DWARFFormValue Val(AttrSpec.Form);
2214 uint32_t AttrSize = Offset;
2215 Val.extractValue(Data, &Offset, &U);
2216 AttrSize = Offset - AttrSize;
2217
Frederic Riss31da3242015-03-11 18:45:52 +00002218 OutOffset +=
2219 cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002220 }
2221
Frederic Rissbce93ff2015-03-16 02:05:10 +00002222 // Look for accelerator entries.
2223 uint16_t Tag = InputDIE.getTag();
2224 // FIXME: This is slightly wrong. An inline_subroutine without a
2225 // low_pc, but with AT_ranges might be interesting to get into the
2226 // accelerator tables too. For now stick with dsymutil's behavior.
2227 if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2228 Tag != dwarf::DW_TAG_compile_unit &&
2229 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2230 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2231 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2232 AttrInfo.MangledNameOffset,
2233 Tag == dwarf::DW_TAG_inlined_subroutine);
2234 if (AttrInfo.Name)
2235 Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2236 Tag == dwarf::DW_TAG_inlined_subroutine);
2237 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2238 getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2239 Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2240 }
2241
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002242 DIEAbbrev NewAbbrev = Die->generateAbbrev();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002243 // If a scope DIE is kept, we must have kept at least one child. If
2244 // it's not the case, we'll just be emitting one wasteful end of
2245 // children marker, but things won't break.
2246 if (InputDIE.hasChildren())
2247 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2248 // Assign a permanent abbrev number
Duncan P. N. Exon Smith815a6eb52015-05-27 22:31:41 +00002249 AssignAbbrev(NewAbbrev);
2250 Die->setAbbrevNumber(NewAbbrev.getNumber());
Frederic Rissb8b43d52015-03-04 22:07:44 +00002251
2252 // Add the size of the abbreviation number to the output offset.
2253 OutOffset += getULEB128Size(Die->getAbbrevNumber());
2254
2255 if (!Abbrev->hasChildren()) {
2256 // Update our size.
2257 Die->setSize(OutOffset - Die->getOffset());
2258 return Die;
2259 }
2260
2261 // Recursively clone children.
2262 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2263 Child = Child->getSibling()) {
Frederic Riss31da3242015-03-11 18:45:52 +00002264 if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002265 Die->addChild(std::unique_ptr<DIE>(Clone));
2266 OutOffset = Clone->getOffset() + Clone->getSize();
2267 }
2268 }
2269
2270 // Account for the end of children marker.
2271 OutOffset += sizeof(int8_t);
2272 // Update our size.
2273 Die->setSize(OutOffset - Die->getOffset());
2274 return Die;
2275}
2276
Frederic Riss25440872015-03-13 23:30:31 +00002277/// \brief Patch the input object file relevant debug_ranges entries
2278/// and emit them in the output file. Update the relevant attributes
2279/// to point at the new entries.
2280void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2281 DWARFContext &OrigDwarf) const {
2282 DWARFDebugRangeList RangeList;
2283 const auto &FunctionRanges = Unit.getFunctionRanges();
2284 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2285 DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2286 OrigDwarf.isLittleEndian(), AddressSize);
2287 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2288 DWARFUnit &OrigUnit = Unit.getOrigUnit();
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002289 const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
Frederic Riss25440872015-03-13 23:30:31 +00002290 uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2291 &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2292 // Ranges addresses are based on the unit's low_pc. Compute the
2293 // offset we need to apply to adapt to the the new unit's low_pc.
2294 int64_t UnitPcOffset = 0;
2295 if (OrigLowPc != -1ULL)
2296 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2297
2298 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002299 uint32_t Offset = RangeAttribute.get();
2300 RangeAttribute.set(Streamer->getRangesSectionSize());
Frederic Riss25440872015-03-13 23:30:31 +00002301 RangeList.extract(RangeExtractor, &Offset);
2302 const auto &Entries = RangeList.getEntries();
2303 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2304
2305 if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2306 First.StartAddress >= CurrRange.stop()) {
2307 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2308 if (CurrRange == InvalidRange ||
2309 CurrRange.start() > First.StartAddress + OrigLowPc) {
2310 reportWarning("no mapping for range.");
2311 continue;
2312 }
2313 }
2314
2315 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2316 AddressSize);
2317 }
2318}
2319
Frederic Riss563b1b02015-03-14 03:46:51 +00002320/// \brief Generate the debug_aranges entries for \p Unit and if the
2321/// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2322/// contribution for this attribute.
Frederic Riss25440872015-03-13 23:30:31 +00002323/// FIXME: this could actually be done right in patchRangesForUnit,
2324/// but for the sake of initial bit-for-bit compatibility with legacy
2325/// dsymutil, we have to do it in a delayed pass.
2326void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002327 auto Attr = Unit.getUnitRangesAttribute();
Frederic Riss563b1b02015-03-14 03:46:51 +00002328 if (Attr)
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00002329 Attr->set(Streamer->getRangesSectionSize());
2330 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
Frederic Riss25440872015-03-13 23:30:31 +00002331}
2332
Frederic Riss63786b02015-03-15 20:45:43 +00002333/// \brief Insert the new line info sequence \p Seq into the current
2334/// set of already linked line info \p Rows.
2335static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2336 std::vector<DWARFDebugLine::Row> &Rows) {
2337 if (Seq.empty())
2338 return;
2339
2340 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2341 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2342 Seq.clear();
2343 return;
2344 }
2345
2346 auto InsertPoint = std::lower_bound(
2347 Rows.begin(), Rows.end(), Seq.front(),
2348 [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2349 return LHS.Address < RHS.Address;
2350 });
2351
2352 // FIXME: this only removes the unneeded end_sequence if the
2353 // sequences have been inserted in order. using a global sort like
2354 // described in patchLineTableForUnit() and delaying the end_sequene
2355 // elimination to emitLineTableForUnit() we can get rid of all of them.
2356 if (InsertPoint != Rows.end() &&
2357 InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2358 *InsertPoint = Seq.front();
2359 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2360 } else {
2361 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2362 }
2363
2364 Seq.clear();
2365}
2366
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002367static void patchStmtList(DIE &Die, DIEInteger Offset) {
2368 for (auto &V : Die.values())
2369 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
2370 Die.setValue(&V - Die.values_begin(),
2371 DIEValue(V.getAttribute(), V.getForm(), Offset));
2372 return;
2373 }
2374
2375 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2376}
2377
Frederic Riss63786b02015-03-15 20:45:43 +00002378/// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2379/// recreate a relocated version of these for the address ranges that
2380/// are present in the binary.
2381void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2382 DWARFContext &OrigDwarf) {
Frederic Rissf37964c2015-06-05 20:27:07 +00002383 const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
Frederic Riss63786b02015-03-15 20:45:43 +00002384 uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2385 &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2386 if (StmtList == -1ULL)
2387 return;
2388
2389 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
Duncan P. N. Exon Smithaed187c2015-06-25 21:42:46 +00002390 if (auto *OutputDIE = Unit.getOutputUnitDIE())
2391 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
Frederic Riss63786b02015-03-15 20:45:43 +00002392
2393 // Parse the original line info for the unit.
2394 DWARFDebugLine::LineTable LineTable;
2395 uint32_t StmtOffset = StmtList;
2396 StringRef LineData = OrigDwarf.getLineSection().Data;
2397 DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2398 Unit.getOrigUnit().getAddressByteSize());
2399 LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2400 &StmtOffset);
2401
2402 // This vector is the output line table.
2403 std::vector<DWARFDebugLine::Row> NewRows;
2404 NewRows.reserve(LineTable.Rows.size());
2405
2406 // Current sequence of rows being extracted, before being inserted
2407 // in NewRows.
2408 std::vector<DWARFDebugLine::Row> Seq;
2409 const auto &FunctionRanges = Unit.getFunctionRanges();
2410 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2411
2412 // FIXME: This logic is meant to generate exactly the same output as
2413 // Darwin's classic dsynutil. There is a nicer way to implement this
2414 // by simply putting all the relocated line info in NewRows and simply
2415 // sorting NewRows before passing it to emitLineTableForUnit. This
2416 // should be correct as sequences for a function should stay
2417 // together in the sorted output. There are a few corner cases that
2418 // look suspicious though, and that required to implement the logic
2419 // this way. Revisit that once initial validation is finished.
2420
2421 // Iterate over the object file line info and extract the sequences
2422 // that correspond to linked functions.
2423 for (auto &Row : LineTable.Rows) {
2424 // Check wether we stepped out of the range. The range is
2425 // half-open, but consider accept the end address of the range if
2426 // it is marked as end_sequence in the input (because in that
2427 // case, the relocation offset is accurate and that entry won't
2428 // serve as the start of another function).
2429 if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2430 Row.Address > CurrRange.stop() ||
2431 (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2432 // We just stepped out of a known range. Insert a end_sequence
2433 // corresponding to the end of the range.
2434 uint64_t StopAddress = CurrRange != InvalidRange
2435 ? CurrRange.stop() + CurrRange.value()
2436 : -1ULL;
2437 CurrRange = FunctionRanges.find(Row.Address);
2438 bool CurrRangeValid =
2439 CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2440 if (!CurrRangeValid) {
2441 CurrRange = InvalidRange;
2442 if (StopAddress != -1ULL) {
2443 // Try harder by looking in the DebugMapObject function
2444 // ranges map. There are corner cases where this finds a
2445 // valid entry. It's unclear if this is right or wrong, but
2446 // for now do as dsymutil.
2447 // FIXME: Understand exactly what cases this addresses and
2448 // potentially remove it along with the Ranges map.
2449 auto Range = Ranges.lower_bound(Row.Address);
2450 if (Range != Ranges.begin() && Range != Ranges.end())
2451 --Range;
2452
2453 if (Range != Ranges.end() && Range->first <= Row.Address &&
2454 Range->second.first >= Row.Address) {
2455 StopAddress = Row.Address + Range->second.second;
2456 }
2457 }
2458 }
2459 if (StopAddress != -1ULL && !Seq.empty()) {
2460 // Insert end sequence row with the computed end address, but
2461 // the same line as the previous one.
2462 Seq.emplace_back(Seq.back());
2463 Seq.back().Address = StopAddress;
2464 Seq.back().EndSequence = 1;
2465 Seq.back().PrologueEnd = 0;
2466 Seq.back().BasicBlock = 0;
2467 Seq.back().EpilogueBegin = 0;
2468 insertLineSequence(Seq, NewRows);
2469 }
2470
2471 if (!CurrRangeValid)
2472 continue;
2473 }
2474
2475 // Ignore empty sequences.
2476 if (Row.EndSequence && Seq.empty())
2477 continue;
2478
2479 // Relocate row address and add it to the current sequence.
2480 Row.Address += CurrRange.value();
2481 Seq.emplace_back(Row);
2482
2483 if (Row.EndSequence)
2484 insertLineSequence(Seq, NewRows);
2485 }
2486
2487 // Finished extracting, now emit the line tables.
2488 uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2489 // FIXME: LLVM hardcodes it's prologue values. We just copy the
2490 // prologue over and that works because we act as both producer and
2491 // consumer. It would be nicer to have a real configurable line
2492 // table emitter.
2493 if (LineTable.Prologue.Version != 2 ||
2494 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2495 LineTable.Prologue.LineBase != -5 || LineTable.Prologue.LineRange != 14 ||
2496 LineTable.Prologue.OpcodeBase != 13)
2497 reportWarning("line table paramters mismatch. Cannot emit.");
2498 else
2499 Streamer->emitLineTableForUnit(LineData.slice(StmtList + 4, PrologueEnd),
2500 LineTable.Prologue.MinInstLength, NewRows,
2501 Unit.getOrigUnit().getAddressByteSize());
2502}
2503
Frederic Rissbce93ff2015-03-16 02:05:10 +00002504void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2505 Streamer->emitPubNamesForUnit(Unit);
2506 Streamer->emitPubTypesForUnit(Unit);
2507}
2508
Frederic Riss5a642072015-06-05 23:06:11 +00002509/// \brief Read the frame info stored in the object, and emit the
2510/// patched frame descriptions for the linked binary.
2511///
2512/// This is actually pretty easy as the data of the CIEs and FDEs can
2513/// be considered as black boxes and moved as is. The only thing to do
2514/// is to patch the addresses in the headers.
2515void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2516 DWARFContext &OrigDwarf,
2517 unsigned AddrSize) {
2518 StringRef FrameData = OrigDwarf.getDebugFrameSection();
2519 if (FrameData.empty())
2520 return;
2521
2522 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2523 uint32_t InputOffset = 0;
2524
2525 // Store the data of the CIEs defined in this object, keyed by their
2526 // offsets.
2527 DenseMap<uint32_t, StringRef> LocalCIES;
2528
2529 while (Data.isValidOffset(InputOffset)) {
2530 uint32_t EntryOffset = InputOffset;
2531 uint32_t InitialLength = Data.getU32(&InputOffset);
2532 if (InitialLength == 0xFFFFFFFF)
2533 return reportWarning("Dwarf64 bits no supported");
2534
2535 uint32_t CIEId = Data.getU32(&InputOffset);
2536 if (CIEId == 0xFFFFFFFF) {
2537 // This is a CIE, store it.
2538 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2539 LocalCIES[EntryOffset] = CIEData;
2540 // The -4 is to account for the CIEId we just read.
2541 InputOffset += InitialLength - 4;
2542 continue;
2543 }
2544
2545 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2546
2547 // Some compilers seem to emit frame info that doesn't start at
2548 // the function entry point, thus we can't just lookup the address
2549 // in the debug map. Use the linker's range map to see if the FDE
2550 // describes something that we can relocate.
2551 auto Range = Ranges.upper_bound(Loc);
2552 if (Range != Ranges.begin())
2553 --Range;
2554 if (Range == Ranges.end() || Range->first > Loc ||
2555 Range->second.first <= Loc) {
2556 // The +4 is to account for the size of the InitialLength field itself.
2557 InputOffset = EntryOffset + InitialLength + 4;
2558 continue;
2559 }
2560
2561 // This is an FDE, and we have a mapping.
2562 // Have we already emitted a corresponding CIE?
2563 StringRef CIEData = LocalCIES[CIEId];
2564 if (CIEData.empty())
2565 return reportWarning("Inconsistent debug_frame content. Dropping.");
2566
2567 // Look if we already emitted a CIE that corresponds to the
2568 // referenced one (the CIE data is the key of that lookup).
2569 auto IteratorInserted = EmittedCIEs.insert(
2570 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
2571 // If there is no CIE yet for this ID, emit it.
2572 if (IteratorInserted.second ||
2573 // FIXME: dsymutil-classic only caches the last used CIE for
2574 // reuse. Mimic that behavior for now. Just removing that
2575 // second half of the condition and the LastCIEOffset variable
2576 // makes the code DTRT.
2577 LastCIEOffset != IteratorInserted.first->getValue()) {
2578 LastCIEOffset = Streamer->getFrameSectionSize();
2579 IteratorInserted.first->getValue() = LastCIEOffset;
2580 Streamer->emitCIE(CIEData);
2581 }
2582
2583 // Emit the FDE with updated address and CIE pointer.
2584 // (4 + AddrSize) is the size of the CIEId + initial_location
2585 // fields that will get reconstructed by emitFDE().
2586 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
2587 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
2588 Loc + Range->second.second,
2589 FrameData.substr(InputOffset, FDERemainingBytes));
2590 InputOffset += FDERemainingBytes;
2591 }
2592}
2593
Frederic Rissd3455182015-01-28 18:27:01 +00002594bool DwarfLinker::link(const DebugMap &Map) {
2595
2596 if (Map.begin() == Map.end()) {
2597 errs() << "Empty debug map.\n";
2598 return false;
2599 }
2600
Frederic Rissc99ea202015-02-28 00:29:11 +00002601 if (!createStreamer(Map.getTriple(), OutputFilename))
2602 return false;
2603
Frederic Rissb8b43d52015-03-04 22:07:44 +00002604 // Size of the DIEs (and headers) generated for the linked output.
2605 uint64_t OutputDebugInfoSize = 0;
Frederic Riss3cced052015-03-14 03:46:40 +00002606 // A unique ID that identifies each compile unit.
2607 unsigned UnitID = 0;
Frederic Rissd3455182015-01-28 18:27:01 +00002608 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002609 CurrentDebugObject = Obj.get();
2610
Frederic Rissb9818322015-02-28 00:29:07 +00002611 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00002612 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
2613 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
2614 if (std::error_code EC = ErrOrObj.getError()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00002615 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
Frederic Rissd3455182015-01-28 18:27:01 +00002616 continue;
2617 }
2618
Frederic Riss1036e642015-02-13 23:18:22 +00002619 // Look for relocations that correspond to debug map entries.
2620 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00002621 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00002622 outs() << "No valid relocations found. Skipping.\n";
2623 continue;
2624 }
2625
Frederic Riss563cba62015-01-28 22:15:14 +00002626 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00002627 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss63786b02015-03-15 20:45:43 +00002628 startDebugObject(DwarfContext, *Obj);
Frederic Rissd3455182015-01-28 18:27:01 +00002629
Frederic Riss563cba62015-01-28 22:15:14 +00002630 // In a first phase, just read in the debug info and store the DIE
2631 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00002632 for (const auto &CU : DwarfContext.compile_units()) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002633 auto *CUDie = CU->getUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00002634 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00002635 outs() << "Input compilation unit:";
2636 CUDie->dump(outs(), CU.get(), 0);
2637 }
Frederic Riss3cced052015-03-14 03:46:40 +00002638 Units.emplace_back(*CU, UnitID++);
Frederic Riss9aa725b2015-02-13 23:18:31 +00002639 gatherDIEParents(CUDie, 0, Units.back());
Frederic Rissd3455182015-01-28 18:27:01 +00002640 }
Frederic Riss563cba62015-01-28 22:15:14 +00002641
Frederic Riss84c09a52015-02-13 23:18:34 +00002642 // Then mark all the DIEs that need to be present in the linked
2643 // output and collect some information about them. Note that this
2644 // loop can not be merged with the previous one becaue cross-cu
2645 // references require the ParentIdx to be setup for every CU in
2646 // the object file before calling this.
2647 for (auto &CurrentUnit : Units)
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002648 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
Frederic Riss84c09a52015-02-13 23:18:34 +00002649 CurrentUnit, 0);
2650
Frederic Riss23e20e92015-03-07 01:25:09 +00002651 // The calls to applyValidRelocs inside cloneDIE will walk the
2652 // reloc array again (in the same way findValidRelocsInDebugInfo()
2653 // did). We need to reset the NextValidReloc index to the beginning.
2654 NextValidReloc = 0;
2655
Frederic Rissb8b43d52015-03-04 22:07:44 +00002656 // Construct the output DIE tree by cloning the DIEs we chose to
2657 // keep above. If there are no valid relocs, then there's nothing
2658 // to clone/emit.
2659 if (!ValidRelocs.empty())
2660 for (auto &CurrentUnit : Units) {
Alexey Samsonov7a18c062015-05-19 21:54:32 +00002661 const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00002662 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Riss31da3242015-03-11 18:45:52 +00002663 DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
2664 11 /* Unit Header size */);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002665 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00002666 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Riss63786b02015-03-15 20:45:43 +00002667 if (Options.NoOutput)
2668 continue;
2669 // FIXME: for compatibility with the classic dsymutil, we emit
2670 // an empty line table for the unit, even if the unit doesn't
2671 // actually exist in the DIE tree.
2672 patchLineTableForUnit(CurrentUnit, DwarfContext);
2673 if (!OutputDIE)
Frederic Riss25440872015-03-13 23:30:31 +00002674 continue;
2675 patchRangesForUnit(CurrentUnit, DwarfContext);
Frederic Rissdfb97902015-03-14 15:49:07 +00002676 Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
Frederic Rissbce93ff2015-03-16 02:05:10 +00002677 emitAcceleratorEntriesForUnit(CurrentUnit);
Frederic Rissb8b43d52015-03-04 22:07:44 +00002678 }
2679
2680 // Emit all the compile unit's debug information.
2681 if (!ValidRelocs.empty() && !Options.NoOutput)
2682 for (auto &CurrentUnit : Units) {
Frederic Riss25440872015-03-13 23:30:31 +00002683 generateUnitRanges(CurrentUnit);
Frederic Riss9833de62015-03-06 23:22:53 +00002684 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00002685 Streamer->emitCompileUnitHeader(CurrentUnit);
2686 if (!CurrentUnit.getOutputUnitDIE())
2687 continue;
2688 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
2689 }
2690
Frederic Riss5a642072015-06-05 23:06:11 +00002691 if (!ValidRelocs.empty() && !Options.NoOutput && !Units.empty())
2692 patchFrameInfoForObject(*Obj, DwarfContext,
2693 Units[0].getOrigUnit().getAddressByteSize());
2694
Frederic Riss563cba62015-01-28 22:15:14 +00002695 // Clean-up before starting working on the next object.
2696 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00002697 }
2698
Frederic Rissb8b43d52015-03-04 22:07:44 +00002699 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00002700 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00002701 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00002702 Streamer->emitStrings(StringPool);
2703 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00002704
Frederic Rissc99ea202015-02-28 00:29:11 +00002705 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00002706}
2707}
Frederic Rissd3455182015-01-28 18:27:01 +00002708
Frederic Rissb9818322015-02-28 00:29:07 +00002709bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
2710 const LinkOptions &Options) {
2711 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00002712 return Linker.link(DM);
2713}
2714}
Frederic Riss231f7142014-12-12 17:31:24 +00002715}