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