1 //===-- llvm-jitlink-macho.cpp -- MachO parsing support for llvm-jitlink --===//
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 // MachO parsing support for llvm-jitlink.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm-jitlink.h"
14 
15 #include "llvm/Support/Error.h"
16 #include "llvm/Support/Path.h"
17 
18 #define DEBUG_TYPE "llvm_jitlink"
19 
20 using namespace llvm;
21 using namespace llvm::jitlink;
22 
isMachOGOTSection(Section & S)23 static bool isMachOGOTSection(Section &S) { return S.getName() == "$__GOT"; }
24 
isMachOStubsSection(Section & S)25 static bool isMachOStubsSection(Section &S) {
26   return S.getName() == "$__STUBS";
27 }
28 
getFirstRelocationEdge(LinkGraph & G,Block & B)29 static Expected<Edge &> getFirstRelocationEdge(LinkGraph &G, Block &B) {
30   auto EItr = std::find_if(B.edges().begin(), B.edges().end(),
31                            [](Edge &E) { return E.isRelocation(); });
32   if (EItr == B.edges().end())
33     return make_error<StringError>("GOT entry in " + G.getName() + ", \"" +
34                                        B.getSection().getName() +
35                                        "\" has no relocations",
36                                    inconvertibleErrorCode());
37   return *EItr;
38 }
39 
getMachOGOTTarget(LinkGraph & G,Block & B)40 static Expected<Symbol &> getMachOGOTTarget(LinkGraph &G, Block &B) {
41   auto E = getFirstRelocationEdge(G, B);
42   if (!E)
43     return E.takeError();
44   auto &TargetSym = E->getTarget();
45   if (!TargetSym.hasName())
46     return make_error<StringError>(
47         "GOT entry in " + G.getName() + ", \"" +
48             TargetSym.getBlock().getSection().getName() +
49             "\" points to anonymous "
50             "symbol",
51         inconvertibleErrorCode());
52   return TargetSym;
53 }
54 
getMachOStubTarget(LinkGraph & G,Block & B)55 static Expected<Symbol &> getMachOStubTarget(LinkGraph &G, Block &B) {
56   auto E = getFirstRelocationEdge(G, B);
57   if (!E)
58     return E.takeError();
59   auto &GOTSym = E->getTarget();
60   if (!GOTSym.isDefined() || !isMachOGOTSection(GOTSym.getBlock().getSection()))
61     return make_error<StringError>(
62         "Stubs entry in " + G.getName() + ", \"" +
63             GOTSym.getBlock().getSection().getName() +
64             "\" does not point to GOT entry",
65         inconvertibleErrorCode());
66   return getMachOGOTTarget(G, GOTSym.getBlock());
67 }
68 
69 namespace llvm {
70 
registerMachOGraphInfo(Session & S,LinkGraph & G)71 Error registerMachOGraphInfo(Session &S, LinkGraph &G) {
72   auto FileName = sys::path::filename(G.getName());
73   if (S.FileInfos.count(FileName)) {
74     return make_error<StringError>("When -check is passed, file names must be "
75                                    "distinct (duplicate: \"" +
76                                        FileName + "\")",
77                                    inconvertibleErrorCode());
78   }
79 
80   auto &FileInfo = S.FileInfos[FileName];
81   LLVM_DEBUG({
82     dbgs() << "Registering MachO file info for \"" << FileName << "\"\n";
83   });
84   for (auto &Sec : G.sections()) {
85     LLVM_DEBUG({
86       dbgs() << "  Section \"" << Sec.getName() << "\": "
87              << (llvm::empty(Sec.symbols()) ? "empty. skipping."
88                                             : "processing...")
89              << "\n";
90     });
91 
92     // Skip empty sections.
93     if (llvm::empty(Sec.symbols()))
94       continue;
95 
96     if (FileInfo.SectionInfos.count(Sec.getName()))
97       return make_error<StringError>("Encountered duplicate section name \"" +
98                                          Sec.getName() + "\" in \"" + FileName +
99                                          "\"",
100                                      inconvertibleErrorCode());
101 
102     bool isGOTSection = isMachOGOTSection(Sec);
103     bool isStubsSection = isMachOStubsSection(Sec);
104 
105     bool SectionContainsContent = false;
106     bool SectionContainsZeroFill = false;
107 
108     auto *FirstSym = *Sec.symbols().begin();
109     auto *LastSym = FirstSym;
110     for (auto *Sym : Sec.symbols()) {
111       if (Sym->getAddress() < FirstSym->getAddress())
112         FirstSym = Sym;
113       if (Sym->getAddress() > LastSym->getAddress())
114         LastSym = Sym;
115       if (isGOTSection) {
116         if (Sym->isSymbolZeroFill())
117           return make_error<StringError>("zero-fill atom in GOT section",
118                                          inconvertibleErrorCode());
119 
120         if (auto TS = getMachOGOTTarget(G, Sym->getBlock()))
121           FileInfo.GOTEntryInfos[TS->getName()] = {Sym->getSymbolContent(),
122                                                    Sym->getAddress()};
123         else
124           return TS.takeError();
125         SectionContainsContent = true;
126       } else if (isStubsSection) {
127         if (Sym->isSymbolZeroFill())
128           return make_error<StringError>("zero-fill atom in Stub section",
129                                          inconvertibleErrorCode());
130 
131         if (auto TS = getMachOStubTarget(G, Sym->getBlock()))
132           FileInfo.StubInfos[TS->getName()] = {Sym->getSymbolContent(),
133                                                Sym->getAddress()};
134         else
135           return TS.takeError();
136         SectionContainsContent = true;
137       } else if (Sym->hasName()) {
138         if (Sym->isSymbolZeroFill()) {
139           S.SymbolInfos[Sym->getName()] = {Sym->getSize(), Sym->getAddress()};
140           SectionContainsZeroFill = true;
141         } else {
142           S.SymbolInfos[Sym->getName()] = {Sym->getSymbolContent(),
143                                            Sym->getAddress()};
144           SectionContainsContent = true;
145         }
146       }
147     }
148 
149     JITTargetAddress SecAddr = FirstSym->getAddress();
150     uint64_t SecSize =
151         (LastSym->getBlock().getAddress() + LastSym->getBlock().getSize()) -
152         SecAddr;
153 
154     if (SectionContainsZeroFill && SectionContainsContent)
155       return make_error<StringError>("Mixed zero-fill and content sections not "
156                                      "supported yet",
157                                      inconvertibleErrorCode());
158     if (SectionContainsZeroFill)
159       FileInfo.SectionInfos[Sec.getName()] = {SecSize, SecAddr};
160     else
161       FileInfo.SectionInfos[Sec.getName()] = {
162           ArrayRef<char>(FirstSym->getBlock().getContent().data(), SecSize),
163           SecAddr};
164   }
165 
166   return Error::success();
167 }
168 
169 } // end namespace llvm
170