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