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