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