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