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