1 //===----- MachOLinkGraphBuilder.h - MachO LinkGraph builder ----*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // Generic MachO LinkGraph building code.
11 //===----------------------------------------------------------------------===//
13 #ifndef LIB_EXECUTIONENGINE_JITLINK_MACHOLINKGRAPHBUILDER_H
14 #define LIB_EXECUTIONENGINE_JITLINK_MACHOLINKGRAPHBUILDER_H
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ExecutionEngine/JITLink/JITLink.h"
20 #include "EHFrameSupportImpl.h"
21 #include "JITLinkGeneric.h"
22 #include "llvm/Object/MachO.h"
29 class MachOLinkGraphBuilder {
31 virtual ~MachOLinkGraphBuilder();
32 Expected<std::unique_ptr<LinkGraph>> buildGraph();
36 struct NormalizedSymbol {
37 friend class MachOLinkGraphBuilder;
40 NormalizedSymbol(Optional<StringRef> Name, uint64_t Value, uint8_t Type,
41 uint8_t Sect, uint16_t Desc, Linkage L, Scope S)
42 : Name(Name), Value(Value), Type(Type), Sect(Sect), Desc(Desc), L(L),
44 assert((!Name || !Name->empty()) && "Name must be none or non-empty");
48 NormalizedSymbol(const NormalizedSymbol &) = delete;
49 NormalizedSymbol &operator=(const NormalizedSymbol &) = delete;
50 NormalizedSymbol(NormalizedSymbol &&) = delete;
51 NormalizedSymbol &operator=(NormalizedSymbol &&) = delete;
53 Optional<StringRef> Name;
58 Linkage L = Linkage::Strong;
59 Scope S = Scope::Default;
60 Symbol *GraphSymbol = nullptr;
63 class NormalizedSection {
64 friend class MachOLinkGraphBuilder;
67 NormalizedSection() = default;
70 Section *GraphSection = nullptr;
73 uint64_t Alignment = 0;
75 const char *Data = nullptr;
78 using SectionParserFunction = std::function<Error(NormalizedSection &S)>;
80 MachOLinkGraphBuilder(const object::MachOObjectFile &Obj);
82 LinkGraph &getGraph() const { return *G; }
84 const object::MachOObjectFile &getObject() const { return Obj; }
86 void addCustomSectionParser(StringRef SectionName,
87 SectionParserFunction Parse);
89 virtual Error addRelocations() = 0;
92 template <typename... ArgTs>
93 NormalizedSymbol &createNormalizedSymbol(ArgTs &&... Args) {
94 NormalizedSymbol *Sym = reinterpret_cast<NormalizedSymbol *>(
95 Allocator.Allocate<NormalizedSymbol>());
96 new (Sym) NormalizedSymbol(std::forward<ArgTs>(Args)...);
100 /// Index is zero-based (MachO section indexes are usually one-based) and
101 /// assumed to be in-range. Client is responsible for checking.
102 NormalizedSection &getSectionByIndex(unsigned Index) {
103 auto I = IndexToSection.find(Index);
104 assert(I != IndexToSection.end() && "No section recorded at index");
108 /// Try to get the section at the given index. Will return an error if the
109 /// given index is out of range, or if no section has been added for the given
111 Expected<NormalizedSection &> findSectionByIndex(unsigned Index) {
112 auto I = IndexToSection.find(Index);
113 if (I == IndexToSection.end())
114 return make_error<JITLinkError>("No section recorded for index " +
115 formatv("{0:u}", Index));
119 /// Try to get the symbol at the given index. Will return an error if the
120 /// given index is out of range, or if no symbol has been added for the given
122 Expected<NormalizedSymbol &> findSymbolByIndex(uint64_t Index) {
123 if (Index >= IndexToSymbol.size())
124 return make_error<JITLinkError>("Symbol index out of range");
125 auto *Sym = IndexToSymbol[Index];
127 return make_error<JITLinkError>("No symbol at index " +
128 formatv("{0:u}", Index));
132 /// Returns the symbol with the highest address not greater than the search
133 /// address, or null if no such symbol exists.
134 Symbol *getSymbolByAddress(JITTargetAddress Address) {
135 auto I = AddrToCanonicalSymbol.upper_bound(Address);
136 if (I == AddrToCanonicalSymbol.begin())
138 return std::prev(I)->second;
141 /// Returns the symbol with the highest address not greater than the search
142 /// address, or an error if no such symbol exists.
143 Expected<Symbol &> findSymbolByAddress(JITTargetAddress Address) {
144 auto *Sym = getSymbolByAddress(Address);
146 if (Address < Sym->getAddress() + Sym->getSize())
148 return make_error<JITLinkError>("No symbol covering address " +
149 formatv("{0:x16}", Address));
152 static Linkage getLinkage(uint16_t Desc);
153 static Scope getScope(StringRef Name, uint8_t Type);
154 static bool isAltEntry(const NormalizedSymbol &NSym);
156 MachO::relocation_info
157 getRelocationInfo(const object::relocation_iterator RelItr) {
158 MachO::any_relocation_info ARI =
159 getObject().getRelocation(RelItr->getRawDataRefImpl());
160 MachO::relocation_info RI;
161 RI.r_address = ARI.r_word0;
162 RI.r_symbolnum = ARI.r_word1 & 0xffffff;
163 RI.r_pcrel = (ARI.r_word1 >> 24) & 1;
164 RI.r_length = (ARI.r_word1 >> 25) & 3;
165 RI.r_extern = (ARI.r_word1 >> 27) & 1;
166 RI.r_type = (ARI.r_word1 >> 28);
171 static unsigned getPointerSize(const object::MachOObjectFile &Obj);
172 static support::endianness getEndianness(const object::MachOObjectFile &Obj);
174 void setCanonicalSymbol(Symbol &Sym) {
175 auto *&CanonicalSymEntry = AddrToCanonicalSymbol[Sym.getAddress()];
176 // There should be no symbol at this address, or, if there is,
177 // it should be a zero-sized symbol from an empty section (which
178 // we can safely override).
179 assert((!CanonicalSymEntry || CanonicalSymEntry->getSize() == 0) &&
180 "Duplicate canonical symbol at address");
181 CanonicalSymEntry = &Sym;
184 Section &getCommonSection();
185 void addSectionStartSymAndBlock(Section &GraphSec, uint64_t Address,
186 const char *Data, uint64_t Size,
187 uint32_t Alignment, bool IsLive);
189 Error createNormalizedSections();
190 Error createNormalizedSymbols();
192 /// Create graph blocks and symbols for externals, absolutes, commons and
193 /// all defined symbols in sections without custom parsers.
194 Error graphifyRegularSymbols();
196 /// Create graph blocks and symbols for all sections.
197 Error graphifySectionsWithCustomParsers();
199 // Put the BumpPtrAllocator first so that we don't free any of the underlying
200 // memory until the Symbol/Addressable destructors have been run.
201 BumpPtrAllocator Allocator;
203 const object::MachOObjectFile &Obj;
204 std::unique_ptr<LinkGraph> G;
206 DenseMap<unsigned, NormalizedSection> IndexToSection;
207 Section *CommonSection = nullptr;
209 DenseMap<uint32_t, NormalizedSymbol *> IndexToSymbol;
210 std::map<JITTargetAddress, Symbol *> AddrToCanonicalSymbol;
211 StringMap<SectionParserFunction> CustomSectionParserFunctions;
214 } // end namespace jitlink
215 } // end namespace llvm
217 #endif // LIB_EXECUTIONENGINE_JITLINK_MACHOLINKGRAPHBUILDER_H