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