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