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