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