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