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