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