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