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 #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/Log.h"
27 #include "lldb/Utility/StreamString.h"
28 #include "llvm/Support/MathExtras.h"
29 
30 #include <memory>
31 
32 using namespace lldb;
33 using namespace lldb_private;
34 
35 // Debug Interface Structures
36 enum jit_actions_t { JIT_NOACTION = 0, JIT_REGISTER_FN, JIT_UNREGISTER_FN };
37 
38 template <typename ptr_t> struct jit_code_entry {
39   ptr_t next_entry;   // pointer
40   ptr_t prev_entry;   // pointer
41   ptr_t symfile_addr; // pointer
42   uint64_t symfile_size;
43 };
44 
45 template <typename ptr_t> struct jit_descriptor {
46   uint32_t version;
47   uint32_t action_flag; // Values are jit_action_t
48   ptr_t relevant_entry; // pointer
49   ptr_t first_entry;    // pointer
50 };
51 
52 namespace {
53 
54 enum EnableJITLoaderGDB {
55   eEnableJITLoaderGDBDefault,
56   eEnableJITLoaderGDBOn,
57   eEnableJITLoaderGDBOff,
58 };
59 
60 static constexpr OptionEnumValueElement g_enable_jit_loader_gdb_enumerators[] = {
61     {eEnableJITLoaderGDBDefault, "default", "Enable JIT compilation interface "
62      "for all platforms except macOS"},
63     {eEnableJITLoaderGDBOn, "on", "Enable JIT compilation interface"},
64     {eEnableJITLoaderGDBOff, "off", "Disable JIT compilation interface"}
65  };
66 
67 #define LLDB_PROPERTIES_jitloadergdb
68 #include "JITLoaderGDBProperties.inc"
69 
70 enum {
71 #define LLDB_PROPERTIES_jitloadergdb
72 #include "JITLoaderGDBPropertiesEnum.inc"
73   ePropertyEnableJITBreakpoint
74 };
75 
76 class PluginProperties : public Properties {
77 public:
78   static ConstString GetSettingName() {
79     return JITLoaderGDB::GetPluginNameStatic();
80   }
81 
82   PluginProperties() {
83     m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
84     m_collection_sp->Initialize(g_jitloadergdb_properties);
85   }
86 
87   EnableJITLoaderGDB GetEnable() const {
88     return (EnableJITLoaderGDB)m_collection_sp->GetPropertyAtIndexAsEnumeration(
89         nullptr, ePropertyEnable,
90         g_jitloadergdb_properties[ePropertyEnable].default_uint_value);
91   }
92 };
93 
94 typedef std::shared_ptr<PluginProperties> JITLoaderGDBPropertiesSP;
95 
96 static const JITLoaderGDBPropertiesSP &GetGlobalPluginProperties() {
97   static const auto g_settings_sp(std::make_shared<PluginProperties>());
98   return g_settings_sp;
99 }
100 
101 template <typename ptr_t>
102 bool ReadJITEntry(const addr_t from_addr, Process *process,
103                   jit_code_entry<ptr_t> *entry) {
104   lldbassert(from_addr % sizeof(ptr_t) == 0);
105 
106   ArchSpec::Core core = process->GetTarget().GetArchitecture().GetCore();
107   bool i386_target = ArchSpec::kCore_x86_32_first <= core &&
108                      core <= ArchSpec::kCore_x86_32_last;
109   uint8_t uint64_align_bytes = i386_target ? 4 : 8;
110   const size_t data_byte_size =
111       llvm::alignTo(sizeof(ptr_t) * 3, uint64_align_bytes) + sizeof(uint64_t);
112 
113   Status error;
114   DataBufferHeap data(data_byte_size, 0);
115   size_t bytes_read = process->ReadMemory(from_addr, data.GetBytes(),
116                                           data.GetByteSize(), error);
117   if (bytes_read != data_byte_size || !error.Success())
118     return false;
119 
120   DataExtractor extractor(data.GetBytes(), data.GetByteSize(),
121                           process->GetByteOrder(), sizeof(ptr_t));
122   lldb::offset_t offset = 0;
123   entry->next_entry = extractor.GetPointer(&offset);
124   entry->prev_entry = extractor.GetPointer(&offset);
125   entry->symfile_addr = extractor.GetPointer(&offset);
126   offset = llvm::alignTo(offset, uint64_align_bytes);
127   entry->symfile_size = extractor.GetU64(&offset);
128 
129   return true;
130 }
131 
132 } // anonymous namespace end
133 
134 JITLoaderGDB::JITLoaderGDB(lldb_private::Process *process)
135     : JITLoader(process), m_jit_objects(),
136       m_jit_break_id(LLDB_INVALID_BREAK_ID),
137       m_jit_descriptor_addr(LLDB_INVALID_ADDRESS) {}
138 
139 JITLoaderGDB::~JITLoaderGDB() {
140   if (LLDB_BREAK_ID_IS_VALID(m_jit_break_id))
141     m_process->GetTarget().RemoveBreakpointByID(m_jit_break_id);
142 }
143 
144 void JITLoaderGDB::DebuggerInitialize(Debugger &debugger) {
145   if (!PluginManager::GetSettingForJITLoaderPlugin(
146           debugger, PluginProperties::GetSettingName())) {
147     const bool is_global_setting = true;
148     PluginManager::CreateSettingForJITLoaderPlugin(
149         debugger, GetGlobalPluginProperties()->GetValueProperties(),
150         ConstString("Properties for the JIT LoaderGDB plug-in."),
151         is_global_setting);
152   }
153 }
154 
155 void JITLoaderGDB::DidAttach() {
156   Target &target = m_process->GetTarget();
157   ModuleList &module_list = target.GetImages();
158   SetJITBreakpoint(module_list);
159 }
160 
161 void JITLoaderGDB::DidLaunch() {
162   Target &target = m_process->GetTarget();
163   ModuleList &module_list = target.GetImages();
164   SetJITBreakpoint(module_list);
165 }
166 
167 void JITLoaderGDB::ModulesDidLoad(ModuleList &module_list) {
168   if (!DidSetJITBreakpoint() && m_process->IsAlive())
169     SetJITBreakpoint(module_list);
170 }
171 
172 // Setup the JIT Breakpoint
173 void JITLoaderGDB::SetJITBreakpoint(lldb_private::ModuleList &module_list) {
174   if (DidSetJITBreakpoint())
175     return;
176 
177   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_JIT_LOADER));
178   LLDB_LOGF(log, "JITLoaderGDB::%s looking for JIT register hook",
179             __FUNCTION__);
180 
181   addr_t jit_addr = GetSymbolAddress(
182       module_list, ConstString("__jit_debug_register_code"), eSymbolTypeAny);
183   if (jit_addr == LLDB_INVALID_ADDRESS)
184     return;
185 
186   m_jit_descriptor_addr = GetSymbolAddress(
187       module_list, ConstString("__jit_debug_descriptor"), eSymbolTypeData);
188   if (m_jit_descriptor_addr == LLDB_INVALID_ADDRESS) {
189     LLDB_LOGF(log, "JITLoaderGDB::%s failed to find JIT descriptor address",
190               __FUNCTION__);
191     return;
192   }
193 
194   LLDB_LOGF(log, "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   LLDB_LOGF(log, "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     LLDB_LOGF(log, "JITLoaderGDB::%s failed to read JIT descriptor",
284               __FUNCTION__);
285     return false;
286   }
287 
288   jit_actions_t jit_action = (jit_actions_t)jit_desc.action_flag;
289   addr_t jit_relevant_entry = (addr_t)jit_desc.relevant_entry;
290   if (all_entries) {
291     jit_action = JIT_REGISTER_FN;
292     jit_relevant_entry = (addr_t)jit_desc.first_entry;
293   }
294 
295   while (jit_relevant_entry != 0) {
296     jit_code_entry<ptr_t> jit_entry;
297     if (!ReadJITEntry(jit_relevant_entry, m_process, &jit_entry)) {
298       LLDB_LOGF(log, "JITLoaderGDB::%s failed to read JIT entry at 0x%" PRIx64,
299                 __FUNCTION__, jit_relevant_entry);
300       return false;
301     }
302 
303     const addr_t &symbolfile_addr = (addr_t)jit_entry.symfile_addr;
304     const size_t &symbolfile_size = (size_t)jit_entry.symfile_size;
305     ModuleSP module_sp;
306 
307     if (jit_action == JIT_REGISTER_FN) {
308       LLDB_LOGF(log,
309                 "JITLoaderGDB::%s registering JIT entry at 0x%" PRIx64
310                 " (%" PRIu64 " bytes)",
311                 __FUNCTION__, symbolfile_addr, (uint64_t)symbolfile_size);
312 
313       char jit_name[64];
314       snprintf(jit_name, 64, "JIT(0x%" PRIx64 ")", symbolfile_addr);
315       module_sp = m_process->ReadModuleFromMemory(
316           FileSpec(jit_name), symbolfile_addr, symbolfile_size);
317 
318       if (module_sp && module_sp->GetObjectFile()) {
319         // Object formats (like ELF) have no representation for a JIT type.
320         // We will get it wrong, if we deduce it from the header.
321         module_sp->GetObjectFile()->SetType(ObjectFile::eTypeJIT);
322 
323         // load the symbol table right away
324         module_sp->GetObjectFile()->GetSymtab();
325 
326         m_jit_objects.insert(std::make_pair(symbolfile_addr, module_sp));
327         if (auto image_object_file =
328                 llvm::dyn_cast<ObjectFileMachO>(module_sp->GetObjectFile())) {
329           const SectionList *section_list = image_object_file->GetSectionList();
330           if (section_list) {
331             uint64_t vmaddrheuristic = 0;
332             uint64_t lower = (uint64_t)-1;
333             uint64_t upper = 0;
334             updateSectionLoadAddress(*section_list, target, symbolfile_addr,
335                                      symbolfile_size, vmaddrheuristic, lower,
336                                      upper);
337           }
338         } else {
339           bool changed = false;
340           module_sp->SetLoadAddress(target, 0, true, changed);
341         }
342 
343         module_list.AppendIfNeeded(module_sp);
344 
345         ModuleList module_list;
346         module_list.Append(module_sp);
347         target.ModulesDidLoad(module_list);
348       } else {
349         LLDB_LOGF(log,
350                   "JITLoaderGDB::%s failed to load module for "
351                   "JIT entry at 0x%" PRIx64,
352                   __FUNCTION__, symbolfile_addr);
353       }
354     } else if (jit_action == JIT_UNREGISTER_FN) {
355       LLDB_LOGF(log, "JITLoaderGDB::%s unregistering JIT entry at 0x%" PRIx64,
356                 __FUNCTION__, symbolfile_addr);
357 
358       JITObjectMap::iterator it = m_jit_objects.find(symbolfile_addr);
359       if (it != m_jit_objects.end()) {
360         module_sp = it->second;
361         ObjectFile *image_object_file = module_sp->GetObjectFile();
362         if (image_object_file) {
363           const SectionList *section_list = image_object_file->GetSectionList();
364           if (section_list) {
365             const uint32_t num_sections = section_list->GetSize();
366             for (uint32_t i = 0; i < num_sections; ++i) {
367               SectionSP section_sp(section_list->GetSectionAtIndex(i));
368               if (section_sp) {
369                 target.GetSectionLoadList().SetSectionUnloaded(section_sp);
370               }
371             }
372           }
373         }
374         module_list.Remove(module_sp);
375         m_jit_objects.erase(it);
376       }
377     } else if (jit_action == JIT_NOACTION) {
378       // Nothing to do
379     } else {
380       assert(false && "Unknown jit action");
381     }
382 
383     if (all_entries)
384       jit_relevant_entry = (addr_t)jit_entry.next_entry;
385     else
386       jit_relevant_entry = 0;
387   }
388 
389   return false; // Continue Running.
390 }
391 
392 // PluginInterface protocol
393 lldb_private::ConstString JITLoaderGDB::GetPluginNameStatic() {
394   static ConstString g_name("gdb");
395   return g_name;
396 }
397 
398 JITLoaderSP JITLoaderGDB::CreateInstance(Process *process, bool force) {
399   JITLoaderSP jit_loader_sp;
400   bool enable;
401   switch (GetGlobalPluginProperties()->GetEnable()) {
402     case EnableJITLoaderGDB::eEnableJITLoaderGDBOn:
403       enable = true;
404       break;
405     case EnableJITLoaderGDB::eEnableJITLoaderGDBOff:
406       enable = false;
407       break;
408     case EnableJITLoaderGDB::eEnableJITLoaderGDBDefault:
409       ArchSpec arch(process->GetTarget().GetArchitecture());
410       enable = arch.GetTriple().getVendor() != llvm::Triple::Apple;
411       break;
412   }
413   if (enable)
414     jit_loader_sp = std::make_shared<JITLoaderGDB>(process);
415   return jit_loader_sp;
416 }
417 
418 const char *JITLoaderGDB::GetPluginDescriptionStatic() {
419   return "JIT loader plug-in that watches for JIT events using the GDB "
420          "interface.";
421 }
422 
423 lldb_private::ConstString JITLoaderGDB::GetPluginName() {
424   return GetPluginNameStatic();
425 }
426 
427 uint32_t JITLoaderGDB::GetPluginVersion() { return 1; }
428 
429 void JITLoaderGDB::Initialize() {
430   PluginManager::RegisterPlugin(GetPluginNameStatic(),
431                                 GetPluginDescriptionStatic(), CreateInstance,
432                                 DebuggerInitialize);
433 }
434 
435 void JITLoaderGDB::Terminate() {
436   PluginManager::UnregisterPlugin(CreateInstance);
437 }
438 
439 bool JITLoaderGDB::DidSetJITBreakpoint() const {
440   return LLDB_BREAK_ID_IS_VALID(m_jit_break_id);
441 }
442 
443 addr_t JITLoaderGDB::GetSymbolAddress(ModuleList &module_list,
444                                       ConstString name,
445                                       SymbolType symbol_type) const {
446   SymbolContextList target_symbols;
447   Target &target = m_process->GetTarget();
448 
449   if (!module_list.FindSymbolsWithNameAndType(name, symbol_type,
450                                               target_symbols))
451     return LLDB_INVALID_ADDRESS;
452 
453   SymbolContext sym_ctx;
454   target_symbols.GetContextAtIndex(0, sym_ctx);
455 
456   const Address jit_descriptor_addr = sym_ctx.symbol->GetAddress();
457   if (!jit_descriptor_addr.IsValid())
458     return LLDB_INVALID_ADDRESS;
459 
460   const addr_t jit_addr = jit_descriptor_addr.GetLoadAddress(&target);
461   return jit_addr;
462 }
463