llvm.org GIT mirror llvm / 7acaefa
[MCJIT] Clean up RuntimeDyld's quirky object-ownership/modification scheme. Previously, when loading an object file, RuntimeDyld (1) took ownership of the ObjectFile instance (and associated MemoryBuffer), (2) potentially modified the object in-place, and (3) returned an ObjectImage that managed ownership of the now-modified object and provided some convenience methods. This scheme accreted over several years as features were tacked on to RuntimeDyld, and was both unintuitive and unsafe (See e.g. http://llvm.org/PR20722). This patch fixes the issue by removing all ownership and in-place modification of object files from RuntimeDyld. Existing behavior, including debugger registration, is preserved. Noteworthy changes include: (1) ObjectFile instances are now passed to RuntimeDyld by const-ref. (2) The ObjectImage and ObjectBuffer classes have been removed entirely, they existed to model ownership within RuntimeDyld, and so are no longer needed. (3) RuntimeDyld::loadObject now returns an instance of a new class, RuntimeDyld::LoadedObjectInfo, which can be used to construct a modified object suitable for registration with the debugger, following the existing debugger registration scheme. (4) The JITRegistrar class has been removed, and the GDBRegistrar class has been re-written as a JITEventListener. This should fix http://llvm.org/PR20722 . git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@222810 91177308-0d34-0410-b5e6-96231b3b80d8 Lang Hames 4 years ago
32 changed file(s) with 834 addition(s) and 1072 deletion(s). Raw diff Collapse all Expand all
1414 #ifndef LLVM_EXECUTIONENGINE_JITEVENTLISTENER_H
1515 #define LLVM_EXECUTIONENGINE_JITEVENTLISTENER_H
1616
17 #include "RuntimeDyld.h"
1718 #include "llvm/Config/llvm-config.h"
1819 #include "llvm/IR/DebugLoc.h"
1920 #include "llvm/Support/DataTypes.h"
2425 class MachineFunction;
2526 class OProfileWrapper;
2627 class IntelJITEventsWrapper;
27 class ObjectImage;
28
29 namespace object {
30 class ObjectFile;
31 }
2832
2933 /// JITEvent_EmittedFunctionDetails - Helper struct for containing information
3034 /// about a generated machine code function.
5660
5761 public:
5862 JITEventListener() {}
59 virtual ~JITEventListener();
63 virtual ~JITEventListener() {}
6064
6165 /// NotifyObjectEmitted - Called after an object has been successfully
6266 /// emitted to memory. NotifyFunctionEmitted will not be called for
6670 /// The ObjectImage contains the generated object image
6771 /// with section headers updated to reflect the address at which sections
6872 /// were loaded and with relocations performed in-place on debug sections.
69 virtual void NotifyObjectEmitted(const ObjectImage &Obj) {}
73 virtual void NotifyObjectEmitted(const object::ObjectFile &Obj,
74 const RuntimeDyld::LoadedObjectInfo &L) {}
7075
7176 /// NotifyFreeingObject - Called just before the memory associated with
7277 /// a previously emitted object is released.
73 virtual void NotifyFreeingObject(const ObjectImage &Obj) {}
78 virtual void NotifyFreeingObject(const object::ObjectFile &Obj) {}
79
80 // Get a pointe to the GDB debugger registration listener.
81 static JITEventListener *createGDBRegistrationListener();
7482
7583 #if LLVM_USE_INTEL_JITEVENTS
7684 // Construct an IntelJITEventListener
104112 return nullptr;
105113 }
106114 #endif // USE_OPROFILE
107
115 private:
116 virtual void anchor();
108117 };
109118
110119 } // end namespace llvm.
+0
-76
include/llvm/ExecutionEngine/ObjectBuffer.h less more
None //===---- ObjectBuffer.h - Utility class to wrap object image memory -----===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares a wrapper class to hold the memory into which an
10 // object will be generated.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_EXECUTIONENGINE_OBJECTBUFFER_H
15 #define LLVM_EXECUTIONENGINE_OBJECTBUFFER_H
16
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Support/MemoryBuffer.h"
19 #include "llvm/Support/raw_ostream.h"
20
21 namespace llvm {
22
23 /// This class acts as a container for the memory buffer used during generation
24 /// and loading of executable objects using MCJIT and RuntimeDyld. The
25 /// underlying memory for the object will be owned by the ObjectBuffer instance
26 /// throughout its lifetime.
27 class ObjectBuffer {
28 virtual void anchor();
29 public:
30 ObjectBuffer() {}
31 ObjectBuffer(std::unique_ptr Buf) : Buffer(std::move(Buf)) {}
32 virtual ~ObjectBuffer() {}
33
34 MemoryBufferRef getMemBuffer() const { return Buffer->getMemBufferRef(); }
35
36 const char *getBufferStart() const { return Buffer->getBufferStart(); }
37 size_t getBufferSize() const { return Buffer->getBufferSize(); }
38 StringRef getBuffer() const { return Buffer->getBuffer(); }
39 StringRef getBufferIdentifier() const {
40 return Buffer->getBufferIdentifier();
41 }
42
43 protected:
44 // The memory contained in an ObjectBuffer
45 std::unique_ptr Buffer;
46 };
47
48 /// This class encapsulates the SmallVector and raw_svector_ostream needed to
49 /// generate an object using MC code emission while providing a common
50 /// ObjectBuffer interface for access to the memory once the object has been
51 /// generated.
52 class ObjectBufferStream : public ObjectBuffer {
53 void anchor() override;
54 public:
55 ObjectBufferStream() : OS(SV) {}
56 virtual ~ObjectBufferStream() {}
57
58 raw_ostream &getOStream() { return OS; }
59 void flush()
60 {
61 OS.flush();
62
63 // Make the data accessible via the ObjectBuffer::Buffer
64 Buffer =
65 MemoryBuffer::getMemBuffer(StringRef(SV.data(), SV.size()), "", false);
66 }
67
68 protected:
69 SmallVector SV; // Working buffer into which we JIT.
70 raw_svector_ostream OS; // streaming wrapper
71 };
72
73 } // namespace llvm
74
75 #endif
+0
-76
include/llvm/ExecutionEngine/ObjectImage.h less more
None //===---- ObjectImage.h - Format independent executuable object image -----===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares a file format independent ObjectImage class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_EXECUTIONENGINE_OBJECTIMAGE_H
14 #define LLVM_EXECUTIONENGINE_OBJECTIMAGE_H
15
16 #include "llvm/ExecutionEngine/ObjectBuffer.h"
17 #include "llvm/Object/ObjectFile.h"
18
19 namespace llvm {
20
21
22 /// ObjectImage - A container class that represents an ObjectFile that has been
23 /// or is in the process of being loaded into memory for execution.
24 class ObjectImage {
25 ObjectImage() LLVM_DELETED_FUNCTION;
26 ObjectImage(const ObjectImage &other) LLVM_DELETED_FUNCTION;
27 virtual void anchor();
28
29 protected:
30 std::unique_ptr Buffer;
31
32 public:
33 ObjectImage(std::unique_ptr Input) : Buffer(std::move(Input)) {}
34 virtual ~ObjectImage() {}
35
36 virtual object::symbol_iterator begin_symbols() const = 0;
37 virtual object::symbol_iterator end_symbols() const = 0;
38 iterator_range symbols() const {
39 return iterator_range(begin_symbols(),
40 end_symbols());
41 }
42
43 virtual object::section_iterator begin_sections() const = 0;
44 virtual object::section_iterator end_sections() const = 0;
45 iterator_range sections() const {
46 return iterator_range(begin_sections(),
47 end_sections());
48 }
49
50 virtual /* Triple::ArchType */ unsigned getArch() const = 0;
51
52 // Return the name associated with this ObjectImage.
53 // This is usually the name of the file or MemoryBuffer that the the
54 // ObjectBuffer was constructed from.
55 StringRef getImageName() const { return Buffer->getBufferIdentifier(); }
56
57 // Subclasses can override these methods to update the image with loaded
58 // addresses for sections and common symbols
59 virtual void updateSectionAddress(const object::SectionRef &Sec,
60 uint64_t Addr) = 0;
61 virtual void updateSymbolAddress(const object::SymbolRef &Sym,
62 uint64_t Addr) = 0;
63
64 virtual StringRef getData() const = 0;
65
66 virtual object::ObjectFile* getObjectFile() const = 0;
67
68 // Subclasses can override these methods to provide JIT debugging support
69 virtual void registerWithDebugger() = 0;
70 virtual void deregisterWithDebugger() = 0;
71 };
72
73 } // end namespace llvm
74
75 #endif // LLVM_EXECUTIONENGINE_OBJECTIMAGE_H
2121 namespace llvm {
2222
2323 class ExecutionEngine;
24 class ObjectImage;
24
25 namespace object {
26 class ObjectFile;
27 }
2528
2629 // RuntimeDyld clients often want to handle the memory management of
2730 // what gets placed where. For JIT clients, this is the subset of
108111 /// address space can use this call to remap the section addresses for the
109112 /// newly loaded object.
110113 virtual void notifyObjectLoaded(ExecutionEngine *EE,
111 const ObjectImage *) {}
114 const object::ObjectFile &) {}
112115
113116 /// This method is called when object loading is complete and section page
114117 /// permissions can be applied. It is up to the memory manager implementation
1414 #define LLVM_EXECUTIONENGINE_RUNTIMEDYLD_H
1515
1616 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ExecutionEngine/ObjectBuffer.h"
1817 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
1918 #include "llvm/Support/Memory.h"
19 #include
2020
2121 namespace llvm {
2222
2323 namespace object {
2424 class ObjectFile;
25 template class OwningBinary;
2526 }
2627
2728 class RuntimeDyldImpl;
2829 class RuntimeDyldCheckerImpl;
29 class ObjectImage;
3030
3131 class RuntimeDyld {
3232 friend class RuntimeDyldCheckerImpl;
4545 // Any relocations already associated with the symbol will be re-resolved.
4646 void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
4747 public:
48
49 /// \brief Information about the loaded object.
50 class LoadedObjectInfo {
51 friend class RuntimeDyldImpl;
52 public:
53 LoadedObjectInfo(RuntimeDyldImpl &RTDyld, unsigned BeginIdx,
54 unsigned EndIdx)
55 : RTDyld(RTDyld), BeginIdx(BeginIdx), EndIdx(EndIdx) { }
56
57 virtual ~LoadedObjectInfo() {}
58
59 virtual object::OwningBinary
60 getObjectForDebug(const object::ObjectFile &Obj) const = 0;
61
62 uint64_t getSectionLoadAddress(StringRef Name) const;
63
64 protected:
65 virtual void anchor();
66
67 RuntimeDyldImpl &RTDyld;
68 unsigned BeginIdx, EndIdx;
69 };
70
4871 RuntimeDyld(RTDyldMemoryManager *);
4972 ~RuntimeDyld();
5073
51 /// Prepare the object contained in the input buffer for execution.
52 /// Ownership of the input buffer is transferred to the ObjectImage
53 /// instance returned from this function if successful. In the case of load
54 /// failure, the input buffer will be deleted.
55 std::unique_ptr
56 loadObject(std::unique_ptr InputBuffer);
57
58 /// Prepare the referenced object file for execution.
59 /// Ownership of the input object is transferred to the ObjectImage
60 /// instance returned from this function if successful. In the case of load
61 /// failure, the input object will be deleted.
62 std::unique_ptr
63 loadObject(std::unique_ptr InputObject);
74 /// Add the referenced object file to the list of objects to be loaded and
75 /// relocated.
76 std::unique_ptr loadObject(const object::ObjectFile &O);
6477
6578 /// Get the address of our local copy of the symbol. This may or may not
6679 /// be the address used for relocation (clients can copy the data around
22 add_llvm_library(LLVMExecutionEngine
33 ExecutionEngine.cpp
44 ExecutionEngineBindings.cpp
5 JITEventListener.cpp
65 RTDyldMemoryManager.cpp
76 TargetSelect.cpp
87 )
1515 #include "llvm/ADT/SmallString.h"
1616 #include "llvm/ADT/Statistic.h"
1717 #include "llvm/ExecutionEngine/GenericValue.h"
18 #include "llvm/ExecutionEngine/ObjectBuffer.h"
19 #include "llvm/ExecutionEngine/ObjectCache.h"
18 #include "llvm/ExecutionEngine/JITEventListener.h"
2019 #include "llvm/IR/Constants.h"
2120 #include "llvm/IR/DataLayout.h"
2221 #include "llvm/IR/DerivedTypes.h"
4241 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
4342 STATISTIC(NumGlobals , "Number of global vars initialized");
4443
45 // Pin the vtable to this file.
46 void ObjectCache::anchor() {}
47 void ObjectBuffer::anchor() {}
48 void ObjectBufferStream::anchor() {}
49
5044 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
5145 std::unique_ptr M, std::string *ErrorStr,
5246 RTDyldMemoryManager *MCJMM, std::unique_ptr TM) = nullptr;
5347 ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr M,
5448 std::string *ErrorStr) =nullptr;
49
50 // Anchor for the JITEventListener class.
51 void JITEventListener::anchor() {}
5552
5653 ExecutionEngine::ExecutionEngine(std::unique_ptr M)
5754 : EEState(*this),
2020 #include "llvm/ADT/DenseMap.h"
2121 #include "llvm/CodeGen/MachineFunction.h"
2222 #include "llvm/DebugInfo/DIContext.h"
23 #include "llvm/ExecutionEngine/ObjectImage.h"
2423 #include "llvm/Object/ObjectFile.h"
2524 #include "llvm/Support/Debug.h"
2625 #include "llvm/Support/raw_ostream.h"
3130
3231 using namespace llvm;
3332 using namespace llvm::jitprofiling;
33 using namespace llvm::object;
3434
3535 #define DEBUG_TYPE "amplifier-jit-event-listener"
3636
4747 typedef DenseMap ObjectMap;
4848
4949 ObjectMap LoadedObjectMap;
50 std::map> DebugObjects;
5051
5152 public:
5253 IntelJITEventListener(IntelJITEventsWrapper* libraryWrapper) {
5657 ~IntelJITEventListener() {
5758 }
5859
59 virtual void NotifyObjectEmitted(const ObjectImage &Obj);
60
61 virtual void NotifyFreeingObject(const ObjectImage &Obj);
60 void NotifyObjectEmitted(const ObjectFile &Obj,
61 const RuntimeDyld::LoadedObjectInfo &L) override;
62
63 void NotifyFreeingObject(const ObjectFile &Obj) override;
6264 };
6365
6466 static LineNumberInfo DILineInfoToIntelJITFormat(uintptr_t StartAddress,
9496 return Result;
9597 }
9698
97 void IntelJITEventListener::NotifyObjectEmitted(const ObjectImage &Obj) {
99 void IntelJITEventListener::NotifyObjectEmitted(
100 const ObjectFile &Obj,
101 const RuntimeDyld::LoadedObjectInfo &L) {
102
103 OwningBinary DebugObjOwner = L.getObjectForDebug(Obj);
104 const ObjectFile &DebugObj = *DebugObjOwner.getBinary();
105
98106 // Get the address of the object image for use as a unique identifier
99 const void* ObjData = Obj.getData().data();
100 DIContext* Context = DIContext::getDWARFContext(*Obj.getObjectFile());
107 const void* ObjData = DebugObj.getData().data();
108 DIContext* Context = DIContext::getDWARFContext(DebugObj);
101109 MethodAddressVector Functions;
102110
103111 // Use symbol info to iterate functions in the object.
104 for (object::symbol_iterator I = Obj.begin_symbols(),
105 E = Obj.end_symbols();
112 for (symbol_iterator I = DebugObj.symbol_begin(),
113 E = DebugObj.symbol_end();
106114 I != E;
107115 ++I) {
108116 std::vector LineInfo;
109117 std::string SourceFileName;
110118
111 object::SymbolRef::Type SymType;
119 SymbolRef::Type SymType;
112120 if (I->getType(SymType)) continue;
113 if (SymType == object::SymbolRef::ST_Function) {
121 if (SymType == SymbolRef::ST_Function) {
114122 StringRef Name;
115123 uint64_t Addr;
116124 uint64_t Size;
161169 // registered function addresses for each loaded object. We will
162170 // use the MethodIDs map to get the registered ID for each function.
163171 LoadedObjectMap[ObjData] = Functions;
164 }
165
166 void IntelJITEventListener::NotifyFreeingObject(const ObjectImage &Obj) {
172 DebugObjects[Obj.getData().data()] = std::move(DebugObjOwner);
173 }
174
175 void IntelJITEventListener::NotifyFreeingObject(const ObjectFile &Obj) {
176 // This object may not have been registered with the listener. If it wasn't,
177 // bail out.
178 if (DebugObjects.find(Obj.getData().data()) == DebugObjects.end())
179 return;
180
167181 // Get the address of the object image for use as a unique identifier
168 const void* ObjData = Obj.getData().data();
182 const ObjectFile &DebugObj = *DebugObjects[Obj.getData().data()].getBinary();
183 const void* ObjData = DebugObj.getData().data();
169184
170185 // Get the object's function list from LoadedObjectMap
171186 ObjectMap::iterator OI = LoadedObjectMap.find(ObjData);
189204
190205 // Erase the object from LoadedObjectMap
191206 LoadedObjectMap.erase(OI);
207 DebugObjects.erase(Obj.getData().data());
192208 }
193209
194210 } // anonymous namespace.
+0
-15
lib/ExecutionEngine/JITEventListener.cpp less more
None //===-- JITEventListener.cpp ----------------------------------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/ExecutionEngine/JITEventListener.h"
10
11 using namespace llvm;
12
13 // Out-of-line definition of the virtual destructor as this is the key function.
14 JITEventListener::~JITEventListener() {}
1010 #include "llvm/ExecutionEngine/GenericValue.h"
1111 #include "llvm/ExecutionEngine/JITEventListener.h"
1212 #include "llvm/ExecutionEngine/MCJIT.h"
13 #include "llvm/ExecutionEngine/ObjectBuffer.h"
14 #include "llvm/ExecutionEngine/ObjectImage.h"
1513 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
1614 #include "llvm/IR/DataLayout.h"
1715 #include "llvm/IR/DerivedTypes.h"
2018 #include "llvm/IR/Module.h"
2119 #include "llvm/MC/MCAsmInfo.h"
2220 #include "llvm/Object/Archive.h"
21 #include "llvm/Object/ObjectFile.h"
2322 #include "llvm/PassManager.h"
2423 #include "llvm/Support/DynamicLibrary.h"
2524 #include "llvm/Support/ErrorHandling.h"
2928 #include "llvm/Target/TargetSubtargetInfo.h"
3029
3130 using namespace llvm;
31
32 void ObjectCache::anchor() {}
3233
3334 namespace {
3435
7374
7475 OwnedModules.addModule(std::move(First));
7576 setDataLayout(TM->getSubtargetImpl()->getDataLayout());
77 RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
7678 }
7779
7880 MCJIT::~MCJIT() {
98100 }
99101
100102 void MCJIT::addObjectFile(std::unique_ptr Obj) {
101 std::unique_ptr LoadedObject = Dyld.loadObject(std::move(Obj));
102 if (!LoadedObject || Dyld.hasError())
103 std::unique_ptr L = Dyld.loadObject(*Obj);
104 if (Dyld.hasError())
103105 report_fatal_error(Dyld.getErrorString());
104106
105 NotifyObjectEmitted(*LoadedObject);
106
107 LoadedObjects.push_back(std::move(LoadedObject));
107 NotifyObjectEmitted(*Obj, *L);
108
109 LoadedObjects.push_back(std::move(Obj));
108110 }
109111
110112 void MCJIT::addObjectFile(object::OwningBinary Obj) {
124126 ObjCache = NewCache;
125127 }
126128
127 std::unique_ptr<ObjectBufferStream> MCJIT::emitObject(Module *M) {
129 std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
128130 MutexGuard locked(lock);
129131
130132 // This must be a module which has already been added but not loaded to this
137139 PM.add(new DataLayoutPass());
138140
139141 // The RuntimeDyld will take ownership of this shortly
140 std::unique_ptr CompiledObject(new ObjectBufferStream());
142 SmallVector ObjBufferSV;
143 raw_svector_ostream ObjStream(ObjBufferSV);
141144
142145 // Turn the machine code intermediate representation into bytes in memory
143146 // that may be executed.
144 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
145 !getVerifyModules())) {
147 if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
146148 report_fatal_error("Target does not support MC emission!");
147 }
148149
149150 // Initialize passes.
150151 PM.run(*M);
151152 // Flush the output buffer to get the generated code into memory
152 CompiledObject->flush();
153 ObjStream.flush();
154
155 std::unique_ptr CompiledObjBuffer(
156 new ObjectMemoryBuffer(std::move(ObjBufferSV)));
153157
154158 // If we have an object cache, tell it about the new object.
155159 // Note that we're using the compiled image, not the loaded image (as below).
156160 if (ObjCache) {
157161 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
158162 // to create a temporary object here and delete it after the call.
159 MemoryBufferRef MB = CompiledObject->getMemBuffer();
163 MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
160164 ObjCache->notifyObjectCompiled(M, MB);
161165 }
162166
163 return CompiledObject;
167 return CompiledObjBuffer;
164168 }
165169
166170 void MCJIT::generateCodeForModule(Module *M) {
175179 if (OwnedModules.hasModuleBeenLoaded(M))
176180 return;
177181
178 std::unique_ptr<ObjectBuffer> ObjectToLoad;
182 std::unique_ptr<MemoryBuffer> ObjectToLoad;
179183 // Try to load the pre-compiled object from cache if possible
180 if (ObjCache) {
181 if (std::unique_ptr PreCompiledObject =
182 ObjCache->getObject(M))
183 ObjectToLoad =
184 llvm::make_unique(std::move(PreCompiledObject));
185 }
184 if (ObjCache)
185 ObjectToLoad = ObjCache->getObject(M);
186186
187187 // If the cache did not contain a suitable object, compile the object
188188 if (!ObjectToLoad) {
192192
193193 // Load the object into the dynamic linker.
194194 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
195 std::unique_ptr LoadedObject =
196 Dyld.loadObject(std::move(ObjectToLoad));
197 if (!LoadedObject)
195 ErrorOr> LoadedObject =
196 object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
197 std::unique_ptr L =
198 Dyld.loadObject(*LoadedObject.get());
199
200 if (Dyld.hasError())
198201 report_fatal_error(Dyld.getErrorString());
199202
200 // FIXME: Make this optional, maybe even move it to a JIT event listener
201 LoadedObject->registerWithDebugger();
202
203 NotifyObjectEmitted(*LoadedObject);
204
205 LoadedObjects.push_back(std::move(LoadedObject));
203 NotifyObjectEmitted(*LoadedObject.get(), *L);
204
205 Buffers.push_back(std::move(ObjectToLoad));
206 LoadedObjects.push_back(std::move(*LoadedObject));
206207
207208 OwnedModules.markModuleAsLoaded(M);
208209 }
548549 MutexGuard locked(lock);
549550 EventListeners.push_back(L);
550551 }
552
551553 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
552554 if (!L)
553555 return;
558560 EventListeners.pop_back();
559561 }
560562 }
561 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
562 MutexGuard locked(lock);
563 MemMgr.notifyObjectLoaded(this, &Obj);
563
564 void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
565 const RuntimeDyld::LoadedObjectInfo &L) {
566 MutexGuard locked(lock);
567 MemMgr.notifyObjectLoaded(this, Obj);
564568 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
565 EventListeners[I]->NotifyObjectEmitted(Obj);
566 }
567 }
568 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
569 EventListeners[I]->NotifyObjectEmitted(Obj, L);
570 }
571 }
572
573 void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
569574 MutexGuard locked(lock);
570575 for (JITEventListener *L : EventListeners)
571576 L->NotifyFreeingObject(Obj);
99 #ifndef LLVM_LIB_EXECUTIONENGINE_MCJIT_MCJIT_H
1010 #define LLVM_LIB_EXECUTIONENGINE_MCJIT_MCJIT_H
1111
12 #include "ObjectBuffer.h"
1213 #include "llvm/ADT/DenseMap.h"
1314 #include "llvm/ADT/SmallPtrSet.h"
1415 #include "llvm/ADT/SmallVector.h"
1516 #include "llvm/ExecutionEngine/ExecutionEngine.h"
1617 #include "llvm/ExecutionEngine/ObjectCache.h"
17 #include "llvm/ExecutionEngine/ObjectImage.h"
1818 #include "llvm/ExecutionEngine/RuntimeDyld.h"
1919 #include "llvm/IR/Module.h"
2020
5656 }
5757
5858 void notifyObjectLoaded(ExecutionEngine *EE,
59 const ObjectImage *Obj) override {
59 const object::ObjectFile &Obj) override {
6060 ClientMM->notifyObjectLoaded(EE, Obj);
6161 }
6262
221221 SmallVector, 2> Archives;
222222 SmallVector, 2> Buffers;
223223
224 SmallVectorObjectImage>, 2> LoadedObjects;
224 SmallVectorobject::ObjectFile>, 2> LoadedObjects;
225225
226226 // An optional ObjectCache to be notified of compiled objects and used to
227227 // perform lookup of pre-compiled code to avoid re-compilation.
340340 /// this function call is expected to be the contained module. The module
341341 /// is passed as a parameter here to prepare for multiple module support in
342342 /// the future.
343 std::unique_ptr emitObject(Module *M);
344
345 void NotifyObjectEmitted(const ObjectImage& Obj);
346 void NotifyFreeingObject(const ObjectImage& Obj);
343 std::unique_ptr emitObject(Module *M);
344
345 void NotifyObjectEmitted(const object::ObjectFile& Obj,
346 const RuntimeDyld::LoadedObjectInfo &L);
347 void NotifyFreeingObject(const object::ObjectFile& Obj);
347348
348349 uint64_t getExistingSymbolAddress(const std::string &Name);
349350 Module *findModuleForSymbol(const std::string &Name,
0 //===--- ObjectBuffer.h - Utility class to wrap object memory ---*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares a wrapper class to hold the memory into which an
10 // object will be generated.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_EXECUTIONENGINE_OBJECTBUFFER_H
15 #define LLVM_EXECUTIONENGINE_OBJECTBUFFER_H
16
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Support/MemoryBuffer.h"
19 #include "llvm/Support/raw_ostream.h"
20
21 namespace llvm {
22
23 class ObjectMemoryBuffer : public MemoryBuffer {
24 public:
25 template
26 ObjectMemoryBuffer(SmallVector SV)
27 : SV(SV), BufferName("") {
28 init(this->SV.begin(), this->SV.end(), false);
29 }
30
31 template
32 ObjectMemoryBuffer(SmallVector SV, StringRef Name)
33 : SV(SV), BufferName(Name) {
34 init(this->SV.begin(), this->SV.end(), false);
35 }
36 const char* getBufferIdentifier() const override { return BufferName.c_str(); }
37
38 BufferKind getBufferKind() const override { return MemoryBuffer_Malloc; }
39
40 private:
41 SmallVector SV;
42 std::string BufferName;
43 };
44
45 } // namespace llvm
46
47 #endif
1717 #include "llvm/IR/DebugInfo.h"
1818 #include "llvm/IR/Function.h"
1919 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/ExecutionEngine/ObjectImage.h"
2120 #include "llvm/ExecutionEngine/OProfileWrapper.h"
21 #include "llvm/ExecutionEngine/RuntimeDyld.h"
2222 #include "llvm/Object/ObjectFile.h"
2323 #include "llvm/Support/Debug.h"
2424 #include "llvm/Support/raw_ostream.h"
3030
3131 using namespace llvm;
3232 using namespace llvm::jitprofiling;
33 using namespace llvm::object;
3334
3435 #define DEBUG_TYPE "oprofile-jit-event-listener"
3536
3637 namespace {
3738
3839 class OProfileJITEventListener : public JITEventListener {
39 OProfileWrapper& Wrapper;
40 std::unique_ptr Wrapper;
4041
4142 void initialize();
43 std::map> DebugObjects;
4244
4345 public:
44 OProfileJITEventListener(OProfileWrapper& LibraryWrapper)
45 : Wrapper(LibraryWrapper) {
46 OProfileJITEventListener(std::unique_ptr LibraryWrapper)
47 : Wrapper(std::move(LibraryWrapper)) {
4648 initialize();
4749 }
4850
4951 ~OProfileJITEventListener();
5052
51 virtual void NotifyObjectEmitted(const ObjectImage &Obj);
53 void NotifyObjectEmitted(const ObjectFile &Obj,
54 const RuntimeDyld::LoadedObjectInfo &L) override;
5255
53 virtual void NotifyFreeingObject(const ObjectImage &Obj);
56 void NotifyFreeingObject(const ObjectFile &Obj) override;
5457 };
5558
5659 void OProfileJITEventListener::initialize() {
57 if (!Wrapper.op_open_agent()) {
60 if (!Wrapper->op_open_agent()) {
5861 const std::string err_str = sys::StrError();
5962 DEBUG(dbgs() << "Failed to connect to OProfile agent: " << err_str << "\n");
6063 } else {
6366 }
6467
6568 OProfileJITEventListener::~OProfileJITEventListener() {
66 if (Wrapper.isAgentAvailable()) {
67 if (Wrapper.op_close_agent() == -1) {
69 if (Wrapper->isAgentAvailable()) {
70 if (Wrapper->op_close_agent() == -1) {
6871 const std::string err_str = sys::StrError();
6972 DEBUG(dbgs() << "Failed to disconnect from OProfile agent: "
7073 << err_str << "\n");
7477 }
7578 }
7679
77 void OProfileJITEventListener::NotifyObjectEmitted(const ObjectImage &Obj) {
78 if (!Wrapper.isAgentAvailable()) {
80 void OProfileJITEventListener::NotifyObjectEmitted(
81 const ObjectFile &Obj,
82 const RuntimeDyld::LoadedObjectInfo &L) {
83 if (!Wrapper->isAgentAvailable()) {
7984 return;
8085 }
8186
87 OwningBinary DebugObjOwner = L.getObjectForDebug(Obj);
88 const ObjectFile &DebugObj = *DebugObjOwner.getBinary();
89
8290 // Use symbol info to iterate functions in the object.
83 for (object::symbol_iterator I = Obj.begin_symbols(), E = Obj.end_symbols();
91 for (symbol_iterator I = DebugObj.symbol_begin(), E = DebugObj.symbol_end();
8492 I != E; ++I) {
85 object::SymbolRef::Type SymType;
93 SymbolRef::Type SymType;
8694 if (I->getType(SymType)) continue;
87 if (SymType == object::SymbolRef::ST_Function) {
95 if (SymType == SymbolRef::ST_Function) {
8896 StringRef Name;
8997 uint64_t Addr;
9098 uint64_t Size;
92100 if (I->getAddress(Addr)) continue;
93101 if (I->getSize(Size)) continue;
94102
95 if (Wrapper.op_write_native_code(Name.data(), Addr, (void*)Addr, Size)
103 if (Wrapper->op_write_native_code(Name.data(), Addr, (void*)Addr, Size)
96104 == -1) {
97105 DEBUG(dbgs() << "Failed to tell OProfile about native function "
98106 << Name << " at ["
102110 // TODO: support line number info (similar to IntelJITEventListener.cpp)
103111 }
104112 }
113
114 DebugObjects[Obj.getData().data()] = std::move(DebugObjOwner);
105115 }
106116
107 void OProfileJITEventListener::NotifyFreeingObject(const ObjectImage &Obj) {
108 if (!Wrapper.isAgentAvailable()) {
109 return;
110 }
117 void OProfileJITEventListener::NotifyFreeingObject(const ObjectFile &Obj) {
118 if (Wrapper->isAgentAvailable()) {
111119
112 // Use symbol info to iterate functions in the object.
113 for (object::symbol_iterator I = Obj.begin_symbols(), E = Obj.end_symbols();
114 I != E; ++I) {
115 object::SymbolRef::Type SymType;
116 if (I->getType(SymType)) continue;
117 if (SymType == object::SymbolRef::ST_Function) {
118 uint64_t Addr;
119 if (I->getAddress(Addr)) continue;
120 // If there was no agent registered when the original object was loaded then
121 // we won't have created a debug object for it, so bail out.
122 if (DebugObjects.find(Obj.getData().data()) == DebugObjects.end())
123 return;
120124
121 if (Wrapper.op_unload_native_code(Addr) == -1) {
122 DEBUG(dbgs()
123 << "Failed to tell OProfile about unload of native function at "
124 << (void*)Addr << "\n");
125 continue;
125 const ObjectFile &DebugObj = *DebugObjects[Obj.getData().data()].getBinary();
126
127 // Use symbol info to iterate functions in the object.
128 for (symbol_iterator I = DebugObj.symbol_begin(),
129 E = DebugObj.symbol_end();
130 I != E; ++I) {
131 SymbolRef::Type SymType;
132 if (I->getType(SymType)) continue;
133 if (SymType == SymbolRef::ST_Function) {
134 uint64_t Addr;
135 if (I->getAddress(Addr)) continue;
136
137 if (Wrapper->op_unload_native_code(Addr) == -1) {
138 DEBUG(dbgs()
139 << "Failed to tell OProfile about unload of native function at "
140 << (void*)Addr << "\n");
141 continue;
142 }
126143 }
127144 }
128145 }
146
147 DebugObjects.erase(Obj.getData().data());
129148 }
130149
131150 } // anonymous namespace.
132151
133152 namespace llvm {
134153 JITEventListener *JITEventListener::createOProfileJITEventListener() {
135 static std::unique_ptr JITProfilingWrapper(
136 new OProfileWrapper);
137 return new OProfileJITEventListener(*JITProfilingWrapper);
138 }
139
140 // for testing
141 JITEventListener *JITEventListener::createOProfileJITEventListener(
142 OProfileWrapper* TestImpl) {
143 return new OProfileJITEventListener(*TestImpl);
154 return new OProfileJITEventListener(llvm::make_unique());
144155 }
145156
146157 } // namespace llvm
0 add_llvm_library(LLVMRuntimeDyld
1 GDBRegistrar.cpp
1 GDBRegistrationListener.cpp
22 RuntimeDyld.cpp
33 RuntimeDyldChecker.cpp
44 RuntimeDyldELF.cpp
+0
-213
lib/ExecutionEngine/RuntimeDyld/GDBRegistrar.cpp less more
None //===-- GDBRegistrar.cpp - Registers objects with GDB ---------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "JITRegistrar.h"
10 #include "llvm/ADT/DenseMap.h"
11 #include "llvm/Support/Compiler.h"
12 #include "llvm/Support/ErrorHandling.h"
13 #include "llvm/Support/Mutex.h"
14 #include "llvm/Support/MutexGuard.h"
15 #include "llvm/Support/ManagedStatic.h"
16
17 using namespace llvm;
18
19 // This must be kept in sync with gdb/gdb/jit.h .
20 extern "C" {
21
22 typedef enum {
23 JIT_NOACTION = 0,
24 JIT_REGISTER_FN,
25 JIT_UNREGISTER_FN
26 } jit_actions_t;
27
28 struct jit_code_entry {
29 struct jit_code_entry *next_entry;
30 struct jit_code_entry *prev_entry;
31 const char *symfile_addr;
32 uint64_t symfile_size;
33 };
34
35 struct jit_descriptor {
36 uint32_t version;
37 // This should be jit_actions_t, but we want to be specific about the
38 // bit-width.
39 uint32_t action_flag;
40 struct jit_code_entry *relevant_entry;
41 struct jit_code_entry *first_entry;
42 };
43
44 // We put information about the JITed function in this global, which the
45 // debugger reads. Make sure to specify the version statically, because the
46 // debugger checks the version before we can set it during runtime.
47 struct jit_descriptor __jit_debug_descriptor = { 1, 0, nullptr, nullptr };
48
49 // Debuggers puts a breakpoint in this function.
50 LLVM_ATTRIBUTE_NOINLINE void __jit_debug_register_code() {
51 // The noinline and the asm prevent calls to this function from being
52 // optimized out.
53 #if !defined(_MSC_VER)
54 asm volatile("":::"memory");
55 #endif
56 }
57
58 }
59
60 namespace {
61
62 // Buffer for an in-memory object file in executable memory
63 typedef llvm::DenseMap< const char*,
64 std::pair >
65 RegisteredObjectBufferMap;
66
67 /// Global access point for the JIT debugging interface designed for use with a
68 /// singleton toolbox. Handles thread-safe registration and deregistration of
69 /// object files that are in executable memory managed by the client of this
70 /// class.
71 class GDBJITRegistrar : public JITRegistrar {
72 /// A map of in-memory object files that have been registered with the
73 /// JIT interface.
74 RegisteredObjectBufferMap ObjectBufferMap;
75
76 public:
77 /// Instantiates the JIT service.
78 GDBJITRegistrar() : ObjectBufferMap() {}
79
80 /// Unregisters each object that was previously registered and releases all
81 /// internal resources.
82 virtual ~GDBJITRegistrar();
83
84 /// Creates an entry in the JIT registry for the buffer @p Object,
85 /// which must contain an object file in executable memory with any
86 /// debug information for the debugger.
87 void registerObject(const ObjectBuffer &Object) override;
88
89 /// Removes the internal registration of @p Object, and
90 /// frees associated resources.
91 /// Returns true if @p Object was found in ObjectBufferMap.
92 bool deregisterObject(const ObjectBuffer &Object) override;
93
94 private:
95 /// Deregister the debug info for the given object file from the debugger
96 /// and delete any temporary copies. This private method does not remove
97 /// the function from Map so that it can be called while iterating over Map.
98 void deregisterObjectInternal(RegisteredObjectBufferMap::iterator I);
99 };
100
101 /// Lock used to serialize all jit registration events, since they
102 /// modify global variables.
103 ManagedStatic JITDebugLock;
104
105 /// Do the registration.
106 void NotifyDebugger(jit_code_entry* JITCodeEntry) {
107 __jit_debug_descriptor.action_flag = JIT_REGISTER_FN;
108
109 // Insert this entry at the head of the list.
110 JITCodeEntry->prev_entry = nullptr;
111 jit_code_entry* NextEntry = __jit_debug_descriptor.first_entry;
112 JITCodeEntry->next_entry = NextEntry;
113 if (NextEntry) {
114 NextEntry->prev_entry = JITCodeEntry;
115 }
116 __jit_debug_descriptor.first_entry = JITCodeEntry;
117 __jit_debug_descriptor.relevant_entry = JITCodeEntry;
118 __jit_debug_register_code();
119 }
120
121 GDBJITRegistrar::~GDBJITRegistrar() {
122 // Free all registered object files.
123 llvm::MutexGuard locked(*JITDebugLock);
124 for (RegisteredObjectBufferMap::iterator I = ObjectBufferMap.begin(), E = ObjectBufferMap.end();
125 I != E; ++I) {
126 // Call the private method that doesn't update the map so our iterator
127 // doesn't break.
128 deregisterObjectInternal(I);
129 }
130 ObjectBufferMap.clear();
131 }
132
133 void GDBJITRegistrar::registerObject(const ObjectBuffer &Object) {
134
135 const char *Buffer = Object.getBufferStart();
136 size_t Size = Object.getBufferSize();
137
138 assert(Buffer && "Attempt to register a null object with a debugger.");
139 llvm::MutexGuard locked(*JITDebugLock);
140 assert(ObjectBufferMap.find(Buffer) == ObjectBufferMap.end() &&
141 "Second attempt to perform debug registration.");
142 jit_code_entry* JITCodeEntry = new jit_code_entry();
143
144 if (!JITCodeEntry) {
145 llvm::report_fatal_error(
146 "Allocation failed when registering a JIT entry!\n");
147 } else {
148 JITCodeEntry->symfile_addr = Buffer;
149 JITCodeEntry->symfile_size = Size;
150
151 ObjectBufferMap[Buffer] = std::make_pair(Size, JITCodeEntry);
152 NotifyDebugger(JITCodeEntry);
153 }
154 }
155
156 bool GDBJITRegistrar::deregisterObject(const ObjectBuffer& Object) {
157 const char *Buffer = Object.getBufferStart();
158 llvm::MutexGuard locked(*JITDebugLock);
159 RegisteredObjectBufferMap::iterator I = ObjectBufferMap.find(Buffer);
160
161 if (I != ObjectBufferMap.end()) {
162 deregisterObjectInternal(I);
163 ObjectBufferMap.erase(I);
164 return true;
165 }
166 return false;
167 }
168
169 void GDBJITRegistrar::deregisterObjectInternal(
170 RegisteredObjectBufferMap::iterator I) {
171
172 jit_code_entry*& JITCodeEntry = I->second.second;
173
174 // Do the unregistration.
175 {
176 __jit_debug_descriptor.action_flag = JIT_UNREGISTER_FN;
177
178 // Remove the jit_code_entry from the linked list.
179 jit_code_entry* PrevEntry = JITCodeEntry->prev_entry;
180 jit_code_entry* NextEntry = JITCodeEntry->next_entry;
181
182 if (NextEntry) {
183 NextEntry->prev_entry = PrevEntry;
184 }
185 if (PrevEntry) {
186 PrevEntry->next_entry = NextEntry;
187 }
188 else {
189 assert(__jit_debug_descriptor.first_entry == JITCodeEntry);
190 __jit_debug_descriptor.first_entry = NextEntry;
191 }
192
193 // Tell the debugger which entry we removed, and unregister the code.
194 __jit_debug_descriptor.relevant_entry = JITCodeEntry;
195 __jit_debug_register_code();
196 }
197
198 delete JITCodeEntry;
199 JITCodeEntry = nullptr;
200 }
201
202 llvm::ManagedStatic TheRegistrar;
203
204 } // end namespace
205
206 namespace llvm {
207
208 JITRegistrar& JITRegistrar::getGDBRegistrar() {
209 return *TheRegistrar;
210 }
211
212 } // namespace llvm
0 //===----- GDBRegistrationListener.cpp - Registers objects with GDB -------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/ADT/DenseMap.h"
10 #include "llvm/ExecutionEngine/JITEventListener.h"
11 #include "llvm/Object/ObjectFile.h"
12 #include "llvm/Support/Compiler.h"
13 #include "llvm/Support/ErrorHandling.h"
14 #include "llvm/Support/Mutex.h"
15 #include "llvm/Support/MutexGuard.h"
16 #include "llvm/Support/ManagedStatic.h"
17
18 using namespace llvm;
19 using namespace llvm::object;
20
21 // This must be kept in sync with gdb/gdb/jit.h .
22 extern "C" {
23
24 typedef enum {
25 JIT_NOACTION = 0,
26 JIT_REGISTER_FN,
27 JIT_UNREGISTER_FN
28 } jit_actions_t;
29
30 struct jit_code_entry {
31 struct jit_code_entry *next_entry;
32 struct jit_code_entry *prev_entry;
33 const char *symfile_addr;
34 uint64_t symfile_size;
35 };
36
37 struct jit_descriptor {
38 uint32_t version;
39 // This should be jit_actions_t, but we want to be specific about the
40 // bit-width.
41 uint32_t action_flag;
42 struct jit_code_entry *relevant_entry;
43 struct jit_code_entry *first_entry;
44 };
45
46 // We put information about the JITed function in this global, which the
47 // debugger reads. Make sure to specify the version statically, because the
48 // debugger checks the version before we can set it during runtime.
49 struct jit_descriptor __jit_debug_descriptor = { 1, 0, nullptr, nullptr };
50
51 // Debuggers puts a breakpoint in this function.
52 LLVM_ATTRIBUTE_NOINLINE void __jit_debug_register_code() {
53 // The noinline and the asm prevent calls to this function from being
54 // optimized out.
55 #if !defined(_MSC_VER)
56 asm volatile("":::"memory");
57 #endif
58 }
59
60 }
61
62 namespace {
63
64 struct RegisteredObjectInfo {
65 RegisteredObjectInfo() {}
66
67 RegisteredObjectInfo(std::size_t Size, jit_code_entry *Entry,
68 OwningBinary Obj)
69 : Size(Size), Entry(Entry), Obj(std::move(Obj)) {}
70
71 std::size_t Size;
72 jit_code_entry *Entry;
73 OwningBinary Obj;
74 };
75
76 // Buffer for an in-memory object file in executable memory
77 typedef llvm::DenseMap< const char*, RegisteredObjectInfo>
78 RegisteredObjectBufferMap;
79
80 /// Global access point for the JIT debugging interface designed for use with a
81 /// singleton toolbox. Handles thread-safe registration and deregistration of
82 /// object files that are in executable memory managed by the client of this
83 /// class.
84 class GDBJITRegistrationListener : public JITEventListener {
85 /// A map of in-memory object files that have been registered with the
86 /// JIT interface.
87 RegisteredObjectBufferMap ObjectBufferMap;
88
89 public:
90 /// Instantiates the JIT service.
91 GDBJITRegistrationListener() : ObjectBufferMap() {}
92
93 /// Unregisters each object that was previously registered and releases all
94 /// internal resources.
95 virtual ~GDBJITRegistrationListener();
96
97 /// Creates an entry in the JIT registry for the buffer @p Object,
98 /// which must contain an object file in executable memory with any
99 /// debug information for the debugger.
100 void NotifyObjectEmitted(const ObjectFile &Object,
101 const RuntimeDyld::LoadedObjectInfo &L) override;
102
103 /// Removes the internal registration of @p Object, and
104 /// frees associated resources.
105 /// Returns true if @p Object was found in ObjectBufferMap.
106 void NotifyFreeingObject(const ObjectFile &Object) override;
107
108 private:
109 /// Deregister the debug info for the given object file from the debugger
110 /// and delete any temporary copies. This private method does not remove
111 /// the function from Map so that it can be called while iterating over Map.
112 void deregisterObjectInternal(RegisteredObjectBufferMap::iterator I);
113 };
114
115 /// Lock used to serialize all jit registration events, since they
116 /// modify global variables.
117 ManagedStatic JITDebugLock;
118
119 /// Do the registration.
120 void NotifyDebugger(jit_code_entry* JITCodeEntry) {
121 __jit_debug_descriptor.action_flag = JIT_REGISTER_FN;
122
123 // Insert this entry at the head of the list.
124 JITCodeEntry->prev_entry = nullptr;
125 jit_code_entry* NextEntry = __jit_debug_descriptor.first_entry;
126 JITCodeEntry->next_entry = NextEntry;
127 if (NextEntry) {
128 NextEntry->prev_entry = JITCodeEntry;
129 }
130 __jit_debug_descriptor.first_entry = JITCodeEntry;
131 __jit_debug_descriptor.relevant_entry = JITCodeEntry;
132 __jit_debug_register_code();
133 }
134
135 GDBJITRegistrationListener::~GDBJITRegistrationListener() {
136 // Free all registered object files.
137 llvm::MutexGuard locked(*JITDebugLock);
138 for (RegisteredObjectBufferMap::iterator I = ObjectBufferMap.begin(),
139 E = ObjectBufferMap.end();
140 I != E; ++I) {
141 // Call the private method that doesn't update the map so our iterator
142 // doesn't break.
143 deregisterObjectInternal(I);
144 }
145 ObjectBufferMap.clear();
146 }
147
148 void GDBJITRegistrationListener::NotifyObjectEmitted(
149 const ObjectFile &Object,
150 const RuntimeDyld::LoadedObjectInfo &L) {
151
152 OwningBinary DebugObj = L.getObjectForDebug(Object);
153 const char *Buffer = DebugObj.getBinary()->getMemoryBufferRef().getBufferStart();
154 size_t Size = DebugObj.getBinary()->getMemoryBufferRef().getBufferSize();
155
156 const char *Key = Object.getMemoryBufferRef().getBufferStart();
157
158 assert(Key && "Attempt to register a null object with a debugger.");
159 llvm::MutexGuard locked(*JITDebugLock);
160 assert(ObjectBufferMap.find(Key) == ObjectBufferMap.end() &&
161 "Second attempt to perform debug registration.");
162 jit_code_entry* JITCodeEntry = new jit_code_entry();
163
164 if (!JITCodeEntry) {
165 llvm::report_fatal_error(
166 "Allocation failed when registering a JIT entry!\n");
167 } else {
168 JITCodeEntry->symfile_addr = Buffer;
169 JITCodeEntry->symfile_size = Size;
170
171 ObjectBufferMap[Key] = RegisteredObjectInfo(Size, JITCodeEntry,
172 std::move(DebugObj));
173 NotifyDebugger(JITCodeEntry);
174 }
175 }
176
177 void GDBJITRegistrationListener::NotifyFreeingObject(const ObjectFile& Object) {
178 const char *Key = Object.getMemoryBufferRef().getBufferStart();
179 llvm::MutexGuard locked(*JITDebugLock);
180 RegisteredObjectBufferMap::iterator I = ObjectBufferMap.find(Key);
181
182 if (I != ObjectBufferMap.end()) {
183 deregisterObjectInternal(I);
184 ObjectBufferMap.erase(I);
185 }
186 }
187
188 void GDBJITRegistrationListener::deregisterObjectInternal(
189 RegisteredObjectBufferMap::iterator I) {
190
191 jit_code_entry*& JITCodeEntry = I->second.Entry;
192
193 // Do the unregistration.
194 {
195 __jit_debug_descriptor.action_flag = JIT_UNREGISTER_FN;
196
197 // Remove the jit_code_entry from the linked list.
198 jit_code_entry* PrevEntry = JITCodeEntry->prev_entry;
199 jit_code_entry* NextEntry = JITCodeEntry->next_entry;
200
201 if (NextEntry) {
202 NextEntry->prev_entry = PrevEntry;
203 }
204 if (PrevEntry) {
205 PrevEntry->next_entry = NextEntry;
206 }
207 else {
208 assert(__jit_debug_descriptor.first_entry == JITCodeEntry);
209 __jit_debug_descriptor.first_entry = NextEntry;
210 }
211
212 // Tell the debugger which entry we removed, and unregister the code.
213 __jit_debug_descriptor.relevant_entry = JITCodeEntry;
214 __jit_debug_register_code();
215 }
216
217 delete JITCodeEntry;
218 JITCodeEntry = nullptr;
219 }
220
221 llvm::ManagedStatic GDBRegListener;
222
223 } // end namespace
224
225 namespace llvm {
226
227 JITEventListener* JITEventListener::createGDBRegistrationListener() {
228 return &*GDBRegListener;
229 }
230
231 } // namespace llvm
+0
-44
lib/ExecutionEngine/RuntimeDyld/JITRegistrar.h less more
None //===-- JITRegistrar.h - Registers objects with a debugger ----------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #ifndef LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_JITREGISTRAR_H
10 #define LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_JITREGISTRAR_H
11
12 #include "llvm/ExecutionEngine/ObjectBuffer.h"
13
14 namespace llvm {
15
16 /// Global access point for the JIT debugging interface.
17 class JITRegistrar {
18 virtual void anchor();
19 public:
20 /// Instantiates the JIT service.
21 JITRegistrar() {}
22
23 /// Unregisters each object that was previously registered and releases all
24 /// internal resources.
25 virtual ~JITRegistrar() {}
26
27 /// Creates an entry in the JIT registry for the buffer @p Object,
28 /// which must contain an object file in executable memory with any
29 /// debug information for the debugger.
30 virtual void registerObject(const ObjectBuffer &Object) = 0;
31
32 /// Removes the internal registration of @p Object, and
33 /// frees associated resources.
34 /// Returns true if @p Object was previously registered.
35 virtual bool deregisterObject(const ObjectBuffer &Object) = 0;
36
37 /// Returns a reference to a GDB JIT registrar singleton
38 static JITRegistrar& getGDBRegistrar();
39 };
40
41 } // end namespace llvm
42
43 #endif
+0
-86
lib/ExecutionEngine/RuntimeDyld/ObjectImageCommon.h less more
None //===-- ObjectImageCommon.h - Format independent executuable object image -===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares a file format independent ObjectImage class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_OBJECTIMAGECOMMON_H
14 #define LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_OBJECTIMAGECOMMON_H
15
16 #include "llvm/ExecutionEngine/ObjectBuffer.h"
17 #include "llvm/ExecutionEngine/ObjectImage.h"
18 #include "llvm/Object/ObjectFile.h"
19
20 #include
21
22 namespace llvm {
23
24 namespace object {
25 class ObjectFile;
26 }
27
28 class ObjectImageCommon : public ObjectImage {
29 ObjectImageCommon(); // = delete
30 ObjectImageCommon(const ObjectImageCommon &other); // = delete
31 void anchor() override;
32
33 protected:
34 std::unique_ptr ObjFile;
35
36 // This form of the constructor allows subclasses to use
37 // format-specific subclasses of ObjectFile directly
38 ObjectImageCommon(std::unique_ptr Input,
39 std::unique_ptr Obj)
40 : ObjectImage(std::move(Input)), ObjFile(std::move(Obj)) {}
41
42 public:
43 ObjectImageCommon(std::unique_ptr Input)
44 : ObjectImage(std::move(Input)) {
45 // FIXME: error checking? createObjectFile returns an ErrorOr
46 // and should probably be checked for failure.
47 MemoryBufferRef Buf = Buffer->getMemBuffer();
48 ObjFile = std::move(object::ObjectFile::createObjectFile(Buf).get());
49 }
50 ObjectImageCommon(std::unique_ptr Input)
51 : ObjectImage(nullptr), ObjFile(std::move(Input)) {}
52 virtual ~ObjectImageCommon() { }
53
54 object::symbol_iterator begin_symbols() const override
55 { return ObjFile->symbol_begin(); }
56 object::symbol_iterator end_symbols() const override
57 { return ObjFile->symbol_end(); }
58
59 object::section_iterator begin_sections() const override
60 { return ObjFile->section_begin(); }
61 object::section_iterator end_sections() const override
62 { return ObjFile->section_end(); }
63
64 /* Triple::ArchType */ unsigned getArch() const override
65 { return ObjFile->getArch(); }
66
67 StringRef getData() const override { return ObjFile->getData(); }
68
69 object::ObjectFile* getObjectFile() const override { return ObjFile.get(); }
70
71 // Subclasses can override these methods to update the image with loaded
72 // addresses for sections and common symbols
73 void updateSectionAddress(const object::SectionRef &Sec,
74 uint64_t Addr) override {}
75 void updateSymbolAddress(const object::SymbolRef &Sym,
76 uint64_t Addr) override {}
77
78 // Subclasses can override these methods to provide JIT debugging support
79 void registerWithDebugger() override {}
80 void deregisterWithDebugger() override {}
81 };
82
83 } // end namespace llvm
84
85 #endif
1111 //===----------------------------------------------------------------------===//
1212
1313 #include "llvm/ExecutionEngine/RuntimeDyld.h"
14 #include "JITRegistrar.h"
15 #include "ObjectImageCommon.h"
1614 #include "RuntimeDyldCheckerImpl.h"
1715 #include "RuntimeDyldELF.h"
1816 #include "RuntimeDyldImpl.h"
2927 // Empty out-of-line virtual destructor as the key function.
3028 RuntimeDyldImpl::~RuntimeDyldImpl() {}
3129
32 // Pin the JITRegistrar's and ObjectImage*'s vtables to this file.
33 void JITRegistrar::anchor() {}
34 void ObjectImage::anchor() {}
35 void ObjectImageCommon::anchor() {}
30 // Pin LoadedObjectInfo's vtables to this file.
31 void RuntimeDyld::LoadedObjectInfo::anchor() {}
3632
3733 namespace llvm {
3834
138134 return object_error::success;
139135 }
140136
141 std::unique_ptr
142 RuntimeDyldImpl::loadObject(std::unique_ptr Obj) {
137 std::pair
138 RuntimeDyldImpl::loadObjectImpl(const object::ObjectFile &Obj) {
143139 MutexGuard locked(lock);
144140
145 if (!Obj)
146 return nullptr;
141 // Grab the first Section ID. We'll use this later to construct the underlying
142 // range for the returned LoadedObjectInfo.
143 unsigned SectionsAddedBeginIdx = Sections.size();
147144
148145 // Save information about our target
149 Arch = (Triple::ArchType)Obj->getArch();
150 IsTargetLittleEndian = Obj->getObjectFile()->isLittleEndian();
146 Arch = (Triple::ArchType)Obj.getArch();
147 IsTargetLittleEndian = Obj.isLittleEndian();
151148
152149 // Compute the memory size required to load all sections to be loaded
153150 // and pass this information to the memory manager
154151 if (MemMgr->needsToReserveAllocationSpace()) {
155152 uint64_t CodeSize = 0, DataSizeRO = 0, DataSizeRW = 0;
156 computeTotalAllocSize(*Obj, CodeSize, DataSizeRO, DataSizeRW);
153 computeTotalAllocSize(Obj, CodeSize, DataSizeRO, DataSizeRW);
157154 MemMgr->reserveAllocationSpace(CodeSize, DataSizeRO, DataSizeRW);
158155 }
159156
169166
170167 // Parse symbols
171168 DEBUG(dbgs() << "Parse symbols:\n");
172 for (symbol_iterator I = Obj->begin_symbols(), E = Obj->end_symbols(); I != E;
169 for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
173170 ++I) {
174171 object::SymbolRef::Type SymType;
175172 StringRef Name;
195192 SymType == object::SymbolRef::ST_Unknown) {
196193 uint64_t SectOffset;
197194 StringRef SectionData;
198 section_iterator SI = Obj->end_sections();
195 section_iterator SI = Obj.section_end();
199196 Check(getOffset(*I, SectOffset));
200197 Check(I->getSection(SI));
201 if (SI == Obj->end_sections())
198 if (SI == Obj.section_end())
202199 continue;
203200 Check(SI->getContents(SectionData));
204201 bool IsCode = SI->isText();
205202 unsigned SectionID =
206 findOrEmitSection(*Obj, *SI, IsCode, LocalSections);
203 findOrEmitSection(Obj, *SI, IsCode, LocalSections);
207204 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
208205 DEBUG(dbgs() << "\tOffset: " << format("%p", (uintptr_t)SectOffset)
209206 << " flags: " << Flags << " SID: " << SectionID);
215212
216213 // Allocate common symbols
217214 if (CommonSize != 0)
218 emitCommonSymbols(*Obj, CommonSymbols, CommonSize, GlobalSymbolTable);
215 emitCommonSymbols(Obj, CommonSymbols, CommonSize, GlobalSymbolTable);
219216
220217 // Parse and process relocations
221218 DEBUG(dbgs() << "Parse relocations:\n");
222 for (section_iterator SI = Obj->begin_sections(), SE = Obj->end_sections();
219 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
223220 SI != SE; ++SI) {
224221 unsigned SectionID = 0;
225222 StubMap Stubs;
233230
234231 bool IsCode = RelocatedSection->isText();
235232 SectionID =
236 findOrEmitSection(*Obj, *RelocatedSection, IsCode, LocalSections);
233 findOrEmitSection(Obj, *RelocatedSection, IsCode, LocalSections);
237234 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
238235
239236 for (; I != E;)
240 I = processRelocationRef(SectionID, I, *Obj, LocalSections, LocalSymbols,
237 I = processRelocationRef(SectionID, I, Obj, LocalSections, LocalSymbols,
241238 Stubs);
242239
243240 // If there is an attached checker, notify it about the stubs for this
244241 // section so that they can be verified.
245242 if (Checker)
246 Checker->registerStubMap(Obj->getImageName(), SectionID, Stubs);
243 Checker->registerStubMap(Obj.getFileName(), SectionID, Stubs);
247244 }
248245
249246 // Give the subclasses a chance to tie-up any loose ends.
250 finalizeLoad(*Obj, LocalSections);
251
252 return Obj;
247 finalizeLoad(Obj, LocalSections);
248
249 unsigned SectionsAddedEndIdx = Sections.size();
250
251 return std::make_pair(SectionsAddedBeginIdx, SectionsAddedEndIdx);
253252 }
254253
255254 // A helper method for computeTotalAllocSize.
269268
270269 // Compute an upper bound of the memory size that is required to load all
271270 // sections
272 void RuntimeDyldImpl::computeTotalAllocSize(ObjectImage &Obj,
271 void RuntimeDyldImpl::computeTotalAllocSize(const ObjectFile &Obj,
273272 uint64_t &CodeSize,
274273 uint64_t &DataSizeRO,
275274 uint64_t &DataSizeRW) {
281280
282281 // Collect sizes of all sections to be loaded;
283282 // also determine the max alignment of all sections
284 for (section_iterator SI = Obj.begin_sections(), SE = Obj.end_sections();
283 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
285284 SI != SE; ++SI) {
286285 const SectionRef &Section = *SI;
287286
327326
328327 // Compute the size of all common symbols
329328 uint64_t CommonSize = 0;
330 for (symbol_iterator I = Obj.begin_symbols(), E = Obj.end_symbols(); I != E;
329 for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
331330 ++I) {
332331 uint32_t Flags = I->getFlags();
333332 if (Flags & SymbolRef::SF_Common) {
352351 }
353352
354353 // compute stub buffer size for the given section
355 unsigned RuntimeDyldImpl::computeSectionStubBufSize(ObjectImage &Obj,
354 unsigned RuntimeDyldImpl::computeSectionStubBufSize(const ObjectFile &Obj,
356355 const SectionRef &Section) {
357356 unsigned StubSize = getMaxStubSize();
358357 if (StubSize == 0) {
362361 // necessary section allocation size in loadObject by walking all the sections
363362 // once.
364363 unsigned StubBufSize = 0;
365 for (section_iterator SI = Obj.begin_sections(), SE = Obj.end_sections();
364 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
366365 SI != SE; ++SI) {
367366 section_iterator RelSecI = SI->getRelocatedSection();
368367 if (!(RelSecI == Section))
417416 }
418417 }
419418
420 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
419 void RuntimeDyldImpl::emitCommonSymbols(const ObjectFile &Obj,
421420 const CommonSymbolMap &CommonSymbols,
422421 uint64_t TotalSize,
423422 SymbolTableMap &SymbolTable) {
449448 DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
450449 << format("%p\n", Addr));
451450 }
452 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
453451 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
454452 Offset += Size;
455453 Addr += Size;
456454 }
457455 }
458456
459 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
457 unsigned RuntimeDyldImpl::emitSection(const ObjectFile &Obj,
460458 const SectionRef &Section, bool IsCode) {
461459
462460 StringRef data;
520518 << " new addr: " << format("%p", Addr)
521519 << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
522520 << " Allocate: " << Allocate << "\n");
523 Obj.updateSectionAddress(Section, (uint64_t)Addr);
524521 } else {
525522 // Even if we didn't load the section, we need to record an entry for it
526523 // to handle later processing (and by 'handle' I mean don't do anything
536533 Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
537534
538535 if (Checker)
539 Checker->registerSection(Obj.getImageName(), SectionID);
536 Checker->registerSection(Obj.getFileName(), SectionID);
540537
541538 return SectionID;
542539 }
543540
544 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
541 unsigned RuntimeDyldImpl::findOrEmitSection(const ObjectFile &Obj,
545542 const SectionRef &Section,
546543 bool IsCode,
547544 ObjSectionToIDMap &LocalSections) {
738735
739736 //===----------------------------------------------------------------------===//
740737 // RuntimeDyld class implementation
738
739 uint64_t RuntimeDyld::LoadedObjectInfo::getSectionLoadAddress(
740 StringRef SectionName) const {
741 for (unsigned I = BeginIdx; I != EndIdx; ++I)
742 if (RTDyld.Sections[I].Name == SectionName)
743 return RTDyld.Sections[I].LoadAddress;
744
745 return 0;
746 }
747
741748 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
742749 // FIXME: There's a potential issue lurking here if a single instance of
743750 // RuntimeDyld is used to load multiple objects. The current implementation
771778 return Dyld;
772779 }
773780
774 std::unique_ptr
775 RuntimeDyld::loadObject(std::unique_ptr InputObject) {
776 std::unique_ptr InputImage;
777
778 ObjectFile &Obj = *InputObject;
779
780 if (InputObject->isELF()) {
781 InputImage.reset(RuntimeDyldELF::createObjectImageFromFile(std::move(InputObject)));
782 if (!Dyld)
781 std::unique_ptr
782 RuntimeDyld::loadObject(const ObjectFile &Obj) {
783 if (!Dyld) {
784 if (Obj.isELF())
783785 Dyld = createRuntimeDyldELF(MM, ProcessAllSections, Checker);
784 } else if (InputObject->isMachO()) {
785 InputImage.reset(RuntimeDyldMachO::createObjectImageFromFile(std::move(InputObject)));
786 if (!Dyld)
786 else if (Obj.isMachO())
787787 Dyld = createRuntimeDyldMachO(
788 static_cast(InputImage->getArch()), MM,
789 ProcessAllSections, Checker);
790 } else
788 static_cast(Obj.getArch()), MM,
789 ProcessAllSections, Checker);
790 else
791 report_fatal_error("Incompatible object format!");
792 }
793
794 if (!Dyld->isCompatibleFile(Obj))
791795 report_fatal_error("Incompatible object format!");
792796
793 if (!Dyld->isCompatibleFile(&Obj))
794 report_fatal_error("Incompatible object format!");
795
796 return Dyld->loadObject(std::move(InputImage));
797 }
798
799 std::unique_ptr
800 RuntimeDyld::loadObject(std::unique_ptr InputBuffer) {
801 std::unique_ptr InputImage;
802 sys::fs::file_magic Type = sys::fs::identify_magic(InputBuffer->getBuffer());
803 auto *InputBufferPtr = InputBuffer.get();
804
805 switch (Type) {
806 case sys::fs::file_magic::elf:
807 case sys::fs::file_magic::elf_relocatable:
808 case sys::fs::file_magic::elf_executable:
809 case sys::fs::file_magic::elf_shared_object:
810 case sys::fs::file_magic::elf_core:
811 InputImage = RuntimeDyldELF::createObjectImage(std::move(InputBuffer));
812 if (!Dyld)
813 Dyld = createRuntimeDyldELF(MM, ProcessAllSections, Checker);
814 break;
815 case sys::fs::file_magic::macho_object:
816 case sys::fs::file_magic::macho_executable:
817 case sys::fs::file_magic::macho_fixed_virtual_memory_shared_lib:
818 case sys::fs::file_magic::macho_core:
819 case sys::fs::file_magic::macho_preload_executable:
820 case sys::fs::file_magic::macho_dynamically_linked_shared_lib:
821 case sys::fs::file_magic::macho_dynamic_linker:
822 case sys::fs::file_magic::macho_bundle:
823 case sys::fs::file_magic::macho_dynamically_linked_shared_lib_stub:
824 case sys::fs::file_magic::macho_dsym_companion:
825 InputImage = RuntimeDyldMachO::createObjectImage(std::move(InputBuffer));
826 if (!Dyld)
827 Dyld = createRuntimeDyldMachO(
828 static_cast(InputImage->getArch()), MM,
829 ProcessAllSections, Checker);
830 break;
831 case sys::fs::file_magic::unknown:
832 case sys::fs::file_magic::bitcode:
833 case sys::fs::file_magic::archive:
834 case sys::fs::file_magic::coff_object:
835 case sys::fs::file_magic::coff_import_library:
836 case sys::fs::file_magic::pecoff_executable:
837 case sys::fs::file_magic::macho_universal_binary:
838 case sys::fs::file_magic::windows_resource:
839 report_fatal_error("Incompatible object format!");
840 }
841
842 if (!Dyld->isCompatibleFormat(InputBufferPtr))
843 report_fatal_error("Incompatible object format!");
844
845 return Dyld->loadObject(std::move(InputImage));
797 return Dyld->loadObject(Obj);
846798 }
847799
848800 void *RuntimeDyld::getSymbolAddress(StringRef Name) const {
1111 //===----------------------------------------------------------------------===//
1212
1313 #include "RuntimeDyldELF.h"
14 #include "JITRegistrar.h"
15 #include "ObjectImageCommon.h"
1614 #include "llvm/ADT/IntervalMap.h"
1715 #include "llvm/ADT/STLExtras.h"
1816 #include "llvm/ADT/StringRef.h"
1917 #include "llvm/ADT/Triple.h"
20 #include "llvm/ExecutionEngine/ObjectBuffer.h"
21 #include "llvm/ExecutionEngine/ObjectImage.h"
18 #include "llvm/MC/MCStreamer.h"
2219 #include "llvm/Object/ELFObjectFile.h"
2320 #include "llvm/Object/ObjectFile.h"
2421 #include "llvm/Support/ELF.h"
2522 #include "llvm/Support/Endian.h"
2623 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/TargetRegistry.h"
2725
2826 using namespace llvm;
2927 using namespace llvm::object;
3028
3129 #define DEBUG_TYPE "dyld"
32
33 namespace {
3430
3531 static inline std::error_code check(std::error_code Err) {
3632 if (Err) {
3834 }
3935 return Err;
4036 }
37
38 namespace {
4139
4240 template class DyldELFObject : public ELFObjectFile {
4341 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
5149
5250 typedef typename ELFDataTypeTypedefHelper::value_type addr_type;
5351
54 std::unique_ptr UnderlyingFile;
55
5652 public:
57 DyldELFObject(std::unique_ptr UnderlyingFile,
58 MemoryBufferRef Wrapper, std::error_code &ec);
59
6053 DyldELFObject(MemoryBufferRef Wrapper, std::error_code &ec);
6154
6255 void updateSectionAddress(const SectionRef &Sec, uint64_t Addr);
63 void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr);
56
57 void updateSymbolAddress(const SymbolRef &SymRef, uint64_t Addr);
6458
6559 // Methods for type inquiry through isa, cast and dyn_cast
6660 static inline bool classof(const Binary *v) {
7064 static inline bool classof(const ELFObjectFile *v) {
7165 return v->isDyldType();
7266 }
67
7368 };
7469
75 template class ELFObjectImage : public ObjectImageCommon {
76 bool Registered;
77
78 public:
79 ELFObjectImage(std::unique_ptr Input,
80 std::unique_ptr> Obj)
81 : ObjectImageCommon(std::move(Input), std::move(Obj)), Registered(false) {
82 }
83
84 virtual ~ELFObjectImage() {
85 if (Registered)
86 deregisterWithDebugger();
87 }
88
89 // Subclasses can override these methods to update the image with loaded
90 // addresses for sections and common symbols
91 void updateSectionAddress(const SectionRef &Sec, uint64_t Addr) override {
92 static_cast*>(getObjectFile())
93 ->updateSectionAddress(Sec, Addr);
94 }
95
96 void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr) override {
97 static_cast*>(getObjectFile())
98 ->updateSymbolAddress(Sym, Addr);
99 }
100
101 void registerWithDebugger() override {
102 JITRegistrar::getGDBRegistrar().registerObject(*Buffer);
103 Registered = true;
104 }
105 void deregisterWithDebugger() override {
106 JITRegistrar::getGDBRegistrar().deregisterObject(*Buffer);
107 }
108 };
70
10971
11072 // The MemoryBuffer passed into this constructor is just a wrapper around the
11173 // actual memory. Ultimately, the Binary parent class will take ownership of
11779 }
11880
11981 template
120 DyldELFObject::DyldELFObject(std::unique_ptr UnderlyingFile,
121 MemoryBufferRef Wrapper, std::error_code &EC)
122 : ELFObjectFile(Wrapper, EC),
123 UnderlyingFile(std::move(UnderlyingFile)) {
124 this->isDyldELFObject = true;
125 }
126
127 template
12882 void DyldELFObject::updateSectionAddress(const SectionRef &Sec,
12983 uint64_t Addr) {
13084 DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
148102 sym->st_value = static_cast(Addr);
149103 }
150104
105 class LoadedELFObjectInfo : public RuntimeDyld::LoadedObjectInfo {
106 public:
107 LoadedELFObjectInfo(RuntimeDyldImpl &RTDyld, unsigned BeginIdx,
108 unsigned EndIdx)
109 : RuntimeDyld::LoadedObjectInfo(RTDyld, BeginIdx, EndIdx) {}
110
111 OwningBinary
112 getObjectForDebug(const ObjectFile &Obj) const override;
113 };
114
115 template
116 std::unique_ptr>
117 createRTDyldELFObject(MemoryBufferRef Buffer,
118 const LoadedELFObjectInfo &L,
119 std::error_code &ec) {
120 typedef typename ELFFile::Elf_Shdr Elf_Shdr;
121 typedef typename ELFDataTypeTypedefHelper::value_type addr_type;
122
123 std::unique_ptr> Obj =
124 llvm::make_unique>(Buffer, ec);
125
126 // Iterate over all sections in the object.
127 for (const auto &Sec : Obj->sections()) {
128 StringRef SectionName;
129 Sec.getName(SectionName);
130 if (SectionName != "") {
131 DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
132 Elf_Shdr *shdr = const_cast(
133 reinterpret_cast(ShdrRef.p));
134
135 if (uint64_t SecLoadAddr = L.getSectionLoadAddress(SectionName)) {
136 // This assumes that the address passed in matches the target address
137 // bitness. The template-based type cast handles everything else.
138 shdr->sh_addr = static_cast(SecLoadAddr);
139 }
140 }
141 }
142
143 return Obj;
144 }
145
146 OwningBinary createELFDebugObject(const ObjectFile &Obj,
147 const LoadedELFObjectInfo &L) {
148 assert(Obj.isELF() && "Not an ELF object file.");
149
150 std::unique_ptr Buffer =
151 MemoryBuffer::getMemBufferCopy(Obj.getData(), Obj.getFileName());
152
153 std::error_code ec;
154
155 std::unique_ptr DebugObj;
156 if (Obj.getBytesInAddress() == 4 && Obj.isLittleEndian()) {
157 typedef ELFType ELF32LE;
158 DebugObj = createRTDyldELFObject(Buffer->getMemBufferRef(), L, ec);
159 } else if (Obj.getBytesInAddress() == 4 && !Obj.isLittleEndian()) {
160 typedef ELFType ELF32BE;
161 DebugObj = createRTDyldELFObject(Buffer->getMemBufferRef(), L, ec);
162 } else if (Obj.getBytesInAddress() == 8 && !Obj.isLittleEndian()) {
163 typedef ELFType ELF64BE;
164 DebugObj = createRTDyldELFObject(Buffer->getMemBufferRef(), L, ec);
165 } else if (Obj.getBytesInAddress() == 8 && Obj.isLittleEndian()) {
166 typedef ELFType ELF64LE;
167 DebugObj = createRTDyldELFObject(Buffer->getMemBufferRef(), L, ec);
168 } else
169 llvm_unreachable("Unexpected ELF format");
170
171 assert(!ec && "Could not construct copy ELF object file");
172
173 return OwningBinary(std::move(DebugObj), std::move(Buffer));
174 }
175
176 OwningBinary
177 LoadedELFObjectInfo::getObjectForDebug(const ObjectFile &Obj) const {
178 return createELFDebugObject(Obj, *this);
179 }
180
151181 } // namespace
152182
153183 namespace llvm {
184
185 RuntimeDyldELF::RuntimeDyldELF(RTDyldMemoryManager *mm) : RuntimeDyldImpl(mm) {}
186 RuntimeDyldELF::~RuntimeDyldELF() {}
154187
155188 void RuntimeDyldELF::registerEHFrames() {
156189 if (!MemMgr)
179212 RegisteredEHFrameSections.clear();
180213 }
181214
182 ObjectImage *
183 RuntimeDyldELF::createObjectImageFromFile(std::unique_ptr ObjFile) {
184 if (!ObjFile)
185 return nullptr;
186
187 std::error_code ec;
188 MemoryBufferRef Buffer = ObjFile->getMemoryBufferRef();
189
190 if (ObjFile->getBytesInAddress() == 4 && ObjFile->isLittleEndian()) {
191 auto Obj =
192 llvm::make_unique>>(
193 std::move(ObjFile), Buffer, ec);
194 return new ELFObjectImage>(
195 nullptr, std::move(Obj));
196 } else if (ObjFile->getBytesInAddress() == 4 && !ObjFile->isLittleEndian()) {
197 auto Obj =
198 llvm::make_unique>>(
199 std::move(ObjFile), Buffer, ec);
200 return new ELFObjectImage>(nullptr, std::move(Obj));
201 } else if (ObjFile->getBytesInAddress() == 8 && !ObjFile->isLittleEndian()) {
202 auto Obj = llvm::make_unique>>(
203 std::move(ObjFile), Buffer, ec);
204 return new ELFObjectImage>(nullptr,
205 std::move(Obj));
206 } else if (ObjFile->getBytesInAddress() == 8 && ObjFile->isLittleEndian()) {
207 auto Obj =
208 llvm::make_unique>>(
209 std::move(ObjFile), Buffer, ec);
210 return new ELFObjectImage>(
211 nullptr, std::move(Obj));
212 } else
213 llvm_unreachable("Unexpected ELF format");
214 }
215
216 std::unique_ptr
217 RuntimeDyldELF::createObjectImage(std::unique_ptr Buffer) {
218 if (Buffer->getBufferSize() < ELF::EI_NIDENT)
219 llvm_unreachable("Unexpected ELF object size");
220 std::pair Ident =
221 std::make_pair((uint8_t)Buffer->getBufferStart()[ELF::EI_CLASS],
222 (uint8_t)Buffer->getBufferStart()[ELF::EI_DATA]);
223 std::error_code ec;
224
225 MemoryBufferRef Buf = Buffer->getMemBuffer();
226
227 if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2LSB) {
228 auto Obj =
229 llvm::make_unique>>(
230 Buf, ec);
231 return llvm::make_unique<
232 ELFObjectImage>>(std::move(Buffer),
233 std::move(Obj));
234 }
235 if (Ident.first == ELF::ELFCLASS32 && Ident.second == ELF::ELFDATA2MSB) {
236 auto Obj =
237 llvm::make_unique>>(Buf,
238 ec);
239 return llvm::make_unique>>(
240 std::move(Buffer), std::move(Obj));
241 }
242 if (Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2MSB) {
243 auto Obj = llvm::make_unique>>(
244 Buf, ec);
245 return llvm::make_unique>>(
246 std::move(Buffer), std::move(Obj));
247 }
248 assert(Ident.first == ELF::ELFCLASS64 && Ident.second == ELF::ELFDATA2LSB &&
249 "Unexpected ELF format");
250 auto Obj =
251 llvm::make_unique>>(Buf,
252 ec);
253 return llvm::make_unique>>(
254 std::move(Buffer), std::move(Obj));
255 }
256
257 RuntimeDyldELF::~RuntimeDyldELF() {}
215 std::unique_ptr
216 RuntimeDyldELF::loadObject(const object::ObjectFile &O) {
217 unsigned SectionStartIdx, SectionEndIdx;
218 std::tie(SectionStartIdx, SectionEndIdx) = loadObjectImpl(O);
219 return llvm::make_unique(*this, SectionStartIdx,
220 SectionEndIdx);
221 }
258222
259223 void RuntimeDyldELF::resolveX86_64Relocation(const SectionEntry &Section,
260224 uint64_t Offset, uint64_t Value,
614578 }
615579
616580 // Return the .TOC. section and offset.
617 void RuntimeDyldELF::findPPC64TOCSection(ObjectImage &Obj,
581 void RuntimeDyldELF::findPPC64TOCSection(const ObjectFile &Obj,
618582 ObjSectionToIDMap &LocalSections,
619583 RelocationValueRef &Rel) {
620584 // Set a default SectionID in case we do not find a TOC section below.
627591
628592 // The TOC consists of sections .got, .toc, .tocbss, .plt in that
629593 // order. The TOC starts where the first of these sections starts.
630 for (section_iterator si = Obj.begin_sections(), se = Obj.end_sections();
594 for (section_iterator si = Obj.section_begin(), se = Obj.section_end();
631595 si != se; ++si) {
632596
633597 StringRef SectionName;
649613
650614 // Returns the sections and offset associated with the ODP entry referenced
651615 // by Symbol.
652 void RuntimeDyldELF::findOPDEntrySection(ObjectImage &Obj,
616 void RuntimeDyldELF::findOPDEntrySection(const ObjectFile &Obj,
653617 ObjSectionToIDMap &LocalSections,
654618 RelocationValueRef &Rel) {
655619 // Get the ELF symbol value (st_value) to compare with Relocation offset in
656620 // .opd entries
657 for (section_iterator si = Obj.begin_sections(), se = Obj.end_sections();
621 for (section_iterator si = Obj.section_begin(), se = Obj.section_end();
658622 si != se; ++si) {
659623 section_iterator RelSecI = si->getRelocatedSection();
660 if (RelSecI == Obj.end_sections())
624 if (RelSecI == Obj.section_end())
661625 continue;
662626
663627 StringRef RelSectionName;
699663 if (Rel.Addend != (int64_t)TargetSymbolOffset)
700664 continue;
701665
702 section_iterator tsi(Obj.end_sections());
666 section_iterator tsi(Obj.section_end());
703667 check(TargetSymbol->getSection(tsi));
704668 bool IsCode = tsi->isText();
705669 Rel.SectionID = findOrEmitSection(Obj, (*tsi), IsCode, LocalSections);
934898 }
935899
936900 relocation_iterator RuntimeDyldELF::processRelocationRef(
937 unsigned SectionID, relocation_iterator RelI, ObjectImage &Obj,
901 unsigned SectionID, relocation_iterator RelI,
902 const ObjectFile &Obj,
938903 ObjSectionToIDMap &ObjSectionToID, const SymbolTableMap &Symbols,
939904 StubMap &Stubs) {
940905 uint64_t RelType;
945910
946911 // Obtain the symbol name which is referenced in the relocation
947912 StringRef TargetName;
948 if (Symbol != Obj.end_symbols())
913 if (Symbol != Obj.symbol_end())
949914 Symbol->getName(TargetName);
950915 DEBUG(dbgs() << "\t\tRelType: " << RelType << " Addend: " << Addend
951916 << " TargetName: " << TargetName << "\n");
953918 // First search for the symbol in the local symbol table
954919 SymbolTableMap::const_iterator lsi = Symbols.end();
955920 SymbolRef::Type SymType = SymbolRef::ST_Unknown;
956 if (Symbol != Obj.end_symbols()) {
921 if (Symbol != Obj.symbol_end()) {
957922 lsi = Symbols.find(TargetName.data());
958923 Symbol->getType(SymType);
959924 }
964929 } else {
965930 // Search for the symbol in the global symbol table
966931 SymbolTableMap::const_iterator gsi = GlobalSymbolTable.end();
967 if (Symbol != Obj.end_symbols())
932 if (Symbol != Obj.symbol_end())
968933 gsi = GlobalSymbolTable.find(TargetName.data());
969934 if (gsi != GlobalSymbolTable.end()) {
970935 Value.SectionID = gsi->second.first;
976941 // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
977942 // and can be changed by another developers. Maybe best way is add
978943 // a new symbol type ST_Section to SymbolRef and use it.
979 section_iterator si(Obj.end_sections());
944 section_iterator si(Obj.section_end());
980945 Symbol->getSection(si);
981 if (si == Obj.end_sections())
946 if (si == Obj.section_end())
982947 llvm_unreachable("Symbol section not found, bad object file format!");
983948 DEBUG(dbgs() << "\t\tThis is section symbol\n");
984949 bool isCode = si->isText();
11341099 if (RelType == ELF::R_PPC64_REL24) {
11351100 // Determine ABI variant in use for this object.
11361101 unsigned AbiVariant;
1137 Obj.getObjectFile()->getPlatformFlags(AbiVariant);
1102 Obj.getPlatformFlags(AbiVariant);
11381103 AbiVariant &= ELF::EF_PPC64_ABI;
11391104 // A PPC branch relocation will need a stub function if the target is
11401105 // an external symbol (Symbol::ST_Unknown) or if the target address
14941459 return 0;
14951460 }
14961461
1497 void RuntimeDyldELF::finalizeLoad(ObjectImage &ObjImg,
1462 void RuntimeDyldELF::finalizeLoad(const ObjectFile &Obj,
14981463 ObjSectionToIDMap &SectionMap) {
14991464 // If necessary, allocate the global offset table
15001465 if (MemMgr) {
15321497 }
15331498 }
15341499
1535 bool RuntimeDyldELF::isCompatibleFormat(const ObjectBuffer *Buffer) const {
1536 if (Buffer->getBufferSize() < strlen(ELF::ElfMagic))
1537 return false;
1538 return (memcmp(Buffer->getBufferStart(), ELF::ElfMagic,
1539 strlen(ELF::ElfMagic))) == 0;
1540 }
1541
1542 bool RuntimeDyldELF::isCompatibleFile(const object::ObjectFile *Obj) const {
1543 return Obj->isELF();
1500 bool RuntimeDyldELF::isCompatibleFile(const object::ObjectFile &Obj) const {
1501 return Obj.isELF();
15441502 }
15451503
15461504 } // namespace llvm
2727 }
2828 return Err;
2929 }
30
3031 } // end anonymous namespace
3132
3233 class RuntimeDyldELF : public RuntimeDyldImpl {
34
3335 void resolveRelocation(const SectionEntry &Section, uint64_t Offset,
3436 uint64_t Value, uint32_t Type, int64_t Addend,
3537 uint64_t SymOffset = 0);
8082 return 1;
8183 }
8284
83 void findPPC64TOCSection(ObjectImage &Obj, ObjSectionToIDMap &LocalSections,
85 void findPPC64TOCSection(const ObjectFile &Obj,
86 ObjSectionToIDMap &LocalSections,
8487 RelocationValueRef &Rel);
85 void findOPDEntrySection(ObjectImage &Obj, ObjSectionToIDMap &LocalSections,
88 void findOPDEntrySection(const ObjectFile &Obj,
89 ObjSectionToIDMap &LocalSections,
8690 RelocationValueRef &Rel);
8791
8892 uint64_t findGOTEntry(uint64_t LoadAddr, uint64_t Offset);
103107 SmallVector RegisteredEHFrameSections;
104108
105109 public:
106 RuntimeDyldELF(RTDyldMemoryManager *mm) : RuntimeDyldImpl(mm) {}
110 RuntimeDyldELF(RTDyldMemoryManager *mm);
111 virtual ~RuntimeDyldELF();
112
113 std::unique_ptr
114 loadObject(const object::ObjectFile &O) override;
107115
108116 void resolveRelocation(const RelocationEntry &RE, uint64_t Value) override;
109117 relocation_iterator
110118 processRelocationRef(unsigned SectionID, relocation_iterator RelI,
111 ObjectImage &Obj, ObjSectionToIDMap &ObjSectionToID,
119 const ObjectFile &Obj,
120 ObjSectionToIDMap &ObjSectionToID,
112121 const SymbolTableMap &Symbols, StubMap &Stubs) override;
113 bool isCompatibleFormat(const ObjectBuffer *Buffer) const override;
114 bool isCompatibleFile(const object::ObjectFile *Buffer) const override;
122 bool isCompatibleFile(const object::ObjectFile &Obj) const override;
115123 void registerEHFrames() override;
116124 void deregisterEHFrames() override;
117 void finalizeLoad(ObjectImage &ObjImg,
125 void finalizeLoad(const ObjectFile &Obj,
118126 ObjSectionToIDMap &SectionMap) override;
119 virtual ~RuntimeDyldELF();
120
121 static std::unique_ptr
122 createObjectImage(std::unique_ptr InputBuffer);
123 static ObjectImage *createObjectImageFromFile(std::unique_ptr Obj);
124127 };
125128
126129 } // end namespace llvm
1717 #include "llvm/ADT/SmallVector.h"
1818 #include "llvm/ADT/StringMap.h"
1919 #include "llvm/ADT/Triple.h"
20 #include "llvm/ExecutionEngine/ObjectImage.h"
2120 #include "llvm/ExecutionEngine/RuntimeDyld.h"
2221 #include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
2322 #include "llvm/Object/ObjectFile.h"
3635
3736 namespace llvm {
3837
39 class ObjectBuffer;
4038 class Twine;
4139
4240 /// SectionEntry - represents a section emitted into memory by the dynamic
158156 };
159157
160158 class RuntimeDyldImpl {
159 friend class RuntimeDyld::LoadedObjectInfo;
161160 friend class RuntimeDyldCheckerImpl;
162161 private:
163162
295294 /// \brief Given the common symbols discovered in the object file, emit a
296295 /// new section for them and update the symbol mappings in the object and
297296 /// symbol table.
298 void emitCommonSymbols(ObjectImage &Obj, const CommonSymbolMap &CommonSymbols,
297 void emitCommonSymbols(const ObjectFile &Obj,
298 const CommonSymbolMap &CommonSymbols,
299299 uint64_t TotalSize, SymbolTableMap &SymbolTable);
300300
301301 /// \brief Emits section data from the object file to the MemoryManager.
302302 /// \param IsCode if it's true then allocateCodeSection() will be
303303 /// used for emits, else allocateDataSection() will be used.
304304 /// \return SectionID.
305 unsigned emitSection(ObjectImage &Obj, const SectionRef &Section,
305 unsigned emitSection(const ObjectFile &Obj, const SectionRef &Section,
306306 bool IsCode);
307307
308308 /// \brief Find Section in LocalSections. If the secton is not found - emit
310310 /// \param IsCode if it's true then allocateCodeSection() will be
311311 /// used for emmits, else allocateDataSection() will be used.
312312 /// \return SectionID.
313 unsigned findOrEmitSection(ObjectImage &Obj, const SectionRef &Section,
313 unsigned findOrEmitSection(const ObjectFile &Obj, const SectionRef &Section,
314314 bool IsCode, ObjSectionToIDMap &LocalSections);
315315
316316 // \brief Add a relocation entry that uses the given section.
338338 /// \return Iterator to the next relocation that needs to be parsed.
339339 virtual relocation_iterator
340340 processRelocationRef(unsigned SectionID, relocation_iterator RelI,
341 ObjectImage &Obj, ObjSectionToIDMap &ObjSectionToID,
341 const ObjectFile &Obj, ObjSectionToIDMap &ObjSectionToID,
342342 const SymbolTableMap &Symbols, StubMap &Stubs) = 0;
343343
344344 /// \brief Resolve relocations to external symbols.
350350
351351 // \brief Compute an upper bound of the memory that is required to load all
352352 // sections
353 void computeTotalAllocSize(ObjectImage &Obj, uint64_t &CodeSize,
353 void computeTotalAllocSize(const ObjectFile &Obj, uint64_t &CodeSize,
354354 uint64_t &DataSizeRO, uint64_t &DataSizeRW);
355355
356356 // \brief Compute the stub buffer size required for a section
357 unsigned computeSectionStubBufSize(ObjectImage &Obj,
357 unsigned computeSectionStubBufSize(const ObjectFile &Obj,
358358 const SectionRef &Section);
359
360 // \brief Implementation of the generic part of the loadObject algorithm.
361 std::pair loadObjectImpl(const object::ObjectFile &Obj);
359362
360363 public:
361364 RuntimeDyldImpl(RTDyldMemoryManager *mm)
372375 this->Checker = Checker;
373376 }
374377
375 std::unique_ptr
376 loadObject(std::unique_ptr InputObject);
378 virtual std::unique_ptr
379 loadObject(const object::ObjectFile &Obj) = 0;
377380
378381 uint8_t* getSymbolAddress(StringRef Name) const {
379382 // FIXME: Just look up as a function for now. Overly simple of course.
410413 // Get the error message.
411414 StringRef getErrorString() { return ErrorStr; }
412415
413 virtual bool isCompatibleFormat(const ObjectBuffer *Buffer) const = 0;
414 virtual bool isCompatibleFile(const ObjectFile *Obj) const = 0;
416 virtual bool isCompatibleFile(const ObjectFile &Obj) const = 0;
415417
416418 virtual void registerEHFrames();
417419
418420 virtual void deregisterEHFrames();
419421
420 virtual void finalizeLoad(ObjectImage &ObjImg, ObjSectionToIDMap &SectionMap) {}
422 virtual void finalizeLoad(const ObjectFile &ObjImg,
423 ObjSectionToIDMap &SectionMap) {}
421424 };
422425
423426 } // end namespace llvm
2424
2525 #define DEBUG_TYPE "dyld"
2626
27 namespace {
28
29 class LoadedMachOObjectInfo : public RuntimeDyld::LoadedObjectInfo {
30 public:
31 LoadedMachOObjectInfo(RuntimeDyldImpl &RTDyld, unsigned BeginIdx,
32 unsigned EndIdx)
33 : RuntimeDyld::LoadedObjectInfo(RTDyld, BeginIdx, EndIdx) {}
34
35 OwningBinary
36 getObjectForDebug(const ObjectFile &Obj) const override {
37 return OwningBinary();
38 }
39 };
40
41 };
42
2743 namespace llvm {
2844
2945 int64_t RuntimeDyldMachO::memcpyAddend(const RelocationEntry &RE) const {
3450 }
3551
3652 RelocationValueRef RuntimeDyldMachO::getRelocationValueRef(
37 ObjectImage &ObjImg, const relocation_iterator &RI,
53 const ObjectFile &BaseTObj, const relocation_iterator &RI,
3854 const RelocationEntry &RE, ObjSectionToIDMap &ObjSectionToID,
3955 const SymbolTableMap &Symbols) {
4056
4157 const MachOObjectFile &Obj =
42 static_cast(*ObjImg.getObjectFile());
58 static_cast(BaseTObj);
4359 MachO::any_relocation_info RelInfo =
4460 Obj.getRelocation(RI->getRawDataRefImpl());
4561 RelocationValueRef Value;
6682 } else {
6783 SectionRef Sec = Obj.getRelocationSection(RelInfo);
6884 bool IsCode = Sec.isText();
69 Value.SectionID = findOrEmitSection(ObjImg, Sec, IsCode, ObjSectionToID);
85 Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
7086 uint64_t Addr = Sec.getAddress();
7187 Value.Offset = RE.Addend - Addr;
7288 }
7591 }
7692
7793 void RuntimeDyldMachO::makeValueAddendPCRel(RelocationValueRef &Value,
78 ObjectImage &ObjImg,
94 const ObjectFile &BaseTObj,
7995 const relocation_iterator &RI,
8096 unsigned OffsetToNextPC) {
8197 const MachOObjectFile &Obj =
82 static_cast(*ObjImg.getObjectFile());
98 static_cast(BaseTObj);
8399 MachO::any_relocation_info RelInfo =
84100 Obj.getRelocation(RI->getRawDataRefImpl());
85101
124140
125141 // Populate __pointers section.
126142 void RuntimeDyldMachO::populateIndirectSymbolPointersSection(
127 MachOObjectFile &Obj,
143 const MachOObjectFile &Obj,
128144 const SectionRef &PTSection,
129145 unsigned PTSectionID) {
130146 assert(!Obj.is64Bit() &&
162178 }
163179 }
164180
165 bool
166 RuntimeDyldMachO::isCompatibleFormat(const ObjectBuffer *InputBuffer) const {
167 if (InputBuffer->getBufferSize() < 4)
168 return false;
169 StringRef Magic(InputBuffer->getBufferStart(), 4);
170 if (Magic == "\xFE\xED\xFA\xCE")
171 return true;
172 if (Magic == "\xCE\xFA\xED\xFE")
173 return true;
174 if (Magic == "\xFE\xED\xFA\xCF")
175 return true;
176 if (Magic == "\xCF\xFA\xED\xFE")
177 return true;
178 return false;
179 }
180
181 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile *Obj) const {
182 return Obj->isMachO();
181 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile &Obj) const {
182 return Obj.isMachO();
183183 }
184184
185185 template
186 void RuntimeDyldMachOCRTPBase::finalizeLoad(ObjectImage &ObjImg,
186 void RuntimeDyldMachOCRTPBase::finalizeLoad(const ObjectFile &ObjImg,
187187 ObjSectionToIDMap &SectionMap) {
188188 unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
189189 unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
283283 }
284284
285285 std::unique_ptr
286 llvm::RuntimeDyldMachO::create(Triple::ArchType Arch, RTDyldMemoryManager *MM) {
286 RuntimeDyldMachO::create(Triple::ArchType Arch, RTDyldMemoryManager *MM) {
287287 switch (Arch) {
288288 default:
289289 llvm_unreachable("Unsupported target for RuntimeDyldMachO.");
295295 }
296296 }
297297
298 std::unique_ptr
299 RuntimeDyldMachO::loadObject(const object::ObjectFile &O) {
300 unsigned SectionStartIdx, SectionEndIdx;
301 std::tie(SectionStartIdx, SectionEndIdx) = loadObjectImpl(O);
302 return llvm::make_unique(*this, SectionStartIdx,
303 SectionEndIdx);
304 }
305
298306 } // end namespace llvm
1313 #ifndef LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_RUNTIMEDYLDMACHO_H
1414 #define LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_RUNTIMEDYLDMACHO_H
1515
16 #include "ObjectImageCommon.h"
1716 #include "RuntimeDyldImpl.h"
1817 #include "llvm/Object/MachO.h"
1918 #include "llvm/Support/Format.h"
6059 /// filled in, since immediate encodings are highly target/opcode specific.
6160 /// For targets/opcodes with simple, contiguous immediates (e.g. X86) the
6261 /// memcpyAddend method can be used to read the immediate.
63 RelocationEntry getRelocationEntry(unsigned SectionID, ObjectImage &ObjImg,
62 RelocationEntry getRelocationEntry(unsigned SectionID,
63 const ObjectFile &BaseTObj,
6464 const relocation_iterator &RI) const {
6565 const MachOObjectFile &Obj =
66 static_cast(*ObjImg.getObjectFile());
66 static_cast(BaseTObj);
6767 MachO::any_relocation_info RelInfo =
6868 Obj.getRelocation(RI->getRawDataRefImpl());
6969
8686 /// In both cases the Addend field is *NOT* fixed up to be PC-relative. That
8787 /// should be done by the caller where appropriate by calling makePCRel on
8888 /// the RelocationValueRef.
89 RelocationValueRef getRelocationValueRef(ObjectImage &ObjImg,
89 RelocationValueRef getRelocationValueRef(const ObjectFile &BaseTObj,
9090 const relocation_iterator &RI,
9191 const RelocationEntry &RE,
9292 ObjSectionToIDMap &ObjSectionToID,
9393 const SymbolTableMap &Symbols);
9494
9595 /// Make the RelocationValueRef addend PC-relative.
96 void makeValueAddendPCRel(RelocationValueRef &Value, ObjectImage &ObjImg,
96 void makeValueAddendPCRel(RelocationValueRef &Value,
97 const ObjectFile &BaseTObj,
9798 const relocation_iterator &RI,
9899 unsigned OffsetToNextPC);
99100
106107
107108
108109 // Populate __pointers section.
109 void populateIndirectSymbolPointersSection(MachOObjectFile &Obj,
110 void populateIndirectSymbolPointersSection(const MachOObjectFile &Obj,
110111 const SectionRef &PTSection,
111112 unsigned PTSectionID);
112113
113114 public:
114 /// Create an ObjectImage from the given ObjectBuffer.
115 static std::unique_ptr
116 createObjectImage(std::unique_ptr InputBuffer) {
117 return llvm::make_unique(std::move(InputBuffer));
118 }
119
120 /// Create an ObjectImage from the given ObjectFile.
121 static ObjectImage *
122 createObjectImageFromFile(std::unique_ptr InputObject) {
123 return new ObjectImageCommon(std::move(InputObject));
124 }
125115
126116 /// Create a RuntimeDyldMachO instance for the given target architecture.
127117 static std::unique_ptr create(Triple::ArchType Arch,
128118 RTDyldMemoryManager *mm);
129119
120 std::unique_ptr
121 loadObject(const object::ObjectFile &O);
122
130123 SectionEntry &getSection(unsigned SectionID) { return Sections[SectionID]; }
131124
132 bool isCompatibleFormat(const ObjectBuffer *Buffer) const override;
133 bool isCompatibleFile(const object::ObjectFile *Obj) const override;
125 bool isCompatibleFile(const object::ObjectFile &Obj) const override;
134126 };
135127
136128 /// RuntimeDyldMachOTarget - Templated base class for generic MachO linker
152144 public:
153145 RuntimeDyldMachOCRTPBase(RTDyldMemoryManager *mm) : RuntimeDyldMachO(mm) {}
154146
155 void finalizeLoad(ObjectImage &ObjImg,
147 void finalizeLoad(const ObjectFile &Obj,
156148 ObjSectionToIDMap &SectionMap) override;
157149 void registerEHFrames() override;
158150 };
242242
243243 relocation_iterator
244244 processRelocationRef(unsigned SectionID, relocation_iterator RelI,
245 ObjectImage &ObjImg, ObjSectionToIDMap &ObjSectionToID,
245 const ObjectFile &BaseObjT,
246 ObjSectionToIDMap &ObjSectionToID,
246247 const SymbolTableMap &Symbols, StubMap &Stubs) override {
247248 const MachOObjectFile &Obj =
248 static_cast(*ObjImg.getObjectFile());
249 static_cast(BaseObjT);
249250 MachO::any_relocation_info RelInfo =
250251 Obj.getRelocation(RelI->getRawDataRefImpl());
251252
267268 RelInfo = Obj.getRelocation(RelI->getRawDataRefImpl());
268269 }
269270
270 RelocationEntry RE(getRelocationEntry(SectionID, ObjImg, RelI));
271 RelocationEntry RE(getRelocationEntry(SectionID, Obj, RelI));
271272 RE.Addend = decodeAddend(RE);
272273 RelocationValueRef Value(
273 getRelocationValueRef(ObjImg, RelI, RE, ObjSectionToID, Symbols));
274 getRelocationValueRef(Obj, RelI, RE, ObjSectionToID, Symbols));
274275
275276 assert((ExplicitAddend == 0 || RE.Addend == 0) && "Relocation has "\
276277 "ARM64_RELOC_ADDEND and embedded addend in the instruction.");
281282
282283 bool IsExtern = Obj.getPlainRelocationExternal(RelInfo);
283284 if (!IsExtern && RE.IsPCRel)
284 makeValueAddendPCRel(Value, ObjImg, RelI, 1 << RE.Size);
285 makeValueAddendPCRel(Value, Obj, RelI, 1 << RE.Size);
285286
286287 RE.Addend = Value.Offset;
287288
358359 }
359360 }
360361
361 void finalizeSection(ObjectImage &ObjImg, unsigned SectionID,
362 void finalizeSection(const ObjectFile &Obj, unsigned SectionID,
362363 const SectionRef &Section) {}
363364
364365 private:
4848
4949 relocation_iterator
5050 processRelocationRef(unsigned SectionID, relocation_iterator RelI,
51 ObjectImage &ObjImg, ObjSectionToIDMap &ObjSectionToID,
51 const ObjectFile &BaseObjT,
52 ObjSectionToIDMap &ObjSectionToID,
5253 const SymbolTableMap &Symbols, StubMap &Stubs) override {
5354 const MachOObjectFile &Obj =
54 static_cast(*ObjImg.getObjectFile());
55 static_cast(BaseObjT);
5556 MachO::any_relocation_info RelInfo =
5657 Obj.getRelocation(RelI->getRawDataRefImpl());
5758 uint32_t RelType = Obj.getAnyRelocationType(RelInfo);
5859
5960 if (Obj.isRelocationScattered(RelInfo)) {
6061 if (RelType == MachO::ARM_RELOC_HALF_SECTDIFF)
61 return processHALFSECTDIFFRelocation(SectionID, RelI, ObjImg,
62 return processHALFSECTDIFFRelocation(SectionID, RelI, Obj,
6263 ObjSectionToID);
6364 else
6465 return ++++RelI;
6566 }
6667
67 RelocationEntry RE(getRelocationEntry(SectionID, ObjImg, RelI));
68 RelocationEntry RE(getRelocationEntry(SectionID, Obj, RelI));
6869 RE.Addend = decodeAddend(RE);
6970 RelocationValueRef Value(
70 getRelocationValueRef(ObjImg, RelI, RE, ObjSectionToID, Symbols));
71 getRelocationValueRef(Obj, RelI, RE, ObjSectionToID, Symbols));
7172
7273 if (RE.IsPCRel)
73 makeValueAddendPCRel(Value, ObjImg, RelI, 8);
74 makeValueAddendPCRel(Value, Obj, RelI, 8);
7475
7576 if ((RE.RelType & 0xf) == MachO::ARM_RELOC_BR24)
7677 processBranchRelocation(RE, Value, Stubs);
153154 }
154155 }
155156
156 void finalizeSection(ObjectImage &ObjImg, unsigned SectionID,
157 void finalizeSection(const ObjectFile &Obj, unsigned SectionID,
157158 const SectionRef &Section) {
158159 StringRef Name;
159160 Section.getName(Name);
160161
161162 if (Name == "__nl_symbol_ptr")
162 populateIndirectSymbolPointersSection(
163 cast(*ObjImg.getObjectFile()),
164 Section, SectionID);
163 populateIndirectSymbolPointersSection(cast(Obj),
164 Section, SectionID);
165165 }
166166
167167 private:
198198
199199 relocation_iterator
200200 processHALFSECTDIFFRelocation(unsigned SectionID, relocation_iterator RelI,
201 ObjectImage &Obj,
201 const ObjectFile &BaseTObj,
202202 ObjSectionToIDMap &ObjSectionToID) {
203 const MachOObjectFile *MachO =
204 static_cast(Obj.getObjectFile());
203 const MachOObjectFile &MachO =
204 static_cast(BaseTObj);
205205 MachO::any_relocation_info RE =
206 MachO->getRelocation(RelI->getRawDataRefImpl());
206 MachO.getRelocation(RelI->getRawDataRefImpl());
207207
208208
209209 // For a half-diff relocation the length bits actually record whether this
210210 // is a movw/movt, and whether this is arm or thumb.
211211 // Bit 0 indicates movw (b0 == 0) or movt (b0 == 1).
212212 // Bit 1 indicates arm (b1 == 0) or thumb (b1 == 1).
213 unsigned HalfDiffKindBits = MachO->getAnyRelocationLength(RE);
213 unsigned HalfDiffKindBits = MachO.getAnyRelocationLength(RE);
214214 if (HalfDiffKindBits & 0x2)
215215 llvm_unreachable("Thumb not yet supported.");
216216
217217 SectionEntry &Section = Sections[SectionID];
218 uint32_t RelocType = MachO->getAnyRelocationType(RE);
219 bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
218 uint32_t RelocType = MachO.getAnyRelocationType(RE);
219 bool IsPCRel = MachO.getAnyRelocationPCRel(RE);
220220 uint64_t Offset;
221221 RelI->getOffset(Offset);
222222 uint8_t *LocalAddress = Section.Address + Offset;
225225
226226 ++RelI;
227227 MachO::any_relocation_info RE2 =
228 MachO->getRelocation(RelI->getRawDataRefImpl());
229 uint32_t AddrA = MachO->getScatteredRelocationValue(RE);
230 section_iterator SAI = getSectionByAddress(*MachO, AddrA);
231 assert(SAI != MachO->section_end() && "Can't find section for address A");
228 MachO.getRelocation(RelI->getRawDataRefImpl());
229 uint32_t AddrA = MachO.getScatteredRelocationValue(RE);
230 section_iterator SAI = getSectionByAddress(MachO, AddrA);
231 assert(SAI != MachO.section_end() && "Can't find section for address A");
232232 uint64_t SectionABase = SAI->getAddress();
233233 uint64_t SectionAOffset = AddrA - SectionABase;
234234 SectionRef SectionA = *SAI;
235235 bool IsCode = SectionA.isText();
236236 uint32_t SectionAID =
237 findOrEmitSection(Obj, SectionA, IsCode, ObjSectionToID);
238
239 uint32_t AddrB = MachO->getScatteredRelocationValue(RE2);
240 section_iterator SBI = getSectionByAddress(*MachO, AddrB);
241 assert(SBI != MachO->section_end() && "Can't find section for address B");
237 findOrEmitSection(MachO, SectionA, IsCode, ObjSectionToID);
238
239 uint32_t AddrB = MachO.getScatteredRelocationValue(RE2);
240 section_iterator SBI = getSectionByAddress(MachO, AddrB);
241 assert(SBI != MachO.section_end() && "Can't find section for address B");
242242 uint64_t SectionBBase = SBI->getAddress();
243243 uint64_t SectionBOffset = AddrB - SectionBBase;
244244 SectionRef SectionB = *SBI;
245245 uint32_t SectionBID =
246 findOrEmitSection(Obj, SectionB, IsCode, ObjSectionToID);
247
248 uint32_t OtherHalf = MachO->getAnyRelocationAddress(RE2) & 0xffff;
246 findOrEmitSection(MachO, SectionB, IsCode, ObjSectionToID);
247
248 uint32_t OtherHalf = MachO.getAnyRelocationAddress(RE2) & 0xffff;
249249 unsigned Shift = (HalfDiffKindBits & 0x1) ? 16 : 0;
250250 uint32_t FullImmVal = (Immediate << Shift) | (OtherHalf << (16 - Shift));
251251 int64_t Addend = FullImmVal - (AddrA - AddrB);
3030
3131 relocation_iterator
3232 processRelocationRef(unsigned SectionID, relocation_iterator RelI,
33 ObjectImage &ObjImg, ObjSectionToIDMap &ObjSectionToID,
33 const ObjectFile &BaseObjT,
34 ObjSectionToIDMap &ObjSectionToID,
3435 const SymbolTableMap &Symbols, StubMap &Stubs) override {
3536 const MachOObjectFile &Obj =
36 static_cast(*ObjImg.getObjectFile());
37 static_cast(BaseObjT);
3738 MachO::any_relocation_info RelInfo =
3839 Obj.getRelocation(RelI->getRawDataRefImpl());
3940 uint32_t RelType = Obj.getAnyRelocationType(RelInfo);
4142 if (Obj.isRelocationScattered(RelInfo)) {
4243 if (RelType == MachO::GENERIC_RELOC_SECTDIFF ||
4344 RelType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)
44 return processSECTDIFFRelocation(SectionID, RelI, ObjImg,
45 return processSECTDIFFRelocation(SectionID, RelI, Obj,
4546 ObjSectionToID);
4647 else if (RelType == MachO::GENERIC_RELOC_VANILLA)
47 return processI386ScatteredVANILLA(SectionID, RelI, ObjImg,
48 return processI386ScatteredVANILLA(SectionID, RelI, Obj,
4849 ObjSectionToID);
4950 llvm_unreachable("Unhandled scattered relocation.");
5051 }
5152
52 RelocationEntry RE(getRelocationEntry(SectionID, ObjImg, RelI));
53 RelocationEntry RE(getRelocationEntry(SectionID, Obj, RelI));
5354 RE.Addend = memcpyAddend(RE);
5455 RelocationValueRef Value(
55 getRelocationValueRef(ObjImg, RelI, RE, ObjSectionToID, Symbols));
56 getRelocationValueRef(Obj, RelI, RE, ObjSectionToID, Symbols));
5657
5758 // Addends for external, PC-rel relocations on i386 point back to the zero
5859 // offset. Calculate the final offset from the relocation target instead.
6566 // Value.Addend += RelocAddr + 4;
6667 // }
6768 if (RE.IsPCRel)
68 makeValueAddendPCRel(Value, ObjImg, RelI, 1 << RE.Size);
69 makeValueAddendPCRel(Value, Obj, RelI, 1 << RE.Size);
6970
7071 RE.Addend = Value.Offset;
7172
109110 }
110111 }
111112
112 void finalizeSection(ObjectImage &ObjImg, unsigned SectionID,
113 void finalizeSection(const ObjectFile &Obj, unsigned SectionID,
113114 const SectionRef &Section) {
114115 StringRef Name;
115116 Section.getName(Name);
116117
117118 if (Name == "__jump_table")
118 populateJumpTable(cast(*ObjImg.getObjectFile()), Section,
119 SectionID);
119 populateJumpTable(cast(Obj), Section, SectionID);
120120 else if (Name == "__pointers")
121 populateIndirectSymbolPointersSection(
122 cast(*ObjImg.getObjectFile()),
123 Section, SectionID);
121 populateIndirectSymbolPointersSection(cast(Obj),
122 Section, SectionID);
124123 }
125124
126125 private:
127126 relocation_iterator
128127 processSECTDIFFRelocation(unsigned SectionID, relocation_iterator RelI,
129 ObjectImage &Obj,
128 const ObjectFile &BaseObjT,
130129 ObjSectionToIDMap &ObjSectionToID) {
131 const MachOObjectFile *MachO =
132 static_cast(Obj.getObjectFile());
130 const MachOObjectFile &Obj =
131 static_cast(BaseObjT);
133132 MachO::any_relocation_info RE =
134 MachO->getRelocation(RelI->getRawDataRefImpl());
133 Obj.getRelocation(RelI->getRawDataRefImpl());
135134
136135 SectionEntry &Section = Sections[SectionID];
137 uint32_t RelocType = MachO->getAnyRelocationType(RE);
138 bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
139 unsigned Size = MachO->getAnyRelocationLength(RE);
136 uint32_t RelocType = Obj.getAnyRelocationType(RE);
137 bool IsPCRel = Obj.getAnyRelocationPCRel(RE);
138 unsigned Size = Obj.getAnyRelocationLength(RE);
140139 uint64_t Offset;
141140 RelI->getOffset(Offset);
142141 uint8_t *LocalAddress = Section.Address + Offset;
145144
146145 ++RelI;
147146 MachO::any_relocation_info RE2 =
148 MachO->getRelocation(RelI->getRawDataRefImpl());
149
150 uint32_t AddrA = MachO->getScatteredRelocationValue(RE);
151 section_iterator SAI = getSectionByAddress(*MachO, AddrA);
152 assert(SAI != MachO->section_end() && "Can't find section for address A");
147 Obj.getRelocation(RelI->getRawDataRefImpl());
148
149 uint32_t AddrA = Obj.getScatteredRelocationValue(RE);
150 section_iterator SAI = getSectionByAddress(Obj, AddrA);
151 assert(SAI != Obj.section_end() && "Can't find section for address A");
153152 uint64_t SectionABase = SAI->getAddress();
154153 uint64_t SectionAOffset = AddrA - SectionABase;
155154 SectionRef SectionA = *SAI;
157156 uint32_t SectionAID =
158157 findOrEmitSection(Obj, SectionA, IsCode, ObjSectionToID);
159158
160 uint32_t AddrB = MachO->getScatteredRelocationValue(RE2);
161 section_iterator SBI = getSectionByAddress(*MachO, AddrB);
162 assert(SBI != MachO->section_end() && "Can't find section for address B");
159 uint32_t AddrB = Obj.getScatteredRelocationValue(RE2);
160 section_iterator SBI = getSectionByAddress(Obj, AddrB);
161 assert(SBI != Obj.section_end() && "Can't find section for address B");
163162 uint64_t SectionBBase = SBI->getAddress();
164163 uint64_t SectionBOffset = AddrB - SectionBBase;
165164 SectionRef SectionB = *SBI;
185184 }
186185
187186 relocation_iterator processI386ScatteredVANILLA(
188 unsigned SectionID, relocation_iterator RelI, ObjectImage &Obj,
187 unsigned SectionID, relocation_iterator RelI,
188 const ObjectFile &BaseObjT,
189189 RuntimeDyldMachO::ObjSectionToIDMap &ObjSectionToID) {
190 const MachOObjectFile *MachO =
191 static_cast(Obj.getObjectFile());
190 const MachOObjectFile &Obj =
191 static_cast(BaseObjT);
192192 MachO::any_relocation_info RE =
193 MachO->getRelocation(RelI->getRawDataRefImpl());
193 Obj.getRelocation(RelI->getRawDataRefImpl());
194194
195195 SectionEntry &Section = Sections[SectionID];
196 uint32_t RelocType = MachO->getAnyRelocationType(RE);
197 bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
198 unsigned Size = MachO->getAnyRelocationLength(RE);
196 uint32_t RelocType = Obj.getAnyRelocationType(RE);
197 bool IsPCRel = Obj.getAnyRelocationPCRel(RE);
198 unsigned Size = Obj.getAnyRelocationLength(RE);
199199 uint64_t Offset;
200200 RelI->getOffset(Offset);
201201 uint8_t *LocalAddress = Section.Address + Offset;
202202 unsigned NumBytes = 1 << Size;
203203 int64_t Addend = readBytesUnaligned(LocalAddress, NumBytes);
204204
205 unsigned SymbolBaseAddr = MachO->getScatteredRelocationValue(RE);
206 section_iterator TargetSI = getSectionByAddress(*MachO, SymbolBaseAddr);
207 assert(TargetSI != MachO->section_end() && "Can't find section for symbol");
205 unsigned SymbolBaseAddr = Obj.getScatteredRelocationValue(RE);
206 section_iterator TargetSI = getSectionByAddress(Obj, SymbolBaseAddr);
207 assert(TargetSI != Obj.section_end() && "Can't find section for symbol");
208208 uint64_t SectionBaseAddr = TargetSI->getAddress();
209209 SectionRef TargetSection = *TargetSI;
210210 bool IsCode = TargetSection.isText();
220220 }
221221
222222 // Populate stubs in __jump_table section.
223 void populateJumpTable(MachOObjectFile &Obj, const SectionRef &JTSection,
223 void populateJumpTable(const MachOObjectFile &Obj, const SectionRef &JTSection,
224224 unsigned JTSectionID) {
225225 assert(!Obj.is64Bit() &&
226226 "__jump_table section not supported in 64-bit MachO.");
3030
3131 relocation_iterator
3232 processRelocationRef(unsigned SectionID, relocation_iterator RelI,
33 ObjectImage &ObjImg, ObjSectionToIDMap &ObjSectionToID,
33 const ObjectFile &BaseObjT,
34 ObjSectionToIDMap &ObjSectionToID,
3435 const SymbolTableMap &Symbols, StubMap &Stubs) override {
3536 const MachOObjectFile &Obj =
36 static_cast(*ObjImg.getObjectFile());
37 static_cast(BaseObjT);
3738 MachO::any_relocation_info RelInfo =
3839 Obj.getRelocation(RelI->getRawDataRefImpl());
3940
4041 assert(!Obj.isRelocationScattered(RelInfo) &&
4142 "Scattered relocations not supported on X86_64");
4243
43 RelocationEntry RE(getRelocationEntry(SectionID, ObjImg, RelI));
44 RelocationEntry RE(getRelocationEntry(SectionID, Obj, RelI));
4445 RE.Addend = memcpyAddend(RE);
4546 RelocationValueRef Value(
46 getRelocationValueRef(ObjImg, RelI, RE, ObjSectionToID, Symbols));
47 getRelocationValueRef(Obj, RelI, RE, ObjSectionToID, Symbols));
4748
4849 bool IsExtern = Obj.getPlainRelocationExternal(RelInfo);
4950 if (!IsExtern && RE.IsPCRel)
50 makeValueAddendPCRel(Value, ObjImg, RelI, 1 << RE.Size);
51 makeValueAddendPCRel(Value, Obj, RelI, 1 << RE.Size);
5152
5253 if (RE.RelType == MachO::X86_64_RELOC_GOT ||
5354 RE.RelType == MachO::X86_64_RELOC_GOT_LOAD)
9697 }
9798 }
9899
99 void finalizeSection(ObjectImage &ObjImg, unsigned SectionID,
100 void finalizeSection(const ObjectFile &Obj, unsigned SectionID,
100101 const SectionRef &Section) {}
101102
102103 private:
1313
1414 #include "RemoteMemoryManager.h"
1515 #include "llvm/ExecutionEngine/ExecutionEngine.h"
16 #include "llvm/ExecutionEngine/ObjectImage.h"
1716 #include "llvm/Support/Debug.h"
1817 #include "llvm/Support/Format.h"
1918
7776 }
7877
7978 void RemoteMemoryManager::notifyObjectLoaded(ExecutionEngine *EE,
80 const ObjectImage *Obj) {
79 const object::ObjectFile &Obj) {
8180 // The client should have called setRemoteTarget() before triggering any
8281 // code generation.
8382 assert(Target);
7979 // symbols from Modules it contains.
8080 uint64_t getSymbolAddress(const std::string &Name) override { return 0; }
8181
82 void notifyObjectLoaded(ExecutionEngine *EE, const ObjectImage *Obj) override;
82 void notifyObjectLoaded(ExecutionEngine *EE,
83 const object::ObjectFile &Obj) override;
8384
8485 bool finalizeMemory(std::string *ErrMsg) override;
8586
1818 #include "llvm/ExecutionEngine/JITEventListener.h"
1919 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
2020 #include "llvm/ExecutionEngine/MCJIT.h"
21 #include "llvm/ExecutionEngine/ObjectImage.h"
2221 #include "llvm/IR/Module.h"
2322 #include "llvm/IRReader/IRReader.h"
2423 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
2525 #include "llvm/Support/Host.h"
2626 #include "llvm/Support/ManagedStatic.h"
2727 #include "llvm/Support/MemoryBuffer.h"
1212
1313 #include "llvm/ADT/StringMap.h"
1414 #include "llvm/DebugInfo/DIContext.h"
15 #include "llvm/ExecutionEngine/ObjectBuffer.h"
16 #include "llvm/ExecutionEngine/ObjectImage.h"
1715 #include "llvm/ExecutionEngine/RuntimeDyld.h"
1816 #include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
1917 #include "llvm/MC/MCAsmInfo.h"
206204 if (std::error_code EC = InputBuffer.getError())
207205 return Error("unable to read input: '" + EC.message() + "'");
208206
209 std::unique_ptr LoadedObject;
207 ErrorOr> MaybeObj(
208 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
209
210 if (std::error_code EC = MaybeObj.getError())
211 return Error("unable to create object file: '" + EC.message() + "'");
212
213 ObjectFile &Obj = **MaybeObj;
214
210215 // Load the object file
211 LoadedObject = Dyld.loadObject(
212 llvm::make_unique(std::move(*InputBuffer)));
213 if (!LoadedObject) {
216 std::unique_ptr LoadedObjInfo =
217 Dyld.loadObject(Obj);
218
219 if (Dyld.hasError())
214220 return Error(Dyld.getErrorString());
215 }
216221
217222 // Resolve all the relocations we can.
218223 Dyld.resolveRelocations();
219224
225 OwningBinary DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
226
220227 std::unique_ptr Context(
221 DIContext::getDWARFContext(*LoadedObject->getObjectFile()));
228 DIContext::getDWARFContext(*DebugObj.getBinary()));
222229
223230 // Use symbol info to iterate functions in the object.
224 for (object::symbol_iterator I = LoadedObject->begin_symbols(),
225 E = LoadedObject->end_symbols();
231 for (object::symbol_iterator I = DebugObj.getBinary()->symbol_begin(),
232 E = DebugObj.getBinary()->symbol_end();
226233 I != E; ++I) {
227234 object::SymbolRef::Type SymType;
228235 if (I->getType(SymType)) continue;
267274 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
268275 if (std::error_code EC = InputBuffer.getError())
269276 return Error("unable to read input: '" + EC.message() + "'");
270 std::unique_ptr LoadedObject;
277 ErrorOr> MaybeObj(
278 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
279
280 if (std::error_code EC = MaybeObj.getError())
281 return Error("unable to create object file: '" + EC.message() + "'");
282
283 ObjectFile &Obj = **MaybeObj;
284
271285 // Load the object file
272 LoadedObject = Dyld.loadObject(
273 llvm::make_unique(std::move(*InputBuffer)));
274 if (!LoadedObject) {
286 Dyld.loadObject(Obj);
287 if (Dyld.hasError()) {
275288 return Error(Dyld.getErrorString());
276289 }
277290 }
511524 // Load the input memory buffer.
512525 ErrorOr> InputBuffer =
513526 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
527
514528 if (std::error_code EC = InputBuffer.getError())
515529 return Error("unable to read input: '" + EC.message() + "'");
516530
517 std::unique_ptr LoadedObject;
531 ErrorOr> MaybeObj(
532 ObjectFile::createObjectFile((*InputBuffer)->getMemBufferRef()));
533
534 if (std::error_code EC = MaybeObj.getError())
535 return Error("unable to create object file: '" + EC.message() + "'");
536
537 ObjectFile &Obj = **MaybeObj;
538
518539 // Load the object file
519 LoadedObject = Dyld.loadObject(
520 llvm::make_unique(std::move(*InputBuffer)));
521 if (!LoadedObject) {
540 Dyld.loadObject(Obj);
541 if (Dyld.hasError()) {
522542 return Error(Dyld.getErrorString());
523543 }
524544 }