15 #define DEBUG_TYPE "jitlink" 28 return make_error<JITLinkError>(
"Object is not a relocatable MachO");
30 if (
auto Err = createNormalizedSections())
31 return std::move(Err);
33 if (
auto Err = createNormalizedSymbols())
34 return std::move(Err);
36 if (
auto Err = graphifyRegularSymbols())
37 return std::move(Err);
39 if (
auto Err = graphifySectionsWithCustomParsers())
40 return std::move(Err);
43 return std::move(Err);
51 getEndianness(Obj))) {}
55 assert(!CustomSectionParserFunctions.
count(SectionName) &&
56 "Custom parser for this section already exists");
57 CustomSectionParserFunctions[
SectionName] = std::move(Parser);
90 Section &MachOLinkGraphBuilder::getCommonSection() {
94 CommonSection = &G->createSection(CommonSectionName, Prot);
96 return *CommonSection;
99 Error MachOLinkGraphBuilder::createNormalizedSections() {
105 for (
auto &SecRef : Obj.
sections()) {
111 auto Name = SecRef.getName();
113 return Name.takeError();
123 DataOffset = Sec64.
offset;
130 DataOffset = Sec32.
offset;
136 <<
", align: " << NSec.
Alignment <<
", index: " << SecIndex
147 return make_error<JITLinkError>(
148 "Section data extends past end of file");
166 IndexToSection.insert(std::make_pair(SecIndex, std::move(NSec)));
169 std::vector<NormalizedSection *> Sections;
170 Sections.reserve(IndexToSection.size());
171 for (
auto &KV : IndexToSection)
172 Sections.push_back(&KV.second);
176 if (Sections.empty())
181 assert(LHS && RHS &&
"Null section?");
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) +
196 formatv(
" [ {0:x16} -- {1:x16} ] ", Next.Address,
197 Next.Address + Next.Size));
203 Error MachOLinkGraphBuilder::createNormalizedSymbols() {
206 for (
auto &SymRef : Obj.
symbols()) {
208 unsigned SymbolIndex = Obj.
getSymbolIndex(SymRef.getRawDataRefImpl());
240 if (
auto NameOrErr = SymRef.getName())
243 return NameOrErr.takeError();
249 dbgs() <<
"<anonymous symbol>";
252 dbgs() <<
": value = " <<
formatv(
"{0:x16}", Value)
253 <<
", type = " <<
formatv(
"{0:x2}", Type)
254 <<
", desc = " <<
formatv(
"{0:x4}", Desc) <<
", sect = ";
256 dbgs() <<
static_cast<unsigned>(Sect - 1);
268 return NSecOrErr.takeError();
271 return make_error<JITLinkError>(
"Symbol address does not fall within " 275 IndexToSymbol[SymbolIndex] =
283 void MachOLinkGraphBuilder::addSectionStartSymAndBlock(
287 Data ? G->createContentBlock(GraphSec,
StringRef(Data, Size), Address,
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;
296 Error MachOLinkGraphBuilder::graphifyRegularSymbols() {
301 std::vector<std::vector<NormalizedSymbol *>> SecIndexToSymbols;
302 SecIndexToSymbols.resize(256);
306 for (
auto &KV : IndexToSymbol) {
307 auto &NSym = *KV.second;
313 return make_error<JITLinkError>(
"Anonymous common symbol at index " +
315 NSym.GraphSymbol = &G->addCommonSymbol(
316 *NSym.Name, NSym.S, getCommonSection(), 0, NSym.Value,
321 return make_error<JITLinkError>(
"Anonymous external symbol at " 324 NSym.GraphSymbol = &G->addExternalSymbol(
331 return make_error<JITLinkError>(
"Anonymous absolute symbol at index " +
333 NSym.GraphSymbol = &G->addAbsoluteSymbol(
338 SecIndexToSymbols[NSym.Sect - 1].push_back(&NSym);
341 return make_error<JITLinkError>(
342 "Unupported N_PBUD symbol " +
343 (NSym.Name ? (
"\"" + *NSym.Name +
"\"") :
Twine(
"<anon>")) +
344 " at index " +
Twine(KV.first));
346 return make_error<JITLinkError>(
347 "Unupported N_INDR symbol " +
348 (NSym.Name ? (
"\"" + *NSym.Name +
"\"") :
Twine(
"<anon>")) +
349 " at index " +
Twine(KV.first));
351 return make_error<JITLinkError>(
354 (NSym.Name ? (
"\"" + *NSym.Name +
"\"") :
Twine(
"<anon>")) +
355 " at index " +
Twine(KV.first));
361 for (
auto &KV : IndexToSection) {
362 auto SecIndex = KV.first;
363 auto &NSec = KV.second;
366 if (CustomSectionParserFunctions.
count(NSec.GraphSection->getName())) {
368 dbgs() <<
" Skipping section " << NSec.GraphSection->getName()
369 <<
" as it has a custom parser.\n";
374 dbgs() <<
" Processing section " << NSec.GraphSection->getName()
381 auto &SecNSymStack = SecIndexToSymbols[SecIndex];
385 if (SecNSymStack.empty()) {
388 dbgs() <<
" Section non-empty, but contains no symbols. " 389 "Creating anonymous block to cover " 390 <<
formatv(
"{0:x16}", NSec.Address) <<
" -- " 391 <<
formatv(
"{0:x16}", NSec.Address + NSec.Size) <<
"\n";
393 addSectionStartSymAndBlock(*NSec.GraphSection, NSec.Address, NSec.Data,
394 NSec.Size, NSec.Alignment,
395 SectionIsNoDeadStrip);
398 dbgs() <<
" Section empty and contains no symbols. Skipping.\n";
412 if (LHS->
S != RHS->
S)
413 return static_cast<uint8_t>(LHS->
S) < static_cast<uint8_t>(RHS->
S);
418 if (!SecNSymStack.empty() &&
isAltEntry(*SecNSymStack.back()))
419 return make_error<JITLinkError>(
420 "First symbol in " + NSec.GraphSection->getName() +
" is alt-entry");
424 if (SecNSymStack.back()->Value != NSec.Address) {
425 auto AnonBlockSize = SecNSymStack.back()->Value - NSec.Address;
427 dbgs() <<
" Section start not covered by symbol. " 428 <<
"Creating anonymous block to cover [ " 429 <<
formatv(
"{0:x16}", NSec.Address) <<
" -- " 430 <<
formatv(
"{0:x16}", NSec.Address + AnonBlockSize) <<
" ]\n";
432 addSectionStartSymAndBlock(*NSec.GraphSection, NSec.Address, NSec.Data,
433 AnonBlockSize, NSec.Alignment,
434 SectionIsNoDeadStrip);
439 while (!SecNSymStack.empty()) {
442 BlockSyms.
push_back(SecNSymStack.back());
443 SecNSymStack.pop_back();
444 while (!SecNSymStack.empty() &&
446 SecNSymStack.back()->Value == BlockSyms.
back()->Value)) {
447 BlockSyms.
push_back(SecNSymStack.back());
448 SecNSymStack.pop_back();
454 ? NSec.Address + NSec.Size
455 : SecNSymStack.back()->Value;
460 dbgs() <<
" Creating block for " <<
formatv(
"{0:x16}", BlockStart)
461 <<
" -- " <<
formatv(
"{0:x16}", BlockEnd) <<
": " 462 << NSec.GraphSection->getName() <<
" + " 463 <<
formatv(
"{0:x16}", BlockOffset) <<
" with " 464 << BlockSyms.
size() <<
" symbol(s)...\n";
469 ? G->createContentBlock(
471 StringRef(NSec.Data + BlockOffset, BlockSize), BlockStart,
472 NSec.Alignment, BlockStart % NSec.Alignment)
473 : G->createZeroFillBlock(*NSec.GraphSection, BlockSize,
474 BlockStart, NSec.Alignment,
475 BlockStart % NSec.Alignment);
479 while (!BlockSyms.
empty()) {
480 auto &NSym = *BlockSyms.
back();
487 dbgs() <<
" " <<
formatv(
"{0:x16}", NSym.Value) <<
" -- " 488 <<
formatv(
"{0:x16}", SymEnd) <<
": ";
490 dbgs() <<
"<anonymous symbol>";
494 dbgs() <<
" [no-dead-strip]";
495 if (LastCanonicalAddr == NSym.Value)
496 dbgs() <<
" [non-canonical]";
502 ? G->addDefinedSymbol(B, NSym.Value - BlockStart, *NSym.Name,
503 SymEnd - NSym.Value, NSym.L, NSym.S,
504 SectionIsText, SymLive)
505 : G->addAnonymousSymbol(B, NSym.Value - BlockStart,
506 SymEnd - NSym.Value, SectionIsText,
508 NSym.GraphSymbol = &Sym;
509 if (LastCanonicalAddr != Sym.getAddress()) {
510 if (LastCanonicalAddr)
511 SymEnd = *LastCanonicalAddr;
512 LastCanonicalAddr = Sym.getAddress();
513 setCanonicalSymbol(Sym);
522 Error MachOLinkGraphBuilder::graphifySectionsWithCustomParsers() {
524 for (
auto &KV : IndexToSection) {
525 auto &NSec = KV.second;
527 auto HI = CustomSectionParserFunctions.
find(NSec.GraphSection->getName());
528 if (
HI != CustomSectionParserFunctions.
end()) {
529 auto &Parse =
HI->second;
530 if (
auto Err = Parse(NSec))
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface ...
virtual ~MachOLinkGraphBuilder()
Expected< NormalizedSection & > findSectionByIndex(unsigned Index)
Try to get the section at the given index.
S_ATTR_PURE_INSTRUCTIONS - Section contains only true machine instructions.
static Linkage getLinkage(uint16_t Desc)
This class represents lattice values for constants.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
bool isRelocatableObject() const override
True if this is a relocatable object (.o/.obj).
void push_back(const T &Elt)
Expected< SectionRef > getSection(unsigned SectionIndex) const
iterator find(StringRef Key)
auto formatv(const char *Fmt, Ts &&... Vals) -> formatv_object< decltype(std::make_tuple(detail::build_format_adapter(std::forward< Ts >(Vals))...))>
An Addressable with content and edges.
uint8_t GET_COMM_ALIGN(uint16_t n_desc)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static bool isAltEntry(const NormalizedSymbol &NSym)
Tagged union holding either a T or a Error.
LLVM_NODISCARD size_t size() const
size - Get the string size.
section_iterator_range sections() const
uint64_t JITTargetAddress
Represents an address in the target process's address space.
MachO::nlist_64 getSymbol64TableEntry(DataRefImpl DRI) const
static Expected< StringRef > getFileName(const DebugStringTableSubsectionRef &Strings, const DebugChecksumsSubsectionRef &Checksums, uint32_t FileID)
MachO::nlist getSymbolTableEntry(DataRefImpl DRI) const
Represents an object file section.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
S_GB_ZEROFILL - Zero fill on demand section (that can be larger than 4 gigabytes).
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
The instances of the Type class are immutable: once they are created, they are never changed...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static const char * CommonSectionName
bool isLittleEndian() const
S_ATTR_NO_DEAD_STRIP - No dead stripping.
Optional< StringRef > Name
void sort(IteratorTy Start, IteratorTy End)
static const int BlockSize
static ErrorSuccess success()
Create a success value.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
NormalizedSymbol & createNormalizedSymbol(ArgTs &&... Args)
Create a symbol.
static Scope getScope(StringRef Name, uint8_t Type)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
symbol_iterator_range symbols() const
MachO::section_64 getSection64(DataRefImpl DRI) const
uint64_t getSectionIndex(DataRefImpl Sec) const override
Linkage
Describes symbol linkage.
LLVM_NODISCARD bool empty() const
void addCustomSectionParser(StringRef SectionName, SectionParserFunction Parse)
Expected< std::unique_ptr< LinkGraph > > buildGraph()
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
virtual Error addRelocations()=0
Lightweight error class with error context and mandatory checking.
MachOLinkGraphBuilder(const object::MachOObjectFile &Obj)
StringRef - Represent a constant reference to a string, i.e.
uint64_t getSymbolIndex(DataRefImpl Symb) const
S_ZEROFILL - Zero fill on demand section.
SectionType
These are the section type and attributes fields.
StringRef getData() const
std::function< Error(NormalizedSection &S)> SectionParserFunction