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