blob: f71d83b31d444e54d57c0aa4cfe3351aea6f9a3d [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 Rissc99ea202015-02-28 00:29:11 +000013#include "llvm/CodeGen/AsmPrinter.h"
Frederic Rissb8b43d52015-03-04 22:07:44 +000014#include "llvm/CodeGen/DIE.h"
Zachary Turner82af9432015-01-30 18:07:45 +000015#include "llvm/DebugInfo/DWARF/DWARFContext.h"
16#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
Frederic Riss1b9da422015-02-13 23:18:29 +000017#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000018#include "llvm/MC/MCAsmBackend.h"
19#include "llvm/MC/MCAsmInfo.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCCodeEmitter.h"
22#include "llvm/MC/MCInstrInfo.h"
23#include "llvm/MC/MCObjectFileInfo.h"
24#include "llvm/MC/MCRegisterInfo.h"
25#include "llvm/MC/MCStreamer.h"
Frederic Riss1036e642015-02-13 23:18:22 +000026#include "llvm/Object/MachO.h"
Frederic Riss84c09a52015-02-13 23:18:34 +000027#include "llvm/Support/Dwarf.h"
28#include "llvm/Support/LEB128.h"
Frederic Rissc99ea202015-02-28 00:29:11 +000029#include "llvm/Support/TargetRegistry.h"
30#include "llvm/Target/TargetMachine.h"
31#include "llvm/Target/TargetOptions.h"
Frederic Rissd3455182015-01-28 18:27:01 +000032#include <string>
Frederic Riss231f7142014-12-12 17:31:24 +000033
34namespace llvm {
35namespace dsymutil {
36
Frederic Rissd3455182015-01-28 18:27:01 +000037namespace {
38
Frederic Rissdef4fb72015-02-28 00:29:01 +000039void warn(const Twine &Warning, const Twine &Context) {
40 errs() << Twine("while processing ") + Context + ":\n";
41 errs() << Twine("warning: ") + Warning + "\n";
42}
43
Frederic Rissc99ea202015-02-28 00:29:11 +000044bool error(const Twine &Error, const Twine &Context) {
45 errs() << Twine("while processing ") + Context + ":\n";
46 errs() << Twine("error: ") + Error + "\n";
47 return false;
48}
49
Frederic Riss563cba62015-01-28 22:15:14 +000050/// \brief Stores all information relating to a compile unit, be it in
51/// its original instance in the object file to its brand new cloned
52/// and linked DIE tree.
53class CompileUnit {
54public:
55 /// \brief Information gathered about a DIE in the object file.
56 struct DIEInfo {
Frederic Riss84c09a52015-02-13 23:18:34 +000057 uint64_t Address; ///< Linked address of the described entity.
Frederic Riss9833de62015-03-06 23:22:53 +000058 DIE *Clone; ///< Cloned version of that DIE.
Frederic Riss84c09a52015-02-13 23:18:34 +000059 uint32_t ParentIdx; ///< The index of this DIE's parent.
60 bool Keep; ///< Is the DIE part of the linked output?
61 bool InDebugMap; ///< Was this DIE's entity found in the map?
Frederic Riss563cba62015-01-28 22:15:14 +000062 };
63
64 CompileUnit(DWARFUnit &OrigUnit) : OrigUnit(OrigUnit) {
65 Info.resize(OrigUnit.getNumDIEs());
66 }
67
David Blaikiea8adc132015-03-04 22:20:52 +000068 // Workaround MSVC not supporting implicit move ops
Frederic Riss2838f9e2015-03-05 05:29:05 +000069 CompileUnit(CompileUnit &&RHS)
70 : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
71 CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
72 NextUnitOffset(RHS.NextUnitOffset) {}
David Blaikiea8adc132015-03-04 22:20:52 +000073
Frederic Rissc3349d42015-02-13 23:18:27 +000074 DWARFUnit &getOrigUnit() const { return OrigUnit; }
Frederic Riss563cba62015-01-28 22:15:14 +000075
Frederic Rissb8b43d52015-03-04 22:07:44 +000076 DIE *getOutputUnitDIE() const { return CUDie.get(); }
77 void setOutputUnitDIE(DIE *Die) { CUDie.reset(Die); }
78
Frederic Riss563cba62015-01-28 22:15:14 +000079 DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
80 const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
81
Frederic Rissb8b43d52015-03-04 22:07:44 +000082 uint64_t getStartOffset() const { return StartOffset; }
83 uint64_t getNextUnitOffset() const { return NextUnitOffset; }
84
Frederic Riss9d441b62015-03-06 23:22:50 +000085 void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
86
87 /// \brief Compute the end offset for this unit. Must be
88 /// called after the CU's DIEs have been cloned.
Frederic Rissb8b43d52015-03-04 22:07:44 +000089 /// \returns the next unit offset (which is also the current
90 /// debug_info section size).
Frederic Riss9d441b62015-03-06 23:22:50 +000091 uint64_t computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +000092
Frederic Riss9833de62015-03-06 23:22:53 +000093 /// \brief Keep track of a forward reference to DIE \p Die by
94 /// \p Attr. The attribute should be fixed up later to point to the
95 /// absolute offset of \p Die in the debug_info section.
96 void noteForwardReference(DIE *Die, DIEInteger *Attr);
97
98 /// \brief Apply all fixups recored by noteForwardReference().
99 void fixupForwardReferences();
100
Frederic Riss563cba62015-01-28 22:15:14 +0000101private:
102 DWARFUnit &OrigUnit;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000103 std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
104 std::unique_ptr<DIE> CUDie; ///< Root of the linked DIE tree.
105
106 uint64_t StartOffset;
107 uint64_t NextUnitOffset;
Frederic Riss9833de62015-03-06 23:22:53 +0000108
109 /// \brief A list of attributes to fixup with the absolute offset of
110 /// a DIE in the debug_info section.
111 ///
112 /// The offsets for the attributes in this array couldn't be set while
113 /// cloning because for forward refences the target DIE's offset isn't
114 /// known you emit the reference attribute.
115 std::vector<std::pair<DIE *, DIEInteger *>> ForwardDIEReferences;
Frederic Riss563cba62015-01-28 22:15:14 +0000116};
117
Frederic Riss9d441b62015-03-06 23:22:50 +0000118uint64_t CompileUnit::computeNextUnitOffset() {
Frederic Rissb8b43d52015-03-04 22:07:44 +0000119 NextUnitOffset = StartOffset + 11 /* Header size */;
120 // The root DIE might be null, meaning that the Unit had nothing to
121 // contribute to the linked output. In that case, we will emit the
122 // unit header without any actual DIE.
123 if (CUDie)
124 NextUnitOffset += CUDie->getSize();
125 return NextUnitOffset;
126}
127
Frederic Riss9833de62015-03-06 23:22:53 +0000128/// \brief Keep track of a forward reference to \p Die.
129void CompileUnit::noteForwardReference(DIE *Die, DIEInteger *Attr) {
130 ForwardDIEReferences.emplace_back(Die, Attr);
131}
132
133/// \brief Apply all fixups recorded by noteForwardReference().
134void CompileUnit::fixupForwardReferences() {
135 for (const auto &Ref : ForwardDIEReferences)
136 Ref.second->setValue(Ref.first->getOffset() + getStartOffset());
137}
138
Frederic Rissef648462015-03-06 17:56:30 +0000139/// \brief A string table that doesn't need relocations.
140///
141/// We are doing a final link, no need for a string table that
142/// has relocation entries for every reference to it. This class
143/// provides this ablitity by just associating offsets with
144/// strings.
145class NonRelocatableStringpool {
146public:
147 /// \brief Entries are stored into the StringMap and simply linked
148 /// together through the second element of this pair in order to
149 /// keep track of insertion order.
150 typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
151 MapTy;
152
153 NonRelocatableStringpool()
154 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
155 // Legacy dsymutil puts an empty string at the start of the line
156 // table.
157 getStringOffset("");
158 }
159
160 /// \brief Get the offset of string \p S in the string table. This
161 /// can insert a new element or return the offset of a preexisitng
162 /// one.
163 uint32_t getStringOffset(StringRef S);
164
165 /// \brief Get permanent storage for \p S (but do not necessarily
166 /// emit \p S in the output section).
167 /// \returns The StringRef that points to permanent storage to use
168 /// in place of \p S.
169 StringRef internString(StringRef S);
170
171 // \brief Return the first entry of the string table.
172 const MapTy::MapEntryTy *getFirstEntry() const {
173 return getNextEntry(&Sentinel);
174 }
175
176 // \brief Get the entry following \p E in the string table or null
177 // if \p E was the last entry.
178 const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
179 return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
180 }
181
182 uint64_t getSize() { return CurrentEndOffset; }
183
184private:
185 MapTy Strings;
186 uint32_t CurrentEndOffset;
187 MapTy::MapEntryTy Sentinel, *Last;
188};
189
190/// \brief Get the offset of string \p S in the string table. This
191/// can insert a new element or return the offset of a preexisitng
192/// one.
193uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
194 if (S.empty() && !Strings.empty())
195 return 0;
196
197 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
198 MapTy::iterator It;
199 bool Inserted;
200
201 // A non-empty string can't be at offset 0, so if we have an entry
202 // with a 0 offset, it must be a previously interned string.
203 std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
204 if (Inserted || It->getValue().first == 0) {
205 // Set offset and chain at the end of the entries list.
206 It->getValue().first = CurrentEndOffset;
207 CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
208 Last->getValue().second = &*It;
209 Last = &*It;
210 }
211 return It->getValue().first;
212};
213
214/// \brief Put \p S into the StringMap so that it gets permanent
215/// storage, but do not actually link it in the chain of elements
216/// that go into the output section. A latter call to
217/// getStringOffset() with the same string will chain it though.
218StringRef NonRelocatableStringpool::internString(StringRef S) {
219 std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
220 auto InsertResult = Strings.insert(std::make_pair(S, Entry));
221 return InsertResult.first->getKey();
222};
223
Frederic Rissc99ea202015-02-28 00:29:11 +0000224/// \brief The Dwarf streaming logic
225///
226/// All interactions with the MC layer that is used to build the debug
227/// information binary representation are handled in this class.
228class DwarfStreamer {
229 /// \defgroup MCObjects MC layer objects constructed by the streamer
230 /// @{
231 std::unique_ptr<MCRegisterInfo> MRI;
232 std::unique_ptr<MCAsmInfo> MAI;
233 std::unique_ptr<MCObjectFileInfo> MOFI;
234 std::unique_ptr<MCContext> MC;
235 MCAsmBackend *MAB; // Owned by MCStreamer
236 std::unique_ptr<MCInstrInfo> MII;
237 std::unique_ptr<MCSubtargetInfo> MSTI;
238 MCCodeEmitter *MCE; // Owned by MCStreamer
239 MCStreamer *MS; // Owned by AsmPrinter
240 std::unique_ptr<TargetMachine> TM;
241 std::unique_ptr<AsmPrinter> Asm;
242 /// @}
243
244 /// \brief the file we stream the linked Dwarf to.
245 std::unique_ptr<raw_fd_ostream> OutFile;
246
247public:
248 /// \brief Actually create the streamer and the ouptut file.
249 ///
250 /// This could be done directly in the constructor, but it feels
251 /// more natural to handle errors through return value.
252 bool init(Triple TheTriple, StringRef OutputFilename);
253
Frederic Rissb8b43d52015-03-04 22:07:44 +0000254 /// \brief Dump the file to the disk.
Frederic Rissc99ea202015-02-28 00:29:11 +0000255 bool finish();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000256
257 AsmPrinter &getAsmPrinter() const { return *Asm; }
258
259 /// \brief Set the current output section to debug_info and change
260 /// the MC Dwarf version to \p DwarfVersion.
261 void switchToDebugInfoSection(unsigned DwarfVersion);
262
263 /// \brief Emit the compilation unit header for \p Unit in the
264 /// debug_info section.
265 ///
266 /// As a side effect, this also switches the current Dwarf version
267 /// of the MC layer to the one of U.getOrigUnit().
268 void emitCompileUnitHeader(CompileUnit &Unit);
269
270 /// \brief Recursively emit the DIE tree rooted at \p Die.
271 void emitDIE(DIE &Die);
272
273 /// \brief Emit the abbreviation table \p Abbrevs to the
274 /// debug_abbrev section.
275 void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
Frederic Rissef648462015-03-06 17:56:30 +0000276
277 /// \brief Emit the string table described by \p Pool.
278 void emitStrings(const NonRelocatableStringpool &Pool);
Frederic Rissc99ea202015-02-28 00:29:11 +0000279};
280
281bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
282 std::string ErrorStr;
283 std::string TripleName;
284 StringRef Context = "dwarf streamer init";
285
286 // Get the target.
287 const Target *TheTarget =
288 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
289 if (!TheTarget)
290 return error(ErrorStr, Context);
291 TripleName = TheTriple.getTriple();
292
293 // Create all the MC Objects.
294 MRI.reset(TheTarget->createMCRegInfo(TripleName));
295 if (!MRI)
296 return error(Twine("no register info for target ") + TripleName, Context);
297
298 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
299 if (!MAI)
300 return error("no asm info for target " + TripleName, Context);
301
302 MOFI.reset(new MCObjectFileInfo);
303 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
304 MOFI->InitMCObjectFileInfo(TripleName, Reloc::Default, CodeModel::Default,
305 *MC);
306
307 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
308 if (!MAB)
309 return error("no asm backend for target " + TripleName, Context);
310
311 MII.reset(TheTarget->createMCInstrInfo());
312 if (!MII)
313 return error("no instr info info for target " + TripleName, Context);
314
315 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
316 if (!MSTI)
317 return error("no subtarget info for target " + TripleName, Context);
318
319 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MSTI, *MC);
320 if (!MCE)
321 return error("no code emitter for target " + TripleName, Context);
322
323 // Create the output file.
324 std::error_code EC;
Frederic Rissb8b43d52015-03-04 22:07:44 +0000325 OutFile =
326 llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
Frederic Rissc99ea202015-02-28 00:29:11 +0000327 if (EC)
328 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
329
330 MS = TheTarget->createMCObjectStreamer(TripleName, *MC, *MAB, *OutFile, MCE,
331 *MSTI, false);
332 if (!MS)
333 return error("no object streamer for target " + TripleName, Context);
334
335 // Finally create the AsmPrinter we'll use to emit the DIEs.
336 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
337 if (!TM)
338 return error("no target machine for target " + TripleName, Context);
339
340 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
341 if (!Asm)
342 return error("no asm printer for target " + TripleName, Context);
343
344 return true;
345}
346
347bool DwarfStreamer::finish() {
348 MS->Finish();
349 return true;
350}
351
Frederic Rissb8b43d52015-03-04 22:07:44 +0000352/// \brief Set the current output section to debug_info and change
353/// the MC Dwarf version to \p DwarfVersion.
354void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
355 MS->SwitchSection(MOFI->getDwarfInfoSection());
356 MC->setDwarfVersion(DwarfVersion);
357}
358
359/// \brief Emit the compilation unit header for \p Unit in the
360/// debug_info section.
361///
362/// A Dwarf scetion header is encoded as:
363/// uint32_t Unit length (omiting this field)
364/// uint16_t Version
365/// uint32_t Abbreviation table offset
366/// uint8_t Address size
367///
368/// Leading to a total of 11 bytes.
369void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
370 unsigned Version = Unit.getOrigUnit().getVersion();
371 switchToDebugInfoSection(Version);
372
373 // Emit size of content not including length itself. The size has
374 // already been computed in CompileUnit::computeOffsets(). Substract
375 // 4 to that size to account for the length field.
376 Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
377 Asm->EmitInt16(Version);
378 // We share one abbreviations table across all units so it's always at the
379 // start of the section.
380 Asm->EmitInt32(0);
381 Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
382}
383
384/// \brief Emit the \p Abbrevs array as the shared abbreviation table
385/// for the linked Dwarf file.
386void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
387 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
388 Asm->emitDwarfAbbrevs(Abbrevs);
389}
390
391/// \brief Recursively emit the DIE tree rooted at \p Die.
392void DwarfStreamer::emitDIE(DIE &Die) {
393 MS->SwitchSection(MOFI->getDwarfInfoSection());
394 Asm->emitDwarfDIE(Die);
395}
396
Frederic Rissef648462015-03-06 17:56:30 +0000397/// \brief Emit the debug_str section stored in \p Pool.
398void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
399 Asm->OutStreamer.SwitchSection(MOFI->getDwarfStrSection());
400 for (auto *Entry = Pool.getFirstEntry(); Entry;
401 Entry = Pool.getNextEntry(Entry))
402 Asm->OutStreamer.EmitBytes(
403 StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
404}
405
Frederic Rissd3455182015-01-28 18:27:01 +0000406/// \brief The core of the Dwarf linking logic.
Frederic Riss1036e642015-02-13 23:18:22 +0000407///
408/// The link of the dwarf information from the object files will be
409/// driven by the selection of 'root DIEs', which are DIEs that
410/// describe variables or functions that are present in the linked
411/// binary (and thus have entries in the debug map). All the debug
412/// information that will be linked (the DIEs, but also the line
413/// tables, ranges, ...) is derived from that set of root DIEs.
414///
415/// The root DIEs are identified because they contain relocations that
416/// correspond to a debug map entry at specific places (the low_pc for
417/// a function, the location for a variable). These relocations are
418/// called ValidRelocs in the DwarfLinker and are gathered as a very
419/// first step when we start processing a DebugMapObject.
Frederic Rissd3455182015-01-28 18:27:01 +0000420class DwarfLinker {
421public:
Frederic Rissb9818322015-02-28 00:29:07 +0000422 DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
423 : OutputFilename(OutputFilename), Options(Options),
424 BinHolder(Options.Verbose) {}
Frederic Rissd3455182015-01-28 18:27:01 +0000425
Frederic Rissb8b43d52015-03-04 22:07:44 +0000426 ~DwarfLinker() {
427 for (auto *Abbrev : Abbreviations)
428 delete Abbrev;
429 }
430
Frederic Rissd3455182015-01-28 18:27:01 +0000431 /// \brief Link the contents of the DebugMap.
432 bool link(const DebugMap &);
433
434private:
Frederic Riss563cba62015-01-28 22:15:14 +0000435 /// \brief Called at the start of a debug object link.
436 void startDebugObject(DWARFContext &);
437
438 /// \brief Called at the end of a debug object link.
439 void endDebugObject();
440
Frederic Riss1036e642015-02-13 23:18:22 +0000441 /// \defgroup FindValidRelocations Translate debug map into a list
442 /// of relevant relocations
443 ///
444 /// @{
445 struct ValidReloc {
446 uint32_t Offset;
447 uint32_t Size;
448 uint64_t Addend;
449 const DebugMapObject::DebugMapEntry *Mapping;
450
451 ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
452 const DebugMapObject::DebugMapEntry *Mapping)
453 : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
454
455 bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
456 };
457
458 /// \brief The valid relocations for the current DebugMapObject.
459 /// This vector is sorted by relocation offset.
460 std::vector<ValidReloc> ValidRelocs;
461
462 /// \brief Index into ValidRelocs of the next relocation to
463 /// consider. As we walk the DIEs in acsending file offset and as
464 /// ValidRelocs is sorted by file offset, keeping this index
465 /// uptodate is all we have to do to have a cheap lookup during the
466 /// root DIE selection.
467 unsigned NextValidReloc;
468
469 bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
470 const DebugMapObject &DMO);
471
472 bool findValidRelocs(const object::SectionRef &Section,
473 const object::ObjectFile &Obj,
474 const DebugMapObject &DMO);
475
476 void findValidRelocsMachO(const object::SectionRef &Section,
477 const object::MachOObjectFile &Obj,
478 const DebugMapObject &DMO);
479 /// @}
Frederic Riss1b9da422015-02-13 23:18:29 +0000480
Frederic Riss84c09a52015-02-13 23:18:34 +0000481 /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
482 ///
483 /// @{
484 /// \brief Recursively walk the \p DIE tree and look for DIEs to
485 /// keep. Store that information in \p CU's DIEInfo.
486 void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
487 const DebugMapObject &DMO, CompileUnit &CU,
488 unsigned Flags);
489
490 /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
491 enum TravesalFlags {
492 TF_Keep = 1 << 0, ///< Mark the traversed DIEs as kept.
493 TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
494 TF_DependencyWalk = 1 << 2, ///< Walking the dependencies of a kept DIE.
495 TF_ParentWalk = 1 << 3, ///< Walking up the parents of a kept DIE.
496 };
497
498 /// \brief Mark the passed DIE as well as all the ones it depends on
499 /// as kept.
500 void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
501 CompileUnit::DIEInfo &MyInfo,
502 const DebugMapObject &DMO, CompileUnit &CU,
503 unsigned Flags);
504
505 unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
506 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
507 unsigned Flags);
508
509 unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
510 CompileUnit &Unit,
511 CompileUnit::DIEInfo &MyInfo, unsigned Flags);
512
513 unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
514 CompileUnit &Unit,
515 CompileUnit::DIEInfo &MyInfo,
516 unsigned Flags);
517
518 bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
519 CompileUnit::DIEInfo &Info);
520 /// @}
521
Frederic Rissb8b43d52015-03-04 22:07:44 +0000522 /// \defgroup Linking Methods used to link the debug information
523 ///
524 /// @{
525 /// \brief Recursively clone \p InputDIE into an tree of DIE objects
526 /// where useless (as decided by lookForDIEsToKeep()) bits have been
527 /// stripped out and addresses have been rewritten according to the
528 /// debug map.
529 ///
530 /// \param OutOffset is the offset the cloned DIE in the output
531 /// compile unit.
532 ///
533 /// \returns the root of the cloned tree.
534 DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
535 uint32_t OutOffset);
536
537 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
538
539 /// \brief Helper for cloneDIE.
540 unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
541 CompileUnit &U, const DWARFFormValue &Val,
542 const AttributeSpec AttrSpec, unsigned AttrSize);
543
544 /// \brief Helper for cloneDIE.
Frederic Rissef648462015-03-06 17:56:30 +0000545 unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
546 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000547
548 /// \brief Helper for cloneDIE.
Frederic Riss9833de62015-03-06 23:22:53 +0000549 unsigned
550 cloneDieReferenceAttribute(DIE &Die,
551 const DWARFDebugInfoEntryMinimal &InputDIE,
552 AttributeSpec AttrSpec, unsigned AttrSize,
553 const DWARFFormValue &Val, const DWARFUnit &U);
Frederic Rissb8b43d52015-03-04 22:07:44 +0000554
555 /// \brief Helper for cloneDIE.
556 unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
557 const DWARFFormValue &Val, unsigned AttrSize);
558
559 /// \brief Helper for cloneDIE.
560 unsigned cloneScalarAttribute(DIE &Die,
561 const DWARFDebugInfoEntryMinimal &InputDIE,
562 const DWARFUnit &U, AttributeSpec AttrSpec,
563 const DWARFFormValue &Val, unsigned AttrSize);
564
565 /// \brief Assign an abbreviation number to \p Abbrev
566 void AssignAbbrev(DIEAbbrev &Abbrev);
567
568 /// \brief FoldingSet that uniques the abbreviations.
569 FoldingSet<DIEAbbrev> AbbreviationsSet;
570 /// \brief Storage for the unique Abbreviations.
571 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
572 /// be changed to a vecot of unique_ptrs.
573 std::vector<DIEAbbrev *> Abbreviations;
574
575 /// \brief DIELoc objects that need to be destructed (but not freed!).
576 std::vector<DIELoc *> DIELocs;
577 /// \brief DIEBlock objects that need to be destructed (but not freed!).
578 std::vector<DIEBlock *> DIEBlocks;
579 /// \brief Allocator used for all the DIEValue objects.
580 BumpPtrAllocator DIEAlloc;
581 /// @}
582
Frederic Riss1b9da422015-02-13 23:18:29 +0000583 /// \defgroup Helpers Various helper methods.
584 ///
585 /// @{
586 const DWARFDebugInfoEntryMinimal *
587 resolveDIEReference(DWARFFormValue &RefValue, const DWARFUnit &Unit,
588 const DWARFDebugInfoEntryMinimal &DIE,
589 CompileUnit *&ReferencedCU);
590
591 CompileUnit *getUnitForOffset(unsigned Offset);
592
593 void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
594 const DWARFDebugInfoEntryMinimal *DIE = nullptr);
Frederic Rissc99ea202015-02-28 00:29:11 +0000595
596 bool createStreamer(Triple TheTriple, StringRef OutputFilename);
Frederic Riss1b9da422015-02-13 23:18:29 +0000597 /// @}
598
Frederic Riss563cba62015-01-28 22:15:14 +0000599private:
Frederic Rissd3455182015-01-28 18:27:01 +0000600 std::string OutputFilename;
Frederic Rissb9818322015-02-28 00:29:07 +0000601 LinkOptions Options;
Frederic Rissd3455182015-01-28 18:27:01 +0000602 BinaryHolder BinHolder;
Frederic Rissc99ea202015-02-28 00:29:11 +0000603 std::unique_ptr<DwarfStreamer> Streamer;
Frederic Riss563cba62015-01-28 22:15:14 +0000604
605 /// The units of the current debug map object.
606 std::vector<CompileUnit> Units;
Frederic Riss1b9da422015-02-13 23:18:29 +0000607
608 /// The debug map object curently under consideration.
609 DebugMapObject *CurrentDebugObject;
Frederic Rissef648462015-03-06 17:56:30 +0000610
611 /// \brief The Dwarf string pool
612 NonRelocatableStringpool StringPool;
Frederic Rissd3455182015-01-28 18:27:01 +0000613};
614
Frederic Riss1b9da422015-02-13 23:18:29 +0000615/// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
616/// returning our CompileUnit object instead.
617CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
618 auto CU =
619 std::upper_bound(Units.begin(), Units.end(), Offset,
620 [](uint32_t LHS, const CompileUnit &RHS) {
621 return LHS < RHS.getOrigUnit().getNextUnitOffset();
622 });
623 return CU != Units.end() ? &*CU : nullptr;
624}
625
626/// \brief Resolve the DIE attribute reference that has been
627/// extracted in \p RefValue. The resulting DIE migh be in another
628/// CompileUnit which is stored into \p ReferencedCU.
629/// \returns null if resolving fails for any reason.
630const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
631 DWARFFormValue &RefValue, const DWARFUnit &Unit,
632 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
633 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
634 uint64_t RefOffset = *RefValue.getAsReference(&Unit);
635
636 if ((RefCU = getUnitForOffset(RefOffset)))
637 if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
638 return RefDie;
639
640 reportWarning("could not find referenced DIE", &Unit, &DIE);
641 return nullptr;
642}
643
644/// \brief Report a warning to the user, optionaly including
645/// information about a specific \p DIE related to the warning.
646void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
647 const DWARFDebugInfoEntryMinimal *DIE) {
Frederic Rissdef4fb72015-02-28 00:29:01 +0000648 StringRef Context = "<debug map>";
Frederic Riss1b9da422015-02-13 23:18:29 +0000649 if (CurrentDebugObject)
Frederic Rissdef4fb72015-02-28 00:29:01 +0000650 Context = CurrentDebugObject->getObjectFilename();
651 warn(Warning, Context);
Frederic Riss1b9da422015-02-13 23:18:29 +0000652
Frederic Rissb9818322015-02-28 00:29:07 +0000653 if (!Options.Verbose || !DIE)
Frederic Riss1b9da422015-02-13 23:18:29 +0000654 return;
655
656 errs() << " in DIE:\n";
657 DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
658 6 /* Indent */);
659}
660
Frederic Rissc99ea202015-02-28 00:29:11 +0000661bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
662 if (Options.NoOutput)
663 return true;
664
Frederic Rissb52cf522015-02-28 00:42:37 +0000665 Streamer = llvm::make_unique<DwarfStreamer>();
Frederic Rissc99ea202015-02-28 00:29:11 +0000666 return Streamer->init(TheTriple, OutputFilename);
667}
668
Frederic Riss563cba62015-01-28 22:15:14 +0000669/// \brief Recursive helper to gather the child->parent relationships in the
670/// original compile unit.
Frederic Riss9aa725b2015-02-13 23:18:31 +0000671static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
672 unsigned ParentIdx, CompileUnit &CU) {
Frederic Riss563cba62015-01-28 22:15:14 +0000673 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
674 CU.getInfo(MyIdx).ParentIdx = ParentIdx;
675
676 if (DIE->hasChildren())
677 for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
678 Child = Child->getSibling())
Frederic Riss9aa725b2015-02-13 23:18:31 +0000679 gatherDIEParents(Child, MyIdx, CU);
Frederic Riss563cba62015-01-28 22:15:14 +0000680}
681
Frederic Riss84c09a52015-02-13 23:18:34 +0000682static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
683 switch (Tag) {
684 default:
685 return false;
686 case dwarf::DW_TAG_subprogram:
687 case dwarf::DW_TAG_lexical_block:
688 case dwarf::DW_TAG_subroutine_type:
689 case dwarf::DW_TAG_structure_type:
690 case dwarf::DW_TAG_class_type:
691 case dwarf::DW_TAG_union_type:
692 return true;
693 }
694 llvm_unreachable("Invalid Tag");
695}
696
Frederic Riss563cba62015-01-28 22:15:14 +0000697void DwarfLinker::startDebugObject(DWARFContext &Dwarf) {
698 Units.reserve(Dwarf.getNumCompileUnits());
Frederic Riss1036e642015-02-13 23:18:22 +0000699 NextValidReloc = 0;
Frederic Riss563cba62015-01-28 22:15:14 +0000700}
701
Frederic Riss1036e642015-02-13 23:18:22 +0000702void DwarfLinker::endDebugObject() {
703 Units.clear();
704 ValidRelocs.clear();
Frederic Rissb8b43d52015-03-04 22:07:44 +0000705
706 for (auto *Block : DIEBlocks)
707 Block->~DIEBlock();
708 for (auto *Loc : DIELocs)
709 Loc->~DIELoc();
710
711 DIEBlocks.clear();
712 DIELocs.clear();
713 DIEAlloc.Reset();
Frederic Riss1036e642015-02-13 23:18:22 +0000714}
715
716/// \brief Iterate over the relocations of the given \p Section and
717/// store the ones that correspond to debug map entries into the
718/// ValidRelocs array.
719void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
720 const object::MachOObjectFile &Obj,
721 const DebugMapObject &DMO) {
722 StringRef Contents;
723 Section.getContents(Contents);
724 DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
725
726 for (const object::RelocationRef &Reloc : Section.relocations()) {
727 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
728 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
729 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
730 uint64_t Offset64;
731 if ((RelocSize != 4 && RelocSize != 8) || Reloc.getOffset(Offset64)) {
Frederic Riss1b9da422015-02-13 23:18:29 +0000732 reportWarning(" unsupported relocation in debug_info section.");
Frederic Riss1036e642015-02-13 23:18:22 +0000733 continue;
734 }
735 uint32_t Offset = Offset64;
736 // Mach-o uses REL relocations, the addend is at the relocation offset.
737 uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
738
739 auto Sym = Reloc.getSymbol();
740 if (Sym != Obj.symbol_end()) {
741 StringRef SymbolName;
742 if (Sym->getName(SymbolName)) {
Frederic Riss1b9da422015-02-13 23:18:29 +0000743 reportWarning("error getting relocation symbol name.");
Frederic Riss1036e642015-02-13 23:18:22 +0000744 continue;
745 }
746 if (const auto *Mapping = DMO.lookupSymbol(SymbolName))
747 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
748 } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
749 // Do not store the addend. The addend was the address of the
750 // symbol in the object file, the address in the binary that is
751 // stored in the debug map doesn't need to be offseted.
752 ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
753 }
754 }
755}
756
757/// \brief Dispatch the valid relocation finding logic to the
758/// appropriate handler depending on the object file format.
759bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
760 const object::ObjectFile &Obj,
761 const DebugMapObject &DMO) {
762 // Dispatch to the right handler depending on the file type.
763 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
764 findValidRelocsMachO(Section, *MachOObj, DMO);
765 else
Frederic Riss1b9da422015-02-13 23:18:29 +0000766 reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
Frederic Riss1036e642015-02-13 23:18:22 +0000767
768 if (ValidRelocs.empty())
769 return false;
770
771 // Sort the relocations by offset. We will walk the DIEs linearly in
772 // the file, this allows us to just keep an index in the relocation
773 // array that we advance during our walk, rather than resorting to
774 // some associative container. See DwarfLinker::NextValidReloc.
775 std::sort(ValidRelocs.begin(), ValidRelocs.end());
776 return true;
777}
778
779/// \brief Look for relocations in the debug_info section that match
780/// entries in the debug map. These relocations will drive the Dwarf
781/// link by indicating which DIEs refer to symbols present in the
782/// linked binary.
783/// \returns wether there are any valid relocations in the debug info.
784bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
785 const DebugMapObject &DMO) {
786 // Find the debug_info section.
787 for (const object::SectionRef &Section : Obj.sections()) {
788 StringRef SectionName;
789 Section.getName(SectionName);
790 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
791 if (SectionName != "debug_info")
792 continue;
793 return findValidRelocs(Section, Obj, DMO);
794 }
795 return false;
796}
Frederic Riss563cba62015-01-28 22:15:14 +0000797
Frederic Riss84c09a52015-02-13 23:18:34 +0000798/// \brief Checks that there is a relocation against an actual debug
799/// map entry between \p StartOffset and \p NextOffset.
800///
801/// This function must be called with offsets in strictly ascending
802/// order because it never looks back at relocations it already 'went past'.
803/// \returns true and sets Info.InDebugMap if it is the case.
804bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
805 CompileUnit::DIEInfo &Info) {
806 assert(NextValidReloc == 0 ||
807 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
808 if (NextValidReloc >= ValidRelocs.size())
809 return false;
810
811 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
812
813 // We might need to skip some relocs that we didn't consider. For
814 // example the high_pc of a discarded DIE might contain a reloc that
815 // is in the list because it actually corresponds to the start of a
816 // function that is in the debug map.
817 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
818 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
819
820 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
821 return false;
822
823 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
Frederic Rissb9818322015-02-28 00:29:07 +0000824 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +0000825 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
826 << " " << format("\t%016" PRIx64 " => %016" PRIx64,
827 ValidReloc.Mapping->getValue().ObjectAddress,
828 ValidReloc.Mapping->getValue().BinaryAddress);
829
830 Info.Address =
831 ValidReloc.Mapping->getValue().BinaryAddress + ValidReloc.Addend;
832 Info.InDebugMap = true;
833 return true;
834}
835
836/// \brief Get the starting and ending (exclusive) offset for the
837/// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
838/// supposed to point to the position of the first attribute described
839/// by \p Abbrev.
840/// \return [StartOffset, EndOffset) as a pair.
841static std::pair<uint32_t, uint32_t>
842getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
843 unsigned Offset, const DWARFUnit &Unit) {
844 DataExtractor Data = Unit.getDebugInfoExtractor();
845
846 for (unsigned i = 0; i < Idx; ++i)
847 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
848
849 uint32_t End = Offset;
850 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
851
852 return std::make_pair(Offset, End);
853}
854
855/// \brief Check if a variable describing DIE should be kept.
856/// \returns updated TraversalFlags.
857unsigned DwarfLinker::shouldKeepVariableDIE(
858 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
859 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
860 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
861
862 // Global variables with constant value can always be kept.
863 if (!(Flags & TF_InFunctionScope) &&
864 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
865 MyInfo.InDebugMap = true;
866 return Flags | TF_Keep;
867 }
868
869 uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
870 if (LocationIdx == -1U)
871 return Flags;
872
873 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
874 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
875 uint32_t LocationOffset, LocationEndOffset;
876 std::tie(LocationOffset, LocationEndOffset) =
877 getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
878
879 // See if there is a relocation to a valid debug map entry inside
880 // this variable's location. The order is important here. We want to
881 // always check in the variable has a valid relocation, so that the
882 // DIEInfo is filled. However, we don't want a static variable in a
883 // function to force us to keep the enclosing function.
884 if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
885 (Flags & TF_InFunctionScope))
886 return Flags;
887
Frederic Rissb9818322015-02-28 00:29:07 +0000888 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +0000889 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
890
891 return Flags | TF_Keep;
892}
893
894/// \brief Check if a function describing DIE should be kept.
895/// \returns updated TraversalFlags.
896unsigned DwarfLinker::shouldKeepSubprogramDIE(
897 const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
898 CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
899 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
900
901 Flags |= TF_InFunctionScope;
902
903 uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
904 if (LowPcIdx == -1U)
905 return Flags;
906
907 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
908 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
909 uint32_t LowPcOffset, LowPcEndOffset;
910 std::tie(LowPcOffset, LowPcEndOffset) =
911 getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
912
913 uint64_t LowPc =
914 DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
915 assert(LowPc != -1ULL && "low_pc attribute is not an address.");
916 if (LowPc == -1ULL ||
917 !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
918 return Flags;
919
Frederic Rissb9818322015-02-28 00:29:07 +0000920 if (Options.Verbose)
Frederic Riss84c09a52015-02-13 23:18:34 +0000921 DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
922
923 return Flags | TF_Keep;
924}
925
926/// \brief Check if a DIE should be kept.
927/// \returns updated TraversalFlags.
928unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
929 CompileUnit &Unit,
930 CompileUnit::DIEInfo &MyInfo,
931 unsigned Flags) {
932 switch (DIE.getTag()) {
933 case dwarf::DW_TAG_constant:
934 case dwarf::DW_TAG_variable:
935 return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
936 case dwarf::DW_TAG_subprogram:
937 return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
938 case dwarf::DW_TAG_module:
939 case dwarf::DW_TAG_imported_module:
940 case dwarf::DW_TAG_imported_declaration:
941 case dwarf::DW_TAG_imported_unit:
942 // We always want to keep these.
943 return Flags | TF_Keep;
944 }
945
946 return Flags;
947}
948
Frederic Riss84c09a52015-02-13 23:18:34 +0000949/// \brief Mark the passed DIE as well as all the ones it depends on
950/// as kept.
951///
952/// This function is called by lookForDIEsToKeep on DIEs that are
953/// newly discovered to be needed in the link. It recursively calls
954/// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
955/// TraversalFlags to inform it that it's not doing the primary DIE
956/// tree walk.
957void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
958 CompileUnit::DIEInfo &MyInfo,
959 const DebugMapObject &DMO,
960 CompileUnit &CU, unsigned Flags) {
961 const DWARFUnit &Unit = CU.getOrigUnit();
962 MyInfo.Keep = true;
963
964 // First mark all the parent chain as kept.
965 unsigned AncestorIdx = MyInfo.ParentIdx;
966 while (!CU.getInfo(AncestorIdx).Keep) {
967 lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
968 TF_ParentWalk | TF_Keep | TF_DependencyWalk);
969 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
970 }
971
972 // Then we need to mark all the DIEs referenced by this DIE's
973 // attributes as kept.
974 DataExtractor Data = Unit.getDebugInfoExtractor();
975 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
976 uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
977
978 // Mark all DIEs referenced through atttributes as kept.
979 for (const auto &AttrSpec : Abbrev->attributes()) {
980 DWARFFormValue Val(AttrSpec.Form);
981
982 if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
983 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
984 continue;
985 }
986
987 Val.extractValue(Data, &Offset, &Unit);
988 CompileUnit *ReferencedCU;
989 if (const auto *RefDIE = resolveDIEReference(Val, Unit, DIE, ReferencedCU))
990 lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
991 TF_Keep | TF_DependencyWalk);
992 }
993}
994
995/// \brief Recursively walk the \p DIE tree and look for DIEs to
996/// keep. Store that information in \p CU's DIEInfo.
997///
998/// This function is the entry point of the DIE selection
999/// algorithm. It is expected to walk the DIE tree in file order and
1000/// (though the mediation of its helper) call hasValidRelocation() on
1001/// each DIE that might be a 'root DIE' (See DwarfLinker class
1002/// comment).
1003/// While walking the dependencies of root DIEs, this function is
1004/// also called, but during these dependency walks the file order is
1005/// not respected. The TF_DependencyWalk flag tells us which kind of
1006/// traversal we are currently doing.
1007void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1008 const DebugMapObject &DMO, CompileUnit &CU,
1009 unsigned Flags) {
1010 unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
1011 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
1012 bool AlreadyKept = MyInfo.Keep;
1013
1014 // If the Keep flag is set, we are marking a required DIE's
1015 // dependencies. If our target is already marked as kept, we're all
1016 // set.
1017 if ((Flags & TF_DependencyWalk) && AlreadyKept)
1018 return;
1019
1020 // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
1021 // because it would screw up the relocation finding logic.
1022 if (!(Flags & TF_DependencyWalk))
1023 Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
1024
1025 // If it is a newly kept DIE mark it as well as all its dependencies as kept.
1026 if (!AlreadyKept && (Flags & TF_Keep))
1027 keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, Flags);
1028
1029 // The TF_ParentWalk flag tells us that we are currently walking up
1030 // the parent chain of a required DIE, and we don't want to mark all
1031 // the children of the parents as kept (consider for example a
1032 // DW_TAG_namespace node in the parent chain). There are however a
1033 // set of DIE types for which we want to ignore that directive and still
1034 // walk their children.
1035 if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
1036 Flags &= ~TF_ParentWalk;
1037
1038 if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
1039 return;
1040
1041 for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
1042 Child = Child->getSibling())
1043 lookForDIEsToKeep(*Child, DMO, CU, Flags);
1044}
1045
Frederic Rissb8b43d52015-03-04 22:07:44 +00001046/// \brief Assign an abbreviation numer to \p Abbrev.
1047///
1048/// Our DIEs get freed after every DebugMapObject has been processed,
1049/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1050/// the instances hold by the DIEs. When we encounter an abbreviation
1051/// that we don't know, we create a permanent copy of it.
1052void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
1053 // Check the set for priors.
1054 FoldingSetNodeID ID;
1055 Abbrev.Profile(ID);
1056 void *InsertToken;
1057 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1058
1059 // If it's newly added.
1060 if (InSet) {
1061 // Assign existing abbreviation number.
1062 Abbrev.setNumber(InSet->getNumber());
1063 } else {
1064 // Add to abbreviation list.
1065 Abbreviations.push_back(
1066 new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
1067 for (const auto &Attr : Abbrev.getData())
1068 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1069 AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
1070 // Assign the unique abbreviation number.
1071 Abbrev.setNumber(Abbreviations.size());
1072 Abbreviations.back()->setNumber(Abbreviations.size());
1073 }
1074}
1075
1076/// \brief Clone a string attribute described by \p AttrSpec and add
1077/// it to \p Die.
1078/// \returns the size of the new attribute.
Frederic Rissef648462015-03-06 17:56:30 +00001079unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1080 const DWARFFormValue &Val,
1081 const DWARFUnit &U) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001082 // Switch everything to out of line strings.
Frederic Rissef648462015-03-06 17:56:30 +00001083 const char *String = *Val.getAsCString(&U);
1084 unsigned Offset = StringPool.getStringOffset(String);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001085 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
Frederic Rissef648462015-03-06 17:56:30 +00001086 new (DIEAlloc) DIEInteger(Offset));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001087 return 4;
1088}
1089
1090/// \brief Clone an attribute referencing another DIE and add
1091/// it to \p Die.
1092/// \returns the size of the new attribute.
Frederic Riss9833de62015-03-06 23:22:53 +00001093unsigned DwarfLinker::cloneDieReferenceAttribute(
1094 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1095 AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
1096 const DWARFUnit &U) {
1097 uint32_t Ref = *Val.getAsReference(&U);
1098 DIE *NewRefDie = nullptr;
1099 CompileUnit *RefUnit = nullptr;
1100 const DWARFDebugInfoEntryMinimal *RefDie = nullptr;
1101
1102 if (!(RefUnit = getUnitForOffset(Ref)) ||
1103 !(RefDie = RefUnit->getOrigUnit().getDIEForOffset(Ref))) {
1104 const char *AttributeString = dwarf::AttributeString(AttrSpec.Attr);
1105 if (!AttributeString)
1106 AttributeString = "DW_AT_???";
1107 reportWarning(Twine("Missing DIE for ref in attribute ") + AttributeString +
1108 ". Dropping.",
1109 &U, &InputDIE);
1110 return 0;
1111 }
1112
1113 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1114 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1115 if (!RefInfo.Clone) {
1116 assert(Ref > InputDIE.getOffset());
1117 // We haven't cloned this DIE yet. Just create an empty one and
1118 // store it. It'll get really cloned when we process it.
1119 RefInfo.Clone = new DIE(dwarf::Tag(RefDie->getTag()));
1120 }
1121 NewRefDie = RefInfo.Clone;
1122
1123 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr) {
1124 // We cannot currently rely on a DIEEntry to emit ref_addr
1125 // references, because the implementation calls back to DwarfDebug
1126 // to find the unit offset. (We don't have a DwarfDebug)
1127 // FIXME: we should be able to design DIEEntry reliance on
1128 // DwarfDebug away.
1129 DIEInteger *Attr;
1130 if (Ref < InputDIE.getOffset()) {
1131 // We must have already cloned that DIE.
1132 uint32_t NewRefOffset =
1133 RefUnit->getStartOffset() + NewRefDie->getOffset();
1134 Attr = new (DIEAlloc) DIEInteger(NewRefOffset);
1135 } else {
1136 // A forward reference. Note and fixup later.
1137 Attr = new (DIEAlloc) DIEInteger(0xBADDEF);
1138 RefUnit->noteForwardReference(NewRefDie, Attr);
1139 }
1140 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_ref_addr,
1141 Attr);
1142 return AttrSize;
1143 }
1144
Frederic Rissb8b43d52015-03-04 22:07:44 +00001145 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
Frederic Riss9833de62015-03-06 23:22:53 +00001146 new (DIEAlloc) DIEEntry(*NewRefDie));
Frederic Rissb8b43d52015-03-04 22:07:44 +00001147 return AttrSize;
1148}
1149
1150/// \brief Clone an attribute of block form (locations, constants) and add
1151/// it to \p Die.
1152/// \returns the size of the new attribute.
1153unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1154 const DWARFFormValue &Val,
1155 unsigned AttrSize) {
1156 DIE *Attr;
1157 DIEValue *Value;
1158 DIELoc *Loc = nullptr;
1159 DIEBlock *Block = nullptr;
1160 // Just copy the block data over.
1161 if (AttrSpec.Attr == dwarf::DW_FORM_exprloc) {
1162 Loc = new (DIEAlloc) DIELoc();
1163 DIELocs.push_back(Loc);
1164 } else {
1165 Block = new (DIEAlloc) DIEBlock();
1166 DIEBlocks.push_back(Block);
1167 }
1168 Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
1169 Value = Loc ? static_cast<DIEValue *>(Loc) : static_cast<DIEValue *>(Block);
1170 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1171 for (auto Byte : Bytes)
1172 Attr->addValue(static_cast<dwarf::Attribute>(0), dwarf::DW_FORM_data1,
1173 new (DIEAlloc) DIEInteger(Byte));
1174 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1175 // the DIE class, this if could be replaced by
1176 // Attr->setSize(Bytes.size()).
1177 if (Streamer) {
1178 if (Loc)
1179 Loc->ComputeSize(&Streamer->getAsmPrinter());
1180 else
1181 Block->ComputeSize(&Streamer->getAsmPrinter());
1182 }
1183 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1184 Value);
1185 return AttrSize;
1186}
1187
1188/// \brief Clone a scalar attribute and add it to \p Die.
1189/// \returns the size of the new attribute.
1190unsigned DwarfLinker::cloneScalarAttribute(
1191 DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, const DWARFUnit &U,
1192 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize) {
1193 uint64_t Value;
1194 if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1195 Value = *Val.getAsSectionOffset();
1196 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1197 Value = *Val.getAsSignedConstant();
1198 else if (AttrSpec.Form == dwarf::DW_FORM_addr)
1199 Value = *Val.getAsAddress(&U);
1200 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1201 Value = *OptionalValue;
1202 else {
1203 reportWarning("Unsupported scalar attribute form. Dropping attribute.", &U,
1204 &InputDIE);
1205 return 0;
1206 }
1207 Die.addValue(dwarf::Attribute(AttrSpec.Attr), dwarf::Form(AttrSpec.Form),
1208 new (DIEAlloc) DIEInteger(Value));
1209 return AttrSize;
1210}
1211
1212/// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
1213/// value \p Val, and add it to \p Die.
1214/// \returns the size of the cloned attribute.
1215unsigned DwarfLinker::cloneAttribute(DIE &Die,
1216 const DWARFDebugInfoEntryMinimal &InputDIE,
1217 CompileUnit &Unit,
1218 const DWARFFormValue &Val,
1219 const AttributeSpec AttrSpec,
1220 unsigned AttrSize) {
1221 const DWARFUnit &U = Unit.getOrigUnit();
1222
1223 switch (AttrSpec.Form) {
1224 case dwarf::DW_FORM_strp:
1225 case dwarf::DW_FORM_string:
Frederic Rissef648462015-03-06 17:56:30 +00001226 return cloneStringAttribute(Die, AttrSpec, Val, U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001227 case dwarf::DW_FORM_ref_addr:
1228 case dwarf::DW_FORM_ref1:
1229 case dwarf::DW_FORM_ref2:
1230 case dwarf::DW_FORM_ref4:
1231 case dwarf::DW_FORM_ref8:
Frederic Riss9833de62015-03-06 23:22:53 +00001232 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1233 U);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001234 case dwarf::DW_FORM_block:
1235 case dwarf::DW_FORM_block1:
1236 case dwarf::DW_FORM_block2:
1237 case dwarf::DW_FORM_block4:
1238 case dwarf::DW_FORM_exprloc:
1239 return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
1240 case dwarf::DW_FORM_addr:
1241 case dwarf::DW_FORM_data1:
1242 case dwarf::DW_FORM_data2:
1243 case dwarf::DW_FORM_data4:
1244 case dwarf::DW_FORM_data8:
1245 case dwarf::DW_FORM_udata:
1246 case dwarf::DW_FORM_sdata:
1247 case dwarf::DW_FORM_sec_offset:
1248 case dwarf::DW_FORM_flag:
1249 case dwarf::DW_FORM_flag_present:
1250 return cloneScalarAttribute(Die, InputDIE, U, AttrSpec, Val, AttrSize);
1251 default:
1252 reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
1253 &InputDIE);
1254 }
1255
1256 return 0;
1257}
1258
1259/// \brief Recursively clone \p InputDIE's subtrees that have been
1260/// selected to appear in the linked output.
1261///
1262/// \param OutOffset is the Offset where the newly created DIE will
1263/// lie in the linked compile unit.
1264///
1265/// \returns the cloned DIE object or null if nothing was selected.
1266DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
1267 CompileUnit &Unit, uint32_t OutOffset) {
1268 DWARFUnit &U = Unit.getOrigUnit();
1269 unsigned Idx = U.getDIEIndex(&InputDIE);
Frederic Riss9833de62015-03-06 23:22:53 +00001270 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001271
1272 // Should the DIE appear in the output?
1273 if (!Unit.getInfo(Idx).Keep)
1274 return nullptr;
1275
1276 uint32_t Offset = InputDIE.getOffset();
Frederic Riss9833de62015-03-06 23:22:53 +00001277 // The DIE might have been already created by a forward reference
1278 // (see cloneDieReferenceAttribute()).
1279 DIE *Die = Info.Clone;
1280 if (!Die)
1281 Die = Info.Clone = new DIE(dwarf::Tag(InputDIE.getTag()));
1282 assert(Die->getTag() == InputDIE.getTag());
Frederic Rissb8b43d52015-03-04 22:07:44 +00001283 Die->setOffset(OutOffset);
1284
1285 // Extract and clone every attribute.
1286 DataExtractor Data = U.getDebugInfoExtractor();
1287 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1288 Offset += getULEB128Size(Abbrev->getCode());
1289
1290 for (const auto &AttrSpec : Abbrev->attributes()) {
1291 DWARFFormValue Val(AttrSpec.Form);
1292 uint32_t AttrSize = Offset;
1293 Val.extractValue(Data, &Offset, &U);
1294 AttrSize = Offset - AttrSize;
1295
1296 OutOffset += cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize);
1297 }
1298
1299 DIEAbbrev &NewAbbrev = Die->getAbbrev();
1300 // If a scope DIE is kept, we must have kept at least one child. If
1301 // it's not the case, we'll just be emitting one wasteful end of
1302 // children marker, but things won't break.
1303 if (InputDIE.hasChildren())
1304 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1305 // Assign a permanent abbrev number
1306 AssignAbbrev(Die->getAbbrev());
1307
1308 // Add the size of the abbreviation number to the output offset.
1309 OutOffset += getULEB128Size(Die->getAbbrevNumber());
1310
1311 if (!Abbrev->hasChildren()) {
1312 // Update our size.
1313 Die->setSize(OutOffset - Die->getOffset());
1314 return Die;
1315 }
1316
1317 // Recursively clone children.
1318 for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
1319 Child = Child->getSibling()) {
1320 if (DIE *Clone = cloneDIE(*Child, Unit, OutOffset)) {
1321 Die->addChild(std::unique_ptr<DIE>(Clone));
1322 OutOffset = Clone->getOffset() + Clone->getSize();
1323 }
1324 }
1325
1326 // Account for the end of children marker.
1327 OutOffset += sizeof(int8_t);
1328 // Update our size.
1329 Die->setSize(OutOffset - Die->getOffset());
1330 return Die;
1331}
1332
Frederic Rissd3455182015-01-28 18:27:01 +00001333bool DwarfLinker::link(const DebugMap &Map) {
1334
1335 if (Map.begin() == Map.end()) {
1336 errs() << "Empty debug map.\n";
1337 return false;
1338 }
1339
Frederic Rissc99ea202015-02-28 00:29:11 +00001340 if (!createStreamer(Map.getTriple(), OutputFilename))
1341 return false;
1342
Frederic Rissb8b43d52015-03-04 22:07:44 +00001343 // Size of the DIEs (and headers) generated for the linked output.
1344 uint64_t OutputDebugInfoSize = 0;
1345
Frederic Rissd3455182015-01-28 18:27:01 +00001346 for (const auto &Obj : Map.objects()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001347 CurrentDebugObject = Obj.get();
1348
Frederic Rissb9818322015-02-28 00:29:07 +00001349 if (Options.Verbose)
Frederic Rissd3455182015-01-28 18:27:01 +00001350 outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
1351 auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
1352 if (std::error_code EC = ErrOrObj.getError()) {
Frederic Riss1b9da422015-02-13 23:18:29 +00001353 reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
Frederic Rissd3455182015-01-28 18:27:01 +00001354 continue;
1355 }
1356
Frederic Riss1036e642015-02-13 23:18:22 +00001357 // Look for relocations that correspond to debug map entries.
1358 if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
Frederic Rissb9818322015-02-28 00:29:07 +00001359 if (Options.Verbose)
Frederic Riss1036e642015-02-13 23:18:22 +00001360 outs() << "No valid relocations found. Skipping.\n";
1361 continue;
1362 }
1363
Frederic Riss563cba62015-01-28 22:15:14 +00001364 // Setup access to the debug info.
Frederic Rissd3455182015-01-28 18:27:01 +00001365 DWARFContextInMemory DwarfContext(*ErrOrObj);
Frederic Riss563cba62015-01-28 22:15:14 +00001366 startDebugObject(DwarfContext);
Frederic Rissd3455182015-01-28 18:27:01 +00001367
Frederic Riss563cba62015-01-28 22:15:14 +00001368 // In a first phase, just read in the debug info and store the DIE
1369 // parent links that we will use during the next phase.
Frederic Rissd3455182015-01-28 18:27:01 +00001370 for (const auto &CU : DwarfContext.compile_units()) {
1371 auto *CUDie = CU->getCompileUnitDIE(false);
Frederic Rissb9818322015-02-28 00:29:07 +00001372 if (Options.Verbose) {
Frederic Rissd3455182015-01-28 18:27:01 +00001373 outs() << "Input compilation unit:";
1374 CUDie->dump(outs(), CU.get(), 0);
1375 }
Frederic Riss563cba62015-01-28 22:15:14 +00001376 Units.emplace_back(*CU);
Frederic Riss9aa725b2015-02-13 23:18:31 +00001377 gatherDIEParents(CUDie, 0, Units.back());
Frederic Rissd3455182015-01-28 18:27:01 +00001378 }
Frederic Riss563cba62015-01-28 22:15:14 +00001379
Frederic Riss84c09a52015-02-13 23:18:34 +00001380 // Then mark all the DIEs that need to be present in the linked
1381 // output and collect some information about them. Note that this
1382 // loop can not be merged with the previous one becaue cross-cu
1383 // references require the ParentIdx to be setup for every CU in
1384 // the object file before calling this.
1385 for (auto &CurrentUnit : Units)
1386 lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getCompileUnitDIE(), *Obj,
1387 CurrentUnit, 0);
1388
Frederic Rissb8b43d52015-03-04 22:07:44 +00001389 // Construct the output DIE tree by cloning the DIEs we chose to
1390 // keep above. If there are no valid relocs, then there's nothing
1391 // to clone/emit.
1392 if (!ValidRelocs.empty())
1393 for (auto &CurrentUnit : Units) {
1394 const auto *InputDIE = CurrentUnit.getOrigUnit().getCompileUnitDIE();
Frederic Riss9d441b62015-03-06 23:22:50 +00001395 CurrentUnit.setStartOffset(OutputDebugInfoSize);
Frederic Rissb8b43d52015-03-04 22:07:44 +00001396 DIE *OutputDIE =
1397 cloneDIE(*InputDIE, CurrentUnit, 11 /* Unit Header size */);
1398 CurrentUnit.setOutputUnitDIE(OutputDIE);
Frederic Riss9d441b62015-03-06 23:22:50 +00001399 OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001400 }
1401
1402 // Emit all the compile unit's debug information.
1403 if (!ValidRelocs.empty() && !Options.NoOutput)
1404 for (auto &CurrentUnit : Units) {
Frederic Riss9833de62015-03-06 23:22:53 +00001405 CurrentUnit.fixupForwardReferences();
Frederic Rissb8b43d52015-03-04 22:07:44 +00001406 Streamer->emitCompileUnitHeader(CurrentUnit);
1407 if (!CurrentUnit.getOutputUnitDIE())
1408 continue;
1409 Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
1410 }
1411
Frederic Riss563cba62015-01-28 22:15:14 +00001412 // Clean-up before starting working on the next object.
1413 endDebugObject();
Frederic Rissd3455182015-01-28 18:27:01 +00001414 }
1415
Frederic Rissb8b43d52015-03-04 22:07:44 +00001416 // Emit everything that's global.
Frederic Rissef648462015-03-06 17:56:30 +00001417 if (!Options.NoOutput) {
Frederic Rissb8b43d52015-03-04 22:07:44 +00001418 Streamer->emitAbbrevs(Abbreviations);
Frederic Rissef648462015-03-06 17:56:30 +00001419 Streamer->emitStrings(StringPool);
1420 }
Frederic Rissb8b43d52015-03-04 22:07:44 +00001421
Frederic Rissc99ea202015-02-28 00:29:11 +00001422 return Options.NoOutput ? true : Streamer->finish();
Frederic Riss231f7142014-12-12 17:31:24 +00001423}
1424}
Frederic Rissd3455182015-01-28 18:27:01 +00001425
Frederic Rissb9818322015-02-28 00:29:07 +00001426bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
1427 const LinkOptions &Options) {
1428 DwarfLinker Linker(OutputFilename, Options);
Frederic Rissd3455182015-01-28 18:27:01 +00001429 return Linker.link(DM);
1430}
1431}
Frederic Riss231f7142014-12-12 17:31:24 +00001432}