xref: /llvm-project/bolt/lib/Core/Exceptions.cpp (revision 07f63b0ac5c530c808420971734b36b8fa79e687)
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 (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   size_t TTypeEncodingSize = 0;
125   uintptr_t TTypeEnd = 0;
126   if (TTypeEncoding != DW_EH_PE_omit) {
127     TTypeEnd = Data.getULEB128(&Offset);
128     TTypeEncodingSize = BC.getDWARFEncodingSize(TTypeEncoding);
129   }
130 
131   if (opts::PrintExceptions) {
132     outs() << "[LSDA at 0x" << Twine::utohexstr(getLSDAAddress())
133            << " for function " << *this << "]:\n";
134     outs() << "LPStart Encoding = 0x" << Twine::utohexstr(LPStartEncoding)
135            << '\n';
136     outs() << "LPStart = 0x" << Twine::utohexstr(LPStart) << '\n';
137     outs() << "TType Encoding = 0x" << Twine::utohexstr(TTypeEncoding) << '\n';
138     outs() << "TType End = " << TTypeEnd << '\n';
139   }
140 
141   // Table to store list of indices in type table. Entries are uleb128 values.
142   const uint64_t TypeIndexTableStart = Offset + TTypeEnd;
143 
144   // Offset past the last decoded index.
145   uint64_t MaxTypeIndexTableOffset = 0;
146 
147   // Max positive index used in type table.
148   unsigned MaxTypeIndex = 0;
149 
150   // The actual type info table starts at the same location, but grows in
151   // opposite direction. TTypeEncoding is used to encode stored values.
152   const uint64_t TypeTableStart = Offset + TTypeEnd;
153 
154   uint8_t CallSiteEncoding = Data.getU8(&Offset);
155   uint32_t CallSiteTableLength = Data.getULEB128(&Offset);
156   uint64_t CallSiteTableStart = Offset;
157   uint64_t CallSiteTableEnd = CallSiteTableStart + CallSiteTableLength;
158   uint64_t CallSitePtr = CallSiteTableStart;
159   uint64_t ActionTableStart = CallSiteTableEnd;
160 
161   if (opts::PrintExceptions) {
162     outs() << "CallSite Encoding = " << (unsigned)CallSiteEncoding << '\n';
163     outs() << "CallSite table length = " << CallSiteTableLength << '\n';
164     outs() << '\n';
165   }
166 
167   this->HasEHRanges = CallSitePtr < CallSiteTableEnd;
168   const uint64_t RangeBase = getAddress();
169   while (CallSitePtr < CallSiteTableEnd) {
170     uint64_t Start = *Data.getEncodedPointer(&CallSitePtr, CallSiteEncoding,
171                                              CallSitePtr + LSDASectionAddress);
172     uint64_t Length = *Data.getEncodedPointer(&CallSitePtr, CallSiteEncoding,
173                                               CallSitePtr + LSDASectionAddress);
174     uint64_t LandingPad = *Data.getEncodedPointer(
175         &CallSitePtr, CallSiteEncoding, CallSitePtr + LSDASectionAddress);
176     uint64_t ActionEntry = Data.getULEB128(&CallSitePtr);
177 
178     uint64_t LPOffset = LPStart + LandingPad;
179     uint64_t LPAddress = Address + LPOffset;
180 
181     // Verify if landing pad code is located outside current function
182     // Support landing pad to builtin_unreachable
183     if (LPAddress < Address || LPAddress > Address + getSize()) {
184       BinaryFunction *Fragment =
185           BC.getBinaryFunctionContainingAddress(LPAddress);
186       assert(Fragment != nullptr &&
187              "BOLT-ERROR: cannot find landing pad fragment");
188       BC.addInterproceduralReference(this, Fragment->getAddress());
189       BC.processInterproceduralReferences();
190       auto isFragmentOf = [](BinaryFunction *Fragment,
191                              BinaryFunction *Parent) -> bool {
192         return (Fragment->isFragment() && Fragment->isParentFragment(Parent));
193       };
194       (void)isFragmentOf;
195       assert((isFragmentOf(this, Fragment) || isFragmentOf(Fragment, this)) &&
196              "BOLT-ERROR: cannot have landing pads in different "
197              "functions");
198       setHasIndirectTargetToSplitFragment(true);
199       BC.addFragmentsToSkip(this);
200       return;
201     }
202 
203     if (opts::PrintExceptions) {
204       outs() << "Call Site: [0x" << Twine::utohexstr(RangeBase + Start)
205              << ", 0x" << Twine::utohexstr(RangeBase + Start + Length)
206              << "); landing pad: 0x" << Twine::utohexstr(LPOffset)
207              << "; action entry: 0x" << Twine::utohexstr(ActionEntry) << "\n";
208       outs() << "  current offset is " << (CallSitePtr - CallSiteTableStart)
209              << '\n';
210     }
211 
212     // Create a handler entry if necessary.
213     MCSymbol *LPSymbol = nullptr;
214     if (LPOffset) {
215       if (!getInstructionAtOffset(LPOffset)) {
216         if (opts::Verbosity >= 1)
217           errs() << "BOLT-WARNING: landing pad " << Twine::utohexstr(LPOffset)
218                  << " not pointing to an instruction in function " << *this
219                  << " - ignoring.\n";
220       } else {
221         auto Label = Labels.find(LPOffset);
222         if (Label != Labels.end()) {
223           LPSymbol = Label->second;
224         } else {
225           LPSymbol = BC.Ctx->createNamedTempSymbol("LP");
226           Labels[LPOffset] = LPSymbol;
227         }
228       }
229     }
230 
231     // Mark all call instructions in the range.
232     auto II = Instructions.find(Start);
233     auto IE = Instructions.end();
234     assert(II != IE && "exception range not pointing to an instruction");
235     do {
236       MCInst &Instruction = II->second;
237       if (BC.MIB->isCall(Instruction) &&
238           !BC.MIB->getConditionalTailCall(Instruction)) {
239         assert(!BC.MIB->isInvoke(Instruction) &&
240                "overlapping exception ranges detected");
241         // Add extra operands to a call instruction making it an invoke from
242         // now on.
243         BC.MIB->addEHInfo(Instruction,
244                           MCPlus::MCLandingPad(LPSymbol, ActionEntry));
245       }
246       ++II;
247     } while (II != IE && II->first < Start + Length);
248 
249     if (ActionEntry != 0) {
250       auto printType = [&](int Index, raw_ostream &OS) {
251         assert(Index > 0 && "only positive indices are valid");
252         uint64_t TTEntry = TypeTableStart - Index * TTypeEncodingSize;
253         const uint64_t TTEntryAddress = TTEntry + LSDASectionAddress;
254         uint64_t TypeAddress =
255             *Data.getEncodedPointer(&TTEntry, TTypeEncoding, TTEntryAddress);
256         if ((TTypeEncoding & DW_EH_PE_pcrel) && TypeAddress == TTEntryAddress)
257           TypeAddress = 0;
258         if (TypeAddress == 0) {
259           OS << "<all>";
260           return;
261         }
262         if (TTypeEncoding & DW_EH_PE_indirect) {
263           ErrorOr<uint64_t> PointerOrErr = BC.getPointerAtAddress(TypeAddress);
264           assert(PointerOrErr && "failed to decode indirect address");
265           TypeAddress = *PointerOrErr;
266         }
267         if (BinaryData *TypeSymBD = BC.getBinaryDataAtAddress(TypeAddress))
268           OS << TypeSymBD->getName();
269         else
270           OS << "0x" << Twine::utohexstr(TypeAddress);
271       };
272       if (opts::PrintExceptions)
273         outs() << "    actions: ";
274       uint64_t ActionPtr = ActionTableStart + ActionEntry - 1;
275       int64_t ActionType;
276       int64_t ActionNext;
277       const char *Sep = "";
278       do {
279         ActionType = Data.getSLEB128(&ActionPtr);
280         const uint32_t Self = ActionPtr;
281         ActionNext = Data.getSLEB128(&ActionPtr);
282         if (opts::PrintExceptions)
283           outs() << Sep << "(" << ActionType << ", " << ActionNext << ") ";
284         if (ActionType == 0) {
285           if (opts::PrintExceptions)
286             outs() << "cleanup";
287         } else if (ActionType > 0) {
288           // It's an index into a type table.
289           MaxTypeIndex =
290               std::max(MaxTypeIndex, static_cast<unsigned>(ActionType));
291           if (opts::PrintExceptions) {
292             outs() << "catch type ";
293             printType(ActionType, outs());
294           }
295         } else { // ActionType < 0
296           if (opts::PrintExceptions)
297             outs() << "filter exception types ";
298           const char *TSep = "";
299           // ActionType is a negative *byte* offset into *uleb128-encoded* table
300           // of indices with base 1.
301           // E.g. -1 means offset 0, -2 is offset 1, etc. The indices are
302           // encoded using uleb128 thus we cannot directly dereference them.
303           uint64_t TypeIndexTablePtr = TypeIndexTableStart - ActionType - 1;
304           while (uint64_t Index = Data.getULEB128(&TypeIndexTablePtr)) {
305             MaxTypeIndex = std::max(MaxTypeIndex, static_cast<unsigned>(Index));
306             if (opts::PrintExceptions) {
307               outs() << TSep;
308               printType(Index, outs());
309               TSep = ", ";
310             }
311           }
312           MaxTypeIndexTableOffset = std::max(
313               MaxTypeIndexTableOffset, TypeIndexTablePtr - TypeIndexTableStart);
314         }
315 
316         Sep = "; ";
317 
318         ActionPtr = Self + ActionNext;
319       } while (ActionNext);
320       if (opts::PrintExceptions)
321         outs() << '\n';
322     }
323   }
324   if (opts::PrintExceptions)
325     outs() << '\n';
326 
327   assert(TypeIndexTableStart + MaxTypeIndexTableOffset <=
328              Data.getData().size() &&
329          "LSDA entry has crossed section boundary");
330 
331   if (TTypeEnd) {
332     LSDAActionTable = LSDASectionData.slice(
333         ActionTableStart, TypeIndexTableStart -
334                               MaxTypeIndex * TTypeEncodingSize -
335                               ActionTableStart);
336     for (unsigned Index = 1; Index <= MaxTypeIndex; ++Index) {
337       uint64_t TTEntry = TypeTableStart - Index * TTypeEncodingSize;
338       const uint64_t TTEntryAddress = TTEntry + LSDASectionAddress;
339       uint64_t TypeAddress =
340           *Data.getEncodedPointer(&TTEntry, TTypeEncoding, TTEntryAddress);
341       if ((TTypeEncoding & DW_EH_PE_pcrel) && (TypeAddress == TTEntryAddress))
342         TypeAddress = 0;
343       if (TTypeEncoding & DW_EH_PE_indirect) {
344         LSDATypeAddressTable.emplace_back(TypeAddress);
345         if (TypeAddress) {
346           ErrorOr<uint64_t> PointerOrErr = BC.getPointerAtAddress(TypeAddress);
347           assert(PointerOrErr && "failed to decode indirect address");
348           TypeAddress = *PointerOrErr;
349         }
350       }
351       LSDATypeTable.emplace_back(TypeAddress);
352     }
353     LSDATypeIndexTable =
354         LSDASectionData.slice(TypeIndexTableStart, MaxTypeIndexTableOffset);
355   }
356 }
357 
358 void BinaryFunction::updateEHRanges() {
359   if (getSize() == 0)
360     return;
361 
362   assert(CurrentState == State::CFG_Finalized && "unexpected state");
363 
364   // Build call sites table.
365   struct EHInfo {
366     const MCSymbol *LP; // landing pad
367     uint64_t Action;
368   };
369 
370   for (FunctionFragment &FF : getLayout().fragments()) {
371     // Sites to update - either regular or cold.
372     CallSitesType &Sites = FF.isMainFragment() ? CallSites : ColdCallSites;
373 
374     // If previous call can throw, this is its exception handler.
375     EHInfo PreviousEH = {nullptr, 0};
376 
377     // Marker for the beginning of exceptions range.
378     const MCSymbol *StartRange = nullptr;
379 
380     for (BinaryBasicBlock *const BB : FF) {
381       for (auto II = BB->begin(); II != BB->end(); ++II) {
382         if (!BC.MIB->isCall(*II))
383           continue;
384 
385         // Instruction can throw an exception that should be handled.
386         const bool Throws = BC.MIB->isInvoke(*II);
387 
388         // Ignore the call if it's a continuation of a no-throw gap.
389         if (!Throws && !StartRange)
390           continue;
391 
392         assert(getLayout().isHotColdSplit() &&
393                "Exceptions only supported for hot/cold splitting");
394 
395         // Extract exception handling information from the instruction.
396         const MCSymbol *LP = nullptr;
397         uint64_t Action = 0;
398         if (const Optional<MCPlus::MCLandingPad> EHInfo =
399                 BC.MIB->getEHInfo(*II))
400           std::tie(LP, Action) = *EHInfo;
401 
402         // No action if the exception handler has not changed.
403         if (Throws && StartRange && PreviousEH.LP == LP &&
404             PreviousEH.Action == Action)
405           continue;
406 
407         // Same symbol is used for the beginning and the end of the range.
408         const MCSymbol *EHSymbol;
409         MCInst EHLabel;
410         {
411           std::unique_lock<std::shared_timed_mutex> Lock(BC.CtxMutex);
412           EHSymbol = BC.Ctx->createNamedTempSymbol("EH");
413           BC.MIB->createEHLabel(EHLabel, EHSymbol, BC.Ctx.get());
414         }
415 
416         II = std::next(BB->insertPseudoInstr(II, EHLabel));
417 
418         // At this point we could be in one of the following states:
419         //
420         // I. Exception handler has changed and we need to close previous range
421         //    and start a new one.
422         //
423         // II. Start a new exception range after the gap.
424         //
425         // III. Close current exception range and start a new gap.
426         const MCSymbol *EndRange;
427         if (StartRange) {
428           // I, III:
429           EndRange = EHSymbol;
430         } else {
431           // II:
432           StartRange = EHSymbol;
433           EndRange = nullptr;
434         }
435 
436         // Close the previous range.
437         if (EndRange) {
438           Sites.emplace_back(
439               CallSite{StartRange, EndRange, PreviousEH.LP, PreviousEH.Action});
440         }
441 
442         if (Throws) {
443           // I, II:
444           StartRange = EHSymbol;
445           PreviousEH = EHInfo{LP, Action};
446         } else {
447           StartRange = nullptr;
448         }
449       }
450     }
451 
452     // Check if we need to close the range.
453     if (StartRange) {
454       assert((FF.isMainFragment() || &Sites == &ColdCallSites) &&
455              "sites mismatch");
456       const MCSymbol *EndRange = getFunctionEndLabel(FF.getFragmentNum());
457       Sites.emplace_back(
458           CallSite{StartRange, EndRange, PreviousEH.LP, PreviousEH.Action});
459     }
460   }
461 }
462 
463 const uint8_t DWARF_CFI_PRIMARY_OPCODE_MASK = 0xc0;
464 
465 CFIReaderWriter::CFIReaderWriter(const DWARFDebugFrame &EHFrame) {
466   // Prepare FDEs for fast lookup
467   for (const dwarf::FrameEntry &Entry : EHFrame.entries()) {
468     const auto *CurFDE = dyn_cast<dwarf::FDE>(&Entry);
469     // Skip CIEs.
470     if (!CurFDE)
471       continue;
472     // There could me multiple FDEs with the same initial address, and perhaps
473     // different sizes (address ranges). Use the first entry with non-zero size.
474     auto FDEI = FDEs.lower_bound(CurFDE->getInitialLocation());
475     if (FDEI != FDEs.end() && FDEI->first == CurFDE->getInitialLocation()) {
476       if (CurFDE->getAddressRange()) {
477         if (FDEI->second->getAddressRange() == 0) {
478           FDEI->second = CurFDE;
479         } else if (opts::Verbosity > 0) {
480           errs() << "BOLT-WARNING: different FDEs for function at 0x"
481                  << Twine::utohexstr(FDEI->first)
482                  << " detected; sizes: " << FDEI->second->getAddressRange()
483                  << " and " << CurFDE->getAddressRange() << '\n';
484         }
485       }
486     } else {
487       FDEs.emplace_hint(FDEI, CurFDE->getInitialLocation(), CurFDE);
488     }
489   }
490 }
491 
492 bool CFIReaderWriter::fillCFIInfoFor(BinaryFunction &Function) const {
493   uint64_t Address = Function.getAddress();
494   auto I = FDEs.find(Address);
495   // Ignore zero-length FDE ranges.
496   if (I == FDEs.end() || !I->second->getAddressRange())
497     return true;
498 
499   const FDE &CurFDE = *I->second;
500   Optional<uint64_t> LSDA = CurFDE.getLSDAAddress();
501   Function.setLSDAAddress(LSDA ? *LSDA : 0);
502 
503   uint64_t Offset = Function.getFirstInstructionOffset();
504   uint64_t CodeAlignment = CurFDE.getLinkedCIE()->getCodeAlignmentFactor();
505   uint64_t DataAlignment = CurFDE.getLinkedCIE()->getDataAlignmentFactor();
506   if (CurFDE.getLinkedCIE()->getPersonalityAddress()) {
507     Function.setPersonalityFunction(
508         *CurFDE.getLinkedCIE()->getPersonalityAddress());
509     Function.setPersonalityEncoding(
510         *CurFDE.getLinkedCIE()->getPersonalityEncoding());
511   }
512 
513   auto decodeFrameInstruction = [&Function, &Offset, Address, CodeAlignment,
514                                  DataAlignment](
515                                     const CFIProgram::Instruction &Instr) {
516     uint8_t Opcode = Instr.Opcode;
517     if (Opcode & DWARF_CFI_PRIMARY_OPCODE_MASK)
518       Opcode &= DWARF_CFI_PRIMARY_OPCODE_MASK;
519     switch (Instr.Opcode) {
520     case DW_CFA_nop:
521       break;
522     case DW_CFA_advance_loc4:
523     case DW_CFA_advance_loc2:
524     case DW_CFA_advance_loc1:
525     case DW_CFA_advance_loc:
526       // Advance our current address
527       Offset += CodeAlignment * int64_t(Instr.Ops[0]);
528       break;
529     case DW_CFA_offset_extended_sf:
530       Function.addCFIInstruction(
531           Offset,
532           MCCFIInstruction::createOffset(
533               nullptr, Instr.Ops[0], DataAlignment * int64_t(Instr.Ops[1])));
534       break;
535     case DW_CFA_offset_extended:
536     case DW_CFA_offset:
537       Function.addCFIInstruction(
538           Offset, MCCFIInstruction::createOffset(nullptr, Instr.Ops[0],
539                                                  DataAlignment * Instr.Ops[1]));
540       break;
541     case DW_CFA_restore_extended:
542     case DW_CFA_restore:
543       Function.addCFIInstruction(
544           Offset, MCCFIInstruction::createRestore(nullptr, Instr.Ops[0]));
545       break;
546     case DW_CFA_set_loc:
547       assert(Instr.Ops[0] >= Address && "set_loc out of function bounds");
548       assert(Instr.Ops[0] <= Address + Function.getSize() &&
549              "set_loc out of function bounds");
550       Offset = Instr.Ops[0] - Address;
551       break;
552 
553     case DW_CFA_undefined:
554       Function.addCFIInstruction(
555           Offset, MCCFIInstruction::createUndefined(nullptr, Instr.Ops[0]));
556       break;
557     case DW_CFA_same_value:
558       Function.addCFIInstruction(
559           Offset, MCCFIInstruction::createSameValue(nullptr, Instr.Ops[0]));
560       break;
561     case DW_CFA_register:
562       Function.addCFIInstruction(
563           Offset, MCCFIInstruction::createRegister(nullptr, Instr.Ops[0],
564                                                    Instr.Ops[1]));
565       break;
566     case DW_CFA_remember_state:
567       Function.addCFIInstruction(
568           Offset, MCCFIInstruction::createRememberState(nullptr));
569       break;
570     case DW_CFA_restore_state:
571       Function.addCFIInstruction(Offset,
572                                  MCCFIInstruction::createRestoreState(nullptr));
573       break;
574     case DW_CFA_def_cfa:
575       Function.addCFIInstruction(
576           Offset,
577           MCCFIInstruction::cfiDefCfa(nullptr, Instr.Ops[0], Instr.Ops[1]));
578       break;
579     case DW_CFA_def_cfa_sf:
580       Function.addCFIInstruction(
581           Offset,
582           MCCFIInstruction::cfiDefCfa(nullptr, Instr.Ops[0],
583                                       DataAlignment * int64_t(Instr.Ops[1])));
584       break;
585     case DW_CFA_def_cfa_register:
586       Function.addCFIInstruction(Offset, MCCFIInstruction::createDefCfaRegister(
587                                              nullptr, Instr.Ops[0]));
588       break;
589     case DW_CFA_def_cfa_offset:
590       Function.addCFIInstruction(
591           Offset, MCCFIInstruction::cfiDefCfaOffset(nullptr, Instr.Ops[0]));
592       break;
593     case DW_CFA_def_cfa_offset_sf:
594       Function.addCFIInstruction(
595           Offset, MCCFIInstruction::cfiDefCfaOffset(
596                       nullptr, DataAlignment * int64_t(Instr.Ops[0])));
597       break;
598     case DW_CFA_GNU_args_size:
599       Function.addCFIInstruction(
600           Offset, MCCFIInstruction::createGnuArgsSize(nullptr, Instr.Ops[0]));
601       Function.setUsesGnuArgsSize();
602       break;
603     case DW_CFA_val_offset_sf:
604     case DW_CFA_val_offset:
605       if (opts::Verbosity >= 1) {
606         errs() << "BOLT-WARNING: DWARF val_offset() unimplemented\n";
607       }
608       return false;
609     case DW_CFA_def_cfa_expression:
610     case DW_CFA_val_expression:
611     case DW_CFA_expression: {
612       StringRef ExprBytes = Instr.Expression->getData();
613       std::string Str;
614       raw_string_ostream OS(Str);
615       // Manually encode this instruction using CFI escape
616       OS << Opcode;
617       if (Opcode != DW_CFA_def_cfa_expression)
618         encodeULEB128(Instr.Ops[0], OS);
619       encodeULEB128(ExprBytes.size(), OS);
620       OS << ExprBytes;
621       Function.addCFIInstruction(
622           Offset, MCCFIInstruction::createEscape(nullptr, OS.str()));
623       break;
624     }
625     case DW_CFA_MIPS_advance_loc8:
626       if (opts::Verbosity >= 1)
627         errs() << "BOLT-WARNING: DW_CFA_MIPS_advance_loc unimplemented\n";
628       return false;
629     case DW_CFA_GNU_window_save:
630     case DW_CFA_lo_user:
631     case DW_CFA_hi_user:
632       if (opts::Verbosity >= 1) {
633         errs() << "BOLT-WARNING: DW_CFA_GNU_* and DW_CFA_*_user "
634                   "unimplemented\n";
635       }
636       return false;
637     default:
638       if (opts::Verbosity >= 1) {
639         errs() << "BOLT-WARNING: Unrecognized CFI instruction: " << Instr.Opcode
640                << '\n';
641       }
642       return false;
643     }
644 
645     return true;
646   };
647 
648   for (const CFIProgram::Instruction &Instr : CurFDE.getLinkedCIE()->cfis())
649     if (!decodeFrameInstruction(Instr))
650       return false;
651 
652   for (const CFIProgram::Instruction &Instr : CurFDE.cfis())
653     if (!decodeFrameInstruction(Instr))
654       return false;
655 
656   return true;
657 }
658 
659 std::vector<char> CFIReaderWriter::generateEHFrameHeader(
660     const DWARFDebugFrame &OldEHFrame, const DWARFDebugFrame &NewEHFrame,
661     uint64_t EHFrameHeaderAddress,
662     std::vector<uint64_t> &FailedAddresses) const {
663   // Common PC -> FDE map to be written into .eh_frame_hdr.
664   std::map<uint64_t, uint64_t> PCToFDE;
665 
666   // Presort array for binary search.
667   llvm::sort(FailedAddresses);
668 
669   // Initialize PCToFDE using NewEHFrame.
670   for (dwarf::FrameEntry &Entry : NewEHFrame.entries()) {
671     const dwarf::FDE *FDE = dyn_cast<dwarf::FDE>(&Entry);
672     if (FDE == nullptr)
673       continue;
674     const uint64_t FuncAddress = FDE->getInitialLocation();
675     const uint64_t FDEAddress =
676         NewEHFrame.getEHFrameAddress() + FDE->getOffset();
677 
678     // Ignore unused FDEs.
679     if (FuncAddress == 0)
680       continue;
681 
682     // Add the address to the map unless we failed to write it.
683     if (!std::binary_search(FailedAddresses.begin(), FailedAddresses.end(),
684                             FuncAddress)) {
685       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: FDE for function at 0x"
686                         << Twine::utohexstr(FuncAddress) << " is at 0x"
687                         << Twine::utohexstr(FDEAddress) << '\n');
688       PCToFDE[FuncAddress] = FDEAddress;
689     }
690   };
691 
692   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: new .eh_frame contains "
693                     << llvm::size(NewEHFrame.entries()) << " 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                     << llvm::size(OldEHFrame.entries()) << " entries\n");
716 
717   // Generate a new .eh_frame_hdr based on the new map.
718 
719   // Header plus table of entries of size 8 bytes.
720   std::vector<char> EHFrameHeader(12 + PCToFDE.size() * 8);
721 
722   // Version is 1.
723   EHFrameHeader[0] = 1;
724   // Encoding of the eh_frame pointer.
725   EHFrameHeader[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
726   // Encoding of the count field to follow.
727   EHFrameHeader[2] = DW_EH_PE_udata4;
728   // Encoding of the table entries - 4-byte offset from the start of the header.
729   EHFrameHeader[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
730 
731   // Address of eh_frame. Use the new one.
732   support::ulittle32_t::ref(EHFrameHeader.data() + 4) =
733       NewEHFrame.getEHFrameAddress() - (EHFrameHeaderAddress + 4);
734 
735   // Number of entries in the table (FDE count).
736   support::ulittle32_t::ref(EHFrameHeader.data() + 8) = PCToFDE.size();
737 
738   // Write the table at offset 12.
739   char *Ptr = EHFrameHeader.data();
740   uint32_t Offset = 12;
741   for (const auto &PCI : PCToFDE) {
742     int64_t InitialPCOffset = PCI.first - EHFrameHeaderAddress;
743     assert(isInt<32>(InitialPCOffset) && "PC offset out of bounds");
744     support::ulittle32_t::ref(Ptr + Offset) = InitialPCOffset;
745     Offset += 4;
746     int64_t FDEOffset = PCI.second - EHFrameHeaderAddress;
747     assert(isInt<32>(FDEOffset) && "FDE offset out of bounds");
748     support::ulittle32_t::ref(Ptr + Offset) = FDEOffset;
749     Offset += 4;
750   }
751 
752   return EHFrameHeader;
753 }
754 
755 Error EHFrameParser::parseCIE(uint64_t StartOffset) {
756   uint8_t Version = Data.getU8(&Offset);
757   const char *Augmentation = Data.getCStr(&Offset);
758   StringRef AugmentationString(Augmentation ? Augmentation : "");
759   uint8_t AddressSize =
760       Version < 4 ? Data.getAddressSize() : Data.getU8(&Offset);
761   Data.setAddressSize(AddressSize);
762   // Skip segment descriptor size
763   if (Version >= 4)
764     Offset += 1;
765   // Skip code alignment factor
766   Data.getULEB128(&Offset);
767   // Skip data alignment
768   Data.getSLEB128(&Offset);
769   // Skip return address register
770   if (Version == 1)
771     Offset += 1;
772   else
773     Data.getULEB128(&Offset);
774 
775   uint32_t FDEPointerEncoding = DW_EH_PE_absptr;
776   uint32_t LSDAPointerEncoding = DW_EH_PE_omit;
777   // Walk the augmentation string to get all the augmentation data.
778   for (unsigned i = 0, e = AugmentationString.size(); i != e; ++i) {
779     switch (AugmentationString[i]) {
780     default:
781       return createStringError(
782           errc::invalid_argument,
783           "unknown augmentation character in entry at 0x%" PRIx64, StartOffset);
784     case 'L':
785       LSDAPointerEncoding = Data.getU8(&Offset);
786       break;
787     case 'P': {
788       uint32_t PersonalityEncoding = Data.getU8(&Offset);
789       Optional<uint64_t> Personality =
790           Data.getEncodedPointer(&Offset, PersonalityEncoding,
791                                  EHFrameAddress ? EHFrameAddress + Offset : 0);
792       // Patch personality address
793       if (Personality)
794         PatcherCallback(*Personality, Offset, PersonalityEncoding);
795       break;
796     }
797     case 'R':
798       FDEPointerEncoding = Data.getU8(&Offset);
799       break;
800     case 'z':
801       if (i)
802         return createStringError(
803             errc::invalid_argument,
804             "'z' must be the first character at 0x%" PRIx64, StartOffset);
805       // Skip augmentation length
806       Data.getULEB128(&Offset);
807       break;
808     case 'S':
809     case 'B':
810       break;
811     }
812   }
813   Entries.emplace_back(std::make_unique<CIEInfo>(
814       FDEPointerEncoding, LSDAPointerEncoding, AugmentationString));
815   CIEs[StartOffset] = &*Entries.back();
816   return Error::success();
817 }
818 
819 Error EHFrameParser::parseFDE(uint64_t CIEPointer,
820                               uint64_t StartStructureOffset) {
821   Optional<uint64_t> LSDAAddress;
822   CIEInfo *Cie = CIEs[StartStructureOffset - CIEPointer];
823 
824   // The address size is encoded in the CIE we reference.
825   if (!Cie)
826     return createStringError(errc::invalid_argument,
827                              "parsing FDE data at 0x%" PRIx64
828                              " failed due to missing CIE",
829                              StartStructureOffset);
830   // Patch initial location
831   if (auto Val = Data.getEncodedPointer(&Offset, Cie->FDEPtrEncoding,
832                                         EHFrameAddress + Offset)) {
833     PatcherCallback(*Val, Offset, Cie->FDEPtrEncoding);
834   }
835   // Skip address range
836   Data.getEncodedPointer(&Offset, Cie->FDEPtrEncoding, 0);
837 
838   // Process augmentation data for this FDE.
839   StringRef AugmentationString = Cie->AugmentationString;
840   if (!AugmentationString.empty() && Cie->LSDAPtrEncoding != DW_EH_PE_omit) {
841     // Skip augmentation length
842     Data.getULEB128(&Offset);
843     LSDAAddress =
844         Data.getEncodedPointer(&Offset, Cie->LSDAPtrEncoding,
845                                EHFrameAddress ? Offset + EHFrameAddress : 0);
846     // Patch LSDA address
847     PatcherCallback(*LSDAAddress, Offset, Cie->LSDAPtrEncoding);
848   }
849   return Error::success();
850 }
851 
852 Error EHFrameParser::parse() {
853   while (Data.isValidOffset(Offset)) {
854     const uint64_t StartOffset = Offset;
855 
856     uint64_t Length;
857     DwarfFormat Format;
858     std::tie(Length, Format) = Data.getInitialLength(&Offset);
859 
860     // If the Length is 0, then this CIE is a terminator
861     if (Length == 0)
862       break;
863 
864     const uint64_t StartStructureOffset = Offset;
865     const uint64_t EndStructureOffset = Offset + Length;
866 
867     Error Err = Error::success();
868     const uint64_t Id = Data.getRelocatedValue(4, &Offset,
869                                                /*SectionIndex=*/nullptr, &Err);
870     if (Err)
871       return Err;
872 
873     if (!Id) {
874       if (Error Err = parseCIE(StartOffset))
875         return Err;
876     } else {
877       if (Error Err = parseFDE(Id, StartStructureOffset))
878         return Err;
879     }
880     Offset = EndStructureOffset;
881   }
882 
883   return Error::success();
884 }
885 
886 Error EHFrameParser::parse(DWARFDataExtractor Data, uint64_t EHFrameAddress,
887                            PatcherCallbackTy PatcherCallback) {
888   EHFrameParser Parser(Data, EHFrameAddress, PatcherCallback);
889   return Parser.parse();
890 }
891 
892 } // namespace bolt
893 } // namespace llvm
894