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