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