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