1 //===-- JITLoaderGDB.cpp ----------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 #include "llvm/Support/MathExtras.h"
14 #include "lldb/Breakpoint/Breakpoint.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/ModuleSpec.h"
17 #include "lldb/Core/PluginManager.h"
18 #include "lldb/Core/Section.h"
19 #include "lldb/Interpreter/OptionValueProperties.h"
20 #include "lldb/Symbol/ObjectFile.h"
21 #include "lldb/Symbol/Symbol.h"
22 #include "lldb/Symbol/SymbolContext.h"
23 #include "lldb/Symbol/SymbolVendor.h"
24 #include "lldb/Target/Process.h"
25 #include "lldb/Target/SectionLoadList.h"
26 #include "lldb/Target/Target.h"
27 #include "lldb/Utility/DataBufferHeap.h"
28 #include "lldb/Utility/LLDBAssert.h"
29 #include "lldb/Utility/Log.h"
30 #include "lldb/Utility/StreamString.h"
32 #include "JITLoaderGDB.h"
35 using namespace lldb_private;
37 //------------------------------------------------------------------
38 // Debug Interface Structures
39 //------------------------------------------------------------------
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;
53 template <typename ptr_t> struct jit_descriptor {
55 uint32_t action_flag; // Values are jit_action_t
56 ptr_t relevant_entry; // pointer
57 ptr_t first_entry; // pointer
62 PropertyDefinition g_properties[] = {
63 {"enable-jit-breakpoint", OptionValue::eTypeBoolean, true, true, nullptr,
64 nullptr, "Enable breakpoint on __jit_debug_register_code."},
65 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
67 enum { ePropertyEnableJITBreakpoint };
69 class PluginProperties : public Properties {
71 static ConstString GetSettingName() {
72 return JITLoaderGDB::GetPluginNameStatic();
76 m_collection_sp.reset(new OptionValueProperties(GetSettingName()));
77 m_collection_sp->Initialize(g_properties);
80 bool GetEnableJITBreakpoint() const {
81 return m_collection_sp->GetPropertyAtIndexAsBoolean(
82 nullptr, ePropertyEnableJITBreakpoint,
83 g_properties[ePropertyEnableJITBreakpoint].default_uint_value != 0);
87 typedef std::shared_ptr<PluginProperties> JITLoaderGDBPropertiesSP;
89 static const JITLoaderGDBPropertiesSP &GetGlobalPluginProperties() {
90 static const auto g_settings_sp(std::make_shared<PluginProperties>());
94 template <typename ptr_t>
95 bool ReadJITEntry(const addr_t from_addr, Process *process,
96 jit_code_entry<ptr_t> *entry) {
97 lldbassert(from_addr % sizeof(ptr_t) == 0);
99 ArchSpec::Core core = process->GetTarget().GetArchitecture().GetCore();
100 bool i386_target = ArchSpec::kCore_x86_32_first <= core &&
101 core <= ArchSpec::kCore_x86_32_last;
102 uint8_t uint64_align_bytes = i386_target ? 4 : 8;
103 const size_t data_byte_size =
104 llvm::alignTo(sizeof(ptr_t) * 3, uint64_align_bytes) + sizeof(uint64_t);
107 DataBufferHeap data(data_byte_size, 0);
108 size_t bytes_read = process->ReadMemory(from_addr, data.GetBytes(),
109 data.GetByteSize(), error);
110 if (bytes_read != data_byte_size || !error.Success())
113 DataExtractor extractor(data.GetBytes(), data.GetByteSize(),
114 process->GetByteOrder(), sizeof(ptr_t));
115 lldb::offset_t offset = 0;
116 entry->next_entry = extractor.GetPointer(&offset);
117 entry->prev_entry = extractor.GetPointer(&offset);
118 entry->symfile_addr = extractor.GetPointer(&offset);
119 offset = llvm::alignTo(offset, uint64_align_bytes);
120 entry->symfile_size = extractor.GetU64(&offset);
125 } // anonymous namespace end
127 JITLoaderGDB::JITLoaderGDB(lldb_private::Process *process)
128 : JITLoader(process), m_jit_objects(),
129 m_jit_break_id(LLDB_INVALID_BREAK_ID),
130 m_jit_descriptor_addr(LLDB_INVALID_ADDRESS) {}
132 JITLoaderGDB::~JITLoaderGDB() {
133 if (LLDB_BREAK_ID_IS_VALID(m_jit_break_id))
134 m_process->GetTarget().RemoveBreakpointByID(m_jit_break_id);
137 void JITLoaderGDB::DebuggerInitialize(Debugger &debugger) {
138 if (!PluginManager::GetSettingForJITLoaderPlugin(
139 debugger, PluginProperties::GetSettingName())) {
140 const bool is_global_setting = true;
141 PluginManager::CreateSettingForJITLoaderPlugin(
142 debugger, GetGlobalPluginProperties()->GetValueProperties(),
143 ConstString("Properties for the JIT LoaderGDB plug-in."),
148 void JITLoaderGDB::DidAttach() {
149 Target &target = m_process->GetTarget();
150 ModuleList &module_list = target.GetImages();
151 SetJITBreakpoint(module_list);
154 void JITLoaderGDB::DidLaunch() {
155 Target &target = m_process->GetTarget();
156 ModuleList &module_list = target.GetImages();
157 SetJITBreakpoint(module_list);
160 void JITLoaderGDB::ModulesDidLoad(ModuleList &module_list) {
161 if (!DidSetJITBreakpoint() && m_process->IsAlive())
162 SetJITBreakpoint(module_list);
165 //------------------------------------------------------------------
166 // Setup the JIT Breakpoint
167 //------------------------------------------------------------------
168 void JITLoaderGDB::SetJITBreakpoint(lldb_private::ModuleList &module_list) {
169 if (!GetGlobalPluginProperties()->GetEnableJITBreakpoint())
172 if (DidSetJITBreakpoint())
175 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_JIT_LOADER));
177 log->Printf("JITLoaderGDB::%s looking for JIT register hook", __FUNCTION__);
179 addr_t jit_addr = GetSymbolAddress(
180 module_list, ConstString("__jit_debug_register_code"), eSymbolTypeAny);
181 if (jit_addr == LLDB_INVALID_ADDRESS)
184 m_jit_descriptor_addr = GetSymbolAddress(
185 module_list, ConstString("__jit_debug_descriptor"), eSymbolTypeData);
186 if (m_jit_descriptor_addr == LLDB_INVALID_ADDRESS) {
188 log->Printf("JITLoaderGDB::%s failed to find JIT descriptor address",
194 log->Printf("JITLoaderGDB::%s setting JIT breakpoint", __FUNCTION__);
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();
202 ReadJITDescriptor(true);
205 bool JITLoaderGDB::JITDebugBreakpointHit(void *baton,
206 StoppointCallbackContext *context,
208 user_id_t break_loc_id) {
209 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_JIT_LOADER));
211 log->Printf("JITLoaderGDB::%s hit JIT breakpoint", __FUNCTION__);
212 JITLoaderGDB *instance = static_cast<JITLoaderGDB *>(baton);
213 return instance->ReadJITDescriptor(false);
216 static void updateSectionLoadAddress(const SectionList §ion_list,
217 Target &target, uint64_t symbolfile_addr,
218 uint64_t symbolfile_size,
219 uint64_t &vmaddrheuristic,
220 uint64_t &min_addr, uint64_t &max_addr) {
221 const uint32_t num_sections = section_list.GetSize();
222 for (uint32_t i = 0; i < num_sections; ++i) {
223 SectionSP section_sp(section_list.GetSectionAtIndex(i));
225 if (section_sp->IsFake()) {
226 uint64_t lower = (uint64_t)-1;
228 updateSectionLoadAddress(section_sp->GetChildren(), target,
229 symbolfile_addr, symbolfile_size,
230 vmaddrheuristic, lower, upper);
231 if (lower < min_addr)
233 if (upper > max_addr)
235 const lldb::addr_t slide_amount = lower - section_sp->GetFileAddress();
236 section_sp->Slide(slide_amount, false);
237 section_sp->GetChildren().Slide(-slide_amount, false);
238 section_sp->SetByteSize(upper - lower);
240 vmaddrheuristic += 2 << section_sp->GetLog2Align();
242 if (section_sp->GetFileAddress() > vmaddrheuristic)
243 lower = section_sp->GetFileAddress();
245 lower = symbolfile_addr + section_sp->GetFileOffset();
246 section_sp->SetFileAddress(symbolfile_addr +
247 section_sp->GetFileOffset());
249 target.SetSectionLoadAddress(section_sp, lower, true);
250 uint64_t upper = lower + section_sp->GetByteSize();
251 if (lower < min_addr)
253 if (upper > max_addr)
255 // This is an upper bound, but a good enough heuristic
256 vmaddrheuristic += section_sp->GetByteSize();
262 bool JITLoaderGDB::ReadJITDescriptor(bool all_entries) {
263 if (m_process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
264 return ReadJITDescriptorImpl<uint64_t>(all_entries);
266 return ReadJITDescriptorImpl<uint32_t>(all_entries);
269 template <typename ptr_t>
270 bool JITLoaderGDB::ReadJITDescriptorImpl(bool all_entries) {
271 if (m_jit_descriptor_addr == LLDB_INVALID_ADDRESS)
274 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_JIT_LOADER));
275 Target &target = m_process->GetTarget();
276 ModuleList &module_list = target.GetImages();
278 jit_descriptor<ptr_t> jit_desc;
279 const size_t jit_desc_size = sizeof(jit_desc);
281 size_t bytes_read = m_process->DoReadMemory(m_jit_descriptor_addr, &jit_desc,
282 jit_desc_size, error);
283 if (bytes_read != jit_desc_size || !error.Success()) {
285 log->Printf("JITLoaderGDB::%s failed to read JIT descriptor",
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;
293 jit_action = JIT_REGISTER_FN;
294 jit_relevant_entry = (addr_t)jit_desc.first_entry;
297 while (jit_relevant_entry != 0) {
298 jit_code_entry<ptr_t> jit_entry;
299 if (!ReadJITEntry(jit_relevant_entry, m_process, &jit_entry)) {
301 log->Printf("JITLoaderGDB::%s failed to read JIT entry at 0x%" PRIx64,
302 __FUNCTION__, jit_relevant_entry);
306 const addr_t &symbolfile_addr = (addr_t)jit_entry.symfile_addr;
307 const size_t &symbolfile_size = (size_t)jit_entry.symfile_size;
310 if (jit_action == JIT_REGISTER_FN) {
312 log->Printf("JITLoaderGDB::%s registering JIT entry at 0x%" PRIx64
313 " (%" PRIu64 " bytes)",
314 __FUNCTION__, symbolfile_addr, (uint64_t)symbolfile_size);
317 snprintf(jit_name, 64, "JIT(0x%" PRIx64 ")", symbolfile_addr);
318 module_sp = m_process->ReadModuleFromMemory(
319 FileSpec(jit_name, false), symbolfile_addr, symbolfile_size);
321 if (module_sp && module_sp->GetObjectFile()) {
322 // load the symbol table right away
323 module_sp->GetObjectFile()->GetSymtab();
325 m_jit_objects.insert(std::make_pair(symbolfile_addr, module_sp));
326 if (module_sp->GetObjectFile()->GetPluginName() ==
327 ConstString("mach-o")) {
328 ObjectFile *image_object_file = module_sp->GetObjectFile();
329 if (image_object_file) {
330 const SectionList *section_list =
331 image_object_file->GetSectionList();
333 uint64_t vmaddrheuristic = 0;
334 uint64_t lower = (uint64_t)-1;
336 updateSectionLoadAddress(*section_list, target, symbolfile_addr,
337 symbolfile_size, vmaddrheuristic, lower,
342 bool changed = false;
343 module_sp->SetLoadAddress(target, 0, true, changed);
346 module_list.AppendIfNeeded(module_sp);
348 ModuleList module_list;
349 module_list.Append(module_sp);
350 target.ModulesDidLoad(module_list);
353 log->Printf("JITLoaderGDB::%s failed to load module for "
354 "JIT entry at 0x%" PRIx64,
355 __FUNCTION__, symbolfile_addr);
357 } else if (jit_action == JIT_UNREGISTER_FN) {
359 log->Printf("JITLoaderGDB::%s unregistering JIT entry at 0x%" PRIx64,
360 __FUNCTION__, symbolfile_addr);
362 JITObjectMap::iterator it = m_jit_objects.find(symbolfile_addr);
363 if (it != m_jit_objects.end()) {
364 module_sp = it->second;
365 ObjectFile *image_object_file = module_sp->GetObjectFile();
366 if (image_object_file) {
367 const SectionList *section_list = image_object_file->GetSectionList();
369 const uint32_t num_sections = section_list->GetSize();
370 for (uint32_t i = 0; i < num_sections; ++i) {
371 SectionSP section_sp(section_list->GetSectionAtIndex(i));
373 target.GetSectionLoadList().SetSectionUnloaded(section_sp);
378 module_list.Remove(module_sp);
379 m_jit_objects.erase(it);
381 } else if (jit_action == JIT_NOACTION) {
384 assert(false && "Unknown jit action");
388 jit_relevant_entry = (addr_t)jit_entry.next_entry;
390 jit_relevant_entry = 0;
393 return false; // Continue Running.
396 //------------------------------------------------------------------
397 // PluginInterface protocol
398 //------------------------------------------------------------------
399 lldb_private::ConstString JITLoaderGDB::GetPluginNameStatic() {
400 static ConstString g_name("gdb");
404 JITLoaderSP JITLoaderGDB::CreateInstance(Process *process, bool force) {
405 JITLoaderSP jit_loader_sp;
406 ArchSpec arch(process->GetTarget().GetArchitecture());
407 if (arch.GetTriple().getVendor() != llvm::Triple::Apple)
408 jit_loader_sp.reset(new JITLoaderGDB(process));
409 return jit_loader_sp;
412 const char *JITLoaderGDB::GetPluginDescriptionStatic() {
413 return "JIT loader plug-in that watches for JIT events using the GDB "
417 lldb_private::ConstString JITLoaderGDB::GetPluginName() {
418 return GetPluginNameStatic();
421 uint32_t JITLoaderGDB::GetPluginVersion() { return 1; }
423 void JITLoaderGDB::Initialize() {
424 PluginManager::RegisterPlugin(GetPluginNameStatic(),
425 GetPluginDescriptionStatic(), CreateInstance,
429 void JITLoaderGDB::Terminate() {
430 PluginManager::UnregisterPlugin(CreateInstance);
433 bool JITLoaderGDB::DidSetJITBreakpoint() const {
434 return LLDB_BREAK_ID_IS_VALID(m_jit_break_id);
437 addr_t JITLoaderGDB::GetSymbolAddress(ModuleList &module_list,
438 const ConstString &name,
439 SymbolType symbol_type) const {
440 SymbolContextList target_symbols;
441 Target &target = m_process->GetTarget();
443 if (!module_list.FindSymbolsWithNameAndType(name, symbol_type,
445 return LLDB_INVALID_ADDRESS;
447 SymbolContext sym_ctx;
448 target_symbols.GetContextAtIndex(0, sym_ctx);
450 const Address jit_descriptor_addr = sym_ctx.symbol->GetAddress();
451 if (!jit_descriptor_addr.IsValid())
452 return LLDB_INVALID_ADDRESS;
454 const addr_t jit_addr = jit_descriptor_addr.GetLoadAddress(&target);