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