1 //===- bolt/Core/Exceptions.cpp - Helpers for 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 // This file implements functions for handling C++ exception meta data.
10 //
11 // Some of the code is taken from examples/ExceptionDemo
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "bolt/Core/Exceptions.h"
16 #include "bolt/Core/BinaryFunction.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/BinaryFormat/Dwarf.h"
20 #include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
21 #include "llvm/Support/Casting.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/LEB128.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <map>
28 
29 #undef  DEBUG_TYPE
30 #define DEBUG_TYPE "bolt-exceptions"
31 
32 using namespace llvm::dwarf;
33 
34 namespace opts {
35 
36 extern llvm::cl::OptionCategory BoltCategory;
37 
38 extern llvm::cl::opt<unsigned> Verbosity;
39 
40 static llvm::cl::opt<bool>
41 PrintExceptions("print-exceptions",
42   llvm::cl::desc("print exception handling data"),
43   llvm::cl::ZeroOrMore,
44   llvm::cl::Hidden,
45   llvm::cl::cat(BoltCategory));
46 
47 } // namespace opts
48 
49 namespace llvm {
50 namespace bolt {
51 
52 // Read and dump the .gcc_exception_table section entry.
53 //
54 // .gcc_except_table section contains a set of Language-Specific Data Areas -
55 // a fancy name for exception handling tables. There's one  LSDA entry per
56 // function. However, we can't actually tell which function LSDA refers to
57 // unless we parse .eh_frame entry that refers to the LSDA.
58 // Then inside LSDA most addresses are encoded relative to the function start,
59 // so we need the function context in order to get to real addresses.
60 //
61 // The best visual representation of the tables comprising LSDA and
62 // relationships between them is illustrated at:
63 //   https://github.com/itanium-cxx-abi/cxx-abi/blob/master/exceptions.pdf
64 // Keep in mind that GCC implementation deviates slightly from that document.
65 //
66 // To summarize, there are 4 tables in LSDA: call site table, actions table,
67 // types table, and types index table (for indirection). The main table contains
68 // call site entries. Each call site includes a PC range that can throw an
69 // exception, a handler (landing pad), and a reference to an entry in the action
70 // table. The handler and/or action could be 0. The action entry is a head
71 // of a list of actions associated with a call site. The action table contains
72 // all such lists (it could be optimized to share list tails). Each action could
73 // be either to catch an exception of a given type, to perform a cleanup, or to
74 // propagate the exception after filtering it out (e.g. to make sure function
75 // exception specification is not violated). Catch action contains a reference
76 // to an entry in the type table, and filter action refers to an entry in the
77 // type index table to encode a set of types to filter.
78 //
79 // Call site table follows LSDA header. Action table immediately follows the
80 // call site table.
81 //
82 // Both types table and type index table start at the same location, but they
83 // grow in opposite directions (types go up, indices go down). The beginning of
84 // these tables is encoded in LSDA header. Sizes for both of the tables are not
85 // included anywhere.
86 //
87 // We have to parse all of the tables to determine their sizes. Then we have
88 // to parse the call site table and associate discovered information with
89 // actual call instructions and landing pad blocks.
90 //
91 // For the purpose of rewriting exception handling tables, we can reuse action,
92 // and type index tables in their original binary format.
93 //
94 // Type table could be encoded using position-independent references, and thus
95 // may require relocation.
96 //
97 // Ideally we should be able to re-write LSDA in-place, without the need to
98 // allocate a new space for it. Sadly there's no guarantee that the new call
99 // site table will be the same size as GCC uses uleb encodings for PC offsets.
100 //
101 // Note: some functions have LSDA entries with 0 call site entries.
102 void BinaryFunction::parseLSDA(ArrayRef<uint8_t> LSDASectionData,
103                                uint64_t LSDASectionAddress) {
104   assert(CurrentState == State::Disassembled && "unexpected function state");
105 
106   if (!getLSDAAddress())
107     return;
108 
109   DWARFDataExtractor Data(
110       StringRef(reinterpret_cast<const char *>(LSDASectionData.data()),
111                 LSDASectionData.size()),
112       BC.DwCtx->getDWARFObj().isLittleEndian(), 8);
113   uint64_t Offset = getLSDAAddress() - LSDASectionAddress;
114   assert(Data.isValidOffset(Offset) && "wrong LSDA address");
115 
116   uint8_t LPStartEncoding = Data.getU8(&Offset);
117   uint64_t LPStart = 0;
118   if (Optional<uint64_t> MaybeLPStart = Data.getEncodedPointer(
119           &Offset, LPStartEncoding, Offset + LSDASectionAddress))
120     LPStart = *MaybeLPStart;
121 
122   assert(LPStart == 0 && "support for split functions not implemented");
123 
124   const uint8_t TTypeEncoding = Data.getU8(&Offset);
125   size_t TTypeEncodingSize = 0;
126   uintptr_t TTypeEnd = 0;
127   if (TTypeEncoding != DW_EH_PE_omit) {
128     TTypeEnd = Data.getULEB128(&Offset);
129     TTypeEncodingSize = BC.getDWARFEncodingSize(TTypeEncoding);
130   }
131 
132   if (opts::PrintExceptions) {
133     outs() << "[LSDA at 0x" << Twine::utohexstr(getLSDAAddress())
134            << " for function " << *this << "]:\n";
135     outs() << "LPStart Encoding = 0x" << Twine::utohexstr(LPStartEncoding)
136            << '\n';
137     outs() << "LPStart = 0x" << Twine::utohexstr(LPStart) << '\n';
138     outs() << "TType Encoding = 0x" << Twine::utohexstr(TTypeEncoding) << '\n';
139     outs() << "TType End = " << TTypeEnd << '\n';
140   }
141 
142   // Table to store list of indices in type table. Entries are uleb128 values.
143   const uint64_t TypeIndexTableStart = Offset + TTypeEnd;
144 
145   // Offset past the last decoded index.
146   uint64_t MaxTypeIndexTableOffset = 0;
147 
148   // Max positive index used in type table.
149   unsigned MaxTypeIndex = 0;
150 
151   // The actual type info table starts at the same location, but grows in
152   // opposite direction. TTypeEncoding is used to encode stored values.
153   const uint64_t TypeTableStart = Offset + TTypeEnd;
154 
155   uint8_t CallSiteEncoding = Data.getU8(&Offset);
156   uint32_t CallSiteTableLength = Data.getULEB128(&Offset);
157   uint64_t CallSiteTableStart = Offset;
158   uint64_t CallSiteTableEnd = CallSiteTableStart + CallSiteTableLength;
159   uint64_t CallSitePtr = CallSiteTableStart;
160   uint64_t ActionTableStart = CallSiteTableEnd;
161 
162   if (opts::PrintExceptions) {
163     outs() << "CallSite Encoding = " << (unsigned)CallSiteEncoding << '\n';
164     outs() << "CallSite table length = " << CallSiteTableLength << '\n';
165     outs() << '\n';
166   }
167 
168   this->HasEHRanges = CallSitePtr < CallSiteTableEnd;
169   const uint64_t RangeBase = getAddress();
170   while (CallSitePtr < CallSiteTableEnd) {
171     uint64_t Start = *Data.getEncodedPointer(&CallSitePtr, CallSiteEncoding,
172                                              CallSitePtr + LSDASectionAddress);
173     uint64_t Length = *Data.getEncodedPointer(&CallSitePtr, CallSiteEncoding,
174                                               CallSitePtr + LSDASectionAddress);
175     uint64_t LandingPad = *Data.getEncodedPointer(
176         &CallSitePtr, CallSiteEncoding, CallSitePtr + LSDASectionAddress);
177     uint64_t ActionEntry = Data.getULEB128(&CallSitePtr);
178 
179     if (opts::PrintExceptions) {
180       outs() << "Call Site: [0x" << Twine::utohexstr(RangeBase + Start)
181              << ", 0x" << Twine::utohexstr(RangeBase + Start + Length)
182              << "); landing pad: 0x" << Twine::utohexstr(LPStart + LandingPad)
183              << "; action entry: 0x" << Twine::utohexstr(ActionEntry) << "\n";
184       outs() << "  current offset is " << (CallSitePtr - CallSiteTableStart)
185              << '\n';
186     }
187 
188     // Create a handler entry if necessary.
189     MCSymbol *LPSymbol = nullptr;
190     if (LandingPad) {
191       if (!getInstructionAtOffset(LandingPad)) {
192         if (opts::Verbosity >= 1)
193           errs() << "BOLT-WARNING: landing pad " << Twine::utohexstr(LandingPad)
194                  << " not pointing to an instruction in function " << *this
195                  << " - ignoring.\n";
196       } else {
197         auto Label = Labels.find(LandingPad);
198         if (Label != Labels.end()) {
199           LPSymbol = Label->second;
200         } else {
201           LPSymbol = BC.Ctx->createNamedTempSymbol("LP");
202           Labels[LandingPad] = LPSymbol;
203         }
204       }
205     }
206 
207     // Mark all call instructions in the range.
208     auto II = Instructions.find(Start);
209     auto IE = Instructions.end();
210     assert(II != IE && "exception range not pointing to an instruction");
211     do {
212       MCInst &Instruction = II->second;
213       if (BC.MIB->isCall(Instruction) &&
214           !BC.MIB->getConditionalTailCall(Instruction)) {
215         assert(!BC.MIB->isInvoke(Instruction) &&
216                "overlapping exception ranges detected");
217         // Add extra operands to a call instruction making it an invoke from
218         // now on.
219         BC.MIB->addEHInfo(Instruction,
220                           MCPlus::MCLandingPad(LPSymbol, ActionEntry));
221       }
222       ++II;
223     } while (II != IE && II->first < Start + Length);
224 
225     if (ActionEntry != 0) {
226       auto printType = [&](int Index, raw_ostream &OS) {
227         assert(Index > 0 && "only positive indices are valid");
228         uint64_t TTEntry = TypeTableStart - Index * TTypeEncodingSize;
229         const uint64_t TTEntryAddress = TTEntry + LSDASectionAddress;
230         uint64_t TypeAddress =
231             *Data.getEncodedPointer(&TTEntry, TTypeEncoding, TTEntryAddress);
232         if ((TTypeEncoding & DW_EH_PE_pcrel) && TypeAddress == TTEntryAddress)
233           TypeAddress = 0;
234         if (TypeAddress == 0) {
235           OS << "<all>";
236           return;
237         }
238         if (TTypeEncoding & DW_EH_PE_indirect) {
239           ErrorOr<uint64_t> PointerOrErr = BC.getPointerAtAddress(TypeAddress);
240           assert(PointerOrErr && "failed to decode indirect address");
241           TypeAddress = *PointerOrErr;
242         }
243         if (BinaryData *TypeSymBD = BC.getBinaryDataAtAddress(TypeAddress))
244           OS << TypeSymBD->getName();
245         else
246           OS << "0x" << Twine::utohexstr(TypeAddress);
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       encodeULEB128(ExprBytes.size(), OS);
614       OS << ExprBytes;
615       Function.addCFIInstruction(
616           Offset, MCCFIInstruction::createEscape(nullptr, OS.str()));
617       break;
618     }
619     case DW_CFA_MIPS_advance_loc8:
620       if (opts::Verbosity >= 1)
621         errs() << "BOLT-WARNING: DW_CFA_MIPS_advance_loc unimplemented\n";
622       return false;
623     case DW_CFA_GNU_window_save:
624     case DW_CFA_lo_user:
625     case DW_CFA_hi_user:
626       if (opts::Verbosity >= 1) {
627         errs() << "BOLT-WARNING: DW_CFA_GNU_* and DW_CFA_*_user "
628                   "unimplemented\n";
629       }
630       return false;
631     default:
632       if (opts::Verbosity >= 1) {
633         errs() << "BOLT-WARNING: Unrecognized CFI instruction: " << Instr.Opcode
634                << '\n';
635       }
636       return false;
637     }
638 
639     return true;
640   };
641 
642   for (const CFIProgram::Instruction &Instr : CurFDE.getLinkedCIE()->cfis())
643     if (!decodeFrameInstruction(Instr))
644       return false;
645 
646   for (const CFIProgram::Instruction &Instr : CurFDE.cfis())
647     if (!decodeFrameInstruction(Instr))
648       return false;
649 
650   return true;
651 }
652 
653 std::vector<char> CFIReaderWriter::generateEHFrameHeader(
654     const DWARFDebugFrame &OldEHFrame, const DWARFDebugFrame &NewEHFrame,
655     uint64_t EHFrameHeaderAddress,
656     std::vector<uint64_t> &FailedAddresses) const {
657   // Common PC -> FDE map to be written into .eh_frame_hdr.
658   std::map<uint64_t, uint64_t> PCToFDE;
659 
660   // Presort array for binary search.
661   std::sort(FailedAddresses.begin(), FailedAddresses.end());
662 
663   // Initialize PCToFDE using NewEHFrame.
664   for (dwarf::FrameEntry &Entry : NewEHFrame.entries()) {
665     const dwarf::FDE *FDE = dyn_cast<dwarf::FDE>(&Entry);
666     if (FDE == nullptr)
667       continue;
668     const uint64_t FuncAddress = FDE->getInitialLocation();
669     const uint64_t FDEAddress =
670         NewEHFrame.getEHFrameAddress() + FDE->getOffset();
671 
672     // Ignore unused FDEs.
673     if (FuncAddress == 0)
674       continue;
675 
676     // Add the address to the map unless we failed to write it.
677     if (!std::binary_search(FailedAddresses.begin(), FailedAddresses.end(),
678                             FuncAddress)) {
679       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: FDE for function at 0x"
680                         << Twine::utohexstr(FuncAddress) << " is at 0x"
681                         << Twine::utohexstr(FDEAddress) << '\n');
682       PCToFDE[FuncAddress] = FDEAddress;
683     }
684   };
685 
686   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: new .eh_frame contains "
687                     << std::distance(NewEHFrame.entries().begin(),
688                                      NewEHFrame.entries().end())
689                     << " entries\n");
690 
691   // Add entries from the original .eh_frame corresponding to the functions
692   // that we did not update.
693   for (const dwarf::FrameEntry &Entry : OldEHFrame) {
694     const dwarf::FDE *FDE = dyn_cast<dwarf::FDE>(&Entry);
695     if (FDE == nullptr)
696       continue;
697     const uint64_t FuncAddress = FDE->getInitialLocation();
698     const uint64_t FDEAddress =
699         OldEHFrame.getEHFrameAddress() + FDE->getOffset();
700 
701     // Add the address if we failed to write it.
702     if (PCToFDE.count(FuncAddress) == 0) {
703       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: old FDE for function at 0x"
704                         << Twine::utohexstr(FuncAddress) << " is at 0x"
705                         << Twine::utohexstr(FDEAddress) << '\n');
706       PCToFDE[FuncAddress] = FDEAddress;
707     }
708   };
709 
710   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: old .eh_frame contains "
711                     << std::distance(OldEHFrame.entries().begin(),
712                                      OldEHFrame.entries().end())
713                     << " entries\n");
714 
715   // Generate a new .eh_frame_hdr based on the new map.
716 
717   // Header plus table of entries of size 8 bytes.
718   std::vector<char> EHFrameHeader(12 + PCToFDE.size() * 8);
719 
720   // Version is 1.
721   EHFrameHeader[0] = 1;
722   // Encoding of the eh_frame pointer.
723   EHFrameHeader[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
724   // Encoding of the count field to follow.
725   EHFrameHeader[2] = DW_EH_PE_udata4;
726   // Encoding of the table entries - 4-byte offset from the start of the header.
727   EHFrameHeader[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
728 
729   // Address of eh_frame. Use the new one.
730   support::ulittle32_t::ref(EHFrameHeader.data() + 4) =
731       NewEHFrame.getEHFrameAddress() - (EHFrameHeaderAddress + 4);
732 
733   // Number of entries in the table (FDE count).
734   support::ulittle32_t::ref(EHFrameHeader.data() + 8) = PCToFDE.size();
735 
736   // Write the table at offset 12.
737   char *Ptr = EHFrameHeader.data();
738   uint32_t Offset = 12;
739   for (const auto &PCI : PCToFDE) {
740     int64_t InitialPCOffset = PCI.first - EHFrameHeaderAddress;
741     assert(isInt<32>(InitialPCOffset) && "PC offset out of bounds");
742     support::ulittle32_t::ref(Ptr + Offset) = InitialPCOffset;
743     Offset += 4;
744     int64_t FDEOffset = PCI.second - EHFrameHeaderAddress;
745     assert(isInt<32>(FDEOffset) && "FDE offset out of bounds");
746     support::ulittle32_t::ref(Ptr + Offset) = FDEOffset;
747     Offset += 4;
748   }
749 
750   return EHFrameHeader;
751 }
752 
753 Error EHFrameParser::parseCIE(uint64_t StartOffset) {
754   uint8_t Version = Data.getU8(&Offset);
755   const char *Augmentation = Data.getCStr(&Offset);
756   StringRef AugmentationString(Augmentation ? Augmentation : "");
757   uint8_t AddressSize =
758       Version < 4 ? Data.getAddressSize() : Data.getU8(&Offset);
759   Data.setAddressSize(AddressSize);
760   // Skip segment descriptor size
761   if (Version >= 4)
762     Offset += 1;
763   // Skip code alignment factor
764   Data.getULEB128(&Offset);
765   // Skip data alignment
766   Data.getSLEB128(&Offset);
767   // Skip return address register
768   if (Version == 1)
769     Offset += 1;
770   else
771     Data.getULEB128(&Offset);
772 
773   uint32_t FDEPointerEncoding = DW_EH_PE_absptr;
774   uint32_t LSDAPointerEncoding = DW_EH_PE_omit;
775   // Walk the augmentation string to get all the augmentation data.
776   for (unsigned i = 0, e = AugmentationString.size(); i != e; ++i) {
777     switch (AugmentationString[i]) {
778     default:
779       return createStringError(
780           errc::invalid_argument,
781           "unknown augmentation character in entry at 0x%" PRIx64, StartOffset);
782     case 'L':
783       LSDAPointerEncoding = Data.getU8(&Offset);
784       break;
785     case 'P': {
786       uint32_t PersonalityEncoding = Data.getU8(&Offset);
787       Optional<uint64_t> Personality =
788           Data.getEncodedPointer(&Offset, PersonalityEncoding,
789                                  EHFrameAddress ? EHFrameAddress + Offset : 0);
790       // Patch personality address
791       if (Personality)
792         PatcherCallback(*Personality, Offset, PersonalityEncoding);
793       break;
794     }
795     case 'R':
796       FDEPointerEncoding = Data.getU8(&Offset);
797       break;
798     case 'z':
799       if (i)
800         return createStringError(
801             errc::invalid_argument,
802             "'z' must be the first character at 0x%" PRIx64, StartOffset);
803       // Skip augmentation length
804       Data.getULEB128(&Offset);
805       break;
806     case 'S':
807     case 'B':
808       break;
809     }
810   }
811   Entries.emplace_back(std::make_unique<CIEInfo>(
812       FDEPointerEncoding, LSDAPointerEncoding, AugmentationString));
813   CIEs[StartOffset] = &*Entries.back();
814   return Error::success();
815 }
816 
817 Error EHFrameParser::parseFDE(uint64_t CIEPointer,
818                               uint64_t StartStructureOffset) {
819   Optional<uint64_t> LSDAAddress;
820   CIEInfo *Cie = CIEs[StartStructureOffset - CIEPointer];
821 
822   // The address size is encoded in the CIE we reference.
823   if (!Cie)
824     return createStringError(errc::invalid_argument,
825                              "parsing FDE data at 0x%" PRIx64
826                              " failed due to missing CIE",
827                              StartStructureOffset);
828   // Patch initial location
829   if (auto Val = Data.getEncodedPointer(&Offset, Cie->FDEPtrEncoding,
830                                         EHFrameAddress + Offset)) {
831     PatcherCallback(*Val, Offset, Cie->FDEPtrEncoding);
832   }
833   // Skip address range
834   Data.getEncodedPointer(&Offset, Cie->FDEPtrEncoding, 0);
835 
836   // Process augmentation data for this FDE.
837   StringRef AugmentationString = Cie->AugmentationString;
838   if (!AugmentationString.empty() && Cie->LSDAPtrEncoding != DW_EH_PE_omit) {
839     // Skip augmentation length
840     Data.getULEB128(&Offset);
841     LSDAAddress =
842         Data.getEncodedPointer(&Offset, Cie->LSDAPtrEncoding,
843                                EHFrameAddress ? Offset + EHFrameAddress : 0);
844     // Patch LSDA address
845     PatcherCallback(*LSDAAddress, Offset, Cie->LSDAPtrEncoding);
846   }
847   return Error::success();
848 }
849 
850 Error EHFrameParser::parse() {
851   while (Data.isValidOffset(Offset)) {
852     const uint64_t StartOffset = Offset;
853 
854     uint64_t Length;
855     DwarfFormat Format;
856     std::tie(Length, Format) = Data.getInitialLength(&Offset);
857 
858     // If the Length is 0, then this CIE is a terminator
859     if (Length == 0)
860       break;
861 
862     const uint64_t StartStructureOffset = Offset;
863     const uint64_t EndStructureOffset = Offset + Length;
864 
865     Error Err = Error::success();
866     const uint64_t Id = Data.getRelocatedValue(4, &Offset,
867                                                /*SectionIndex=*/nullptr, &Err);
868     if (Err)
869       return Err;
870 
871     if (!Id) {
872       if (Error Err = parseCIE(StartOffset))
873         return Err;
874     } else {
875       if (Error Err = parseFDE(Id, StartStructureOffset))
876         return Err;
877     }
878     Offset = EndStructureOffset;
879   }
880 
881   return Error::success();
882 }
883 
884 Error EHFrameParser::parse(DWARFDataExtractor Data, uint64_t EHFrameAddress,
885                            PatcherCallbackTy PatcherCallback) {
886   EHFrameParser Parser(Data, EHFrameAddress, PatcherCallback);
887   return Parser.parse();
888 }
889 
890 } // namespace bolt
891 } // namespace llvm
892