]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.cpp
9523 Large alloc in zdb can cause trouble
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Plugins / JITLoader / GDB / JITLoaderGDB.cpp
1 //===-- JITLoaderGDB.cpp ----------------------------------------*- C++ -*-===//
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 // C Includes
11
12 #include "llvm/Support/MathExtras.h"
13
14 #include "lldb/Breakpoint/Breakpoint.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/ModuleSpec.h"
17 #include "lldb/Core/PluginManager.h"
18 #include "lldb/Core/Section.h"
19 #include "lldb/Interpreter/OptionValueProperties.h"
20 #include "lldb/Symbol/ObjectFile.h"
21 #include "lldb/Symbol/Symbol.h"
22 #include "lldb/Symbol/SymbolContext.h"
23 #include "lldb/Symbol/SymbolVendor.h"
24 #include "lldb/Target/Process.h"
25 #include "lldb/Target/SectionLoadList.h"
26 #include "lldb/Target/Target.h"
27 #include "lldb/Utility/DataBufferHeap.h"
28 #include "lldb/Utility/LLDBAssert.h"
29 #include "lldb/Utility/Log.h"
30 #include "lldb/Utility/StreamString.h"
31
32 #include "JITLoaderGDB.h"
33
34 using namespace lldb;
35 using namespace lldb_private;
36
37 //------------------------------------------------------------------
38 // Debug Interface Structures
39 //------------------------------------------------------------------
40 typedef enum {
41   JIT_NOACTION = 0,
42   JIT_REGISTER_FN,
43   JIT_UNREGISTER_FN
44 } jit_actions_t;
45
46 template <typename ptr_t> struct jit_code_entry {
47   ptr_t next_entry;   // pointer
48   ptr_t prev_entry;   // pointer
49   ptr_t symfile_addr; // pointer
50   uint64_t symfile_size;
51 };
52
53 template <typename ptr_t> struct jit_descriptor {
54   uint32_t version;
55   uint32_t action_flag; // Values are jit_action_t
56   ptr_t relevant_entry; // pointer
57   ptr_t first_entry;    // pointer
58 };
59
60 namespace {
61
62 PropertyDefinition g_properties[] = {
63     {"enable-jit-breakpoint", OptionValue::eTypeBoolean, true, true, nullptr,
64      nullptr, "Enable breakpoint on __jit_debug_register_code."},
65     {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
66
67 enum { ePropertyEnableJITBreakpoint };
68
69 class PluginProperties : public Properties {
70 public:
71   static ConstString GetSettingName() {
72     return JITLoaderGDB::GetPluginNameStatic();
73   }
74
75   PluginProperties() {
76     m_collection_sp.reset(new OptionValueProperties(GetSettingName()));
77     m_collection_sp->Initialize(g_properties);
78   }
79
80   bool GetEnableJITBreakpoint() const {
81     return m_collection_sp->GetPropertyAtIndexAsBoolean(
82         nullptr, ePropertyEnableJITBreakpoint,
83         g_properties[ePropertyEnableJITBreakpoint].default_uint_value != 0);
84   }
85 };
86
87 typedef std::shared_ptr<PluginProperties> JITLoaderGDBPropertiesSP;
88
89 static const JITLoaderGDBPropertiesSP &GetGlobalPluginProperties() {
90   static const auto g_settings_sp(std::make_shared<PluginProperties>());
91   return g_settings_sp;
92 }
93
94 template <typename ptr_t>
95 bool ReadJITEntry(const addr_t from_addr, Process *process,
96                   jit_code_entry<ptr_t> *entry) {
97   lldbassert(from_addr % sizeof(ptr_t) == 0);
98
99   ArchSpec::Core core = process->GetTarget().GetArchitecture().GetCore();
100   bool i386_target = ArchSpec::kCore_x86_32_first <= core &&
101                      core <= ArchSpec::kCore_x86_32_last;
102   uint8_t uint64_align_bytes = i386_target ? 4 : 8;
103   const size_t data_byte_size =
104       llvm::alignTo(sizeof(ptr_t) * 3, uint64_align_bytes) + sizeof(uint64_t);
105
106   Status error;
107   DataBufferHeap data(data_byte_size, 0);
108   size_t bytes_read = process->ReadMemory(from_addr, data.GetBytes(),
109                                           data.GetByteSize(), error);
110   if (bytes_read != data_byte_size || !error.Success())
111     return false;
112
113   DataExtractor extractor(data.GetBytes(), data.GetByteSize(),
114                           process->GetByteOrder(), sizeof(ptr_t));
115   lldb::offset_t offset = 0;
116   entry->next_entry = extractor.GetPointer(&offset);
117   entry->prev_entry = extractor.GetPointer(&offset);
118   entry->symfile_addr = extractor.GetPointer(&offset);
119   offset = llvm::alignTo(offset, uint64_align_bytes);
120   entry->symfile_size = extractor.GetU64(&offset);
121
122   return true;
123 }
124
125 } // anonymous namespace end
126
127 JITLoaderGDB::JITLoaderGDB(lldb_private::Process *process)
128     : JITLoader(process), m_jit_objects(),
129       m_jit_break_id(LLDB_INVALID_BREAK_ID),
130       m_jit_descriptor_addr(LLDB_INVALID_ADDRESS) {}
131
132 JITLoaderGDB::~JITLoaderGDB() {
133   if (LLDB_BREAK_ID_IS_VALID(m_jit_break_id))
134     m_process->GetTarget().RemoveBreakpointByID(m_jit_break_id);
135 }
136
137 void JITLoaderGDB::DebuggerInitialize(Debugger &debugger) {
138   if (!PluginManager::GetSettingForJITLoaderPlugin(
139           debugger, PluginProperties::GetSettingName())) {
140     const bool is_global_setting = true;
141     PluginManager::CreateSettingForJITLoaderPlugin(
142         debugger, GetGlobalPluginProperties()->GetValueProperties(),
143         ConstString("Properties for the JIT LoaderGDB plug-in."),
144         is_global_setting);
145   }
146 }
147
148 void JITLoaderGDB::DidAttach() {
149   Target &target = m_process->GetTarget();
150   ModuleList &module_list = target.GetImages();
151   SetJITBreakpoint(module_list);
152 }
153
154 void JITLoaderGDB::DidLaunch() {
155   Target &target = m_process->GetTarget();
156   ModuleList &module_list = target.GetImages();
157   SetJITBreakpoint(module_list);
158 }
159
160 void JITLoaderGDB::ModulesDidLoad(ModuleList &module_list) {
161   if (!DidSetJITBreakpoint() && m_process->IsAlive())
162     SetJITBreakpoint(module_list);
163 }
164
165 //------------------------------------------------------------------
166 // Setup the JIT Breakpoint
167 //------------------------------------------------------------------
168 void JITLoaderGDB::SetJITBreakpoint(lldb_private::ModuleList &module_list) {
169   if (!GetGlobalPluginProperties()->GetEnableJITBreakpoint())
170     return;
171
172   if (DidSetJITBreakpoint())
173     return;
174
175   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_JIT_LOADER));
176   if (log)
177     log->Printf("JITLoaderGDB::%s looking for JIT register hook", __FUNCTION__);
178
179   addr_t jit_addr = GetSymbolAddress(
180       module_list, ConstString("__jit_debug_register_code"), eSymbolTypeAny);
181   if (jit_addr == LLDB_INVALID_ADDRESS)
182     return;
183
184   m_jit_descriptor_addr = GetSymbolAddress(
185       module_list, ConstString("__jit_debug_descriptor"), eSymbolTypeData);
186   if (m_jit_descriptor_addr == LLDB_INVALID_ADDRESS) {
187     if (log)
188       log->Printf("JITLoaderGDB::%s failed to find JIT descriptor address",
189                   __FUNCTION__);
190     return;
191   }
192
193   if (log)
194     log->Printf("JITLoaderGDB::%s setting JIT breakpoint", __FUNCTION__);
195
196   Breakpoint *bp =
197       m_process->GetTarget().CreateBreakpoint(jit_addr, true, false).get();
198   bp->SetCallback(JITDebugBreakpointHit, this, true);
199   bp->SetBreakpointKind("jit-debug-register");
200   m_jit_break_id = bp->GetID();
201
202   ReadJITDescriptor(true);
203 }
204
205 bool JITLoaderGDB::JITDebugBreakpointHit(void *baton,
206                                          StoppointCallbackContext *context,
207                                          user_id_t break_id,
208                                          user_id_t break_loc_id) {
209   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_JIT_LOADER));
210   if (log)
211     log->Printf("JITLoaderGDB::%s hit JIT breakpoint", __FUNCTION__);
212   JITLoaderGDB *instance = static_cast<JITLoaderGDB *>(baton);
213   return instance->ReadJITDescriptor(false);
214 }
215
216 static void updateSectionLoadAddress(const SectionList &section_list,
217                                      Target &target, uint64_t symbolfile_addr,
218                                      uint64_t symbolfile_size,
219                                      uint64_t &vmaddrheuristic,
220                                      uint64_t &min_addr, uint64_t &max_addr) {
221   const uint32_t num_sections = section_list.GetSize();
222   for (uint32_t i = 0; i < num_sections; ++i) {
223     SectionSP section_sp(section_list.GetSectionAtIndex(i));
224     if (section_sp) {
225       if (section_sp->IsFake()) {
226         uint64_t lower = (uint64_t)-1;
227         uint64_t upper = 0;
228         updateSectionLoadAddress(section_sp->GetChildren(), target,
229                                  symbolfile_addr, symbolfile_size,
230                                  vmaddrheuristic, lower, upper);
231         if (lower < min_addr)
232           min_addr = lower;
233         if (upper > max_addr)
234           max_addr = upper;
235         const lldb::addr_t slide_amount = lower - section_sp->GetFileAddress();
236         section_sp->Slide(slide_amount, false);
237         section_sp->GetChildren().Slide(-slide_amount, false);
238         section_sp->SetByteSize(upper - lower);
239       } else {
240         vmaddrheuristic += 2 << section_sp->GetLog2Align();
241         uint64_t lower;
242         if (section_sp->GetFileAddress() > vmaddrheuristic)
243           lower = section_sp->GetFileAddress();
244         else {
245           lower = symbolfile_addr + section_sp->GetFileOffset();
246           section_sp->SetFileAddress(symbolfile_addr +
247                                      section_sp->GetFileOffset());
248         }
249         target.SetSectionLoadAddress(section_sp, lower, true);
250         uint64_t upper = lower + section_sp->GetByteSize();
251         if (lower < min_addr)
252           min_addr = lower;
253         if (upper > max_addr)
254           max_addr = upper;
255         // This is an upper bound, but a good enough heuristic
256         vmaddrheuristic += section_sp->GetByteSize();
257       }
258     }
259   }
260 }
261
262 bool JITLoaderGDB::ReadJITDescriptor(bool all_entries) {
263   if (m_process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
264     return ReadJITDescriptorImpl<uint64_t>(all_entries);
265   else
266     return ReadJITDescriptorImpl<uint32_t>(all_entries);
267 }
268
269 template <typename ptr_t>
270 bool JITLoaderGDB::ReadJITDescriptorImpl(bool all_entries) {
271   if (m_jit_descriptor_addr == LLDB_INVALID_ADDRESS)
272     return false;
273
274   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_JIT_LOADER));
275   Target &target = m_process->GetTarget();
276   ModuleList &module_list = target.GetImages();
277
278   jit_descriptor<ptr_t> jit_desc;
279   const size_t jit_desc_size = sizeof(jit_desc);
280   Status error;
281   size_t bytes_read = m_process->DoReadMemory(m_jit_descriptor_addr, &jit_desc,
282                                               jit_desc_size, error);
283   if (bytes_read != jit_desc_size || !error.Success()) {
284     if (log)
285       log->Printf("JITLoaderGDB::%s failed to read JIT descriptor",
286                   __FUNCTION__);
287     return false;
288   }
289
290   jit_actions_t jit_action = (jit_actions_t)jit_desc.action_flag;
291   addr_t jit_relevant_entry = (addr_t)jit_desc.relevant_entry;
292   if (all_entries) {
293     jit_action = JIT_REGISTER_FN;
294     jit_relevant_entry = (addr_t)jit_desc.first_entry;
295   }
296
297   while (jit_relevant_entry != 0) {
298     jit_code_entry<ptr_t> jit_entry;
299     if (!ReadJITEntry(jit_relevant_entry, m_process, &jit_entry)) {
300       if (log)
301         log->Printf("JITLoaderGDB::%s failed to read JIT entry at 0x%" PRIx64,
302                     __FUNCTION__, jit_relevant_entry);
303       return false;
304     }
305
306     const addr_t &symbolfile_addr = (addr_t)jit_entry.symfile_addr;
307     const size_t &symbolfile_size = (size_t)jit_entry.symfile_size;
308     ModuleSP module_sp;
309
310     if (jit_action == JIT_REGISTER_FN) {
311       if (log)
312         log->Printf("JITLoaderGDB::%s registering JIT entry at 0x%" PRIx64
313                     " (%" PRIu64 " bytes)",
314                     __FUNCTION__, symbolfile_addr, (uint64_t)symbolfile_size);
315
316       char jit_name[64];
317       snprintf(jit_name, 64, "JIT(0x%" PRIx64 ")", symbolfile_addr);
318       module_sp = m_process->ReadModuleFromMemory(
319           FileSpec(jit_name, false), symbolfile_addr, symbolfile_size);
320
321       if (module_sp && module_sp->GetObjectFile()) {
322         // load the symbol table right away
323         module_sp->GetObjectFile()->GetSymtab();
324
325         m_jit_objects.insert(std::make_pair(symbolfile_addr, module_sp));
326         if (module_sp->GetObjectFile()->GetPluginName() ==
327             ConstString("mach-o")) {
328           ObjectFile *image_object_file = module_sp->GetObjectFile();
329           if (image_object_file) {
330             const SectionList *section_list =
331                 image_object_file->GetSectionList();
332             if (section_list) {
333               uint64_t vmaddrheuristic = 0;
334               uint64_t lower = (uint64_t)-1;
335               uint64_t upper = 0;
336               updateSectionLoadAddress(*section_list, target, symbolfile_addr,
337                                        symbolfile_size, vmaddrheuristic, lower,
338                                        upper);
339             }
340           }
341         } else {
342           bool changed = false;
343           module_sp->SetLoadAddress(target, 0, true, changed);
344         }
345
346         module_list.AppendIfNeeded(module_sp);
347
348         ModuleList module_list;
349         module_list.Append(module_sp);
350         target.ModulesDidLoad(module_list);
351       } else {
352         if (log)
353           log->Printf("JITLoaderGDB::%s failed to load module for "
354                       "JIT entry at 0x%" PRIx64,
355                       __FUNCTION__, symbolfile_addr);
356       }
357     } else if (jit_action == JIT_UNREGISTER_FN) {
358       if (log)
359         log->Printf("JITLoaderGDB::%s unregistering JIT entry at 0x%" PRIx64,
360                     __FUNCTION__, symbolfile_addr);
361
362       JITObjectMap::iterator it = m_jit_objects.find(symbolfile_addr);
363       if (it != m_jit_objects.end()) {
364         module_sp = it->second;
365         ObjectFile *image_object_file = module_sp->GetObjectFile();
366         if (image_object_file) {
367           const SectionList *section_list = image_object_file->GetSectionList();
368           if (section_list) {
369             const uint32_t num_sections = section_list->GetSize();
370             for (uint32_t i = 0; i < num_sections; ++i) {
371               SectionSP section_sp(section_list->GetSectionAtIndex(i));
372               if (section_sp) {
373                 target.GetSectionLoadList().SetSectionUnloaded(section_sp);
374               }
375             }
376           }
377         }
378         module_list.Remove(module_sp);
379         m_jit_objects.erase(it);
380       }
381     } else if (jit_action == JIT_NOACTION) {
382       // Nothing to do
383     } else {
384       assert(false && "Unknown jit action");
385     }
386
387     if (all_entries)
388       jit_relevant_entry = (addr_t)jit_entry.next_entry;
389     else
390       jit_relevant_entry = 0;
391   }
392
393   return false; // Continue Running.
394 }
395
396 //------------------------------------------------------------------
397 // PluginInterface protocol
398 //------------------------------------------------------------------
399 lldb_private::ConstString JITLoaderGDB::GetPluginNameStatic() {
400   static ConstString g_name("gdb");
401   return g_name;
402 }
403
404 JITLoaderSP JITLoaderGDB::CreateInstance(Process *process, bool force) {
405   JITLoaderSP jit_loader_sp;
406   ArchSpec arch(process->GetTarget().GetArchitecture());
407   if (arch.GetTriple().getVendor() != llvm::Triple::Apple)
408     jit_loader_sp.reset(new JITLoaderGDB(process));
409   return jit_loader_sp;
410 }
411
412 const char *JITLoaderGDB::GetPluginDescriptionStatic() {
413   return "JIT loader plug-in that watches for JIT events using the GDB "
414          "interface.";
415 }
416
417 lldb_private::ConstString JITLoaderGDB::GetPluginName() {
418   return GetPluginNameStatic();
419 }
420
421 uint32_t JITLoaderGDB::GetPluginVersion() { return 1; }
422
423 void JITLoaderGDB::Initialize() {
424   PluginManager::RegisterPlugin(GetPluginNameStatic(),
425                                 GetPluginDescriptionStatic(), CreateInstance,
426                                 DebuggerInitialize);
427 }
428
429 void JITLoaderGDB::Terminate() {
430   PluginManager::UnregisterPlugin(CreateInstance);
431 }
432
433 bool JITLoaderGDB::DidSetJITBreakpoint() const {
434   return LLDB_BREAK_ID_IS_VALID(m_jit_break_id);
435 }
436
437 addr_t JITLoaderGDB::GetSymbolAddress(ModuleList &module_list,
438                                       const ConstString &name,
439                                       SymbolType symbol_type) const {
440   SymbolContextList target_symbols;
441   Target &target = m_process->GetTarget();
442
443   if (!module_list.FindSymbolsWithNameAndType(name, symbol_type,
444                                               target_symbols))
445     return LLDB_INVALID_ADDRESS;
446
447   SymbolContext sym_ctx;
448   target_symbols.GetContextAtIndex(0, sym_ctx);
449
450   const Address jit_descriptor_addr = sym_ctx.symbol->GetAddress();
451   if (!jit_descriptor_addr.IsValid())
452     return LLDB_INVALID_ADDRESS;
453
454   const addr_t jit_addr = jit_descriptor_addr.GetLoadAddress(&target);
455   return jit_addr;
456 }