]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/API/SBDebugger.cpp
Update our devicetree to 4.19 for arm and arm64
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / API / SBDebugger.cpp
1 //===-- SBDebugger.cpp ------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 // C Includes
11 // C++ Includes
12 // Other libraries and framework includes
13 // Project includes
14 #include "lldb/API/SBDebugger.h"
15
16 #include "lldb/lldb-private.h"
17
18 #include "lldb/API/SBBroadcaster.h"
19 #include "lldb/API/SBCommandInterpreter.h"
20 #include "lldb/API/SBCommandReturnObject.h"
21 #include "lldb/API/SBError.h"
22 #include "lldb/API/SBEvent.h"
23 #include "lldb/API/SBFrame.h"
24 #include "lldb/API/SBListener.h"
25 #include "lldb/API/SBProcess.h"
26 #include "lldb/API/SBSourceManager.h"
27 #include "lldb/API/SBStream.h"
28 #include "lldb/API/SBStringList.h"
29 #include "lldb/API/SBStructuredData.h"
30 #include "lldb/API/SBTarget.h"
31 #include "lldb/API/SBThread.h"
32 #include "lldb/API/SBTypeCategory.h"
33 #include "lldb/API/SBTypeFilter.h"
34 #include "lldb/API/SBTypeFormat.h"
35 #include "lldb/API/SBTypeNameSpecifier.h"
36 #include "lldb/API/SBTypeSummary.h"
37 #include "lldb/API/SBTypeSynthetic.h"
38 #include "lldb/API/SystemInitializerFull.h"
39
40 #include "lldb/Core/Debugger.h"
41 #include "lldb/Core/PluginManager.h"
42 #include "lldb/Core/State.h"
43 #include "lldb/Core/StreamFile.h"
44 #include "lldb/Core/StructuredDataImpl.h"
45 #include "lldb/DataFormatters/DataVisualization.h"
46 #include "lldb/Initialization/SystemLifetimeManager.h"
47 #include "lldb/Interpreter/Args.h"
48 #include "lldb/Interpreter/CommandInterpreter.h"
49 #include "lldb/Interpreter/OptionGroupPlatform.h"
50 #include "lldb/Target/Process.h"
51 #include "lldb/Target/TargetList.h"
52
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/StringRef.h"
55 #include "llvm/Support/DynamicLibrary.h"
56 #include "llvm/Support/ManagedStatic.h"
57
58 using namespace lldb;
59 using namespace lldb_private;
60
61 static llvm::sys::DynamicLibrary LoadPlugin(const lldb::DebuggerSP &debugger_sp,
62                                             const FileSpec &spec,
63                                             Status &error) {
64   llvm::sys::DynamicLibrary dynlib =
65       llvm::sys::DynamicLibrary::getPermanentLibrary(spec.GetPath().c_str());
66   if (dynlib.isValid()) {
67     typedef bool (*LLDBCommandPluginInit)(lldb::SBDebugger & debugger);
68
69     lldb::SBDebugger debugger_sb(debugger_sp);
70     // This calls the bool lldb::PluginInitialize(lldb::SBDebugger debugger)
71     // function.
72     // TODO: mangle this differently for your system - on OSX, the first
73     // underscore needs to be removed and the second one stays
74     LLDBCommandPluginInit init_func =
75         (LLDBCommandPluginInit)(uintptr_t)dynlib.getAddressOfSymbol(
76             "_ZN4lldb16PluginInitializeENS_10SBDebuggerE");
77     if (init_func) {
78       if (init_func(debugger_sb))
79         return dynlib;
80       else
81         error.SetErrorString("plug-in refused to load "
82                              "(lldb::PluginInitialize(lldb::SBDebugger) "
83                              "returned false)");
84     } else {
85       error.SetErrorString("plug-in is missing the required initialization: "
86                            "lldb::PluginInitialize(lldb::SBDebugger)");
87     }
88   } else {
89     if (spec.Exists())
90       error.SetErrorString("this file does not represent a loadable dylib");
91     else
92       error.SetErrorString("no such file");
93   }
94   return llvm::sys::DynamicLibrary();
95 }
96
97 static llvm::ManagedStatic<SystemLifetimeManager> g_debugger_lifetime;
98
99 SBError SBInputReader::Initialize(
100     lldb::SBDebugger &sb_debugger,
101     unsigned long (*)(void *, lldb::SBInputReader *, lldb::InputReaderAction,
102                       char const *, unsigned long),
103     void *, lldb::InputReaderGranularity, char const *, char const *, bool) {
104   return SBError();
105 }
106
107 void SBInputReader::SetIsDone(bool) {}
108
109 bool SBInputReader::IsActive() const { return false; }
110
111 SBDebugger::SBDebugger() = default;
112
113 SBDebugger::SBDebugger(const lldb::DebuggerSP &debugger_sp)
114     : m_opaque_sp(debugger_sp) {}
115
116 SBDebugger::SBDebugger(const SBDebugger &rhs) : m_opaque_sp(rhs.m_opaque_sp) {}
117
118 SBDebugger::~SBDebugger() = default;
119
120 SBDebugger &SBDebugger::operator=(const SBDebugger &rhs) {
121   if (this != &rhs) {
122     m_opaque_sp = rhs.m_opaque_sp;
123   }
124   return *this;
125 }
126
127 void SBDebugger::Initialize() {
128   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
129
130   if (log)
131     log->Printf("SBDebugger::Initialize ()");
132
133   g_debugger_lifetime->Initialize(llvm::make_unique<SystemInitializerFull>(),
134                                   LoadPlugin);
135 }
136
137 void SBDebugger::Terminate() { g_debugger_lifetime->Terminate(); }
138
139 void SBDebugger::Clear() {
140   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
141
142   if (log)
143     log->Printf("SBDebugger(%p)::Clear ()",
144                 static_cast<void *>(m_opaque_sp.get()));
145
146   if (m_opaque_sp)
147     m_opaque_sp->ClearIOHandlers();
148
149   m_opaque_sp.reset();
150 }
151
152 SBDebugger SBDebugger::Create() {
153   return SBDebugger::Create(false, nullptr, nullptr);
154 }
155
156 SBDebugger SBDebugger::Create(bool source_init_files) {
157   return SBDebugger::Create(source_init_files, nullptr, nullptr);
158 }
159
160 SBDebugger SBDebugger::Create(bool source_init_files,
161                               lldb::LogOutputCallback callback, void *baton)
162
163 {
164   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
165
166   SBDebugger debugger;
167
168   // Currently we have issues if this function is called simultaneously on two
169   // different
170   // threads. The issues mainly revolve around the fact that the
171   // lldb_private::FormatManager
172   // uses global collections and having two threads parsing the .lldbinit files
173   // can cause
174   // mayhem. So to get around this for now we need to use a mutex to prevent bad
175   // things
176   // from happening.
177   static std::recursive_mutex g_mutex;
178   std::lock_guard<std::recursive_mutex> guard(g_mutex);
179
180   debugger.reset(Debugger::CreateInstance(callback, baton));
181
182   if (log) {
183     SBStream sstr;
184     debugger.GetDescription(sstr);
185     log->Printf("SBDebugger::Create () => SBDebugger(%p): %s",
186                 static_cast<void *>(debugger.m_opaque_sp.get()),
187                 sstr.GetData());
188   }
189
190   SBCommandInterpreter interp = debugger.GetCommandInterpreter();
191   if (source_init_files) {
192     interp.get()->SkipLLDBInitFiles(false);
193     interp.get()->SkipAppInitFiles(false);
194     SBCommandReturnObject result;
195     interp.SourceInitFileInHomeDirectory(result);
196   } else {
197     interp.get()->SkipLLDBInitFiles(true);
198     interp.get()->SkipAppInitFiles(true);
199   }
200   return debugger;
201 }
202
203 void SBDebugger::Destroy(SBDebugger &debugger) {
204   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
205
206   if (log) {
207     SBStream sstr;
208     debugger.GetDescription(sstr);
209     log->Printf("SBDebugger::Destroy () => SBDebugger(%p): %s",
210                 static_cast<void *>(debugger.m_opaque_sp.get()),
211                 sstr.GetData());
212   }
213
214   Debugger::Destroy(debugger.m_opaque_sp);
215
216   if (debugger.m_opaque_sp.get() != nullptr)
217     debugger.m_opaque_sp.reset();
218 }
219
220 void SBDebugger::MemoryPressureDetected() {
221   // Since this function can be call asynchronously, we allow it to be
222   // non-mandatory. We have seen deadlocks with this function when called
223   // so we need to safeguard against this until we can determine what is
224   // causing the deadlocks.
225   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
226
227   const bool mandatory = false;
228   if (log) {
229     log->Printf("SBDebugger::MemoryPressureDetected (), mandatory = %d",
230                 mandatory);
231   }
232
233   ModuleList::RemoveOrphanSharedModules(mandatory);
234 }
235
236 bool SBDebugger::IsValid() const { return m_opaque_sp.get() != nullptr; }
237
238 void SBDebugger::SetAsync(bool b) {
239   if (m_opaque_sp)
240     m_opaque_sp->SetAsyncExecution(b);
241 }
242
243 bool SBDebugger::GetAsync() {
244   return (m_opaque_sp ? m_opaque_sp->GetAsyncExecution() : false);
245 }
246
247 void SBDebugger::SkipLLDBInitFiles(bool b) {
248   if (m_opaque_sp)
249     m_opaque_sp->GetCommandInterpreter().SkipLLDBInitFiles(b);
250 }
251
252 void SBDebugger::SkipAppInitFiles(bool b) {
253   if (m_opaque_sp)
254     m_opaque_sp->GetCommandInterpreter().SkipAppInitFiles(b);
255 }
256
257 // Shouldn't really be settable after initialization as this could cause lots of
258 // problems; don't want users
259 // trying to switch modes in the middle of a debugging session.
260 void SBDebugger::SetInputFileHandle(FILE *fh, bool transfer_ownership) {
261   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
262
263   if (log)
264     log->Printf(
265         "SBDebugger(%p)::SetInputFileHandle (fh=%p, transfer_ownership=%i)",
266         static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(fh),
267         transfer_ownership);
268
269   if (m_opaque_sp)
270     m_opaque_sp->SetInputFileHandle(fh, transfer_ownership);
271 }
272
273 void SBDebugger::SetOutputFileHandle(FILE *fh, bool transfer_ownership) {
274   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
275
276   if (log)
277     log->Printf(
278         "SBDebugger(%p)::SetOutputFileHandle (fh=%p, transfer_ownership=%i)",
279         static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(fh),
280         transfer_ownership);
281
282   if (m_opaque_sp)
283     m_opaque_sp->SetOutputFileHandle(fh, transfer_ownership);
284 }
285
286 void SBDebugger::SetErrorFileHandle(FILE *fh, bool transfer_ownership) {
287   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
288
289   if (log)
290     log->Printf(
291         "SBDebugger(%p)::SetErrorFileHandle (fh=%p, transfer_ownership=%i)",
292         static_cast<void *>(m_opaque_sp.get()), static_cast<void *>(fh),
293         transfer_ownership);
294
295   if (m_opaque_sp)
296     m_opaque_sp->SetErrorFileHandle(fh, transfer_ownership);
297 }
298
299 FILE *SBDebugger::GetInputFileHandle() {
300   if (m_opaque_sp) {
301     StreamFileSP stream_file_sp(m_opaque_sp->GetInputFile());
302     if (stream_file_sp)
303       return stream_file_sp->GetFile().GetStream();
304   }
305   return nullptr;
306 }
307
308 FILE *SBDebugger::GetOutputFileHandle() {
309   if (m_opaque_sp) {
310     StreamFileSP stream_file_sp(m_opaque_sp->GetOutputFile());
311     if (stream_file_sp)
312       return stream_file_sp->GetFile().GetStream();
313   }
314   return nullptr;
315 }
316
317 FILE *SBDebugger::GetErrorFileHandle() {
318   if (m_opaque_sp) {
319     StreamFileSP stream_file_sp(m_opaque_sp->GetErrorFile());
320     if (stream_file_sp)
321       return stream_file_sp->GetFile().GetStream();
322   }
323   return nullptr;
324 }
325
326 void SBDebugger::SaveInputTerminalState() {
327   if (m_opaque_sp)
328     m_opaque_sp->SaveInputTerminalState();
329 }
330
331 void SBDebugger::RestoreInputTerminalState() {
332   if (m_opaque_sp)
333     m_opaque_sp->RestoreInputTerminalState();
334 }
335 SBCommandInterpreter SBDebugger::GetCommandInterpreter() {
336   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
337
338   SBCommandInterpreter sb_interpreter;
339   if (m_opaque_sp)
340     sb_interpreter.reset(&m_opaque_sp->GetCommandInterpreter());
341
342   if (log)
343     log->Printf(
344         "SBDebugger(%p)::GetCommandInterpreter () => SBCommandInterpreter(%p)",
345         static_cast<void *>(m_opaque_sp.get()),
346         static_cast<void *>(sb_interpreter.get()));
347
348   return sb_interpreter;
349 }
350
351 void SBDebugger::HandleCommand(const char *command) {
352   if (m_opaque_sp) {
353     TargetSP target_sp(m_opaque_sp->GetSelectedTarget());
354     std::unique_lock<std::recursive_mutex> lock;
355     if (target_sp)
356       lock = std::unique_lock<std::recursive_mutex>(target_sp->GetAPIMutex());
357
358     SBCommandInterpreter sb_interpreter(GetCommandInterpreter());
359     SBCommandReturnObject result;
360
361     sb_interpreter.HandleCommand(command, result, false);
362
363     if (GetErrorFileHandle() != nullptr)
364       result.PutError(GetErrorFileHandle());
365     if (GetOutputFileHandle() != nullptr)
366       result.PutOutput(GetOutputFileHandle());
367
368     if (!m_opaque_sp->GetAsyncExecution()) {
369       SBProcess process(GetCommandInterpreter().GetProcess());
370       ProcessSP process_sp(process.GetSP());
371       if (process_sp) {
372         EventSP event_sp;
373         ListenerSP lldb_listener_sp = m_opaque_sp->GetListener();
374         while (lldb_listener_sp->GetEventForBroadcaster(
375             process_sp.get(), event_sp, std::chrono::seconds(0))) {
376           SBEvent event(event_sp);
377           HandleProcessEvent(process, event, GetOutputFileHandle(),
378                              GetErrorFileHandle());
379         }
380       }
381     }
382   }
383 }
384
385 SBListener SBDebugger::GetListener() {
386   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
387
388   SBListener sb_listener;
389   if (m_opaque_sp)
390     sb_listener.reset(m_opaque_sp->GetListener());
391
392   if (log)
393     log->Printf("SBDebugger(%p)::GetListener () => SBListener(%p)",
394                 static_cast<void *>(m_opaque_sp.get()),
395                 static_cast<void *>(sb_listener.get()));
396
397   return sb_listener;
398 }
399
400 void SBDebugger::HandleProcessEvent(const SBProcess &process,
401                                     const SBEvent &event, FILE *out,
402                                     FILE *err) {
403   if (!process.IsValid())
404     return;
405
406   TargetSP target_sp(process.GetTarget().GetSP());
407   if (!target_sp)
408     return;
409
410   const uint32_t event_type = event.GetType();
411   char stdio_buffer[1024];
412   size_t len;
413
414   std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
415
416   if (event_type &
417       (Process::eBroadcastBitSTDOUT | Process::eBroadcastBitStateChanged)) {
418     // Drain stdout when we stop just in case we have any bytes
419     while ((len = process.GetSTDOUT(stdio_buffer, sizeof(stdio_buffer))) > 0)
420       if (out != nullptr)
421         ::fwrite(stdio_buffer, 1, len, out);
422   }
423
424   if (event_type &
425       (Process::eBroadcastBitSTDERR | Process::eBroadcastBitStateChanged)) {
426     // Drain stderr when we stop just in case we have any bytes
427     while ((len = process.GetSTDERR(stdio_buffer, sizeof(stdio_buffer))) > 0)
428       if (err != nullptr)
429         ::fwrite(stdio_buffer, 1, len, err);
430   }
431
432   if (event_type & Process::eBroadcastBitStateChanged) {
433     StateType event_state = SBProcess::GetStateFromEvent(event);
434
435     if (event_state == eStateInvalid)
436       return;
437
438     bool is_stopped = StateIsStoppedState(event_state);
439     if (!is_stopped)
440       process.ReportEventState(event, out);
441   }
442 }
443
444 SBSourceManager SBDebugger::GetSourceManager() {
445   SBSourceManager sb_source_manager(*this);
446   return sb_source_manager;
447 }
448
449 bool SBDebugger::GetDefaultArchitecture(char *arch_name, size_t arch_name_len) {
450   if (arch_name && arch_name_len) {
451     ArchSpec default_arch = Target::GetDefaultArchitecture();
452
453     if (default_arch.IsValid()) {
454       const std::string &triple_str = default_arch.GetTriple().str();
455       if (!triple_str.empty())
456         ::snprintf(arch_name, arch_name_len, "%s", triple_str.c_str());
457       else
458         ::snprintf(arch_name, arch_name_len, "%s",
459                    default_arch.GetArchitectureName());
460       return true;
461     }
462   }
463   if (arch_name && arch_name_len)
464     arch_name[0] = '\0';
465   return false;
466 }
467
468 bool SBDebugger::SetDefaultArchitecture(const char *arch_name) {
469   if (arch_name) {
470     ArchSpec arch(arch_name);
471     if (arch.IsValid()) {
472       Target::SetDefaultArchitecture(arch);
473       return true;
474     }
475   }
476   return false;
477 }
478
479 ScriptLanguage
480 SBDebugger::GetScriptingLanguage(const char *script_language_name) {
481   if (!script_language_name) return eScriptLanguageDefault;
482   return Args::StringToScriptLanguage(llvm::StringRef(script_language_name),
483                                       eScriptLanguageDefault, nullptr);
484 }
485
486 const char *SBDebugger::GetVersionString() {
487   return lldb_private::GetVersion();
488 }
489
490 const char *SBDebugger::StateAsCString(StateType state) {
491   return lldb_private::StateAsCString(state);
492 }
493
494 bool SBDebugger::StateIsRunningState(StateType state) {
495   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
496
497   const bool result = lldb_private::StateIsRunningState(state);
498   if (log)
499     log->Printf("SBDebugger::StateIsRunningState (state=%s) => %i",
500                 StateAsCString(state), result);
501
502   return result;
503 }
504
505 bool SBDebugger::StateIsStoppedState(StateType state) {
506   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
507
508   const bool result = lldb_private::StateIsStoppedState(state, false);
509   if (log)
510     log->Printf("SBDebugger::StateIsStoppedState (state=%s) => %i",
511                 StateAsCString(state), result);
512
513   return result;
514 }
515
516 lldb::SBTarget SBDebugger::CreateTarget(const char *filename,
517                                         const char *target_triple,
518                                         const char *platform_name,
519                                         bool add_dependent_modules,
520                                         lldb::SBError &sb_error) {
521   SBTarget sb_target;
522   TargetSP target_sp;
523   if (m_opaque_sp) {
524     sb_error.Clear();
525     OptionGroupPlatform platform_options(false);
526     platform_options.SetPlatformName(platform_name);
527
528     sb_error.ref() = m_opaque_sp->GetTargetList().CreateTarget(
529         *m_opaque_sp, filename, target_triple, add_dependent_modules,
530         &platform_options, target_sp);
531
532     if (sb_error.Success())
533       sb_target.SetSP(target_sp);
534   } else {
535     sb_error.SetErrorString("invalid debugger");
536   }
537
538   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
539   if (log)
540     log->Printf("SBDebugger(%p)::CreateTarget (filename=\"%s\", triple=%s, "
541                 "platform_name=%s, add_dependent_modules=%u, error=%s) => "
542                 "SBTarget(%p)",
543                 static_cast<void *>(m_opaque_sp.get()), filename, target_triple,
544                 platform_name, add_dependent_modules, sb_error.GetCString(),
545                 static_cast<void *>(target_sp.get()));
546
547   return sb_target;
548 }
549
550 SBTarget
551 SBDebugger::CreateTargetWithFileAndTargetTriple(const char *filename,
552                                                 const char *target_triple) {
553   SBTarget sb_target;
554   TargetSP target_sp;
555   if (m_opaque_sp) {
556     const bool add_dependent_modules = true;
557     Status error(m_opaque_sp->GetTargetList().CreateTarget(
558         *m_opaque_sp, filename, target_triple, add_dependent_modules, nullptr,
559         target_sp));
560     sb_target.SetSP(target_sp);
561   }
562
563   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
564   if (log)
565     log->Printf("SBDebugger(%p)::CreateTargetWithFileAndTargetTriple "
566                 "(filename=\"%s\", triple=%s) => SBTarget(%p)",
567                 static_cast<void *>(m_opaque_sp.get()), filename, target_triple,
568                 static_cast<void *>(target_sp.get()));
569
570   return sb_target;
571 }
572
573 SBTarget SBDebugger::CreateTargetWithFileAndArch(const char *filename,
574                                                  const char *arch_cstr) {
575   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
576
577   SBTarget sb_target;
578   TargetSP target_sp;
579   if (m_opaque_sp) {
580     Status error;
581     const bool add_dependent_modules = true;
582
583     error = m_opaque_sp->GetTargetList().CreateTarget(
584         *m_opaque_sp, filename, arch_cstr, add_dependent_modules, nullptr,
585         target_sp);
586
587     if (error.Success()) {
588       m_opaque_sp->GetTargetList().SetSelectedTarget(target_sp.get());
589       sb_target.SetSP(target_sp);
590     }
591   }
592
593   if (log)
594     log->Printf("SBDebugger(%p)::CreateTargetWithFileAndArch (filename=\"%s\", "
595                 "arch=%s) => SBTarget(%p)",
596                 static_cast<void *>(m_opaque_sp.get()), filename, arch_cstr,
597                 static_cast<void *>(target_sp.get()));
598
599   return sb_target;
600 }
601
602 SBTarget SBDebugger::CreateTarget(const char *filename) {
603   SBTarget sb_target;
604   TargetSP target_sp;
605   if (m_opaque_sp) {
606     Status error;
607     const bool add_dependent_modules = true;
608     error = m_opaque_sp->GetTargetList().CreateTarget(
609         *m_opaque_sp, filename, "", add_dependent_modules, nullptr, target_sp);
610
611     if (error.Success()) {
612       m_opaque_sp->GetTargetList().SetSelectedTarget(target_sp.get());
613       sb_target.SetSP(target_sp);
614     }
615   }
616   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
617   if (log)
618     log->Printf(
619         "SBDebugger(%p)::CreateTarget (filename=\"%s\") => SBTarget(%p)",
620         static_cast<void *>(m_opaque_sp.get()), filename,
621         static_cast<void *>(target_sp.get()));
622   return sb_target;
623 }
624
625 SBTarget SBDebugger::GetDummyTarget() {
626   SBTarget sb_target;
627   if (m_opaque_sp) {
628       sb_target.SetSP(m_opaque_sp->GetDummyTarget()->shared_from_this());
629   }
630   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
631   if (log)
632     log->Printf(
633         "SBDebugger(%p)::GetDummyTarget() => SBTarget(%p)",
634         static_cast<void *>(m_opaque_sp.get()),
635         static_cast<void *>(sb_target.GetSP().get()));
636   return sb_target;
637 }
638
639 bool SBDebugger::DeleteTarget(lldb::SBTarget &target) {
640   bool result = false;
641   if (m_opaque_sp) {
642     TargetSP target_sp(target.GetSP());
643     if (target_sp) {
644       // No need to lock, the target list is thread safe
645       result = m_opaque_sp->GetTargetList().DeleteTarget(target_sp);
646       target_sp->Destroy();
647       target.Clear();
648       const bool mandatory = true;
649       ModuleList::RemoveOrphanSharedModules(mandatory);
650     }
651   }
652
653   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
654   if (log)
655     log->Printf("SBDebugger(%p)::DeleteTarget (SBTarget(%p)) => %i",
656                 static_cast<void *>(m_opaque_sp.get()),
657                 static_cast<void *>(target.m_opaque_sp.get()), result);
658
659   return result;
660 }
661
662 SBTarget SBDebugger::GetTargetAtIndex(uint32_t idx) {
663   SBTarget sb_target;
664   if (m_opaque_sp) {
665     // No need to lock, the target list is thread safe
666     sb_target.SetSP(m_opaque_sp->GetTargetList().GetTargetAtIndex(idx));
667   }
668   return sb_target;
669 }
670
671 uint32_t SBDebugger::GetIndexOfTarget(lldb::SBTarget target) {
672
673   lldb::TargetSP target_sp = target.GetSP();
674   if (!target_sp)
675     return UINT32_MAX;
676
677   if (!m_opaque_sp)
678     return UINT32_MAX;
679
680   return m_opaque_sp->GetTargetList().GetIndexOfTarget(target.GetSP());
681 }
682
683 SBTarget SBDebugger::FindTargetWithProcessID(lldb::pid_t pid) {
684   SBTarget sb_target;
685   if (m_opaque_sp) {
686     // No need to lock, the target list is thread safe
687     sb_target.SetSP(m_opaque_sp->GetTargetList().FindTargetWithProcessID(pid));
688   }
689   return sb_target;
690 }
691
692 SBTarget SBDebugger::FindTargetWithFileAndArch(const char *filename,
693                                                const char *arch_name) {
694   SBTarget sb_target;
695   if (m_opaque_sp && filename && filename[0]) {
696     // No need to lock, the target list is thread safe
697     ArchSpec arch = Platform::GetAugmentedArchSpec(
698         m_opaque_sp->GetPlatformList().GetSelectedPlatform().get(), arch_name);
699     TargetSP target_sp(
700         m_opaque_sp->GetTargetList().FindTargetWithExecutableAndArchitecture(
701             FileSpec(filename, false), arch_name ? &arch : nullptr));
702     sb_target.SetSP(target_sp);
703   }
704   return sb_target;
705 }
706
707 SBTarget SBDebugger::FindTargetWithLLDBProcess(const ProcessSP &process_sp) {
708   SBTarget sb_target;
709   if (m_opaque_sp) {
710     // No need to lock, the target list is thread safe
711     sb_target.SetSP(
712         m_opaque_sp->GetTargetList().FindTargetWithProcess(process_sp.get()));
713   }
714   return sb_target;
715 }
716
717 uint32_t SBDebugger::GetNumTargets() {
718   if (m_opaque_sp) {
719     // No need to lock, the target list is thread safe
720     return m_opaque_sp->GetTargetList().GetNumTargets();
721   }
722   return 0;
723 }
724
725 SBTarget SBDebugger::GetSelectedTarget() {
726   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
727
728   SBTarget sb_target;
729   TargetSP target_sp;
730   if (m_opaque_sp) {
731     // No need to lock, the target list is thread safe
732     target_sp = m_opaque_sp->GetTargetList().GetSelectedTarget();
733     sb_target.SetSP(target_sp);
734   }
735
736   if (log) {
737     SBStream sstr;
738     sb_target.GetDescription(sstr, eDescriptionLevelBrief);
739     log->Printf("SBDebugger(%p)::GetSelectedTarget () => SBTarget(%p): %s",
740                 static_cast<void *>(m_opaque_sp.get()),
741                 static_cast<void *>(target_sp.get()), sstr.GetData());
742   }
743
744   return sb_target;
745 }
746
747 void SBDebugger::SetSelectedTarget(SBTarget &sb_target) {
748   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
749
750   TargetSP target_sp(sb_target.GetSP());
751   if (m_opaque_sp) {
752     m_opaque_sp->GetTargetList().SetSelectedTarget(target_sp.get());
753   }
754   if (log) {
755     SBStream sstr;
756     sb_target.GetDescription(sstr, eDescriptionLevelBrief);
757     log->Printf("SBDebugger(%p)::SetSelectedTarget () => SBTarget(%p): %s",
758                 static_cast<void *>(m_opaque_sp.get()),
759                 static_cast<void *>(target_sp.get()), sstr.GetData());
760   }
761 }
762
763 SBPlatform SBDebugger::GetSelectedPlatform() {
764   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
765
766   SBPlatform sb_platform;
767   DebuggerSP debugger_sp(m_opaque_sp);
768   if (debugger_sp) {
769     sb_platform.SetSP(debugger_sp->GetPlatformList().GetSelectedPlatform());
770   }
771   if (log)
772     log->Printf("SBDebugger(%p)::GetSelectedPlatform () => SBPlatform(%p): %s",
773                 static_cast<void *>(m_opaque_sp.get()),
774                 static_cast<void *>(sb_platform.GetSP().get()),
775                 sb_platform.GetName());
776   return sb_platform;
777 }
778
779 void SBDebugger::SetSelectedPlatform(SBPlatform &sb_platform) {
780   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
781
782   DebuggerSP debugger_sp(m_opaque_sp);
783   if (debugger_sp) {
784     debugger_sp->GetPlatformList().SetSelectedPlatform(sb_platform.GetSP());
785   }
786
787   if (log)
788     log->Printf("SBDebugger(%p)::SetSelectedPlatform (SBPlatform(%p) %s)",
789                 static_cast<void *>(m_opaque_sp.get()),
790                 static_cast<void *>(sb_platform.GetSP().get()),
791                 sb_platform.GetName());
792 }
793
794 uint32_t SBDebugger::GetNumPlatforms() {
795   if (m_opaque_sp) {
796     // No need to lock, the platform list is thread safe
797     return m_opaque_sp->GetPlatformList().GetSize();
798   }
799   return 0;
800 }
801
802 SBPlatform SBDebugger::GetPlatformAtIndex(uint32_t idx) {
803   SBPlatform sb_platform;
804   if (m_opaque_sp) {
805     // No need to lock, the platform list is thread safe
806     sb_platform.SetSP(m_opaque_sp->GetPlatformList().GetAtIndex(idx));
807   }
808   return sb_platform;
809 }
810
811 uint32_t SBDebugger::GetNumAvailablePlatforms() {
812   uint32_t idx = 0;
813   while (true) {
814     if (!PluginManager::GetPlatformPluginNameAtIndex(idx)) {
815       break;
816     }
817     ++idx;
818   }
819   // +1 for the host platform, which should always appear first in the list.
820   return idx + 1;
821 }
822
823 SBStructuredData SBDebugger::GetAvailablePlatformInfoAtIndex(uint32_t idx) {
824   SBStructuredData data;
825   auto platform_dict = llvm::make_unique<StructuredData::Dictionary>();
826   llvm::StringRef name_str("name"), desc_str("description");
827
828   if (idx == 0) {
829     PlatformSP host_platform_sp(Platform::GetHostPlatform());
830     platform_dict->AddStringItem(
831         name_str, host_platform_sp->GetPluginName().GetStringRef());
832     platform_dict->AddStringItem(
833         desc_str, llvm::StringRef(host_platform_sp->GetDescription()));
834   } else if (idx > 0) {
835     const char *plugin_name =
836         PluginManager::GetPlatformPluginNameAtIndex(idx - 1);
837     if (!plugin_name) {
838       return data;
839     }
840     platform_dict->AddStringItem(name_str, llvm::StringRef(plugin_name));
841
842     const char *plugin_desc =
843         PluginManager::GetPlatformPluginDescriptionAtIndex(idx - 1);
844     if (!plugin_desc) {
845       return data;
846     }
847     platform_dict->AddStringItem(desc_str, llvm::StringRef(plugin_desc));
848   }
849
850   data.m_impl_up->SetObjectSP(
851       StructuredData::ObjectSP(platform_dict.release()));
852   return data;
853 }
854
855 void SBDebugger::DispatchInput(void *baton, const void *data, size_t data_len) {
856   DispatchInput(data, data_len);
857 }
858
859 void SBDebugger::DispatchInput(const void *data, size_t data_len) {
860   //    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_API));
861   //
862   //    if (log)
863   //        log->Printf ("SBDebugger(%p)::DispatchInput (data=\"%.*s\",
864   //        size_t=%" PRIu64 ")",
865   //                     m_opaque_sp.get(),
866   //                     (int) data_len,
867   //                     (const char *) data,
868   //                     (uint64_t)data_len);
869   //
870   //    if (m_opaque_sp)
871   //        m_opaque_sp->DispatchInput ((const char *) data, data_len);
872 }
873
874 void SBDebugger::DispatchInputInterrupt() {
875   if (m_opaque_sp)
876     m_opaque_sp->DispatchInputInterrupt();
877 }
878
879 void SBDebugger::DispatchInputEndOfFile() {
880   if (m_opaque_sp)
881     m_opaque_sp->DispatchInputEndOfFile();
882 }
883
884 void SBDebugger::PushInputReader(SBInputReader &reader) {}
885
886 void SBDebugger::RunCommandInterpreter(bool auto_handle_events,
887                                        bool spawn_thread) {
888   if (m_opaque_sp) {
889     CommandInterpreterRunOptions options;
890
891     m_opaque_sp->GetCommandInterpreter().RunCommandInterpreter(
892         auto_handle_events, spawn_thread, options);
893   }
894 }
895
896 void SBDebugger::RunCommandInterpreter(bool auto_handle_events,
897                                        bool spawn_thread,
898                                        SBCommandInterpreterRunOptions &options,
899                                        int &num_errors, bool &quit_requested,
900                                        bool &stopped_for_crash)
901
902 {
903   if (m_opaque_sp) {
904     CommandInterpreter &interp = m_opaque_sp->GetCommandInterpreter();
905     interp.RunCommandInterpreter(auto_handle_events, spawn_thread,
906                                  options.ref());
907     num_errors = interp.GetNumErrors();
908     quit_requested = interp.GetQuitRequested();
909     stopped_for_crash = interp.GetStoppedForCrash();
910   }
911 }
912
913 SBError SBDebugger::RunREPL(lldb::LanguageType language,
914                             const char *repl_options) {
915   SBError error;
916   if (m_opaque_sp)
917     error.ref() = m_opaque_sp->RunREPL(language, repl_options);
918   else
919     error.SetErrorString("invalid debugger");
920   return error;
921 }
922
923 void SBDebugger::reset(const DebuggerSP &debugger_sp) {
924   m_opaque_sp = debugger_sp;
925 }
926
927 Debugger *SBDebugger::get() const { return m_opaque_sp.get(); }
928
929 Debugger &SBDebugger::ref() const {
930   assert(m_opaque_sp.get());
931   return *m_opaque_sp;
932 }
933
934 const lldb::DebuggerSP &SBDebugger::get_sp() const { return m_opaque_sp; }
935
936 SBDebugger SBDebugger::FindDebuggerWithID(int id) {
937   // No need to lock, the debugger list is thread safe
938   SBDebugger sb_debugger;
939   DebuggerSP debugger_sp = Debugger::FindDebuggerWithID(id);
940   if (debugger_sp)
941     sb_debugger.reset(debugger_sp);
942   return sb_debugger;
943 }
944
945 const char *SBDebugger::GetInstanceName() {
946   return (m_opaque_sp ? m_opaque_sp->GetInstanceName().AsCString() : nullptr);
947 }
948
949 SBError SBDebugger::SetInternalVariable(const char *var_name, const char *value,
950                                         const char *debugger_instance_name) {
951   SBError sb_error;
952   DebuggerSP debugger_sp(Debugger::FindDebuggerWithInstanceName(
953       ConstString(debugger_instance_name)));
954   Status error;
955   if (debugger_sp) {
956     ExecutionContext exe_ctx(
957         debugger_sp->GetCommandInterpreter().GetExecutionContext());
958     error = debugger_sp->SetPropertyValue(&exe_ctx, eVarSetOperationAssign,
959                                           var_name, value);
960   } else {
961     error.SetErrorStringWithFormat("invalid debugger instance name '%s'",
962                                    debugger_instance_name);
963   }
964   if (error.Fail())
965     sb_error.SetError(error);
966   return sb_error;
967 }
968
969 SBStringList
970 SBDebugger::GetInternalVariableValue(const char *var_name,
971                                      const char *debugger_instance_name) {
972   SBStringList ret_value;
973   DebuggerSP debugger_sp(Debugger::FindDebuggerWithInstanceName(
974       ConstString(debugger_instance_name)));
975   Status error;
976   if (debugger_sp) {
977     ExecutionContext exe_ctx(
978         debugger_sp->GetCommandInterpreter().GetExecutionContext());
979     lldb::OptionValueSP value_sp(
980         debugger_sp->GetPropertyValue(&exe_ctx, var_name, false, error));
981     if (value_sp) {
982       StreamString value_strm;
983       value_sp->DumpValue(&exe_ctx, value_strm, OptionValue::eDumpOptionValue);
984       const std::string &value_str = value_strm.GetString();
985       if (!value_str.empty()) {
986         StringList string_list;
987         string_list.SplitIntoLines(value_str);
988         return SBStringList(&string_list);
989       }
990     }
991   }
992   return SBStringList();
993 }
994
995 uint32_t SBDebugger::GetTerminalWidth() const {
996   return (m_opaque_sp ? m_opaque_sp->GetTerminalWidth() : 0);
997 }
998
999 void SBDebugger::SetTerminalWidth(uint32_t term_width) {
1000   if (m_opaque_sp)
1001     m_opaque_sp->SetTerminalWidth(term_width);
1002 }
1003
1004 const char *SBDebugger::GetPrompt() const {
1005   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1006
1007   if (log)
1008     log->Printf("SBDebugger(%p)::GetPrompt () => \"%s\"",
1009                 static_cast<void *>(m_opaque_sp.get()),
1010                 (m_opaque_sp ? m_opaque_sp->GetPrompt().str().c_str() : ""));
1011
1012   return (m_opaque_sp ? ConstString(m_opaque_sp->GetPrompt()).GetCString()
1013                       : nullptr);
1014 }
1015
1016 void SBDebugger::SetPrompt(const char *prompt) {
1017   if (m_opaque_sp)
1018     m_opaque_sp->SetPrompt(llvm::StringRef::withNullAsEmpty(prompt));
1019 }
1020
1021 ScriptLanguage SBDebugger::GetScriptLanguage() const {
1022   return (m_opaque_sp ? m_opaque_sp->GetScriptLanguage() : eScriptLanguageNone);
1023 }
1024
1025 void SBDebugger::SetScriptLanguage(ScriptLanguage script_lang) {
1026   if (m_opaque_sp) {
1027     m_opaque_sp->SetScriptLanguage(script_lang);
1028   }
1029 }
1030
1031 bool SBDebugger::SetUseExternalEditor(bool value) {
1032   return (m_opaque_sp ? m_opaque_sp->SetUseExternalEditor(value) : false);
1033 }
1034
1035 bool SBDebugger::GetUseExternalEditor() {
1036   return (m_opaque_sp ? m_opaque_sp->GetUseExternalEditor() : false);
1037 }
1038
1039 bool SBDebugger::SetUseColor(bool value) {
1040   return (m_opaque_sp ? m_opaque_sp->SetUseColor(value) : false);
1041 }
1042
1043 bool SBDebugger::GetUseColor() const {
1044   return (m_opaque_sp ? m_opaque_sp->GetUseColor() : false);
1045 }
1046
1047 bool SBDebugger::GetDescription(SBStream &description) {
1048   Stream &strm = description.ref();
1049
1050   if (m_opaque_sp) {
1051     const char *name = m_opaque_sp->GetInstanceName().AsCString();
1052     user_id_t id = m_opaque_sp->GetID();
1053     strm.Printf("Debugger (instance: \"%s\", id: %" PRIu64 ")", name, id);
1054   } else
1055     strm.PutCString("No value");
1056
1057   return true;
1058 }
1059
1060 user_id_t SBDebugger::GetID() {
1061   return (m_opaque_sp ? m_opaque_sp->GetID() : LLDB_INVALID_UID);
1062 }
1063
1064 SBError SBDebugger::SetCurrentPlatform(const char *platform_name_cstr) {
1065   SBError sb_error;
1066   if (m_opaque_sp) {
1067     if (platform_name_cstr && platform_name_cstr[0]) {
1068       ConstString platform_name(platform_name_cstr);
1069       PlatformSP platform_sp(Platform::Find(platform_name));
1070
1071       if (platform_sp) {
1072         // Already have a platform with this name, just select it
1073         m_opaque_sp->GetPlatformList().SetSelectedPlatform(platform_sp);
1074       } else {
1075         // We don't have a platform by this name yet, create one
1076         platform_sp = Platform::Create(platform_name, sb_error.ref());
1077         if (platform_sp) {
1078           // We created the platform, now append and select it
1079           bool make_selected = true;
1080           m_opaque_sp->GetPlatformList().Append(platform_sp, make_selected);
1081         }
1082       }
1083     } else {
1084       sb_error.ref().SetErrorString("invalid platform name");
1085     }
1086   } else {
1087     sb_error.ref().SetErrorString("invalid debugger");
1088   }
1089   return sb_error;
1090 }
1091
1092 bool SBDebugger::SetCurrentPlatformSDKRoot(const char *sysroot) {
1093   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1094   if (m_opaque_sp) {
1095     PlatformSP platform_sp(
1096         m_opaque_sp->GetPlatformList().GetSelectedPlatform());
1097
1098     if (platform_sp) {
1099       if (log && sysroot)
1100         log->Printf("SBDebugger::SetCurrentPlatformSDKRoot (\"%s\")", sysroot);
1101       platform_sp->SetSDKRootDirectory(ConstString(sysroot));
1102       return true;
1103     }
1104   }
1105   return false;
1106 }
1107
1108 bool SBDebugger::GetCloseInputOnEOF() const {
1109   return (m_opaque_sp ? m_opaque_sp->GetCloseInputOnEOF() : false);
1110 }
1111
1112 void SBDebugger::SetCloseInputOnEOF(bool b) {
1113   if (m_opaque_sp)
1114     m_opaque_sp->SetCloseInputOnEOF(b);
1115 }
1116
1117 SBTypeCategory SBDebugger::GetCategory(const char *category_name) {
1118   if (!category_name || *category_name == 0)
1119     return SBTypeCategory();
1120
1121   TypeCategoryImplSP category_sp;
1122
1123   if (DataVisualization::Categories::GetCategory(ConstString(category_name),
1124                                                  category_sp, false))
1125     return SBTypeCategory(category_sp);
1126   else
1127     return SBTypeCategory();
1128 }
1129
1130 SBTypeCategory SBDebugger::GetCategory(lldb::LanguageType lang_type) {
1131   TypeCategoryImplSP category_sp;
1132   if (DataVisualization::Categories::GetCategory(lang_type, category_sp))
1133     return SBTypeCategory(category_sp);
1134   else
1135     return SBTypeCategory();
1136 }
1137
1138 SBTypeCategory SBDebugger::CreateCategory(const char *category_name) {
1139   if (!category_name || *category_name == 0)
1140     return SBTypeCategory();
1141
1142   TypeCategoryImplSP category_sp;
1143
1144   if (DataVisualization::Categories::GetCategory(ConstString(category_name),
1145                                                  category_sp, true))
1146     return SBTypeCategory(category_sp);
1147   else
1148     return SBTypeCategory();
1149 }
1150
1151 bool SBDebugger::DeleteCategory(const char *category_name) {
1152   if (!category_name || *category_name == 0)
1153     return false;
1154
1155   return DataVisualization::Categories::Delete(ConstString(category_name));
1156 }
1157
1158 uint32_t SBDebugger::GetNumCategories() {
1159   return DataVisualization::Categories::GetCount();
1160 }
1161
1162 SBTypeCategory SBDebugger::GetCategoryAtIndex(uint32_t index) {
1163   return SBTypeCategory(
1164       DataVisualization::Categories::GetCategoryAtIndex(index));
1165 }
1166
1167 SBTypeCategory SBDebugger::GetDefaultCategory() {
1168   return GetCategory("default");
1169 }
1170
1171 SBTypeFormat SBDebugger::GetFormatForType(SBTypeNameSpecifier type_name) {
1172   SBTypeCategory default_category_sb = GetDefaultCategory();
1173   if (default_category_sb.GetEnabled())
1174     return default_category_sb.GetFormatForType(type_name);
1175   return SBTypeFormat();
1176 }
1177
1178 #ifndef LLDB_DISABLE_PYTHON
1179 SBTypeSummary SBDebugger::GetSummaryForType(SBTypeNameSpecifier type_name) {
1180   if (!type_name.IsValid())
1181     return SBTypeSummary();
1182   return SBTypeSummary(DataVisualization::GetSummaryForType(type_name.GetSP()));
1183 }
1184 #endif // LLDB_DISABLE_PYTHON
1185
1186 SBTypeFilter SBDebugger::GetFilterForType(SBTypeNameSpecifier type_name) {
1187   if (!type_name.IsValid())
1188     return SBTypeFilter();
1189   return SBTypeFilter(DataVisualization::GetFilterForType(type_name.GetSP()));
1190 }
1191
1192 #ifndef LLDB_DISABLE_PYTHON
1193 SBTypeSynthetic SBDebugger::GetSyntheticForType(SBTypeNameSpecifier type_name) {
1194   if (!type_name.IsValid())
1195     return SBTypeSynthetic();
1196   return SBTypeSynthetic(
1197       DataVisualization::GetSyntheticForType(type_name.GetSP()));
1198 }
1199 #endif // LLDB_DISABLE_PYTHON
1200
1201 static llvm::ArrayRef<const char *> GetCategoryArray(const char **categories) {
1202   if (categories == nullptr)
1203     return {};
1204   size_t len = 0;
1205   while (categories[len] != nullptr)
1206     ++len;
1207   return llvm::makeArrayRef(categories, len);
1208 }
1209
1210 bool SBDebugger::EnableLog(const char *channel, const char **categories) {
1211   if (m_opaque_sp) {
1212     uint32_t log_options =
1213         LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
1214     std::string error;
1215     llvm::raw_string_ostream error_stream(error);
1216     return m_opaque_sp->EnableLog(channel, GetCategoryArray(categories), "",
1217                                   log_options, error_stream);
1218   } else
1219     return false;
1220 }
1221
1222 void SBDebugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1223                                     void *baton) {
1224   if (m_opaque_sp) {
1225     return m_opaque_sp->SetLoggingCallback(log_callback, baton);
1226   }
1227 }