1 //===- DWARFDebugFrame.h - Parsing of .debug_frame ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
11 #include "llvm/ADT/ArrayRef.h"
12 #include "llvm/ADT/DenseMap.h"
13 #include "llvm/ADT/Optional.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/BinaryFormat/Dwarf.h"
18 #include "llvm/Support/Casting.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/DataExtractor.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <algorithm>
25 #include <cassert>
26 #include <cinttypes>
27 #include <cstdint>
28 #include <string>
29 #include <vector>
30 
31 using namespace llvm;
32 using namespace dwarf;
33 
34 /// \brief Abstract frame entry defining the common interface concrete
35 /// entries implement.
36 class llvm::FrameEntry {
37 public:
38   enum FrameKind {FK_CIE, FK_FDE};
39 
40   FrameEntry(FrameKind K, uint64_t Offset, uint64_t Length)
41       : Kind(K), Offset(Offset), Length(Length) {}
42 
43   virtual ~FrameEntry() = default;
44 
45   FrameKind getKind() const { return Kind; }
46   virtual uint64_t getOffset() const { return Offset; }
47 
48   /// Parse and store a sequence of CFI instructions from Data,
49   /// starting at *Offset and ending at EndOffset. If everything
50   /// goes well, *Offset should be equal to EndOffset when this method
51   /// returns. Otherwise, an error occurred.
52   virtual void parseInstructions(DataExtractor Data, uint32_t *Offset,
53                                  uint32_t EndOffset);
54 
55   /// Dump the entry header to the given output stream.
56   virtual void dumpHeader(raw_ostream &OS) const = 0;
57 
58   /// Dump the entry's instructions to the given output stream.
59   virtual void dumpInstructions(raw_ostream &OS) const;
60 
61   /// Dump the entire entry to the given output stream.
62   void dump(raw_ostream &OS) const {
63     dumpHeader(OS);
64     dumpInstructions(OS);
65     OS << "\n";
66   }
67 
68 protected:
69   const FrameKind Kind;
70 
71   /// \brief Offset of this entry in the section.
72   uint64_t Offset;
73 
74   /// \brief Entry length as specified in DWARF.
75   uint64_t Length;
76 
77   /// An entry may contain CFI instructions. An instruction consists of an
78   /// opcode and an optional sequence of operands.
79   using Operands = std::vector<uint64_t>;
80   struct Instruction {
81     Instruction(uint8_t Opcode)
82       : Opcode(Opcode)
83     {}
84 
85     uint8_t Opcode;
86     Operands Ops;
87   };
88 
89   std::vector<Instruction> Instructions;
90 
91   /// Convenience methods to add a new instruction with the given opcode and
92   /// operands to the Instructions vector.
93   void addInstruction(uint8_t Opcode) {
94     Instructions.push_back(Instruction(Opcode));
95   }
96 
97   void addInstruction(uint8_t Opcode, uint64_t Operand1) {
98     Instructions.push_back(Instruction(Opcode));
99     Instructions.back().Ops.push_back(Operand1);
100   }
101 
102   void addInstruction(uint8_t Opcode, uint64_t Operand1, uint64_t Operand2) {
103     Instructions.push_back(Instruction(Opcode));
104     Instructions.back().Ops.push_back(Operand1);
105     Instructions.back().Ops.push_back(Operand2);
106   }
107 };
108 
109 // See DWARF standard v3, section 7.23
110 const uint8_t DWARF_CFI_PRIMARY_OPCODE_MASK = 0xc0;
111 const uint8_t DWARF_CFI_PRIMARY_OPERAND_MASK = 0x3f;
112 
113 void FrameEntry::parseInstructions(DataExtractor Data, uint32_t *Offset,
114                                    uint32_t EndOffset) {
115   while (*Offset < EndOffset) {
116     uint8_t Opcode = Data.getU8(Offset);
117     // Some instructions have a primary opcode encoded in the top bits.
118     uint8_t Primary = Opcode & DWARF_CFI_PRIMARY_OPCODE_MASK;
119 
120     if (Primary) {
121       // If it's a primary opcode, the first operand is encoded in the bottom
122       // bits of the opcode itself.
123       uint64_t Op1 = Opcode & DWARF_CFI_PRIMARY_OPERAND_MASK;
124       switch (Primary) {
125         default: llvm_unreachable("Impossible primary CFI opcode");
126         case DW_CFA_advance_loc:
127         case DW_CFA_restore:
128           addInstruction(Primary, Op1);
129           break;
130         case DW_CFA_offset:
131           addInstruction(Primary, Op1, Data.getULEB128(Offset));
132           break;
133       }
134     } else {
135       // Extended opcode - its value is Opcode itself.
136       switch (Opcode) {
137         default: llvm_unreachable("Invalid extended CFI opcode");
138         case DW_CFA_nop:
139         case DW_CFA_remember_state:
140         case DW_CFA_restore_state:
141         case DW_CFA_GNU_window_save:
142           // No operands
143           addInstruction(Opcode);
144           break;
145         case DW_CFA_set_loc:
146           // Operands: Address
147           addInstruction(Opcode, Data.getAddress(Offset));
148           break;
149         case DW_CFA_advance_loc1:
150           // Operands: 1-byte delta
151           addInstruction(Opcode, Data.getU8(Offset));
152           break;
153         case DW_CFA_advance_loc2:
154           // Operands: 2-byte delta
155           addInstruction(Opcode, Data.getU16(Offset));
156           break;
157         case DW_CFA_advance_loc4:
158           // Operands: 4-byte delta
159           addInstruction(Opcode, Data.getU32(Offset));
160           break;
161         case DW_CFA_restore_extended:
162         case DW_CFA_undefined:
163         case DW_CFA_same_value:
164         case DW_CFA_def_cfa_register:
165         case DW_CFA_def_cfa_offset:
166           // Operands: ULEB128
167           addInstruction(Opcode, Data.getULEB128(Offset));
168           break;
169         case DW_CFA_def_cfa_offset_sf:
170           // Operands: SLEB128
171           addInstruction(Opcode, Data.getSLEB128(Offset));
172           break;
173         case DW_CFA_offset_extended:
174         case DW_CFA_register:
175         case DW_CFA_def_cfa:
176         case DW_CFA_val_offset: {
177           // Operands: ULEB128, ULEB128
178           // Note: We can not embed getULEB128 directly into function
179           // argument list. getULEB128 changes Offset and order of evaluation
180           // for arguments is unspecified.
181           auto op1 = Data.getULEB128(Offset);
182           auto op2 = Data.getULEB128(Offset);
183           addInstruction(Opcode, op1, op2);
184           break;
185         }
186         case DW_CFA_offset_extended_sf:
187         case DW_CFA_def_cfa_sf:
188         case DW_CFA_val_offset_sf: {
189           // Operands: ULEB128, SLEB128
190           // Note: see comment for the previous case
191           auto op1 = Data.getULEB128(Offset);
192           auto op2 = (uint64_t)Data.getSLEB128(Offset);
193           addInstruction(Opcode, op1, op2);
194           break;
195         }
196         case DW_CFA_def_cfa_expression:
197           // FIXME: Parse the actual instruction.
198           *Offset += Data.getULEB128(Offset);
199           break;
200         case DW_CFA_expression:
201         case DW_CFA_val_expression: {
202           // FIXME: Parse the actual instruction.
203           Data.getULEB128(Offset);
204           *Offset += Data.getULEB128(Offset);
205           break;
206         }
207       }
208     }
209   }
210 }
211 
212 namespace {
213 
214 /// \brief DWARF Common Information Entry (CIE)
215 class CIE : public FrameEntry {
216 public:
217   // CIEs (and FDEs) are simply container classes, so the only sensible way to
218   // create them is by providing the full parsed contents in the constructor.
219   CIE(uint64_t Offset, uint64_t Length, uint8_t Version,
220       SmallString<8> Augmentation, uint8_t AddressSize,
221       uint8_t SegmentDescriptorSize, uint64_t CodeAlignmentFactor,
222       int64_t DataAlignmentFactor, uint64_t ReturnAddressRegister,
223       SmallString<8> AugmentationData, uint32_t FDEPointerEncoding,
224       uint32_t LSDAPointerEncoding)
225       : FrameEntry(FK_CIE, Offset, Length), Version(Version),
226         Augmentation(std::move(Augmentation)), AddressSize(AddressSize),
227         SegmentDescriptorSize(SegmentDescriptorSize),
228         CodeAlignmentFactor(CodeAlignmentFactor),
229         DataAlignmentFactor(DataAlignmentFactor),
230         ReturnAddressRegister(ReturnAddressRegister),
231         AugmentationData(std::move(AugmentationData)),
232         FDEPointerEncoding(FDEPointerEncoding),
233         LSDAPointerEncoding(LSDAPointerEncoding) {}
234 
235   ~CIE() override = default;
236 
237   StringRef getAugmentationString() const { return Augmentation; }
238   uint64_t getCodeAlignmentFactor() const { return CodeAlignmentFactor; }
239   int64_t getDataAlignmentFactor() const { return DataAlignmentFactor; }
240 
241   uint32_t getFDEPointerEncoding() const {
242     return FDEPointerEncoding;
243   }
244 
245   uint32_t getLSDAPointerEncoding() const {
246     return LSDAPointerEncoding;
247   }
248 
249   void dumpHeader(raw_ostream &OS) const override {
250     OS << format("%08x %08x %08x CIE",
251                  (uint32_t)Offset, (uint32_t)Length, DW_CIE_ID)
252        << "\n";
253     OS << format("  Version:               %d\n", Version);
254     OS << "  Augmentation:          \"" << Augmentation << "\"\n";
255     if (Version >= 4) {
256       OS << format("  Address size:          %u\n",
257                    (uint32_t)AddressSize);
258       OS << format("  Segment desc size:     %u\n",
259                    (uint32_t)SegmentDescriptorSize);
260     }
261     OS << format("  Code alignment factor: %u\n",
262                  (uint32_t)CodeAlignmentFactor);
263     OS << format("  Data alignment factor: %d\n",
264                  (int32_t)DataAlignmentFactor);
265     OS << format("  Return address column: %d\n",
266                  (int32_t)ReturnAddressRegister);
267     if (!AugmentationData.empty()) {
268       OS << "  Augmentation data:    ";
269       for (uint8_t Byte : AugmentationData)
270         OS << ' ' << hexdigit(Byte >> 4) << hexdigit(Byte & 0xf);
271       OS << "\n";
272     }
273     OS << "\n";
274   }
275 
276   static bool classof(const FrameEntry *FE) {
277     return FE->getKind() == FK_CIE;
278   }
279 
280 private:
281   /// The following fields are defined in section 6.4.1 of the DWARF standard v4
282   uint8_t Version;
283   SmallString<8> Augmentation;
284   uint8_t AddressSize;
285   uint8_t SegmentDescriptorSize;
286   uint64_t CodeAlignmentFactor;
287   int64_t DataAlignmentFactor;
288   uint64_t ReturnAddressRegister;
289 
290   // The following are used when the CIE represents an EH frame entry.
291   SmallString<8> AugmentationData;
292   uint32_t FDEPointerEncoding;
293   uint32_t LSDAPointerEncoding;
294 };
295 
296 /// \brief DWARF Frame Description Entry (FDE)
297 class FDE : public FrameEntry {
298 public:
299   // Each FDE has a CIE it's "linked to". Our FDE contains is constructed with
300   // an offset to the CIE (provided by parsing the FDE header). The CIE itself
301   // is obtained lazily once it's actually required.
302   FDE(uint64_t Offset, uint64_t Length, int64_t LinkedCIEOffset,
303       uint64_t InitialLocation, uint64_t AddressRange,
304       CIE *Cie)
305       : FrameEntry(FK_FDE, Offset, Length), LinkedCIEOffset(LinkedCIEOffset),
306         InitialLocation(InitialLocation), AddressRange(AddressRange),
307         LinkedCIE(Cie) {}
308 
309   ~FDE() override = default;
310 
311   CIE *getLinkedCIE() const { return LinkedCIE; }
312 
313   void dumpHeader(raw_ostream &OS) const override {
314     OS << format("%08x %08x %08x FDE ",
315                  (uint32_t)Offset, (uint32_t)Length, (int32_t)LinkedCIEOffset);
316     OS << format("cie=%08x pc=%08x...%08x\n",
317                  (int32_t)LinkedCIEOffset,
318                  (uint32_t)InitialLocation,
319                  (uint32_t)InitialLocation + (uint32_t)AddressRange);
320   }
321 
322   static bool classof(const FrameEntry *FE) {
323     return FE->getKind() == FK_FDE;
324   }
325 
326 private:
327   /// The following fields are defined in section 6.4.1 of the DWARF standard v3
328   uint64_t LinkedCIEOffset;
329   uint64_t InitialLocation;
330   uint64_t AddressRange;
331   CIE *LinkedCIE;
332 };
333 
334 /// \brief Types of operands to CF instructions.
335 enum OperandType {
336   OT_Unset,
337   OT_None,
338   OT_Address,
339   OT_Offset,
340   OT_FactoredCodeOffset,
341   OT_SignedFactDataOffset,
342   OT_UnsignedFactDataOffset,
343   OT_Register,
344   OT_Expression
345 };
346 
347 } // end anonymous namespace
348 
349 /// \brief Initialize the array describing the types of operands.
350 static ArrayRef<OperandType[2]> getOperandTypes() {
351   static OperandType OpTypes[DW_CFA_restore+1][2];
352 
353 #define DECLARE_OP2(OP, OPTYPE0, OPTYPE1)       \
354   do {                                          \
355     OpTypes[OP][0] = OPTYPE0;                   \
356     OpTypes[OP][1] = OPTYPE1;                   \
357   } while (false)
358 #define DECLARE_OP1(OP, OPTYPE0) DECLARE_OP2(OP, OPTYPE0, OT_None)
359 #define DECLARE_OP0(OP) DECLARE_OP1(OP, OT_None)
360 
361   DECLARE_OP1(DW_CFA_set_loc, OT_Address);
362   DECLARE_OP1(DW_CFA_advance_loc, OT_FactoredCodeOffset);
363   DECLARE_OP1(DW_CFA_advance_loc1, OT_FactoredCodeOffset);
364   DECLARE_OP1(DW_CFA_advance_loc2, OT_FactoredCodeOffset);
365   DECLARE_OP1(DW_CFA_advance_loc4, OT_FactoredCodeOffset);
366   DECLARE_OP1(DW_CFA_MIPS_advance_loc8, OT_FactoredCodeOffset);
367   DECLARE_OP2(DW_CFA_def_cfa, OT_Register, OT_Offset);
368   DECLARE_OP2(DW_CFA_def_cfa_sf, OT_Register, OT_SignedFactDataOffset);
369   DECLARE_OP1(DW_CFA_def_cfa_register, OT_Register);
370   DECLARE_OP1(DW_CFA_def_cfa_offset, OT_Offset);
371   DECLARE_OP1(DW_CFA_def_cfa_offset_sf, OT_SignedFactDataOffset);
372   DECLARE_OP1(DW_CFA_def_cfa_expression, OT_Expression);
373   DECLARE_OP1(DW_CFA_undefined, OT_Register);
374   DECLARE_OP1(DW_CFA_same_value, OT_Register);
375   DECLARE_OP2(DW_CFA_offset, OT_Register, OT_UnsignedFactDataOffset);
376   DECLARE_OP2(DW_CFA_offset_extended, OT_Register, OT_UnsignedFactDataOffset);
377   DECLARE_OP2(DW_CFA_offset_extended_sf, OT_Register, OT_SignedFactDataOffset);
378   DECLARE_OP2(DW_CFA_val_offset, OT_Register, OT_UnsignedFactDataOffset);
379   DECLARE_OP2(DW_CFA_val_offset_sf, OT_Register, OT_SignedFactDataOffset);
380   DECLARE_OP2(DW_CFA_register, OT_Register, OT_Register);
381   DECLARE_OP2(DW_CFA_expression, OT_Register, OT_Expression);
382   DECLARE_OP2(DW_CFA_val_expression, OT_Register, OT_Expression);
383   DECLARE_OP1(DW_CFA_restore, OT_Register);
384   DECLARE_OP1(DW_CFA_restore_extended, OT_Register);
385   DECLARE_OP0(DW_CFA_remember_state);
386   DECLARE_OP0(DW_CFA_restore_state);
387   DECLARE_OP0(DW_CFA_GNU_window_save);
388   DECLARE_OP1(DW_CFA_GNU_args_size, OT_Offset);
389   DECLARE_OP0(DW_CFA_nop);
390 
391 #undef DECLARE_OP0
392 #undef DECLARE_OP1
393 #undef DECLARE_OP2
394 
395   return ArrayRef<OperandType[2]>(&OpTypes[0], DW_CFA_restore+1);
396 }
397 
398 static ArrayRef<OperandType[2]> OpTypes = getOperandTypes();
399 
400 /// \brief Print \p Opcode's operand number \p OperandIdx which has
401 /// value \p Operand.
402 static void printOperand(raw_ostream &OS, uint8_t Opcode, unsigned OperandIdx,
403                          uint64_t Operand, uint64_t CodeAlignmentFactor,
404                          int64_t DataAlignmentFactor) {
405   assert(OperandIdx < 2);
406   OperandType Type = OpTypes[Opcode][OperandIdx];
407 
408   switch (Type) {
409   case OT_Unset: {
410     OS << " Unsupported " << (OperandIdx ? "second" : "first") << " operand to";
411     auto OpcodeName = CallFrameString(Opcode);
412     if (!OpcodeName.empty())
413       OS << " " << OpcodeName;
414     else
415       OS << format(" Opcode %x",  Opcode);
416     break;
417   }
418   case OT_None:
419     break;
420   case OT_Address:
421     OS << format(" %" PRIx64, Operand);
422     break;
423   case OT_Offset:
424     // The offsets are all encoded in a unsigned form, but in practice
425     // consumers use them signed. It's most certainly legacy due to
426     // the lack of signed variants in the first Dwarf standards.
427     OS << format(" %+" PRId64, int64_t(Operand));
428     break;
429   case OT_FactoredCodeOffset: // Always Unsigned
430     if (CodeAlignmentFactor)
431       OS << format(" %" PRId64, Operand * CodeAlignmentFactor);
432     else
433       OS << format(" %" PRId64 "*code_alignment_factor" , Operand);
434     break;
435   case OT_SignedFactDataOffset:
436     if (DataAlignmentFactor)
437       OS << format(" %" PRId64, int64_t(Operand) * DataAlignmentFactor);
438     else
439       OS << format(" %" PRId64 "*data_alignment_factor" , int64_t(Operand));
440     break;
441   case OT_UnsignedFactDataOffset:
442     if (DataAlignmentFactor)
443       OS << format(" %" PRId64, Operand * DataAlignmentFactor);
444     else
445       OS << format(" %" PRId64 "*data_alignment_factor" , Operand);
446     break;
447   case OT_Register:
448     OS << format(" reg%" PRId64, Operand);
449     break;
450   case OT_Expression:
451     OS << " expression";
452     break;
453   }
454 }
455 
456 void FrameEntry::dumpInstructions(raw_ostream &OS) const {
457   uint64_t CodeAlignmentFactor = 0;
458   int64_t DataAlignmentFactor = 0;
459   const CIE *Cie = dyn_cast<CIE>(this);
460 
461   if (!Cie)
462     Cie = cast<FDE>(this)->getLinkedCIE();
463   if (Cie) {
464     CodeAlignmentFactor = Cie->getCodeAlignmentFactor();
465     DataAlignmentFactor = Cie->getDataAlignmentFactor();
466   }
467 
468   for (const auto &Instr : Instructions) {
469     uint8_t Opcode = Instr.Opcode;
470     if (Opcode & DWARF_CFI_PRIMARY_OPCODE_MASK)
471       Opcode &= DWARF_CFI_PRIMARY_OPCODE_MASK;
472     OS << "  " << CallFrameString(Opcode) << ":";
473     for (unsigned i = 0; i < Instr.Ops.size(); ++i)
474       printOperand(OS, Opcode, i, Instr.Ops[i], CodeAlignmentFactor,
475                    DataAlignmentFactor);
476     OS << '\n';
477   }
478 }
479 
480 DWARFDebugFrame::DWARFDebugFrame(bool IsEH) : IsEH(IsEH) {}
481 
482 DWARFDebugFrame::~DWARFDebugFrame() = default;
483 
484 static void LLVM_ATTRIBUTE_UNUSED dumpDataAux(DataExtractor Data,
485                                               uint32_t Offset, int Length) {
486   errs() << "DUMP: ";
487   for (int i = 0; i < Length; ++i) {
488     uint8_t c = Data.getU8(&Offset);
489     errs().write_hex(c); errs() << " ";
490   }
491   errs() << "\n";
492 }
493 
494 static unsigned getSizeForEncoding(const DataExtractor &Data,
495                                    unsigned symbolEncoding) {
496   unsigned format = symbolEncoding & 0x0f;
497   switch (format) {
498     default: llvm_unreachable("Unknown Encoding");
499     case DW_EH_PE_absptr:
500     case DW_EH_PE_signed:
501       return Data.getAddressSize();
502     case DW_EH_PE_udata2:
503     case DW_EH_PE_sdata2:
504       return 2;
505     case DW_EH_PE_udata4:
506     case DW_EH_PE_sdata4:
507       return 4;
508     case DW_EH_PE_udata8:
509     case DW_EH_PE_sdata8:
510       return 8;
511   }
512 }
513 
514 static uint64_t readPointer(const DataExtractor &Data, uint32_t &Offset,
515                             unsigned Encoding) {
516   switch (getSizeForEncoding(Data, Encoding)) {
517     case 2:
518       return Data.getU16(&Offset);
519     case 4:
520       return Data.getU32(&Offset);
521     case 8:
522       return Data.getU64(&Offset);
523     default:
524       llvm_unreachable("Illegal data size");
525   }
526 }
527 
528 // This is a workaround for old compilers which do not allow
529 // noreturn attribute usage in lambdas. Once the support for those
530 // compilers are phased out, we can remove this and return back to
531 // a ReportError lambda: [StartOffset](const char *ErrorMsg).
532 static void LLVM_ATTRIBUTE_NORETURN ReportError(uint32_t StartOffset,
533                                                 const char *ErrorMsg) {
534   std::string Str;
535   raw_string_ostream OS(Str);
536   OS << format(ErrorMsg, StartOffset);
537   OS.flush();
538   report_fatal_error(Str);
539 }
540 
541 void DWARFDebugFrame::parse(DataExtractor Data) {
542   uint32_t Offset = 0;
543   DenseMap<uint32_t, CIE *> CIEs;
544 
545   while (Data.isValidOffset(Offset)) {
546     uint32_t StartOffset = Offset;
547 
548     bool IsDWARF64 = false;
549     uint64_t Length = Data.getU32(&Offset);
550     uint64_t Id;
551 
552     if (Length == UINT32_MAX) {
553       // DWARF-64 is distinguished by the first 32 bits of the initial length
554       // field being 0xffffffff. Then, the next 64 bits are the actual entry
555       // length.
556       IsDWARF64 = true;
557       Length = Data.getU64(&Offset);
558     }
559 
560     // At this point, Offset points to the next field after Length.
561     // Length is the structure size excluding itself. Compute an offset one
562     // past the end of the structure (needed to know how many instructions to
563     // read).
564     // TODO: For honest DWARF64 support, DataExtractor will have to treat
565     //       offset_ptr as uint64_t*
566     uint32_t StartStructureOffset = Offset;
567     uint32_t EndStructureOffset = Offset + static_cast<uint32_t>(Length);
568 
569     // The Id field's size depends on the DWARF format
570     Id = Data.getUnsigned(&Offset, (IsDWARF64 && !IsEH) ? 8 : 4);
571     bool IsCIE = ((IsDWARF64 && Id == DW64_CIE_ID) ||
572                   Id == DW_CIE_ID ||
573                   (IsEH && !Id));
574 
575     if (IsCIE) {
576       uint8_t Version = Data.getU8(&Offset);
577       const char *Augmentation = Data.getCStr(&Offset);
578       StringRef AugmentationString(Augmentation ? Augmentation : "");
579       uint8_t AddressSize = Version < 4 ? Data.getAddressSize() :
580                                           Data.getU8(&Offset);
581       Data.setAddressSize(AddressSize);
582       uint8_t SegmentDescriptorSize = Version < 4 ? 0 : Data.getU8(&Offset);
583       uint64_t CodeAlignmentFactor = Data.getULEB128(&Offset);
584       int64_t DataAlignmentFactor = Data.getSLEB128(&Offset);
585       uint64_t ReturnAddressRegister = Data.getULEB128(&Offset);
586 
587       // Parse the augmentation data for EH CIEs
588       StringRef AugmentationData("");
589       uint32_t FDEPointerEncoding = DW_EH_PE_omit;
590       uint32_t LSDAPointerEncoding = DW_EH_PE_omit;
591       if (IsEH) {
592         Optional<uint32_t> PersonalityEncoding;
593         Optional<uint64_t> Personality;
594 
595         Optional<uint64_t> AugmentationLength;
596         uint32_t StartAugmentationOffset;
597         uint32_t EndAugmentationOffset;
598 
599         // Walk the augmentation string to get all the augmentation data.
600         for (unsigned i = 0, e = AugmentationString.size(); i != e; ++i) {
601           switch (AugmentationString[i]) {
602             default:
603               ReportError(StartOffset,
604                           "Unknown augmentation character in entry at %lx");
605             case 'L':
606               LSDAPointerEncoding = Data.getU8(&Offset);
607               break;
608             case 'P': {
609               if (Personality)
610                 ReportError(StartOffset,
611                             "Duplicate personality in entry at %lx");
612               PersonalityEncoding = Data.getU8(&Offset);
613               Personality = readPointer(Data, Offset, *PersonalityEncoding);
614               break;
615             }
616             case 'R':
617               FDEPointerEncoding = Data.getU8(&Offset);
618               break;
619             case 'z':
620               if (i)
621                 ReportError(StartOffset,
622                             "'z' must be the first character at %lx");
623               // Parse the augmentation length first.  We only parse it if
624               // the string contains a 'z'.
625               AugmentationLength = Data.getULEB128(&Offset);
626               StartAugmentationOffset = Offset;
627               EndAugmentationOffset = Offset +
628                 static_cast<uint32_t>(*AugmentationLength);
629           }
630         }
631 
632         if (AugmentationLength.hasValue()) {
633           if (Offset != EndAugmentationOffset)
634             ReportError(StartOffset, "Parsing augmentation data at %lx failed");
635 
636           AugmentationData = Data.getData().slice(StartAugmentationOffset,
637                                                   EndAugmentationOffset);
638         }
639       }
640 
641       auto Cie = llvm::make_unique<CIE>(StartOffset, Length, Version,
642                                         AugmentationString, AddressSize,
643                                         SegmentDescriptorSize,
644                                         CodeAlignmentFactor,
645                                         DataAlignmentFactor,
646                                         ReturnAddressRegister,
647                                         AugmentationData, FDEPointerEncoding,
648                                         LSDAPointerEncoding);
649       CIEs[StartOffset] = Cie.get();
650       Entries.emplace_back(std::move(Cie));
651     } else {
652       // FDE
653       uint64_t CIEPointer = Id;
654       uint64_t InitialLocation = 0;
655       uint64_t AddressRange = 0;
656       CIE *Cie = CIEs[IsEH ? (StartStructureOffset - CIEPointer) : CIEPointer];
657 
658       if (IsEH) {
659         // The address size is encoded in the CIE we reference.
660         if (!Cie)
661           ReportError(StartOffset,
662                       "Parsing FDE data at %lx failed due to missing CIE");
663 
664         InitialLocation = readPointer(Data, Offset,
665                                       Cie->getFDEPointerEncoding());
666         AddressRange = readPointer(Data, Offset,
667                                    Cie->getFDEPointerEncoding());
668 
669         StringRef AugmentationString = Cie->getAugmentationString();
670         if (!AugmentationString.empty()) {
671           // Parse the augmentation length and data for this FDE.
672           uint64_t AugmentationLength = Data.getULEB128(&Offset);
673 
674           uint32_t EndAugmentationOffset =
675             Offset + static_cast<uint32_t>(AugmentationLength);
676 
677           // Decode the LSDA if the CIE augmentation string said we should.
678           if (Cie->getLSDAPointerEncoding() != DW_EH_PE_omit)
679             readPointer(Data, Offset, Cie->getLSDAPointerEncoding());
680 
681           if (Offset != EndAugmentationOffset)
682             ReportError(StartOffset, "Parsing augmentation data at %lx failed");
683         }
684       } else {
685         InitialLocation = Data.getAddress(&Offset);
686         AddressRange = Data.getAddress(&Offset);
687       }
688 
689       Entries.emplace_back(new FDE(StartOffset, Length, CIEPointer,
690                                    InitialLocation, AddressRange,
691                                    Cie));
692     }
693 
694     Entries.back()->parseInstructions(Data, &Offset, EndStructureOffset);
695 
696     if (Offset != EndStructureOffset)
697       ReportError(StartOffset, "Parsing entry instructions at %lx failed");
698   }
699 }
700 
701 FrameEntry *DWARFDebugFrame::getEntryAtOffset(uint64_t Offset) const {
702   auto It =
703       std::lower_bound(Entries.begin(), Entries.end(), Offset,
704                        [](const std::unique_ptr<FrameEntry> &E,
705                           uint64_t Offset) { return E->getOffset() < Offset; });
706   if (It != Entries.end() && (*It)->getOffset() == Offset)
707     return It->get();
708   return nullptr;
709 }
710 
711 void DWARFDebugFrame::dump(raw_ostream &OS, Optional<uint64_t> Offset) const {
712   if (Offset) {
713     if (auto *Entry = getEntryAtOffset(*Offset))
714       Entry->dump(OS);
715     return;
716   }
717 
718   OS << "\n";
719   for (const auto &Entry : Entries)
720     Entry->dump(OS);
721 }
722