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