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