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