1 //===-------- JITLink_EHFrameSupport.cpp - JITLink eh-frame utils ---------===//
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 #include "EHFrameSupportImpl.h"
10 
11 #include "llvm/BinaryFormat/Dwarf.h"
12 #include "llvm/Config/config.h"
13 #include "llvm/ExecutionEngine/JITLink/DWARFRecordSectionSplitter.h"
14 #include "llvm/ExecutionEngine/Orc/TargetProcess/RegisterEHFrames.h"
15 #include "llvm/Support/DynamicLibrary.h"
16 
17 #define DEBUG_TYPE "jitlink"
18 
19 namespace llvm {
20 namespace jitlink {
21 
22 EHFrameEdgeFixer::EHFrameEdgeFixer(StringRef EHFrameSectionName,
23                                    unsigned PointerSize, Edge::Kind Pointer32,
24                                    Edge::Kind Pointer64, Edge::Kind Delta32,
25                                    Edge::Kind Delta64, Edge::Kind NegDelta32)
26     : EHFrameSectionName(EHFrameSectionName), PointerSize(PointerSize),
27       Pointer32(Pointer32), Pointer64(Pointer64), Delta32(Delta32),
28       Delta64(Delta64), NegDelta32(NegDelta32) {}
29 
30 Error EHFrameEdgeFixer::operator()(LinkGraph &G) {
31   auto *EHFrame = G.findSectionByName(EHFrameSectionName);
32 
33   if (!EHFrame) {
34     LLVM_DEBUG({
35       dbgs() << "EHFrameEdgeFixer: No " << EHFrameSectionName
36              << " section. Nothing to do\n";
37     });
38     return Error::success();
39   }
40 
41   // Check that we support the graph's pointer size.
42   if (G.getPointerSize() != 4 && G.getPointerSize() != 8)
43     return make_error<JITLinkError>(
44         "EHFrameEdgeFixer only supports 32 and 64 bit targets");
45 
46   LLVM_DEBUG({
47     dbgs() << "EHFrameEdgeFixer: Processing " << EHFrameSectionName << "...\n";
48   });
49 
50   ParseContext PC(G);
51 
52   // Build a map of all blocks and symbols in the text sections. We will use
53   // these for finding / building edge targets when processing FDEs.
54   for (auto &Sec : G.sections()) {
55     // Just record the most-canonical symbol (for eh-frame purposes) at each
56     // address.
57     for (auto *Sym : Sec.symbols()) {
58       auto &CurSym = PC.AddrToSym[Sym->getAddress()];
59       if (!CurSym || (std::make_tuple(Sym->getLinkage(), Sym->getScope(),
60                                       !Sym->hasName(), Sym->getName()) <
61                       std::make_tuple(CurSym->getLinkage(), CurSym->getScope(),
62                                       !CurSym->hasName(), CurSym->getName())))
63         CurSym = Sym;
64     }
65     if (auto Err = PC.AddrToBlock.addBlocks(Sec.blocks(),
66                                             BlockAddressMap::includeNonNull))
67       return Err;
68   }
69 
70   // Sort eh-frame blocks into address order to ensure we visit CIEs before
71   // their child FDEs.
72   std::vector<Block *> EHFrameBlocks;
73   for (auto *B : EHFrame->blocks())
74     EHFrameBlocks.push_back(B);
75   llvm::sort(EHFrameBlocks, [](const Block *LHS, const Block *RHS) {
76     return LHS->getAddress() < RHS->getAddress();
77   });
78 
79   // Loop over the blocks in address order.
80   for (auto *B : EHFrameBlocks)
81     if (auto Err = processBlock(PC, *B))
82       return Err;
83 
84   return Error::success();
85 }
86 
87 Error EHFrameEdgeFixer::processBlock(ParseContext &PC, Block &B) {
88 
89   LLVM_DEBUG(dbgs() << "  Processing block at " << B.getAddress() << "\n");
90 
91   // eh-frame should not contain zero-fill blocks.
92   if (B.isZeroFill())
93     return make_error<JITLinkError>("Unexpected zero-fill block in " +
94                                     EHFrameSectionName + " section");
95 
96   if (B.getSize() == 0) {
97     LLVM_DEBUG(dbgs() << "    Block is empty. Skipping.\n");
98     return Error::success();
99   }
100 
101   // Find the offsets of any existing edges from this block.
102   BlockEdgeMap BlockEdges;
103   for (auto &E : B.edges())
104     if (E.isRelocation()) {
105       if (BlockEdges.count(E.getOffset()))
106         return make_error<JITLinkError>(
107             "Multiple relocations at offset " +
108             formatv("{0:x16}", E.getOffset()) + " in " + EHFrameSectionName +
109             " block at address " + formatv("{0:x16}", B.getAddress()));
110 
111       BlockEdges[E.getOffset()] = EdgeTarget(E);
112     }
113 
114   CIEInfosMap CIEInfos;
115   BinaryStreamReader BlockReader(
116       StringRef(B.getContent().data(), B.getContent().size()),
117       PC.G.getEndianness());
118   while (!BlockReader.empty()) {
119     size_t RecordStartOffset = BlockReader.getOffset();
120 
121     LLVM_DEBUG({
122       dbgs() << "    Processing CFI record at "
123              << (B.getAddress() + RecordStartOffset) << "\n";
124     });
125 
126     // Get the record length.
127     size_t RecordRemaining;
128     {
129       uint32_t Length;
130       if (auto Err = BlockReader.readInteger(Length))
131         return Err;
132       // If Length < 0xffffffff then use the regular length field, otherwise
133       // read the extended length field.
134       if (Length != 0xffffffff)
135         RecordRemaining = Length;
136       else {
137         uint64_t ExtendedLength;
138         if (auto Err = BlockReader.readInteger(ExtendedLength))
139           return Err;
140         RecordRemaining = ExtendedLength;
141       }
142     }
143 
144     if (BlockReader.bytesRemaining() < RecordRemaining)
145       return make_error<JITLinkError>(
146           "Incomplete CFI record at " +
147           formatv("{0:x16}", B.getAddress() + RecordStartOffset));
148 
149     // Read the CIE delta for this record.
150     uint64_t CIEDeltaFieldOffset = BlockReader.getOffset() - RecordStartOffset;
151     uint32_t CIEDelta;
152     if (auto Err = BlockReader.readInteger(CIEDelta))
153       return Err;
154 
155     if (CIEDelta == 0) {
156       if (auto Err = processCIE(PC, B, RecordStartOffset,
157                                 CIEDeltaFieldOffset + RecordRemaining,
158                                 CIEDeltaFieldOffset, BlockEdges))
159         return Err;
160     } else {
161       if (auto Err = processFDE(PC, B, RecordStartOffset,
162                                 CIEDeltaFieldOffset + RecordRemaining,
163                                 CIEDeltaFieldOffset, CIEDelta, BlockEdges))
164         return Err;
165     }
166 
167     // Move to the next record.
168     BlockReader.setOffset(RecordStartOffset + CIEDeltaFieldOffset +
169                           RecordRemaining);
170   }
171 
172   return Error::success();
173 }
174 
175 Error EHFrameEdgeFixer::processCIE(ParseContext &PC, Block &B,
176                                    size_t RecordOffset, size_t RecordLength,
177                                    size_t CIEDeltaFieldOffset,
178                                    const BlockEdgeMap &BlockEdges) {
179 
180   LLVM_DEBUG(dbgs() << "      Record is CIE\n");
181 
182   auto RecordContent = B.getContent().slice(RecordOffset, RecordLength);
183   BinaryStreamReader RecordReader(
184       StringRef(RecordContent.data(), RecordContent.size()),
185       PC.G.getEndianness());
186 
187   // Skip past the CIE delta field: we've already processed this far.
188   RecordReader.setOffset(CIEDeltaFieldOffset + 4);
189 
190   auto &CIESymbol =
191       PC.G.addAnonymousSymbol(B, RecordOffset, RecordLength, false, false);
192   CIEInformation CIEInfo(CIESymbol);
193 
194   uint8_t Version = 0;
195   if (auto Err = RecordReader.readInteger(Version))
196     return Err;
197 
198   if (Version != 0x01)
199     return make_error<JITLinkError>("Bad CIE version " + Twine(Version) +
200                                     " (should be 0x01) in eh-frame");
201 
202   auto AugInfo = parseAugmentationString(RecordReader);
203   if (!AugInfo)
204     return AugInfo.takeError();
205 
206   // Skip the EH Data field if present.
207   if (AugInfo->EHDataFieldPresent)
208     if (auto Err = RecordReader.skip(PC.G.getPointerSize()))
209       return Err;
210 
211   // Read and validate the code alignment factor.
212   {
213     uint64_t CodeAlignmentFactor = 0;
214     if (auto Err = RecordReader.readULEB128(CodeAlignmentFactor))
215       return Err;
216   }
217 
218   // Read and validate the data alignment factor.
219   {
220     int64_t DataAlignmentFactor = 0;
221     if (auto Err = RecordReader.readSLEB128(DataAlignmentFactor))
222       return Err;
223   }
224 
225   // Skip the return address register field.
226   if (auto Err = RecordReader.skip(1))
227     return Err;
228 
229   if (AugInfo->AugmentationDataPresent) {
230 
231     CIEInfo.AugmentationDataPresent = true;
232 
233     uint64_t AugmentationDataLength = 0;
234     if (auto Err = RecordReader.readULEB128(AugmentationDataLength))
235       return Err;
236 
237     uint32_t AugmentationDataStartOffset = RecordReader.getOffset();
238 
239     uint8_t *NextField = &AugInfo->Fields[0];
240     while (uint8_t Field = *NextField++) {
241       switch (Field) {
242       case 'L':
243         CIEInfo.LSDAPresent = true;
244         if (auto PE = readPointerEncoding(RecordReader, B, "LSDA"))
245           CIEInfo.LSDAEncoding = *PE;
246         else
247           return PE.takeError();
248         break;
249       case 'P': {
250         auto PersonalityPointerEncoding =
251             readPointerEncoding(RecordReader, B, "personality");
252         if (!PersonalityPointerEncoding)
253           return PersonalityPointerEncoding.takeError();
254         if (auto Err =
255                 getOrCreateEncodedPointerEdge(
256                     PC, BlockEdges, *PersonalityPointerEncoding, RecordReader,
257                     B, RecordOffset + RecordReader.getOffset(), "personality")
258                     .takeError())
259           return Err;
260         break;
261       }
262       case 'R':
263         if (auto PE = readPointerEncoding(RecordReader, B, "address")) {
264           CIEInfo.AddressEncoding = *PE;
265           if (CIEInfo.AddressEncoding == dwarf::DW_EH_PE_omit)
266             return make_error<JITLinkError>(
267                 "Invalid address encoding DW_EH_PE_omit in CIE at " +
268                 formatv("{0:x}", (B.getAddress() + RecordOffset).getValue()));
269         } else
270           return PE.takeError();
271         break;
272       default:
273         llvm_unreachable("Invalid augmentation string field");
274       }
275     }
276 
277     if (RecordReader.getOffset() - AugmentationDataStartOffset >
278         AugmentationDataLength)
279       return make_error<JITLinkError>("Read past the end of the augmentation "
280                                       "data while parsing fields");
281   }
282 
283   assert(!PC.CIEInfos.count(CIESymbol.getAddress()) &&
284          "Multiple CIEs recorded at the same address?");
285   PC.CIEInfos[CIESymbol.getAddress()] = std::move(CIEInfo);
286 
287   return Error::success();
288 }
289 
290 Error EHFrameEdgeFixer::processFDE(ParseContext &PC, Block &B,
291                                    size_t RecordOffset, size_t RecordLength,
292                                    size_t CIEDeltaFieldOffset,
293                                    uint32_t CIEDelta,
294                                    const BlockEdgeMap &BlockEdges) {
295   LLVM_DEBUG(dbgs() << "      Record is FDE\n");
296 
297   orc::ExecutorAddr RecordAddress = B.getAddress() + RecordOffset;
298 
299   auto RecordContent = B.getContent().slice(RecordOffset, RecordLength);
300   BinaryStreamReader RecordReader(
301       StringRef(RecordContent.data(), RecordContent.size()),
302       PC.G.getEndianness());
303 
304   // Skip past the CIE delta field: we've already read this far.
305   RecordReader.setOffset(CIEDeltaFieldOffset + 4);
306 
307   auto &FDESymbol =
308       PC.G.addAnonymousSymbol(B, RecordOffset, RecordLength, false, false);
309 
310   CIEInformation *CIEInfo = nullptr;
311 
312   {
313     // Process the CIE pointer field.
314     auto CIEEdgeItr = BlockEdges.find(RecordOffset + CIEDeltaFieldOffset);
315     orc::ExecutorAddr CIEAddress =
316         RecordAddress + orc::ExecutorAddrDiff(CIEDeltaFieldOffset) -
317         orc::ExecutorAddrDiff(CIEDelta);
318     if (CIEEdgeItr == BlockEdges.end()) {
319 
320       LLVM_DEBUG({
321         dbgs() << "        Adding edge at "
322                << (RecordAddress + CIEDeltaFieldOffset)
323                << " to CIE at: " << CIEAddress << "\n";
324       });
325       if (auto CIEInfoOrErr = PC.findCIEInfo(CIEAddress))
326         CIEInfo = *CIEInfoOrErr;
327       else
328         return CIEInfoOrErr.takeError();
329       assert(CIEInfo->CIESymbol && "CIEInfo has no CIE symbol set");
330       B.addEdge(NegDelta32, RecordOffset + CIEDeltaFieldOffset,
331                 *CIEInfo->CIESymbol, 0);
332     } else {
333       LLVM_DEBUG({
334         dbgs() << "        Already has edge at "
335                << (RecordAddress + CIEDeltaFieldOffset) << " to CIE at "
336                << CIEAddress << "\n";
337       });
338       auto &EI = CIEEdgeItr->second;
339       if (EI.Addend)
340         return make_error<JITLinkError>(
341             "CIE edge at " +
342             formatv("{0:x16}", RecordAddress + CIEDeltaFieldOffset) +
343             " has non-zero addend");
344       if (auto CIEInfoOrErr = PC.findCIEInfo(EI.Target->getAddress()))
345         CIEInfo = *CIEInfoOrErr;
346       else
347         return CIEInfoOrErr.takeError();
348     }
349   }
350 
351   // Process the PC-Begin field.
352   LLVM_DEBUG({
353     dbgs() << "        Processing PC-begin at "
354            << (RecordAddress + RecordReader.getOffset()) << "\n";
355   });
356   if (auto PCBegin = getOrCreateEncodedPointerEdge(
357           PC, BlockEdges, CIEInfo->AddressEncoding, RecordReader, B,
358           RecordReader.getOffset(), "PC begin")) {
359     assert(*PCBegin && "PC-begin symbol not set");
360     // Add a keep-alive edge from the FDE target to the FDE to ensure that the
361     // FDE is kept alive if its target is.
362     LLVM_DEBUG({
363       dbgs() << "        Adding keep-alive edge from target at "
364              << (*PCBegin)->getBlock().getAddress() << " to FDE at "
365              << RecordAddress << "\n";
366     });
367     (*PCBegin)->getBlock().addEdge(Edge::KeepAlive, 0, FDESymbol, 0);
368   } else
369     return PCBegin.takeError();
370 
371   // Skip over the PC range size field.
372   if (auto Err = skipEncodedPointer(CIEInfo->AddressEncoding, RecordReader))
373     return Err;
374 
375   if (CIEInfo->AugmentationDataPresent) {
376     uint64_t AugmentationDataSize;
377     if (auto Err = RecordReader.readULEB128(AugmentationDataSize))
378       return Err;
379 
380     if (CIEInfo->LSDAPresent)
381       if (auto Err = getOrCreateEncodedPointerEdge(
382                          PC, BlockEdges, CIEInfo->LSDAEncoding, RecordReader, B,
383                          RecordReader.getOffset(), "LSDA")
384                          .takeError())
385         return Err;
386   } else {
387     LLVM_DEBUG(dbgs() << "        Record does not have LSDA field.\n");
388   }
389 
390   return Error::success();
391 }
392 
393 Expected<EHFrameEdgeFixer::AugmentationInfo>
394 EHFrameEdgeFixer::parseAugmentationString(BinaryStreamReader &RecordReader) {
395   AugmentationInfo AugInfo;
396   uint8_t NextChar;
397   uint8_t *NextField = &AugInfo.Fields[0];
398 
399   if (auto Err = RecordReader.readInteger(NextChar))
400     return std::move(Err);
401 
402   while (NextChar != 0) {
403     switch (NextChar) {
404     case 'z':
405       AugInfo.AugmentationDataPresent = true;
406       break;
407     case 'e':
408       if (auto Err = RecordReader.readInteger(NextChar))
409         return std::move(Err);
410       if (NextChar != 'h')
411         return make_error<JITLinkError>("Unrecognized substring e" +
412                                         Twine(NextChar) +
413                                         " in augmentation string");
414       AugInfo.EHDataFieldPresent = true;
415       break;
416     case 'L':
417     case 'P':
418     case 'R':
419       *NextField++ = NextChar;
420       break;
421     default:
422       return make_error<JITLinkError>("Unrecognized character " +
423                                       Twine(NextChar) +
424                                       " in augmentation string");
425     }
426 
427     if (auto Err = RecordReader.readInteger(NextChar))
428       return std::move(Err);
429   }
430 
431   return std::move(AugInfo);
432 }
433 
434 Expected<uint8_t> EHFrameEdgeFixer::readPointerEncoding(BinaryStreamReader &R,
435                                                         Block &InBlock,
436                                                         const char *FieldName) {
437   using namespace dwarf;
438 
439   uint8_t PointerEncoding;
440   if (auto Err = R.readInteger(PointerEncoding))
441     return std::move(Err);
442 
443   bool Supported = true;
444   switch (PointerEncoding & 0xf) {
445   case DW_EH_PE_uleb128:
446   case DW_EH_PE_udata2:
447   case DW_EH_PE_sleb128:
448   case DW_EH_PE_sdata2:
449     Supported = false;
450     break;
451   }
452   if (Supported) {
453     switch (PointerEncoding & 0x70) {
454     case DW_EH_PE_textrel:
455     case DW_EH_PE_datarel:
456     case DW_EH_PE_funcrel:
457     case DW_EH_PE_aligned:
458       Supported = false;
459       break;
460     }
461   }
462 
463   if (Supported)
464     return PointerEncoding;
465 
466   return make_error<JITLinkError>("Unsupported pointer encoding " +
467                                   formatv("{0:x2}", PointerEncoding) + " for " +
468                                   FieldName + "in CFI record at " +
469                                   formatv("{0:x16}", InBlock.getAddress()));
470 }
471 
472 Error EHFrameEdgeFixer::skipEncodedPointer(uint8_t PointerEncoding,
473                                            BinaryStreamReader &RecordReader) {
474   using namespace dwarf;
475 
476   // Switch absptr to corresponding udata encoding.
477   if ((PointerEncoding & 0xf) == DW_EH_PE_absptr)
478     PointerEncoding |= (PointerSize == 8) ? DW_EH_PE_udata8 : DW_EH_PE_udata4;
479 
480   switch (PointerEncoding & 0xf) {
481   case DW_EH_PE_udata4:
482   case DW_EH_PE_sdata4:
483     if (auto Err = RecordReader.skip(4))
484       return Err;
485     break;
486   case DW_EH_PE_udata8:
487   case DW_EH_PE_sdata8:
488     if (auto Err = RecordReader.skip(8))
489       return Err;
490     break;
491   default:
492     llvm_unreachable("Unrecognized encoding");
493   }
494   return Error::success();
495 }
496 
497 Expected<Symbol *> EHFrameEdgeFixer::getOrCreateEncodedPointerEdge(
498     ParseContext &PC, const BlockEdgeMap &BlockEdges, uint8_t PointerEncoding,
499     BinaryStreamReader &RecordReader, Block &BlockToFix,
500     size_t PointerFieldOffset, const char *FieldName) {
501   using namespace dwarf;
502 
503   if (PointerEncoding == DW_EH_PE_omit)
504     return nullptr;
505 
506   // If there's already an edge here then just skip the encoded pointer and
507   // return the edge's target.
508   {
509     auto EdgeI = BlockEdges.find(PointerFieldOffset);
510     if (EdgeI != BlockEdges.end()) {
511       LLVM_DEBUG({
512         dbgs() << "        Existing edge at "
513                << (BlockToFix.getAddress() + PointerFieldOffset) << " to "
514                << FieldName << " at " << EdgeI->second.Target->getAddress();
515         if (EdgeI->second.Target->hasName())
516           dbgs() << " (" << EdgeI->second.Target->getName() << ")";
517         dbgs() << "\n";
518       });
519       if (auto Err = skipEncodedPointer(PointerEncoding, RecordReader))
520         return std::move(Err);
521       return EdgeI->second.Target;
522     }
523   }
524 
525   // Switch absptr to corresponding udata encoding.
526   if ((PointerEncoding & 0xf) == DW_EH_PE_absptr)
527     PointerEncoding |= (PointerSize == 8) ? DW_EH_PE_udata8 : DW_EH_PE_udata4;
528 
529   // We need to create an edge. Start by reading the field value.
530   uint64_t FieldValue;
531   bool Is64Bit = false;
532   switch (PointerEncoding & 0xf) {
533   case DW_EH_PE_udata4: {
534     uint32_t Val;
535     if (auto Err = RecordReader.readInteger(Val))
536       return std::move(Err);
537     FieldValue = Val;
538     break;
539   }
540   case DW_EH_PE_sdata4: {
541     uint32_t Val;
542     if (auto Err = RecordReader.readInteger(Val))
543       return std::move(Err);
544     FieldValue = Val;
545     break;
546   }
547   case DW_EH_PE_udata8:
548   case DW_EH_PE_sdata8:
549     Is64Bit = true;
550     if (auto Err = RecordReader.readInteger(FieldValue))
551       return std::move(Err);
552     break;
553   default:
554     llvm_unreachable("Unsupported encoding");
555   }
556 
557   // Find the edge target and edge kind to use.
558   orc::ExecutorAddr Target;
559   Edge::Kind PtrEdgeKind = Edge::Invalid;
560   if ((PointerEncoding & 0x70) == DW_EH_PE_pcrel) {
561     Target = BlockToFix.getAddress() + PointerFieldOffset;
562     PtrEdgeKind = Is64Bit ? Delta64 : Delta32;
563   } else
564     PtrEdgeKind = Is64Bit ? Pointer64 : Pointer32;
565   Target += FieldValue;
566 
567   // Find or create a symbol to point the edge at.
568   auto TargetSym = getOrCreateSymbol(PC, Target);
569   if (!TargetSym)
570     return TargetSym.takeError();
571   BlockToFix.addEdge(PtrEdgeKind, PointerFieldOffset, *TargetSym, 0);
572 
573   LLVM_DEBUG({
574     dbgs() << "        Adding edge at "
575            << (BlockToFix.getAddress() + PointerFieldOffset) << " to "
576            << FieldName << " at " << TargetSym->getAddress();
577     if (TargetSym->hasName())
578       dbgs() << " (" << TargetSym->getName() << ")";
579     dbgs() << "\n";
580   });
581 
582   return &*TargetSym;
583 }
584 
585 Expected<Symbol &> EHFrameEdgeFixer::getOrCreateSymbol(ParseContext &PC,
586                                                        orc::ExecutorAddr Addr) {
587   // See whether we have a canonical symbol for the given address already.
588   auto CanonicalSymI = PC.AddrToSym.find(Addr);
589   if (CanonicalSymI != PC.AddrToSym.end())
590     return *CanonicalSymI->second;
591 
592   // Otherwise search for a block covering the address and create a new symbol.
593   auto *B = PC.AddrToBlock.getBlockCovering(Addr);
594   if (!B)
595     return make_error<JITLinkError>("No symbol or block covering address " +
596                                     formatv("{0:x16}", Addr));
597 
598   auto &S =
599       PC.G.addAnonymousSymbol(*B, Addr - B->getAddress(), 0, false, false);
600   PC.AddrToSym[S.getAddress()] = &S;
601   return S;
602 }
603 
604 char EHFrameNullTerminator::NullTerminatorBlockContent[4] = {0, 0, 0, 0};
605 
606 EHFrameNullTerminator::EHFrameNullTerminator(StringRef EHFrameSectionName)
607     : EHFrameSectionName(EHFrameSectionName) {}
608 
609 Error EHFrameNullTerminator::operator()(LinkGraph &G) {
610   auto *EHFrame = G.findSectionByName(EHFrameSectionName);
611 
612   if (!EHFrame)
613     return Error::success();
614 
615   LLVM_DEBUG({
616     dbgs() << "EHFrameNullTerminator adding null terminator to "
617            << EHFrameSectionName << "\n";
618   });
619 
620   auto &NullTerminatorBlock =
621       G.createContentBlock(*EHFrame, NullTerminatorBlockContent,
622                            orc::ExecutorAddr(~uint64_t(4)), 1, 0);
623   G.addAnonymousSymbol(NullTerminatorBlock, 0, 4, false, true);
624   return Error::success();
625 }
626 
627 EHFrameRegistrar::~EHFrameRegistrar() = default;
628 
629 Error InProcessEHFrameRegistrar::registerEHFrames(
630     orc::ExecutorAddrRange EHFrameSection) {
631   return orc::registerEHFrameSection(EHFrameSection.Start.toPtr<void *>(),
632                                      EHFrameSection.size());
633 }
634 
635 Error InProcessEHFrameRegistrar::deregisterEHFrames(
636     orc::ExecutorAddrRange EHFrameSection) {
637   return orc::deregisterEHFrameSection(EHFrameSection.Start.toPtr<void *>(),
638                                        EHFrameSection.size());
639 }
640 
641 LinkGraphPassFunction
642 createEHFrameRecorderPass(const Triple &TT,
643                           StoreFrameRangeFunction StoreRangeAddress) {
644   const char *EHFrameSectionName = nullptr;
645   if (TT.getObjectFormat() == Triple::MachO)
646     EHFrameSectionName = "__TEXT,__eh_frame";
647   else
648     EHFrameSectionName = ".eh_frame";
649 
650   auto RecordEHFrame =
651       [EHFrameSectionName,
652        StoreFrameRange = std::move(StoreRangeAddress)](LinkGraph &G) -> Error {
653     // Search for a non-empty eh-frame and record the address of the first
654     // symbol in it.
655     orc::ExecutorAddr Addr;
656     size_t Size = 0;
657     if (auto *S = G.findSectionByName(EHFrameSectionName)) {
658       auto R = SectionRange(*S);
659       Addr = R.getStart();
660       Size = R.getSize();
661     }
662     if (!Addr && Size != 0)
663       return make_error<JITLinkError>(
664           StringRef(EHFrameSectionName) +
665           " section can not have zero address with non-zero size");
666     StoreFrameRange(Addr, Size);
667     return Error::success();
668   };
669 
670   return RecordEHFrame;
671 }
672 
673 } // end namespace jitlink
674 } // end namespace llvm
675