llvm.org GIT mirror llvm / 19afe67
Reverting r222828 and r222810-r222812 as they broke the build on Windows. http://bb.pgr.jp/builders/ninja-clang-i686-msc17-R/builds/11753 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@222833 91177308-0d34-0410-b5e6-96231b3b80d8 Aaron Ballman 6 years ago
32 changed file(s) with 1072 addition(s) and 839 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"
1817 #include "llvm/Config/llvm-config.h"
1918 #include "llvm/IR/DebugLoc.h"
2019 #include "llvm/Support/DataTypes.h"
2524 class MachineFunction;
2625 class OProfileWrapper;
2726 class IntelJITEventsWrapper;
28
29 namespace object {
30 class ObjectFile;
31 }
27 class ObjectImage;
3228
3329 /// JITEvent_EmittedFunctionDetails - Helper struct for containing information
3430 /// about a generated machine code function.
6056
6157 public:
6258 JITEventListener() {}
63 virtual ~JITEventListener() {}
59 virtual ~JITEventListener();
6460
6561 /// NotifyObjectEmitted - Called after an object has been successfully
6662 /// emitted to memory. NotifyFunctionEmitted will not be called for
7066 /// The ObjectImage contains the generated object image
7167 /// with section headers updated to reflect the address at which sections
7268 /// were loaded and with relocations performed in-place on debug sections.
73 virtual void NotifyObjectEmitted(const object::ObjectFile &Obj,
74 const RuntimeDyld::LoadedObjectInfo &L) {}
69 virtual void NotifyObjectEmitted(const ObjectImage &Obj) {}
7570
7671 /// NotifyFreeingObject - Called just before the memory associated with
7772 /// a previously emitted object is released.
78 virtual void NotifyFreeingObject(const object::ObjectFile &Obj) {}
79
80 // Get a pointe to the GDB debugger registration listener.
81 static JITEventListener *createGDBRegistrationListener();
73 virtual void NotifyFreeingObject(const ObjectImage &Obj) {}
8274
8375 #if LLVM_USE_INTEL_JITEVENTS
8476 // Construct an IntelJITEventListener
112104 return nullptr;
113105 }
114106 #endif // USE_OPROFILE
115 private:
116 virtual void anchor();
107
117108 };
118109
119110 } // end namespace llvm.
0 //===---- 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 //===---- 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
25 namespace object {
26 class ObjectFile;
27 }
24 class ObjectImage;
2825
2926 // RuntimeDyld clients often want to handle the memory management of
3027 // what gets placed where. For JIT clients, this is the subset of
111108 /// address space can use this call to remap the section addresses for the
112109 /// newly loaded object.
113110 virtual void notifyObjectLoaded(ExecutionEngine *EE,
114 const object::ObjectFile &) {}
111 const ObjectImage *) {}
115112
116113 /// This method is called when object loading is complete and section page
117114 /// 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"
1718 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
1819 #include "llvm/Support/Memory.h"
19 #include
2020
2121 namespace llvm {
2222
2323 namespace object {
2424 class ObjectFile;
25 template class OwningBinary;
2625 }
2726
2827 class RuntimeDyldImpl;
2928 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
7148 RuntimeDyld(RTDyldMemoryManager *);
7249 ~RuntimeDyld();
7350
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);
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);
7764
7865 /// Get the address of our local copy of the symbol. This may or may not
7966 /// 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
56 RTDyldMemoryManager.cpp
67 TargetSelect.cpp
78 )
1515 #include "llvm/ADT/SmallString.h"
1616 #include "llvm/ADT/Statistic.h"
1717 #include "llvm/ExecutionEngine/GenericValue.h"
18 #include "llvm/ExecutionEngine/JITEventListener.h"
18 #include "llvm/ExecutionEngine/ObjectBuffer.h"
19 #include "llvm/ExecutionEngine/ObjectCache.h"
1920 #include "llvm/IR/Constants.h"
2021 #include "llvm/IR/DataLayout.h"
2122 #include "llvm/IR/DerivedTypes.h"
4142 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
4243 STATISTIC(NumGlobals , "Number of global vars initialized");
4344
45 // Pin the vtable to this file.
46 void ObjectCache::anchor() {}
47 void ObjectBuffer::anchor() {}
48 void ObjectBufferStream::anchor() {}
49
4450 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
4551 std::unique_ptr M, std::string *ErrorStr,
4652 RTDyldMemoryManager *MCJMM, std::unique_ptr TM) = nullptr;
4753 ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr M,
4854 std::string *ErrorStr) =nullptr;
49
50 // Anchor for the JITEventListener class.
51 void JITEventListener::anchor() {}
5255
5356 ExecutionEngine::ExecutionEngine(std::unique_ptr M)
5457 : 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"
2324 #include "llvm/Object/ObjectFile.h"
2425 #include "llvm/Support/Debug.h"
2526 #include "llvm/Support/raw_ostream.h"
3031
3132 using namespace llvm;
3233 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;
5150
5251 public:
5352 IntelJITEventListener(IntelJITEventsWrapper* libraryWrapper) {
5756 ~IntelJITEventListener() {
5857 }
5958
60 void NotifyObjectEmitted(const ObjectFile &Obj,
61 const RuntimeDyld::LoadedObjectInfo &L) override;
62
63 void NotifyFreeingObject(const ObjectFile &Obj) override;
59 virtual void NotifyObjectEmitted(const ObjectImage &Obj);
60
61 virtual void NotifyFreeingObject(const ObjectImage &Obj);
6462 };
6563
6664 static LineNumberInfo DILineInfoToIntelJITFormat(uintptr_t StartAddress,
9694 return Result;
9795 }
9896
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
97 void IntelJITEventListener::NotifyObjectEmitted(const ObjectImage &Obj) {
10698 // Get the address of the object image for use as a unique identifier
107 const void* ObjData = DebugObj.getData().data();
108 DIContext* Context = DIContext::getDWARFContext(DebugObj);
99 const void* ObjData = Obj.getData().data();
100 DIContext* Context = DIContext::getDWARFContext(*Obj.getObjectFile());
109101 MethodAddressVector Functions;
110102
111103 // Use symbol info to iterate functions in the object.
112 for (symbol_iterator I = DebugObj.symbol_begin(),
113 E = DebugObj.symbol_end();
104 for (object::symbol_iterator I = Obj.begin_symbols(),
105 E = Obj.end_symbols();
114106 I != E;
115107 ++I) {
116108 std::vector LineInfo;
117109 std::string SourceFileName;
118110
119 SymbolRef::Type SymType;
111 object::SymbolRef::Type SymType;
120112 if (I->getType(SymType)) continue;
121 if (SymType == SymbolRef::ST_Function) {
113 if (SymType == object::SymbolRef::ST_Function) {
122114 StringRef Name;
123115 uint64_t Addr;
124116 uint64_t Size;
169161 // registered function addresses for each loaded object. We will
170162 // use the MethodIDs map to get the registered ID for each function.
171163 LoadedObjectMap[ObjData] = Functions;
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
164 }
165
166 void IntelJITEventListener::NotifyFreeingObject(const ObjectImage &Obj) {
181167 // Get the address of the object image for use as a unique identifier
182 const ObjectFile &DebugObj = *DebugObjects[Obj.getData().data()].getBinary();
183 const void* ObjData = DebugObj.getData().data();
168 const void* ObjData = Obj.getData().data();
184169
185170 // Get the object's function list from LoadedObjectMap
186171 ObjectMap::iterator OI = LoadedObjectMap.find(ObjData);
204189
205190 // Erase the object from LoadedObjectMap
206191 LoadedObjectMap.erase(OI);
207 DebugObjects.erase(Obj.getData().data());
208192 }
209193
210194 } // anonymous namespace.
0 //===-- 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"
1315 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
1416 #include "llvm/IR/DataLayout.h"
1517 #include "llvm/IR/DerivedTypes.h"
1820 #include "llvm/IR/Module.h"
1921 #include "llvm/MC/MCAsmInfo.h"
2022 #include "llvm/Object/Archive.h"
21 #include "llvm/Object/ObjectFile.h"
2223 #include "llvm/PassManager.h"
2324 #include "llvm/Support/DynamicLibrary.h"
2425 #include "llvm/Support/ErrorHandling.h"
2829 #include "llvm/Target/TargetSubtargetInfo.h"
2930
3031 using namespace llvm;
31
32 void ObjectCache::anchor() {}
3332
3433 namespace {
3534
7473
7574 OwnedModules.addModule(std::move(First));
7675 setDataLayout(TM->getSubtargetImpl()->getDataLayout());
77 RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
7876 }
7977
8078 MCJIT::~MCJIT() {
10098 }
10199
102100 void MCJIT::addObjectFile(std::unique_ptr Obj) {
103 std::unique_ptr L = Dyld.loadObject(*Obj);
104 if (Dyld.hasError())
101 std::unique_ptr LoadedObject = Dyld.loadObject(std::move(Obj));
102 if (!LoadedObject || Dyld.hasError())
105103 report_fatal_error(Dyld.getErrorString());
106104
107 NotifyObjectEmitted(*Obj, *L);
108
109 LoadedObjects.push_back(std::move(Obj));
105 NotifyObjectEmitted(*LoadedObject);
106
107 LoadedObjects.push_back(std::move(LoadedObject));
110108 }
111109
112110 void MCJIT::addObjectFile(object::OwningBinary Obj) {
126124 ObjCache = NewCache;
127125 }
128126
129 std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
127 std::unique_ptr<ObjectBufferStream> MCJIT::emitObject(Module *M) {
130128 MutexGuard locked(lock);
131129
132130 // This must be a module which has already been added but not loaded to this
139137 PM.add(new DataLayoutPass());
140138
141139 // The RuntimeDyld will take ownership of this shortly
142 SmallVector ObjBufferSV;
143 raw_svector_ostream ObjStream(ObjBufferSV);
140 std::unique_ptr CompiledObject(new ObjectBufferStream());
144141
145142 // Turn the machine code intermediate representation into bytes in memory
146143 // that may be executed.
147 if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
144 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
145 !getVerifyModules())) {
148146 report_fatal_error("Target does not support MC emission!");
147 }
149148
150149 // Initialize passes.
151150 PM.run(*M);
152151 // Flush the output buffer to get the generated code into memory
153 ObjStream.flush();
154
155 std::unique_ptr CompiledObjBuffer(
156 new ObjectMemoryBuffer(std::move(ObjBufferSV)));
152 CompiledObject->flush();
157153
158154 // If we have an object cache, tell it about the new object.
159155 // Note that we're using the compiled image, not the loaded image (as below).
160156 if (ObjCache) {
161157 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
162158 // to create a temporary object here and delete it after the call.
163 MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
159 MemoryBufferRef MB = CompiledObject->getMemBuffer();
164160 ObjCache->notifyObjectCompiled(M, MB);
165161 }
166162
167 return CompiledObjBuffer;
163 return CompiledObject;
168164 }
169165
170166 void MCJIT::generateCodeForModule(Module *M) {
179175 if (OwnedModules.hasModuleBeenLoaded(M))
180176 return;
181177
182 std::unique_ptr<MemoryBuffer> ObjectToLoad;
178 std::unique_ptr<ObjectBuffer> ObjectToLoad;
183179 // Try to load the pre-compiled object from cache if possible
184 if (ObjCache)
185 ObjectToLoad = ObjCache->getObject(M);
180 if (ObjCache) {
181 if (std::unique_ptr PreCompiledObject =
182 ObjCache->getObject(M))
183 ObjectToLoad =
184 llvm::make_unique(std::move(PreCompiledObject));
185 }
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 ErrorOr> LoadedObject =
196 object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
197 std::unique_ptr L =
198 Dyld.loadObject(*LoadedObject.get());
199
200 if (Dyld.hasError())
195 std::unique_ptr LoadedObject =
196 Dyld.loadObject(std::move(ObjectToLoad));
197 if (!LoadedObject)
201198 report_fatal_error(Dyld.getErrorString());
202199
203 NotifyObjectEmitted(*LoadedObject.get(), *L);
204
205 Buffers.push_back(std::move(ObjectToLoad));
206 LoadedObjects.push_back(std::move(*LoadedObject));
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));
207206
208207 OwnedModules.markModuleAsLoaded(M);
209208 }
549548 MutexGuard locked(lock);
550549 EventListeners.push_back(L);
551550 }
552
553551 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
554552 if (!L)
555553 return;
560558 EventListeners.pop_back();
561559 }
562560 }
563
564 void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
565 const RuntimeDyld::LoadedObjectInfo &L) {
566 MutexGuard locked(lock);
567 MemMgr.notifyObjectLoaded(this, Obj);
561 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
562 MutexGuard locked(lock);
563 MemMgr.notifyObjectLoaded(this, &Obj);
568564 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
569 EventListeners[I]->NotifyObjectEmitted(Obj, L);
570 }
571 }
572
573 void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
565 EventListeners[I]->NotifyObjectEmitted(Obj);
566 }
567 }
568 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
574569 MutexGuard locked(lock);
575570 for (JITEventListener *L : EventListeners)
576571 L->NotifyFreeingObject(Obj);
99 #ifndef LLVM_LIB_EXECUTIONENGINE_MCJIT_MCJIT_H
1010 #define LLVM_LIB_EXECUTIONENGINE_MCJIT_MCJIT_H
1111
12 #include "ObjectBuffer.h"
1312 #include "llvm/ADT/DenseMap.h"
1413 #include "llvm/ADT/SmallPtrSet.h"
1514 #include "llvm/ADT/SmallVector.h"
1615 #include "llvm/ExecutionEngine/ExecutionEngine.h"
1716 #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 object::ObjectFile &Obj) override {
59 const ObjectImage *Obj) override {
6060 ClientMM->notifyObjectLoaded(EE, Obj);
6161 }
6262
221221 SmallVector, 2> Archives;
222222 SmallVector, 2> Buffers;
223223
224 SmallVectorobject::ObjectFile>, 2> LoadedObjects;
224 SmallVectorObjectImage>, 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 object::ObjectFile& Obj,
346 const RuntimeDyld::LoadedObjectInfo &L);
347 void NotifyFreeingObject(const object::ObjectFile& Obj);
343 std::unique_ptr emitObject(Module *M);
344
345 void NotifyObjectEmitted(const ObjectImage& Obj);
346 void NotifyFreeingObject(const ObjectImage& Obj);
348347
349348 uint64_t getExistingSymbolAddress(const std::string &Name);
350349 Module *findModuleForSymbol(const std::string &Name,
+0
-48
lib/ExecutionEngine/MCJIT/ObjectBuffer.h less more
None //===--- 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"
2021 #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;
3433
3534 #define DEBUG_TYPE "oprofile-jit-event-listener"
3635
3736 namespace {
3837
3938 class OProfileJITEventListener : public JITEventListener {
40 std::unique_ptr Wrapper;
39 OProfileWrapper& Wrapper;
4140
4241 void initialize();
43 std::map> DebugObjects;
4442
4543 public:
46 OProfileJITEventListener(std::unique_ptr LibraryWrapper)
47 : Wrapper(std::move(LibraryWrapper)) {
44 OProfileJITEventListener(OProfileWrapper& LibraryWrapper)
45 : Wrapper(LibraryWrapper) {
4846 initialize();
4947 }
5048
5149 ~OProfileJITEventListener();
5250
53 void NotifyObjectEmitted(const ObjectFile &Obj,
54 const RuntimeDyld::LoadedObjectInfo &L) override;
51 virtual void NotifyObjectEmitted(const ObjectImage &Obj);
5552
56 void NotifyFreeingObject(const ObjectFile &Obj) override;
53 virtual void NotifyFreeingObject(const ObjectImage &Obj);
5754 };
5855
5956 void OProfileJITEventListener::initialize() {
60 if (!Wrapper->op_open_agent()) {
57 if (!Wrapper.op_open_agent()) {
6158 const std::string err_str = sys::StrError();
6259 DEBUG(dbgs() << "Failed to connect to OProfile agent: " << err_str << "\n");
6360 } else {
6663 }
6764
6865 OProfileJITEventListener::~OProfileJITEventListener() {
69 if (Wrapper->isAgentAvailable()) {
70 if (Wrapper->op_close_agent() == -1) {
66 if (Wrapper.isAgentAvailable()) {
67 if (Wrapper.op_close_agent() == -1) {
7168 const std::string err_str = sys::StrError();
7269 DEBUG(dbgs() << "Failed to disconnect from OProfile agent: "
7370 << err_str << "\n");
7774 }
7875 }
7976
80 void OProfileJITEventListener::NotifyObjectEmitted(
81 const ObjectFile &Obj,
82 const RuntimeDyld::LoadedObjectInfo &L) {
83 if (!Wrapper->isAgentAvailable()) {
77 void OProfileJITEventListener::NotifyObjectEmitted(const ObjectImage &Obj) {
78 if (!Wrapper.isAgentAvailable()) {
8479 return;
8580 }
8681
87 OwningBinary DebugObjOwner = L.getObjectForDebug(Obj);
88 const ObjectFile &DebugObj = *DebugObjOwner.getBinary();
89
9082 // Use symbol info to iterate functions in the object.
91 for (symbol_iterator I = DebugObj.symbol_begin(), E = DebugObj.symbol_end();
83 for (object::symbol_iterator I = Obj.begin_symbols(), E = Obj.end_symbols();
9284 I != E; ++I) {
93 SymbolRef::Type SymType;
85 object::SymbolRef::Type SymType;
9486 if (I->getType(SymType)) continue;
95 if (SymType == SymbolRef::ST_Function) {
87 if (SymType == object::SymbolRef::ST_Function) {
9688 StringRef Name;
9789 uint64_t Addr;
9890 uint64_t Size;
10092 if (I->getAddress(Addr)) continue;
10193 if (I->getSize(Size)) continue;
10294
103 if (Wrapper->op_write_native_code(Name.data(), Addr, (void*)Addr, Size)
95 if (Wrapper.op_write_native_code(Name.data(), Addr, (void*)Addr, Size)
10496 == -1) {
10597 DEBUG(dbgs() << "Failed to tell OProfile about native function "
10698 << Name << " at ["
110102 // TODO: support line number info (similar to IntelJITEventListener.cpp)
111103 }
112104 }
113
114 DebugObjects[Obj.getData().data()] = std::move(DebugObjOwner);
115105 }
116106
117 void OProfileJITEventListener::NotifyFreeingObject(const ObjectFile &Obj) {
118 if (Wrapper->isAgentAvailable()) {
107 void OProfileJITEventListener::NotifyFreeingObject(const ObjectImage &Obj) {
108 if (!Wrapper.isAgentAvailable()) {
109 return;
110 }
119111
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;
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;
124120
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 }
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;
143126 }
144127 }
145128 }
146
147 DebugObjects.erase(Obj.getData().data());
148129 }
149130
150131 } // anonymous namespace.
151132
152133 namespace llvm {
153134 JITEventListener *JITEventListener::createOProfileJITEventListener() {
154 return new OProfileJITEventListener(llvm::make_unique());
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);
155144 }
156145
157146 } // namespace llvm
0 add_llvm_library(LLVMRuntimeDyld
1 GDBRegistrationListener.cpp
1 GDBRegistrar.cpp
22 RuntimeDyld.cpp
33 RuntimeDyldChecker.cpp
44 RuntimeDyldELF.cpp
0 //===-- 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
-237
lib/ExecutionEngine/RuntimeDyld/GDBRegistrationListener.cpp less more
None //===----- 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
154 // Bail out if debug objects aren't supported.
155 if (!DebugObj.getBinary())
156 return;
157
158 const char *Buffer = DebugObj.getBinary()->getMemoryBufferRef().getBufferStart();
159 size_t Size = DebugObj.getBinary()->getMemoryBufferRef().getBufferSize();
160
161 const char *Key = Object.getMemoryBufferRef().getBufferStart();
162
163 assert(Key && "Attempt to register a null object with a debugger.");
164 llvm::MutexGuard locked(*JITDebugLock);
165 assert(ObjectBufferMap.find(Key) == ObjectBufferMap.end() &&
166 "Second attempt to perform debug registration.");
167 jit_code_entry* JITCodeEntry = new jit_code_entry();
168
169 if (!JITCodeEntry) {
170 llvm::report_fatal_error(
171 "Allocation failed when registering a JIT entry!\n");
172 } else {
173 JITCodeEntry->symfile_addr = Buffer;
174 JITCodeEntry->symfile_size = Size;
175
176 ObjectBufferMap[Key] = RegisteredObjectInfo(Size, JITCodeEntry,
177 std::move(DebugObj));
178 NotifyDebugger(JITCodeEntry);
179 }
180 }
181
182 void GDBJITRegistrationListener::NotifyFreeingObject(const ObjectFile& Object) {
183 const char *Key = Object.getMemoryBufferRef().getBufferStart();
184 llvm::MutexGuard locked(*JITDebugLock);
185 RegisteredObjectBufferMap::iterator I = ObjectBufferMap.find(Key);
186
187 if (I != ObjectBufferMap.end()) {
188 deregisterObjectInternal(I);
189 ObjectBufferMap.erase(I);
190 }
191 }
192
193 void GDBJITRegistrationListener::deregisterObjectInternal(
194 RegisteredObjectBufferMap::iterator I) {
195
196 jit_code_entry*& JITCodeEntry = I->second.Entry;
197
198 // Do the unregistration.
199 {
200 __jit_debug_descriptor.action_flag = JIT_UNREGISTER_FN;
201
202 // Remove the jit_code_entry from the linked list.
203 jit_code_entry* PrevEntry = JITCodeEntry->prev_entry;
204 jit_code_entry* NextEntry = JITCodeEntry->next_entry;
205
206 if (NextEntry) {
207 NextEntry->prev_entry = PrevEntry;
208 }
209 if (PrevEntry) {
210 PrevEntry->next_entry = NextEntry;
211 }
212 else {
213 assert(__jit_debug_descriptor.first_entry == JITCodeEntry);
214 __jit_debug_descriptor.first_entry = NextEntry;
215 }
216
217 // Tell the debugger which entry we removed, and unregister the code.
218 __jit_debug_descriptor.relevant_entry = JITCodeEntry;
219 __jit_debug_register_code();
220 }
221
222 delete JITCodeEntry;
223 JITCodeEntry = nullptr;
224 }
225
226 llvm::ManagedStatic GDBRegListener;
227
228 } // end namespace
229
230 namespace llvm {
231
232 JITEventListener* JITEventListener::createGDBRegistrationListener() {
233 return &*GDBRegListener;
234 }
235
236 } // namespace llvm
0 //===-- 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 //===-- 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"
1416 #include "RuntimeDyldCheckerImpl.h"
1517 #include "RuntimeDyldELF.h"
1618 #include "RuntimeDyldImpl.h"
2729 // Empty out-of-line virtual destructor as the key function.
2830 RuntimeDyldImpl::~RuntimeDyldImpl() {}
2931
30 // Pin LoadedObjectInfo's vtables to this file.
31 void RuntimeDyld::LoadedObjectInfo::anchor() {}
32 // Pin the JITRegistrar's and ObjectImage*'s vtables to this file.
33 void JITRegistrar::anchor() {}
34 void ObjectImage::anchor() {}
35 void ObjectImageCommon::anchor() {}
3236
3337 namespace llvm {
3438
134138 return object_error::success;
135139 }
136140
137 std::pair
138 RuntimeDyldImpl::loadObjectImpl(const object::ObjectFile &Obj) {
141 std::unique_ptr
142 RuntimeDyldImpl::loadObject(std::unique_ptr Obj) {
139143 MutexGuard locked(lock);
140144
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();
145 if (!Obj)
146 return nullptr;
144147
145148 // Save information about our target
146 Arch = (Triple::ArchType)Obj.getArch();
147 IsTargetLittleEndian = Obj.isLittleEndian();
149 Arch = (Triple::ArchType)Obj->getArch();
150 IsTargetLittleEndian = Obj->getObjectFile()->isLittleEndian();
148151
149152 // Compute the memory size required to load all sections to be loaded
150153 // and pass this information to the memory manager
151154 if (MemMgr->needsToReserveAllocationSpace()) {
152155 uint64_t CodeSize = 0, DataSizeRO = 0, DataSizeRW = 0;
153 computeTotalAllocSize(Obj, CodeSize, DataSizeRO, DataSizeRW);
156 computeTotalAllocSize(*Obj, CodeSize, DataSizeRO, DataSizeRW);
154157 MemMgr->reserveAllocationSpace(CodeSize, DataSizeRO, DataSizeRW);
155158 }
156159
166169
167170 // Parse symbols
168171 DEBUG(dbgs() << "Parse symbols:\n");
169 for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
172 for (symbol_iterator I = Obj->begin_symbols(), E = Obj->end_symbols(); I != E;
170173 ++I) {
171174 object::SymbolRef::Type SymType;
172175 StringRef Name;
192195 SymType == object::SymbolRef::ST_Unknown) {
193196 uint64_t SectOffset;
194197 StringRef SectionData;
195 section_iterator SI = Obj.section_end();
198 section_iterator SI = Obj->end_sections();
196199 Check(getOffset(*I, SectOffset));
197200 Check(I->getSection(SI));
198 if (SI == Obj.section_end())
201 if (SI == Obj->end_sections())
199202 continue;
200203 Check(SI->getContents(SectionData));
201204 bool IsCode = SI->isText();
202205 unsigned SectionID =
203 findOrEmitSection(Obj, *SI, IsCode, LocalSections);
206 findOrEmitSection(*Obj, *SI, IsCode, LocalSections);
204207 LocalSymbols[Name.data()] = SymbolLoc(SectionID, SectOffset);
205208 DEBUG(dbgs() << "\tOffset: " << format("%p", (uintptr_t)SectOffset)
206209 << " flags: " << Flags << " SID: " << SectionID);
212215
213216 // Allocate common symbols
214217 if (CommonSize != 0)
215 emitCommonSymbols(Obj, CommonSymbols, CommonSize, GlobalSymbolTable);
218 emitCommonSymbols(*Obj, CommonSymbols, CommonSize, GlobalSymbolTable);
216219
217220 // Parse and process relocations
218221 DEBUG(dbgs() << "Parse relocations:\n");
219 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
222 for (section_iterator SI = Obj->begin_sections(), SE = Obj->end_sections();
220223 SI != SE; ++SI) {
221224 unsigned SectionID = 0;
222225 StubMap Stubs;
230233
231234 bool IsCode = RelocatedSection->isText();
232235 SectionID =
233 findOrEmitSection(Obj, *RelocatedSection, IsCode, LocalSections);
236 findOrEmitSection(*Obj, *RelocatedSection, IsCode, LocalSections);
234237 DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
235238
236239 for (; I != E;)
237 I = processRelocationRef(SectionID, I, Obj, LocalSections, LocalSymbols,
240 I = processRelocationRef(SectionID, I, *Obj, LocalSections, LocalSymbols,
238241 Stubs);
239242
240243 // If there is an attached checker, notify it about the stubs for this
241244 // section so that they can be verified.
242245 if (Checker)
243 Checker->registerStubMap(Obj.getFileName(), SectionID, Stubs);
246 Checker->registerStubMap(Obj->getImageName(), SectionID, Stubs);
244247 }
245248
246249 // Give the subclasses a chance to tie-up any loose ends.
247 finalizeLoad(Obj, LocalSections);
248
249 unsigned SectionsAddedEndIdx = Sections.size();
250
251 return std::make_pair(SectionsAddedBeginIdx, SectionsAddedEndIdx);
250 finalizeLoad(*Obj, LocalSections);
251
252 return Obj;
252253 }
253254
254255 // A helper method for computeTotalAllocSize.
268269
269270 // Compute an upper bound of the memory size that is required to load all
270271 // sections
271 void RuntimeDyldImpl::computeTotalAllocSize(const ObjectFile &Obj,
272 void RuntimeDyldImpl::computeTotalAllocSize(ObjectImage &Obj,
272273 uint64_t &CodeSize,
273274 uint64_t &DataSizeRO,
274275 uint64_t &DataSizeRW) {
280281
281282 // Collect sizes of all sections to be loaded;
282283 // also determine the max alignment of all sections
283 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
284 for (section_iterator SI = Obj.begin_sections(), SE = Obj.end_sections();
284285 SI != SE; ++SI) {
285286 const SectionRef &Section = *SI;
286287
326327
327328 // Compute the size of all common symbols
328329 uint64_t CommonSize = 0;
329 for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
330 for (symbol_iterator I = Obj.begin_symbols(), E = Obj.end_symbols(); I != E;
330331 ++I) {
331332 uint32_t Flags = I->getFlags();
332333 if (Flags & SymbolRef::SF_Common) {
351352 }
352353
353354 // compute stub buffer size for the given section
354 unsigned RuntimeDyldImpl::computeSectionStubBufSize(const ObjectFile &Obj,
355 unsigned RuntimeDyldImpl::computeSectionStubBufSize(ObjectImage &Obj,
355356 const SectionRef &Section) {
356357 unsigned StubSize = getMaxStubSize();
357358 if (StubSize == 0) {
361362 // necessary section allocation size in loadObject by walking all the sections
362363 // once.
363364 unsigned StubBufSize = 0;
364 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
365 for (section_iterator SI = Obj.begin_sections(), SE = Obj.end_sections();
365366 SI != SE; ++SI) {
366367 section_iterator RelSecI = SI->getRelocatedSection();
367368 if (!(RelSecI == Section))
416417 }
417418 }
418419
419 void RuntimeDyldImpl::emitCommonSymbols(const ObjectFile &Obj,
420 void RuntimeDyldImpl::emitCommonSymbols(ObjectImage &Obj,
420421 const CommonSymbolMap &CommonSymbols,
421422 uint64_t TotalSize,
422423 SymbolTableMap &SymbolTable) {
448449 DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
449450 << format("%p\n", Addr));
450451 }
452 Obj.updateSymbolAddress(it->first, (uint64_t)Addr);
451453 SymbolTable[Name.data()] = SymbolLoc(SectionID, Offset);
452454 Offset += Size;
453455 Addr += Size;
454456 }
455457 }
456458
457 unsigned RuntimeDyldImpl::emitSection(const ObjectFile &Obj,
459 unsigned RuntimeDyldImpl::emitSection(ObjectImage &Obj,
458460 const SectionRef &Section, bool IsCode) {
459461
460462 StringRef data;
518520 << " new addr: " << format("%p", Addr)
519521 << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
520522 << " Allocate: " << Allocate << "\n");
523 Obj.updateSectionAddress(Section, (uint64_t)Addr);
521524 } else {
522525 // Even if we didn't load the section, we need to record an entry for it
523526 // to handle later processing (and by 'handle' I mean don't do anything
533536 Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
534537
535538 if (Checker)
536 Checker->registerSection(Obj.getFileName(), SectionID);
539 Checker->registerSection(Obj.getImageName(), SectionID);
537540
538541 return SectionID;
539542 }
540543
541 unsigned RuntimeDyldImpl::findOrEmitSection(const ObjectFile &Obj,
544 unsigned RuntimeDyldImpl::findOrEmitSection(ObjectImage &Obj,
542545 const SectionRef &Section,
543546 bool IsCode,
544547 ObjSectionToIDMap &LocalSections) {
735738
736739 //===----------------------------------------------------------------------===//
737740 // 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
748741 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
749742 // FIXME: There's a potential issue lurking here if a single instance of
750743 // RuntimeDyld is used to load multiple objects. The current implementation
778771 return Dyld;
779772 }
780773
781 std::unique_ptr
782 RuntimeDyld::loadObject(const ObjectFile &Obj) {
783 if (!Dyld) {
784 if (Obj.isELF())
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)
785783 Dyld = createRuntimeDyldELF(MM, ProcessAllSections, Checker);
786 else if (Obj.isMachO())
784 } else if (InputObject->isMachO()) {
785 InputImage.reset(RuntimeDyldMachO::createObjectImageFromFile(std::move(InputObject)));
786 if (!Dyld)
787787 Dyld = createRuntimeDyldMachO(
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))
788 static_cast(InputImage->getArch()), MM,
789 ProcessAllSections, Checker);
790 } else
795791 report_fatal_error("Incompatible object format!");
796792
797 return Dyld->loadObject(Obj);
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));
798846 }
799847
800848 void *RuntimeDyld::getSymbolAddress(StringRef Name) const {
1111 //===----------------------------------------------------------------------===//
1212
1313 #include "RuntimeDyldELF.h"
14 #include "JITRegistrar.h"
15 #include "ObjectImageCommon.h"
1416 #include "llvm/ADT/IntervalMap.h"
1517 #include "llvm/ADT/STLExtras.h"
1618 #include "llvm/ADT/StringRef.h"
1719 #include "llvm/ADT/Triple.h"
18 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/ExecutionEngine/ObjectBuffer.h"
21 #include "llvm/ExecutionEngine/ObjectImage.h"
1922 #include "llvm/Object/ELFObjectFile.h"
2023 #include "llvm/Object/ObjectFile.h"
2124 #include "llvm/Support/ELF.h"
2225 #include "llvm/Support/Endian.h"
2326 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/TargetRegistry.h"
2527
2628 using namespace llvm;
2729 using namespace llvm::object;
2830
2931 #define DEBUG_TYPE "dyld"
32
33 namespace {
3034
3135 static inline std::error_code check(std::error_code Err) {
3236 if (Err) {
3438 }
3539 return Err;
3640 }
37
38 namespace {
3941
4042 template class DyldELFObject : public ELFObjectFile {
4143 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
4951
5052 typedef typename ELFDataTypeTypedefHelper::value_type addr_type;
5153
54 std::unique_ptr UnderlyingFile;
55
5256 public:
57 DyldELFObject(std::unique_ptr UnderlyingFile,
58 MemoryBufferRef Wrapper, std::error_code &ec);
59
5360 DyldELFObject(MemoryBufferRef Wrapper, std::error_code &ec);
5461
5562 void updateSectionAddress(const SectionRef &Sec, uint64_t Addr);
56
57 void updateSymbolAddress(const SymbolRef &SymRef, uint64_t Addr);
63 void updateSymbolAddress(const SymbolRef &Sym, uint64_t Addr);
5864
5965 // Methods for type inquiry through isa, cast and dyn_cast
6066 static inline bool classof(const Binary *v) {
6470 static inline bool classof(const ELFObjectFile *v) {
6571 return v->isDyldType();
6672 }
67
6873 };
6974
70
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 };
71109
72110 // The MemoryBuffer passed into this constructor is just a wrapper around the
73111 // actual memory. Ultimately, the Binary parent class will take ownership of
79117 }
80118
81119 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
82128 void DyldELFObject::updateSectionAddress(const SectionRef &Sec,
83129 uint64_t Addr) {
84130 DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
102148 sym->st_value = static_cast(Addr);
103149 }
104150
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
181151 } // namespace
182152
183153 namespace llvm {
184
185 RuntimeDyldELF::RuntimeDyldELF(RTDyldMemoryManager *mm) : RuntimeDyldImpl(mm) {}
186 RuntimeDyldELF::~RuntimeDyldELF() {}
187154
188155 void RuntimeDyldELF::registerEHFrames() {
189156 if (!MemMgr)
212179 RegisteredEHFrameSections.clear();
213180 }
214181
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 }
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() {}
222258
223259 void RuntimeDyldELF::resolveX86_64Relocation(const SectionEntry &Section,
224260 uint64_t Offset, uint64_t Value,
578614 }
579615
580616 // Return the .TOC. section and offset.
581 void RuntimeDyldELF::findPPC64TOCSection(const ObjectFile &Obj,
617 void RuntimeDyldELF::findPPC64TOCSection(ObjectImage &Obj,
582618 ObjSectionToIDMap &LocalSections,
583619 RelocationValueRef &Rel) {
584620 // Set a default SectionID in case we do not find a TOC section below.
591627
592628 // The TOC consists of sections .got, .toc, .tocbss, .plt in that
593629 // order. The TOC starts where the first of these sections starts.
594 for (section_iterator si = Obj.section_begin(), se = Obj.section_end();
630 for (section_iterator si = Obj.begin_sections(), se = Obj.end_sections();
595631 si != se; ++si) {
596632
597633 StringRef SectionName;
613649
614650 // Returns the sections and offset associated with the ODP entry referenced
615651 // by Symbol.
616 void RuntimeDyldELF::findOPDEntrySection(const ObjectFile &Obj,
652 void RuntimeDyldELF::findOPDEntrySection(ObjectImage &Obj,
617653 ObjSectionToIDMap &LocalSections,
618654 RelocationValueRef &Rel) {
619655 // Get the ELF symbol value (st_value) to compare with Relocation offset in
620656 // .opd entries
621 for (section_iterator si = Obj.section_begin(), se = Obj.section_end();
657 for (section_iterator si = Obj.begin_sections(), se = Obj.end_sections();
622658 si != se; ++si) {
623659 section_iterator RelSecI = si->getRelocatedSection();
624 if (RelSecI == Obj.section_end())
660 if (RelSecI == Obj.end_sections())
625661 continue;
626662
627663 StringRef RelSectionName;
663699 if (Rel.Addend != (int64_t)TargetSymbolOffset)
664700 continue;
665701
666 section_iterator tsi(Obj.section_end());
702 section_iterator tsi(Obj.end_sections());
667703 check(TargetSymbol->getSection(tsi));
668704 bool IsCode = tsi->isText();
669705 Rel.SectionID = findOrEmitSection(Obj, (*tsi), IsCode, LocalSections);
898934 }
899935
900936 relocation_iterator RuntimeDyldELF::processRelocationRef(
901 unsigned SectionID, relocation_iterator RelI,
902 const ObjectFile &Obj,
937 unsigned SectionID, relocation_iterator RelI, ObjectImage &Obj,
903938 ObjSectionToIDMap &ObjSectionToID, const SymbolTableMap &Symbols,
904939 StubMap &Stubs) {
905940 uint64_t RelType;
910945
911946 // Obtain the symbol name which is referenced in the relocation
912947 StringRef TargetName;
913 if (Symbol != Obj.symbol_end())
948 if (Symbol != Obj.end_symbols())
914949 Symbol->getName(TargetName);
915950 DEBUG(dbgs() << "\t\tRelType: " << RelType << " Addend: " << Addend
916951 << " TargetName: " << TargetName << "\n");
918953 // First search for the symbol in the local symbol table
919954 SymbolTableMap::const_iterator lsi = Symbols.end();
920955 SymbolRef::Type SymType = SymbolRef::ST_Unknown;
921 if (Symbol != Obj.symbol_end()) {
956 if (Symbol != Obj.end_symbols()) {
922957 lsi = Symbols.find(TargetName.data());
923958 Symbol->getType(SymType);
924959 }
929964 } else {
930965 // Search for the symbol in the global symbol table
931966 SymbolTableMap::const_iterator gsi = GlobalSymbolTable.end();
932 if (Symbol != Obj.symbol_end())
967 if (Symbol != Obj.end_symbols())
933968 gsi = GlobalSymbolTable.find(TargetName.data());
934969 if (gsi != GlobalSymbolTable.end()) {
935970 Value.SectionID = gsi->second.first;
941976 // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
942977 // and can be changed by another developers. Maybe best way is add
943978 // a new symbol type ST_Section to SymbolRef and use it.
944 section_iterator si(Obj.section_end());
979 section_iterator si(Obj.end_sections());
945980 Symbol->getSection(si);
946 if (si == Obj.section_end())
981 if (si == Obj.end_sections())
947982 llvm_unreachable("Symbol section not found, bad object file format!");
948983 DEBUG(dbgs() << "\t\tThis is section symbol\n");
949984 bool isCode = si->isText();
10991134 if (RelType == ELF::R_PPC64_REL24) {
11001135 // Determine ABI variant in use for this object.
11011136 unsigned AbiVariant;
1102 Obj.getPlatformFlags(AbiVariant);
1137 Obj.getObjectFile()->getPlatformFlags(AbiVariant);
11031138 AbiVariant &= ELF::EF_PPC64_ABI;
11041139 // A PPC branch relocation will need a stub function if the target is
11051140 // an external symbol (Symbol::ST_Unknown) or if the target address
14591494 return 0;
14601495 }
14611496
1462 void RuntimeDyldELF::finalizeLoad(const ObjectFile &Obj,
1497 void RuntimeDyldELF::finalizeLoad(ObjectImage &ObjImg,
14631498 ObjSectionToIDMap &SectionMap) {
14641499 // If necessary, allocate the global offset table
14651500 if (MemMgr) {
14971532 }
14981533 }
14991534
1500 bool RuntimeDyldELF::isCompatibleFile(const object::ObjectFile &Obj) const {
1501 return Obj.isELF();
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();
15021544 }
15031545
15041546 } // namespace llvm
2727 }
2828 return Err;
2929 }
30
3130 } // end anonymous namespace
3231
3332 class RuntimeDyldELF : public RuntimeDyldImpl {
34
3533 void resolveRelocation(const SectionEntry &Section, uint64_t Offset,
3634 uint64_t Value, uint32_t Type, int64_t Addend,
3735 uint64_t SymOffset = 0);
8280 return 1;
8381 }
8482
85 void findPPC64TOCSection(const ObjectFile &Obj,
86 ObjSectionToIDMap &LocalSections,
83 void findPPC64TOCSection(ObjectImage &Obj, ObjSectionToIDMap &LocalSections,
8784 RelocationValueRef &Rel);
88 void findOPDEntrySection(const ObjectFile &Obj,
89 ObjSectionToIDMap &LocalSections,
85 void findOPDEntrySection(ObjectImage &Obj, ObjSectionToIDMap &LocalSections,
9086 RelocationValueRef &Rel);
9187
9288 uint64_t findGOTEntry(uint64_t LoadAddr, uint64_t Offset);
107103 SmallVector RegisteredEHFrameSections;
108104
109105 public:
110 RuntimeDyldELF(RTDyldMemoryManager *mm);
111 virtual ~RuntimeDyldELF();
112
113 std::unique_ptr
114 loadObject(const object::ObjectFile &O) override;
106 RuntimeDyldELF(RTDyldMemoryManager *mm) : RuntimeDyldImpl(mm) {}
115107
116108 void resolveRelocation(const RelocationEntry &RE, uint64_t Value) override;
117109 relocation_iterator
118110 processRelocationRef(unsigned SectionID, relocation_iterator RelI,
119 const ObjectFile &Obj,
120 ObjSectionToIDMap &ObjSectionToID,
111 ObjectImage &Obj, ObjSectionToIDMap &ObjSectionToID,
121112 const SymbolTableMap &Symbols, StubMap &Stubs) override;
122 bool isCompatibleFile(const object::ObjectFile &Obj) const override;
113 bool isCompatibleFormat(const ObjectBuffer *Buffer) const override;
114 bool isCompatibleFile(const object::ObjectFile *Buffer) const override;
123115 void registerEHFrames() override;
124116 void deregisterEHFrames() override;
125 void finalizeLoad(const ObjectFile &Obj,
117 void finalizeLoad(ObjectImage &ObjImg,
126118 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);
127124 };
128125
129126 } // 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"
2021 #include "llvm/ExecutionEngine/RuntimeDyld.h"
2122 #include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
2223 #include "llvm/Object/ObjectFile.h"
3536
3637 namespace llvm {
3738
39 class ObjectBuffer;
3840 class Twine;
3941
4042 /// SectionEntry - represents a section emitted into memory by the dynamic
156158 };
157159
158160 class RuntimeDyldImpl {
159 friend class RuntimeDyld::LoadedObjectInfo;
160161 friend class RuntimeDyldCheckerImpl;
161162 private:
162163
294295 /// \brief Given the common symbols discovered in the object file, emit a
295296 /// new section for them and update the symbol mappings in the object and
296297 /// symbol table.
297 void emitCommonSymbols(const ObjectFile &Obj,
298 const CommonSymbolMap &CommonSymbols,
298 void emitCommonSymbols(ObjectImage &Obj, 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(const ObjectFile &Obj, const SectionRef &Section,
305 unsigned emitSection(ObjectImage &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(const ObjectFile &Obj, const SectionRef &Section,
313 unsigned findOrEmitSection(ObjectImage &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 const ObjectFile &Obj, ObjSectionToIDMap &ObjSectionToID,
341 ObjectImage &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(const ObjectFile &Obj, uint64_t &CodeSize,
353 void computeTotalAllocSize(ObjectImage &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(const ObjectFile &Obj,
357 unsigned computeSectionStubBufSize(ObjectImage &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);
362359
363360 public:
364361 RuntimeDyldImpl(RTDyldMemoryManager *mm)
375372 this->Checker = Checker;
376373 }
377374
378 virtual std::unique_ptr
379 loadObject(const object::ObjectFile &Obj) = 0;
375 std::unique_ptr
376 loadObject(std::unique_ptr InputObject);
380377
381378 uint8_t* getSymbolAddress(StringRef Name) const {
382379 // FIXME: Just look up as a function for now. Overly simple of course.
413410 // Get the error message.
414411 StringRef getErrorString() { return ErrorStr; }
415412
416 virtual bool isCompatibleFile(const ObjectFile &Obj) const = 0;
413 virtual bool isCompatibleFormat(const ObjectBuffer *Buffer) const = 0;
414 virtual bool isCompatibleFile(const ObjectFile *Obj) const = 0;
417415
418416 virtual void registerEHFrames();
419417
420418 virtual void deregisterEHFrames();
421419
422 virtual void finalizeLoad(const ObjectFile &ObjImg,
423 ObjSectionToIDMap &SectionMap) {}
420 virtual void finalizeLoad(ObjectImage &ObjImg, ObjSectionToIDMap &SectionMap) {}
424421 };
425422
426423 } // 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
4327 namespace llvm {
4428
4529 int64_t RuntimeDyldMachO::memcpyAddend(const RelocationEntry &RE) const {
5034 }
5135
5236 RelocationValueRef RuntimeDyldMachO::getRelocationValueRef(
53 const ObjectFile &BaseTObj, const relocation_iterator &RI,
37 ObjectImage &ObjImg, const relocation_iterator &RI,
5438 const RelocationEntry &RE, ObjSectionToIDMap &ObjSectionToID,
5539 const SymbolTableMap &Symbols) {
5640
5741 const MachOObjectFile &Obj =
58 static_cast(BaseTObj);
42 static_cast(*ObjImg.getObjectFile());
5943 MachO::any_relocation_info RelInfo =
6044 Obj.getRelocation(RI->getRawDataRefImpl());
6145 RelocationValueRef Value;
8266 } else {
8367 SectionRef Sec = Obj.getRelocationSection(RelInfo);
8468 bool IsCode = Sec.isText();
85 Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
69 Value.SectionID = findOrEmitSection(ObjImg, Sec, IsCode, ObjSectionToID);
8670 uint64_t Addr = Sec.getAddress();
8771 Value.Offset = RE.Addend - Addr;
8872 }
9175 }
9276
9377 void RuntimeDyldMachO::makeValueAddendPCRel(RelocationValueRef &Value,
94 const ObjectFile &BaseTObj,
78 ObjectImage &ObjImg,
9579 const relocation_iterator &RI,
9680 unsigned OffsetToNextPC) {
9781 const MachOObjectFile &Obj =
98 static_cast(BaseTObj);
82 static_cast(*ObjImg.getObjectFile());
9983 MachO::any_relocation_info RelInfo =
10084 Obj.getRelocation(RI->getRawDataRefImpl());
10185
140124
141125 // Populate __pointers section.
142126 void RuntimeDyldMachO::populateIndirectSymbolPointersSection(
143 const MachOObjectFile &Obj,
127 MachOObjectFile &Obj,
144128 const SectionRef &PTSection,
145129 unsigned PTSectionID) {
146130 assert(!Obj.is64Bit() &&
178162 }
179163 }
180164
181 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile &Obj) const {
182 return Obj.isMachO();
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();
183183 }
184184
185185 template
186 void RuntimeDyldMachOCRTPBase::finalizeLoad(const ObjectFile &ObjImg,
186 void RuntimeDyldMachOCRTPBase::finalizeLoad(ObjectImage &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 RuntimeDyldMachO::create(Triple::ArchType Arch, RTDyldMemoryManager *MM) {
286 llvm::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
306298 } // end namespace llvm
1313 #ifndef LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_RUNTIMEDYLDMACHO_H
1414 #define LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_RUNTIMEDYLDMACHO_H
1515
16 #include "ObjectImageCommon.h"
1617 #include "RuntimeDyldImpl.h"
1718 #include "llvm/Object/MachO.h"
1819 #include "llvm/Support/Format.h"
5960 /// filled in, since immediate encodings are highly target/opcode specific.
6061 /// For targets/opcodes with simple, contiguous immediates (e.g. X86) the
6162 /// memcpyAddend method can be used to read the immediate.
62 RelocationEntry getRelocationEntry(unsigned SectionID,
63 const ObjectFile &BaseTObj,
63 RelocationEntry getRelocationEntry(unsigned SectionID, ObjectImage &ObjImg,
6464 const relocation_iterator &RI) const {
6565 const MachOObjectFile &Obj =
66 static_cast(BaseTObj);
66 static_cast(*ObjImg.getObjectFile());
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(const ObjectFile &BaseTObj,
89 RelocationValueRef getRelocationValueRef(ObjectImage &ObjImg,
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,
97 const ObjectFile &BaseTObj,
96 void makeValueAddendPCRel(RelocationValueRef &Value, ObjectImage &ObjImg,
9897 const relocation_iterator &RI,
9998 unsigned OffsetToNextPC);
10099
107106
108107
109108 // Populate __pointers section.
110 void populateIndirectSymbolPointersSection(const MachOObjectFile &Obj,
109 void populateIndirectSymbolPointersSection(MachOObjectFile &Obj,
111110 const SectionRef &PTSection,
112111 unsigned PTSectionID);
113112
114113 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 }
115125
116126 /// Create a RuntimeDyldMachO instance for the given target architecture.
117127 static std::unique_ptr create(Triple::ArchType Arch,
118128 RTDyldMemoryManager *mm);
119129
120 std::unique_ptr
121 loadObject(const object::ObjectFile &O) override;
122
123130 SectionEntry &getSection(unsigned SectionID) { return Sections[SectionID]; }
124131
125 bool isCompatibleFile(const object::ObjectFile &Obj) const override;
132 bool isCompatibleFormat(const ObjectBuffer *Buffer) const override;
133 bool isCompatibleFile(const object::ObjectFile *Obj) const override;
126134 };
127135
128136 /// RuntimeDyldMachOTarget - Templated base class for generic MachO linker
144152 public:
145153 RuntimeDyldMachOCRTPBase(RTDyldMemoryManager *mm) : RuntimeDyldMachO(mm) {}
146154
147 void finalizeLoad(const ObjectFile &Obj,
155 void finalizeLoad(ObjectImage &ObjImg,
148156 ObjSectionToIDMap &SectionMap) override;
149157 void registerEHFrames() override;
150158 };
242242
243243 relocation_iterator
244244 processRelocationRef(unsigned SectionID, relocation_iterator RelI,
245 const ObjectFile &BaseObjT,
246 ObjSectionToIDMap &ObjSectionToID,
245 ObjectImage &ObjImg, ObjSectionToIDMap &ObjSectionToID,
247246 const SymbolTableMap &Symbols, StubMap &Stubs) override {
248247 const MachOObjectFile &Obj =
249 static_cast(BaseObjT);
248 static_cast(*ObjImg.getObjectFile());
250249 MachO::any_relocation_info RelInfo =
251250 Obj.getRelocation(RelI->getRawDataRefImpl());
252251
268267 RelInfo = Obj.getRelocation(RelI->getRawDataRefImpl());
269268 }
270269
271 RelocationEntry RE(getRelocationEntry(SectionID, Obj, RelI));
270 RelocationEntry RE(getRelocationEntry(SectionID, ObjImg, RelI));
272271 RE.Addend = decodeAddend(RE);
273272 RelocationValueRef Value(
274 getRelocationValueRef(Obj, RelI, RE, ObjSectionToID, Symbols));
273 getRelocationValueRef(ObjImg, RelI, RE, ObjSectionToID, Symbols));
275274
276275 assert((ExplicitAddend == 0 || RE.Addend == 0) && "Relocation has "\
277276 "ARM64_RELOC_ADDEND and embedded addend in the instruction.");
282281
283282 bool IsExtern = Obj.getPlainRelocationExternal(RelInfo);
284283 if (!IsExtern && RE.IsPCRel)
285 makeValueAddendPCRel(Value, Obj, RelI, 1 << RE.Size);
284 makeValueAddendPCRel(Value, ObjImg, RelI, 1 << RE.Size);
286285
287286 RE.Addend = Value.Offset;
288287
359358 }
360359 }
361360
362 void finalizeSection(const ObjectFile &Obj, unsigned SectionID,
361 void finalizeSection(ObjectImage &ObjImg, unsigned SectionID,
363362 const SectionRef &Section) {}
364363
365364 private:
4848
4949 relocation_iterator
5050 processRelocationRef(unsigned SectionID, relocation_iterator RelI,
51 const ObjectFile &BaseObjT,
52 ObjSectionToIDMap &ObjSectionToID,
51 ObjectImage &ObjImg, ObjSectionToIDMap &ObjSectionToID,
5352 const SymbolTableMap &Symbols, StubMap &Stubs) override {
5453 const MachOObjectFile &Obj =
55 static_cast(BaseObjT);
54 static_cast(*ObjImg.getObjectFile());
5655 MachO::any_relocation_info RelInfo =
5756 Obj.getRelocation(RelI->getRawDataRefImpl());
5857 uint32_t RelType = Obj.getAnyRelocationType(RelInfo);
5958
6059 if (Obj.isRelocationScattered(RelInfo)) {
6160 if (RelType == MachO::ARM_RELOC_HALF_SECTDIFF)
62 return processHALFSECTDIFFRelocation(SectionID, RelI, Obj,
61 return processHALFSECTDIFFRelocation(SectionID, RelI, ObjImg,
6362 ObjSectionToID);
6463 else
6564 return ++++RelI;
6665 }
6766
68 RelocationEntry RE(getRelocationEntry(SectionID, Obj, RelI));
67 RelocationEntry RE(getRelocationEntry(SectionID, ObjImg, RelI));
6968 RE.Addend = decodeAddend(RE);
7069 RelocationValueRef Value(
71 getRelocationValueRef(Obj, RelI, RE, ObjSectionToID, Symbols));
70 getRelocationValueRef(ObjImg, RelI, RE, ObjSectionToID, Symbols));
7271
7372 if (RE.IsPCRel)
74 makeValueAddendPCRel(Value, Obj, RelI, 8);
73 makeValueAddendPCRel(Value, ObjImg, RelI, 8);
7574
7675 if ((RE.RelType & 0xf) == MachO::ARM_RELOC_BR24)
7776 processBranchRelocation(RE, Value, Stubs);
154153 }
155154 }
156155
157 void finalizeSection(const ObjectFile &Obj, unsigned SectionID,
156 void finalizeSection(ObjectImage &ObjImg, unsigned SectionID,
158157 const SectionRef &Section) {
159158 StringRef Name;
160159 Section.getName(Name);
161160
162161 if (Name == "__nl_symbol_ptr")
163 populateIndirectSymbolPointersSection(cast(Obj),
164 Section, SectionID);
162 populateIndirectSymbolPointersSection(
163 cast(*ObjImg.getObjectFile()),
164 Section, SectionID);
165165 }
166166
167167 private:
198198
199199 relocation_iterator
200200 processHALFSECTDIFFRelocation(unsigned SectionID, relocation_iterator RelI,
201 const ObjectFile &BaseTObj,
201 ObjectImage &Obj,
202202 ObjSectionToIDMap &ObjSectionToID) {
203 const MachOObjectFile &MachO =
204 static_cast(BaseTObj);
203 const MachOObjectFile *MachO =
204 static_cast(Obj.getObjectFile());
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(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");
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");
242242 uint64_t SectionBBase = SBI->getAddress();
243243 uint64_t SectionBOffset = AddrB - SectionBBase;
244244 SectionRef SectionB = *SBI;
245245 uint32_t SectionBID =
246 findOrEmitSection(MachO, SectionB, IsCode, ObjSectionToID);
247
248 uint32_t OtherHalf = MachO.getAnyRelocationAddress(RE2) & 0xffff;
246 findOrEmitSection(Obj, 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 const ObjectFile &BaseObjT,
34 ObjSectionToIDMap &ObjSectionToID,
33 ObjectImage &ObjImg, ObjSectionToIDMap &ObjSectionToID,
3534 const SymbolTableMap &Symbols, StubMap &Stubs) override {
3635 const MachOObjectFile &Obj =
37 static_cast(BaseObjT);
36 static_cast(*ObjImg.getObjectFile());
3837 MachO::any_relocation_info RelInfo =
3938 Obj.getRelocation(RelI->getRawDataRefImpl());
4039 uint32_t RelType = Obj.getAnyRelocationType(RelInfo);
4241 if (Obj.isRelocationScattered(RelInfo)) {
4342 if (RelType == MachO::GENERIC_RELOC_SECTDIFF ||
4443 RelType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)
45 return processSECTDIFFRelocation(SectionID, RelI, Obj,
44 return processSECTDIFFRelocation(SectionID, RelI, ObjImg,
4645 ObjSectionToID);
4746 else if (RelType == MachO::GENERIC_RELOC_VANILLA)
48 return processI386ScatteredVANILLA(SectionID, RelI, Obj,
47 return processI386ScatteredVANILLA(SectionID, RelI, ObjImg,
4948 ObjSectionToID);
5049 llvm_unreachable("Unhandled scattered relocation.");
5150 }
5251
53 RelocationEntry RE(getRelocationEntry(SectionID, Obj, RelI));
52 RelocationEntry RE(getRelocationEntry(SectionID, ObjImg, RelI));
5453 RE.Addend = memcpyAddend(RE);
5554 RelocationValueRef Value(
56 getRelocationValueRef(Obj, RelI, RE, ObjSectionToID, Symbols));
55 getRelocationValueRef(ObjImg, RelI, RE, ObjSectionToID, Symbols));
5756
5857 // Addends for external, PC-rel relocations on i386 point back to the zero
5958 // offset. Calculate the final offset from the relocation target instead.
6665 // Value.Addend += RelocAddr + 4;
6766 // }
6867 if (RE.IsPCRel)
69 makeValueAddendPCRel(Value, Obj, RelI, 1 << RE.Size);
68 makeValueAddendPCRel(Value, ObjImg, RelI, 1 << RE.Size);
7069
7170 RE.Addend = Value.Offset;
7271
110109 }
111110 }
112111
113 void finalizeSection(const ObjectFile &Obj, unsigned SectionID,
112 void finalizeSection(ObjectImage &ObjImg, unsigned SectionID,
114113 const SectionRef &Section) {
115114 StringRef Name;
116115 Section.getName(Name);
117116
118117 if (Name == "__jump_table")
119 populateJumpTable(cast(Obj), Section, SectionID);
118 populateJumpTable(cast(*ObjImg.getObjectFile()), Section,
119 SectionID);
120120 else if (Name == "__pointers")
121 populateIndirectSymbolPointersSection(cast(Obj),
122 Section, SectionID);
121 populateIndirectSymbolPointersSection(
122 cast(*ObjImg.getObjectFile()),
123 Section, SectionID);
123124 }
124125
125126 private:
126127 relocation_iterator
127128 processSECTDIFFRelocation(unsigned SectionID, relocation_iterator RelI,
128 const ObjectFile &BaseObjT,
129 ObjectImage &Obj,
129130 ObjSectionToIDMap &ObjSectionToID) {
130 const MachOObjectFile &Obj =
131 static_cast(BaseObjT);
131 const MachOObjectFile *MachO =
132 static_cast(Obj.getObjectFile());
132133 MachO::any_relocation_info RE =
133 Obj.getRelocation(RelI->getRawDataRefImpl());
134 MachO->getRelocation(RelI->getRawDataRefImpl());
134135
135136 SectionEntry &Section = Sections[SectionID];
136 uint32_t RelocType = Obj.getAnyRelocationType(RE);
137 bool IsPCRel = Obj.getAnyRelocationPCRel(RE);
138 unsigned Size = Obj.getAnyRelocationLength(RE);
137 uint32_t RelocType = MachO->getAnyRelocationType(RE);
138 bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
139 unsigned Size = MachO->getAnyRelocationLength(RE);
139140 uint64_t Offset;
140141 RelI->getOffset(Offset);
141142 uint8_t *LocalAddress = Section.Address + Offset;
144145
145146 ++RelI;
146147 MachO::any_relocation_info RE2 =
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");
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");
152153 uint64_t SectionABase = SAI->getAddress();
153154 uint64_t SectionAOffset = AddrA - SectionABase;
154155 SectionRef SectionA = *SAI;
156157 uint32_t SectionAID =
157158 findOrEmitSection(Obj, SectionA, IsCode, ObjSectionToID);
158159
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");
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");
162163 uint64_t SectionBBase = SBI->getAddress();
163164 uint64_t SectionBOffset = AddrB - SectionBBase;
164165 SectionRef SectionB = *SBI;
184185 }
185186
186187 relocation_iterator processI386ScatteredVANILLA(
187 unsigned SectionID, relocation_iterator RelI,
188 const ObjectFile &BaseObjT,
188 unsigned SectionID, relocation_iterator RelI, ObjectImage &Obj,
189189 RuntimeDyldMachO::ObjSectionToIDMap &ObjSectionToID) {
190 const MachOObjectFile &Obj =
191 static_cast(BaseObjT);
190 const MachOObjectFile *MachO =
191 static_cast(Obj.getObjectFile());
192192 MachO::any_relocation_info RE =
193 Obj.getRelocation(RelI->getRawDataRefImpl());
193 MachO->getRelocation(RelI->getRawDataRefImpl());
194194
195195 SectionEntry &Section = Sections[SectionID];
196 uint32_t RelocType = Obj.getAnyRelocationType(RE);
197 bool IsPCRel = Obj.getAnyRelocationPCRel(RE);
198 unsigned Size = Obj.getAnyRelocationLength(RE);
196 uint32_t RelocType = MachO->getAnyRelocationType(RE);
197 bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
198 unsigned Size = MachO->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 = Obj.getScatteredRelocationValue(RE);
206 section_iterator TargetSI = getSectionByAddress(Obj, SymbolBaseAddr);
207 assert(TargetSI != Obj.section_end() && "Can't find section for symbol");
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");
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(const MachOObjectFile &Obj, const SectionRef &JTSection,
223 void populateJumpTable(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 const ObjectFile &BaseObjT,
34 ObjSectionToIDMap &ObjSectionToID,
33 ObjectImage &ObjImg, ObjSectionToIDMap &ObjSectionToID,
3534 const SymbolTableMap &Symbols, StubMap &Stubs) override {
3635 const MachOObjectFile &Obj =
37 static_cast(BaseObjT);
36 static_cast(*ObjImg.getObjectFile());
3837 MachO::any_relocation_info RelInfo =
3938 Obj.getRelocation(RelI->getRawDataRefImpl());
4039
4140 assert(!Obj.isRelocationScattered(RelInfo) &&
4241 "Scattered relocations not supported on X86_64");
4342
44 RelocationEntry RE(getRelocationEntry(SectionID, Obj, RelI));
43 RelocationEntry RE(getRelocationEntry(SectionID, ObjImg, RelI));
4544 RE.Addend = memcpyAddend(RE);
4645 RelocationValueRef Value(
47 getRelocationValueRef(Obj, RelI, RE, ObjSectionToID, Symbols));
46 getRelocationValueRef(ObjImg, RelI, RE, ObjSectionToID, Symbols));
4847
4948 bool IsExtern = Obj.getPlainRelocationExternal(RelInfo);
5049 if (!IsExtern && RE.IsPCRel)
51 makeValueAddendPCRel(Value, Obj, RelI, 1 << RE.Size);
50 makeValueAddendPCRel(Value, ObjImg, RelI, 1 << RE.Size);
5251
5352 if (RE.RelType == MachO::X86_64_RELOC_GOT ||
5453 RE.RelType == MachO::X86_64_RELOC_GOT_LOAD)
9796 }
9897 }
9998
100 void finalizeSection(const ObjectFile &Obj, unsigned SectionID,
99 void finalizeSection(ObjectImage &ObjImg, unsigned SectionID,
101100 const SectionRef &Section) {}
102101
103102 private:
1313
1414 #include "RemoteMemoryManager.h"
1515 #include "llvm/ExecutionEngine/ExecutionEngine.h"
16 #include "llvm/ExecutionEngine/ObjectImage.h"
1617 #include "llvm/Support/Debug.h"
1718 #include "llvm/Support/Format.h"
1819
7677 }
7778
7879 void RemoteMemoryManager::notifyObjectLoaded(ExecutionEngine *EE,
79 const object::ObjectFile &Obj) {
80 const ObjectImage *Obj) {
8081 // The client should have called setRemoteTarget() before triggering any
8182 // code generation.
8283 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,
83 const object::ObjectFile &Obj) override;
82 void notifyObjectLoaded(ExecutionEngine *EE, const ObjectImage *Obj) override;
8483
8584 bool finalizeMemory(std::string *ErrMsg) override;
8685
1818 #include "llvm/ExecutionEngine/JITEventListener.h"
1919 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
2020 #include "llvm/ExecutionEngine/MCJIT.h"
21 #include "llvm/ExecutionEngine/ObjectImage.h"
2122 #include "llvm/IR/Module.h"
2223 #include "llvm/IRReader/IRReader.h"
2324 #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"
1517 #include "llvm/ExecutionEngine/RuntimeDyld.h"
1618 #include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
1719 #include "llvm/MC/MCAsmInfo.h"
204206 if (std::error_code EC = InputBuffer.getError())
205207 return Error("unable to read input: '" + EC.message() + "'");
206208
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
209 std::unique_ptr LoadedObject;
215210 // Load the object file
216 std::unique_ptr LoadedObjInfo =
217 Dyld.loadObject(Obj);
218
219 if (Dyld.hasError())
211 LoadedObject = Dyld.loadObject(
212 llvm::make_unique(std::move(*InputBuffer)));
213 if (!LoadedObject) {
220214 return Error(Dyld.getErrorString());
215 }
221216
222217 // Resolve all the relocations we can.
223218 Dyld.resolveRelocations();
224219
225 OwningBinary DebugObj = LoadedObjInfo->getObjectForDebug(Obj);
226
227220 std::unique_ptr Context(
228 DIContext::getDWARFContext(*DebugObj.getBinary()));
221 DIContext::getDWARFContext(*LoadedObject->getObjectFile()));
229222
230223 // Use symbol info to iterate functions in the object.
231 for (object::symbol_iterator I = DebugObj.getBinary()->symbol_begin(),
232 E = DebugObj.getBinary()->symbol_end();
224 for (object::symbol_iterator I = LoadedObject->begin_symbols(),
225 E = LoadedObject->end_symbols();
233226 I != E; ++I) {
234227 object::SymbolRef::Type SymType;
235228 if (I->getType(SymType)) continue;
274267 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
275268 if (std::error_code EC = InputBuffer.getError())
276269 return Error("unable to read input: '" + EC.message() + "'");
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
270 std::unique_ptr LoadedObject;
285271 // Load the object file
286 Dyld.loadObject(Obj);
287 if (Dyld.hasError()) {
272 LoadedObject = Dyld.loadObject(
273 llvm::make_unique(std::move(*InputBuffer)));
274 if (!LoadedObject) {
288275 return Error(Dyld.getErrorString());
289276 }
290277 }
524511 // Load the input memory buffer.
525512 ErrorOr> InputBuffer =
526513 MemoryBuffer::getFileOrSTDIN(InputFileList[i]);
527
528514 if (std::error_code EC = InputBuffer.getError())
529515 return Error("unable to read input: '" + EC.message() + "'");
530516
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
517 std::unique_ptr LoadedObject;
539518 // Load the object file
540 Dyld.loadObject(Obj);
541 if (Dyld.hasError()) {
519 LoadedObject = Dyld.loadObject(
520 llvm::make_unique(std::move(*InputBuffer)));
521 if (!LoadedObject) {
542522 return Error(Dyld.getErrorString());
543523 }
544524 }