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