]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Core/Debugger.cpp
Update our devicetree to 4.19 for arm and arm64
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Core / Debugger.cpp
1 //===-- Debugger.cpp --------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "lldb/Core/Debugger.h"
11
12 #include "lldb/Breakpoint/Breakpoint.h" // 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 bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1166                                          const SymbolContext *sc,
1167                                          const SymbolContext *prev_sc,
1168                                          const ExecutionContext *exe_ctx,
1169                                          const Address *addr, Stream &s) {
1170   FormatEntity::Entry format_entry;
1171
1172   if (format == nullptr) {
1173     if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1174       format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1175     if (format == nullptr) {
1176       FormatEntity::Parse("${addr}: ", format_entry);
1177       format = &format_entry;
1178     }
1179   }
1180   bool function_changed = false;
1181   bool initial_function = false;
1182   if (prev_sc && (prev_sc->function || prev_sc->symbol)) {
1183     if (sc && (sc->function || sc->symbol)) {
1184       if (prev_sc->symbol && sc->symbol) {
1185         if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1186                                  prev_sc->symbol->GetType())) {
1187           function_changed = true;
1188         }
1189       } else if (prev_sc->function && sc->function) {
1190         if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1191           function_changed = true;
1192         }
1193       }
1194     }
1195   }
1196   // The first context on a list of instructions will have a prev_sc that
1197   // has no Function or Symbol -- if SymbolContext had an IsValid() method, it
1198   // would return false.  But we do get a prev_sc pointer.
1199   if ((sc && (sc->function || sc->symbol)) && prev_sc &&
1200       (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) {
1201     initial_function = true;
1202   }
1203   return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1204                               function_changed, initial_function);
1205 }
1206
1207 void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1208                                   void *baton) {
1209   // For simplicity's sake, I am not going to deal with how to close down any
1210   // open logging streams, I just redirect everything from here on out to the
1211   // callback.
1212   m_log_callback_stream_sp =
1213       std::make_shared<StreamCallback>(log_callback, baton);
1214 }
1215
1216 bool Debugger::EnableLog(llvm::StringRef channel,
1217                          llvm::ArrayRef<const char *> categories,
1218                          llvm::StringRef log_file, uint32_t log_options,
1219                          llvm::raw_ostream &error_stream) {
1220   const bool should_close = true;
1221   const bool unbuffered = true;
1222
1223   std::shared_ptr<llvm::raw_ostream> log_stream_sp;
1224   if (m_log_callback_stream_sp) {
1225     log_stream_sp = m_log_callback_stream_sp;
1226     // For now when using the callback mode you always get thread & timestamp.
1227     log_options |=
1228         LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
1229   } else if (log_file.empty()) {
1230     log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1231         GetOutputFile()->GetFile().GetDescriptor(), !should_close, unbuffered);
1232   } else {
1233     auto pos = m_log_streams.find(log_file);
1234     if (pos != m_log_streams.end())
1235       log_stream_sp = pos->second.lock();
1236     if (!log_stream_sp) {
1237       llvm::sys::fs::OpenFlags flags = llvm::sys::fs::F_Text;
1238       if (log_options & LLDB_LOG_OPTION_APPEND)
1239         flags |= llvm::sys::fs::F_Append;
1240       int FD;
1241       if (std::error_code ec =
1242               llvm::sys::fs::openFileForWrite(log_file, FD, flags)) {
1243         error_stream << "Unable to open log file: " << ec.message();
1244         return false;
1245       }
1246       log_stream_sp =
1247           std::make_shared<llvm::raw_fd_ostream>(FD, should_close, unbuffered);
1248       m_log_streams[log_file] = log_stream_sp;
1249     }
1250   }
1251   assert(log_stream_sp);
1252
1253   if (log_options == 0)
1254     log_options =
1255         LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1256
1257   return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories,
1258                                error_stream);
1259 }
1260
1261 SourceManager &Debugger::GetSourceManager() {
1262   if (!m_source_manager_ap)
1263     m_source_manager_ap = llvm::make_unique<SourceManager>(shared_from_this());
1264   return *m_source_manager_ap;
1265 }
1266
1267 // This function handles events that were broadcast by the process.
1268 void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1269   using namespace lldb;
1270   const uint32_t event_type =
1271       Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1272           event_sp);
1273
1274   //    if (event_type & eBreakpointEventTypeAdded
1275   //        || event_type & eBreakpointEventTypeRemoved
1276   //        || event_type & eBreakpointEventTypeEnabled
1277   //        || event_type & eBreakpointEventTypeDisabled
1278   //        || event_type & eBreakpointEventTypeCommandChanged
1279   //        || event_type & eBreakpointEventTypeConditionChanged
1280   //        || event_type & eBreakpointEventTypeIgnoreChanged
1281   //        || event_type & eBreakpointEventTypeLocationsResolved)
1282   //    {
1283   //        // Don't do anything about these events, since the breakpoint
1284   //        commands already echo these actions.
1285   //    }
1286   //
1287   if (event_type & eBreakpointEventTypeLocationsAdded) {
1288     uint32_t num_new_locations =
1289         Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1290             event_sp);
1291     if (num_new_locations > 0) {
1292       BreakpointSP breakpoint =
1293           Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1294       StreamSP output_sp(GetAsyncOutputStream());
1295       if (output_sp) {
1296         output_sp->Printf("%d location%s added to breakpoint %d\n",
1297                           num_new_locations, num_new_locations == 1 ? "" : "s",
1298                           breakpoint->GetID());
1299         output_sp->Flush();
1300       }
1301     }
1302   }
1303   //    else if (event_type & eBreakpointEventTypeLocationsRemoved)
1304   //    {
1305   //        // These locations just get disabled, not sure it is worth spamming
1306   //        folks about this on the command line.
1307   //    }
1308   //    else if (event_type & eBreakpointEventTypeLocationsResolved)
1309   //    {
1310   //        // This might be an interesting thing to note, but I'm going to
1311   //        leave it quiet for now, it just looked noisy.
1312   //    }
1313 }
1314
1315 size_t Debugger::GetProcessSTDOUT(Process *process, Stream *stream) {
1316   size_t total_bytes = 0;
1317   if (stream == nullptr)
1318     stream = GetOutputFile().get();
1319
1320   if (stream) {
1321     //  The process has stuff waiting for stdout; get it and write it out to the
1322     //  appropriate place.
1323     if (process == nullptr) {
1324       TargetSP target_sp = GetTargetList().GetSelectedTarget();
1325       if (target_sp)
1326         process = target_sp->GetProcessSP().get();
1327     }
1328     if (process) {
1329       Status error;
1330       size_t len;
1331       char stdio_buffer[1024];
1332       while ((len = process->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
1333                                        error)) > 0) {
1334         stream->Write(stdio_buffer, len);
1335         total_bytes += len;
1336       }
1337     }
1338     stream->Flush();
1339   }
1340   return total_bytes;
1341 }
1342
1343 size_t Debugger::GetProcessSTDERR(Process *process, Stream *stream) {
1344   size_t total_bytes = 0;
1345   if (stream == nullptr)
1346     stream = GetOutputFile().get();
1347
1348   if (stream) {
1349     //  The process has stuff waiting for stderr; get it and write it out to the
1350     //  appropriate place.
1351     if (process == nullptr) {
1352       TargetSP target_sp = GetTargetList().GetSelectedTarget();
1353       if (target_sp)
1354         process = target_sp->GetProcessSP().get();
1355     }
1356     if (process) {
1357       Status error;
1358       size_t len;
1359       char stdio_buffer[1024];
1360       while ((len = process->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
1361                                        error)) > 0) {
1362         stream->Write(stdio_buffer, len);
1363         total_bytes += len;
1364       }
1365     }
1366     stream->Flush();
1367   }
1368   return total_bytes;
1369 }
1370
1371 // This function handles events that were broadcast by the process.
1372 void Debugger::HandleProcessEvent(const EventSP &event_sp) {
1373   using namespace lldb;
1374   const uint32_t event_type = event_sp->GetType();
1375   ProcessSP process_sp =
1376       (event_type == Process::eBroadcastBitStructuredData)
1377           ? EventDataStructuredData::GetProcessFromEvent(event_sp.get())
1378           : Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1379
1380   StreamSP output_stream_sp = GetAsyncOutputStream();
1381   StreamSP error_stream_sp = GetAsyncErrorStream();
1382   const bool gui_enabled = IsForwardingEvents();
1383
1384   if (!gui_enabled) {
1385     bool pop_process_io_handler = false;
1386     assert(process_sp);
1387
1388     bool state_is_stopped = false;
1389     const bool got_state_changed =
1390         (event_type & Process::eBroadcastBitStateChanged) != 0;
1391     const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1392     const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1393     const bool got_structured_data =
1394         (event_type & Process::eBroadcastBitStructuredData) != 0;
1395
1396     if (got_state_changed) {
1397       StateType event_state =
1398           Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1399       state_is_stopped = StateIsStoppedState(event_state, false);
1400     }
1401
1402     // Display running state changes first before any STDIO
1403     if (got_state_changed && !state_is_stopped) {
1404       Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1405                                               pop_process_io_handler);
1406     }
1407
1408     // Now display and STDOUT
1409     if (got_stdout || got_state_changed) {
1410       GetProcessSTDOUT(process_sp.get(), output_stream_sp.get());
1411     }
1412
1413     // Now display and STDERR
1414     if (got_stderr || got_state_changed) {
1415       GetProcessSTDERR(process_sp.get(), error_stream_sp.get());
1416     }
1417
1418     // Give structured data events an opportunity to display.
1419     if (got_structured_data) {
1420       StructuredDataPluginSP plugin_sp =
1421           EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1422       if (plugin_sp) {
1423         auto structured_data_sp =
1424             EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1425         if (output_stream_sp) {
1426           StreamString content_stream;
1427           Status error =
1428               plugin_sp->GetDescription(structured_data_sp, content_stream);
1429           if (error.Success()) {
1430             if (!content_stream.GetString().empty()) {
1431               // Add newline.
1432               content_stream.PutChar('\n');
1433               content_stream.Flush();
1434
1435               // Print it.
1436               output_stream_sp->PutCString(content_stream.GetString());
1437             }
1438           } else {
1439             error_stream_sp->Printf("Failed to print structured "
1440                                     "data with plugin %s: %s",
1441                                     plugin_sp->GetPluginName().AsCString(),
1442                                     error.AsCString());
1443           }
1444         }
1445       }
1446     }
1447
1448     // Now display any stopped state changes after any STDIO
1449     if (got_state_changed && state_is_stopped) {
1450       Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1451                                               pop_process_io_handler);
1452     }
1453
1454     output_stream_sp->Flush();
1455     error_stream_sp->Flush();
1456
1457     if (pop_process_io_handler)
1458       process_sp->PopProcessIOHandler();
1459   }
1460 }
1461
1462 void Debugger::HandleThreadEvent(const EventSP &event_sp) {
1463   // At present the only thread event we handle is the Frame Changed event,
1464   // and all we do for that is just reprint the thread status for that thread.
1465   using namespace lldb;
1466   const uint32_t event_type = event_sp->GetType();
1467   const bool stop_format = true;
1468   if (event_type == Thread::eBroadcastBitStackChanged ||
1469       event_type == Thread::eBroadcastBitThreadSelected) {
1470     ThreadSP thread_sp(
1471         Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1472     if (thread_sp) {
1473       thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format);
1474     }
1475   }
1476 }
1477
1478 bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1479
1480 void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1481   m_forward_listener_sp = listener_sp;
1482 }
1483
1484 void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1485   m_forward_listener_sp.reset();
1486 }
1487
1488 void Debugger::DefaultEventHandler() {
1489   ListenerSP listener_sp(GetListener());
1490   ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1491   ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1492   ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1493   BroadcastEventSpec target_event_spec(broadcaster_class_target,
1494                                        Target::eBroadcastBitBreakpointChanged);
1495
1496   BroadcastEventSpec process_event_spec(
1497       broadcaster_class_process,
1498       Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1499           Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
1500
1501   BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1502                                        Thread::eBroadcastBitStackChanged |
1503                                            Thread::eBroadcastBitThreadSelected);
1504
1505   listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1506                                           target_event_spec);
1507   listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1508                                           process_event_spec);
1509   listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1510                                           thread_event_spec);
1511   listener_sp->StartListeningForEvents(
1512       m_command_interpreter_ap.get(),
1513       CommandInterpreter::eBroadcastBitQuitCommandReceived |
1514           CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1515           CommandInterpreter::eBroadcastBitAsynchronousErrorData);
1516
1517   // Let the thread that spawned us know that we have started up and
1518   // that we are now listening to all required events so no events get missed
1519   m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
1520
1521   bool done = false;
1522   while (!done) {
1523     EventSP event_sp;
1524     if (listener_sp->GetEvent(event_sp, llvm::None)) {
1525       if (event_sp) {
1526         Broadcaster *broadcaster = event_sp->GetBroadcaster();
1527         if (broadcaster) {
1528           uint32_t event_type = event_sp->GetType();
1529           ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1530           if (broadcaster_class == broadcaster_class_process) {
1531             HandleProcessEvent(event_sp);
1532           } else if (broadcaster_class == broadcaster_class_target) {
1533             if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1534                     event_sp.get())) {
1535               HandleBreakpointEvent(event_sp);
1536             }
1537           } else if (broadcaster_class == broadcaster_class_thread) {
1538             HandleThreadEvent(event_sp);
1539           } else if (broadcaster == m_command_interpreter_ap.get()) {
1540             if (event_type &
1541                 CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1542               done = true;
1543             } else if (event_type &
1544                        CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1545               const char *data = reinterpret_cast<const char *>(
1546                   EventDataBytes::GetBytesFromEvent(event_sp.get()));
1547               if (data && data[0]) {
1548                 StreamSP error_sp(GetAsyncErrorStream());
1549                 if (error_sp) {
1550                   error_sp->PutCString(data);
1551                   error_sp->Flush();
1552                 }
1553               }
1554             } else if (event_type & CommandInterpreter::
1555                                         eBroadcastBitAsynchronousOutputData) {
1556               const char *data = reinterpret_cast<const char *>(
1557                   EventDataBytes::GetBytesFromEvent(event_sp.get()));
1558               if (data && data[0]) {
1559                 StreamSP output_sp(GetAsyncOutputStream());
1560                 if (output_sp) {
1561                   output_sp->PutCString(data);
1562                   output_sp->Flush();
1563                 }
1564               }
1565             }
1566           }
1567         }
1568
1569         if (m_forward_listener_sp)
1570           m_forward_listener_sp->AddEvent(event_sp);
1571       }
1572     }
1573   }
1574 }
1575
1576 lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) {
1577   ((Debugger *)arg)->DefaultEventHandler();
1578   return NULL;
1579 }
1580
1581 bool Debugger::StartEventHandlerThread() {
1582   if (!m_event_handler_thread.IsJoinable()) {
1583     // We must synchronize with the DefaultEventHandler() thread to ensure
1584     // it is up and running and listening to events before we return from
1585     // this function. We do this by listening to events for the
1586     // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
1587     ListenerSP listener_sp(
1588         Listener::MakeListener("lldb.debugger.event-handler"));
1589     listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1590                                          eBroadcastBitEventThreadIsListening);
1591
1592     // Use larger 8MB stack for this thread
1593     m_event_handler_thread = ThreadLauncher::LaunchThread(
1594         "lldb.debugger.event-handler", EventHandlerThread, this, nullptr,
1595         g_debugger_event_thread_stack_bytes);
1596
1597     // Make sure DefaultEventHandler() is running and listening to events before
1598     // we return
1599     // from this function. We are only listening for events of type
1600     // eBroadcastBitEventThreadIsListening so we don't need to check the event,
1601     // we just need
1602     // to wait an infinite amount of time for it (nullptr timeout as the first
1603     // parameter)
1604     lldb::EventSP event_sp;
1605     listener_sp->GetEvent(event_sp, llvm::None);
1606   }
1607   return m_event_handler_thread.IsJoinable();
1608 }
1609
1610 void Debugger::StopEventHandlerThread() {
1611   if (m_event_handler_thread.IsJoinable()) {
1612     GetCommandInterpreter().BroadcastEvent(
1613         CommandInterpreter::eBroadcastBitQuitCommandReceived);
1614     m_event_handler_thread.Join(nullptr);
1615   }
1616 }
1617
1618 lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) {
1619   Debugger *debugger = (Debugger *)arg;
1620   debugger->ExecuteIOHandlers();
1621   debugger->StopEventHandlerThread();
1622   return NULL;
1623 }
1624
1625 bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1626
1627 bool Debugger::StartIOHandlerThread() {
1628   if (!m_io_handler_thread.IsJoinable())
1629     m_io_handler_thread = ThreadLauncher::LaunchThread(
1630         "lldb.debugger.io-handler", IOHandlerThread, this, nullptr,
1631         8 * 1024 * 1024); // Use larger 8MB stack for this thread
1632   return m_io_handler_thread.IsJoinable();
1633 }
1634
1635 void Debugger::StopIOHandlerThread() {
1636   if (m_io_handler_thread.IsJoinable()) {
1637     if (m_input_file_sp)
1638       m_input_file_sp->GetFile().Close();
1639     m_io_handler_thread.Join(nullptr);
1640   }
1641 }
1642
1643 void Debugger::JoinIOHandlerThread() {
1644   if (HasIOHandlerThread()) {
1645     thread_result_t result;
1646     m_io_handler_thread.Join(&result);
1647     m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1648   }
1649 }
1650
1651 Target *Debugger::GetDummyTarget() {
1652   return m_target_list.GetDummyTarget(*this).get();
1653 }
1654
1655 Target *Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1656   Target *target = nullptr;
1657   if (!prefer_dummy) {
1658     target = m_target_list.GetSelectedTarget().get();
1659     if (target)
1660       return target;
1661   }
1662
1663   return GetDummyTarget();
1664 }
1665
1666 Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
1667   Status err;
1668   FileSpec repl_executable;
1669
1670   if (language == eLanguageTypeUnknown) {
1671     std::set<LanguageType> repl_languages;
1672
1673     Language::GetLanguagesSupportingREPLs(repl_languages);
1674
1675     if (repl_languages.size() == 1) {
1676       language = *repl_languages.begin();
1677     } else if (repl_languages.empty()) {
1678       err.SetErrorStringWithFormat(
1679           "LLDB isn't configured with REPL support for any languages.");
1680       return err;
1681     } else {
1682       err.SetErrorStringWithFormat(
1683           "Multiple possible REPL languages.  Please specify a language.");
1684       return err;
1685     }
1686   }
1687
1688   Target *const target =
1689       nullptr; // passing in an empty target means the REPL must create one
1690
1691   REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
1692
1693   if (!err.Success()) {
1694     return err;
1695   }
1696
1697   if (!repl_sp) {
1698     err.SetErrorStringWithFormat("couldn't find a REPL for %s",
1699                                  Language::GetNameForLanguageType(language));
1700     return err;
1701   }
1702
1703   repl_sp->SetCompilerOptions(repl_options);
1704   repl_sp->RunLoop();
1705
1706   return err;
1707 }