1 //===-- SBDebugger.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 // Other libraries and framework includes
15 #include "SystemInitializerFull.h"
17 #include "lldb/API/SBDebugger.h"
19 #include "lldb/lldb-private.h"
21 #include "lldb/API/SBBroadcaster.h"
22 #include "lldb/API/SBCommandInterpreter.h"
23 #include "lldb/API/SBCommandReturnObject.h"
24 #include "lldb/API/SBError.h"
25 #include "lldb/API/SBEvent.h"
26 #include "lldb/API/SBFrame.h"
27 #include "lldb/API/SBListener.h"
28 #include "lldb/API/SBProcess.h"
29 #include "lldb/API/SBSourceManager.h"
30 #include "lldb/API/SBStream.h"
31 #include "lldb/API/SBStringList.h"
32 #include "lldb/API/SBStructuredData.h"
33 #include "lldb/API/SBTarget.h"
34 #include "lldb/API/SBThread.h"
35 #include "lldb/API/SBTypeCategory.h"
36 #include "lldb/API/SBTypeFilter.h"
37 #include "lldb/API/SBTypeFormat.h"
38 #include "lldb/API/SBTypeNameSpecifier.h"
39 #include "lldb/API/SBTypeSummary.h"
40 #include "lldb/API/SBTypeSynthetic.h"
42 #include "lldb/Core/Debugger.h"
43 #include "lldb/Core/PluginManager.h"
44 #include "lldb/Core/State.h"
45 #include "lldb/Core/StreamFile.h"
46 #include "lldb/Core/StructuredDataImpl.h"
47 #include "lldb/DataFormatters/DataVisualization.h"
48 #include "lldb/Host/XML.h"
49 #include "lldb/Initialization/SystemLifetimeManager.h"
50 #include "lldb/Interpreter/CommandInterpreter.h"
51 #include "lldb/Interpreter/OptionArgParser.h"
52 #include "lldb/Interpreter/OptionGroupPlatform.h"
53 #include "lldb/Target/Process.h"
54 #include "lldb/Target/TargetList.h"
55 #include "lldb/Utility/Args.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include "llvm/ADT/StringRef.h"
59 #include "llvm/Support/DynamicLibrary.h"
60 #include "llvm/Support/ManagedStatic.h"
63 using namespace lldb_private;
65 static llvm::sys::DynamicLibrary LoadPlugin(const lldb::DebuggerSP &debugger_sp,
68 llvm::sys::DynamicLibrary dynlib =
69 llvm::sys::DynamicLibrary::getPermanentLibrary(spec.GetPath().c_str());
70 if (dynlib.isValid()) {
71 typedef bool (*LLDBCommandPluginInit)(lldb::SBDebugger & debugger);
73 lldb::SBDebugger debugger_sb(debugger_sp);
74 // This calls the bool lldb::PluginInitialize(lldb::SBDebugger debugger)
76 // TODO: mangle this differently for your system - on OSX, the first
77 // underscore needs to be removed and the second one stays
78 LLDBCommandPluginInit init_func =
79 (LLDBCommandPluginInit)(uintptr_t)dynlib.getAddressOfSymbol(
80 "_ZN4lldb16PluginInitializeENS_10SBDebuggerE");
82 if (init_func(debugger_sb))
85 error.SetErrorString("plug-in refused to load "
86 "(lldb::PluginInitialize(lldb::SBDebugger) "
89 error.SetErrorString("plug-in is missing the required initialization: "
90 "lldb::PluginInitialize(lldb::SBDebugger)");
94 error.SetErrorString("this file does not represent a loadable dylib");
96 error.SetErrorString("no such file");
98 return llvm::sys::DynamicLibrary();
101 static llvm::ManagedStatic<SystemLifetimeManager> g_debugger_lifetime;
103 SBError SBInputReader::Initialize(
104 lldb::SBDebugger &sb_debugger,
105 unsigned long (*)(void *, lldb::SBInputReader *, lldb::InputReaderAction,
106 char const *, unsigned long),
107 void *, lldb::InputReaderGranularity, char const *, char const *, bool) {
111 void SBInputReader::SetIsDone(bool) {}
113 bool SBInputReader::IsActive() const { return false; }
115 SBDebugger::SBDebugger() = default;
117 SBDebugger::SBDebugger(const lldb::DebuggerSP &debugger_sp)
118 : m_opaque_sp(debugger_sp) {}
120 SBDebugger::SBDebugger(const SBDebugger &rhs) : m_opaque_sp(rhs.m_opaque_sp) {}
122 SBDebugger::~SBDebugger() = default;
124 SBDebugger &SBDebugger::operator=(const SBDebugger &rhs) {
126 m_opaque_sp = rhs.m_opaque_sp;
131 void SBDebugger::Initialize() {
132 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
135 log->Printf("SBDebugger::Initialize ()");
137 g_debugger_lifetime->Initialize(llvm::make_unique<SystemInitializerFull>(),
141 void SBDebugger::Terminate() { g_debugger_lifetime->Terminate(); }
143 void SBDebugger::Clear() {
144 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
147 log->Printf("SBDebugger(%p)::Clear ()",
148 static_cast<void *>(m_opaque_sp.get()));
151 m_opaque_sp->ClearIOHandlers();
156 SBDebugger SBDebugger::Create() {
157 return SBDebugger::Create(false, nullptr, nullptr);
160 SBDebugger SBDebugger::Create(bool source_init_files) {
161 return SBDebugger::Create(source_init_files, nullptr, nullptr);
164 SBDebugger SBDebugger::Create(bool source_init_files,
165 lldb::LogOutputCallback callback, void *baton)
168 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
172 // Currently we have issues if this function is called simultaneously on two
173 // different threads. The issues mainly revolve around the fact that the
174 // lldb_private::FormatManager uses global collections and having two threads
175 // parsing the .lldbinit files can cause mayhem. So to get around this for
176 // now we need to use a mutex to prevent bad things from happening.
177 static std::recursive_mutex g_mutex;
178 std::lock_guard<std::recursive_mutex> guard(g_mutex);
180 debugger.reset(Debugger::CreateInstance(callback, baton));
184 debugger.GetDescription(sstr);
185 log->Printf("SBDebugger::Create () => SBDebugger(%p): %s",
186 static_cast<void *>(debugger.m_opaque_sp.get()),
190 SBCommandInterpreter interp = debugger.GetCommandInterpreter();
191 if (source_init_files) {
192 interp.get()->SkipLLDBInitFiles(false);
193 interp.get()->SkipAppInitFiles(false);
194 SBCommandReturnObject result;
195 interp.SourceInitFileInHomeDirectory(result);
197 interp.get()->SkipLLDBInitFiles(true);
198 interp.get()->SkipAppInitFiles(true);
203 void SBDebugger::Destroy(SBDebugger &debugger) {
204 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
208 debugger.GetDescription(sstr);
209 log->Printf("SBDebugger::Destroy () => SBDebugger(%p): %s",
210 static_cast<void *>(debugger.m_opaque_sp.get()),
214 Debugger::Destroy(debugger.m_opaque_sp);
216 if (debugger.m_opaque_sp.get() != nullptr)
217 debugger.m_opaque_sp.reset();
220 void SBDebugger::MemoryPressureDetected() {
221 // Since this function can be call asynchronously, we allow it to be non-
222 // mandatory. We have seen deadlocks with this function when called so we
223 // need to safeguard against this until we can determine what is causing the
225 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
227 const bool mandatory = false;
229 log->Printf("SBDebugger::MemoryPressureDetected (), mandatory = %d",
233 ModuleList::RemoveOrphanSharedModules(mandatory);
236 bool SBDebugger::IsValid() const { return m_opaque_sp.get() != nullptr; }
238 void SBDebugger::SetAsync(bool b) {
240 m_opaque_sp->SetAsyncExecution(b);
243 bool SBDebugger::GetAsync() {
244 return (m_opaque_sp ? m_opaque_sp->GetAsyncExecution() : false);
247 void SBDebugger::SkipLLDBInitFiles(bool b) {
249 m_opaque_sp->GetCommandInterpreter().SkipLLDBInitFiles(b);
252 void SBDebugger::SkipAppInitFiles(bool b) {
254 m_opaque_sp->GetCommandInterpreter().SkipAppInitFiles(b);
257 // Shouldn't really be settable after initialization as this could cause lots
258 // of problems; don't want users trying to switch modes in the middle of a
259 // debugging session.
260 void SBDebugger::SetInputFileHandle(FILE *fh, bool transfer_ownership) {
261 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
265 "SBDebugger(%p)::SetInputFileHandle (fh=%p, transfer_ownership=%i)",
266 static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(fh),
270 m_opaque_sp->SetInputFileHandle(fh, transfer_ownership);
273 void SBDebugger::SetOutputFileHandle(FILE *fh, bool transfer_ownership) {
274 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
278 "SBDebugger(%p)::SetOutputFileHandle (fh=%p, transfer_ownership=%i)",
279 static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(fh),
283 m_opaque_sp->SetOutputFileHandle(fh, transfer_ownership);
286 void SBDebugger::SetErrorFileHandle(FILE *fh, bool transfer_ownership) {
287 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
291 "SBDebugger(%p)::SetErrorFileHandle (fh=%p, transfer_ownership=%i)",
292 static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(fh),
296 m_opaque_sp->SetErrorFileHandle(fh, transfer_ownership);
299 FILE *SBDebugger::GetInputFileHandle() {
301 StreamFileSP stream_file_sp(m_opaque_sp->GetInputFile());
303 return stream_file_sp->GetFile().GetStream();
308 FILE *SBDebugger::GetOutputFileHandle() {
310 StreamFileSP stream_file_sp(m_opaque_sp->GetOutputFile());
312 return stream_file_sp->GetFile().GetStream();
317 FILE *SBDebugger::GetErrorFileHandle() {
319 StreamFileSP stream_file_sp(m_opaque_sp->GetErrorFile());
321 return stream_file_sp->GetFile().GetStream();
326 void SBDebugger::SaveInputTerminalState() {
328 m_opaque_sp->SaveInputTerminalState();
331 void SBDebugger::RestoreInputTerminalState() {
333 m_opaque_sp->RestoreInputTerminalState();
335 SBCommandInterpreter SBDebugger::GetCommandInterpreter() {
336 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
338 SBCommandInterpreter sb_interpreter;
340 sb_interpreter.reset(&m_opaque_sp->GetCommandInterpreter());
344 "SBDebugger(%p)::GetCommandInterpreter () => SBCommandInterpreter(%p)",
345 static_cast<void *>(m_opaque_sp.get()),
346 static_cast<void *>(sb_interpreter.get()));
348 return sb_interpreter;
351 void SBDebugger::HandleCommand(const char *command) {
353 TargetSP target_sp(m_opaque_sp->GetSelectedTarget());
354 std::unique_lock<std::recursive_mutex> lock;
356 lock = std::unique_lock<std::recursive_mutex>(target_sp->GetAPIMutex());
358 SBCommandInterpreter sb_interpreter(GetCommandInterpreter());
359 SBCommandReturnObject result;
361 sb_interpreter.HandleCommand(command, result, false);
363 if (GetErrorFileHandle() != nullptr)
364 result.PutError(GetErrorFileHandle());
365 if (GetOutputFileHandle() != nullptr)
366 result.PutOutput(GetOutputFileHandle());
368 if (!m_opaque_sp->GetAsyncExecution()) {
369 SBProcess process(GetCommandInterpreter().GetProcess());
370 ProcessSP process_sp(process.GetSP());
373 ListenerSP lldb_listener_sp = m_opaque_sp->GetListener();
374 while (lldb_listener_sp->GetEventForBroadcaster(
375 process_sp.get(), event_sp, std::chrono::seconds(0))) {
376 SBEvent event(event_sp);
377 HandleProcessEvent(process, event, GetOutputFileHandle(),
378 GetErrorFileHandle());
385 SBListener SBDebugger::GetListener() {
386 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
388 SBListener sb_listener;
390 sb_listener.reset(m_opaque_sp->GetListener());
393 log->Printf("SBDebugger(%p)::GetListener () => SBListener(%p)",
394 static_cast<void *>(m_opaque_sp.get()),
395 static_cast<void *>(sb_listener.get()));
400 void SBDebugger::HandleProcessEvent(const SBProcess &process,
401 const SBEvent &event, FILE *out,
403 if (!process.IsValid())
406 TargetSP target_sp(process.GetTarget().GetSP());
410 const uint32_t event_type = event.GetType();
411 char stdio_buffer[1024];
414 std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
417 (Process::eBroadcastBitSTDOUT | Process::eBroadcastBitStateChanged)) {
418 // Drain stdout when we stop just in case we have any bytes
419 while ((len = process.GetSTDOUT(stdio_buffer, sizeof(stdio_buffer))) > 0)
421 ::fwrite(stdio_buffer, 1, len, out);
425 (Process::eBroadcastBitSTDERR | Process::eBroadcastBitStateChanged)) {
426 // Drain stderr when we stop just in case we have any bytes
427 while ((len = process.GetSTDERR(stdio_buffer, sizeof(stdio_buffer))) > 0)
429 ::fwrite(stdio_buffer, 1, len, err);
432 if (event_type & Process::eBroadcastBitStateChanged) {
433 StateType event_state = SBProcess::GetStateFromEvent(event);
435 if (event_state == eStateInvalid)
438 bool is_stopped = StateIsStoppedState(event_state);
440 process.ReportEventState(event, out);
444 SBSourceManager SBDebugger::GetSourceManager() {
445 SBSourceManager sb_source_manager(*this);
446 return sb_source_manager;
449 bool SBDebugger::GetDefaultArchitecture(char *arch_name, size_t arch_name_len) {
450 if (arch_name && arch_name_len) {
451 ArchSpec default_arch = Target::GetDefaultArchitecture();
453 if (default_arch.IsValid()) {
454 const std::string &triple_str = default_arch.GetTriple().str();
455 if (!triple_str.empty())
456 ::snprintf(arch_name, arch_name_len, "%s", triple_str.c_str());
458 ::snprintf(arch_name, arch_name_len, "%s",
459 default_arch.GetArchitectureName());
463 if (arch_name && arch_name_len)
468 bool SBDebugger::SetDefaultArchitecture(const char *arch_name) {
470 ArchSpec arch(arch_name);
471 if (arch.IsValid()) {
472 Target::SetDefaultArchitecture(arch);
480 SBDebugger::GetScriptingLanguage(const char *script_language_name) {
481 if (!script_language_name) return eScriptLanguageDefault;
482 return OptionArgParser::ToScriptLanguage(
483 llvm::StringRef(script_language_name), eScriptLanguageDefault, nullptr);
486 const char *SBDebugger::GetVersionString() {
487 return lldb_private::GetVersion();
490 const char *SBDebugger::StateAsCString(StateType state) {
491 return lldb_private::StateAsCString(state);
494 static void AddBoolConfigEntry(StructuredData::Dictionary &dict,
495 llvm::StringRef name, bool value,
496 llvm::StringRef description) {
497 auto entry_up = llvm::make_unique<StructuredData::Dictionary>();
498 entry_up->AddBooleanItem("value", value);
499 entry_up->AddStringItem("description", description);
500 dict.AddItem(name, std::move(entry_up));
503 static void AddLLVMTargets(StructuredData::Dictionary &dict) {
504 auto array_up = llvm::make_unique<StructuredData::Array>();
505 #define LLVM_TARGET(target) \
506 array_up->AddItem(llvm::make_unique<StructuredData::String>(#target));
507 #include "llvm/Config/Targets.def"
508 auto entry_up = llvm::make_unique<StructuredData::Dictionary>();
509 entry_up->AddItem("value", std::move(array_up));
510 entry_up->AddStringItem("description", "A list of configured LLVM targets.");
511 dict.AddItem("targets", std::move(entry_up));
514 SBStructuredData SBDebugger::GetBuildConfiguration() {
515 auto config_up = llvm::make_unique<StructuredData::Dictionary>();
517 *config_up, "xml", XMLDocument::XMLEnabled(),
518 "A boolean value that indicates if XML support is enabled in LLDB");
519 AddLLVMTargets(*config_up);
521 SBStructuredData data;
522 data.m_impl_up->SetObjectSP(std::move(config_up));
526 bool SBDebugger::StateIsRunningState(StateType state) {
527 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
529 const bool result = lldb_private::StateIsRunningState(state);
531 log->Printf("SBDebugger::StateIsRunningState (state=%s) => %i",
532 StateAsCString(state), result);
537 bool SBDebugger::StateIsStoppedState(StateType state) {
538 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
540 const bool result = lldb_private::StateIsStoppedState(state, false);
542 log->Printf("SBDebugger::StateIsStoppedState (state=%s) => %i",
543 StateAsCString(state), result);
548 lldb::SBTarget SBDebugger::CreateTarget(const char *filename,
549 const char *target_triple,
550 const char *platform_name,
551 bool add_dependent_modules,
552 lldb::SBError &sb_error) {
557 OptionGroupPlatform platform_options(false);
558 platform_options.SetPlatformName(platform_name);
560 sb_error.ref() = m_opaque_sp->GetTargetList().CreateTarget(
561 *m_opaque_sp, filename, target_triple, add_dependent_modules,
562 &platform_options, target_sp);
564 if (sb_error.Success())
565 sb_target.SetSP(target_sp);
567 sb_error.SetErrorString("invalid debugger");
570 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
572 log->Printf("SBDebugger(%p)::CreateTarget (filename=\"%s\", triple=%s, "
573 "platform_name=%s, add_dependent_modules=%u, error=%s) => "
575 static_cast<void *>(m_opaque_sp.get()), filename, target_triple,
576 platform_name, add_dependent_modules, sb_error.GetCString(),
577 static_cast<void *>(target_sp.get()));
583 SBDebugger::CreateTargetWithFileAndTargetTriple(const char *filename,
584 const char *target_triple) {
588 const bool add_dependent_modules = true;
589 Status error(m_opaque_sp->GetTargetList().CreateTarget(
590 *m_opaque_sp, filename, target_triple, add_dependent_modules, nullptr,
592 sb_target.SetSP(target_sp);
595 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
597 log->Printf("SBDebugger(%p)::CreateTargetWithFileAndTargetTriple "
598 "(filename=\"%s\", triple=%s) => SBTarget(%p)",
599 static_cast<void *>(m_opaque_sp.get()), filename, target_triple,
600 static_cast<void *>(target_sp.get()));
605 SBTarget SBDebugger::CreateTargetWithFileAndArch(const char *filename,
606 const char *arch_cstr) {
607 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
613 const bool add_dependent_modules = true;
615 error = m_opaque_sp->GetTargetList().CreateTarget(
616 *m_opaque_sp, filename, arch_cstr, add_dependent_modules, nullptr,
619 if (error.Success()) {
620 m_opaque_sp->GetTargetList().SetSelectedTarget(target_sp.get());
621 sb_target.SetSP(target_sp);
626 log->Printf("SBDebugger(%p)::CreateTargetWithFileAndArch (filename=\"%s\", "
627 "arch=%s) => SBTarget(%p)",
628 static_cast<void *>(m_opaque_sp.get()), filename, arch_cstr,
629 static_cast<void *>(target_sp.get()));
634 SBTarget SBDebugger::CreateTarget(const char *filename) {
639 const bool add_dependent_modules = true;
640 error = m_opaque_sp->GetTargetList().CreateTarget(
641 *m_opaque_sp, filename, "", add_dependent_modules, nullptr, target_sp);
643 if (error.Success()) {
644 m_opaque_sp->GetTargetList().SetSelectedTarget(target_sp.get());
645 sb_target.SetSP(target_sp);
648 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
651 "SBDebugger(%p)::CreateTarget (filename=\"%s\") => SBTarget(%p)",
652 static_cast<void *>(m_opaque_sp.get()), filename,
653 static_cast<void *>(target_sp.get()));
657 SBTarget SBDebugger::GetDummyTarget() {
660 sb_target.SetSP(m_opaque_sp->GetDummyTarget()->shared_from_this());
662 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
665 "SBDebugger(%p)::GetDummyTarget() => SBTarget(%p)",
666 static_cast<void *>(m_opaque_sp.get()),
667 static_cast<void *>(sb_target.GetSP().get()));
671 bool SBDebugger::DeleteTarget(lldb::SBTarget &target) {
674 TargetSP target_sp(target.GetSP());
676 // No need to lock, the target list is thread safe
677 result = m_opaque_sp->GetTargetList().DeleteTarget(target_sp);
678 target_sp->Destroy();
680 const bool mandatory = true;
681 ModuleList::RemoveOrphanSharedModules(mandatory);
685 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
687 log->Printf("SBDebugger(%p)::DeleteTarget (SBTarget(%p)) => %i",
688 static_cast<void *>(m_opaque_sp.get()),
689 static_cast<void *>(target.m_opaque_sp.get()), result);
694 SBTarget SBDebugger::GetTargetAtIndex(uint32_t idx) {
697 // No need to lock, the target list is thread safe
698 sb_target.SetSP(m_opaque_sp->GetTargetList().GetTargetAtIndex(idx));
703 uint32_t SBDebugger::GetIndexOfTarget(lldb::SBTarget target) {
705 lldb::TargetSP target_sp = target.GetSP();
712 return m_opaque_sp->GetTargetList().GetIndexOfTarget(target.GetSP());
715 SBTarget SBDebugger::FindTargetWithProcessID(lldb::pid_t pid) {
718 // No need to lock, the target list is thread safe
719 sb_target.SetSP(m_opaque_sp->GetTargetList().FindTargetWithProcessID(pid));
724 SBTarget SBDebugger::FindTargetWithFileAndArch(const char *filename,
725 const char *arch_name) {
727 if (m_opaque_sp && filename && filename[0]) {
728 // No need to lock, the target list is thread safe
729 ArchSpec arch = Platform::GetAugmentedArchSpec(
730 m_opaque_sp->GetPlatformList().GetSelectedPlatform().get(), arch_name);
732 m_opaque_sp->GetTargetList().FindTargetWithExecutableAndArchitecture(
733 FileSpec(filename, false), arch_name ? &arch : nullptr));
734 sb_target.SetSP(target_sp);
739 SBTarget SBDebugger::FindTargetWithLLDBProcess(const ProcessSP &process_sp) {
742 // No need to lock, the target list is thread safe
744 m_opaque_sp->GetTargetList().FindTargetWithProcess(process_sp.get()));
749 uint32_t SBDebugger::GetNumTargets() {
751 // No need to lock, the target list is thread safe
752 return m_opaque_sp->GetTargetList().GetNumTargets();
757 SBTarget SBDebugger::GetSelectedTarget() {
758 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
763 // No need to lock, the target list is thread safe
764 target_sp = m_opaque_sp->GetTargetList().GetSelectedTarget();
765 sb_target.SetSP(target_sp);
770 sb_target.GetDescription(sstr, eDescriptionLevelBrief);
771 log->Printf("SBDebugger(%p)::GetSelectedTarget () => SBTarget(%p): %s",
772 static_cast<void *>(m_opaque_sp.get()),
773 static_cast<void *>(target_sp.get()), sstr.GetData());
779 void SBDebugger::SetSelectedTarget(SBTarget &sb_target) {
780 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
782 TargetSP target_sp(sb_target.GetSP());
784 m_opaque_sp->GetTargetList().SetSelectedTarget(target_sp.get());
788 sb_target.GetDescription(sstr, eDescriptionLevelBrief);
789 log->Printf("SBDebugger(%p)::SetSelectedTarget () => SBTarget(%p): %s",
790 static_cast<void *>(m_opaque_sp.get()),
791 static_cast<void *>(target_sp.get()), sstr.GetData());
795 SBPlatform SBDebugger::GetSelectedPlatform() {
796 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
798 SBPlatform sb_platform;
799 DebuggerSP debugger_sp(m_opaque_sp);
801 sb_platform.SetSP(debugger_sp->GetPlatformList().GetSelectedPlatform());
804 log->Printf("SBDebugger(%p)::GetSelectedPlatform () => SBPlatform(%p): %s",
805 static_cast<void *>(m_opaque_sp.get()),
806 static_cast<void *>(sb_platform.GetSP().get()),
807 sb_platform.GetName());
811 void SBDebugger::SetSelectedPlatform(SBPlatform &sb_platform) {
812 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
814 DebuggerSP debugger_sp(m_opaque_sp);
816 debugger_sp->GetPlatformList().SetSelectedPlatform(sb_platform.GetSP());
820 log->Printf("SBDebugger(%p)::SetSelectedPlatform (SBPlatform(%p) %s)",
821 static_cast<void *>(m_opaque_sp.get()),
822 static_cast<void *>(sb_platform.GetSP().get()),
823 sb_platform.GetName());
826 uint32_t SBDebugger::GetNumPlatforms() {
828 // No need to lock, the platform list is thread safe
829 return m_opaque_sp->GetPlatformList().GetSize();
834 SBPlatform SBDebugger::GetPlatformAtIndex(uint32_t idx) {
835 SBPlatform sb_platform;
837 // No need to lock, the platform list is thread safe
838 sb_platform.SetSP(m_opaque_sp->GetPlatformList().GetAtIndex(idx));
843 uint32_t SBDebugger::GetNumAvailablePlatforms() {
846 if (!PluginManager::GetPlatformPluginNameAtIndex(idx)) {
851 // +1 for the host platform, which should always appear first in the list.
855 SBStructuredData SBDebugger::GetAvailablePlatformInfoAtIndex(uint32_t idx) {
856 SBStructuredData data;
857 auto platform_dict = llvm::make_unique<StructuredData::Dictionary>();
858 llvm::StringRef name_str("name"), desc_str("description");
861 PlatformSP host_platform_sp(Platform::GetHostPlatform());
862 platform_dict->AddStringItem(
863 name_str, host_platform_sp->GetPluginName().GetStringRef());
864 platform_dict->AddStringItem(
865 desc_str, llvm::StringRef(host_platform_sp->GetDescription()));
866 } else if (idx > 0) {
867 const char *plugin_name =
868 PluginManager::GetPlatformPluginNameAtIndex(idx - 1);
872 platform_dict->AddStringItem(name_str, llvm::StringRef(plugin_name));
874 const char *plugin_desc =
875 PluginManager::GetPlatformPluginDescriptionAtIndex(idx - 1);
879 platform_dict->AddStringItem(desc_str, llvm::StringRef(plugin_desc));
882 data.m_impl_up->SetObjectSP(
883 StructuredData::ObjectSP(platform_dict.release()));
887 void SBDebugger::DispatchInput(void *baton, const void *data, size_t data_len) {
888 DispatchInput(data, data_len);
891 void SBDebugger::DispatchInput(const void *data, size_t data_len) {
892 // Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API));
895 // log->Printf ("SBDebugger(%p)::DispatchInput (data=\"%.*s\",
896 // size_t=%" PRIu64 ")",
897 // m_opaque_sp.get(),
899 // (const char *) data,
900 // (uint64_t)data_len);
903 // m_opaque_sp->DispatchInput ((const char *) data, data_len);
906 void SBDebugger::DispatchInputInterrupt() {
908 m_opaque_sp->DispatchInputInterrupt();
911 void SBDebugger::DispatchInputEndOfFile() {
913 m_opaque_sp->DispatchInputEndOfFile();
916 void SBDebugger::PushInputReader(SBInputReader &reader) {}
918 void SBDebugger::RunCommandInterpreter(bool auto_handle_events,
921 CommandInterpreterRunOptions options;
923 m_opaque_sp->GetCommandInterpreter().RunCommandInterpreter(
924 auto_handle_events, spawn_thread, options);
928 void SBDebugger::RunCommandInterpreter(bool auto_handle_events,
930 SBCommandInterpreterRunOptions &options,
931 int &num_errors, bool &quit_requested,
932 bool &stopped_for_crash)
936 CommandInterpreter &interp = m_opaque_sp->GetCommandInterpreter();
937 interp.RunCommandInterpreter(auto_handle_events, spawn_thread,
939 num_errors = interp.GetNumErrors();
940 quit_requested = interp.GetQuitRequested();
941 stopped_for_crash = interp.GetStoppedForCrash();
945 SBError SBDebugger::RunREPL(lldb::LanguageType language,
946 const char *repl_options) {
949 error.ref() = m_opaque_sp->RunREPL(language, repl_options);
951 error.SetErrorString("invalid debugger");
955 void SBDebugger::reset(const DebuggerSP &debugger_sp) {
956 m_opaque_sp = debugger_sp;
959 Debugger *SBDebugger::get() const { return m_opaque_sp.get(); }
961 Debugger &SBDebugger::ref() const {
962 assert(m_opaque_sp.get());
966 const lldb::DebuggerSP &SBDebugger::get_sp() const { return m_opaque_sp; }
968 SBDebugger SBDebugger::FindDebuggerWithID(int id) {
969 // No need to lock, the debugger list is thread safe
970 SBDebugger sb_debugger;
971 DebuggerSP debugger_sp = Debugger::FindDebuggerWithID(id);
973 sb_debugger.reset(debugger_sp);
977 const char *SBDebugger::GetInstanceName() {
978 return (m_opaque_sp ? m_opaque_sp->GetInstanceName().AsCString() : nullptr);
981 SBError SBDebugger::SetInternalVariable(const char *var_name, const char *value,
982 const char *debugger_instance_name) {
984 DebuggerSP debugger_sp(Debugger::FindDebuggerWithInstanceName(
985 ConstString(debugger_instance_name)));
988 ExecutionContext exe_ctx(
989 debugger_sp->GetCommandInterpreter().GetExecutionContext());
990 error = debugger_sp->SetPropertyValue(&exe_ctx, eVarSetOperationAssign,
993 error.SetErrorStringWithFormat("invalid debugger instance name '%s'",
994 debugger_instance_name);
997 sb_error.SetError(error);
1002 SBDebugger::GetInternalVariableValue(const char *var_name,
1003 const char *debugger_instance_name) {
1004 SBStringList ret_value;
1005 DebuggerSP debugger_sp(Debugger::FindDebuggerWithInstanceName(
1006 ConstString(debugger_instance_name)));
1009 ExecutionContext exe_ctx(
1010 debugger_sp->GetCommandInterpreter().GetExecutionContext());
1011 lldb::OptionValueSP value_sp(
1012 debugger_sp->GetPropertyValue(&exe_ctx, var_name, false, error));
1014 StreamString value_strm;
1015 value_sp->DumpValue(&exe_ctx, value_strm, OptionValue::eDumpOptionValue);
1016 const std::string &value_str = value_strm.GetString();
1017 if (!value_str.empty()) {
1018 StringList string_list;
1019 string_list.SplitIntoLines(value_str);
1020 return SBStringList(&string_list);
1024 return SBStringList();
1027 uint32_t SBDebugger::GetTerminalWidth() const {
1028 return (m_opaque_sp ? m_opaque_sp->GetTerminalWidth() : 0);
1031 void SBDebugger::SetTerminalWidth(uint32_t term_width) {
1033 m_opaque_sp->SetTerminalWidth(term_width);
1036 const char *SBDebugger::GetPrompt() const {
1037 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1040 log->Printf("SBDebugger(%p)::GetPrompt () => \"%s\"",
1041 static_cast<void *>(m_opaque_sp.get()),
1042 (m_opaque_sp ? m_opaque_sp->GetPrompt().str().c_str() : ""));
1044 return (m_opaque_sp ? ConstString(m_opaque_sp->GetPrompt()).GetCString()
1048 void SBDebugger::SetPrompt(const char *prompt) {
1050 m_opaque_sp->SetPrompt(llvm::StringRef::withNullAsEmpty(prompt));
1053 ScriptLanguage SBDebugger::GetScriptLanguage() const {
1054 return (m_opaque_sp ? m_opaque_sp->GetScriptLanguage() : eScriptLanguageNone);
1057 void SBDebugger::SetScriptLanguage(ScriptLanguage script_lang) {
1059 m_opaque_sp->SetScriptLanguage(script_lang);
1063 bool SBDebugger::SetUseExternalEditor(bool value) {
1064 return (m_opaque_sp ? m_opaque_sp->SetUseExternalEditor(value) : false);
1067 bool SBDebugger::GetUseExternalEditor() {
1068 return (m_opaque_sp ? m_opaque_sp->GetUseExternalEditor() : false);
1071 bool SBDebugger::SetUseColor(bool value) {
1072 return (m_opaque_sp ? m_opaque_sp->SetUseColor(value) : false);
1075 bool SBDebugger::GetUseColor() const {
1076 return (m_opaque_sp ? m_opaque_sp->GetUseColor() : false);
1079 bool SBDebugger::GetDescription(SBStream &description) {
1080 Stream &strm = description.ref();
1083 const char *name = m_opaque_sp->GetInstanceName().AsCString();
1084 user_id_t id = m_opaque_sp->GetID();
1085 strm.Printf("Debugger (instance: \"%s\", id: %" PRIu64 ")", name, id);
1087 strm.PutCString("No value");
1092 user_id_t SBDebugger::GetID() {
1093 return (m_opaque_sp ? m_opaque_sp->GetID() : LLDB_INVALID_UID);
1096 SBError SBDebugger::SetCurrentPlatform(const char *platform_name_cstr) {
1099 if (platform_name_cstr && platform_name_cstr[0]) {
1100 ConstString platform_name(platform_name_cstr);
1101 PlatformSP platform_sp(Platform::Find(platform_name));
1104 // Already have a platform with this name, just select it
1105 m_opaque_sp->GetPlatformList().SetSelectedPlatform(platform_sp);
1107 // We don't have a platform by this name yet, create one
1108 platform_sp = Platform::Create(platform_name, sb_error.ref());
1110 // We created the platform, now append and select it
1111 bool make_selected = true;
1112 m_opaque_sp->GetPlatformList().Append(platform_sp, make_selected);
1116 sb_error.ref().SetErrorString("invalid platform name");
1119 sb_error.ref().SetErrorString("invalid debugger");
1124 bool SBDebugger::SetCurrentPlatformSDKRoot(const char *sysroot) {
1125 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1127 PlatformSP platform_sp(
1128 m_opaque_sp->GetPlatformList().GetSelectedPlatform());
1132 log->Printf("SBDebugger::SetCurrentPlatformSDKRoot (\"%s\")", sysroot);
1133 platform_sp->SetSDKRootDirectory(ConstString(sysroot));
1140 bool SBDebugger::GetCloseInputOnEOF() const {
1141 return (m_opaque_sp ? m_opaque_sp->GetCloseInputOnEOF() : false);
1144 void SBDebugger::SetCloseInputOnEOF(bool b) {
1146 m_opaque_sp->SetCloseInputOnEOF(b);
1149 SBTypeCategory SBDebugger::GetCategory(const char *category_name) {
1150 if (!category_name || *category_name == 0)
1151 return SBTypeCategory();
1153 TypeCategoryImplSP category_sp;
1155 if (DataVisualization::Categories::GetCategory(ConstString(category_name),
1156 category_sp, false))
1157 return SBTypeCategory(category_sp);
1159 return SBTypeCategory();
1162 SBTypeCategory SBDebugger::GetCategory(lldb::LanguageType lang_type) {
1163 TypeCategoryImplSP category_sp;
1164 if (DataVisualization::Categories::GetCategory(lang_type, category_sp))
1165 return SBTypeCategory(category_sp);
1167 return SBTypeCategory();
1170 SBTypeCategory SBDebugger::CreateCategory(const char *category_name) {
1171 if (!category_name || *category_name == 0)
1172 return SBTypeCategory();
1174 TypeCategoryImplSP category_sp;
1176 if (DataVisualization::Categories::GetCategory(ConstString(category_name),
1178 return SBTypeCategory(category_sp);
1180 return SBTypeCategory();
1183 bool SBDebugger::DeleteCategory(const char *category_name) {
1184 if (!category_name || *category_name == 0)
1187 return DataVisualization::Categories::Delete(ConstString(category_name));
1190 uint32_t SBDebugger::GetNumCategories() {
1191 return DataVisualization::Categories::GetCount();
1194 SBTypeCategory SBDebugger::GetCategoryAtIndex(uint32_t index) {
1195 return SBTypeCategory(
1196 DataVisualization::Categories::GetCategoryAtIndex(index));
1199 SBTypeCategory SBDebugger::GetDefaultCategory() {
1200 return GetCategory("default");
1203 SBTypeFormat SBDebugger::GetFormatForType(SBTypeNameSpecifier type_name) {
1204 SBTypeCategory default_category_sb = GetDefaultCategory();
1205 if (default_category_sb.GetEnabled())
1206 return default_category_sb.GetFormatForType(type_name);
1207 return SBTypeFormat();
1210 #ifndef LLDB_DISABLE_PYTHON
1211 SBTypeSummary SBDebugger::GetSummaryForType(SBTypeNameSpecifier type_name) {
1212 if (!type_name.IsValid())
1213 return SBTypeSummary();
1214 return SBTypeSummary(DataVisualization::GetSummaryForType(type_name.GetSP()));
1216 #endif // LLDB_DISABLE_PYTHON
1218 SBTypeFilter SBDebugger::GetFilterForType(SBTypeNameSpecifier type_name) {
1219 if (!type_name.IsValid())
1220 return SBTypeFilter();
1221 return SBTypeFilter(DataVisualization::GetFilterForType(type_name.GetSP()));
1224 #ifndef LLDB_DISABLE_PYTHON
1225 SBTypeSynthetic SBDebugger::GetSyntheticForType(SBTypeNameSpecifier type_name) {
1226 if (!type_name.IsValid())
1227 return SBTypeSynthetic();
1228 return SBTypeSynthetic(
1229 DataVisualization::GetSyntheticForType(type_name.GetSP()));
1231 #endif // LLDB_DISABLE_PYTHON
1233 static llvm::ArrayRef<const char *> GetCategoryArray(const char **categories) {
1234 if (categories == nullptr)
1237 while (categories[len] != nullptr)
1239 return llvm::makeArrayRef(categories, len);
1242 bool SBDebugger::EnableLog(const char *channel, const char **categories) {
1244 uint32_t log_options =
1245 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
1247 llvm::raw_string_ostream error_stream(error);
1248 return m_opaque_sp->EnableLog(channel, GetCategoryArray(categories), "",
1249 log_options, error_stream);
1254 void SBDebugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1257 return m_opaque_sp->SetLoggingCallback(log_callback, baton);