1 //===-- Exceptions.cpp - Helpers for processing C++ exceptions ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Some of the code is taken from examples/ExceptionDemo
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "bolt/Core/Exceptions.h"
14 #include "bolt/Core/BinaryFunction.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/BinaryFormat/Dwarf.h"
18 #include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/LEB128.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <map>
26 
27 #undef  DEBUG_TYPE
28 #define DEBUG_TYPE "bolt-exceptions"
29 
30 using namespace llvm::dwarf;
31 
32 namespace opts {
33 
34 extern llvm::cl::OptionCategory BoltCategory;
35 
36 extern llvm::cl::opt<unsigned> Verbosity;
37 
38 static llvm::cl::opt<bool>
39 PrintExceptions("print-exceptions",
40   llvm::cl::desc("print exception handling data"),
41   llvm::cl::ZeroOrMore,
42   llvm::cl::Hidden,
43   llvm::cl::cat(BoltCategory));
44 
45 } // namespace opts
46 
47 namespace llvm {
48 namespace bolt {
49 
50 // Read and dump the .gcc_exception_table section entry.
51 //
52 // .gcc_except_table section contains a set of Language-Specific Data Areas -
53 // a fancy name for exception handling tables. There's one  LSDA entry per
54 // function. However, we can't actually tell which function LSDA refers to
55 // unless we parse .eh_frame entry that refers to the LSDA.
56 // Then inside LSDA most addresses are encoded relative to the function start,
57 // so we need the function context in order to get to real addresses.
58 //
59 // The best visual representation of the tables comprising LSDA and
60 // relationships between them is illustrated at:
61 //   https://github.com/itanium-cxx-abi/cxx-abi/blob/master/exceptions.pdf
62 // Keep in mind that GCC implementation deviates slightly from that document.
63 //
64 // To summarize, there are 4 tables in LSDA: call site table, actions table,
65 // types table, and types index table (for indirection). The main table contains
66 // call site entries. Each call site includes a PC range that can throw an
67 // exception, a handler (landing pad), and a reference to an entry in the action
68 // table. The handler and/or action could be 0. The action entry is a head
69 // of a list of actions associated with a call site. The action table contains
70 // all such lists (it could be optimized to share list tails). Each action could
71 // be either to catch an exception of a given type, to perform a cleanup, or to
72 // propagate the exception after filtering it out (e.g. to make sure function
73 // exception specification is not violated). Catch action contains a reference
74 // to an entry in the type table, and filter action refers to an entry in the
75 // type index table to encode a set of types to filter.
76 //
77 // Call site table follows LSDA header. Action table immediately follows the
78 // call site table.
79 //
80 // Both types table and type index table start at the same location, but they
81 // grow in opposite directions (types go up, indices go down). The beginning of
82 // these tables is encoded in LSDA header. Sizes for both of the tables are not
83 // included anywhere.
84 //
85 // We have to parse all of the tables to determine their sizes. Then we have
86 // to parse the call site table and associate discovered information with
87 // actual call instructions and landing pad blocks.
88 //
89 // For the purpose of rewriting exception handling tables, we can reuse action,
90 // and type index tables in their original binary format.
91 //
92 // Type table could be encoded using position-independent references, and thus
93 // may require relocation.
94 //
95 // Ideally we should be able to re-write LSDA in-place, without the need to
96 // allocate a new space for it. Sadly there's no guarantee that the new call
97 // site table will be the same size as GCC uses uleb encodings for PC offsets.
98 //
99 // Note: some functions have LSDA entries with 0 call site entries.
100 void BinaryFunction::parseLSDA(ArrayRef<uint8_t> LSDASectionData,
101                                uint64_t LSDASectionAddress) {
102   assert(CurrentState == State::Disassembled && "unexpected function state");
103 
104   if (!getLSDAAddress())
105     return;
106 
107   DWARFDataExtractor Data(
108       StringRef(reinterpret_cast<const char *>(LSDASectionData.data()),
109                 LSDASectionData.size()),
110       BC.DwCtx->getDWARFObj().isLittleEndian(), 8);
111   uint64_t Offset = getLSDAAddress() - LSDASectionAddress;
112   assert(Data.isValidOffset(Offset) && "wrong LSDA address");
113 
114   uint8_t LPStartEncoding = Data.getU8(&Offset);
115   uint64_t LPStart = 0;
116   if (Optional<uint64_t> MaybeLPStart = Data.getEncodedPointer(
117           &Offset, LPStartEncoding, Offset + LSDASectionAddress))
118     LPStart = *MaybeLPStart;
119 
120   assert(LPStart == 0 && "support for split functions not implemented");
121 
122   const uint8_t TTypeEncoding = Data.getU8(&Offset);
123   size_t TTypeEncodingSize = 0;
124   uintptr_t TTypeEnd = 0;
125   if (TTypeEncoding != DW_EH_PE_omit) {
126     TTypeEnd = Data.getULEB128(&Offset);
127     TTypeEncodingSize = BC.getDWARFEncodingSize(TTypeEncoding);
128   }
129 
130   if (opts::PrintExceptions) {
131     outs() << "[LSDA at 0x" << Twine::utohexstr(getLSDAAddress())
132            << " for function " << *this << "]:\n";
133     outs() << "LPStart Encoding = 0x" << Twine::utohexstr(LPStartEncoding)
134            << '\n';
135     outs() << "LPStart = 0x" << Twine::utohexstr(LPStart) << '\n';
136     outs() << "TType Encoding = 0x" << Twine::utohexstr(TTypeEncoding) << '\n';
137     outs() << "TType End = " << TTypeEnd << '\n';
138   }
139 
140   // Table to store list of indices in type table. Entries are uleb128 values.
141   const uint64_t TypeIndexTableStart = Offset + TTypeEnd;
142 
143   // Offset past the last decoded index.
144   uint64_t MaxTypeIndexTableOffset = 0;
145 
146   // Max positive index used in type table.
147   unsigned MaxTypeIndex = 0;
148 
149   // The actual type info table starts at the same location, but grows in
150   // opposite direction. TTypeEncoding is used to encode stored values.
151   const uint64_t TypeTableStart = Offset + TTypeEnd;
152 
153   uint8_t CallSiteEncoding = Data.getU8(&Offset);
154   uint32_t CallSiteTableLength = Data.getULEB128(&Offset);
155   uint64_t CallSiteTableStart = Offset;
156   uint64_t CallSiteTableEnd = CallSiteTableStart + CallSiteTableLength;
157   uint64_t CallSitePtr = CallSiteTableStart;
158   uint64_t ActionTableStart = CallSiteTableEnd;
159 
160   if (opts::PrintExceptions) {
161     outs() << "CallSite Encoding = " << (unsigned)CallSiteEncoding << '\n';
162     outs() << "CallSite table length = " << CallSiteTableLength << '\n';
163     outs() << '\n';
164   }
165 
166   this->HasEHRanges = CallSitePtr < CallSiteTableEnd;
167   const uint64_t RangeBase = getAddress();
168   while (CallSitePtr < CallSiteTableEnd) {
169     uint64_t Start = *Data.getEncodedPointer(&CallSitePtr, CallSiteEncoding,
170                                              CallSitePtr + LSDASectionAddress);
171     uint64_t Length = *Data.getEncodedPointer(&CallSitePtr, CallSiteEncoding,
172                                               CallSitePtr + LSDASectionAddress);
173     uint64_t LandingPad = *Data.getEncodedPointer(
174         &CallSitePtr, CallSiteEncoding, CallSitePtr + LSDASectionAddress);
175     uint64_t ActionEntry = Data.getULEB128(&CallSitePtr);
176 
177     if (opts::PrintExceptions) {
178       outs() << "Call Site: [0x" << Twine::utohexstr(RangeBase + Start)
179              << ", 0x" << Twine::utohexstr(RangeBase + Start + Length)
180              << "); landing pad: 0x" << Twine::utohexstr(LPStart + LandingPad)
181              << "; action entry: 0x" << Twine::utohexstr(ActionEntry) << "\n";
182       outs() << "  current offset is " << (CallSitePtr - CallSiteTableStart)
183              << '\n';
184     }
185 
186     // Create a handler entry if necessary.
187     MCSymbol *LPSymbol = nullptr;
188     if (LandingPad) {
189       if (!getInstructionAtOffset(LandingPad)) {
190         if (opts::Verbosity >= 1)
191           errs() << "BOLT-WARNING: landing pad " << Twine::utohexstr(LandingPad)
192                  << " not pointing to an instruction in function " << *this
193                  << " - ignoring.\n";
194       } else {
195         auto Label = Labels.find(LandingPad);
196         if (Label != Labels.end()) {
197           LPSymbol = Label->second;
198         } else {
199           LPSymbol = BC.Ctx->createNamedTempSymbol("LP");
200           Labels[LandingPad] = LPSymbol;
201         }
202       }
203     }
204 
205     // Mark all call instructions in the range.
206     auto II = Instructions.find(Start);
207     auto IE = Instructions.end();
208     assert(II != IE && "exception range not pointing to an instruction");
209     do {
210       MCInst &Instruction = II->second;
211       if (BC.MIB->isCall(Instruction) &&
212           !BC.MIB->getConditionalTailCall(Instruction)) {
213         assert(!BC.MIB->isInvoke(Instruction) &&
214                "overlapping exception ranges detected");
215         // Add extra operands to a call instruction making it an invoke from
216         // now on.
217         BC.MIB->addEHInfo(Instruction,
218                           MCPlus::MCLandingPad(LPSymbol, ActionEntry));
219       }
220       ++II;
221     } while (II != IE && II->first < Start + Length);
222 
223     if (ActionEntry != 0) {
224       auto printType = [&](int Index, raw_ostream &OS) {
225         assert(Index > 0 && "only positive indices are valid");
226         uint64_t TTEntry = TypeTableStart - Index * TTypeEncodingSize;
227         const uint64_t TTEntryAddress = TTEntry + LSDASectionAddress;
228         uint64_t TypeAddress =
229             *Data.getEncodedPointer(&TTEntry, TTypeEncoding, TTEntryAddress);
230         if ((TTypeEncoding & DW_EH_PE_pcrel) && TypeAddress == TTEntryAddress) {
231           TypeAddress = 0;
232         }
233         if (TypeAddress == 0) {
234           OS << "<all>";
235           return;
236         }
237         if (TTypeEncoding & DW_EH_PE_indirect) {
238           ErrorOr<uint64_t> PointerOrErr = BC.getPointerAtAddress(TypeAddress);
239           assert(PointerOrErr && "failed to decode indirect address");
240           TypeAddress = *PointerOrErr;
241         }
242         if (BinaryData *TypeSymBD = BC.getBinaryDataAtAddress(TypeAddress)) {
243           OS << TypeSymBD->getName();
244         } else {
245           OS << "0x" << Twine::utohexstr(TypeAddress);
246         }
247       };
248       if (opts::PrintExceptions)
249         outs() << "    actions: ";
250       uint64_t ActionPtr = ActionTableStart + ActionEntry - 1;
251       int64_t ActionType;
252       int64_t ActionNext;
253       const char *Sep = "";
254       do {
255         ActionType = Data.getSLEB128(&ActionPtr);
256         const uint32_t Self = ActionPtr;
257         ActionNext = Data.getSLEB128(&ActionPtr);
258         if (opts::PrintExceptions)
259           outs() << Sep << "(" << ActionType << ", " << ActionNext << ") ";
260         if (ActionType == 0) {
261           if (opts::PrintExceptions)
262             outs() << "cleanup";
263         } else if (ActionType > 0) {
264           // It's an index into a type table.
265           MaxTypeIndex =
266               std::max(MaxTypeIndex, static_cast<unsigned>(ActionType));
267           if (opts::PrintExceptions) {
268             outs() << "catch type ";
269             printType(ActionType, outs());
270           }
271         } else { // ActionType < 0
272           if (opts::PrintExceptions)
273             outs() << "filter exception types ";
274           const char *TSep = "";
275           // ActionType is a negative *byte* offset into *uleb128-encoded* table
276           // of indices with base 1.
277           // E.g. -1 means offset 0, -2 is offset 1, etc. The indices are
278           // encoded using uleb128 thus we cannot directly dereference them.
279           uint64_t TypeIndexTablePtr = TypeIndexTableStart - ActionType - 1;
280           while (uint64_t Index = Data.getULEB128(&TypeIndexTablePtr)) {
281             MaxTypeIndex = std::max(MaxTypeIndex, static_cast<unsigned>(Index));
282             if (opts::PrintExceptions) {
283               outs() << TSep;
284               printType(Index, outs());
285               TSep = ", ";
286             }
287           }
288           MaxTypeIndexTableOffset = std::max(
289               MaxTypeIndexTableOffset, TypeIndexTablePtr - TypeIndexTableStart);
290         }
291 
292         Sep = "; ";
293 
294         ActionPtr = Self + ActionNext;
295       } while (ActionNext);
296       if (opts::PrintExceptions)
297         outs() << '\n';
298     }
299   }
300   if (opts::PrintExceptions)
301     outs() << '\n';
302 
303   assert(TypeIndexTableStart + MaxTypeIndexTableOffset <=
304              Data.getData().size() &&
305          "LSDA entry has crossed section boundary");
306 
307   if (TTypeEnd) {
308     LSDAActionTable = LSDASectionData.slice(
309         ActionTableStart, TypeIndexTableStart -
310                               MaxTypeIndex * TTypeEncodingSize -
311                               ActionTableStart);
312     for (unsigned Index = 1; Index <= MaxTypeIndex; ++Index) {
313       uint64_t TTEntry = TypeTableStart - Index * TTypeEncodingSize;
314       const uint64_t TTEntryAddress = TTEntry + LSDASectionAddress;
315       uint64_t TypeAddress =
316           *Data.getEncodedPointer(&TTEntry, TTypeEncoding, TTEntryAddress);
317       if ((TTypeEncoding & DW_EH_PE_pcrel) && (TypeAddress == TTEntryAddress))
318         TypeAddress = 0;
319       if (TTypeEncoding & DW_EH_PE_indirect) {
320         LSDATypeAddressTable.emplace_back(TypeAddress);
321         if (TypeAddress) {
322           ErrorOr<uint64_t> PointerOrErr = BC.getPointerAtAddress(TypeAddress);
323           assert(PointerOrErr && "failed to decode indirect address");
324           TypeAddress = *PointerOrErr;
325         }
326       }
327       LSDATypeTable.emplace_back(TypeAddress);
328     }
329     LSDATypeIndexTable =
330         LSDASectionData.slice(TypeIndexTableStart, MaxTypeIndexTableOffset);
331   }
332 }
333 
334 void BinaryFunction::updateEHRanges() {
335   if (getSize() == 0)
336     return;
337 
338   assert(CurrentState == State::CFG_Finalized && "unexpected state");
339 
340   // Build call sites table.
341   struct EHInfo {
342     const MCSymbol *LP; // landing pad
343     uint64_t Action;
344   };
345 
346   // If previous call can throw, this is its exception handler.
347   EHInfo PreviousEH = {nullptr, 0};
348 
349   // Marker for the beginning of exceptions range.
350   const MCSymbol *StartRange = nullptr;
351 
352   // Indicates whether the start range is located in a cold part.
353   bool IsStartInCold = false;
354 
355   // Have we crossed hot/cold border for split functions?
356   bool SeenCold = false;
357 
358   // Sites to update - either regular or cold.
359   CallSitesType *Sites = &CallSites;
360 
361   for (BinaryBasicBlock *&BB : BasicBlocksLayout) {
362 
363     if (BB->isCold() && !SeenCold) {
364       SeenCold = true;
365 
366       // Close the range (if any) and change the target call sites.
367       if (StartRange) {
368         Sites->emplace_back(CallSite{StartRange, getFunctionEndLabel(),
369                                      PreviousEH.LP, PreviousEH.Action});
370       }
371       Sites = &ColdCallSites;
372 
373       // Reset the range.
374       StartRange = nullptr;
375       PreviousEH = {nullptr, 0};
376     }
377 
378     for (auto II = BB->begin(); II != BB->end(); ++II) {
379       if (!BC.MIB->isCall(*II))
380         continue;
381 
382       // Instruction can throw an exception that should be handled.
383       const bool Throws = BC.MIB->isInvoke(*II);
384 
385       // Ignore the call if it's a continuation of a no-throw gap.
386       if (!Throws && !StartRange)
387         continue;
388 
389       // Extract exception handling information from the instruction.
390       const MCSymbol *LP = nullptr;
391       uint64_t Action = 0;
392       if (const Optional<MCPlus::MCLandingPad> EHInfo = BC.MIB->getEHInfo(*II))
393         std::tie(LP, Action) = *EHInfo;
394 
395       // No action if the exception handler has not changed.
396       if (Throws && StartRange && PreviousEH.LP == LP &&
397           PreviousEH.Action == Action)
398         continue;
399 
400       // Same symbol is used for the beginning and the end of the range.
401       const MCSymbol *EHSymbol;
402       MCInst EHLabel;
403       {
404         std::unique_lock<std::shared_timed_mutex> Lock(BC.CtxMutex);
405         EHSymbol = BC.Ctx->createNamedTempSymbol("EH");
406         BC.MIB->createEHLabel(EHLabel, EHSymbol, BC.Ctx.get());
407       }
408 
409       II = std::next(BB->insertPseudoInstr(II, EHLabel));
410 
411       // At this point we could be in one of the following states:
412       //
413       // I. Exception handler has changed and we need to close previous range
414       //    and start a new one.
415       //
416       // II. Start a new exception range after the gap.
417       //
418       // III. Close current exception range and start a new gap.
419       const MCSymbol *EndRange;
420       if (StartRange) {
421         // I, III:
422         EndRange = EHSymbol;
423       } else {
424         // II:
425         StartRange = EHSymbol;
426         IsStartInCold = SeenCold;
427         EndRange = nullptr;
428       }
429 
430       // Close the previous range.
431       if (EndRange) {
432         Sites->emplace_back(
433             CallSite{StartRange, EndRange, PreviousEH.LP, PreviousEH.Action});
434       }
435 
436       if (Throws) {
437         // I, II:
438         StartRange = EHSymbol;
439         IsStartInCold = SeenCold;
440         PreviousEH = EHInfo{LP, Action};
441       } else {
442         StartRange = nullptr;
443       }
444     }
445   }
446 
447   // Check if we need to close the range.
448   if (StartRange) {
449     assert((!isSplit() || Sites == &ColdCallSites) && "sites mismatch");
450     const MCSymbol *EndRange =
451         IsStartInCold ? getFunctionColdEndLabel() : getFunctionEndLabel();
452     Sites->emplace_back(
453         CallSite{StartRange, EndRange, PreviousEH.LP, PreviousEH.Action});
454   }
455 }
456 
457 const uint8_t DWARF_CFI_PRIMARY_OPCODE_MASK = 0xc0;
458 
459 CFIReaderWriter::CFIReaderWriter(const DWARFDebugFrame &EHFrame) {
460   // Prepare FDEs for fast lookup
461   for (const dwarf::FrameEntry &Entry : EHFrame.entries()) {
462     const auto *CurFDE = dyn_cast<dwarf::FDE>(&Entry);
463     // Skip CIEs.
464     if (!CurFDE)
465       continue;
466     // There could me multiple FDEs with the same initial address, and perhaps
467     // different sizes (address ranges). Use the first entry with non-zero size.
468     auto FDEI = FDEs.lower_bound(CurFDE->getInitialLocation());
469     if (FDEI != FDEs.end() && FDEI->first == CurFDE->getInitialLocation()) {
470       if (CurFDE->getAddressRange()) {
471         if (FDEI->second->getAddressRange() == 0) {
472           FDEI->second = CurFDE;
473         } else if (opts::Verbosity > 0) {
474           errs() << "BOLT-WARNING: different FDEs for function at 0x"
475                  << Twine::utohexstr(FDEI->first)
476                  << " detected; sizes: " << FDEI->second->getAddressRange()
477                  << " and " << CurFDE->getAddressRange() << '\n';
478         }
479       }
480     } else {
481       FDEs.emplace_hint(FDEI, CurFDE->getInitialLocation(), CurFDE);
482     }
483   }
484 }
485 
486 bool CFIReaderWriter::fillCFIInfoFor(BinaryFunction &Function) const {
487   uint64_t Address = Function.getAddress();
488   auto I = FDEs.find(Address);
489   // Ignore zero-length FDE ranges.
490   if (I == FDEs.end() || !I->second->getAddressRange())
491     return true;
492 
493   const FDE &CurFDE = *I->second;
494   Optional<uint64_t> LSDA = CurFDE.getLSDAAddress();
495   Function.setLSDAAddress(LSDA ? *LSDA : 0);
496 
497   uint64_t Offset = 0;
498   uint64_t CodeAlignment = CurFDE.getLinkedCIE()->getCodeAlignmentFactor();
499   uint64_t DataAlignment = CurFDE.getLinkedCIE()->getDataAlignmentFactor();
500   if (CurFDE.getLinkedCIE()->getPersonalityAddress()) {
501     Function.setPersonalityFunction(
502         *CurFDE.getLinkedCIE()->getPersonalityAddress());
503     Function.setPersonalityEncoding(
504         *CurFDE.getLinkedCIE()->getPersonalityEncoding());
505   }
506 
507   auto decodeFrameInstruction = [&Function, &Offset, Address, CodeAlignment,
508                                  DataAlignment](
509                                     const CFIProgram::Instruction &Instr) {
510     uint8_t Opcode = Instr.Opcode;
511     if (Opcode & DWARF_CFI_PRIMARY_OPCODE_MASK)
512       Opcode &= DWARF_CFI_PRIMARY_OPCODE_MASK;
513     switch (Instr.Opcode) {
514     case DW_CFA_nop:
515       break;
516     case DW_CFA_advance_loc4:
517     case DW_CFA_advance_loc2:
518     case DW_CFA_advance_loc1:
519     case DW_CFA_advance_loc:
520       // Advance our current address
521       Offset += CodeAlignment * int64_t(Instr.Ops[0]);
522       break;
523     case DW_CFA_offset_extended_sf:
524       Function.addCFIInstruction(
525           Offset,
526           MCCFIInstruction::createOffset(
527               nullptr, Instr.Ops[0], DataAlignment * int64_t(Instr.Ops[1])));
528       break;
529     case DW_CFA_offset_extended:
530     case DW_CFA_offset:
531       Function.addCFIInstruction(
532           Offset, MCCFIInstruction::createOffset(nullptr, Instr.Ops[0],
533                                                  DataAlignment * Instr.Ops[1]));
534       break;
535     case DW_CFA_restore_extended:
536     case DW_CFA_restore:
537       Function.addCFIInstruction(
538           Offset, MCCFIInstruction::createRestore(nullptr, Instr.Ops[0]));
539       break;
540     case DW_CFA_set_loc:
541       assert(Instr.Ops[0] >= Address && "set_loc out of function bounds");
542       assert(Instr.Ops[0] <= Address + Function.getSize() &&
543              "set_loc out of function bounds");
544       Offset = Instr.Ops[0] - Address;
545       break;
546 
547     case DW_CFA_undefined:
548       Function.addCFIInstruction(
549           Offset, MCCFIInstruction::createUndefined(nullptr, Instr.Ops[0]));
550       break;
551     case DW_CFA_same_value:
552       Function.addCFIInstruction(
553           Offset, MCCFIInstruction::createSameValue(nullptr, Instr.Ops[0]));
554       break;
555     case DW_CFA_register:
556       Function.addCFIInstruction(
557           Offset, MCCFIInstruction::createRegister(nullptr, Instr.Ops[0],
558                                                    Instr.Ops[1]));
559       break;
560     case DW_CFA_remember_state:
561       Function.addCFIInstruction(
562           Offset, MCCFIInstruction::createRememberState(nullptr));
563       break;
564     case DW_CFA_restore_state:
565       Function.addCFIInstruction(Offset,
566                                  MCCFIInstruction::createRestoreState(nullptr));
567       break;
568     case DW_CFA_def_cfa:
569       Function.addCFIInstruction(
570           Offset,
571           MCCFIInstruction::cfiDefCfa(nullptr, Instr.Ops[0], Instr.Ops[1]));
572       break;
573     case DW_CFA_def_cfa_sf:
574       Function.addCFIInstruction(
575           Offset,
576           MCCFIInstruction::cfiDefCfa(nullptr, Instr.Ops[0],
577                                       DataAlignment * int64_t(Instr.Ops[1])));
578       break;
579     case DW_CFA_def_cfa_register:
580       Function.addCFIInstruction(Offset, MCCFIInstruction::createDefCfaRegister(
581                                              nullptr, Instr.Ops[0]));
582       break;
583     case DW_CFA_def_cfa_offset:
584       Function.addCFIInstruction(
585           Offset, MCCFIInstruction::cfiDefCfaOffset(nullptr, Instr.Ops[0]));
586       break;
587     case DW_CFA_def_cfa_offset_sf:
588       Function.addCFIInstruction(
589           Offset, MCCFIInstruction::cfiDefCfaOffset(
590                       nullptr, DataAlignment * int64_t(Instr.Ops[0])));
591       break;
592     case DW_CFA_GNU_args_size:
593       Function.addCFIInstruction(
594           Offset, MCCFIInstruction::createGnuArgsSize(nullptr, Instr.Ops[0]));
595       Function.setUsesGnuArgsSize();
596       break;
597     case DW_CFA_val_offset_sf:
598     case DW_CFA_val_offset:
599       if (opts::Verbosity >= 1) {
600         errs() << "BOLT-WARNING: DWARF val_offset() unimplemented\n";
601       }
602       return false;
603     case DW_CFA_def_cfa_expression:
604     case DW_CFA_val_expression:
605     case DW_CFA_expression: {
606       StringRef ExprBytes = Instr.Expression->getData();
607       std::string Str;
608       raw_string_ostream OS(Str);
609       // Manually encode this instruction using CFI escape
610       OS << Opcode;
611       if (Opcode != DW_CFA_def_cfa_expression) {
612         encodeULEB128(Instr.Ops[0], OS);
613       }
614       encodeULEB128(ExprBytes.size(), OS);
615       OS << ExprBytes;
616       Function.addCFIInstruction(
617           Offset, MCCFIInstruction::createEscape(nullptr, OS.str()));
618       break;
619     }
620     case DW_CFA_MIPS_advance_loc8:
621       if (opts::Verbosity >= 1) {
622         errs() << "BOLT-WARNING: DW_CFA_MIPS_advance_loc unimplemented\n";
623       }
624       return false;
625     case DW_CFA_GNU_window_save:
626     case DW_CFA_lo_user:
627     case DW_CFA_hi_user:
628       if (opts::Verbosity >= 1) {
629         errs() << "BOLT-WARNING: DW_CFA_GNU_* and DW_CFA_*_user "
630                   "unimplemented\n";
631       }
632       return false;
633     default:
634       if (opts::Verbosity >= 1) {
635         errs() << "BOLT-WARNING: Unrecognized CFI instruction: " << Instr.Opcode
636                << '\n';
637       }
638       return false;
639     }
640 
641     return true;
642   };
643 
644   for (const CFIProgram::Instruction &Instr : CurFDE.getLinkedCIE()->cfis()) {
645     if (!decodeFrameInstruction(Instr))
646       return false;
647   }
648 
649   for (const CFIProgram::Instruction &Instr : CurFDE.cfis()) {
650     if (!decodeFrameInstruction(Instr))
651       return false;
652   }
653 
654   return true;
655 }
656 
657 std::vector<char> CFIReaderWriter::generateEHFrameHeader(
658     const DWARFDebugFrame &OldEHFrame, const DWARFDebugFrame &NewEHFrame,
659     uint64_t EHFrameHeaderAddress,
660     std::vector<uint64_t> &FailedAddresses) const {
661   // Common PC -> FDE map to be written into .eh_frame_hdr.
662   std::map<uint64_t, uint64_t> PCToFDE;
663 
664   // Presort array for binary search.
665   std::sort(FailedAddresses.begin(), FailedAddresses.end());
666 
667   // Initialize PCToFDE using NewEHFrame.
668   for (dwarf::FrameEntry &Entry : NewEHFrame.entries()) {
669     const dwarf::FDE *FDE = dyn_cast<dwarf::FDE>(&Entry);
670     if (FDE == nullptr)
671       continue;
672     const uint64_t FuncAddress = FDE->getInitialLocation();
673     const uint64_t FDEAddress =
674         NewEHFrame.getEHFrameAddress() + FDE->getOffset();
675 
676     // Ignore unused FDEs.
677     if (FuncAddress == 0)
678       continue;
679 
680     // Add the address to the map unless we failed to write it.
681     if (!std::binary_search(FailedAddresses.begin(), FailedAddresses.end(),
682                             FuncAddress)) {
683       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: FDE for function at 0x"
684                         << Twine::utohexstr(FuncAddress) << " is at 0x"
685                         << Twine::utohexstr(FDEAddress) << '\n');
686       PCToFDE[FuncAddress] = FDEAddress;
687     }
688   };
689 
690   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: new .eh_frame contains "
691                     << std::distance(NewEHFrame.entries().begin(),
692                                      NewEHFrame.entries().end())
693                     << " entries\n");
694 
695   // Add entries from the original .eh_frame corresponding to the functions
696   // that we did not update.
697   for (const dwarf::FrameEntry &Entry : OldEHFrame) {
698     const dwarf::FDE *FDE = dyn_cast<dwarf::FDE>(&Entry);
699     if (FDE == nullptr)
700       continue;
701     const uint64_t FuncAddress = FDE->getInitialLocation();
702     const uint64_t FDEAddress =
703         OldEHFrame.getEHFrameAddress() + FDE->getOffset();
704 
705     // Add the address if we failed to write it.
706     if (PCToFDE.count(FuncAddress) == 0) {
707       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: old FDE for function at 0x"
708                         << Twine::utohexstr(FuncAddress) << " is at 0x"
709                         << Twine::utohexstr(FDEAddress) << '\n');
710       PCToFDE[FuncAddress] = FDEAddress;
711     }
712   };
713 
714   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: old .eh_frame contains "
715                     << std::distance(OldEHFrame.entries().begin(),
716                                      OldEHFrame.entries().end())
717                     << " entries\n");
718 
719   // Generate a new .eh_frame_hdr based on the new map.
720 
721   // Header plus table of entries of size 8 bytes.
722   std::vector<char> EHFrameHeader(12 + PCToFDE.size() * 8);
723 
724   // Version is 1.
725   EHFrameHeader[0] = 1;
726   // Encoding of the eh_frame pointer.
727   EHFrameHeader[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
728   // Encoding of the count field to follow.
729   EHFrameHeader[2] = DW_EH_PE_udata4;
730   // Encoding of the table entries - 4-byte offset from the start of the header.
731   EHFrameHeader[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
732 
733   // Address of eh_frame. Use the new one.
734   support::ulittle32_t::ref(EHFrameHeader.data() + 4) =
735       NewEHFrame.getEHFrameAddress() - (EHFrameHeaderAddress + 4);
736 
737   // Number of entries in the table (FDE count).
738   support::ulittle32_t::ref(EHFrameHeader.data() + 8) = PCToFDE.size();
739 
740   // Write the table at offset 12.
741   char *Ptr = EHFrameHeader.data();
742   uint32_t Offset = 12;
743   for (const auto &PCI : PCToFDE) {
744     int64_t InitialPCOffset = PCI.first - EHFrameHeaderAddress;
745     assert(isInt<32>(InitialPCOffset) && "PC offset out of bounds");
746     support::ulittle32_t::ref(Ptr + Offset) = InitialPCOffset;
747     Offset += 4;
748     int64_t FDEOffset = PCI.second - EHFrameHeaderAddress;
749     assert(isInt<32>(FDEOffset) && "FDE offset out of bounds");
750     support::ulittle32_t::ref(Ptr + Offset) = FDEOffset;
751     Offset += 4;
752   }
753 
754   return EHFrameHeader;
755 }
756 
757 Error EHFrameParser::parseCIE(uint64_t StartOffset) {
758   uint8_t Version = Data.getU8(&Offset);
759   const char *Augmentation = Data.getCStr(&Offset);
760   StringRef AugmentationString(Augmentation ? Augmentation : "");
761   uint8_t AddressSize =
762       Version < 4 ? Data.getAddressSize() : Data.getU8(&Offset);
763   Data.setAddressSize(AddressSize);
764   // Skip segment descriptor size
765   if (Version >= 4)
766     Offset += 1;
767   // Skip code alignment factor
768   Data.getULEB128(&Offset);
769   // Skip data alignment
770   Data.getSLEB128(&Offset);
771   // Skip return address register
772   if (Version == 1) {
773     Offset += 1;
774   } else {
775     Data.getULEB128(&Offset);
776   }
777 
778   uint32_t FDEPointerEncoding = DW_EH_PE_absptr;
779   uint32_t LSDAPointerEncoding = DW_EH_PE_omit;
780   // Walk the augmentation string to get all the augmentation data.
781   for (unsigned i = 0, e = AugmentationString.size(); i != e; ++i) {
782     switch (AugmentationString[i]) {
783     default:
784       return createStringError(
785           errc::invalid_argument,
786           "unknown augmentation character in entry at 0x%" PRIx64, StartOffset);
787     case 'L':
788       LSDAPointerEncoding = Data.getU8(&Offset);
789       break;
790     case 'P': {
791       uint32_t PersonalityEncoding = Data.getU8(&Offset);
792       Optional<uint64_t> Personality =
793           Data.getEncodedPointer(&Offset, PersonalityEncoding,
794                                  EHFrameAddress ? EHFrameAddress + Offset : 0);
795       // Patch personality address
796       if (Personality)
797         PatcherCallback(*Personality, Offset, PersonalityEncoding);
798       break;
799     }
800     case 'R':
801       FDEPointerEncoding = Data.getU8(&Offset);
802       break;
803     case 'z':
804       if (i)
805         return createStringError(
806             errc::invalid_argument,
807             "'z' must be the first character at 0x%" PRIx64, StartOffset);
808       // Skip augmentation length
809       Data.getULEB128(&Offset);
810       break;
811     case 'S':
812     case 'B':
813       break;
814     }
815   }
816   Entries.emplace_back(std::make_unique<CIEInfo>(
817       FDEPointerEncoding, LSDAPointerEncoding, AugmentationString));
818   CIEs[StartOffset] = &*Entries.back();
819   return Error::success();
820 }
821 
822 Error EHFrameParser::parseFDE(uint64_t CIEPointer,
823                               uint64_t StartStructureOffset) {
824   Optional<uint64_t> LSDAAddress;
825   CIEInfo *Cie = CIEs[StartStructureOffset - CIEPointer];
826 
827   // The address size is encoded in the CIE we reference.
828   if (!Cie)
829     return createStringError(errc::invalid_argument,
830                              "parsing FDE data at 0x%" PRIx64
831                              " failed due to missing CIE",
832                              StartStructureOffset);
833   // Patch initial location
834   if (auto Val = Data.getEncodedPointer(&Offset, Cie->FDEPtrEncoding,
835                                         EHFrameAddress + Offset)) {
836     PatcherCallback(*Val, Offset, Cie->FDEPtrEncoding);
837   }
838   // Skip address range
839   Data.getEncodedPointer(&Offset, Cie->FDEPtrEncoding, 0);
840 
841   // Process augmentation data for this FDE.
842   StringRef AugmentationString = Cie->AugmentationString;
843   if (!AugmentationString.empty() && Cie->LSDAPtrEncoding != DW_EH_PE_omit) {
844     // Skip augmentation length
845     Data.getULEB128(&Offset);
846     LSDAAddress =
847         Data.getEncodedPointer(&Offset, Cie->LSDAPtrEncoding,
848                                EHFrameAddress ? Offset + EHFrameAddress : 0);
849     // Patch LSDA address
850     PatcherCallback(*LSDAAddress, Offset, Cie->LSDAPtrEncoding);
851   }
852   return Error::success();
853 }
854 
855 Error EHFrameParser::parse() {
856   while (Data.isValidOffset(Offset)) {
857     const uint64_t StartOffset = Offset;
858 
859     uint64_t Length;
860     DwarfFormat Format;
861     std::tie(Length, Format) = Data.getInitialLength(&Offset);
862 
863     // If the Length is 0, then this CIE is a terminator
864     if (Length == 0)
865       break;
866 
867     const uint64_t StartStructureOffset = Offset;
868     const uint64_t EndStructureOffset = Offset + Length;
869 
870     Error Err = Error::success();
871     const uint64_t Id = Data.getRelocatedValue(4, &Offset,
872                                                /*SectionIndex=*/nullptr, &Err);
873     if (Err)
874       return Err;
875 
876     if (!Id) {
877       if (Error Err = parseCIE(StartOffset))
878         return Err;
879     } else {
880       if (Error Err = parseFDE(Id, StartStructureOffset))
881         return Err;
882     }
883     Offset = EndStructureOffset;
884   }
885 
886   return Error::success();
887 }
888 
889 Error EHFrameParser::parse(DWARFDataExtractor Data, uint64_t EHFrameAddress,
890                            PatcherCallbackTy PatcherCallback) {
891   EHFrameParser Parser(Data, EHFrameAddress, PatcherCallback);
892   return Parser.parse();
893 }
894 
895 } // namespace bolt
896 } // namespace llvm
897