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