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