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