[MCJIT] Reapply r222828 and r222810-r222812 with fix for MSVC move-op issues.
[oota-llvm.git] / lib / ExecutionEngine / RuntimeDyld / GDBRegistrationListener.cpp
1 //===----- GDBRegistrationListener.cpp - Registers objects with GDB -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/ADT/DenseMap.h"
11 #include "llvm/ExecutionEngine/JITEventListener.h"
12 #include "llvm/Object/ObjectFile.h"
13 #include "llvm/Support/Compiler.h"
14 #include "llvm/Support/ErrorHandling.h"
15 #include "llvm/Support/Mutex.h"
16 #include "llvm/Support/MutexGuard.h"
17 #include "llvm/Support/ManagedStatic.h"
18
19 using namespace llvm;
20 using namespace llvm::object;
21
22 // This must be kept in sync with gdb/gdb/jit.h .
23 extern "C" {
24
25   typedef enum {
26     JIT_NOACTION = 0,
27     JIT_REGISTER_FN,
28     JIT_UNREGISTER_FN
29   } jit_actions_t;
30
31   struct jit_code_entry {
32     struct jit_code_entry *next_entry;
33     struct jit_code_entry *prev_entry;
34     const char *symfile_addr;
35     uint64_t symfile_size;
36   };
37
38   struct jit_descriptor {
39     uint32_t version;
40     // This should be jit_actions_t, but we want to be specific about the
41     // bit-width.
42     uint32_t action_flag;
43     struct jit_code_entry *relevant_entry;
44     struct jit_code_entry *first_entry;
45   };
46
47   // We put information about the JITed function in this global, which the
48   // debugger reads.  Make sure to specify the version statically, because the
49   // debugger checks the version before we can set it during runtime.
50   struct jit_descriptor __jit_debug_descriptor = { 1, 0, nullptr, nullptr };
51
52   // Debuggers puts a breakpoint in this function.
53   LLVM_ATTRIBUTE_NOINLINE void __jit_debug_register_code() {
54     // The noinline and the asm prevent calls to this function from being
55     // optimized out.
56 #if !defined(_MSC_VER)
57     asm volatile("":::"memory");
58 #endif
59   }
60
61 }
62
63 namespace {
64
65 struct RegisteredObjectInfo {
66   RegisteredObjectInfo() {}
67
68   RegisteredObjectInfo(std::size_t Size, jit_code_entry *Entry,
69                        OwningBinary<ObjectFile> Obj)
70     : Size(Size), Entry(Entry), Obj(std::move(Obj)) {}
71
72   RegisteredObjectInfo(RegisteredObjectInfo &&Other)
73     : Size(Other.Size), Entry(Other.Entry), Obj(std::move(Other.Obj)) {}
74
75   RegisteredObjectInfo& operator=(RegisteredObjectInfo &&Other) {
76     Size = Other.Size;
77     Entry = Other.Entry;
78     Obj = std::move(Other.Obj);
79   }
80
81   std::size_t Size;
82   jit_code_entry *Entry;
83   OwningBinary<ObjectFile> Obj;
84 };
85
86 // Buffer for an in-memory object file in executable memory
87 typedef llvm::DenseMap< const char*, RegisteredObjectInfo>
88   RegisteredObjectBufferMap;
89
90 /// Global access point for the JIT debugging interface designed for use with a
91 /// singleton toolbox. Handles thread-safe registration and deregistration of
92 /// object files that are in executable memory managed by the client of this
93 /// class.
94 class GDBJITRegistrationListener : public JITEventListener {
95   /// A map of in-memory object files that have been registered with the
96   /// JIT interface.
97   RegisteredObjectBufferMap ObjectBufferMap;
98
99 public:
100   /// Instantiates the JIT service.
101   GDBJITRegistrationListener() : ObjectBufferMap() {}
102
103   /// Unregisters each object that was previously registered and releases all
104   /// internal resources.
105   virtual ~GDBJITRegistrationListener();
106
107   /// Creates an entry in the JIT registry for the buffer @p Object,
108   /// which must contain an object file in executable memory with any
109   /// debug information for the debugger.
110   void NotifyObjectEmitted(const ObjectFile &Object,
111                            const RuntimeDyld::LoadedObjectInfo &L) override;
112
113   /// Removes the internal registration of @p Object, and
114   /// frees associated resources.
115   /// Returns true if @p Object was found in ObjectBufferMap.
116   void NotifyFreeingObject(const ObjectFile &Object) override;
117
118 private:
119   /// Deregister the debug info for the given object file from the debugger
120   /// and delete any temporary copies.  This private method does not remove
121   /// the function from Map so that it can be called while iterating over Map.
122   void deregisterObjectInternal(RegisteredObjectBufferMap::iterator I);
123 };
124
125 /// Lock used to serialize all jit registration events, since they
126 /// modify global variables.
127 ManagedStatic<sys::Mutex> JITDebugLock;
128
129 /// Do the registration.
130 void NotifyDebugger(jit_code_entry* JITCodeEntry) {
131   __jit_debug_descriptor.action_flag = JIT_REGISTER_FN;
132
133   // Insert this entry at the head of the list.
134   JITCodeEntry->prev_entry = nullptr;
135   jit_code_entry* NextEntry = __jit_debug_descriptor.first_entry;
136   JITCodeEntry->next_entry = NextEntry;
137   if (NextEntry) {
138     NextEntry->prev_entry = JITCodeEntry;
139   }
140   __jit_debug_descriptor.first_entry = JITCodeEntry;
141   __jit_debug_descriptor.relevant_entry = JITCodeEntry;
142   __jit_debug_register_code();
143 }
144
145 GDBJITRegistrationListener::~GDBJITRegistrationListener() {
146   // Free all registered object files.
147   llvm::MutexGuard locked(*JITDebugLock);
148   for (RegisteredObjectBufferMap::iterator I = ObjectBufferMap.begin(),
149                                            E = ObjectBufferMap.end();
150        I != E; ++I) {
151     // Call the private method that doesn't update the map so our iterator
152     // doesn't break.
153     deregisterObjectInternal(I);
154   }
155   ObjectBufferMap.clear();
156 }
157
158 void GDBJITRegistrationListener::NotifyObjectEmitted(
159                                        const ObjectFile &Object,
160                                        const RuntimeDyld::LoadedObjectInfo &L) {
161
162   OwningBinary<ObjectFile> DebugObj = L.getObjectForDebug(Object);
163
164   // Bail out if debug objects aren't supported.
165   if (!DebugObj.getBinary())
166     return;
167
168   const char *Buffer = DebugObj.getBinary()->getMemoryBufferRef().getBufferStart();
169   size_t      Size = DebugObj.getBinary()->getMemoryBufferRef().getBufferSize();
170
171   const char *Key = Object.getMemoryBufferRef().getBufferStart();
172
173   assert(Key && "Attempt to register a null object with a debugger.");
174   llvm::MutexGuard locked(*JITDebugLock);
175   assert(ObjectBufferMap.find(Key) == ObjectBufferMap.end() &&
176          "Second attempt to perform debug registration.");
177   jit_code_entry* JITCodeEntry = new jit_code_entry();
178
179   if (!JITCodeEntry) {
180     llvm::report_fatal_error(
181       "Allocation failed when registering a JIT entry!\n");
182   } else {
183     JITCodeEntry->symfile_addr = Buffer;
184     JITCodeEntry->symfile_size = Size;
185
186     ObjectBufferMap[Key] = RegisteredObjectInfo(Size, JITCodeEntry,
187                                                 std::move(DebugObj));
188     NotifyDebugger(JITCodeEntry);
189   }
190 }
191
192 void GDBJITRegistrationListener::NotifyFreeingObject(const ObjectFile& Object) {
193   const char *Key = Object.getMemoryBufferRef().getBufferStart();
194   llvm::MutexGuard locked(*JITDebugLock);
195   RegisteredObjectBufferMap::iterator I = ObjectBufferMap.find(Key);
196
197   if (I != ObjectBufferMap.end()) {
198     deregisterObjectInternal(I);
199     ObjectBufferMap.erase(I);
200   }
201 }
202
203 void GDBJITRegistrationListener::deregisterObjectInternal(
204     RegisteredObjectBufferMap::iterator I) {
205
206   jit_code_entry*& JITCodeEntry = I->second.Entry;
207
208   // Do the unregistration.
209   {
210     __jit_debug_descriptor.action_flag = JIT_UNREGISTER_FN;
211
212     // Remove the jit_code_entry from the linked list.
213     jit_code_entry* PrevEntry = JITCodeEntry->prev_entry;
214     jit_code_entry* NextEntry = JITCodeEntry->next_entry;
215
216     if (NextEntry) {
217       NextEntry->prev_entry = PrevEntry;
218     }
219     if (PrevEntry) {
220       PrevEntry->next_entry = NextEntry;
221     }
222     else {
223       assert(__jit_debug_descriptor.first_entry == JITCodeEntry);
224       __jit_debug_descriptor.first_entry = NextEntry;
225     }
226
227     // Tell the debugger which entry we removed, and unregister the code.
228     __jit_debug_descriptor.relevant_entry = JITCodeEntry;
229     __jit_debug_register_code();
230   }
231
232   delete JITCodeEntry;
233   JITCodeEntry = nullptr;
234 }
235
236 llvm::ManagedStatic<GDBJITRegistrationListener> GDBRegListener;
237
238 } // end namespace
239
240 namespace llvm {
241
242 JITEventListener* JITEventListener::createGDBRegistrationListener() {
243   return &*GDBRegListener;
244 }
245
246 } // namespace llvm