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