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