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