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