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