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