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