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