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