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