xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/JITLink/JITLink.cpp (revision 179219ea046f46927d6478d43431e8b541703539)
1 //===------------- JITLink.cpp - Core Run-time JIT linker APIs ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/ExecutionEngine/JITLink/JITLink.h"
11 
12 #include "llvm/BinaryFormat/Magic.h"
13 #include "llvm/ExecutionEngine/JITLink/ELF.h"
14 #include "llvm/ExecutionEngine/JITLink/MachO.h"
15 #include "llvm/Support/Format.h"
16 #include "llvm/Support/ManagedStatic.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 #include "llvm/Support/raw_ostream.h"
19 
20 using namespace llvm;
21 using namespace llvm::object;
22 
23 #define DEBUG_TYPE "jitlink"
24 
25 namespace {
26 
27 enum JITLinkErrorCode { GenericJITLinkError = 1 };
28 
29 // FIXME: This class is only here to support the transition to llvm::Error. It
30 // will be removed once this transition is complete. Clients should prefer to
31 // deal with the Error value directly, rather than converting to error_code.
32 class JITLinkerErrorCategory : public std::error_category {
33 public:
34   const char *name() const noexcept override { return "runtimedyld"; }
35 
36   std::string message(int Condition) const override {
37     switch (static_cast<JITLinkErrorCode>(Condition)) {
38     case GenericJITLinkError:
39       return "Generic JITLink error";
40     }
41     llvm_unreachable("Unrecognized JITLinkErrorCode");
42   }
43 };
44 
45 static ManagedStatic<JITLinkerErrorCategory> JITLinkerErrorCategory;
46 
47 } // namespace
48 
49 namespace llvm {
50 namespace jitlink {
51 
52 char JITLinkError::ID = 0;
53 
54 void JITLinkError::log(raw_ostream &OS) const { OS << ErrMsg << "\n"; }
55 
56 std::error_code JITLinkError::convertToErrorCode() const {
57   return std::error_code(GenericJITLinkError, *JITLinkerErrorCategory);
58 }
59 
60 const char *getGenericEdgeKindName(Edge::Kind K) {
61   switch (K) {
62   case Edge::Invalid:
63     return "INVALID RELOCATION";
64   case Edge::KeepAlive:
65     return "Keep-Alive";
66   default:
67     return "<Unrecognized edge kind>";
68   }
69 }
70 
71 const char *getLinkageName(Linkage L) {
72   switch (L) {
73   case Linkage::Strong:
74     return "strong";
75   case Linkage::Weak:
76     return "weak";
77   }
78   llvm_unreachable("Unrecognized llvm.jitlink.Linkage enum");
79 }
80 
81 const char *getScopeName(Scope S) {
82   switch (S) {
83   case Scope::Default:
84     return "default";
85   case Scope::Hidden:
86     return "hidden";
87   case Scope::Local:
88     return "local";
89   }
90   llvm_unreachable("Unrecognized llvm.jitlink.Scope enum");
91 }
92 
93 raw_ostream &operator<<(raw_ostream &OS, const Block &B) {
94   return OS << formatv("{0:x16}", B.getAddress()) << " -- "
95             << formatv("{0:x16}", B.getAddress() + B.getSize()) << ": "
96             << "size = " << formatv("{0:x}", B.getSize()) << ", "
97             << (B.isZeroFill() ? "zero-fill" : "content")
98             << ", align = " << B.getAlignment()
99             << ", align-ofs = " << B.getAlignmentOffset()
100             << ", section = " << B.getSection().getName();
101 }
102 
103 raw_ostream &operator<<(raw_ostream &OS, const Symbol &Sym) {
104   OS << "<";
105   if (Sym.getName().empty())
106     OS << "*anon*";
107   else
108     OS << Sym.getName();
109   OS << ": flags = ";
110   switch (Sym.getLinkage()) {
111   case Linkage::Strong:
112     OS << 'S';
113     break;
114   case Linkage::Weak:
115     OS << 'W';
116     break;
117   }
118   switch (Sym.getScope()) {
119   case Scope::Default:
120     OS << 'D';
121     break;
122   case Scope::Hidden:
123     OS << 'H';
124     break;
125   case Scope::Local:
126     OS << 'L';
127     break;
128   }
129   OS << (Sym.isLive() ? '+' : '-')
130      << ", size = " << formatv("{0:x}", Sym.getSize())
131      << ", addr = " << formatv("{0:x16}", Sym.getAddress()) << " ("
132      << formatv("{0:x16}", Sym.getAddressable().getAddress()) << " + "
133      << formatv("{0:x}", Sym.getOffset());
134   if (Sym.isDefined())
135     OS << " " << Sym.getBlock().getSection().getName();
136   OS << ")>";
137   return OS;
138 }
139 
140 void printEdge(raw_ostream &OS, const Block &B, const Edge &E,
141                StringRef EdgeKindName) {
142   OS << "edge@" << formatv("{0:x16}", B.getAddress() + E.getOffset()) << ": "
143      << formatv("{0:x16}", B.getAddress()) << " + "
144      << formatv("{0:x}", E.getOffset()) << " -- " << EdgeKindName << " -> ";
145 
146   auto &TargetSym = E.getTarget();
147   if (TargetSym.hasName())
148     OS << TargetSym.getName();
149   else {
150     auto &TargetBlock = TargetSym.getBlock();
151     auto &TargetSec = TargetBlock.getSection();
152     JITTargetAddress SecAddress = ~JITTargetAddress(0);
153     for (auto *B : TargetSec.blocks())
154       if (B->getAddress() < SecAddress)
155         SecAddress = B->getAddress();
156 
157     JITTargetAddress SecDelta = TargetSym.getAddress() - SecAddress;
158     OS << formatv("{0:x16}", TargetSym.getAddress()) << " (section "
159        << TargetSec.getName();
160     if (SecDelta)
161       OS << " + " << formatv("{0:x}", SecDelta);
162     OS << " / block " << formatv("{0:x16}", TargetBlock.getAddress());
163     if (TargetSym.getOffset())
164       OS << " + " << formatv("{0:x}", TargetSym.getOffset());
165     OS << ")";
166   }
167 
168   if (E.getAddend() != 0)
169     OS << " + " << E.getAddend();
170 }
171 
172 Section::~Section() {
173   for (auto *Sym : Symbols)
174     Sym->~Symbol();
175   for (auto *B : Blocks)
176     B->~Block();
177 }
178 
179 Block &LinkGraph::splitBlock(Block &B, size_t SplitIndex,
180                              SplitBlockCache *Cache) {
181 
182   assert(SplitIndex > 0 && "splitBlock can not be called with SplitIndex == 0");
183 
184   // If the split point covers all of B then just return B.
185   if (SplitIndex == B.getSize())
186     return B;
187 
188   assert(SplitIndex < B.getSize() && "SplitIndex out of range");
189 
190   // Create the new block covering [ 0, SplitIndex ).
191   auto &NewBlock =
192       B.isZeroFill()
193           ? createZeroFillBlock(B.getSection(), SplitIndex, B.getAddress(),
194                                 B.getAlignment(), B.getAlignmentOffset())
195           : createContentBlock(
196                 B.getSection(), B.getContent().substr(0, SplitIndex),
197                 B.getAddress(), B.getAlignment(), B.getAlignmentOffset());
198 
199   // Modify B to cover [ SplitIndex, B.size() ).
200   B.setAddress(B.getAddress() + SplitIndex);
201   B.setContent(B.getContent().substr(SplitIndex));
202   B.setAlignmentOffset((B.getAlignmentOffset() + SplitIndex) %
203                        B.getAlignment());
204 
205   // Handle edge transfer/update.
206   {
207     // Copy edges to NewBlock (recording their iterators so that we can remove
208     // them from B), and update of Edges remaining on B.
209     std::vector<Block::edge_iterator> EdgesToRemove;
210     for (auto I = B.edges().begin(); I != B.edges().end();) {
211       if (I->getOffset() < SplitIndex) {
212         NewBlock.addEdge(*I);
213         I = B.removeEdge(I);
214       } else {
215         I->setOffset(I->getOffset() - SplitIndex);
216         ++I;
217       }
218     }
219   }
220 
221   // Handle symbol transfer/update.
222   {
223     // Initialize the symbols cache if necessary.
224     SplitBlockCache LocalBlockSymbolsCache;
225     if (!Cache)
226       Cache = &LocalBlockSymbolsCache;
227     if (*Cache == None) {
228       *Cache = SplitBlockCache::value_type();
229       for (auto *Sym : B.getSection().symbols())
230         if (&Sym->getBlock() == &B)
231           (*Cache)->push_back(Sym);
232 
233       llvm::sort(**Cache, [](const Symbol *LHS, const Symbol *RHS) {
234         return LHS->getOffset() > RHS->getOffset();
235       });
236     }
237     auto &BlockSymbols = **Cache;
238 
239     // Transfer all symbols with offset less than SplitIndex to NewBlock.
240     while (!BlockSymbols.empty() &&
241            BlockSymbols.back()->getOffset() < SplitIndex) {
242       BlockSymbols.back()->setBlock(NewBlock);
243       BlockSymbols.pop_back();
244     }
245 
246     // Update offsets for all remaining symbols in B.
247     for (auto *Sym : BlockSymbols)
248       Sym->setOffset(Sym->getOffset() - SplitIndex);
249   }
250 
251   return NewBlock;
252 }
253 
254 void LinkGraph::dump(raw_ostream &OS,
255                      std::function<StringRef(Edge::Kind)> EdgeKindToName) {
256   if (!EdgeKindToName)
257     EdgeKindToName = [](Edge::Kind K) { return StringRef(); };
258 
259   OS << "Symbols:\n";
260   for (auto *Sym : defined_symbols()) {
261     OS << "  " << format("0x%016" PRIx64, Sym->getAddress()) << ": " << *Sym
262        << "\n";
263     if (Sym->isDefined()) {
264       for (auto &E : Sym->getBlock().edges()) {
265         OS << "    ";
266         StringRef EdgeName = (E.getKind() < Edge::FirstRelocation
267                                   ? getGenericEdgeKindName(E.getKind())
268                                   : EdgeKindToName(E.getKind()));
269 
270         if (!EdgeName.empty())
271           printEdge(OS, Sym->getBlock(), E, EdgeName);
272         else {
273           auto EdgeNumberString = std::to_string(E.getKind());
274           printEdge(OS, Sym->getBlock(), E, EdgeNumberString);
275         }
276         OS << "\n";
277       }
278     }
279   }
280 
281   OS << "Absolute symbols:\n";
282   for (auto *Sym : absolute_symbols())
283     OS << "  " << format("0x%016" PRIx64, Sym->getAddress()) << ": " << *Sym
284        << "\n";
285 
286   OS << "External symbols:\n";
287   for (auto *Sym : external_symbols())
288     OS << "  " << format("0x%016" PRIx64, Sym->getAddress()) << ": " << *Sym
289        << "\n";
290 }
291 
292 raw_ostream &operator<<(raw_ostream &OS, const SymbolLookupFlags &LF) {
293   switch (LF) {
294   case SymbolLookupFlags::RequiredSymbol:
295     return OS << "RequiredSymbol";
296   case SymbolLookupFlags::WeaklyReferencedSymbol:
297     return OS << "WeaklyReferencedSymbol";
298   }
299   llvm_unreachable("Unrecognized lookup flags");
300 }
301 
302 void JITLinkAsyncLookupContinuation::anchor() {}
303 
304 JITLinkContext::~JITLinkContext() {}
305 
306 bool JITLinkContext::shouldAddDefaultTargetPasses(const Triple &TT) const {
307   return true;
308 }
309 
310 LinkGraphPassFunction JITLinkContext::getMarkLivePass(const Triple &TT) const {
311   return LinkGraphPassFunction();
312 }
313 
314 Error JITLinkContext::modifyPassConfig(const Triple &TT,
315                                        PassConfiguration &Config) {
316   return Error::success();
317 }
318 
319 Error markAllSymbolsLive(LinkGraph &G) {
320   for (auto *Sym : G.defined_symbols())
321     Sym->setLive(true);
322   return Error::success();
323 }
324 
325 Expected<std::unique_ptr<LinkGraph>>
326 createLinkGraphFromObject(MemoryBufferRef ObjectBuffer) {
327   auto Magic = identify_magic(ObjectBuffer.getBuffer());
328   switch (Magic) {
329   case file_magic::macho_object:
330     return createLinkGraphFromMachOObject(std::move(ObjectBuffer));
331   case file_magic::elf_relocatable:
332     return createLinkGraphFromELFObject(std::move(ObjectBuffer));
333   default:
334     return make_error<JITLinkError>("Unsupported file format");
335   };
336 }
337 
338 void link(std::unique_ptr<LinkGraph> G, std::unique_ptr<JITLinkContext> Ctx) {
339   switch (G->getTargetTriple().getObjectFormat()) {
340   case Triple::MachO:
341     return link_MachO(std::move(G), std::move(Ctx));
342   case Triple::ELF:
343     return link_ELF(std::move(G), std::move(Ctx));
344   default:
345     Ctx->notifyFailed(make_error<JITLinkError>("Unsupported object format"));
346   };
347 }
348 
349 } // end namespace jitlink
350 } // end namespace llvm
351