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