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