xref: /llvm-project/llvm/lib/ExecutionEngine/JITLink/MachOLinkGraphBuilder.cpp (revision 5379c46d490640bfa80283e00240b6f1006092b4)
1 //=--------- MachOLinkGraphBuilder.cpp - MachO LinkGraph builder ----------===//
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 // Generic MachO LinkGraph buliding code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "MachOLinkGraphBuilder.h"
14 #include <optional>
15 
16 #define DEBUG_TYPE "jitlink"
17 
18 static const char *CommonSectionName = "__common";
19 
20 namespace llvm {
21 namespace jitlink {
22 
23 MachOLinkGraphBuilder::~MachOLinkGraphBuilder() = default;
24 
25 Expected<std::unique_ptr<LinkGraph>> MachOLinkGraphBuilder::buildGraph() {
26 
27   // We only operate on relocatable objects.
28   if (!Obj.isRelocatableObject())
29     return make_error<JITLinkError>("Object is not a relocatable MachO");
30 
31   if (auto Err = createNormalizedSections())
32     return std::move(Err);
33 
34   if (auto Err = createNormalizedSymbols())
35     return std::move(Err);
36 
37   if (auto Err = graphifyRegularSymbols())
38     return std::move(Err);
39 
40   if (auto Err = graphifySectionsWithCustomParsers())
41     return std::move(Err);
42 
43   if (auto Err = addRelocations())
44     return std::move(Err);
45 
46   return std::move(G);
47 }
48 
49 MachOLinkGraphBuilder::MachOLinkGraphBuilder(
50     const object::MachOObjectFile &Obj, Triple TT,
51     LinkGraph::GetEdgeKindNameFunction GetEdgeKindName)
52     : Obj(Obj),
53       G(std::make_unique<LinkGraph>(
54           std::string(Obj.getFileName()), std::move(TT), getPointerSize(Obj),
55           getEndianness(Obj), std::move(GetEdgeKindName))) {
56   auto &MachHeader = Obj.getHeader64();
57   SubsectionsViaSymbols = MachHeader.flags & MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
58 }
59 
60 void MachOLinkGraphBuilder::addCustomSectionParser(
61     StringRef SectionName, SectionParserFunction Parser) {
62   assert(!CustomSectionParserFunctions.count(SectionName) &&
63          "Custom parser for this section already exists");
64   CustomSectionParserFunctions[SectionName] = std::move(Parser);
65 }
66 
67 Linkage MachOLinkGraphBuilder::getLinkage(uint16_t Desc) {
68   if ((Desc & MachO::N_WEAK_DEF) || (Desc & MachO::N_WEAK_REF))
69     return Linkage::Weak;
70   return Linkage::Strong;
71 }
72 
73 Scope MachOLinkGraphBuilder::getScope(StringRef Name, uint8_t Type) {
74   if (Type & MachO::N_EXT) {
75     if ((Type & MachO::N_PEXT) || Name.startswith("l"))
76       return Scope::Hidden;
77     else
78       return Scope::Default;
79   }
80   return Scope::Local;
81 }
82 
83 bool MachOLinkGraphBuilder::isAltEntry(const NormalizedSymbol &NSym) {
84   return NSym.Desc & MachO::N_ALT_ENTRY;
85 }
86 
87 bool MachOLinkGraphBuilder::isDebugSection(const NormalizedSection &NSec) {
88   return (NSec.Flags & MachO::S_ATTR_DEBUG &&
89           strcmp(NSec.SegName, "__DWARF") == 0);
90 }
91 
92 bool MachOLinkGraphBuilder::isZeroFillSection(const NormalizedSection &NSec) {
93   switch (NSec.Flags & MachO::SECTION_TYPE) {
94   case MachO::S_ZEROFILL:
95   case MachO::S_GB_ZEROFILL:
96   case MachO::S_THREAD_LOCAL_ZEROFILL:
97     return true;
98   default:
99     return false;
100   }
101 }
102 
103 unsigned
104 MachOLinkGraphBuilder::getPointerSize(const object::MachOObjectFile &Obj) {
105   return Obj.is64Bit() ? 8 : 4;
106 }
107 
108 support::endianness
109 MachOLinkGraphBuilder::getEndianness(const object::MachOObjectFile &Obj) {
110   return Obj.isLittleEndian() ? support::little : support::big;
111 }
112 
113 Section &MachOLinkGraphBuilder::getCommonSection() {
114   if (!CommonSection)
115     CommonSection = &G->createSection(CommonSectionName,
116                                       orc::MemProt::Read | orc::MemProt::Write);
117   return *CommonSection;
118 }
119 
120 Error MachOLinkGraphBuilder::createNormalizedSections() {
121   // Build normalized sections. Verifies that section data is in-range (for
122   // sections with content) and that address ranges are non-overlapping.
123 
124   LLVM_DEBUG(dbgs() << "Creating normalized sections...\n");
125 
126   for (auto &SecRef : Obj.sections()) {
127     NormalizedSection NSec;
128     uint32_t DataOffset = 0;
129 
130     auto SecIndex = Obj.getSectionIndex(SecRef.getRawDataRefImpl());
131 
132     if (Obj.is64Bit()) {
133       const MachO::section_64 &Sec64 =
134           Obj.getSection64(SecRef.getRawDataRefImpl());
135 
136       memcpy(&NSec.SectName, &Sec64.sectname, 16);
137       NSec.SectName[16] = '\0';
138       memcpy(&NSec.SegName, Sec64.segname, 16);
139       NSec.SegName[16] = '\0';
140 
141       NSec.Address = orc::ExecutorAddr(Sec64.addr);
142       NSec.Size = Sec64.size;
143       NSec.Alignment = 1ULL << Sec64.align;
144       NSec.Flags = Sec64.flags;
145       DataOffset = Sec64.offset;
146     } else {
147       const MachO::section &Sec32 = Obj.getSection(SecRef.getRawDataRefImpl());
148 
149       memcpy(&NSec.SectName, &Sec32.sectname, 16);
150       NSec.SectName[16] = '\0';
151       memcpy(&NSec.SegName, Sec32.segname, 16);
152       NSec.SegName[16] = '\0';
153 
154       NSec.Address = orc::ExecutorAddr(Sec32.addr);
155       NSec.Size = Sec32.size;
156       NSec.Alignment = 1ULL << Sec32.align;
157       NSec.Flags = Sec32.flags;
158       DataOffset = Sec32.offset;
159     }
160 
161     LLVM_DEBUG({
162       dbgs() << "  " << NSec.SegName << "," << NSec.SectName << ": "
163              << formatv("{0:x16}", NSec.Address) << " -- "
164              << formatv("{0:x16}", NSec.Address + NSec.Size)
165              << ", align: " << NSec.Alignment << ", index: " << SecIndex
166              << "\n";
167     });
168 
169     // Get the section data if any.
170     if (!isZeroFillSection(NSec)) {
171       if (DataOffset + NSec.Size > Obj.getData().size())
172         return make_error<JITLinkError>(
173             "Section data extends past end of file");
174 
175       NSec.Data = Obj.getData().data() + DataOffset;
176     }
177 
178     // Get prot flags.
179     // FIXME: Make sure this test is correct (it's probably missing cases
180     // as-is).
181     orc::MemProt Prot;
182     if (NSec.Flags & MachO::S_ATTR_PURE_INSTRUCTIONS)
183       Prot = orc::MemProt::Read | orc::MemProt::Exec;
184     else
185       Prot = orc::MemProt::Read | orc::MemProt::Write;
186 
187     auto FullyQualifiedName =
188         G->allocateContent(StringRef(NSec.SegName) + "," + NSec.SectName);
189     NSec.GraphSection = &G->createSection(
190         StringRef(FullyQualifiedName.data(), FullyQualifiedName.size()), Prot);
191 
192     IndexToSection.insert(std::make_pair(SecIndex, std::move(NSec)));
193   }
194 
195   std::vector<NormalizedSection *> Sections;
196   Sections.reserve(IndexToSection.size());
197   for (auto &KV : IndexToSection)
198     Sections.push_back(&KV.second);
199 
200   // If we didn't end up creating any sections then bail out. The code below
201   // assumes that we have at least one section.
202   if (Sections.empty())
203     return Error::success();
204 
205   llvm::sort(Sections,
206              [](const NormalizedSection *LHS, const NormalizedSection *RHS) {
207                assert(LHS && RHS && "Null section?");
208                if (LHS->Address != RHS->Address)
209                  return LHS->Address < RHS->Address;
210                return LHS->Size < RHS->Size;
211              });
212 
213   for (unsigned I = 0, E = Sections.size() - 1; I != E; ++I) {
214     auto &Cur = *Sections[I];
215     auto &Next = *Sections[I + 1];
216     if (Next.Address < Cur.Address + Cur.Size)
217       return make_error<JITLinkError>(
218           "Address range for section " +
219           formatv("\"{0}/{1}\" [ {2:x16} -- {3:x16} ] ", Cur.SegName,
220                   Cur.SectName, Cur.Address, Cur.Address + Cur.Size) +
221           "overlaps section \"" + Next.SegName + "/" + Next.SectName + "\"" +
222           formatv("\"{0}/{1}\" [ {2:x16} -- {3:x16} ] ", Next.SegName,
223                   Next.SectName, Next.Address, Next.Address + Next.Size));
224   }
225 
226   return Error::success();
227 }
228 
229 Error MachOLinkGraphBuilder::createNormalizedSymbols() {
230   LLVM_DEBUG(dbgs() << "Creating normalized symbols...\n");
231 
232   for (auto &SymRef : Obj.symbols()) {
233 
234     unsigned SymbolIndex = Obj.getSymbolIndex(SymRef.getRawDataRefImpl());
235     uint64_t Value;
236     uint32_t NStrX;
237     uint8_t Type;
238     uint8_t Sect;
239     uint16_t Desc;
240 
241     if (Obj.is64Bit()) {
242       const MachO::nlist_64 &NL64 =
243           Obj.getSymbol64TableEntry(SymRef.getRawDataRefImpl());
244       Value = NL64.n_value;
245       NStrX = NL64.n_strx;
246       Type = NL64.n_type;
247       Sect = NL64.n_sect;
248       Desc = NL64.n_desc;
249     } else {
250       const MachO::nlist &NL32 =
251           Obj.getSymbolTableEntry(SymRef.getRawDataRefImpl());
252       Value = NL32.n_value;
253       NStrX = NL32.n_strx;
254       Type = NL32.n_type;
255       Sect = NL32.n_sect;
256       Desc = NL32.n_desc;
257     }
258 
259     // Skip stabs.
260     // FIXME: Are there other symbols we should be skipping?
261     if (Type & MachO::N_STAB)
262       continue;
263 
264     std::optional<StringRef> Name;
265     if (NStrX) {
266       if (auto NameOrErr = SymRef.getName())
267         Name = *NameOrErr;
268       else
269         return NameOrErr.takeError();
270     } else if (Type & MachO::N_EXT)
271       return make_error<JITLinkError>("Symbol at index " +
272                                       formatv("{0}", SymbolIndex) +
273                                       " has no name (string table index 0), "
274                                       "but N_EXT bit is set");
275 
276     LLVM_DEBUG({
277       dbgs() << "  ";
278       if (!Name)
279         dbgs() << "<anonymous symbol>";
280       else
281         dbgs() << *Name;
282       dbgs() << ": value = " << formatv("{0:x16}", Value)
283              << ", type = " << formatv("{0:x2}", Type)
284              << ", desc = " << formatv("{0:x4}", Desc) << ", sect = ";
285       if (Sect)
286         dbgs() << static_cast<unsigned>(Sect - 1);
287       else
288         dbgs() << "none";
289       dbgs() << "\n";
290     });
291 
292     // If this symbol has a section, verify that the addresses line up.
293     if (Sect != 0) {
294       auto NSec = findSectionByIndex(Sect - 1);
295       if (!NSec)
296         return NSec.takeError();
297 
298       if (orc::ExecutorAddr(Value) < NSec->Address ||
299           orc::ExecutorAddr(Value) > NSec->Address + NSec->Size)
300         return make_error<JITLinkError>("Address " + formatv("{0:x}", Value) +
301                                         " for symbol " + *Name +
302                                         " does not fall within section");
303 
304       if (!NSec->GraphSection) {
305         LLVM_DEBUG({
306           dbgs() << "  Skipping: Symbol is in section " << NSec->SegName << "/"
307                  << NSec->SectName
308                  << " which has no associated graph section.\n";
309         });
310         continue;
311       }
312     }
313 
314     IndexToSymbol[SymbolIndex] =
315         &createNormalizedSymbol(*Name, Value, Type, Sect, Desc,
316                                 getLinkage(Desc), getScope(*Name, Type));
317   }
318 
319   return Error::success();
320 }
321 
322 void MachOLinkGraphBuilder::addSectionStartSymAndBlock(
323     unsigned SecIndex, Section &GraphSec, orc::ExecutorAddr Address,
324     const char *Data, orc::ExecutorAddrDiff Size, uint32_t Alignment,
325     bool IsLive) {
326   Block &B =
327       Data ? G->createContentBlock(GraphSec, ArrayRef<char>(Data, Size),
328                                    Address, Alignment, 0)
329            : G->createZeroFillBlock(GraphSec, Size, Address, Alignment, 0);
330   auto &Sym = G->addAnonymousSymbol(B, 0, Size, false, IsLive);
331   auto SecI = IndexToSection.find(SecIndex);
332   assert(SecI != IndexToSection.end() && "SecIndex invalid");
333   auto &NSec = SecI->second;
334   assert(!NSec.CanonicalSymbols.count(Sym.getAddress()) &&
335          "Anonymous block start symbol clashes with existing symbol address");
336   NSec.CanonicalSymbols[Sym.getAddress()] = &Sym;
337 }
338 
339 Error MachOLinkGraphBuilder::graphifyRegularSymbols() {
340 
341   LLVM_DEBUG(dbgs() << "Creating graph symbols...\n");
342 
343   /// We only have 256 section indexes: Use a vector rather than a map.
344   std::vector<std::vector<NormalizedSymbol *>> SecIndexToSymbols;
345   SecIndexToSymbols.resize(256);
346 
347   // Create commons, externs, and absolutes, and partition all other symbols by
348   // section.
349   for (auto &KV : IndexToSymbol) {
350     auto &NSym = *KV.second;
351 
352     switch (NSym.Type & MachO::N_TYPE) {
353     case MachO::N_UNDF:
354       if (NSym.Value) {
355         if (!NSym.Name)
356           return make_error<JITLinkError>("Anonymous common symbol at index " +
357                                           Twine(KV.first));
358         NSym.GraphSymbol = &G->addDefinedSymbol(
359             G->createZeroFillBlock(getCommonSection(),
360                                    orc::ExecutorAddrDiff(NSym.Value),
361                                    orc::ExecutorAddr(),
362                                    1ull << MachO::GET_COMM_ALIGN(NSym.Desc), 0),
363             0, *NSym.Name, orc::ExecutorAddrDiff(NSym.Value), Linkage::Strong,
364             NSym.S, false, NSym.Desc & MachO::N_NO_DEAD_STRIP);
365       } else {
366         if (!NSym.Name)
367           return make_error<JITLinkError>("Anonymous external symbol at "
368                                           "index " +
369                                           Twine(KV.first));
370         NSym.GraphSymbol = &G->addExternalSymbol(
371             *NSym.Name, 0, (NSym.Desc & MachO::N_WEAK_REF) != 0);
372       }
373       break;
374     case MachO::N_ABS:
375       if (!NSym.Name)
376         return make_error<JITLinkError>("Anonymous absolute symbol at index " +
377                                         Twine(KV.first));
378       NSym.GraphSymbol = &G->addAbsoluteSymbol(
379           *NSym.Name, orc::ExecutorAddr(NSym.Value), 0, Linkage::Strong,
380           getScope(*NSym.Name, NSym.Type), NSym.Desc & MachO::N_NO_DEAD_STRIP);
381       break;
382     case MachO::N_SECT:
383       SecIndexToSymbols[NSym.Sect - 1].push_back(&NSym);
384       break;
385     case MachO::N_PBUD:
386       return make_error<JITLinkError>(
387           "Unupported N_PBUD symbol " +
388           (NSym.Name ? ("\"" + *NSym.Name + "\"") : Twine("<anon>")) +
389           " at index " + Twine(KV.first));
390     case MachO::N_INDR:
391       return make_error<JITLinkError>(
392           "Unupported N_INDR symbol " +
393           (NSym.Name ? ("\"" + *NSym.Name + "\"") : Twine("<anon>")) +
394           " at index " + Twine(KV.first));
395     default:
396       return make_error<JITLinkError>(
397           "Unrecognized symbol type " + Twine(NSym.Type & MachO::N_TYPE) +
398           " for symbol " +
399           (NSym.Name ? ("\"" + *NSym.Name + "\"") : Twine("<anon>")) +
400           " at index " + Twine(KV.first));
401     }
402   }
403 
404   // Loop over sections performing regular graphification for those that
405   // don't have custom parsers.
406   for (auto &KV : IndexToSection) {
407     auto SecIndex = KV.first;
408     auto &NSec = KV.second;
409 
410     if (!NSec.GraphSection) {
411       LLVM_DEBUG({
412         dbgs() << "  " << NSec.SegName << "/" << NSec.SectName
413                << " has no graph section. Skipping.\n";
414       });
415       continue;
416     }
417 
418     // Skip sections with custom parsers.
419     if (CustomSectionParserFunctions.count(NSec.GraphSection->getName())) {
420       LLVM_DEBUG({
421         dbgs() << "  Skipping section " << NSec.GraphSection->getName()
422                << " as it has a custom parser.\n";
423       });
424       continue;
425     } else if ((NSec.Flags & MachO::SECTION_TYPE) ==
426                MachO::S_CSTRING_LITERALS) {
427       if (auto Err = graphifyCStringSection(
428               NSec, std::move(SecIndexToSymbols[SecIndex])))
429         return Err;
430       continue;
431     } else
432       LLVM_DEBUG({
433         dbgs() << "  Graphifying regular section "
434                << NSec.GraphSection->getName() << "...\n";
435       });
436 
437     bool SectionIsNoDeadStrip = NSec.Flags & MachO::S_ATTR_NO_DEAD_STRIP;
438     bool SectionIsText = NSec.Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
439 
440     auto &SecNSymStack = SecIndexToSymbols[SecIndex];
441 
442     // If this section is non-empty but there are no symbols covering it then
443     // create one block and anonymous symbol to cover the entire section.
444     if (SecNSymStack.empty()) {
445       if (NSec.Size > 0) {
446         LLVM_DEBUG({
447           dbgs() << "    Section non-empty, but contains no symbols. "
448                     "Creating anonymous block to cover "
449                  << formatv("{0:x16}", NSec.Address) << " -- "
450                  << formatv("{0:x16}", NSec.Address + NSec.Size) << "\n";
451         });
452         addSectionStartSymAndBlock(SecIndex, *NSec.GraphSection, NSec.Address,
453                                    NSec.Data, NSec.Size, NSec.Alignment,
454                                    SectionIsNoDeadStrip);
455       } else
456         LLVM_DEBUG({
457           dbgs() << "    Section empty and contains no symbols. Skipping.\n";
458         });
459       continue;
460     }
461 
462     // Sort the symbol stack in by address, alt-entry status, scope, and name.
463     // We sort in reverse order so that symbols will be visited in the right
464     // order when we pop off the stack below.
465     llvm::sort(SecNSymStack, [](const NormalizedSymbol *LHS,
466                                 const NormalizedSymbol *RHS) {
467       if (LHS->Value != RHS->Value)
468         return LHS->Value > RHS->Value;
469       if (isAltEntry(*LHS) != isAltEntry(*RHS))
470         return isAltEntry(*RHS);
471       if (LHS->S != RHS->S)
472         return static_cast<uint8_t>(LHS->S) < static_cast<uint8_t>(RHS->S);
473       return LHS->Name < RHS->Name;
474     });
475 
476     // The first symbol in a section can not be an alt-entry symbol.
477     if (!SecNSymStack.empty() && isAltEntry(*SecNSymStack.back()))
478       return make_error<JITLinkError>(
479           "First symbol in " + NSec.GraphSection->getName() + " is alt-entry");
480 
481     // If the section is non-empty but there is no symbol covering the start
482     // address then add an anonymous one.
483     if (orc::ExecutorAddr(SecNSymStack.back()->Value) != NSec.Address) {
484       auto AnonBlockSize =
485           orc::ExecutorAddr(SecNSymStack.back()->Value) - NSec.Address;
486       LLVM_DEBUG({
487         dbgs() << "    Section start not covered by symbol. "
488                << "Creating anonymous block to cover [ " << NSec.Address
489                << " -- " << (NSec.Address + AnonBlockSize) << " ]\n";
490       });
491       addSectionStartSymAndBlock(SecIndex, *NSec.GraphSection, NSec.Address,
492                                  NSec.Data, AnonBlockSize, NSec.Alignment,
493                                  SectionIsNoDeadStrip);
494     }
495 
496     // Visit section symbols in order by popping off the reverse-sorted stack,
497     // building graph symbols as we go.
498     //
499     // If MH_SUBSECTIONS_VIA_SYMBOLS is set we'll build a block for each
500     // alt-entry chain.
501     //
502     // If MH_SUBSECTIONS_VIA_SYMBOLS is not set then we'll just build one block
503     // for the whole section.
504     while (!SecNSymStack.empty()) {
505       SmallVector<NormalizedSymbol *, 8> BlockSyms;
506 
507       // Get the symbols in this alt-entry chain, or the whole section (if
508       // !SubsectionsViaSymbols).
509       BlockSyms.push_back(SecNSymStack.back());
510       SecNSymStack.pop_back();
511       while (!SecNSymStack.empty() &&
512              (isAltEntry(*SecNSymStack.back()) ||
513               SecNSymStack.back()->Value == BlockSyms.back()->Value ||
514              !SubsectionsViaSymbols)) {
515         BlockSyms.push_back(SecNSymStack.back());
516         SecNSymStack.pop_back();
517       }
518 
519       // BlockNSyms now contains the block symbols in reverse canonical order.
520       auto BlockStart = orc::ExecutorAddr(BlockSyms.front()->Value);
521       orc::ExecutorAddr BlockEnd =
522           SecNSymStack.empty() ? NSec.Address + NSec.Size
523                                : orc::ExecutorAddr(SecNSymStack.back()->Value);
524       orc::ExecutorAddrDiff BlockOffset = BlockStart - NSec.Address;
525       orc::ExecutorAddrDiff BlockSize = BlockEnd - BlockStart;
526 
527       LLVM_DEBUG({
528         dbgs() << "    Creating block for " << formatv("{0:x16}", BlockStart)
529                << " -- " << formatv("{0:x16}", BlockEnd) << ": "
530                << NSec.GraphSection->getName() << " + "
531                << formatv("{0:x16}", BlockOffset) << " with "
532                << BlockSyms.size() << " symbol(s)...\n";
533       });
534 
535       Block &B =
536           NSec.Data
537               ? G->createContentBlock(
538                     *NSec.GraphSection,
539                     ArrayRef<char>(NSec.Data + BlockOffset, BlockSize),
540                     BlockStart, NSec.Alignment, BlockStart % NSec.Alignment)
541               : G->createZeroFillBlock(*NSec.GraphSection, BlockSize,
542                                        BlockStart, NSec.Alignment,
543                                        BlockStart % NSec.Alignment);
544 
545       std::optional<orc::ExecutorAddr> LastCanonicalAddr;
546       auto SymEnd = BlockEnd;
547       while (!BlockSyms.empty()) {
548         auto &NSym = *BlockSyms.back();
549         BlockSyms.pop_back();
550 
551         bool SymLive =
552             (NSym.Desc & MachO::N_NO_DEAD_STRIP) || SectionIsNoDeadStrip;
553 
554         auto &Sym = createStandardGraphSymbol(
555             NSym, B, SymEnd - orc::ExecutorAddr(NSym.Value), SectionIsText,
556             SymLive, LastCanonicalAddr != orc::ExecutorAddr(NSym.Value));
557 
558         if (LastCanonicalAddr != Sym.getAddress()) {
559           if (LastCanonicalAddr)
560             SymEnd = *LastCanonicalAddr;
561           LastCanonicalAddr = Sym.getAddress();
562         }
563       }
564     }
565   }
566 
567   return Error::success();
568 }
569 
570 Symbol &MachOLinkGraphBuilder::createStandardGraphSymbol(NormalizedSymbol &NSym,
571                                                          Block &B, size_t Size,
572                                                          bool IsText,
573                                                          bool IsNoDeadStrip,
574                                                          bool IsCanonical) {
575 
576   LLVM_DEBUG({
577     dbgs() << "      " << formatv("{0:x16}", NSym.Value) << " -- "
578            << formatv("{0:x16}", NSym.Value + Size) << ": ";
579     if (!NSym.Name)
580       dbgs() << "<anonymous symbol>";
581     else
582       dbgs() << NSym.Name;
583     if (IsText)
584       dbgs() << " [text]";
585     if (IsNoDeadStrip)
586       dbgs() << " [no-dead-strip]";
587     if (!IsCanonical)
588       dbgs() << " [non-canonical]";
589     dbgs() << "\n";
590   });
591 
592   auto SymOffset = orc::ExecutorAddr(NSym.Value) - B.getAddress();
593   auto &Sym =
594       NSym.Name
595           ? G->addDefinedSymbol(B, SymOffset, *NSym.Name, Size, NSym.L, NSym.S,
596                                 IsText, IsNoDeadStrip)
597           : G->addAnonymousSymbol(B, SymOffset, Size, IsText, IsNoDeadStrip);
598   NSym.GraphSymbol = &Sym;
599 
600   if (IsCanonical)
601     setCanonicalSymbol(getSectionByIndex(NSym.Sect - 1), Sym);
602 
603   return Sym;
604 }
605 
606 Error MachOLinkGraphBuilder::graphifySectionsWithCustomParsers() {
607   // Graphify special sections.
608   for (auto &KV : IndexToSection) {
609     auto &NSec = KV.second;
610 
611     // Skip non-graph sections.
612     if (!NSec.GraphSection)
613       continue;
614 
615     auto HI = CustomSectionParserFunctions.find(NSec.GraphSection->getName());
616     if (HI != CustomSectionParserFunctions.end()) {
617       auto &Parse = HI->second;
618       if (auto Err = Parse(NSec))
619         return Err;
620     }
621   }
622 
623   return Error::success();
624 }
625 
626 Error MachOLinkGraphBuilder::graphifyCStringSection(
627     NormalizedSection &NSec, std::vector<NormalizedSymbol *> NSyms) {
628   assert(NSec.GraphSection && "C string literal section missing graph section");
629   assert(NSec.Data && "C string literal section has no data");
630 
631   LLVM_DEBUG({
632     dbgs() << "  Graphifying C-string literal section "
633            << NSec.GraphSection->getName() << "\n";
634   });
635 
636   if (NSec.Data[NSec.Size - 1] != '\0')
637     return make_error<JITLinkError>("C string literal section " +
638                                     NSec.GraphSection->getName() +
639                                     " does not end with null terminator");
640 
641   /// Sort into reverse order to use as a stack.
642   llvm::sort(NSyms,
643              [](const NormalizedSymbol *LHS, const NormalizedSymbol *RHS) {
644                if (LHS->Value != RHS->Value)
645                  return LHS->Value > RHS->Value;
646                if (LHS->L != RHS->L)
647                  return LHS->L > RHS->L;
648                if (LHS->S != RHS->S)
649                  return LHS->S > RHS->S;
650                if (RHS->Name) {
651                  if (!LHS->Name)
652                    return true;
653                  return *LHS->Name > *RHS->Name;
654                }
655                return false;
656              });
657 
658   bool SectionIsNoDeadStrip = NSec.Flags & MachO::S_ATTR_NO_DEAD_STRIP;
659   bool SectionIsText = NSec.Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
660   orc::ExecutorAddrDiff BlockStart = 0;
661 
662   // Scan section for null characters.
663   for (size_t I = 0; I != NSec.Size; ++I) {
664     if (NSec.Data[I] == '\0') {
665       size_t BlockSize = I + 1 - BlockStart;
666       // Create a block for this null terminated string.
667       auto &B = G->createContentBlock(*NSec.GraphSection,
668                                       {NSec.Data + BlockStart, BlockSize},
669                                       NSec.Address + BlockStart, NSec.Alignment,
670                                       BlockStart % NSec.Alignment);
671 
672       LLVM_DEBUG({
673         dbgs() << "    Created block " << B.getRange()
674                << ", align = " << B.getAlignment()
675                << ", align-ofs = " << B.getAlignmentOffset() << " for \"";
676         for (size_t J = 0; J != std::min(B.getSize(), size_t(16)); ++J)
677           switch (B.getContent()[J]) {
678           case '\0': break;
679           case '\n': dbgs() << "\\n"; break;
680           case '\t': dbgs() << "\\t"; break;
681           default:   dbgs() << B.getContent()[J]; break;
682           }
683         if (B.getSize() > 16)
684           dbgs() << "...";
685         dbgs() << "\"\n";
686       });
687 
688       // If there's no symbol at the start of this block then create one.
689       if (NSyms.empty() ||
690           orc::ExecutorAddr(NSyms.back()->Value) != B.getAddress()) {
691         auto &S = G->addAnonymousSymbol(B, 0, BlockSize, false, false);
692         setCanonicalSymbol(NSec, S);
693         LLVM_DEBUG({
694           dbgs() << "      Adding symbol for c-string block " << B.getRange()
695                  << ": <anonymous symbol> at offset 0\n";
696         });
697       }
698 
699       // Process any remaining symbols that point into this block.
700       auto LastCanonicalAddr = B.getAddress() + BlockSize;
701       while (!NSyms.empty() && orc::ExecutorAddr(NSyms.back()->Value) <
702                                    B.getAddress() + BlockSize) {
703         auto &NSym = *NSyms.back();
704         size_t SymSize = (B.getAddress() + BlockSize) -
705                          orc::ExecutorAddr(NSyms.back()->Value);
706         bool SymLive =
707             (NSym.Desc & MachO::N_NO_DEAD_STRIP) || SectionIsNoDeadStrip;
708 
709         bool IsCanonical = false;
710         if (LastCanonicalAddr != orc::ExecutorAddr(NSym.Value)) {
711           IsCanonical = true;
712           LastCanonicalAddr = orc::ExecutorAddr(NSym.Value);
713         }
714 
715         auto &Sym = createStandardGraphSymbol(NSym, B, SymSize, SectionIsText,
716                                               SymLive, IsCanonical);
717         (void)Sym;
718         LLVM_DEBUG({
719           dbgs() << "      Adding symbol for c-string block " << B.getRange()
720                  << ": "
721                  << (Sym.hasName() ? Sym.getName() : "<anonymous symbol>")
722                  << " at offset " << formatv("{0:x}", Sym.getOffset()) << "\n";
723         });
724 
725         NSyms.pop_back();
726       }
727 
728       BlockStart += BlockSize;
729     }
730   }
731 
732   assert(llvm::all_of(NSec.GraphSection->blocks(),
733                       [](Block *B) { return isCStringBlock(*B); }) &&
734          "All blocks in section should hold single c-strings");
735 
736   return Error::success();
737 }
738 
739 Error CompactUnwindSplitter::operator()(LinkGraph &G) {
740   auto *CUSec = G.findSectionByName(CompactUnwindSectionName);
741   if (!CUSec)
742     return Error::success();
743 
744   if (!G.getTargetTriple().isOSBinFormatMachO())
745     return make_error<JITLinkError>(
746         "Error linking " + G.getName() +
747         ": compact unwind splitting not supported on non-macho target " +
748         G.getTargetTriple().str());
749 
750   unsigned CURecordSize = 0;
751   unsigned PersonalityEdgeOffset = 0;
752   unsigned LSDAEdgeOffset = 0;
753   switch (G.getTargetTriple().getArch()) {
754   case Triple::aarch64:
755   case Triple::x86_64:
756     // 64-bit compact-unwind record format:
757     // Range start: 8 bytes.
758     // Range size:  4 bytes.
759     // CU encoding: 4 bytes.
760     // Personality: 8 bytes.
761     // LSDA:        8 bytes.
762     CURecordSize = 32;
763     PersonalityEdgeOffset = 16;
764     LSDAEdgeOffset = 24;
765     break;
766   default:
767     return make_error<JITLinkError>(
768         "Error linking " + G.getName() +
769         ": compact unwind splitting not supported on " +
770         G.getTargetTriple().getArchName());
771   }
772 
773   std::vector<Block *> OriginalBlocks(CUSec->blocks().begin(),
774                                       CUSec->blocks().end());
775   LLVM_DEBUG({
776     dbgs() << "In " << G.getName() << " splitting compact unwind section "
777            << CompactUnwindSectionName << " containing "
778            << OriginalBlocks.size() << " initial blocks...\n";
779   });
780 
781   while (!OriginalBlocks.empty()) {
782     auto *B = OriginalBlocks.back();
783     OriginalBlocks.pop_back();
784 
785     if (B->getSize() == 0) {
786       LLVM_DEBUG({
787         dbgs() << "  Skipping empty block at "
788                << formatv("{0:x16}", B->getAddress()) << "\n";
789       });
790       continue;
791     }
792 
793     LLVM_DEBUG({
794       dbgs() << "  Splitting block at " << formatv("{0:x16}", B->getAddress())
795              << " into " << (B->getSize() / CURecordSize)
796              << " compact unwind record(s)\n";
797     });
798 
799     if (B->getSize() % CURecordSize)
800       return make_error<JITLinkError>(
801           "Error splitting compact unwind record in " + G.getName() +
802           ": block at " + formatv("{0:x}", B->getAddress()) + " has size " +
803           formatv("{0:x}", B->getSize()) +
804           " (not a multiple of CU record size of " +
805           formatv("{0:x}", CURecordSize) + ")");
806 
807     unsigned NumBlocks = B->getSize() / CURecordSize;
808     LinkGraph::SplitBlockCache C;
809 
810     for (unsigned I = 0; I != NumBlocks; ++I) {
811       auto &CURec = G.splitBlock(*B, CURecordSize, &C);
812       bool AddedKeepAlive = false;
813 
814       for (auto &E : CURec.edges()) {
815         if (E.getOffset() == 0) {
816           LLVM_DEBUG({
817             dbgs() << "    Updating compact unwind record at "
818                    << formatv("{0:x16}", CURec.getAddress()) << " to point to "
819                    << (E.getTarget().hasName() ? E.getTarget().getName()
820                                                : StringRef())
821                    << " (at " << formatv("{0:x16}", E.getTarget().getAddress())
822                    << ")\n";
823           });
824 
825           if (E.getTarget().isExternal())
826             return make_error<JITLinkError>(
827                 "Error adding keep-alive edge for compact unwind record at " +
828                 formatv("{0:x}", CURec.getAddress()) + ": target " +
829                 E.getTarget().getName() + " is an external symbol");
830           auto &TgtBlock = E.getTarget().getBlock();
831           auto &CURecSym =
832               G.addAnonymousSymbol(CURec, 0, CURecordSize, false, false);
833           TgtBlock.addEdge(Edge::KeepAlive, 0, CURecSym, 0);
834           AddedKeepAlive = true;
835         } else if (E.getOffset() != PersonalityEdgeOffset &&
836                    E.getOffset() != LSDAEdgeOffset)
837           return make_error<JITLinkError>("Unexpected edge at offset " +
838                                           formatv("{0:x}", E.getOffset()) +
839                                           " in compact unwind record at " +
840                                           formatv("{0:x}", CURec.getAddress()));
841       }
842 
843       if (!AddedKeepAlive)
844         return make_error<JITLinkError>(
845             "Error adding keep-alive edge for compact unwind record at " +
846             formatv("{0:x}", CURec.getAddress()) +
847             ": no outgoing target edge at offset 0");
848     }
849   }
850   return Error::success();
851 }
852 
853 } // end namespace jitlink
854 } // end namespace llvm
855