LLDB mainline
JITLoaderGDB.cpp
Go to the documentation of this file.
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"
12#include "lldb/Core/Module.h"
15#include "lldb/Core/Section.h"
18#include "lldb/Symbol/Symbol.h"
21#include "lldb/Target/Process.h"
23#include "lldb/Target/Target.h"
27#include "lldb/Utility/Log.h"
29#include "llvm/Support/MathExtras.h"
30
31#include <memory>
32
33using namespace lldb;
34using namespace lldb_private;
35
37
38namespace {
39// Debug Interface Structures
40enum jit_actions_t { JIT_NOACTION = 0, JIT_REGISTER_FN, JIT_UNREGISTER_FN };
41
42template <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
49template <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
56enum EnableJITLoaderGDB {
57 eEnableJITLoaderGDBDefault,
58 eEnableJITLoaderGDBOn,
59 eEnableJITLoaderGDBOff,
60};
61
62static constexpr OptionEnumValueElement g_enable_jit_loader_gdb_enumerators[] =
63 {
64 {
65 eEnableJITLoaderGDBDefault,
66 "default",
67 "Enable JIT compilation interface for all platforms except macOS",
68 },
69 {
70 eEnableJITLoaderGDBOn,
71 "on",
72 "Enable JIT compilation interface",
73 },
74 {
75 eEnableJITLoaderGDBOff,
76 "off",
77 "Disable JIT compilation interface",
78 },
79};
80
81#define LLDB_PROPERTIES_jitloadergdb
82#include "JITLoaderGDBProperties.inc"
83
84enum {
85#define LLDB_PROPERTIES_jitloadergdb
86#include "JITLoaderGDBPropertiesEnum.inc"
87 ePropertyEnableJITBreakpoint
88};
89
90class PluginProperties : public Properties {
91public:
92 static llvm::StringRef GetSettingName() {
94 }
95
96 PluginProperties() {
97 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
98 m_collection_sp->Initialize(g_jitloadergdb_properties);
99 }
100
101 EnableJITLoaderGDB GetEnable() const {
102 return GetPropertyAtIndexAs<EnableJITLoaderGDB>(
103 ePropertyEnable,
104 static_cast<EnableJITLoaderGDB>(
105 g_jitloadergdb_properties[ePropertyEnable].default_uint_value));
106 }
107};
108} // namespace
109
110static PluginProperties &GetGlobalPluginProperties() {
111 static PluginProperties g_settings;
112 return g_settings;
113}
114
115template <typename ptr_t>
116static bool ReadJITEntry(const addr_t from_addr, Process *process,
117 jit_code_entry<ptr_t> *entry) {
118 lldbassert(from_addr % sizeof(ptr_t) == 0);
119
120 ArchSpec::Core core = process->GetTarget().GetArchitecture().GetCore();
121 bool i386_target = ArchSpec::kCore_x86_32_first <= core &&
123 uint8_t uint64_align_bytes = i386_target ? 4 : 8;
124 const size_t data_byte_size =
125 llvm::alignTo(sizeof(ptr_t) * 3, uint64_align_bytes) + sizeof(uint64_t);
126
128 DataBufferHeap data(data_byte_size, 0);
129 size_t bytes_read = process->ReadMemory(from_addr, data.GetBytes(),
130 data.GetByteSize(), error);
131 if (bytes_read != data_byte_size || !error.Success())
132 return false;
133
134 DataExtractor extractor(data.GetBytes(), data.GetByteSize(),
135 process->GetByteOrder(), sizeof(ptr_t));
136 lldb::offset_t offset = 0;
137 entry->next_entry = extractor.GetAddress(&offset);
138 entry->prev_entry = extractor.GetAddress(&offset);
139 entry->symfile_addr = extractor.GetAddress(&offset);
140 offset = llvm::alignTo(offset, uint64_align_bytes);
141 entry->symfile_size = extractor.GetU64(&offset);
142
143 return true;
144}
145
147 : JITLoader(process), m_jit_objects(),
148 m_jit_break_id(LLDB_INVALID_BREAK_ID),
149 m_jit_descriptor_addr(LLDB_INVALID_ADDRESS) {}
150
154}
155
158 debugger, PluginProperties::GetSettingName())) {
159 const bool is_global_setting = true;
161 debugger, GetGlobalPluginProperties().GetValueProperties(),
162 "Properties for the JIT LoaderGDB plug-in.", is_global_setting);
163 }
164}
165
167 Target &target = m_process->GetTarget();
168 ModuleList &module_list = target.GetImages();
169 SetJITBreakpoint(module_list);
170}
171
173 Target &target = m_process->GetTarget();
174 ModuleList &module_list = target.GetImages();
175 SetJITBreakpoint(module_list);
176}
177
180 SetJITBreakpoint(module_list);
181}
182
183// Setup the JIT Breakpoint
186 return;
187
188 Log *log = GetLog(LLDBLog::JITLoader);
189 LLDB_LOGF(log, "JITLoaderGDB::%s looking for JIT register hook",
190 __FUNCTION__);
191
192 addr_t jit_addr = GetSymbolAddress(
193 module_list, ConstString("__jit_debug_register_code"), eSymbolTypeCode);
194 if (jit_addr == LLDB_INVALID_ADDRESS)
195 return;
196
198 module_list, ConstString("__jit_debug_descriptor"), eSymbolTypeData);
200 LLDB_LOGF(log, "JITLoaderGDB::%s failed to find JIT descriptor address",
201 __FUNCTION__);
202 return;
203 }
204
205 LLDB_LOGF(log, "JITLoaderGDB::%s setting JIT breakpoint", __FUNCTION__);
206
207 Breakpoint *bp =
208 m_process->GetTarget().CreateBreakpoint(jit_addr, true, false).get();
209 bp->SetCallback(JITDebugBreakpointHit, this, true);
210 bp->SetBreakpointKind("jit-debug-register");
211 m_jit_break_id = bp->GetID();
212
213 ReadJITDescriptor(true);
214}
215
218 user_id_t break_id,
219 user_id_t break_loc_id) {
220 Log *log = GetLog(LLDBLog::JITLoader);
221 LLDB_LOGF(log, "JITLoaderGDB::%s hit JIT breakpoint", __FUNCTION__);
222 JITLoaderGDB *instance = static_cast<JITLoaderGDB *>(baton);
223 return instance->ReadJITDescriptor(false);
224}
225
226static void updateSectionLoadAddress(const SectionList &section_list,
227 Target &target, uint64_t symbolfile_addr,
228 uint64_t symbolfile_size,
229 uint64_t &vmaddrheuristic,
230 uint64_t &min_addr, uint64_t &max_addr) {
231 const uint32_t num_sections = section_list.GetSize();
232 for (uint32_t i = 0; i < num_sections; ++i) {
233 SectionSP section_sp(section_list.GetSectionAtIndex(i));
234 if (section_sp) {
235 if (section_sp->IsFake()) {
236 uint64_t lower = (uint64_t)-1;
237 uint64_t upper = 0;
238 updateSectionLoadAddress(section_sp->GetChildren(), target,
239 symbolfile_addr, symbolfile_size,
240 vmaddrheuristic, lower, upper);
241 if (lower < min_addr)
242 min_addr = lower;
243 if (upper > max_addr)
244 max_addr = upper;
245 const lldb::addr_t slide_amount = lower - section_sp->GetFileAddress();
246 section_sp->Slide(slide_amount, false);
247 section_sp->GetChildren().Slide(-slide_amount, false);
248 section_sp->SetByteSize(upper - lower);
249 } else {
250 vmaddrheuristic += 2 << section_sp->GetLog2Align();
251 uint64_t lower;
252 if (section_sp->GetFileAddress() > vmaddrheuristic)
253 lower = section_sp->GetFileAddress();
254 else {
255 lower = symbolfile_addr + section_sp->GetFileOffset();
256 section_sp->SetFileAddress(symbolfile_addr +
257 section_sp->GetFileOffset());
258 }
259 target.SetSectionLoadAddress(section_sp, lower, true);
260 uint64_t upper = lower + section_sp->GetByteSize();
261 if (lower < min_addr)
262 min_addr = lower;
263 if (upper > max_addr)
264 max_addr = upper;
265 // This is an upper bound, but a good enough heuristic
266 vmaddrheuristic += section_sp->GetByteSize();
267 }
268 }
269 }
270}
271
272bool JITLoaderGDB::ReadJITDescriptor(bool all_entries) {
274 return ReadJITDescriptorImpl<uint64_t>(all_entries);
275 else
276 return ReadJITDescriptorImpl<uint32_t>(all_entries);
277}
278
279template <typename ptr_t>
282 return false;
283
284 Log *log = GetLog(LLDBLog::JITLoader);
285 Target &target = m_process->GetTarget();
286 ModuleList &module_list = target.GetImages();
287
288 jit_descriptor<ptr_t> jit_desc;
289 const size_t jit_desc_size = sizeof(jit_desc);
291 size_t bytes_read = m_process->ReadMemory(m_jit_descriptor_addr, &jit_desc,
292 jit_desc_size, error);
293 if (bytes_read != jit_desc_size || !error.Success()) {
294 LLDB_LOGF(log, "JITLoaderGDB::%s failed to read JIT descriptor",
295 __FUNCTION__);
296 return false;
297 }
298
299 jit_actions_t jit_action = (jit_actions_t)jit_desc.action_flag;
300 addr_t jit_relevant_entry = (addr_t)jit_desc.relevant_entry;
301 if (all_entries) {
302 jit_action = JIT_REGISTER_FN;
303 jit_relevant_entry = (addr_t)jit_desc.first_entry;
304 }
305
306 while (jit_relevant_entry != 0) {
307 jit_code_entry<ptr_t> jit_entry;
308 if (!ReadJITEntry(jit_relevant_entry, m_process, &jit_entry)) {
309 LLDB_LOGF(log, "JITLoaderGDB::%s failed to read JIT entry at 0x%" PRIx64,
310 __FUNCTION__, jit_relevant_entry);
311 return false;
312 }
313
314 const addr_t &symbolfile_addr = (addr_t)jit_entry.symfile_addr;
315 const size_t &symbolfile_size = (size_t)jit_entry.symfile_size;
316 ModuleSP module_sp;
317
318 if (jit_action == JIT_REGISTER_FN) {
319 LLDB_LOGF(log,
320 "JITLoaderGDB::%s registering JIT entry at 0x%" PRIx64
321 " (%" PRIu64 " bytes)",
322 __FUNCTION__, symbolfile_addr, (uint64_t)symbolfile_size);
323
324 char jit_name[64];
325 snprintf(jit_name, 64, "JIT(0x%" PRIx64 ")", symbolfile_addr);
326 module_sp = m_process->ReadModuleFromMemory(
327 FileSpec(jit_name), symbolfile_addr, symbolfile_size);
328
329 if (module_sp && module_sp->GetObjectFile()) {
330 // Object formats (like ELF) have no representation for a JIT type.
331 // We will get it wrong, if we deduce it from the header.
332 module_sp->GetObjectFile()->SetType(ObjectFile::eTypeJIT);
333
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 (auto image_object_file =
339 llvm::dyn_cast<ObjectFileMachO>(module_sp->GetObjectFile())) {
340 const SectionList *section_list = image_object_file->GetSectionList();
341 if (section_list) {
342 uint64_t vmaddrheuristic = 0;
343 uint64_t lower = (uint64_t)-1;
344 uint64_t upper = 0;
345 updateSectionLoadAddress(*section_list, target, symbolfile_addr,
346 symbolfile_size, vmaddrheuristic, lower,
347 upper);
348 }
349 } else {
350 bool changed = false;
351 module_sp->SetLoadAddress(target, 0, true, changed);
352 }
353
354 module_list.AppendIfNeeded(module_sp);
355
356 ModuleList module_list;
357 module_list.Append(module_sp);
358 target.ModulesDidLoad(module_list);
359 } else {
360 LLDB_LOGF(log,
361 "JITLoaderGDB::%s failed to load module for "
362 "JIT entry at 0x%" PRIx64,
363 __FUNCTION__, symbolfile_addr);
364 }
365 } else if (jit_action == JIT_UNREGISTER_FN) {
366 LLDB_LOGF(log, "JITLoaderGDB::%s unregistering JIT entry at 0x%" PRIx64,
367 __FUNCTION__, symbolfile_addr);
368
369 JITObjectMap::iterator it = m_jit_objects.find(symbolfile_addr);
370 if (it != m_jit_objects.end()) {
371 module_sp = it->second;
372 ObjectFile *image_object_file = module_sp->GetObjectFile();
373 if (image_object_file) {
374 const SectionList *section_list = image_object_file->GetSectionList();
375 if (section_list) {
376 const uint32_t num_sections = section_list->GetSize();
377 for (uint32_t i = 0; i < num_sections; ++i) {
378 SectionSP section_sp(section_list->GetSectionAtIndex(i));
379 if (section_sp) {
380 target.GetSectionLoadList().SetSectionUnloaded(section_sp);
381 }
382 }
383 }
384 }
385 module_list.Remove(module_sp);
386 m_jit_objects.erase(it);
387 }
388 } else if (jit_action == JIT_NOACTION) {
389 // Nothing to do
390 } else {
391 assert(false && "Unknown jit action");
392 }
393
394 if (all_entries)
395 jit_relevant_entry = (addr_t)jit_entry.next_entry;
396 else
397 jit_relevant_entry = 0;
398 }
399
400 return false; // Continue Running.
401}
402
403// PluginInterface protocol
405 JITLoaderSP jit_loader_sp;
406 bool enable;
407 switch (GetGlobalPluginProperties().GetEnable()) {
408 case EnableJITLoaderGDB::eEnableJITLoaderGDBOn:
409 enable = true;
410 break;
411 case EnableJITLoaderGDB::eEnableJITLoaderGDBOff:
412 enable = false;
413 break;
414 case EnableJITLoaderGDB::eEnableJITLoaderGDBDefault:
415 ArchSpec arch(process->GetTarget().GetArchitecture());
416 enable = arch.GetTriple().getVendor() != llvm::Triple::Apple;
417 break;
418 }
419 if (enable)
420 jit_loader_sp = std::make_shared<JITLoaderGDB>(process);
421 return jit_loader_sp;
422}
423
425 return "JIT loader plug-in that watches for JIT events using the GDB "
426 "interface.";
427}
428
433}
434
437}
438
441}
442
444 ConstString name,
445 SymbolType symbol_type) const {
446 SymbolContextList target_symbols;
447 Target &target = m_process->GetTarget();
448
449 module_list.FindSymbolsWithNameAndType(name, symbol_type, target_symbols);
450 if (target_symbols.IsEmpty())
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())
459
460 const addr_t jit_addr = jit_descriptor_addr.GetLoadAddress(&target);
461 return jit_addr;
462}
static llvm::raw_ostream & error(Stream &strm)
static PluginProperties & GetGlobalPluginProperties()
static void updateSectionLoadAddress(const SectionList &section_list, Target &target, uint64_t symbolfile_addr, uint64_t symbolfile_size, uint64_t &vmaddrheuristic, uint64_t &min_addr, uint64_t &max_addr)
static bool ReadJITEntry(const addr_t from_addr, Process *process, jit_code_entry< ptr_t > *entry)
#define lldbassert(x)
Definition: LLDBAssert.h:15
#define LLDB_LOGF(log,...)
Definition: Log.h:349
#define LLDB_PLUGIN_DEFINE(PluginName)
Definition: PluginManager.h:31
JITObjectMap m_jit_objects
Definition: JITLoaderGDB.h:72
lldb::addr_t m_jit_descriptor_addr
Definition: JITLoaderGDB.h:75
JITLoaderGDB(lldb_private::Process *process)
lldb::addr_t GetSymbolAddress(lldb_private::ModuleList &module_list, lldb_private::ConstString name, lldb::SymbolType symbol_type) const
static void Terminate()
static void Initialize()
bool ReadJITDescriptor(bool all_entries)
~JITLoaderGDB() override
static lldb::JITLoaderSP CreateInstance(lldb_private::Process *process, bool force)
bool ReadJITDescriptorImpl(bool all_entries)
static void DebuggerInitialize(lldb_private::Debugger &debugger)
static llvm::StringRef GetPluginNameStatic()
Definition: JITLoaderGDB.h:28
static llvm::StringRef GetPluginDescriptionStatic()
bool DidSetJITBreakpoint() const
static bool JITDebugBreakpointHit(void *baton, lldb_private::StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
lldb::user_id_t m_jit_break_id
Definition: JITLoaderGDB.h:74
void DidLaunch() override
Called after launching a process.
void ModulesDidLoad(lldb_private::ModuleList &module_list) override
Called after a new shared object has been loaded so that it can be probed for JIT entry point hooks.
void DidAttach() override
Called after attaching a process.
void SetJITBreakpoint(lldb_private::ModuleList &module_list)
A section + offset based address class.
Definition: Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition: Address.cpp:313
bool IsValid() const
Check if the object state is valid.
Definition: Address.h:355
An architecture specification class.
Definition: ArchSpec.h:31
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition: ArchSpec.cpp:691
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition: ArchSpec.h:450
Core GetCore() const
Definition: ArchSpec.h:429
General Outline: A breakpoint has four main parts, a filter, a resolver, the list of breakpoint locat...
Definition: Breakpoint.h:81
void SetBreakpointKind(const char *kind)
Set the "kind" description for a breakpoint.
Definition: Breakpoint.h:452
void SetCallback(BreakpointHitCallback callback, void *baton, bool is_synchronous=false)
Set the callback action invoked when the breakpoint is hit.
Definition: Breakpoint.cpp:408
A uniqued constant string class.
Definition: ConstString.h:40
A subclass of DataBuffer that stores a data buffer on the heap.
lldb::offset_t GetByteSize() const override
Get the number of bytes in the data buffer.
An data extractor class.
Definition: DataExtractor.h:48
uint64_t GetU64(lldb::offset_t *offset_ptr) const
Extract a uint64_t value from *offset_ptr.
uint64_t GetAddress(lldb::offset_t *offset_ptr) const
Extract an address from *offset_ptr.
A class to manage flag bits.
Definition: Debugger.h:79
A file utility class.
Definition: FileSpec.h:56
A plug-in interface definition class for JIT loaders.
Definition: JITLoader.h:27
A collection class for Module objects.
Definition: ModuleList.h:103
bool AppendIfNeeded(const lldb::ModuleSP &new_module, bool notify=true)
Append a module to the module list, if it is not already there.
Definition: ModuleList.cpp:280
void FindSymbolsWithNameAndType(ConstString name, lldb::SymbolType symbol_type, SymbolContextList &sc_list) const
Definition: ModuleList.cpp:527
bool Remove(const lldb::ModuleSP &module_sp, bool notify=true)
Remove a module from the module list.
Definition: ModuleList.cpp:334
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
Definition: ModuleList.cpp:247
A plug-in interface definition class for object file parsers.
Definition: ObjectFile.h:44
@ eTypeJIT
JIT code that has symbols, sections and possibly debug info.
Definition: ObjectFile.h:65
virtual SectionList * GetSectionList(bool update_module_section_list=true)
Gets the section list for the currently selected architecture (and object for archives).
Definition: ObjectFile.cpp:590
static bool CreateSettingForJITLoaderPlugin(Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, llvm::StringRef description, bool is_global_property)
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static lldb::OptionValuePropertiesSP GetSettingForJITLoaderPlugin(Debugger &debugger, llvm::StringRef setting_name)
static bool UnregisterPlugin(ABICreateInstance create_callback)
A plug-in interface definition class for debugging a process.
Definition: Process.h:340
virtual size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition: Process.cpp:1938
lldb::ByteOrder GetByteOrder() const
Definition: Process.cpp:3399
virtual bool IsAlive()
Check if a process is still alive.
Definition: Process.cpp:1092
lldb::ModuleSP ReadModuleFromMemory(const FileSpec &file_spec, lldb::addr_t header_addr, size_t size_to_read=512)
Definition: Process.cpp:2387
Target & GetTarget()
Get the target object pointer for this module.
Definition: Process.h:1276
size_t GetSize() const
Definition: Section.h:75
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition: Section.cpp:544
bool SetSectionUnloaded(const lldb::SectionSP &section_sp, lldb::addr_t load_addr)
An error handling class.
Definition: Status.h:44
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
lldb::break_id_t GetID() const
Definition: Stoppoint.cpp:22
Defines a list of symbol context objects.
bool GetContextAtIndex(size_t idx, SymbolContext &sc) const
Get accessor for a symbol context at index idx.
Defines a symbol context baton that can be handed other debug core functions.
Definition: SymbolContext.h:34
Symbol * symbol
The Symbol for a given query.
Address GetAddress() const
Definition: Symbol.h:88
void ModulesDidLoad(ModuleList &module_list)
Definition: Target.cpp:1690
SectionLoadList & GetSectionLoadList()
Definition: Target.h:1127
bool RemoveBreakpointByID(lldb::break_id_t break_id)
Definition: Target.cpp:1004
lldb::BreakpointSP CreateBreakpoint(const FileSpecList *containingModules, const FileSpec &file, uint32_t line_no, uint32_t column, lldb::addr_t offset, LazyBool check_inlines, LazyBool skip_prologue, bool internal, bool request_hardware, LazyBool move_to_nearest_code)
Definition: Target.cpp:395
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition: Target.h:972
const ArchSpec & GetArchitecture() const
Definition: Target.h:1014
bool SetSectionLoadAddress(const lldb::SectionSP &section, lldb::addr_t load_addr, bool warn_multiple=false)
Definition: Target.cpp:3121
uint8_t * GetBytes()
Get a pointer to the data.
Definition: DataBuffer.h:108
#define LLDB_INVALID_BREAK_ID
Definition: lldb-defines.h:37
#define LLDB_BREAK_ID_IS_VALID(bid)
Definition: lldb-defines.h:39
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:82
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:314
Definition: SBAddress.h:15
uint64_t offset_t
Definition: lldb-types.h:83
SymbolType
Symbol types.
uint64_t user_id_t
Definition: lldb-types.h:80
std::shared_ptr< lldb_private::Section > SectionSP
Definition: lldb-forward.h:406
uint64_t addr_t
Definition: lldb-types.h:79
std::shared_ptr< lldb_private::JITLoader > JITLoaderSP
Definition: lldb-forward.h:356
std::shared_ptr< lldb_private::Module > ModuleSP
Definition: lldb-forward.h:365