xref: /freebsd-src/contrib/llvm-project/lldb/source/API/SBDebugger.cpp (revision 8cc087a1eee9ec1ca9f7ac1e63ad51bdb5a682eb)
1 //===-- SBDebugger.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 "SystemInitializerFull.h"
10 #include "lldb/Utility/Instrumentation.h"
11 
12 #include "lldb/API/SBDebugger.h"
13 
14 #include "lldb/API/SBBroadcaster.h"
15 #include "lldb/API/SBCommandInterpreter.h"
16 #include "lldb/API/SBCommandInterpreterRunOptions.h"
17 #include "lldb/API/SBCommandReturnObject.h"
18 #include "lldb/API/SBError.h"
19 #include "lldb/API/SBEvent.h"
20 #include "lldb/API/SBFile.h"
21 #include "lldb/API/SBFrame.h"
22 #include "lldb/API/SBListener.h"
23 #include "lldb/API/SBProcess.h"
24 #include "lldb/API/SBSourceManager.h"
25 #include "lldb/API/SBStream.h"
26 #include "lldb/API/SBStringList.h"
27 #include "lldb/API/SBStructuredData.h"
28 #include "lldb/API/SBTarget.h"
29 #include "lldb/API/SBThread.h"
30 #include "lldb/API/SBTypeCategory.h"
31 #include "lldb/API/SBTypeFilter.h"
32 #include "lldb/API/SBTypeFormat.h"
33 #include "lldb/API/SBTypeNameSpecifier.h"
34 #include "lldb/API/SBTypeSummary.h"
35 #include "lldb/API/SBTypeSynthetic.h"
36 
37 #include "lldb/Core/Debugger.h"
38 #include "lldb/Core/PluginManager.h"
39 #include "lldb/Core/Progress.h"
40 #include "lldb/Core/StreamFile.h"
41 #include "lldb/Core/StructuredDataImpl.h"
42 #include "lldb/DataFormatters/DataVisualization.h"
43 #include "lldb/Host/Config.h"
44 #include "lldb/Host/XML.h"
45 #include "lldb/Initialization/SystemLifetimeManager.h"
46 #include "lldb/Interpreter/CommandInterpreter.h"
47 #include "lldb/Interpreter/OptionArgParser.h"
48 #include "lldb/Interpreter/OptionGroupPlatform.h"
49 #include "lldb/Target/Process.h"
50 #include "lldb/Target/TargetList.h"
51 #include "lldb/Utility/Args.h"
52 #include "lldb/Utility/State.h"
53 #include "lldb/Version/Version.h"
54 
55 #include "llvm/ADT/STLExtras.h"
56 #include "llvm/ADT/StringRef.h"
57 #include "llvm/Support/DynamicLibrary.h"
58 #include "llvm/Support/ManagedStatic.h"
59 
60 using namespace lldb;
61 using namespace lldb_private;
62 
63 static llvm::sys::DynamicLibrary LoadPlugin(const lldb::DebuggerSP &debugger_sp,
64                                             const FileSpec &spec,
65                                             Status &error) {
66   llvm::sys::DynamicLibrary dynlib =
67       llvm::sys::DynamicLibrary::getPermanentLibrary(spec.GetPath().c_str());
68   if (dynlib.isValid()) {
69     typedef bool (*LLDBCommandPluginInit)(lldb::SBDebugger & debugger);
70 
71     lldb::SBDebugger debugger_sb(debugger_sp);
72     // This calls the bool lldb::PluginInitialize(lldb::SBDebugger debugger)
73     // function.
74     // TODO: mangle this differently for your system - on OSX, the first
75     // underscore needs to be removed and the second one stays
76     LLDBCommandPluginInit init_func =
77         (LLDBCommandPluginInit)(uintptr_t)dynlib.getAddressOfSymbol(
78             "_ZN4lldb16PluginInitializeENS_10SBDebuggerE");
79     if (init_func) {
80       if (init_func(debugger_sb))
81         return dynlib;
82       else
83         error.SetErrorString("plug-in refused to load "
84                              "(lldb::PluginInitialize(lldb::SBDebugger) "
85                              "returned false)");
86     } else {
87       error.SetErrorString("plug-in is missing the required initialization: "
88                            "lldb::PluginInitialize(lldb::SBDebugger)");
89     }
90   } else {
91     if (FileSystem::Instance().Exists(spec))
92       error.SetErrorString("this file does not represent a loadable dylib");
93     else
94       error.SetErrorString("no such file");
95   }
96   return llvm::sys::DynamicLibrary();
97 }
98 
99 static llvm::ManagedStatic<SystemLifetimeManager> g_debugger_lifetime;
100 
101 SBError SBInputReader::Initialize(
102     lldb::SBDebugger &sb_debugger,
103     unsigned long (*callback)(void *, lldb::SBInputReader *,
104                               lldb::InputReaderAction, char const *,
105                               unsigned long),
106     void *a, lldb::InputReaderGranularity b, char const *c, char const *d,
107     bool e) {
108   LLDB_INSTRUMENT_VA(this, sb_debugger, callback, a, b, c, d, e);
109 
110   return SBError();
111 }
112 
113 void SBInputReader::SetIsDone(bool b) { LLDB_INSTRUMENT_VA(this, b); }
114 
115 bool SBInputReader::IsActive() const {
116   LLDB_INSTRUMENT_VA(this);
117 
118   return false;
119 }
120 
121 SBDebugger::SBDebugger() { LLDB_INSTRUMENT_VA(this); }
122 
123 SBDebugger::SBDebugger(const lldb::DebuggerSP &debugger_sp)
124     : m_opaque_sp(debugger_sp) {
125   LLDB_INSTRUMENT_VA(this, debugger_sp);
126 }
127 
128 SBDebugger::SBDebugger(const SBDebugger &rhs) : m_opaque_sp(rhs.m_opaque_sp) {
129   LLDB_INSTRUMENT_VA(this, rhs);
130 }
131 
132 SBDebugger::~SBDebugger() = default;
133 
134 SBDebugger &SBDebugger::operator=(const SBDebugger &rhs) {
135   LLDB_INSTRUMENT_VA(this, rhs);
136 
137   if (this != &rhs) {
138     m_opaque_sp = rhs.m_opaque_sp;
139   }
140   return *this;
141 }
142 
143 const char *SBDebugger::GetBroadcasterClass() {
144   LLDB_INSTRUMENT();
145 
146   return Debugger::GetStaticBroadcasterClass().AsCString();
147 }
148 
149 const char *SBDebugger::GetProgressFromEvent(const lldb::SBEvent &event,
150                                              uint64_t &progress_id,
151                                              uint64_t &completed,
152                                              uint64_t &total,
153                                              bool &is_debugger_specific) {
154   LLDB_INSTRUMENT_VA(event, progress_id, completed, total,
155                      is_debugger_specific);
156   const Debugger::ProgressEventData *progress_data =
157       Debugger::ProgressEventData::GetEventDataFromEvent(event.get());
158   if (progress_data == nullptr)
159     return nullptr;
160   progress_id = progress_data->GetID();
161   completed = progress_data->GetCompleted();
162   total = progress_data->GetTotal();
163   is_debugger_specific = progress_data->IsDebuggerSpecific();
164   return progress_data->GetMessage().c_str();
165 }
166 
167 SBBroadcaster SBDebugger::GetBroadcaster() {
168   LLDB_INSTRUMENT_VA(this);
169   SBBroadcaster broadcaster(&m_opaque_sp->GetBroadcaster(), false);
170   return broadcaster;
171 }
172 
173 void SBDebugger::Initialize() {
174   LLDB_INSTRUMENT();
175   SBError ignored = SBDebugger::InitializeWithErrorHandling();
176 }
177 
178 lldb::SBError SBDebugger::InitializeWithErrorHandling() {
179   LLDB_INSTRUMENT();
180 
181   SBError error;
182   if (auto e = g_debugger_lifetime->Initialize(
183           std::make_unique<SystemInitializerFull>(), LoadPlugin)) {
184     error.SetError(Status(std::move(e)));
185   }
186   return error;
187 }
188 
189 void SBDebugger::Terminate() {
190   LLDB_INSTRUMENT();
191 
192   g_debugger_lifetime->Terminate();
193 }
194 
195 void SBDebugger::Clear() {
196   LLDB_INSTRUMENT_VA(this);
197 
198   if (m_opaque_sp)
199     m_opaque_sp->ClearIOHandlers();
200 
201   m_opaque_sp.reset();
202 }
203 
204 SBDebugger SBDebugger::Create() {
205   LLDB_INSTRUMENT();
206 
207   return SBDebugger::Create(false, nullptr, nullptr);
208 }
209 
210 SBDebugger SBDebugger::Create(bool source_init_files) {
211   LLDB_INSTRUMENT_VA(source_init_files);
212 
213   return SBDebugger::Create(source_init_files, nullptr, nullptr);
214 }
215 
216 SBDebugger SBDebugger::Create(bool source_init_files,
217                               lldb::LogOutputCallback callback, void *baton)
218 
219 {
220   LLDB_INSTRUMENT_VA(source_init_files, callback, baton);
221 
222   SBDebugger debugger;
223 
224   // Currently we have issues if this function is called simultaneously on two
225   // different threads. The issues mainly revolve around the fact that the
226   // lldb_private::FormatManager uses global collections and having two threads
227   // parsing the .lldbinit files can cause mayhem. So to get around this for
228   // now we need to use a mutex to prevent bad things from happening.
229   static std::recursive_mutex g_mutex;
230   std::lock_guard<std::recursive_mutex> guard(g_mutex);
231 
232   debugger.reset(Debugger::CreateInstance(callback, baton));
233 
234   SBCommandInterpreter interp = debugger.GetCommandInterpreter();
235   if (source_init_files) {
236     interp.get()->SkipLLDBInitFiles(false);
237     interp.get()->SkipAppInitFiles(false);
238     SBCommandReturnObject result;
239     interp.SourceInitFileInHomeDirectory(result, false);
240   } else {
241     interp.get()->SkipLLDBInitFiles(true);
242     interp.get()->SkipAppInitFiles(true);
243   }
244   return debugger;
245 }
246 
247 void SBDebugger::Destroy(SBDebugger &debugger) {
248   LLDB_INSTRUMENT_VA(debugger);
249 
250   Debugger::Destroy(debugger.m_opaque_sp);
251 
252   if (debugger.m_opaque_sp.get() != nullptr)
253     debugger.m_opaque_sp.reset();
254 }
255 
256 void SBDebugger::MemoryPressureDetected() {
257   LLDB_INSTRUMENT();
258 
259   // Since this function can be call asynchronously, we allow it to be non-
260   // mandatory. We have seen deadlocks with this function when called so we
261   // need to safeguard against this until we can determine what is causing the
262   // deadlocks.
263 
264   const bool mandatory = false;
265 
266   ModuleList::RemoveOrphanSharedModules(mandatory);
267 }
268 
269 bool SBDebugger::IsValid() const {
270   LLDB_INSTRUMENT_VA(this);
271   return this->operator bool();
272 }
273 SBDebugger::operator bool() const {
274   LLDB_INSTRUMENT_VA(this);
275 
276   return m_opaque_sp.get() != nullptr;
277 }
278 
279 void SBDebugger::SetAsync(bool b) {
280   LLDB_INSTRUMENT_VA(this, b);
281 
282   if (m_opaque_sp)
283     m_opaque_sp->SetAsyncExecution(b);
284 }
285 
286 bool SBDebugger::GetAsync() {
287   LLDB_INSTRUMENT_VA(this);
288 
289   return (m_opaque_sp ? m_opaque_sp->GetAsyncExecution() : false);
290 }
291 
292 void SBDebugger::SkipLLDBInitFiles(bool b) {
293   LLDB_INSTRUMENT_VA(this, b);
294 
295   if (m_opaque_sp)
296     m_opaque_sp->GetCommandInterpreter().SkipLLDBInitFiles(b);
297 }
298 
299 void SBDebugger::SkipAppInitFiles(bool b) {
300   LLDB_INSTRUMENT_VA(this, b);
301 
302   if (m_opaque_sp)
303     m_opaque_sp->GetCommandInterpreter().SkipAppInitFiles(b);
304 }
305 
306 void SBDebugger::SetInputFileHandle(FILE *fh, bool transfer_ownership) {
307   LLDB_INSTRUMENT_VA(this, fh, transfer_ownership);
308   if (m_opaque_sp)
309     m_opaque_sp->SetInputFile(
310         (FileSP)std::make_shared<NativeFile>(fh, transfer_ownership));
311 }
312 
313 SBError SBDebugger::SetInputString(const char *data) {
314   LLDB_INSTRUMENT_VA(this, data);
315   SBError sb_error;
316   if (data == nullptr) {
317     sb_error.SetErrorString("String data is null");
318     return sb_error;
319   }
320 
321   size_t size = strlen(data);
322   if (size == 0) {
323     sb_error.SetErrorString("String data is empty");
324     return sb_error;
325   }
326 
327   if (!m_opaque_sp) {
328     sb_error.SetErrorString("invalid debugger");
329     return sb_error;
330   }
331 
332   sb_error.SetError(m_opaque_sp->SetInputString(data));
333   return sb_error;
334 }
335 
336 // Shouldn't really be settable after initialization as this could cause lots
337 // of problems; don't want users trying to switch modes in the middle of a
338 // debugging session.
339 SBError SBDebugger::SetInputFile(SBFile file) {
340   LLDB_INSTRUMENT_VA(this, file);
341 
342   SBError error;
343   if (!m_opaque_sp) {
344     error.ref().SetErrorString("invalid debugger");
345     return error;
346   }
347   error.SetError(m_opaque_sp->SetInputFile(file.m_opaque_sp));
348   return error;
349 }
350 
351 SBError SBDebugger::SetInputFile(FileSP file_sp) {
352   LLDB_INSTRUMENT_VA(this, file_sp);
353   return SetInputFile(SBFile(file_sp));
354 }
355 
356 SBError SBDebugger::SetOutputFile(FileSP file_sp) {
357   LLDB_INSTRUMENT_VA(this, file_sp);
358   return SetOutputFile(SBFile(file_sp));
359 }
360 
361 void SBDebugger::SetOutputFileHandle(FILE *fh, bool transfer_ownership) {
362   LLDB_INSTRUMENT_VA(this, fh, transfer_ownership);
363   SetOutputFile((FileSP)std::make_shared<NativeFile>(fh, transfer_ownership));
364 }
365 
366 SBError SBDebugger::SetOutputFile(SBFile file) {
367   LLDB_INSTRUMENT_VA(this, file);
368   SBError error;
369   if (!m_opaque_sp) {
370     error.ref().SetErrorString("invalid debugger");
371     return error;
372   }
373   if (!file) {
374     error.ref().SetErrorString("invalid file");
375     return error;
376   }
377   m_opaque_sp->SetOutputFile(file.m_opaque_sp);
378   return error;
379 }
380 
381 void SBDebugger::SetErrorFileHandle(FILE *fh, bool transfer_ownership) {
382   LLDB_INSTRUMENT_VA(this, fh, transfer_ownership);
383   SetErrorFile((FileSP)std::make_shared<NativeFile>(fh, transfer_ownership));
384 }
385 
386 SBError SBDebugger::SetErrorFile(FileSP file_sp) {
387   LLDB_INSTRUMENT_VA(this, file_sp);
388   return SetErrorFile(SBFile(file_sp));
389 }
390 
391 SBError SBDebugger::SetErrorFile(SBFile file) {
392   LLDB_INSTRUMENT_VA(this, file);
393   SBError error;
394   if (!m_opaque_sp) {
395     error.ref().SetErrorString("invalid debugger");
396     return error;
397   }
398   if (!file) {
399     error.ref().SetErrorString("invalid file");
400     return error;
401   }
402   m_opaque_sp->SetErrorFile(file.m_opaque_sp);
403   return error;
404 }
405 
406 FILE *SBDebugger::GetInputFileHandle() {
407   LLDB_INSTRUMENT_VA(this);
408   if (m_opaque_sp) {
409     File &file_sp = m_opaque_sp->GetInputFile();
410     return file_sp.GetStream();
411   }
412   return nullptr;
413 }
414 
415 SBFile SBDebugger::GetInputFile() {
416   LLDB_INSTRUMENT_VA(this);
417   if (m_opaque_sp) {
418     return SBFile(m_opaque_sp->GetInputFileSP());
419   }
420   return SBFile();
421 }
422 
423 FILE *SBDebugger::GetOutputFileHandle() {
424   LLDB_INSTRUMENT_VA(this);
425   if (m_opaque_sp) {
426     StreamFile &stream_file = m_opaque_sp->GetOutputStream();
427     return stream_file.GetFile().GetStream();
428   }
429   return nullptr;
430 }
431 
432 SBFile SBDebugger::GetOutputFile() {
433   LLDB_INSTRUMENT_VA(this);
434   if (m_opaque_sp) {
435     SBFile file(m_opaque_sp->GetOutputStream().GetFileSP());
436     return file;
437   }
438   return SBFile();
439 }
440 
441 FILE *SBDebugger::GetErrorFileHandle() {
442   LLDB_INSTRUMENT_VA(this);
443 
444   if (m_opaque_sp) {
445     StreamFile &stream_file = m_opaque_sp->GetErrorStream();
446     return stream_file.GetFile().GetStream();
447   }
448   return nullptr;
449 }
450 
451 SBFile SBDebugger::GetErrorFile() {
452   LLDB_INSTRUMENT_VA(this);
453   SBFile file;
454   if (m_opaque_sp) {
455     SBFile file(m_opaque_sp->GetErrorStream().GetFileSP());
456     return file;
457   }
458   return SBFile();
459 }
460 
461 void SBDebugger::SaveInputTerminalState() {
462   LLDB_INSTRUMENT_VA(this);
463 
464   if (m_opaque_sp)
465     m_opaque_sp->SaveInputTerminalState();
466 }
467 
468 void SBDebugger::RestoreInputTerminalState() {
469   LLDB_INSTRUMENT_VA(this);
470 
471   if (m_opaque_sp)
472     m_opaque_sp->RestoreInputTerminalState();
473 }
474 SBCommandInterpreter SBDebugger::GetCommandInterpreter() {
475   LLDB_INSTRUMENT_VA(this);
476 
477   SBCommandInterpreter sb_interpreter;
478   if (m_opaque_sp)
479     sb_interpreter.reset(&m_opaque_sp->GetCommandInterpreter());
480 
481   return sb_interpreter;
482 }
483 
484 void SBDebugger::HandleCommand(const char *command) {
485   LLDB_INSTRUMENT_VA(this, command);
486 
487   if (m_opaque_sp) {
488     TargetSP target_sp(m_opaque_sp->GetSelectedTarget());
489     std::unique_lock<std::recursive_mutex> lock;
490     if (target_sp)
491       lock = std::unique_lock<std::recursive_mutex>(target_sp->GetAPIMutex());
492 
493     SBCommandInterpreter sb_interpreter(GetCommandInterpreter());
494     SBCommandReturnObject result;
495 
496     sb_interpreter.HandleCommand(command, result, false);
497 
498     result.PutError(m_opaque_sp->GetErrorStream().GetFileSP());
499     result.PutOutput(m_opaque_sp->GetOutputStream().GetFileSP());
500 
501     if (!m_opaque_sp->GetAsyncExecution()) {
502       SBProcess process(GetCommandInterpreter().GetProcess());
503       ProcessSP process_sp(process.GetSP());
504       if (process_sp) {
505         EventSP event_sp;
506         ListenerSP lldb_listener_sp = m_opaque_sp->GetListener();
507         while (lldb_listener_sp->GetEventForBroadcaster(
508             process_sp.get(), event_sp, std::chrono::seconds(0))) {
509           SBEvent event(event_sp);
510           HandleProcessEvent(process, event, GetOutputFile(), GetErrorFile());
511         }
512       }
513     }
514   }
515 }
516 
517 SBListener SBDebugger::GetListener() {
518   LLDB_INSTRUMENT_VA(this);
519 
520   SBListener sb_listener;
521   if (m_opaque_sp)
522     sb_listener.reset(m_opaque_sp->GetListener());
523 
524   return sb_listener;
525 }
526 
527 void SBDebugger::HandleProcessEvent(const SBProcess &process,
528                                     const SBEvent &event, SBFile out,
529                                     SBFile err) {
530   LLDB_INSTRUMENT_VA(this, process, event, out, err);
531 
532   return HandleProcessEvent(process, event, out.m_opaque_sp, err.m_opaque_sp);
533 }
534 
535 void SBDebugger::HandleProcessEvent(const SBProcess &process,
536                                     const SBEvent &event, FILE *out,
537                                     FILE *err) {
538   LLDB_INSTRUMENT_VA(this, process, event, out, err);
539 
540   FileSP outfile = std::make_shared<NativeFile>(out, false);
541   FileSP errfile = std::make_shared<NativeFile>(err, false);
542   return HandleProcessEvent(process, event, outfile, errfile);
543 }
544 
545 void SBDebugger::HandleProcessEvent(const SBProcess &process,
546                                     const SBEvent &event, FileSP out_sp,
547                                     FileSP err_sp) {
548 
549   LLDB_INSTRUMENT_VA(this, process, event, out_sp, err_sp);
550 
551   if (!process.IsValid())
552     return;
553 
554   TargetSP target_sp(process.GetTarget().GetSP());
555   if (!target_sp)
556     return;
557 
558   const uint32_t event_type = event.GetType();
559   char stdio_buffer[1024];
560   size_t len;
561 
562   std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
563 
564   if (event_type &
565       (Process::eBroadcastBitSTDOUT | Process::eBroadcastBitStateChanged)) {
566     // Drain stdout when we stop just in case we have any bytes
567     while ((len = process.GetSTDOUT(stdio_buffer, sizeof(stdio_buffer))) > 0)
568       if (out_sp)
569         out_sp->Write(stdio_buffer, len);
570   }
571 
572   if (event_type &
573       (Process::eBroadcastBitSTDERR | Process::eBroadcastBitStateChanged)) {
574     // Drain stderr when we stop just in case we have any bytes
575     while ((len = process.GetSTDERR(stdio_buffer, sizeof(stdio_buffer))) > 0)
576       if (err_sp)
577         err_sp->Write(stdio_buffer, len);
578   }
579 
580   if (event_type & Process::eBroadcastBitStateChanged) {
581     StateType event_state = SBProcess::GetStateFromEvent(event);
582 
583     if (event_state == eStateInvalid)
584       return;
585 
586     bool is_stopped = StateIsStoppedState(event_state);
587     if (!is_stopped)
588       process.ReportEventState(event, out_sp);
589   }
590 }
591 
592 SBSourceManager SBDebugger::GetSourceManager() {
593   LLDB_INSTRUMENT_VA(this);
594 
595   SBSourceManager sb_source_manager(*this);
596   return sb_source_manager;
597 }
598 
599 bool SBDebugger::GetDefaultArchitecture(char *arch_name, size_t arch_name_len) {
600   LLDB_INSTRUMENT_VA(arch_name, arch_name_len);
601 
602   if (arch_name && arch_name_len) {
603     ArchSpec default_arch = Target::GetDefaultArchitecture();
604 
605     if (default_arch.IsValid()) {
606       const std::string &triple_str = default_arch.GetTriple().str();
607       if (!triple_str.empty())
608         ::snprintf(arch_name, arch_name_len, "%s", triple_str.c_str());
609       else
610         ::snprintf(arch_name, arch_name_len, "%s",
611                    default_arch.GetArchitectureName());
612       return true;
613     }
614   }
615   if (arch_name && arch_name_len)
616     arch_name[0] = '\0';
617   return false;
618 }
619 
620 bool SBDebugger::SetDefaultArchitecture(const char *arch_name) {
621   LLDB_INSTRUMENT_VA(arch_name);
622 
623   if (arch_name) {
624     ArchSpec arch(arch_name);
625     if (arch.IsValid()) {
626       Target::SetDefaultArchitecture(arch);
627       return true;
628     }
629   }
630   return false;
631 }
632 
633 ScriptLanguage
634 SBDebugger::GetScriptingLanguage(const char *script_language_name) {
635   LLDB_INSTRUMENT_VA(this, script_language_name);
636 
637   if (!script_language_name)
638     return eScriptLanguageDefault;
639   return OptionArgParser::ToScriptLanguage(
640       llvm::StringRef(script_language_name), eScriptLanguageDefault, nullptr);
641 }
642 
643 SBStructuredData
644 SBDebugger::GetScriptInterpreterInfo(lldb::ScriptLanguage language) {
645   LLDB_INSTRUMENT_VA(this, language);
646   SBStructuredData data;
647   if (m_opaque_sp) {
648     lldb_private::ScriptInterpreter *interp =
649         m_opaque_sp->GetScriptInterpreter(language);
650     if (interp) {
651       data.m_impl_up->SetObjectSP(interp->GetInterpreterInfo());
652     }
653   }
654   return data;
655 }
656 
657 const char *SBDebugger::GetVersionString() {
658   LLDB_INSTRUMENT();
659 
660   return lldb_private::GetVersion();
661 }
662 
663 const char *SBDebugger::StateAsCString(StateType state) {
664   LLDB_INSTRUMENT_VA(state);
665 
666   return lldb_private::StateAsCString(state);
667 }
668 
669 static void AddBoolConfigEntry(StructuredData::Dictionary &dict,
670                                llvm::StringRef name, bool value,
671                                llvm::StringRef description) {
672   auto entry_up = std::make_unique<StructuredData::Dictionary>();
673   entry_up->AddBooleanItem("value", value);
674   entry_up->AddStringItem("description", description);
675   dict.AddItem(name, std::move(entry_up));
676 }
677 
678 static void AddLLVMTargets(StructuredData::Dictionary &dict) {
679   auto array_up = std::make_unique<StructuredData::Array>();
680 #define LLVM_TARGET(target)                                                    \
681   array_up->AddItem(std::make_unique<StructuredData::String>(#target));
682 #include "llvm/Config/Targets.def"
683   auto entry_up = std::make_unique<StructuredData::Dictionary>();
684   entry_up->AddItem("value", std::move(array_up));
685   entry_up->AddStringItem("description", "A list of configured LLVM targets.");
686   dict.AddItem("targets", std::move(entry_up));
687 }
688 
689 SBStructuredData SBDebugger::GetBuildConfiguration() {
690   LLDB_INSTRUMENT();
691 
692   auto config_up = std::make_unique<StructuredData::Dictionary>();
693   AddBoolConfigEntry(
694       *config_up, "xml", XMLDocument::XMLEnabled(),
695       "A boolean value that indicates if XML support is enabled in LLDB");
696   AddBoolConfigEntry(
697       *config_up, "curses", LLDB_ENABLE_CURSES,
698       "A boolean value that indicates if curses support is enabled in LLDB");
699   AddBoolConfigEntry(
700       *config_up, "editline", LLDB_ENABLE_LIBEDIT,
701       "A boolean value that indicates if editline support is enabled in LLDB");
702   AddBoolConfigEntry(
703       *config_up, "lzma", LLDB_ENABLE_LZMA,
704       "A boolean value that indicates if lzma support is enabled in LLDB");
705   AddBoolConfigEntry(
706       *config_up, "python", LLDB_ENABLE_PYTHON,
707       "A boolean value that indicates if python support is enabled in LLDB");
708   AddBoolConfigEntry(
709       *config_up, "lua", LLDB_ENABLE_LUA,
710       "A boolean value that indicates if lua support is enabled in LLDB");
711   AddBoolConfigEntry(*config_up, "fbsdvmcore", LLDB_ENABLE_FBSDVMCORE,
712                      "A boolean value that indicates if fbsdvmcore support is "
713                      "enabled in LLDB");
714   AddLLVMTargets(*config_up);
715 
716   SBStructuredData data;
717   data.m_impl_up->SetObjectSP(std::move(config_up));
718   return data;
719 }
720 
721 bool SBDebugger::StateIsRunningState(StateType state) {
722   LLDB_INSTRUMENT_VA(state);
723 
724   const bool result = lldb_private::StateIsRunningState(state);
725 
726   return result;
727 }
728 
729 bool SBDebugger::StateIsStoppedState(StateType state) {
730   LLDB_INSTRUMENT_VA(state);
731 
732   const bool result = lldb_private::StateIsStoppedState(state, false);
733 
734   return result;
735 }
736 
737 lldb::SBTarget SBDebugger::CreateTarget(const char *filename,
738                                         const char *target_triple,
739                                         const char *platform_name,
740                                         bool add_dependent_modules,
741                                         lldb::SBError &sb_error) {
742   LLDB_INSTRUMENT_VA(this, filename, target_triple, platform_name,
743                      add_dependent_modules, sb_error);
744 
745   SBTarget sb_target;
746   TargetSP target_sp;
747   if (m_opaque_sp) {
748     sb_error.Clear();
749     OptionGroupPlatform platform_options(false);
750     platform_options.SetPlatformName(platform_name);
751 
752     sb_error.ref() = m_opaque_sp->GetTargetList().CreateTarget(
753         *m_opaque_sp, filename, target_triple,
754         add_dependent_modules ? eLoadDependentsYes : eLoadDependentsNo,
755         &platform_options, target_sp);
756 
757     if (sb_error.Success())
758       sb_target.SetSP(target_sp);
759   } else {
760     sb_error.SetErrorString("invalid debugger");
761   }
762 
763   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
764   LLDB_LOGF(log,
765             "SBDebugger(%p)::CreateTarget (filename=\"%s\", triple=%s, "
766             "platform_name=%s, add_dependent_modules=%u, error=%s) => "
767             "SBTarget(%p)",
768             static_cast<void *>(m_opaque_sp.get()), filename, target_triple,
769             platform_name, add_dependent_modules, sb_error.GetCString(),
770             static_cast<void *>(target_sp.get()));
771 
772   return sb_target;
773 }
774 
775 SBTarget
776 SBDebugger::CreateTargetWithFileAndTargetTriple(const char *filename,
777                                                 const char *target_triple) {
778   LLDB_INSTRUMENT_VA(this, filename, target_triple);
779 
780   SBTarget sb_target;
781   TargetSP target_sp;
782   if (m_opaque_sp) {
783     const bool add_dependent_modules = true;
784     Status error(m_opaque_sp->GetTargetList().CreateTarget(
785         *m_opaque_sp, filename, target_triple,
786         add_dependent_modules ? eLoadDependentsYes : eLoadDependentsNo, nullptr,
787         target_sp));
788     sb_target.SetSP(target_sp);
789   }
790 
791   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
792   LLDB_LOGF(log,
793             "SBDebugger(%p)::CreateTargetWithFileAndTargetTriple "
794             "(filename=\"%s\", triple=%s) => SBTarget(%p)",
795             static_cast<void *>(m_opaque_sp.get()), filename, target_triple,
796             static_cast<void *>(target_sp.get()));
797 
798   return sb_target;
799 }
800 
801 SBTarget SBDebugger::CreateTargetWithFileAndArch(const char *filename,
802                                                  const char *arch_cstr) {
803   LLDB_INSTRUMENT_VA(this, filename, arch_cstr);
804 
805   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
806 
807   SBTarget sb_target;
808   TargetSP target_sp;
809   if (m_opaque_sp) {
810     Status error;
811     if (arch_cstr == nullptr) {
812       // The version of CreateTarget that takes an ArchSpec won't accept an
813       // empty ArchSpec, so when the arch hasn't been specified, we need to
814       // call the target triple version.
815       error = m_opaque_sp->GetTargetList().CreateTarget(
816           *m_opaque_sp, filename, arch_cstr, eLoadDependentsYes, nullptr,
817           target_sp);
818     } else {
819       PlatformSP platform_sp =
820           m_opaque_sp->GetPlatformList().GetSelectedPlatform();
821       ArchSpec arch =
822           Platform::GetAugmentedArchSpec(platform_sp.get(), arch_cstr);
823       if (arch.IsValid())
824         error = m_opaque_sp->GetTargetList().CreateTarget(
825             *m_opaque_sp, filename, arch, eLoadDependentsYes, platform_sp,
826             target_sp);
827       else
828         error.SetErrorStringWithFormat("invalid arch_cstr: %s", arch_cstr);
829     }
830     if (error.Success())
831       sb_target.SetSP(target_sp);
832   }
833 
834   LLDB_LOGF(log,
835             "SBDebugger(%p)::CreateTargetWithFileAndArch (filename=\"%s\", "
836             "arch=%s) => SBTarget(%p)",
837             static_cast<void *>(m_opaque_sp.get()),
838             filename ? filename : "<unspecified>",
839             arch_cstr ? arch_cstr : "<unspecified>",
840             static_cast<void *>(target_sp.get()));
841 
842   return sb_target;
843 }
844 
845 SBTarget SBDebugger::CreateTarget(const char *filename) {
846   LLDB_INSTRUMENT_VA(this, filename);
847 
848   SBTarget sb_target;
849   TargetSP target_sp;
850   if (m_opaque_sp) {
851     Status error;
852     const bool add_dependent_modules = true;
853     error = m_opaque_sp->GetTargetList().CreateTarget(
854         *m_opaque_sp, filename, "",
855         add_dependent_modules ? eLoadDependentsYes : eLoadDependentsNo, nullptr,
856         target_sp);
857 
858     if (error.Success())
859       sb_target.SetSP(target_sp);
860   }
861   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
862   LLDB_LOGF(log,
863             "SBDebugger(%p)::CreateTarget (filename=\"%s\") => SBTarget(%p)",
864             static_cast<void *>(m_opaque_sp.get()), filename,
865             static_cast<void *>(target_sp.get()));
866   return sb_target;
867 }
868 
869 SBTarget SBDebugger::GetDummyTarget() {
870   LLDB_INSTRUMENT_VA(this);
871 
872   SBTarget sb_target;
873   if (m_opaque_sp) {
874     sb_target.SetSP(m_opaque_sp->GetDummyTarget().shared_from_this());
875   }
876   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
877   LLDB_LOGF(log, "SBDebugger(%p)::GetDummyTarget() => SBTarget(%p)",
878             static_cast<void *>(m_opaque_sp.get()),
879             static_cast<void *>(sb_target.GetSP().get()));
880   return sb_target;
881 }
882 
883 bool SBDebugger::DeleteTarget(lldb::SBTarget &target) {
884   LLDB_INSTRUMENT_VA(this, target);
885 
886   bool result = false;
887   if (m_opaque_sp) {
888     TargetSP target_sp(target.GetSP());
889     if (target_sp) {
890       // No need to lock, the target list is thread safe
891       result = m_opaque_sp->GetTargetList().DeleteTarget(target_sp);
892       target_sp->Destroy();
893       target.Clear();
894     }
895   }
896 
897   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
898   LLDB_LOGF(log, "SBDebugger(%p)::DeleteTarget (SBTarget(%p)) => %i",
899             static_cast<void *>(m_opaque_sp.get()),
900             static_cast<void *>(target.m_opaque_sp.get()), result);
901 
902   return result;
903 }
904 
905 SBTarget SBDebugger::GetTargetAtIndex(uint32_t idx) {
906   LLDB_INSTRUMENT_VA(this, idx);
907 
908   SBTarget sb_target;
909   if (m_opaque_sp) {
910     // No need to lock, the target list is thread safe
911     sb_target.SetSP(m_opaque_sp->GetTargetList().GetTargetAtIndex(idx));
912   }
913   return sb_target;
914 }
915 
916 uint32_t SBDebugger::GetIndexOfTarget(lldb::SBTarget target) {
917   LLDB_INSTRUMENT_VA(this, target);
918 
919   lldb::TargetSP target_sp = target.GetSP();
920   if (!target_sp)
921     return UINT32_MAX;
922 
923   if (!m_opaque_sp)
924     return UINT32_MAX;
925 
926   return m_opaque_sp->GetTargetList().GetIndexOfTarget(target.GetSP());
927 }
928 
929 SBTarget SBDebugger::FindTargetWithProcessID(lldb::pid_t pid) {
930   LLDB_INSTRUMENT_VA(this, pid);
931 
932   SBTarget sb_target;
933   if (m_opaque_sp) {
934     // No need to lock, the target list is thread safe
935     sb_target.SetSP(m_opaque_sp->GetTargetList().FindTargetWithProcessID(pid));
936   }
937   return sb_target;
938 }
939 
940 SBTarget SBDebugger::FindTargetWithFileAndArch(const char *filename,
941                                                const char *arch_name) {
942   LLDB_INSTRUMENT_VA(this, filename, arch_name);
943 
944   SBTarget sb_target;
945   if (m_opaque_sp && filename && filename[0]) {
946     // No need to lock, the target list is thread safe
947     ArchSpec arch = Platform::GetAugmentedArchSpec(
948         m_opaque_sp->GetPlatformList().GetSelectedPlatform().get(), arch_name);
949     TargetSP target_sp(
950         m_opaque_sp->GetTargetList().FindTargetWithExecutableAndArchitecture(
951             FileSpec(filename), arch_name ? &arch : nullptr));
952     sb_target.SetSP(target_sp);
953   }
954   return sb_target;
955 }
956 
957 SBTarget SBDebugger::FindTargetWithLLDBProcess(const ProcessSP &process_sp) {
958   SBTarget sb_target;
959   if (m_opaque_sp) {
960     // No need to lock, the target list is thread safe
961     sb_target.SetSP(
962         m_opaque_sp->GetTargetList().FindTargetWithProcess(process_sp.get()));
963   }
964   return sb_target;
965 }
966 
967 uint32_t SBDebugger::GetNumTargets() {
968   LLDB_INSTRUMENT_VA(this);
969 
970   if (m_opaque_sp) {
971     // No need to lock, the target list is thread safe
972     return m_opaque_sp->GetTargetList().GetNumTargets();
973   }
974   return 0;
975 }
976 
977 SBTarget SBDebugger::GetSelectedTarget() {
978   LLDB_INSTRUMENT_VA(this);
979 
980   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
981 
982   SBTarget sb_target;
983   TargetSP target_sp;
984   if (m_opaque_sp) {
985     // No need to lock, the target list is thread safe
986     target_sp = m_opaque_sp->GetTargetList().GetSelectedTarget();
987     sb_target.SetSP(target_sp);
988   }
989 
990   if (log) {
991     SBStream sstr;
992     sb_target.GetDescription(sstr, eDescriptionLevelBrief);
993     LLDB_LOGF(log, "SBDebugger(%p)::GetSelectedTarget () => SBTarget(%p): %s",
994               static_cast<void *>(m_opaque_sp.get()),
995               static_cast<void *>(target_sp.get()), sstr.GetData());
996   }
997 
998   return sb_target;
999 }
1000 
1001 void SBDebugger::SetSelectedTarget(SBTarget &sb_target) {
1002   LLDB_INSTRUMENT_VA(this, sb_target);
1003 
1004   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1005 
1006   TargetSP target_sp(sb_target.GetSP());
1007   if (m_opaque_sp) {
1008     m_opaque_sp->GetTargetList().SetSelectedTarget(target_sp);
1009   }
1010   if (log) {
1011     SBStream sstr;
1012     sb_target.GetDescription(sstr, eDescriptionLevelBrief);
1013     LLDB_LOGF(log, "SBDebugger(%p)::SetSelectedTarget () => SBTarget(%p): %s",
1014               static_cast<void *>(m_opaque_sp.get()),
1015               static_cast<void *>(target_sp.get()), sstr.GetData());
1016   }
1017 }
1018 
1019 SBPlatform SBDebugger::GetSelectedPlatform() {
1020   LLDB_INSTRUMENT_VA(this);
1021 
1022   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1023 
1024   SBPlatform sb_platform;
1025   DebuggerSP debugger_sp(m_opaque_sp);
1026   if (debugger_sp) {
1027     sb_platform.SetSP(debugger_sp->GetPlatformList().GetSelectedPlatform());
1028   }
1029   LLDB_LOGF(log, "SBDebugger(%p)::GetSelectedPlatform () => SBPlatform(%p): %s",
1030             static_cast<void *>(m_opaque_sp.get()),
1031             static_cast<void *>(sb_platform.GetSP().get()),
1032             sb_platform.GetName());
1033   return sb_platform;
1034 }
1035 
1036 void SBDebugger::SetSelectedPlatform(SBPlatform &sb_platform) {
1037   LLDB_INSTRUMENT_VA(this, sb_platform);
1038 
1039   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1040 
1041   DebuggerSP debugger_sp(m_opaque_sp);
1042   if (debugger_sp) {
1043     debugger_sp->GetPlatformList().SetSelectedPlatform(sb_platform.GetSP());
1044   }
1045 
1046   LLDB_LOGF(log, "SBDebugger(%p)::SetSelectedPlatform (SBPlatform(%p) %s)",
1047             static_cast<void *>(m_opaque_sp.get()),
1048             static_cast<void *>(sb_platform.GetSP().get()),
1049             sb_platform.GetName());
1050 }
1051 
1052 uint32_t SBDebugger::GetNumPlatforms() {
1053   LLDB_INSTRUMENT_VA(this);
1054 
1055   if (m_opaque_sp) {
1056     // No need to lock, the platform list is thread safe
1057     return m_opaque_sp->GetPlatformList().GetSize();
1058   }
1059   return 0;
1060 }
1061 
1062 SBPlatform SBDebugger::GetPlatformAtIndex(uint32_t idx) {
1063   LLDB_INSTRUMENT_VA(this, idx);
1064 
1065   SBPlatform sb_platform;
1066   if (m_opaque_sp) {
1067     // No need to lock, the platform list is thread safe
1068     sb_platform.SetSP(m_opaque_sp->GetPlatformList().GetAtIndex(idx));
1069   }
1070   return sb_platform;
1071 }
1072 
1073 uint32_t SBDebugger::GetNumAvailablePlatforms() {
1074   LLDB_INSTRUMENT_VA(this);
1075 
1076   uint32_t idx = 0;
1077   while (true) {
1078     if (PluginManager::GetPlatformPluginNameAtIndex(idx).empty()) {
1079       break;
1080     }
1081     ++idx;
1082   }
1083   // +1 for the host platform, which should always appear first in the list.
1084   return idx + 1;
1085 }
1086 
1087 SBStructuredData SBDebugger::GetAvailablePlatformInfoAtIndex(uint32_t idx) {
1088   LLDB_INSTRUMENT_VA(this, idx);
1089 
1090   SBStructuredData data;
1091   auto platform_dict = std::make_unique<StructuredData::Dictionary>();
1092   llvm::StringRef name_str("name"), desc_str("description");
1093 
1094   if (idx == 0) {
1095     PlatformSP host_platform_sp(Platform::GetHostPlatform());
1096     platform_dict->AddStringItem(name_str, host_platform_sp->GetPluginName());
1097     platform_dict->AddStringItem(
1098         desc_str, llvm::StringRef(host_platform_sp->GetDescription()));
1099   } else if (idx > 0) {
1100     llvm::StringRef plugin_name =
1101         PluginManager::GetPlatformPluginNameAtIndex(idx - 1);
1102     if (plugin_name.empty()) {
1103       return data;
1104     }
1105     platform_dict->AddStringItem(name_str, llvm::StringRef(plugin_name));
1106 
1107     llvm::StringRef plugin_desc =
1108         PluginManager::GetPlatformPluginDescriptionAtIndex(idx - 1);
1109     platform_dict->AddStringItem(desc_str, llvm::StringRef(plugin_desc));
1110   }
1111 
1112   data.m_impl_up->SetObjectSP(
1113       StructuredData::ObjectSP(platform_dict.release()));
1114   return data;
1115 }
1116 
1117 void SBDebugger::DispatchInput(void *baton, const void *data, size_t data_len) {
1118   LLDB_INSTRUMENT_VA(this, baton, data, data_len);
1119 
1120   DispatchInput(data, data_len);
1121 }
1122 
1123 void SBDebugger::DispatchInput(const void *data, size_t data_len) {
1124   LLDB_INSTRUMENT_VA(this, data, data_len);
1125 
1126   //    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API));
1127   //
1128   //    if (log)
1129   //        LLDB_LOGF(log, "SBDebugger(%p)::DispatchInput (data=\"%.*s\",
1130   //        size_t=%" PRIu64 ")",
1131   //                     m_opaque_sp.get(),
1132   //                     (int) data_len,
1133   //                     (const char *) data,
1134   //                     (uint64_t)data_len);
1135   //
1136   //    if (m_opaque_sp)
1137   //        m_opaque_sp->DispatchInput ((const char *) data, data_len);
1138 }
1139 
1140 void SBDebugger::DispatchInputInterrupt() {
1141   LLDB_INSTRUMENT_VA(this);
1142 
1143   if (m_opaque_sp)
1144     m_opaque_sp->DispatchInputInterrupt();
1145 }
1146 
1147 void SBDebugger::DispatchInputEndOfFile() {
1148   LLDB_INSTRUMENT_VA(this);
1149 
1150   if (m_opaque_sp)
1151     m_opaque_sp->DispatchInputEndOfFile();
1152 }
1153 
1154 void SBDebugger::PushInputReader(SBInputReader &reader) {
1155   LLDB_INSTRUMENT_VA(this, reader);
1156 }
1157 
1158 void SBDebugger::RunCommandInterpreter(bool auto_handle_events,
1159                                        bool spawn_thread) {
1160   LLDB_INSTRUMENT_VA(this, auto_handle_events, spawn_thread);
1161 
1162   if (m_opaque_sp) {
1163     CommandInterpreterRunOptions options;
1164     options.SetAutoHandleEvents(auto_handle_events);
1165     options.SetSpawnThread(spawn_thread);
1166     m_opaque_sp->GetCommandInterpreter().RunCommandInterpreter(options);
1167   }
1168 }
1169 
1170 void SBDebugger::RunCommandInterpreter(bool auto_handle_events,
1171                                        bool spawn_thread,
1172                                        SBCommandInterpreterRunOptions &options,
1173                                        int &num_errors, bool &quit_requested,
1174                                        bool &stopped_for_crash)
1175 
1176 {
1177   LLDB_INSTRUMENT_VA(this, auto_handle_events, spawn_thread, options,
1178                      num_errors, quit_requested, stopped_for_crash);
1179 
1180   if (m_opaque_sp) {
1181     options.SetAutoHandleEvents(auto_handle_events);
1182     options.SetSpawnThread(spawn_thread);
1183     CommandInterpreter &interp = m_opaque_sp->GetCommandInterpreter();
1184     CommandInterpreterRunResult result =
1185         interp.RunCommandInterpreter(options.ref());
1186     num_errors = result.GetNumErrors();
1187     quit_requested =
1188         result.IsResult(lldb::eCommandInterpreterResultQuitRequested);
1189     stopped_for_crash =
1190         result.IsResult(lldb::eCommandInterpreterResultInferiorCrash);
1191   }
1192 }
1193 
1194 SBCommandInterpreterRunResult SBDebugger::RunCommandInterpreter(
1195     const SBCommandInterpreterRunOptions &options) {
1196   LLDB_INSTRUMENT_VA(this, options);
1197 
1198   if (!m_opaque_sp)
1199     return SBCommandInterpreterRunResult();
1200 
1201   CommandInterpreter &interp = m_opaque_sp->GetCommandInterpreter();
1202   CommandInterpreterRunResult result =
1203       interp.RunCommandInterpreter(options.ref());
1204 
1205   return SBCommandInterpreterRunResult(result);
1206 }
1207 
1208 SBError SBDebugger::RunREPL(lldb::LanguageType language,
1209                             const char *repl_options) {
1210   LLDB_INSTRUMENT_VA(this, language, repl_options);
1211 
1212   SBError error;
1213   if (m_opaque_sp)
1214     error.ref() = m_opaque_sp->RunREPL(language, repl_options);
1215   else
1216     error.SetErrorString("invalid debugger");
1217   return error;
1218 }
1219 
1220 void SBDebugger::reset(const DebuggerSP &debugger_sp) {
1221   m_opaque_sp = debugger_sp;
1222 }
1223 
1224 Debugger *SBDebugger::get() const { return m_opaque_sp.get(); }
1225 
1226 Debugger &SBDebugger::ref() const {
1227   assert(m_opaque_sp.get());
1228   return *m_opaque_sp;
1229 }
1230 
1231 const lldb::DebuggerSP &SBDebugger::get_sp() const { return m_opaque_sp; }
1232 
1233 SBDebugger SBDebugger::FindDebuggerWithID(int id) {
1234   LLDB_INSTRUMENT_VA(id);
1235 
1236   // No need to lock, the debugger list is thread safe
1237   SBDebugger sb_debugger;
1238   DebuggerSP debugger_sp = Debugger::FindDebuggerWithID(id);
1239   if (debugger_sp)
1240     sb_debugger.reset(debugger_sp);
1241   return sb_debugger;
1242 }
1243 
1244 const char *SBDebugger::GetInstanceName() {
1245   LLDB_INSTRUMENT_VA(this);
1246 
1247   return (m_opaque_sp ? m_opaque_sp->GetInstanceName().AsCString() : nullptr);
1248 }
1249 
1250 SBError SBDebugger::SetInternalVariable(const char *var_name, const char *value,
1251                                         const char *debugger_instance_name) {
1252   LLDB_INSTRUMENT_VA(var_name, value, debugger_instance_name);
1253 
1254   SBError sb_error;
1255   DebuggerSP debugger_sp(Debugger::FindDebuggerWithInstanceName(
1256       ConstString(debugger_instance_name)));
1257   Status error;
1258   if (debugger_sp) {
1259     ExecutionContext exe_ctx(
1260         debugger_sp->GetCommandInterpreter().GetExecutionContext());
1261     error = debugger_sp->SetPropertyValue(&exe_ctx, eVarSetOperationAssign,
1262                                           var_name, value);
1263   } else {
1264     error.SetErrorStringWithFormat("invalid debugger instance name '%s'",
1265                                    debugger_instance_name);
1266   }
1267   if (error.Fail())
1268     sb_error.SetError(error);
1269   return sb_error;
1270 }
1271 
1272 SBStringList
1273 SBDebugger::GetInternalVariableValue(const char *var_name,
1274                                      const char *debugger_instance_name) {
1275   LLDB_INSTRUMENT_VA(var_name, debugger_instance_name);
1276 
1277   DebuggerSP debugger_sp(Debugger::FindDebuggerWithInstanceName(
1278       ConstString(debugger_instance_name)));
1279   Status error;
1280   if (debugger_sp) {
1281     ExecutionContext exe_ctx(
1282         debugger_sp->GetCommandInterpreter().GetExecutionContext());
1283     lldb::OptionValueSP value_sp(
1284         debugger_sp->GetPropertyValue(&exe_ctx, var_name, false, error));
1285     if (value_sp) {
1286       StreamString value_strm;
1287       value_sp->DumpValue(&exe_ctx, value_strm, OptionValue::eDumpOptionValue);
1288       const std::string &value_str = std::string(value_strm.GetString());
1289       if (!value_str.empty()) {
1290         StringList string_list;
1291         string_list.SplitIntoLines(value_str);
1292         return SBStringList(&string_list);
1293       }
1294     }
1295   }
1296   return SBStringList();
1297 }
1298 
1299 uint32_t SBDebugger::GetTerminalWidth() const {
1300   LLDB_INSTRUMENT_VA(this);
1301 
1302   return (m_opaque_sp ? m_opaque_sp->GetTerminalWidth() : 0);
1303 }
1304 
1305 void SBDebugger::SetTerminalWidth(uint32_t term_width) {
1306   LLDB_INSTRUMENT_VA(this, term_width);
1307 
1308   if (m_opaque_sp)
1309     m_opaque_sp->SetTerminalWidth(term_width);
1310 }
1311 
1312 const char *SBDebugger::GetPrompt() const {
1313   LLDB_INSTRUMENT_VA(this);
1314 
1315   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1316 
1317   LLDB_LOGF(log, "SBDebugger(%p)::GetPrompt () => \"%s\"",
1318             static_cast<void *>(m_opaque_sp.get()),
1319             (m_opaque_sp ? m_opaque_sp->GetPrompt().str().c_str() : ""));
1320 
1321   return (m_opaque_sp ? ConstString(m_opaque_sp->GetPrompt()).GetCString()
1322                       : nullptr);
1323 }
1324 
1325 void SBDebugger::SetPrompt(const char *prompt) {
1326   LLDB_INSTRUMENT_VA(this, prompt);
1327 
1328   if (m_opaque_sp)
1329     m_opaque_sp->SetPrompt(llvm::StringRef(prompt));
1330 }
1331 
1332 const char *SBDebugger::GetReproducerPath() const {
1333   LLDB_INSTRUMENT_VA(this);
1334 
1335   return (m_opaque_sp
1336               ? ConstString(m_opaque_sp->GetReproducerPath()).GetCString()
1337               : nullptr);
1338 }
1339 
1340 ScriptLanguage SBDebugger::GetScriptLanguage() const {
1341   LLDB_INSTRUMENT_VA(this);
1342 
1343   return (m_opaque_sp ? m_opaque_sp->GetScriptLanguage() : eScriptLanguageNone);
1344 }
1345 
1346 void SBDebugger::SetScriptLanguage(ScriptLanguage script_lang) {
1347   LLDB_INSTRUMENT_VA(this, script_lang);
1348 
1349   if (m_opaque_sp) {
1350     m_opaque_sp->SetScriptLanguage(script_lang);
1351   }
1352 }
1353 
1354 LanguageType SBDebugger::GetREPLLanguage() const {
1355   LLDB_INSTRUMENT_VA(this);
1356 
1357   return (m_opaque_sp ? m_opaque_sp->GetREPLLanguage() : eLanguageTypeUnknown);
1358 }
1359 
1360 void SBDebugger::SetREPLLanguage(LanguageType repl_lang) {
1361   LLDB_INSTRUMENT_VA(this, repl_lang);
1362 
1363   if (m_opaque_sp) {
1364     m_opaque_sp->SetREPLLanguage(repl_lang);
1365   }
1366 }
1367 
1368 bool SBDebugger::SetUseExternalEditor(bool value) {
1369   LLDB_INSTRUMENT_VA(this, value);
1370 
1371   return (m_opaque_sp ? m_opaque_sp->SetUseExternalEditor(value) : false);
1372 }
1373 
1374 bool SBDebugger::GetUseExternalEditor() {
1375   LLDB_INSTRUMENT_VA(this);
1376 
1377   return (m_opaque_sp ? m_opaque_sp->GetUseExternalEditor() : false);
1378 }
1379 
1380 bool SBDebugger::SetUseColor(bool value) {
1381   LLDB_INSTRUMENT_VA(this, value);
1382 
1383   return (m_opaque_sp ? m_opaque_sp->SetUseColor(value) : false);
1384 }
1385 
1386 bool SBDebugger::GetUseColor() const {
1387   LLDB_INSTRUMENT_VA(this);
1388 
1389   return (m_opaque_sp ? m_opaque_sp->GetUseColor() : false);
1390 }
1391 
1392 bool SBDebugger::SetUseSourceCache(bool value) {
1393   LLDB_INSTRUMENT_VA(this, value);
1394 
1395   return (m_opaque_sp ? m_opaque_sp->SetUseSourceCache(value) : false);
1396 }
1397 
1398 bool SBDebugger::GetUseSourceCache() const {
1399   LLDB_INSTRUMENT_VA(this);
1400 
1401   return (m_opaque_sp ? m_opaque_sp->GetUseSourceCache() : false);
1402 }
1403 
1404 bool SBDebugger::GetDescription(SBStream &description) {
1405   LLDB_INSTRUMENT_VA(this, description);
1406 
1407   Stream &strm = description.ref();
1408 
1409   if (m_opaque_sp) {
1410     const char *name = m_opaque_sp->GetInstanceName().AsCString();
1411     user_id_t id = m_opaque_sp->GetID();
1412     strm.Printf("Debugger (instance: \"%s\", id: %" PRIu64 ")", name, id);
1413   } else
1414     strm.PutCString("No value");
1415 
1416   return true;
1417 }
1418 
1419 user_id_t SBDebugger::GetID() {
1420   LLDB_INSTRUMENT_VA(this);
1421 
1422   return (m_opaque_sp ? m_opaque_sp->GetID() : LLDB_INVALID_UID);
1423 }
1424 
1425 SBError SBDebugger::SetCurrentPlatform(const char *platform_name_cstr) {
1426   LLDB_INSTRUMENT_VA(this, platform_name_cstr);
1427 
1428   SBError sb_error;
1429   if (m_opaque_sp) {
1430     if (platform_name_cstr && platform_name_cstr[0]) {
1431       ConstString platform_name(platform_name_cstr);
1432       PlatformSP platform_sp(Platform::Find(platform_name));
1433 
1434       if (platform_sp) {
1435         // Already have a platform with this name, just select it
1436         m_opaque_sp->GetPlatformList().SetSelectedPlatform(platform_sp);
1437       } else {
1438         // We don't have a platform by this name yet, create one
1439         platform_sp = Platform::Create(platform_name, sb_error.ref());
1440         if (platform_sp) {
1441           // We created the platform, now append and select it
1442           bool make_selected = true;
1443           m_opaque_sp->GetPlatformList().Append(platform_sp, make_selected);
1444         }
1445       }
1446     } else {
1447       sb_error.ref().SetErrorString("invalid platform name");
1448     }
1449   } else {
1450     sb_error.ref().SetErrorString("invalid debugger");
1451   }
1452   return sb_error;
1453 }
1454 
1455 bool SBDebugger::SetCurrentPlatformSDKRoot(const char *sysroot) {
1456   LLDB_INSTRUMENT_VA(this, sysroot);
1457 
1458   if (SBPlatform platform = GetSelectedPlatform()) {
1459     platform.SetSDKRoot(sysroot);
1460     return true;
1461   }
1462   return false;
1463 }
1464 
1465 bool SBDebugger::GetCloseInputOnEOF() const {
1466   LLDB_INSTRUMENT_VA(this);
1467 
1468   return (m_opaque_sp ? m_opaque_sp->GetCloseInputOnEOF() : false);
1469 }
1470 
1471 void SBDebugger::SetCloseInputOnEOF(bool b) {
1472   LLDB_INSTRUMENT_VA(this, b);
1473 
1474   if (m_opaque_sp)
1475     m_opaque_sp->SetCloseInputOnEOF(b);
1476 }
1477 
1478 SBTypeCategory SBDebugger::GetCategory(const char *category_name) {
1479   LLDB_INSTRUMENT_VA(this, category_name);
1480 
1481   if (!category_name || *category_name == 0)
1482     return SBTypeCategory();
1483 
1484   TypeCategoryImplSP category_sp;
1485 
1486   if (DataVisualization::Categories::GetCategory(ConstString(category_name),
1487                                                  category_sp, false)) {
1488     return SBTypeCategory(category_sp);
1489   } else {
1490     return SBTypeCategory();
1491   }
1492 }
1493 
1494 SBTypeCategory SBDebugger::GetCategory(lldb::LanguageType lang_type) {
1495   LLDB_INSTRUMENT_VA(this, lang_type);
1496 
1497   TypeCategoryImplSP category_sp;
1498   if (DataVisualization::Categories::GetCategory(lang_type, category_sp)) {
1499     return SBTypeCategory(category_sp);
1500   } else {
1501     return SBTypeCategory();
1502   }
1503 }
1504 
1505 SBTypeCategory SBDebugger::CreateCategory(const char *category_name) {
1506   LLDB_INSTRUMENT_VA(this, category_name);
1507 
1508   if (!category_name || *category_name == 0)
1509     return SBTypeCategory();
1510 
1511   TypeCategoryImplSP category_sp;
1512 
1513   if (DataVisualization::Categories::GetCategory(ConstString(category_name),
1514                                                  category_sp, true)) {
1515     return SBTypeCategory(category_sp);
1516   } else {
1517     return SBTypeCategory();
1518   }
1519 }
1520 
1521 bool SBDebugger::DeleteCategory(const char *category_name) {
1522   LLDB_INSTRUMENT_VA(this, category_name);
1523 
1524   if (!category_name || *category_name == 0)
1525     return false;
1526 
1527   return DataVisualization::Categories::Delete(ConstString(category_name));
1528 }
1529 
1530 uint32_t SBDebugger::GetNumCategories() {
1531   LLDB_INSTRUMENT_VA(this);
1532 
1533   return DataVisualization::Categories::GetCount();
1534 }
1535 
1536 SBTypeCategory SBDebugger::GetCategoryAtIndex(uint32_t index) {
1537   LLDB_INSTRUMENT_VA(this, index);
1538 
1539   return SBTypeCategory(
1540       DataVisualization::Categories::GetCategoryAtIndex(index));
1541 }
1542 
1543 SBTypeCategory SBDebugger::GetDefaultCategory() {
1544   LLDB_INSTRUMENT_VA(this);
1545 
1546   return GetCategory("default");
1547 }
1548 
1549 SBTypeFormat SBDebugger::GetFormatForType(SBTypeNameSpecifier type_name) {
1550   LLDB_INSTRUMENT_VA(this, type_name);
1551 
1552   SBTypeCategory default_category_sb = GetDefaultCategory();
1553   if (default_category_sb.GetEnabled())
1554     return default_category_sb.GetFormatForType(type_name);
1555   return SBTypeFormat();
1556 }
1557 
1558 SBTypeSummary SBDebugger::GetSummaryForType(SBTypeNameSpecifier type_name) {
1559   LLDB_INSTRUMENT_VA(this, type_name);
1560 
1561   if (!type_name.IsValid())
1562     return SBTypeSummary();
1563   return SBTypeSummary(DataVisualization::GetSummaryForType(type_name.GetSP()));
1564 }
1565 
1566 SBTypeFilter SBDebugger::GetFilterForType(SBTypeNameSpecifier type_name) {
1567   LLDB_INSTRUMENT_VA(this, type_name);
1568 
1569   if (!type_name.IsValid())
1570     return SBTypeFilter();
1571   return SBTypeFilter(DataVisualization::GetFilterForType(type_name.GetSP()));
1572 }
1573 
1574 SBTypeSynthetic SBDebugger::GetSyntheticForType(SBTypeNameSpecifier type_name) {
1575   LLDB_INSTRUMENT_VA(this, type_name);
1576 
1577   if (!type_name.IsValid())
1578     return SBTypeSynthetic();
1579   return SBTypeSynthetic(
1580       DataVisualization::GetSyntheticForType(type_name.GetSP()));
1581 }
1582 
1583 static llvm::ArrayRef<const char *> GetCategoryArray(const char **categories) {
1584   if (categories == nullptr)
1585     return {};
1586   size_t len = 0;
1587   while (categories[len] != nullptr)
1588     ++len;
1589   return llvm::makeArrayRef(categories, len);
1590 }
1591 
1592 bool SBDebugger::EnableLog(const char *channel, const char **categories) {
1593   LLDB_INSTRUMENT_VA(this, channel, categories);
1594 
1595   if (m_opaque_sp) {
1596     uint32_t log_options =
1597         LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
1598     std::string error;
1599     llvm::raw_string_ostream error_stream(error);
1600     return m_opaque_sp->EnableLog(channel, GetCategoryArray(categories), "",
1601                                   log_options, error_stream);
1602   } else
1603     return false;
1604 }
1605 
1606 void SBDebugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1607                                     void *baton) {
1608   LLDB_INSTRUMENT_VA(this, log_callback, baton);
1609 
1610   if (m_opaque_sp) {
1611     return m_opaque_sp->SetLoggingCallback(log_callback, baton);
1612   }
1613 }
1614