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 
15 #define DEBUG_TYPE "jitlink"
16 
17 static const char *CommonSectionName = "__common";
18 
19 namespace llvm {
20 namespace jitlink {
21 
22 MachOLinkGraphBuilder::~MachOLinkGraphBuilder() {}
23 
24 Expected<std::unique_ptr<LinkGraph>> MachOLinkGraphBuilder::buildGraph() {
25 
26   // Sanity check: we only operate on relocatable objects.
27   if (!Obj.isRelocatableObject())
28     return make_error<JITLinkError>("Object is not a relocatable MachO");
29 
30   if (auto Err = createNormalizedSections())
31     return std::move(Err);
32 
33   if (auto Err = createNormalizedSymbols())
34     return std::move(Err);
35 
36   if (auto Err = graphifyRegularSymbols())
37     return std::move(Err);
38 
39   if (auto Err = graphifySectionsWithCustomParsers())
40     return std::move(Err);
41 
42   if (auto Err = addRelocations())
43     return std::move(Err);
44 
45   return std::move(G);
46 }
47 
48 MachOLinkGraphBuilder::MachOLinkGraphBuilder(const object::MachOObjectFile &Obj)
49     : Obj(Obj),
50       G(std::make_unique<LinkGraph>(Obj.getFileName(), getPointerSize(Obj),
51                                     getEndianness(Obj))) {}
52 
53 void MachOLinkGraphBuilder::addCustomSectionParser(
54     StringRef SectionName, SectionParserFunction Parser) {
55   assert(!CustomSectionParserFunctions.count(SectionName) &&
56          "Custom parser for this section already exists");
57   CustomSectionParserFunctions[SectionName] = std::move(Parser);
58 }
59 
60 Linkage MachOLinkGraphBuilder::getLinkage(uint16_t Desc) {
61   if ((Desc & MachO::N_WEAK_DEF) || (Desc & MachO::N_WEAK_REF))
62     return Linkage::Weak;
63   return Linkage::Strong;
64 }
65 
66 Scope MachOLinkGraphBuilder::getScope(StringRef Name, uint8_t Type) {
67   if (Name.startswith("l"))
68     return Scope::Local;
69   if (Type & MachO::N_PEXT)
70     return Scope::Hidden;
71   if (Type & MachO::N_EXT)
72     return Scope::Default;
73   return Scope::Local;
74 }
75 
76 bool MachOLinkGraphBuilder::isAltEntry(const NormalizedSymbol &NSym) {
77   return NSym.Desc & MachO::N_ALT_ENTRY;
78 }
79 
80 unsigned
81 MachOLinkGraphBuilder::getPointerSize(const object::MachOObjectFile &Obj) {
82   return Obj.is64Bit() ? 8 : 4;
83 }
84 
85 support::endianness
86 MachOLinkGraphBuilder::getEndianness(const object::MachOObjectFile &Obj) {
87   return Obj.isLittleEndian() ? support::little : support::big;
88 }
89 
90 Section &MachOLinkGraphBuilder::getCommonSection() {
91   if (!CommonSection) {
92     auto Prot = static_cast<sys::Memory::ProtectionFlags>(
93         sys::Memory::MF_READ | sys::Memory::MF_WRITE);
94     CommonSection = &G->createSection(CommonSectionName, Prot);
95   }
96   return *CommonSection;
97 }
98 
99 Error MachOLinkGraphBuilder::createNormalizedSections() {
100   // Build normalized sections. Verifies that section data is in-range (for
101   // sections with content) and that address ranges are non-overlapping.
102 
103   LLVM_DEBUG(dbgs() << "Creating normalized sections...\n");
104 
105   for (auto &SecRef : Obj.sections()) {
106     NormalizedSection NSec;
107     uint32_t DataOffset = 0;
108 
109     auto SecIndex = Obj.getSectionIndex(SecRef.getRawDataRefImpl());
110 
111     auto Name = SecRef.getName();
112     if (!Name)
113       return Name.takeError();
114 
115     if (Obj.is64Bit()) {
116       const MachO::section_64 &Sec64 =
117           Obj.getSection64(SecRef.getRawDataRefImpl());
118 
119       NSec.Address = Sec64.addr;
120       NSec.Size = Sec64.size;
121       NSec.Alignment = 1ULL << Sec64.align;
122       NSec.Flags = Sec64.flags;
123       DataOffset = Sec64.offset;
124     } else {
125       const MachO::section &Sec32 = Obj.getSection(SecRef.getRawDataRefImpl());
126       NSec.Address = Sec32.addr;
127       NSec.Size = Sec32.size;
128       NSec.Alignment = 1ULL << Sec32.align;
129       NSec.Flags = Sec32.flags;
130       DataOffset = Sec32.offset;
131     }
132 
133     LLVM_DEBUG({
134       dbgs() << "  " << *Name << ": " << formatv("{0:x16}", NSec.Address)
135              << " -- " << formatv("{0:x16}", NSec.Address + NSec.Size)
136              << ", align: " << NSec.Alignment << ", index: " << SecIndex
137              << "\n";
138     });
139 
140     // Get the section data if any.
141     {
142       unsigned SectionType = NSec.Flags & MachO::SECTION_TYPE;
143       if (SectionType != MachO::S_ZEROFILL &&
144           SectionType != MachO::S_GB_ZEROFILL) {
145 
146         if (DataOffset + NSec.Size > Obj.getData().size())
147           return make_error<JITLinkError>(
148               "Section data extends past end of file");
149 
150         NSec.Data = Obj.getData().data() + DataOffset;
151       }
152     }
153 
154     // Get prot flags.
155     // FIXME: Make sure this test is correct (it's probably missing cases
156     // as-is).
157     sys::Memory::ProtectionFlags Prot;
158     if (NSec.Flags & MachO::S_ATTR_PURE_INSTRUCTIONS)
159       Prot = static_cast<sys::Memory::ProtectionFlags>(sys::Memory::MF_READ |
160                                                        sys::Memory::MF_EXEC);
161     else
162       Prot = static_cast<sys::Memory::ProtectionFlags>(sys::Memory::MF_READ |
163                                                        sys::Memory::MF_WRITE);
164 
165     NSec.GraphSection = &G->createSection(*Name, Prot);
166     IndexToSection.insert(std::make_pair(SecIndex, std::move(NSec)));
167   }
168 
169   std::vector<NormalizedSection *> Sections;
170   Sections.reserve(IndexToSection.size());
171   for (auto &KV : IndexToSection)
172     Sections.push_back(&KV.second);
173 
174   // If we didn't end up creating any sections then bail out. The code below
175   // assumes that we have at least one section.
176   if (Sections.empty())
177     return Error::success();
178 
179   llvm::sort(Sections,
180              [](const NormalizedSection *LHS, const NormalizedSection *RHS) {
181                assert(LHS && RHS && "Null section?");
182                if (LHS->Address != RHS->Address)
183                  return LHS->Address < RHS->Address;
184                return LHS->Size < RHS->Size;
185              });
186 
187   for (unsigned I = 0, E = Sections.size() - 1; I != E; ++I) {
188     auto &Cur = *Sections[I];
189     auto &Next = *Sections[I + 1];
190     if (Next.Address < Cur.Address + Cur.Size)
191       return make_error<JITLinkError>(
192           "Address range for section " + Cur.GraphSection->getName() +
193           formatv(" [ {0:x16} -- {1:x16} ] ", Cur.Address,
194                   Cur.Address + Cur.Size) +
195           "overlaps " +
196           formatv(" [ {0:x16} -- {1:x16} ] ", Next.Address,
197                   Next.Address + Next.Size));
198   }
199 
200   return Error::success();
201 }
202 
203 Error MachOLinkGraphBuilder::createNormalizedSymbols() {
204   LLVM_DEBUG(dbgs() << "Creating normalized symbols...\n");
205 
206   for (auto &SymRef : Obj.symbols()) {
207 
208     unsigned SymbolIndex = Obj.getSymbolIndex(SymRef.getRawDataRefImpl());
209     uint64_t Value;
210     uint32_t NStrX;
211     uint8_t Type;
212     uint8_t Sect;
213     uint16_t Desc;
214 
215     if (Obj.is64Bit()) {
216       const MachO::nlist_64 &NL64 =
217           Obj.getSymbol64TableEntry(SymRef.getRawDataRefImpl());
218       Value = NL64.n_value;
219       NStrX = NL64.n_strx;
220       Type = NL64.n_type;
221       Sect = NL64.n_sect;
222       Desc = NL64.n_desc;
223     } else {
224       const MachO::nlist &NL32 =
225           Obj.getSymbolTableEntry(SymRef.getRawDataRefImpl());
226       Value = NL32.n_value;
227       NStrX = NL32.n_strx;
228       Type = NL32.n_type;
229       Sect = NL32.n_sect;
230       Desc = NL32.n_desc;
231     }
232 
233     // Skip stabs.
234     // FIXME: Are there other symbols we should be skipping?
235     if (Type & MachO::N_STAB)
236       continue;
237 
238     Optional<StringRef> Name;
239     if (NStrX) {
240       if (auto NameOrErr = SymRef.getName())
241         Name = *NameOrErr;
242       else
243         return NameOrErr.takeError();
244     }
245 
246     LLVM_DEBUG({
247       dbgs() << "  ";
248       if (!Name)
249         dbgs() << "<anonymous symbol>";
250       else
251         dbgs() << *Name;
252       dbgs() << ": value = " << formatv("{0:x16}", Value)
253              << ", type = " << formatv("{0:x2}", Type)
254              << ", desc = " << formatv("{0:x4}", Desc) << ", sect = ";
255       if (Sect)
256         dbgs() << static_cast<unsigned>(Sect - 1);
257       else
258         dbgs() << "none";
259       dbgs() << "\n";
260     });
261 
262     // If this symbol has a section, sanity check that the addresses line up.
263     NormalizedSection *NSec = nullptr;
264     if (Sect != 0) {
265       if (auto NSecOrErr = findSectionByIndex(Sect - 1))
266         NSec = &*NSecOrErr;
267       else
268         return NSecOrErr.takeError();
269 
270       if (Value < NSec->Address || Value > NSec->Address + NSec->Size)
271         return make_error<JITLinkError>("Symbol address does not fall within "
272                                         "section");
273     }
274 
275     IndexToSymbol[SymbolIndex] =
276         &createNormalizedSymbol(*Name, Value, Type, Sect, Desc,
277                                 getLinkage(Type), getScope(*Name, Type));
278   }
279 
280   return Error::success();
281 }
282 
283 void MachOLinkGraphBuilder::addSectionStartSymAndBlock(
284     Section &GraphSec, uint64_t Address, const char *Data, uint64_t Size,
285     uint32_t Alignment, bool IsLive) {
286   Block &B =
287       Data ? G->createContentBlock(GraphSec, StringRef(Data, Size), Address,
288                                    Alignment, 0)
289            : G->createZeroFillBlock(GraphSec, Size, Address, Alignment, 0);
290   auto &Sym = G->addAnonymousSymbol(B, 0, Size, false, IsLive);
291   assert(!AddrToCanonicalSymbol.count(Sym.getAddress()) &&
292          "Anonymous block start symbol clashes with existing symbol address");
293   AddrToCanonicalSymbol[Sym.getAddress()] = &Sym;
294 }
295 
296 Error MachOLinkGraphBuilder::graphifyRegularSymbols() {
297 
298   LLVM_DEBUG(dbgs() << "Creating graph symbols...\n");
299 
300   /// We only have 256 section indexes: Use a vector rather than a map.
301   std::vector<std::vector<NormalizedSymbol *>> SecIndexToSymbols;
302   SecIndexToSymbols.resize(256);
303 
304   // Create commons, externs, and absolutes, and partition all other symbols by
305   // section.
306   for (auto &KV : IndexToSymbol) {
307     auto &NSym = *KV.second;
308 
309     switch (NSym.Type & MachO::N_TYPE) {
310     case MachO::N_UNDF:
311       if (NSym.Value) {
312         if (!NSym.Name)
313           return make_error<JITLinkError>("Anonymous common symbol at index " +
314                                           Twine(KV.first));
315         NSym.GraphSymbol = &G->addCommonSymbol(
316             *NSym.Name, NSym.S, getCommonSection(), NSym.Value, 0,
317             1ull << MachO::GET_COMM_ALIGN(NSym.Desc),
318             NSym.Desc & MachO::N_NO_DEAD_STRIP);
319       } else {
320         if (!NSym.Name)
321           return make_error<JITLinkError>("Anonymous external symbol at "
322                                           "index " +
323                                           Twine(KV.first));
324         NSym.GraphSymbol = &G->addExternalSymbol(*NSym.Name, 0);
325       }
326       break;
327     case MachO::N_ABS:
328       if (!NSym.Name)
329         return make_error<JITLinkError>("Anonymous absolute symbol at index " +
330                                         Twine(KV.first));
331       NSym.GraphSymbol = &G->addAbsoluteSymbol(
332           *NSym.Name, NSym.Value, 0, Linkage::Strong, Scope::Default,
333           NSym.Desc & MachO::N_NO_DEAD_STRIP);
334       break;
335     case MachO::N_SECT:
336       SecIndexToSymbols[NSym.Sect - 1].push_back(&NSym);
337       break;
338     case MachO::N_PBUD:
339       return make_error<JITLinkError>(
340           "Unupported N_PBUD symbol " +
341           (NSym.Name ? ("\"" + *NSym.Name + "\"") : Twine("<anon>")) +
342           " at index " + Twine(KV.first));
343     case MachO::N_INDR:
344       return make_error<JITLinkError>(
345           "Unupported N_INDR symbol " +
346           (NSym.Name ? ("\"" + *NSym.Name + "\"") : Twine("<anon>")) +
347           " at index " + Twine(KV.first));
348     default:
349       return make_error<JITLinkError>(
350           "Unrecognized symbol type " + Twine(NSym.Type & MachO::N_TYPE) +
351           " for symbol " +
352           (NSym.Name ? ("\"" + *NSym.Name + "\"") : Twine("<anon>")) +
353           " at index " + Twine(KV.first));
354     }
355   }
356 
357   // Loop over sections performing regular graphification for those that
358   // don't have custom parsers.
359   for (auto &KV : IndexToSection) {
360     auto SecIndex = KV.first;
361     auto &NSec = KV.second;
362 
363     // Skip sections with custom parsers.
364     if (CustomSectionParserFunctions.count(NSec.GraphSection->getName())) {
365       LLVM_DEBUG({
366         dbgs() << "  Skipping section " << NSec.GraphSection->getName()
367                << " as it has a custom parser.\n";
368       });
369       continue;
370     } else
371       LLVM_DEBUG({
372         dbgs() << "  Processing section " << NSec.GraphSection->getName()
373                << "...\n";
374       });
375 
376     bool SectionIsNoDeadStrip = NSec.Flags & MachO::S_ATTR_NO_DEAD_STRIP;
377     bool SectionIsText = NSec.Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
378 
379     auto &SecNSymStack = SecIndexToSymbols[SecIndex];
380 
381     // If this section is non-empty but there are no symbols covering it then
382     // create one block and anonymous symbol to cover the entire section.
383     if (SecNSymStack.empty()) {
384       if (NSec.Size > 0) {
385         LLVM_DEBUG({
386           dbgs() << "    Section non-empty, but contains no symbols. "
387                     "Creating anonymous block to cover "
388                  << formatv("{0:x16}", NSec.Address) << " -- "
389                  << formatv("{0:x16}", NSec.Address + NSec.Size) << "\n";
390         });
391         addSectionStartSymAndBlock(*NSec.GraphSection, NSec.Address, NSec.Data,
392                                    NSec.Size, NSec.Alignment,
393                                    SectionIsNoDeadStrip);
394       } else
395         LLVM_DEBUG({
396           dbgs() << "    Section empty and contains no symbols. Skipping.\n";
397         });
398       continue;
399     }
400 
401     // Sort the symbol stack in by address, alt-entry status, scope, and name.
402     // We sort in reverse order so that symbols will be visited in the right
403     // order when we pop off the stack below.
404     llvm::sort(SecNSymStack, [](const NormalizedSymbol *LHS,
405                                 const NormalizedSymbol *RHS) {
406       if (LHS->Value != RHS->Value)
407         return LHS->Value > RHS->Value;
408       if (isAltEntry(*LHS) != isAltEntry(*RHS))
409         return isAltEntry(*RHS);
410       if (LHS->S != RHS->S)
411         return static_cast<uint8_t>(LHS->S) < static_cast<uint8_t>(RHS->S);
412       return LHS->Name < RHS->Name;
413     });
414 
415     // The first symbol in a section can not be an alt-entry symbol.
416     if (!SecNSymStack.empty() && isAltEntry(*SecNSymStack.back()))
417       return make_error<JITLinkError>(
418           "First symbol in " + NSec.GraphSection->getName() + " is alt-entry");
419 
420     // If the section is non-empty but there is no symbol covering the start
421     // address then add an anonymous one.
422     if (SecNSymStack.back()->Value != NSec.Address) {
423       auto AnonBlockSize = SecNSymStack.back()->Value - NSec.Address;
424       LLVM_DEBUG({
425         dbgs() << "    Section start not covered by symbol. "
426                << "Creating anonymous block to cover [ "
427                << formatv("{0:x16}", NSec.Address) << " -- "
428                << formatv("{0:x16}", NSec.Address + AnonBlockSize) << " ]\n";
429       });
430       addSectionStartSymAndBlock(*NSec.GraphSection, NSec.Address, NSec.Data,
431                                  AnonBlockSize, NSec.Alignment,
432                                  SectionIsNoDeadStrip);
433     }
434 
435     // Visit section symbols in order by popping off the reverse-sorted stack,
436     // building blocks for each alt-entry chain and creating symbols as we go.
437     while (!SecNSymStack.empty()) {
438       SmallVector<NormalizedSymbol *, 8> BlockSyms;
439 
440       BlockSyms.push_back(SecNSymStack.back());
441       SecNSymStack.pop_back();
442       while (!SecNSymStack.empty() &&
443              (isAltEntry(*SecNSymStack.back()) ||
444               SecNSymStack.back()->Value == BlockSyms.back()->Value)) {
445         BlockSyms.push_back(SecNSymStack.back());
446         SecNSymStack.pop_back();
447       }
448 
449       // BlockNSyms now contains the block symbols in reverse canonical order.
450       JITTargetAddress BlockStart = BlockSyms.front()->Value;
451       JITTargetAddress BlockEnd = SecNSymStack.empty()
452                                       ? NSec.Address + NSec.Size
453                                       : SecNSymStack.back()->Value;
454       JITTargetAddress BlockOffset = BlockStart - NSec.Address;
455       JITTargetAddress BlockSize = BlockEnd - BlockStart;
456 
457       LLVM_DEBUG({
458         dbgs() << "    Creating block for " << formatv("{0:x16}", BlockStart)
459                << " -- " << formatv("{0:x16}", BlockEnd) << ": "
460                << NSec.GraphSection->getName() << " + "
461                << formatv("{0:x16}", BlockOffset) << " with "
462                << BlockSyms.size() << " symbol(s)...\n";
463       });
464 
465       Block &B =
466           NSec.Data
467               ? G->createContentBlock(
468                     *NSec.GraphSection,
469                     StringRef(NSec.Data + BlockOffset, BlockSize), BlockStart,
470                     NSec.Alignment, BlockStart % NSec.Alignment)
471               : G->createZeroFillBlock(*NSec.GraphSection, BlockSize,
472                                        BlockStart, NSec.Alignment,
473                                        BlockStart % NSec.Alignment);
474 
475       Optional<JITTargetAddress> LastCanonicalAddr;
476       JITTargetAddress SymEnd = BlockEnd;
477       while (!BlockSyms.empty()) {
478         auto &NSym = *BlockSyms.back();
479         BlockSyms.pop_back();
480 
481         bool SymLive =
482             (NSym.Desc & MachO::N_NO_DEAD_STRIP) || SectionIsNoDeadStrip;
483 
484         LLVM_DEBUG({
485           dbgs() << "      " << formatv("{0:x16}", NSym.Value) << " -- "
486                  << formatv("{0:x16}", SymEnd) << ": ";
487           if (!NSym.Name)
488             dbgs() << "<anonymous symbol>";
489           else
490             dbgs() << NSym.Name;
491           if (SymLive)
492             dbgs() << " [no-dead-strip]";
493           if (LastCanonicalAddr == NSym.Value)
494             dbgs() << " [non-canonical]";
495           dbgs() << "\n";
496         });
497 
498         auto &Sym =
499             NSym.Name
500                 ? G->addDefinedSymbol(B, NSym.Value - BlockStart, *NSym.Name,
501                                       SymEnd - NSym.Value, NSym.L, NSym.S,
502                                       SectionIsText, SymLive)
503                 : G->addAnonymousSymbol(B, NSym.Value - BlockStart,
504                                         SymEnd - NSym.Value, SectionIsText,
505                                         SymLive);
506         NSym.GraphSymbol = &Sym;
507         if (LastCanonicalAddr != Sym.getAddress()) {
508           if (LastCanonicalAddr)
509             SymEnd = *LastCanonicalAddr;
510           LastCanonicalAddr = Sym.getAddress();
511           setCanonicalSymbol(Sym);
512         }
513       }
514     }
515   }
516 
517   return Error::success();
518 }
519 
520 Error MachOLinkGraphBuilder::graphifySectionsWithCustomParsers() {
521   // Graphify special sections.
522   for (auto &KV : IndexToSection) {
523     auto &NSec = KV.second;
524 
525     auto HI = CustomSectionParserFunctions.find(NSec.GraphSection->getName());
526     if (HI != CustomSectionParserFunctions.end()) {
527       auto &Parse = HI->second;
528       if (auto Err = Parse(NSec))
529         return Err;
530     }
531   }
532 
533   return Error::success();
534 }
535 
536 } // end namespace jitlink
537 } // end namespace llvm
538