1 //===-- Debugger.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/Core/Debugger.h"
13 
14 #include <map>
15 
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/Type.h"
18 #include "llvm/ADT/StringRef.h"
19 
20 #include "lldb/lldb-private.h"
21 #include "lldb/Core/FormatEntity.h"
22 #include "lldb/Core/Module.h"
23 #include "lldb/Core/PluginManager.h"
24 #include "lldb/Core/RegisterValue.h"
25 #include "lldb/Core/State.h"
26 #include "lldb/Core/StreamAsynchronousIO.h"
27 #include "lldb/Core/StreamCallback.h"
28 #include "lldb/Core/StreamFile.h"
29 #include "lldb/Core/StreamString.h"
30 #include "lldb/Core/StructuredData.h"
31 #include "lldb/Core/Timer.h"
32 #include "lldb/Core/ValueObject.h"
33 #include "lldb/Core/ValueObjectVariable.h"
34 #include "lldb/DataFormatters/DataVisualization.h"
35 #include "lldb/DataFormatters/FormatManager.h"
36 #include "lldb/DataFormatters/TypeSummary.h"
37 #include "lldb/Host/ConnectionFileDescriptor.h"
38 #include "lldb/Host/HostInfo.h"
39 #include "lldb/Host/Terminal.h"
40 #include "lldb/Host/ThreadLauncher.h"
41 #include "lldb/Interpreter/CommandInterpreter.h"
42 #include "lldb/Interpreter/OptionValueSInt64.h"
43 #include "lldb/Interpreter/OptionValueString.h"
44 #include "lldb/Symbol/ClangASTContext.h"
45 #include "lldb/Symbol/CompileUnit.h"
46 #include "lldb/Symbol/Function.h"
47 #include "lldb/Symbol/Symbol.h"
48 #include "lldb/Symbol/VariableList.h"
49 #include "lldb/Target/CPPLanguageRuntime.h"
50 #include "lldb/Target/ObjCLanguageRuntime.h"
51 #include "lldb/Target/TargetList.h"
52 #include "lldb/Target/Process.h"
53 #include "lldb/Target/RegisterContext.h"
54 #include "lldb/Target/SectionLoadList.h"
55 #include "lldb/Target/StopInfo.h"
56 #include "lldb/Target/Target.h"
57 #include "lldb/Target/Thread.h"
58 #include "lldb/Utility/AnsiTerminal.h"
59 
60 #include "llvm/Support/DynamicLibrary.h"
61 
62 using namespace lldb;
63 using namespace lldb_private;
64 
65 
66 static uint32_t g_shared_debugger_refcount = 0;
67 static lldb::user_id_t g_unique_id = 1;
68 static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
69 
70 #pragma mark Static Functions
71 
72 static Mutex &
73 GetDebuggerListMutex ()
74 {
75     static Mutex g_mutex(Mutex::eMutexTypeRecursive);
76     return g_mutex;
77 }
78 
79 typedef std::vector<DebuggerSP> DebuggerList;
80 
81 static DebuggerList &
82 GetDebuggerList()
83 {
84     // hide the static debugger list inside a singleton accessor to avoid
85     // global init constructors
86     static DebuggerList g_list;
87     return g_list;
88 }
89 
90 OptionEnumValueElement
91 g_show_disassembly_enum_values[] =
92 {
93     { Debugger::eStopDisassemblyTypeNever,    "never",     "Never show disassembly when displaying a stop context."},
94     { Debugger::eStopDisassemblyTypeNoSource, "no-source", "Show disassembly when there is no source information, or the source file is missing when displaying a stop context."},
95     { Debugger::eStopDisassemblyTypeAlways,   "always",    "Always show disassembly when displaying a stop context."},
96     { 0, NULL, NULL }
97 };
98 
99 OptionEnumValueElement
100 g_language_enumerators[] =
101 {
102     { eScriptLanguageNone,      "none",     "Disable scripting languages."},
103     { eScriptLanguagePython,    "python",   "Select python as the default scripting language."},
104     { eScriptLanguageDefault,   "default",  "Select the lldb default as the default scripting language."},
105     { 0, NULL, NULL }
106 };
107 
108 #define MODULE_WITH_FUNC "{ ${module.file.basename}{`${function.name-with-args}${function.pc-offset}}}"
109 #define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}"
110 
111 #define DEFAULT_THREAD_FORMAT "thread #${thread.index}: tid = ${thread.id%tid}"\
112     "{, ${frame.pc}}"\
113     MODULE_WITH_FUNC\
114     FILE_AND_LINE\
115     "{, name = '${thread.name}'}"\
116     "{, queue = '${thread.queue}'}"\
117     "{, activity = '${thread.info.activity.name}'}" \
118     "{, ${thread.info.trace_messages} messages}" \
119     "{, stop reason = ${thread.stop-reason}}"\
120     "{\\nReturn value: ${thread.return-value}}"\
121     "{\\nCompleted expression: ${thread.completed-expression}}"\
122     "\\n"
123 
124 #define DEFAULT_FRAME_FORMAT "frame #${frame.index}: ${frame.pc}"\
125     MODULE_WITH_FUNC\
126     FILE_AND_LINE\
127     "\\n"
128 
129 #define DEFAULT_DISASSEMBLY_FORMAT "${current-pc-arrow}${addr-file-or-load}{ <${function.name-without-args}${function.concrete-only-addr-offset-no-padding}>}: "
130 
131 static PropertyDefinition
132 g_properties[] =
133 {
134 {   "auto-confirm",             OptionValue::eTypeBoolean     , true, false, NULL, NULL, "If true all confirmation prompts will receive their default reply." },
135 {   "disassembly-format",       OptionValue::eTypeFormatEntity, true, 0    , DEFAULT_DISASSEMBLY_FORMAT, NULL, "The default disassembly format string to use when disassembling instruction sequences." },
136 {   "frame-format",             OptionValue::eTypeFormatEntity, true, 0    , DEFAULT_FRAME_FORMAT, NULL, "The default frame format string to use when displaying stack frame information for threads." },
137 {   "notify-void",              OptionValue::eTypeBoolean     , true, false, NULL, NULL, "Notify the user explicitly if an expression returns void (default: false)." },
138 {   "prompt",                   OptionValue::eTypeString      , true, OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ", NULL, "The debugger command line prompt displayed for the user." },
139 {   "script-lang",              OptionValue::eTypeEnum        , true, eScriptLanguagePython, NULL, g_language_enumerators, "The script language to be used for evaluating user-written scripts." },
140 {   "stop-disassembly-count",   OptionValue::eTypeSInt64      , true, 4    , NULL, NULL, "The number of disassembly lines to show when displaying a stopped context." },
141 {   "stop-disassembly-display", OptionValue::eTypeEnum        , true, Debugger::eStopDisassemblyTypeNoSource, NULL, g_show_disassembly_enum_values, "Control when to display disassembly when displaying a stopped context." },
142 {   "stop-line-count-after",    OptionValue::eTypeSInt64      , true, 3    , NULL, NULL, "The number of sources lines to display that come after the current source line when displaying a stopped context." },
143 {   "stop-line-count-before",   OptionValue::eTypeSInt64      , true, 3    , NULL, NULL, "The number of sources lines to display that come before the current source line when displaying a stopped context." },
144 {   "term-width",               OptionValue::eTypeSInt64      , true, 80   , NULL, NULL, "The maximum number of columns to use for displaying text." },
145 {   "thread-format",            OptionValue::eTypeFormatEntity, true, 0    , DEFAULT_THREAD_FORMAT, NULL, "The default thread format string to use when displaying thread information." },
146 {   "use-external-editor",      OptionValue::eTypeBoolean     , true, false, NULL, NULL, "Whether to use an external editor or not." },
147 {   "use-color",                OptionValue::eTypeBoolean     , true, true , NULL, NULL, "Whether to use Ansi color codes or not." },
148 {   "auto-one-line-summaries",  OptionValue::eTypeBoolean     , true, true, NULL, NULL, "If true, LLDB will automatically display small structs in one-liner format (default: true)." },
149 {   "escape-non-printables",    OptionValue::eTypeBoolean     , true, true, NULL, NULL, "If true, LLDB will automatically escape non-printable and escape characters when formatting strings." },
150 {   NULL,                       OptionValue::eTypeInvalid     , true, 0    , NULL, NULL, NULL }
151 };
152 
153 enum
154 {
155     ePropertyAutoConfirm = 0,
156     ePropertyDisassemblyFormat,
157     ePropertyFrameFormat,
158     ePropertyNotiftVoid,
159     ePropertyPrompt,
160     ePropertyScriptLanguage,
161     ePropertyStopDisassemblyCount,
162     ePropertyStopDisassemblyDisplay,
163     ePropertyStopLineCountAfter,
164     ePropertyStopLineCountBefore,
165     ePropertyTerminalWidth,
166     ePropertyThreadFormat,
167     ePropertyUseExternalEditor,
168     ePropertyUseColor,
169     ePropertyAutoOneLineSummaries,
170     ePropertyEscapeNonPrintables
171 };
172 
173 Debugger::LoadPluginCallbackType Debugger::g_load_plugin_callback = NULL;
174 
175 Error
176 Debugger::SetPropertyValue (const ExecutionContext *exe_ctx,
177                             VarSetOperationType op,
178                             const char *property_path,
179                             const char *value)
180 {
181     bool is_load_script = strcmp(property_path,"target.load-script-from-symbol-file") == 0;
182     bool is_escape_non_printables = strcmp(property_path, "escape-non-printables") == 0;
183     TargetSP target_sp;
184     LoadScriptFromSymFile load_script_old_value;
185     if (is_load_script && exe_ctx->GetTargetSP())
186     {
187         target_sp = exe_ctx->GetTargetSP();
188         load_script_old_value = target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
189     }
190     Error error (Properties::SetPropertyValue (exe_ctx, op, property_path, value));
191     if (error.Success())
192     {
193         // FIXME it would be nice to have "on-change" callbacks for properties
194         if (strcmp(property_path, g_properties[ePropertyPrompt].name) == 0)
195         {
196             const char *new_prompt = GetPrompt();
197             std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
198             if (str.length())
199                 new_prompt = str.c_str();
200             GetCommandInterpreter().UpdatePrompt(new_prompt);
201             EventSP prompt_change_event_sp (new Event(CommandInterpreter::eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));
202             GetCommandInterpreter().BroadcastEvent (prompt_change_event_sp);
203         }
204         else if (strcmp(property_path, g_properties[ePropertyUseColor].name) == 0)
205         {
206 			// use-color changed. Ping the prompt so it can reset the ansi terminal codes.
207             SetPrompt (GetPrompt());
208         }
209         else if (is_load_script && target_sp && load_script_old_value == eLoadScriptFromSymFileWarn)
210         {
211             if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() == eLoadScriptFromSymFileTrue)
212             {
213                 std::list<Error> errors;
214                 StreamString feedback_stream;
215                 if (!target_sp->LoadScriptingResources(errors,&feedback_stream))
216                 {
217                     StreamFileSP stream_sp (GetErrorFile());
218                     if (stream_sp)
219                     {
220                         for (auto error : errors)
221                         {
222                             stream_sp->Printf("%s\n",error.AsCString());
223                         }
224                         if (feedback_stream.GetSize())
225                             stream_sp->Printf("%s",feedback_stream.GetData());
226                     }
227                 }
228             }
229         }
230         else if (is_escape_non_printables)
231         {
232             DataVisualization::ForceUpdate();
233         }
234     }
235     return error;
236 }
237 
238 bool
239 Debugger::GetAutoConfirm () const
240 {
241     const uint32_t idx = ePropertyAutoConfirm;
242     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
243 }
244 
245 const FormatEntity::Entry *
246 Debugger::GetDisassemblyFormat() const
247 {
248     const uint32_t idx = ePropertyDisassemblyFormat;
249     return m_collection_sp->GetPropertyAtIndexAsFormatEntity(NULL, idx);
250 }
251 
252 const FormatEntity::Entry *
253 Debugger::GetFrameFormat() const
254 {
255     const uint32_t idx = ePropertyFrameFormat;
256     return m_collection_sp->GetPropertyAtIndexAsFormatEntity(NULL, idx);
257 }
258 
259 bool
260 Debugger::GetNotifyVoid () const
261 {
262     const uint32_t idx = ePropertyNotiftVoid;
263     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
264 }
265 
266 const char *
267 Debugger::GetPrompt() const
268 {
269     const uint32_t idx = ePropertyPrompt;
270     return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
271 }
272 
273 void
274 Debugger::SetPrompt(const char *p)
275 {
276     const uint32_t idx = ePropertyPrompt;
277     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
278     const char *new_prompt = GetPrompt();
279     std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
280     if (str.length())
281         new_prompt = str.c_str();
282     GetCommandInterpreter().UpdatePrompt(new_prompt);
283 }
284 
285 const FormatEntity::Entry *
286 Debugger::GetThreadFormat() const
287 {
288     const uint32_t idx = ePropertyThreadFormat;
289     return m_collection_sp->GetPropertyAtIndexAsFormatEntity(NULL, idx);
290 }
291 
292 lldb::ScriptLanguage
293 Debugger::GetScriptLanguage() const
294 {
295     const uint32_t idx = ePropertyScriptLanguage;
296     return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
297 }
298 
299 bool
300 Debugger::SetScriptLanguage (lldb::ScriptLanguage script_lang)
301 {
302     const uint32_t idx = ePropertyScriptLanguage;
303     return m_collection_sp->SetPropertyAtIndexAsEnumeration (NULL, idx, script_lang);
304 }
305 
306 uint32_t
307 Debugger::GetTerminalWidth () const
308 {
309     const uint32_t idx = ePropertyTerminalWidth;
310     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
311 }
312 
313 bool
314 Debugger::SetTerminalWidth (uint32_t term_width)
315 {
316     const uint32_t idx = ePropertyTerminalWidth;
317     return m_collection_sp->SetPropertyAtIndexAsSInt64 (NULL, idx, term_width);
318 }
319 
320 bool
321 Debugger::GetUseExternalEditor () const
322 {
323     const uint32_t idx = ePropertyUseExternalEditor;
324     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
325 }
326 
327 bool
328 Debugger::SetUseExternalEditor (bool b)
329 {
330     const uint32_t idx = ePropertyUseExternalEditor;
331     return m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
332 }
333 
334 bool
335 Debugger::GetUseColor () const
336 {
337     const uint32_t idx = ePropertyUseColor;
338     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
339 }
340 
341 bool
342 Debugger::SetUseColor (bool b)
343 {
344     const uint32_t idx = ePropertyUseColor;
345     bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
346     SetPrompt (GetPrompt());
347     return ret;
348 }
349 
350 uint32_t
351 Debugger::GetStopSourceLineCount (bool before) const
352 {
353     const uint32_t idx = before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
354     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
355 }
356 
357 Debugger::StopDisassemblyType
358 Debugger::GetStopDisassemblyDisplay () const
359 {
360     const uint32_t idx = ePropertyStopDisassemblyDisplay;
361     return (Debugger::StopDisassemblyType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
362 }
363 
364 uint32_t
365 Debugger::GetDisassemblyLineCount () const
366 {
367     const uint32_t idx = ePropertyStopDisassemblyCount;
368     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
369 }
370 
371 bool
372 Debugger::GetAutoOneLineSummaries () const
373 {
374     const uint32_t idx = ePropertyAutoOneLineSummaries;
375     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
376 }
377 
378 bool
379 Debugger::GetEscapeNonPrintables () const
380 {
381     const uint32_t idx = ePropertyEscapeNonPrintables;
382     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
383 }
384 
385 #pragma mark Debugger
386 
387 //const DebuggerPropertiesSP &
388 //Debugger::GetSettings() const
389 //{
390 //    return m_properties_sp;
391 //}
392 //
393 
394 int
395 Debugger::TestDebuggerRefCount ()
396 {
397     return g_shared_debugger_refcount;
398 }
399 
400 void
401 Debugger::Initialize (LoadPluginCallbackType load_plugin_callback)
402 {
403     g_load_plugin_callback = load_plugin_callback;
404     if (g_shared_debugger_refcount++ == 0)
405         lldb_private::Initialize();
406 }
407 
408 void
409 Debugger::Terminate ()
410 {
411     if (g_shared_debugger_refcount > 0)
412     {
413         g_shared_debugger_refcount--;
414         if (g_shared_debugger_refcount == 0)
415         {
416             lldb_private::WillTerminate();
417             lldb_private::Terminate();
418 
419             // Clear our master list of debugger objects
420             Mutex::Locker locker (GetDebuggerListMutex ());
421             GetDebuggerList().clear();
422         }
423     }
424 }
425 
426 void
427 Debugger::SettingsInitialize ()
428 {
429     Target::SettingsInitialize ();
430 }
431 
432 void
433 Debugger::SettingsTerminate ()
434 {
435     Target::SettingsTerminate ();
436 }
437 
438 bool
439 Debugger::LoadPlugin (const FileSpec& spec, Error& error)
440 {
441     if (g_load_plugin_callback)
442     {
443         llvm::sys::DynamicLibrary dynlib = g_load_plugin_callback (shared_from_this(), spec, error);
444         if (dynlib.isValid())
445         {
446             m_loaded_plugins.push_back(dynlib);
447             return true;
448         }
449     }
450     else
451     {
452         // The g_load_plugin_callback is registered in SBDebugger::Initialize()
453         // and if the public API layer isn't available (code is linking against
454         // all of the internal LLDB static libraries), then we can't load plugins
455         error.SetErrorString("Public API layer is not available");
456     }
457     return false;
458 }
459 
460 static FileSpec::EnumerateDirectoryResult
461 LoadPluginCallback
462 (
463  void *baton,
464  FileSpec::FileType file_type,
465  const FileSpec &file_spec
466  )
467 {
468     Error error;
469 
470     static ConstString g_dylibext("dylib");
471     static ConstString g_solibext("so");
472 
473     if (!baton)
474         return FileSpec::eEnumerateDirectoryResultQuit;
475 
476     Debugger *debugger = (Debugger*)baton;
477 
478     // If we have a regular file, a symbolic link or unknown file type, try
479     // and process the file. We must handle unknown as sometimes the directory
480     // enumeration might be enumerating a file system that doesn't have correct
481     // file type information.
482     if (file_type == FileSpec::eFileTypeRegular         ||
483         file_type == FileSpec::eFileTypeSymbolicLink    ||
484         file_type == FileSpec::eFileTypeUnknown          )
485     {
486         FileSpec plugin_file_spec (file_spec);
487         plugin_file_spec.ResolvePath ();
488 
489         if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
490             plugin_file_spec.GetFileNameExtension() != g_solibext)
491         {
492             return FileSpec::eEnumerateDirectoryResultNext;
493         }
494 
495         Error plugin_load_error;
496         debugger->LoadPlugin (plugin_file_spec, plugin_load_error);
497 
498         return FileSpec::eEnumerateDirectoryResultNext;
499     }
500 
501     else if (file_type == FileSpec::eFileTypeUnknown     ||
502         file_type == FileSpec::eFileTypeDirectory   ||
503         file_type == FileSpec::eFileTypeSymbolicLink )
504     {
505         // Try and recurse into anything that a directory or symbolic link.
506         // We must also do this for unknown as sometimes the directory enumeration
507         // might be enumerating a file system that doesn't have correct file type
508         // information.
509         return FileSpec::eEnumerateDirectoryResultEnter;
510     }
511 
512     return FileSpec::eEnumerateDirectoryResultNext;
513 }
514 
515 void
516 Debugger::InstanceInitialize ()
517 {
518     FileSpec dir_spec;
519     const bool find_directories = true;
520     const bool find_files = true;
521     const bool find_other = true;
522     char dir_path[PATH_MAX];
523     if (HostInfo::GetLLDBPath(ePathTypeLLDBSystemPlugins, dir_spec))
524     {
525         if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
526         {
527             FileSpec::EnumerateDirectory (dir_path,
528                                           find_directories,
529                                           find_files,
530                                           find_other,
531                                           LoadPluginCallback,
532                                           this);
533         }
534     }
535 
536     if (HostInfo::GetLLDBPath(ePathTypeLLDBUserPlugins, dir_spec))
537     {
538         if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
539         {
540             FileSpec::EnumerateDirectory (dir_path,
541                                           find_directories,
542                                           find_files,
543                                           find_other,
544                                           LoadPluginCallback,
545                                           this);
546         }
547     }
548 
549     PluginManager::DebuggerInitialize (*this);
550 }
551 
552 DebuggerSP
553 Debugger::CreateInstance (lldb::LogOutputCallback log_callback, void *baton)
554 {
555     DebuggerSP debugger_sp (new Debugger(log_callback, baton));
556     if (g_shared_debugger_refcount > 0)
557     {
558         Mutex::Locker locker (GetDebuggerListMutex ());
559         GetDebuggerList().push_back(debugger_sp);
560     }
561     debugger_sp->InstanceInitialize ();
562     return debugger_sp;
563 }
564 
565 void
566 Debugger::Destroy (DebuggerSP &debugger_sp)
567 {
568     if (debugger_sp.get() == NULL)
569         return;
570 
571     debugger_sp->Clear();
572 
573     if (g_shared_debugger_refcount > 0)
574     {
575         Mutex::Locker locker (GetDebuggerListMutex ());
576         DebuggerList &debugger_list = GetDebuggerList ();
577         DebuggerList::iterator pos, end = debugger_list.end();
578         for (pos = debugger_list.begin (); pos != end; ++pos)
579         {
580             if ((*pos).get() == debugger_sp.get())
581             {
582                 debugger_list.erase (pos);
583                 return;
584             }
585         }
586     }
587 }
588 
589 DebuggerSP
590 Debugger::FindDebuggerWithInstanceName (const ConstString &instance_name)
591 {
592     DebuggerSP debugger_sp;
593     if (g_shared_debugger_refcount > 0)
594     {
595         Mutex::Locker locker (GetDebuggerListMutex ());
596         DebuggerList &debugger_list = GetDebuggerList();
597         DebuggerList::iterator pos, end = debugger_list.end();
598 
599         for (pos = debugger_list.begin(); pos != end; ++pos)
600         {
601             if ((*pos).get()->m_instance_name == instance_name)
602             {
603                 debugger_sp = *pos;
604                 break;
605             }
606         }
607     }
608     return debugger_sp;
609 }
610 
611 TargetSP
612 Debugger::FindTargetWithProcessID (lldb::pid_t pid)
613 {
614     TargetSP target_sp;
615     if (g_shared_debugger_refcount > 0)
616     {
617         Mutex::Locker locker (GetDebuggerListMutex ());
618         DebuggerList &debugger_list = GetDebuggerList();
619         DebuggerList::iterator pos, end = debugger_list.end();
620         for (pos = debugger_list.begin(); pos != end; ++pos)
621         {
622             target_sp = (*pos)->GetTargetList().FindTargetWithProcessID (pid);
623             if (target_sp)
624                 break;
625         }
626     }
627     return target_sp;
628 }
629 
630 TargetSP
631 Debugger::FindTargetWithProcess (Process *process)
632 {
633     TargetSP target_sp;
634     if (g_shared_debugger_refcount > 0)
635     {
636         Mutex::Locker locker (GetDebuggerListMutex ());
637         DebuggerList &debugger_list = GetDebuggerList();
638         DebuggerList::iterator pos, end = debugger_list.end();
639         for (pos = debugger_list.begin(); pos != end; ++pos)
640         {
641             target_sp = (*pos)->GetTargetList().FindTargetWithProcess (process);
642             if (target_sp)
643                 break;
644         }
645     }
646     return target_sp;
647 }
648 
649 Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton) :
650     UserID(g_unique_id++),
651     Properties(OptionValuePropertiesSP(new OptionValueProperties())),
652     m_input_file_sp(new StreamFile(stdin, false)),
653     m_output_file_sp(new StreamFile(stdout, false)),
654     m_error_file_sp(new StreamFile(stderr, false)),
655     m_terminal_state(),
656     m_target_list(*this),
657     m_platform_list(),
658     m_listener("lldb.Debugger"),
659     m_source_manager_ap(),
660     m_source_file_cache(),
661     m_command_interpreter_ap(new CommandInterpreter(*this, eScriptLanguageDefault, false)),
662     m_input_reader_stack(),
663     m_instance_name(),
664     m_loaded_plugins(),
665     m_event_handler_thread (),
666     m_io_handler_thread (),
667     m_sync_broadcaster (NULL, "lldb.debugger.sync")
668 {
669     char instance_cstr[256];
670     snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
671     m_instance_name.SetCString(instance_cstr);
672     if (log_callback)
673         m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
674     m_command_interpreter_ap->Initialize ();
675     // Always add our default platform to the platform list
676     PlatformSP default_platform_sp (Platform::GetHostPlatform());
677     assert (default_platform_sp.get());
678     m_platform_list.Append (default_platform_sp, true);
679 
680     m_collection_sp->Initialize (g_properties);
681     m_collection_sp->AppendProperty (ConstString("target"),
682                                      ConstString("Settings specify to debugging targets."),
683                                      true,
684                                      Target::GetGlobalProperties()->GetValueProperties());
685     if (m_command_interpreter_ap.get())
686     {
687         m_collection_sp->AppendProperty (ConstString("interpreter"),
688                                          ConstString("Settings specify to the debugger's command interpreter."),
689                                          true,
690                                          m_command_interpreter_ap->GetValueProperties());
691     }
692     OptionValueSInt64 *term_width = m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64 (NULL, ePropertyTerminalWidth);
693     term_width->SetMinimumValue(10);
694     term_width->SetMaximumValue(1024);
695 
696     // Turn off use-color if this is a dumb terminal.
697     const char *term = getenv ("TERM");
698     if (term && !strcmp (term, "dumb"))
699         SetUseColor (false);
700 }
701 
702 Debugger::~Debugger ()
703 {
704     Clear();
705 }
706 
707 void
708 Debugger::Clear()
709 {
710     ClearIOHandlers();
711     StopIOHandlerThread();
712     StopEventHandlerThread();
713     m_listener.Clear();
714     int num_targets = m_target_list.GetNumTargets();
715     for (int i = 0; i < num_targets; i++)
716     {
717         TargetSP target_sp (m_target_list.GetTargetAtIndex (i));
718         if (target_sp)
719         {
720             ProcessSP process_sp (target_sp->GetProcessSP());
721             if (process_sp)
722                 process_sp->Finalize();
723             target_sp->Destroy();
724         }
725     }
726     BroadcasterManager::Clear ();
727 
728     // Close the input file _before_ we close the input read communications class
729     // as it does NOT own the input file, our m_input_file does.
730     m_terminal_state.Clear();
731     if (m_input_file_sp)
732         m_input_file_sp->GetFile().Close ();
733 
734     m_command_interpreter_ap->Clear();
735 }
736 
737 bool
738 Debugger::GetCloseInputOnEOF () const
739 {
740 //    return m_input_comm.GetCloseOnEOF();
741     return false;
742 }
743 
744 void
745 Debugger::SetCloseInputOnEOF (bool b)
746 {
747 //    m_input_comm.SetCloseOnEOF(b);
748 }
749 
750 bool
751 Debugger::GetAsyncExecution ()
752 {
753     return !m_command_interpreter_ap->GetSynchronous();
754 }
755 
756 void
757 Debugger::SetAsyncExecution (bool async_execution)
758 {
759     m_command_interpreter_ap->SetSynchronous (!async_execution);
760 }
761 
762 
763 void
764 Debugger::SetInputFileHandle (FILE *fh, bool tranfer_ownership)
765 {
766     if (m_input_file_sp)
767         m_input_file_sp->GetFile().SetStream (fh, tranfer_ownership);
768     else
769         m_input_file_sp.reset (new StreamFile (fh, tranfer_ownership));
770 
771     File &in_file = m_input_file_sp->GetFile();
772     if (in_file.IsValid() == false)
773         in_file.SetStream (stdin, true);
774 
775     // Save away the terminal state if that is relevant, so that we can restore it in RestoreInputState.
776     SaveInputTerminalState ();
777 }
778 
779 void
780 Debugger::SetOutputFileHandle (FILE *fh, bool tranfer_ownership)
781 {
782     if (m_output_file_sp)
783         m_output_file_sp->GetFile().SetStream (fh, tranfer_ownership);
784     else
785         m_output_file_sp.reset (new StreamFile (fh, tranfer_ownership));
786 
787     File &out_file = m_output_file_sp->GetFile();
788     if (out_file.IsValid() == false)
789         out_file.SetStream (stdout, false);
790 
791     // do not create the ScriptInterpreter just for setting the output file handle
792     // as the constructor will know how to do the right thing on its own
793     const bool can_create = false;
794     ScriptInterpreter* script_interpreter = GetCommandInterpreter().GetScriptInterpreter(can_create);
795     if (script_interpreter)
796         script_interpreter->ResetOutputFileHandle (fh);
797 }
798 
799 void
800 Debugger::SetErrorFileHandle (FILE *fh, bool tranfer_ownership)
801 {
802     if (m_error_file_sp)
803         m_error_file_sp->GetFile().SetStream (fh, tranfer_ownership);
804     else
805         m_error_file_sp.reset (new StreamFile (fh, tranfer_ownership));
806 
807     File &err_file = m_error_file_sp->GetFile();
808     if (err_file.IsValid() == false)
809         err_file.SetStream (stderr, false);
810 }
811 
812 void
813 Debugger::SaveInputTerminalState ()
814 {
815     if (m_input_file_sp)
816     {
817         File &in_file = m_input_file_sp->GetFile();
818         if (in_file.GetDescriptor() != File::kInvalidDescriptor)
819             m_terminal_state.Save(in_file.GetDescriptor(), true);
820     }
821 }
822 
823 void
824 Debugger::RestoreInputTerminalState ()
825 {
826     m_terminal_state.Restore();
827 }
828 
829 ExecutionContext
830 Debugger::GetSelectedExecutionContext ()
831 {
832     ExecutionContext exe_ctx;
833     TargetSP target_sp(GetSelectedTarget());
834     exe_ctx.SetTargetSP (target_sp);
835 
836     if (target_sp)
837     {
838         ProcessSP process_sp (target_sp->GetProcessSP());
839         exe_ctx.SetProcessSP (process_sp);
840         if (process_sp && process_sp->IsRunning() == false)
841         {
842             ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
843             if (thread_sp)
844             {
845                 exe_ctx.SetThreadSP (thread_sp);
846                 exe_ctx.SetFrameSP (thread_sp->GetSelectedFrame());
847                 if (exe_ctx.GetFramePtr() == NULL)
848                     exe_ctx.SetFrameSP (thread_sp->GetStackFrameAtIndex (0));
849             }
850         }
851     }
852     return exe_ctx;
853 }
854 
855 void
856 Debugger::DispatchInputInterrupt ()
857 {
858     Mutex::Locker locker (m_input_reader_stack.GetMutex());
859     IOHandlerSP reader_sp (m_input_reader_stack.Top());
860     if (reader_sp)
861         reader_sp->Interrupt();
862 }
863 
864 void
865 Debugger::DispatchInputEndOfFile ()
866 {
867     Mutex::Locker locker (m_input_reader_stack.GetMutex());
868     IOHandlerSP reader_sp (m_input_reader_stack.Top());
869     if (reader_sp)
870         reader_sp->GotEOF();
871 }
872 
873 void
874 Debugger::ClearIOHandlers ()
875 {
876     // The bottom input reader should be the main debugger input reader.  We do not want to close that one here.
877     Mutex::Locker locker (m_input_reader_stack.GetMutex());
878     while (m_input_reader_stack.GetSize() > 1)
879     {
880         IOHandlerSP reader_sp (m_input_reader_stack.Top());
881         if (reader_sp)
882         {
883             m_input_reader_stack.Pop();
884             reader_sp->SetIsDone(true);
885             reader_sp->Cancel();
886         }
887     }
888 }
889 
890 void
891 Debugger::ExecuteIOHanders()
892 {
893 
894     while (1)
895     {
896         IOHandlerSP reader_sp(m_input_reader_stack.Top());
897         if (!reader_sp)
898             break;
899 
900         reader_sp->Activate();
901         reader_sp->Run();
902         reader_sp->Deactivate();
903 
904         // Remove all input readers that are done from the top of the stack
905         while (1)
906         {
907             IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
908             if (top_reader_sp && top_reader_sp->GetIsDone())
909                 m_input_reader_stack.Pop();
910             else
911                 break;
912         }
913     }
914     ClearIOHandlers();
915 }
916 
917 bool
918 Debugger::IsTopIOHandler (const lldb::IOHandlerSP& reader_sp)
919 {
920     return m_input_reader_stack.IsTop (reader_sp);
921 }
922 
923 
924 ConstString
925 Debugger::GetTopIOHandlerControlSequence(char ch)
926 {
927     return m_input_reader_stack.GetTopIOHandlerControlSequence (ch);
928 }
929 
930 const char *
931 Debugger::GetIOHandlerCommandPrefix()
932 {
933     return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
934 }
935 
936 const char *
937 Debugger::GetIOHandlerHelpPrologue()
938 {
939     return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
940 }
941 
942 void
943 Debugger::RunIOHandler (const IOHandlerSP& reader_sp)
944 {
945     PushIOHandler (reader_sp);
946 
947     IOHandlerSP top_reader_sp = reader_sp;
948     while (top_reader_sp)
949     {
950         top_reader_sp->Activate();
951         top_reader_sp->Run();
952         top_reader_sp->Deactivate();
953 
954         if (top_reader_sp.get() == reader_sp.get())
955         {
956             if (PopIOHandler (reader_sp))
957                 break;
958         }
959 
960         while (1)
961         {
962             top_reader_sp = m_input_reader_stack.Top();
963             if (top_reader_sp && top_reader_sp->GetIsDone())
964                 m_input_reader_stack.Pop();
965             else
966                 break;
967         }
968     }
969 }
970 
971 void
972 Debugger::AdoptTopIOHandlerFilesIfInvalid (StreamFileSP &in, StreamFileSP &out, StreamFileSP &err)
973 {
974     // Before an IOHandler runs, it must have in/out/err streams.
975     // This function is called when one ore more of the streams
976     // are NULL. We use the top input reader's in/out/err streams,
977     // or fall back to the debugger file handles, or we fall back
978     // onto stdin/stdout/stderr as a last resort.
979 
980     Mutex::Locker locker (m_input_reader_stack.GetMutex());
981     IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
982     // If no STDIN has been set, then set it appropriately
983     if (!in)
984     {
985         if (top_reader_sp)
986             in = top_reader_sp->GetInputStreamFile();
987         else
988             in = GetInputFile();
989 
990         // If there is nothing, use stdin
991         if (!in)
992             in = StreamFileSP(new StreamFile(stdin, false));
993     }
994     // If no STDOUT has been set, then set it appropriately
995     if (!out)
996     {
997         if (top_reader_sp)
998             out = top_reader_sp->GetOutputStreamFile();
999         else
1000             out = GetOutputFile();
1001 
1002         // If there is nothing, use stdout
1003         if (!out)
1004             out = StreamFileSP(new StreamFile(stdout, false));
1005     }
1006     // If no STDERR has been set, then set it appropriately
1007     if (!err)
1008     {
1009         if (top_reader_sp)
1010             err = top_reader_sp->GetErrorStreamFile();
1011         else
1012             err = GetErrorFile();
1013 
1014         // If there is nothing, use stderr
1015         if (!err)
1016             err = StreamFileSP(new StreamFile(stdout, false));
1017 
1018     }
1019 }
1020 
1021 void
1022 Debugger::PushIOHandler (const IOHandlerSP& reader_sp)
1023 {
1024     if (!reader_sp)
1025         return;
1026 
1027     // Got the current top input reader...
1028     IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
1029 
1030     // Don't push the same IO handler twice...
1031     if (reader_sp.get() != top_reader_sp.get())
1032     {
1033         // Push our new input reader
1034         m_input_reader_stack.Push (reader_sp);
1035 
1036         // Interrupt the top input reader to it will exit its Run() function
1037         // and let this new input reader take over
1038         if (top_reader_sp)
1039             top_reader_sp->Deactivate();
1040     }
1041 }
1042 
1043 bool
1044 Debugger::PopIOHandler (const IOHandlerSP& pop_reader_sp)
1045 {
1046     bool result = false;
1047 
1048     Mutex::Locker locker (m_input_reader_stack.GetMutex());
1049 
1050     // The reader on the stop of the stack is done, so let the next
1051     // read on the stack refresh its prompt and if there is one...
1052     if (!m_input_reader_stack.IsEmpty())
1053     {
1054         IOHandlerSP reader_sp(m_input_reader_stack.Top());
1055 
1056         if (!pop_reader_sp || pop_reader_sp.get() == reader_sp.get())
1057         {
1058             reader_sp->Deactivate();
1059             reader_sp->Cancel();
1060             m_input_reader_stack.Pop ();
1061 
1062             reader_sp = m_input_reader_stack.Top();
1063             if (reader_sp)
1064                 reader_sp->Activate();
1065 
1066             result = true;
1067         }
1068     }
1069     return result;
1070 }
1071 
1072 bool
1073 Debugger::HideTopIOHandler()
1074 {
1075     Mutex::Locker locker;
1076 
1077     if (locker.TryLock(m_input_reader_stack.GetMutex()))
1078     {
1079         IOHandlerSP reader_sp(m_input_reader_stack.Top());
1080         if (reader_sp)
1081             reader_sp->Hide();
1082         return true;
1083     }
1084     return false;
1085 }
1086 
1087 void
1088 Debugger::RefreshTopIOHandler()
1089 {
1090     IOHandlerSP reader_sp(m_input_reader_stack.Top());
1091     if (reader_sp)
1092         reader_sp->Refresh();
1093 }
1094 
1095 
1096 StreamSP
1097 Debugger::GetAsyncOutputStream ()
1098 {
1099     return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
1100                                                CommandInterpreter::eBroadcastBitAsynchronousOutputData));
1101 }
1102 
1103 StreamSP
1104 Debugger::GetAsyncErrorStream ()
1105 {
1106     return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
1107                                                CommandInterpreter::eBroadcastBitAsynchronousErrorData));
1108 }
1109 
1110 size_t
1111 Debugger::GetNumDebuggers()
1112 {
1113     if (g_shared_debugger_refcount > 0)
1114     {
1115         Mutex::Locker locker (GetDebuggerListMutex ());
1116         return GetDebuggerList().size();
1117     }
1118     return 0;
1119 }
1120 
1121 lldb::DebuggerSP
1122 Debugger::GetDebuggerAtIndex (size_t index)
1123 {
1124     DebuggerSP debugger_sp;
1125 
1126     if (g_shared_debugger_refcount > 0)
1127     {
1128         Mutex::Locker locker (GetDebuggerListMutex ());
1129         DebuggerList &debugger_list = GetDebuggerList();
1130 
1131         if (index < debugger_list.size())
1132             debugger_sp = debugger_list[index];
1133     }
1134 
1135     return debugger_sp;
1136 }
1137 
1138 DebuggerSP
1139 Debugger::FindDebuggerWithID (lldb::user_id_t id)
1140 {
1141     DebuggerSP debugger_sp;
1142 
1143     if (g_shared_debugger_refcount > 0)
1144     {
1145         Mutex::Locker locker (GetDebuggerListMutex ());
1146         DebuggerList &debugger_list = GetDebuggerList();
1147         DebuggerList::iterator pos, end = debugger_list.end();
1148         for (pos = debugger_list.begin(); pos != end; ++pos)
1149         {
1150             if ((*pos).get()->GetID() == id)
1151             {
1152                 debugger_sp = *pos;
1153                 break;
1154             }
1155         }
1156     }
1157     return debugger_sp;
1158 }
1159 
1160 #if 0
1161 static void
1162 TestPromptFormats (StackFrame *frame)
1163 {
1164     if (frame == NULL)
1165         return;
1166 
1167     StreamString s;
1168     const char *prompt_format =
1169     "{addr = '${addr}'\n}"
1170     "{addr-file-or-load = '${addr-file-or-load}'\n}"
1171     "{current-pc-arrow = '${current-pc-arrow}'\n}"
1172     "{process.id = '${process.id}'\n}"
1173     "{process.name = '${process.name}'\n}"
1174     "{process.file.basename = '${process.file.basename}'\n}"
1175     "{process.file.fullpath = '${process.file.fullpath}'\n}"
1176     "{thread.id = '${thread.id}'\n}"
1177     "{thread.index = '${thread.index}'\n}"
1178     "{thread.name = '${thread.name}'\n}"
1179     "{thread.queue = '${thread.queue}'\n}"
1180     "{thread.stop-reason = '${thread.stop-reason}'\n}"
1181     "{target.arch = '${target.arch}'\n}"
1182     "{module.file.basename = '${module.file.basename}'\n}"
1183     "{module.file.fullpath = '${module.file.fullpath}'\n}"
1184     "{file.basename = '${file.basename}'\n}"
1185     "{file.fullpath = '${file.fullpath}'\n}"
1186     "{frame.index = '${frame.index}'\n}"
1187     "{frame.pc = '${frame.pc}'\n}"
1188     "{frame.sp = '${frame.sp}'\n}"
1189     "{frame.fp = '${frame.fp}'\n}"
1190     "{frame.flags = '${frame.flags}'\n}"
1191     "{frame.reg.rdi = '${frame.reg.rdi}'\n}"
1192     "{frame.reg.rip = '${frame.reg.rip}'\n}"
1193     "{frame.reg.rsp = '${frame.reg.rsp}'\n}"
1194     "{frame.reg.rbp = '${frame.reg.rbp}'\n}"
1195     "{frame.reg.rflags = '${frame.reg.rflags}'\n}"
1196     "{frame.reg.xmm0 = '${frame.reg.xmm0}'\n}"
1197     "{frame.reg.carp = '${frame.reg.carp}'\n}"
1198     "{function.id = '${function.id}'\n}"
1199     "{function.changed = '${function.changed}'\n}"
1200     "{function.initial-function = '${function.initial-function}'\n}"
1201     "{function.name = '${function.name}'\n}"
1202     "{function.name-without-args = '${function.name-without-args}'\n}"
1203     "{function.name-with-args = '${function.name-with-args}'\n}"
1204     "{function.addr-offset = '${function.addr-offset}'\n}"
1205     "{function.concrete-only-addr-offset-no-padding = '${function.concrete-only-addr-offset-no-padding}'\n}"
1206     "{function.line-offset = '${function.line-offset}'\n}"
1207     "{function.pc-offset = '${function.pc-offset}'\n}"
1208     "{line.file.basename = '${line.file.basename}'\n}"
1209     "{line.file.fullpath = '${line.file.fullpath}'\n}"
1210     "{line.number = '${line.number}'\n}"
1211     "{line.start-addr = '${line.start-addr}'\n}"
1212     "{line.end-addr = '${line.end-addr}'\n}"
1213 ;
1214 
1215     SymbolContext sc (frame->GetSymbolContext(eSymbolContextEverything));
1216     ExecutionContext exe_ctx;
1217     frame->CalculateExecutionContext(exe_ctx);
1218     if (Debugger::FormatPrompt (prompt_format, &sc, &exe_ctx, &sc.line_entry.range.GetBaseAddress(), s))
1219     {
1220         printf("%s\n", s.GetData());
1221     }
1222     else
1223     {
1224         printf ("what we got: %s\n", s.GetData());
1225     }
1226 }
1227 #endif
1228 
1229 bool
1230 Debugger::FormatDisassemblerAddress (const FormatEntity::Entry *format,
1231                                      const SymbolContext *sc,
1232                                      const SymbolContext *prev_sc,
1233                                      const ExecutionContext *exe_ctx,
1234                                      const Address *addr,
1235                                      Stream &s)
1236 {
1237     FormatEntity::Entry format_entry;
1238 
1239     if (format == NULL)
1240     {
1241         if (exe_ctx != NULL && exe_ctx->HasTargetScope())
1242             format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1243         if (format == NULL)
1244         {
1245             FormatEntity::Parse("${addr}: ", format_entry);
1246             format = &format_entry;
1247         }
1248     }
1249     bool function_changed = false;
1250     bool initial_function = false;
1251     if (prev_sc && (prev_sc->function || prev_sc->symbol))
1252     {
1253         if (sc && (sc->function || sc->symbol))
1254         {
1255             if (prev_sc->symbol && sc->symbol)
1256             {
1257                 if (!sc->symbol->Compare (prev_sc->symbol->GetName(), prev_sc->symbol->GetType()))
1258                 {
1259                     function_changed = true;
1260                 }
1261             }
1262             else if (prev_sc->function && sc->function)
1263             {
1264                 if (prev_sc->function->GetMangled() != sc->function->GetMangled())
1265                 {
1266                     function_changed = true;
1267                 }
1268             }
1269         }
1270     }
1271     // The first context on a list of instructions will have a prev_sc that
1272     // has no Function or Symbol -- if SymbolContext had an IsValid() method, it
1273     // would return false.  But we do get a prev_sc pointer.
1274     if ((sc && (sc->function || sc->symbol))
1275         && prev_sc && (prev_sc->function == NULL && prev_sc->symbol == NULL))
1276     {
1277         initial_function = true;
1278     }
1279     return FormatEntity::Format(*format, s, sc, exe_ctx, addr, NULL, function_changed, initial_function);
1280 }
1281 
1282 
1283 void
1284 Debugger::SetLoggingCallback (lldb::LogOutputCallback log_callback, void *baton)
1285 {
1286     // For simplicity's sake, I am not going to deal with how to close down any
1287     // open logging streams, I just redirect everything from here on out to the
1288     // callback.
1289     m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
1290 }
1291 
1292 bool
1293 Debugger::EnableLog (const char *channel, const char **categories, const char *log_file, uint32_t log_options, Stream &error_stream)
1294 {
1295     Log::Callbacks log_callbacks;
1296 
1297     StreamSP log_stream_sp;
1298     if (m_log_callback_stream_sp)
1299     {
1300         log_stream_sp = m_log_callback_stream_sp;
1301         // For now when using the callback mode you always get thread & timestamp.
1302         log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
1303     }
1304     else if (log_file == NULL || *log_file == '\0')
1305     {
1306         log_stream_sp = GetOutputFile();
1307     }
1308     else
1309     {
1310         LogStreamMap::iterator pos = m_log_streams.find(log_file);
1311         if (pos != m_log_streams.end())
1312             log_stream_sp = pos->second.lock();
1313         if (!log_stream_sp)
1314         {
1315             log_stream_sp.reset (new StreamFile (log_file));
1316             m_log_streams[log_file] = log_stream_sp;
1317         }
1318     }
1319     assert (log_stream_sp.get());
1320 
1321     if (log_options == 0)
1322         log_options = LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1323 
1324     if (Log::GetLogChannelCallbacks (ConstString(channel), log_callbacks))
1325     {
1326         log_callbacks.enable (log_stream_sp, log_options, categories, &error_stream);
1327         return true;
1328     }
1329     else
1330     {
1331         LogChannelSP log_channel_sp (LogChannel::FindPlugin (channel));
1332         if (log_channel_sp)
1333         {
1334             if (log_channel_sp->Enable (log_stream_sp, log_options, &error_stream, categories))
1335             {
1336                 return true;
1337             }
1338             else
1339             {
1340                 error_stream.Printf ("Invalid log channel '%s'.\n", channel);
1341                 return false;
1342             }
1343         }
1344         else
1345         {
1346             error_stream.Printf ("Invalid log channel '%s'.\n", channel);
1347             return false;
1348         }
1349     }
1350     return false;
1351 }
1352 
1353 SourceManager &
1354 Debugger::GetSourceManager ()
1355 {
1356     if (m_source_manager_ap.get() == NULL)
1357         m_source_manager_ap.reset (new SourceManager (shared_from_this()));
1358     return *m_source_manager_ap;
1359 }
1360 
1361 
1362 
1363 // This function handles events that were broadcast by the process.
1364 void
1365 Debugger::HandleBreakpointEvent (const EventSP &event_sp)
1366 {
1367     using namespace lldb;
1368     const uint32_t event_type = Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent (event_sp);
1369 
1370 //    if (event_type & eBreakpointEventTypeAdded
1371 //        || event_type & eBreakpointEventTypeRemoved
1372 //        || event_type & eBreakpointEventTypeEnabled
1373 //        || event_type & eBreakpointEventTypeDisabled
1374 //        || event_type & eBreakpointEventTypeCommandChanged
1375 //        || event_type & eBreakpointEventTypeConditionChanged
1376 //        || event_type & eBreakpointEventTypeIgnoreChanged
1377 //        || event_type & eBreakpointEventTypeLocationsResolved)
1378 //    {
1379 //        // Don't do anything about these events, since the breakpoint commands already echo these actions.
1380 //    }
1381 //
1382     if (event_type & eBreakpointEventTypeLocationsAdded)
1383     {
1384         uint32_t num_new_locations = Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(event_sp);
1385         if (num_new_locations > 0)
1386         {
1387             BreakpointSP breakpoint = Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1388             StreamFileSP output_sp (GetOutputFile());
1389             if (output_sp)
1390             {
1391                 output_sp->Printf("%d location%s added to breakpoint %d\n",
1392                                   num_new_locations,
1393                                   num_new_locations == 1 ? "" : "s",
1394                                   breakpoint->GetID());
1395                 RefreshTopIOHandler();
1396             }
1397         }
1398     }
1399 //    else if (event_type & eBreakpointEventTypeLocationsRemoved)
1400 //    {
1401 //        // These locations just get disabled, not sure it is worth spamming folks about this on the command line.
1402 //    }
1403 //    else if (event_type & eBreakpointEventTypeLocationsResolved)
1404 //    {
1405 //        // This might be an interesting thing to note, but I'm going to leave it quiet for now, it just looked noisy.
1406 //    }
1407 }
1408 
1409 size_t
1410 Debugger::GetProcessSTDOUT (Process *process, Stream *stream)
1411 {
1412     size_t total_bytes = 0;
1413     if (stream == NULL)
1414         stream = GetOutputFile().get();
1415 
1416     if (stream)
1417     {
1418         //  The process has stuff waiting for stdout; get it and write it out to the appropriate place.
1419         if (process == NULL)
1420         {
1421             TargetSP target_sp = GetTargetList().GetSelectedTarget();
1422             if (target_sp)
1423                 process = target_sp->GetProcessSP().get();
1424         }
1425         if (process)
1426         {
1427             Error error;
1428             size_t len;
1429             char stdio_buffer[1024];
1430             while ((len = process->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
1431             {
1432                 stream->Write(stdio_buffer, len);
1433                 total_bytes += len;
1434             }
1435         }
1436         stream->Flush();
1437     }
1438     return total_bytes;
1439 }
1440 
1441 size_t
1442 Debugger::GetProcessSTDERR (Process *process, Stream *stream)
1443 {
1444     size_t total_bytes = 0;
1445     if (stream == NULL)
1446         stream = GetOutputFile().get();
1447 
1448     if (stream)
1449     {
1450         //  The process has stuff waiting for stderr; get it and write it out to the appropriate place.
1451         if (process == NULL)
1452         {
1453             TargetSP target_sp = GetTargetList().GetSelectedTarget();
1454             if (target_sp)
1455                 process = target_sp->GetProcessSP().get();
1456         }
1457         if (process)
1458         {
1459             Error error;
1460             size_t len;
1461             char stdio_buffer[1024];
1462             while ((len = process->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
1463             {
1464                 stream->Write(stdio_buffer, len);
1465                 total_bytes += len;
1466             }
1467         }
1468         stream->Flush();
1469     }
1470     return total_bytes;
1471 }
1472 
1473 
1474 // This function handles events that were broadcast by the process.
1475 void
1476 Debugger::HandleProcessEvent (const EventSP &event_sp)
1477 {
1478     using namespace lldb;
1479     const uint32_t event_type = event_sp->GetType();
1480     ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1481 
1482     StreamString output_stream;
1483     StreamString error_stream;
1484     const bool gui_enabled = IsForwardingEvents();
1485 
1486     if (!gui_enabled)
1487     {
1488         bool pop_process_io_handler = false;
1489         assert (process_sp);
1490 
1491         if (event_type & Process::eBroadcastBitSTDOUT || event_type & Process::eBroadcastBitStateChanged)
1492         {
1493             GetProcessSTDOUT (process_sp.get(), &output_stream);
1494         }
1495 
1496         if (event_type & Process::eBroadcastBitSTDERR || event_type & Process::eBroadcastBitStateChanged)
1497         {
1498             GetProcessSTDERR (process_sp.get(), &error_stream);
1499         }
1500 
1501         if (event_type & Process::eBroadcastBitStateChanged)
1502         {
1503             Process::HandleProcessStateChangedEvent (event_sp, &output_stream, pop_process_io_handler);
1504         }
1505 
1506         if (output_stream.GetSize() || error_stream.GetSize())
1507         {
1508             StreamFileSP error_stream_sp (GetOutputFile());
1509             bool top_io_handler_hid = false;
1510 
1511             if (process_sp->ProcessIOHandlerIsActive() == false)
1512                 top_io_handler_hid = HideTopIOHandler();
1513 
1514             if (output_stream.GetSize())
1515             {
1516                 StreamFileSP output_stream_sp (GetOutputFile());
1517                 if (output_stream_sp)
1518                     output_stream_sp->Write (output_stream.GetData(), output_stream.GetSize());
1519             }
1520 
1521             if (error_stream.GetSize())
1522             {
1523                 StreamFileSP error_stream_sp (GetErrorFile());
1524                 if (error_stream_sp)
1525                     error_stream_sp->Write (error_stream.GetData(), error_stream.GetSize());
1526             }
1527 
1528             if (top_io_handler_hid)
1529                 RefreshTopIOHandler();
1530         }
1531 
1532         if (pop_process_io_handler)
1533             process_sp->PopProcessIOHandler();
1534     }
1535 }
1536 
1537 void
1538 Debugger::HandleThreadEvent (const EventSP &event_sp)
1539 {
1540     // At present the only thread event we handle is the Frame Changed event,
1541     // and all we do for that is just reprint the thread status for that thread.
1542     using namespace lldb;
1543     const uint32_t event_type = event_sp->GetType();
1544     if (event_type == Thread::eBroadcastBitStackChanged   ||
1545         event_type == Thread::eBroadcastBitThreadSelected )
1546     {
1547         ThreadSP thread_sp (Thread::ThreadEventData::GetThreadFromEvent (event_sp.get()));
1548         if (thread_sp)
1549         {
1550             HideTopIOHandler();
1551             StreamFileSP stream_sp (GetOutputFile());
1552             thread_sp->GetStatus(*stream_sp, 0, 1, 1);
1553             RefreshTopIOHandler();
1554         }
1555     }
1556 }
1557 
1558 bool
1559 Debugger::IsForwardingEvents ()
1560 {
1561     return (bool)m_forward_listener_sp;
1562 }
1563 
1564 void
1565 Debugger::EnableForwardEvents (const ListenerSP &listener_sp)
1566 {
1567     m_forward_listener_sp = listener_sp;
1568 }
1569 
1570 void
1571 Debugger::CancelForwardEvents (const ListenerSP &listener_sp)
1572 {
1573     m_forward_listener_sp.reset();
1574 }
1575 
1576 
1577 void
1578 Debugger::DefaultEventHandler()
1579 {
1580     Listener& listener(GetListener());
1581     ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1582     ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1583     ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1584     BroadcastEventSpec target_event_spec (broadcaster_class_target,
1585                                           Target::eBroadcastBitBreakpointChanged);
1586 
1587     BroadcastEventSpec process_event_spec (broadcaster_class_process,
1588                                            Process::eBroadcastBitStateChanged   |
1589                                            Process::eBroadcastBitSTDOUT         |
1590                                            Process::eBroadcastBitSTDERR);
1591 
1592     BroadcastEventSpec thread_event_spec (broadcaster_class_thread,
1593                                           Thread::eBroadcastBitStackChanged     |
1594                                           Thread::eBroadcastBitThreadSelected   );
1595 
1596     listener.StartListeningForEventSpec (*this, target_event_spec);
1597     listener.StartListeningForEventSpec (*this, process_event_spec);
1598     listener.StartListeningForEventSpec (*this, thread_event_spec);
1599     listener.StartListeningForEvents (m_command_interpreter_ap.get(),
1600                                       CommandInterpreter::eBroadcastBitQuitCommandReceived      |
1601                                       CommandInterpreter::eBroadcastBitAsynchronousOutputData   |
1602                                       CommandInterpreter::eBroadcastBitAsynchronousErrorData    );
1603 
1604     // Let the thread that spawned us know that we have started up and
1605     // that we are now listening to all required events so no events get missed
1606     m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
1607 
1608     bool done = false;
1609     while (!done)
1610     {
1611         EventSP event_sp;
1612         if (listener.WaitForEvent(NULL, event_sp))
1613         {
1614             if (event_sp)
1615             {
1616                 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1617                 if (broadcaster)
1618                 {
1619                     uint32_t event_type = event_sp->GetType();
1620                     ConstString broadcaster_class (broadcaster->GetBroadcasterClass());
1621                     if (broadcaster_class == broadcaster_class_process)
1622                     {
1623                         HandleProcessEvent (event_sp);
1624                     }
1625                     else if (broadcaster_class == broadcaster_class_target)
1626                     {
1627                         if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(event_sp.get()))
1628                         {
1629                             HandleBreakpointEvent (event_sp);
1630                         }
1631                     }
1632                     else if (broadcaster_class == broadcaster_class_thread)
1633                     {
1634                         HandleThreadEvent (event_sp);
1635                     }
1636                     else if (broadcaster == m_command_interpreter_ap.get())
1637                     {
1638                         if (event_type & CommandInterpreter::eBroadcastBitQuitCommandReceived)
1639                         {
1640                             done = true;
1641                         }
1642                         else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousErrorData)
1643                         {
1644                             const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
1645                             if (data && data[0])
1646                             {
1647                                 StreamFileSP error_sp (GetErrorFile());
1648                                 if (error_sp)
1649                                 {
1650                                     HideTopIOHandler();
1651                                     error_sp->PutCString(data);
1652                                     error_sp->Flush();
1653                                     RefreshTopIOHandler();
1654                                 }
1655                             }
1656                         }
1657                         else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousOutputData)
1658                         {
1659                             const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
1660                             if (data && data[0])
1661                             {
1662                                 StreamFileSP output_sp (GetOutputFile());
1663                                 if (output_sp)
1664                                 {
1665                                     HideTopIOHandler();
1666                                     output_sp->PutCString(data);
1667                                     output_sp->Flush();
1668                                     RefreshTopIOHandler();
1669                                 }
1670                             }
1671                         }
1672                     }
1673                 }
1674 
1675                 if (m_forward_listener_sp)
1676                     m_forward_listener_sp->AddEvent(event_sp);
1677             }
1678         }
1679     }
1680 }
1681 
1682 lldb::thread_result_t
1683 Debugger::EventHandlerThread (lldb::thread_arg_t arg)
1684 {
1685     ((Debugger *)arg)->DefaultEventHandler();
1686     return NULL;
1687 }
1688 
1689 bool
1690 Debugger::StartEventHandlerThread()
1691 {
1692     if (!m_event_handler_thread.IsJoinable())
1693     {
1694         // We must synchronize with the DefaultEventHandler() thread to ensure
1695         // it is up and running and listening to events before we return from
1696         // this function. We do this by listening to events for the
1697         // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
1698         Listener listener("lldb.debugger.event-handler");
1699         listener.StartListeningForEvents(&m_sync_broadcaster, eBroadcastBitEventThreadIsListening);
1700 
1701         // Use larger 8MB stack for this thread
1702         m_event_handler_thread = ThreadLauncher::LaunchThread("lldb.debugger.event-handler", EventHandlerThread,
1703                                                               this,
1704                                                               NULL,
1705                                                               g_debugger_event_thread_stack_bytes);
1706 
1707         // Make sure DefaultEventHandler() is running and listening to events before we return
1708         // from this function. We are only listening for events of type
1709         // eBroadcastBitEventThreadIsListening so we don't need to check the event, we just need
1710         // to wait an infinite amount of time for it (NULL timeout as the first parameter)
1711         lldb::EventSP event_sp;
1712         listener.WaitForEvent(NULL, event_sp);
1713     }
1714     return m_event_handler_thread.IsJoinable();
1715 }
1716 
1717 void
1718 Debugger::StopEventHandlerThread()
1719 {
1720     if (m_event_handler_thread.IsJoinable())
1721     {
1722         GetCommandInterpreter().BroadcastEvent(CommandInterpreter::eBroadcastBitQuitCommandReceived);
1723         m_event_handler_thread.Join(nullptr);
1724     }
1725 }
1726 
1727 
1728 lldb::thread_result_t
1729 Debugger::IOHandlerThread (lldb::thread_arg_t arg)
1730 {
1731     Debugger *debugger = (Debugger *)arg;
1732     debugger->ExecuteIOHanders();
1733     debugger->StopEventHandlerThread();
1734     return NULL;
1735 }
1736 
1737 bool
1738 Debugger::StartIOHandlerThread()
1739 {
1740     if (!m_io_handler_thread.IsJoinable())
1741         m_io_handler_thread = ThreadLauncher::LaunchThread ("lldb.debugger.io-handler",
1742                                                             IOHandlerThread,
1743                                                             this,
1744                                                             NULL,
1745                                                             8*1024*1024); // Use larger 8MB stack for this thread
1746     return m_io_handler_thread.IsJoinable();
1747 }
1748 
1749 void
1750 Debugger::StopIOHandlerThread()
1751 {
1752     if (m_io_handler_thread.IsJoinable())
1753     {
1754         if (m_input_file_sp)
1755             m_input_file_sp->GetFile().Close();
1756         m_io_handler_thread.Join(nullptr);
1757     }
1758 }
1759 
1760 Target *
1761 Debugger::GetDummyTarget()
1762 {
1763     return m_target_list.GetDummyTarget (*this).get();
1764 }
1765 
1766 Target *
1767 Debugger::GetSelectedOrDummyTarget(bool prefer_dummy)
1768 {
1769     Target *target = nullptr;
1770     if (!prefer_dummy)
1771     {
1772         target = m_target_list.GetSelectedTarget().get();
1773         if (target)
1774             return target;
1775     }
1776 
1777     return GetDummyTarget();
1778 }
1779 
1780