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