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