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