1 //===-- Debugger.cpp --------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Core/Debugger.h"
14 #include "llvm/ADT/StringRef.h"
16 #include "lldb/lldb-private.h"
17 #include "lldb/Core/FormatEntity.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/PluginInterface.h"
20 #include "lldb/Core/PluginManager.h"
21 #include "lldb/Core/RegisterValue.h"
22 #include "lldb/Core/State.h"
23 #include "lldb/Core/StreamAsynchronousIO.h"
24 #include "lldb/Core/StreamCallback.h"
25 #include "lldb/Core/StreamFile.h"
26 #include "lldb/Core/StreamString.h"
27 #include "lldb/Core/StructuredData.h"
28 #include "lldb/Core/Timer.h"
29 #include "lldb/Core/ValueObject.h"
30 #include "lldb/Core/ValueObjectVariable.h"
31 #include "lldb/DataFormatters/DataVisualization.h"
32 #include "lldb/DataFormatters/FormatManager.h"
33 #include "lldb/DataFormatters/TypeSummary.h"
34 #include "lldb/Expression/REPL.h"
35 #include "lldb/Host/ConnectionFileDescriptor.h"
36 #include "lldb/Host/HostInfo.h"
37 #include "lldb/Host/Terminal.h"
38 #include "lldb/Host/ThreadLauncher.h"
39 #include "lldb/Interpreter/CommandInterpreter.h"
40 #include "lldb/Interpreter/OptionValueProperties.h"
41 #include "lldb/Interpreter/OptionValueSInt64.h"
42 #include "lldb/Interpreter/OptionValueString.h"
43 #include "lldb/Symbol/CompileUnit.h"
44 #include "lldb/Symbol/Function.h"
45 #include "lldb/Symbol/Symbol.h"
46 #include "lldb/Symbol/VariableList.h"
47 #include "lldb/Target/TargetList.h"
48 #include "lldb/Target/Language.h"
49 #include "lldb/Target/Process.h"
50 #include "lldb/Target/RegisterContext.h"
51 #include "lldb/Target/SectionLoadList.h"
52 #include "lldb/Target/StopInfo.h"
53 #include "lldb/Target/Target.h"
54 #include "lldb/Target/Thread.h"
55 #include "lldb/Utility/AnsiTerminal.h"
57 #include "llvm/Support/DynamicLibrary.h"
60 using namespace lldb_private;
63 static lldb::user_id_t g_unique_id = 1;
64 static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
66 #pragma mark Static Functions
69 GetDebuggerListMutex ()
71 static Mutex g_mutex(Mutex::eMutexTypeRecursive);
75 typedef std::vector<DebuggerSP> DebuggerList;
80 // hide the static debugger list inside a singleton accessor to avoid
81 // global init constructors
82 static DebuggerList g_list;
86 OptionEnumValueElement
87 g_show_disassembly_enum_values[] =
89 { Debugger::eStopDisassemblyTypeNever, "never", "Never show disassembly when displaying a stop context."},
90 { Debugger::eStopDisassemblyTypeNoDebugInfo, "no-debuginfo", "Show disassembly when there is no debug information."},
91 { Debugger::eStopDisassemblyTypeNoSource, "no-source", "Show disassembly when there is no source information, or the source file is missing when displaying a stop context."},
92 { Debugger::eStopDisassemblyTypeAlways, "always", "Always show disassembly when displaying a stop context."},
96 OptionEnumValueElement
97 g_language_enumerators[] =
99 { eScriptLanguageNone, "none", "Disable scripting languages."},
100 { eScriptLanguagePython, "python", "Select python as the default scripting language."},
101 { eScriptLanguageDefault, "default", "Select the lldb default as the default scripting language."},
105 #define MODULE_WITH_FUNC "{ ${module.file.basename}{`${function.name-with-args}${function.pc-offset}}}"
106 #define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}"
107 #define IS_OPTIMIZED "{${function.is-optimized} [opt]}"
109 #define DEFAULT_THREAD_FORMAT "thread #${thread.index}: tid = ${thread.id%tid}"\
113 "{, name = '${thread.name}'}"\
114 "{, queue = '${thread.queue}'}"\
115 "{, activity = '${thread.info.activity.name}'}" \
116 "{, ${thread.info.trace_messages} messages}" \
117 "{, stop reason = ${thread.stop-reason}}"\
118 "{\\nReturn value: ${thread.return-value}}"\
119 "{\\nCompleted expression: ${thread.completed-expression}}"\
122 #define DEFAULT_FRAME_FORMAT "frame #${frame.index}: ${frame.pc}"\
128 // Three parts to this disassembly format specification:
129 // 1. If this is a new function/symbol (no previous symbol/function), print
131 // 2. If this is a symbol context change (different from previous symbol/function), print
134 // address <+offset>:
135 #define DEFAULT_DISASSEMBLY_FORMAT "{${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} }${addr-file-or-load}{ <${function.concrete-only-addr-offset-no-padding}>}: "
137 // gdb's disassembly format can be emulated with
138 // ${current-pc-arrow}${addr-file-or-load}{ <${function.name-without-args}${function.concrete-only-addr-offset-no-padding}>}:
140 // lldb's original format for disassembly would look like this format string -
141 // {${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} }{${addr-file-or-load}}:
144 static PropertyDefinition
147 { "auto-confirm", OptionValue::eTypeBoolean , true, false, NULL, NULL, "If true all confirmation prompts will receive their default reply." },
148 { "disassembly-format", OptionValue::eTypeFormatEntity, true, 0 , DEFAULT_DISASSEMBLY_FORMAT, NULL, "The default disassembly format string to use when disassembling instruction sequences." },
149 { "frame-format", OptionValue::eTypeFormatEntity, true, 0 , DEFAULT_FRAME_FORMAT, NULL, "The default frame format string to use when displaying stack frame information for threads." },
150 { "notify-void", OptionValue::eTypeBoolean , true, false, NULL, NULL, "Notify the user explicitly if an expression returns void (default: false)." },
151 { "prompt", OptionValue::eTypeString , true, OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ", NULL, "The debugger command line prompt displayed for the user." },
152 { "script-lang", OptionValue::eTypeEnum , true, eScriptLanguagePython, NULL, g_language_enumerators, "The script language to be used for evaluating user-written scripts." },
153 { "stop-disassembly-count", OptionValue::eTypeSInt64 , true, 4 , NULL, NULL, "The number of disassembly lines to show when displaying a stopped context." },
154 { "stop-disassembly-display", OptionValue::eTypeEnum , true, Debugger::eStopDisassemblyTypeNoDebugInfo, NULL, g_show_disassembly_enum_values, "Control when to display disassembly when displaying a stopped context." },
155 { "stop-line-count-after", OptionValue::eTypeSInt64 , true, 3 , NULL, NULL, "The number of sources lines to display that come after the current source line when displaying a stopped context." },
156 { "stop-line-count-before", OptionValue::eTypeSInt64 , true, 3 , NULL, NULL, "The number of sources lines to display that come before the current source line when displaying a stopped context." },
157 { "term-width", OptionValue::eTypeSInt64 , true, 80 , NULL, NULL, "The maximum number of columns to use for displaying text." },
158 { "thread-format", OptionValue::eTypeFormatEntity, true, 0 , DEFAULT_THREAD_FORMAT, NULL, "The default thread format string to use when displaying thread information." },
159 { "use-external-editor", OptionValue::eTypeBoolean , true, false, NULL, NULL, "Whether to use an external editor or not." },
160 { "use-color", OptionValue::eTypeBoolean , true, true , NULL, NULL, "Whether to use Ansi color codes or not." },
161 { "auto-one-line-summaries", OptionValue::eTypeBoolean , true, true, NULL, NULL, "If true, LLDB will automatically display small structs in one-liner format (default: true)." },
162 { "auto-indent", OptionValue::eTypeBoolean , true, true , NULL, NULL, "If true, LLDB will auto indent/outdent code. Currently only supported in the REPL (default: true)." },
163 { "print-decls", OptionValue::eTypeBoolean , true, true , NULL, NULL, "If true, LLDB will print the values of variables declared in an expression. Currently only supported in the REPL (default: true)." },
164 { "tab-size", OptionValue::eTypeUInt64 , true, 4 , NULL, NULL, "The tab size to use when indenting code in multi-line input mode (default: 4)." },
165 { "escape-non-printables", OptionValue::eTypeBoolean , true, true, NULL, NULL, "If true, LLDB will automatically escape non-printable and escape characters when formatting strings." },
166 { NULL, OptionValue::eTypeInvalid , true, 0 , NULL, NULL, NULL }
171 ePropertyAutoConfirm = 0,
172 ePropertyDisassemblyFormat,
173 ePropertyFrameFormat,
176 ePropertyScriptLanguage,
177 ePropertyStopDisassemblyCount,
178 ePropertyStopDisassemblyDisplay,
179 ePropertyStopLineCountAfter,
180 ePropertyStopLineCountBefore,
181 ePropertyTerminalWidth,
182 ePropertyThreadFormat,
183 ePropertyUseExternalEditor,
185 ePropertyAutoOneLineSummaries,
189 ePropertyEscapeNonPrintables
192 LoadPluginCallbackType Debugger::g_load_plugin_callback = NULL;
195 Debugger::SetPropertyValue (const ExecutionContext *exe_ctx,
196 VarSetOperationType op,
197 const char *property_path,
200 bool is_load_script = strcmp(property_path,"target.load-script-from-symbol-file") == 0;
201 bool is_escape_non_printables = strcmp(property_path, "escape-non-printables") == 0;
203 LoadScriptFromSymFile load_script_old_value;
204 if (is_load_script && exe_ctx->GetTargetSP())
206 target_sp = exe_ctx->GetTargetSP();
207 load_script_old_value = target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
209 Error error (Properties::SetPropertyValue (exe_ctx, op, property_path, value));
212 // FIXME it would be nice to have "on-change" callbacks for properties
213 if (strcmp(property_path, g_properties[ePropertyPrompt].name) == 0)
215 const char *new_prompt = GetPrompt();
216 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
218 new_prompt = str.c_str();
219 GetCommandInterpreter().UpdatePrompt(new_prompt);
220 EventSP prompt_change_event_sp (new Event(CommandInterpreter::eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));
221 GetCommandInterpreter().BroadcastEvent (prompt_change_event_sp);
223 else if (strcmp(property_path, g_properties[ePropertyUseColor].name) == 0)
225 // use-color changed. Ping the prompt so it can reset the ansi terminal codes.
226 SetPrompt (GetPrompt());
228 else if (is_load_script && target_sp && load_script_old_value == eLoadScriptFromSymFileWarn)
230 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() == eLoadScriptFromSymFileTrue)
232 std::list<Error> errors;
233 StreamString feedback_stream;
234 if (!target_sp->LoadScriptingResources(errors,&feedback_stream))
236 StreamFileSP stream_sp (GetErrorFile());
239 for (auto error : errors)
241 stream_sp->Printf("%s\n",error.AsCString());
243 if (feedback_stream.GetSize())
244 stream_sp->Printf("%s",feedback_stream.GetData());
249 else if (is_escape_non_printables)
251 DataVisualization::ForceUpdate();
258 Debugger::GetAutoConfirm () const
260 const uint32_t idx = ePropertyAutoConfirm;
261 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
264 const FormatEntity::Entry *
265 Debugger::GetDisassemblyFormat() const
267 const uint32_t idx = ePropertyDisassemblyFormat;
268 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(NULL, idx);
271 const FormatEntity::Entry *
272 Debugger::GetFrameFormat() const
274 const uint32_t idx = ePropertyFrameFormat;
275 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(NULL, idx);
279 Debugger::GetNotifyVoid () const
281 const uint32_t idx = ePropertyNotiftVoid;
282 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
286 Debugger::GetPrompt() const
288 const uint32_t idx = ePropertyPrompt;
289 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
293 Debugger::SetPrompt(const char *p)
295 const uint32_t idx = ePropertyPrompt;
296 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
297 const char *new_prompt = GetPrompt();
298 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
300 new_prompt = str.c_str();
301 GetCommandInterpreter().UpdatePrompt(new_prompt);
304 const FormatEntity::Entry *
305 Debugger::GetThreadFormat() const
307 const uint32_t idx = ePropertyThreadFormat;
308 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(NULL, idx);
312 Debugger::GetScriptLanguage() const
314 const uint32_t idx = ePropertyScriptLanguage;
315 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
319 Debugger::SetScriptLanguage (lldb::ScriptLanguage script_lang)
321 const uint32_t idx = ePropertyScriptLanguage;
322 return m_collection_sp->SetPropertyAtIndexAsEnumeration (NULL, idx, script_lang);
326 Debugger::GetTerminalWidth () const
328 const uint32_t idx = ePropertyTerminalWidth;
329 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
333 Debugger::SetTerminalWidth (uint32_t term_width)
335 const uint32_t idx = ePropertyTerminalWidth;
336 return m_collection_sp->SetPropertyAtIndexAsSInt64 (NULL, idx, term_width);
340 Debugger::GetUseExternalEditor () const
342 const uint32_t idx = ePropertyUseExternalEditor;
343 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
347 Debugger::SetUseExternalEditor (bool b)
349 const uint32_t idx = ePropertyUseExternalEditor;
350 return m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
354 Debugger::GetUseColor () const
356 const uint32_t idx = ePropertyUseColor;
357 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
361 Debugger::SetUseColor (bool b)
363 const uint32_t idx = ePropertyUseColor;
364 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
365 SetPrompt (GetPrompt());
370 Debugger::GetStopSourceLineCount (bool before) const
372 const uint32_t idx = before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
373 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
376 Debugger::StopDisassemblyType
377 Debugger::GetStopDisassemblyDisplay () const
379 const uint32_t idx = ePropertyStopDisassemblyDisplay;
380 return (Debugger::StopDisassemblyType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
384 Debugger::GetDisassemblyLineCount () const
386 const uint32_t idx = ePropertyStopDisassemblyCount;
387 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
391 Debugger::GetAutoOneLineSummaries () const
393 const uint32_t idx = ePropertyAutoOneLineSummaries;
394 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
398 Debugger::GetEscapeNonPrintables () const
400 const uint32_t idx = ePropertyEscapeNonPrintables;
401 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
405 Debugger::GetAutoIndent () const
407 const uint32_t idx = ePropertyAutoIndent;
408 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
412 Debugger::SetAutoIndent (bool b)
414 const uint32_t idx = ePropertyAutoIndent;
415 return m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
419 Debugger::GetPrintDecls () const
421 const uint32_t idx = ePropertyPrintDecls;
422 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
426 Debugger::SetPrintDecls (bool b)
428 const uint32_t idx = ePropertyPrintDecls;
429 return m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
433 Debugger::GetTabSize () const
435 const uint32_t idx = ePropertyTabSize;
436 return m_collection_sp->GetPropertyAtIndexAsUInt64 (NULL, idx, g_properties[idx].default_uint_value);
440 Debugger::SetTabSize (uint32_t tab_size)
442 const uint32_t idx = ePropertyTabSize;
443 return m_collection_sp->SetPropertyAtIndexAsUInt64 (NULL, idx, tab_size);
447 #pragma mark Debugger
449 //const DebuggerPropertiesSP &
450 //Debugger::GetSettings() const
452 // return m_properties_sp;
456 static bool lldb_initialized = false;
458 Debugger::Initialize(LoadPluginCallbackType load_plugin_callback)
460 assert(!lldb_initialized && "Debugger::Initialize called more than once!");
462 lldb_initialized = true;
463 g_load_plugin_callback = load_plugin_callback;
467 Debugger::Terminate ()
469 assert(lldb_initialized && "Debugger::Terminate called without a matching Debugger::Initialize!");
471 // Clear our master list of debugger objects
472 Mutex::Locker locker (GetDebuggerListMutex ());
473 auto& debuggers = GetDebuggerList();
474 for (const auto& debugger: debuggers)
481 Debugger::SettingsInitialize ()
483 Target::SettingsInitialize ();
487 Debugger::SettingsTerminate ()
489 Target::SettingsTerminate ();
493 Debugger::LoadPlugin (const FileSpec& spec, Error& error)
495 if (g_load_plugin_callback)
497 llvm::sys::DynamicLibrary dynlib = g_load_plugin_callback (shared_from_this(), spec, error);
498 if (dynlib.isValid())
500 m_loaded_plugins.push_back(dynlib);
506 // The g_load_plugin_callback is registered in SBDebugger::Initialize()
507 // and if the public API layer isn't available (code is linking against
508 // all of the internal LLDB static libraries), then we can't load plugins
509 error.SetErrorString("Public API layer is not available");
514 static FileSpec::EnumerateDirectoryResult
518 FileSpec::FileType file_type,
519 const FileSpec &file_spec
524 static ConstString g_dylibext("dylib");
525 static ConstString g_solibext("so");
528 return FileSpec::eEnumerateDirectoryResultQuit;
530 Debugger *debugger = (Debugger*)baton;
532 // If we have a regular file, a symbolic link or unknown file type, try
533 // and process the file. We must handle unknown as sometimes the directory
534 // enumeration might be enumerating a file system that doesn't have correct
535 // file type information.
536 if (file_type == FileSpec::eFileTypeRegular ||
537 file_type == FileSpec::eFileTypeSymbolicLink ||
538 file_type == FileSpec::eFileTypeUnknown )
540 FileSpec plugin_file_spec (file_spec);
541 plugin_file_spec.ResolvePath ();
543 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
544 plugin_file_spec.GetFileNameExtension() != g_solibext)
546 return FileSpec::eEnumerateDirectoryResultNext;
549 Error plugin_load_error;
550 debugger->LoadPlugin (plugin_file_spec, plugin_load_error);
552 return FileSpec::eEnumerateDirectoryResultNext;
555 else if (file_type == FileSpec::eFileTypeUnknown ||
556 file_type == FileSpec::eFileTypeDirectory ||
557 file_type == FileSpec::eFileTypeSymbolicLink )
559 // Try and recurse into anything that a directory or symbolic link.
560 // We must also do this for unknown as sometimes the directory enumeration
561 // might be enumerating a file system that doesn't have correct file type
563 return FileSpec::eEnumerateDirectoryResultEnter;
566 return FileSpec::eEnumerateDirectoryResultNext;
570 Debugger::InstanceInitialize ()
573 const bool find_directories = true;
574 const bool find_files = true;
575 const bool find_other = true;
576 char dir_path[PATH_MAX];
577 if (HostInfo::GetLLDBPath(ePathTypeLLDBSystemPlugins, dir_spec))
579 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
581 FileSpec::EnumerateDirectory (dir_path,
590 if (HostInfo::GetLLDBPath(ePathTypeLLDBUserPlugins, dir_spec))
592 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
594 FileSpec::EnumerateDirectory (dir_path,
603 PluginManager::DebuggerInitialize (*this);
607 Debugger::CreateInstance (lldb::LogOutputCallback log_callback, void *baton)
609 DebuggerSP debugger_sp (new Debugger(log_callback, baton));
610 if (lldb_initialized)
612 Mutex::Locker locker (GetDebuggerListMutex ());
613 GetDebuggerList().push_back(debugger_sp);
615 debugger_sp->InstanceInitialize ();
620 Debugger::Destroy (DebuggerSP &debugger_sp)
622 if (debugger_sp.get() == NULL)
625 debugger_sp->Clear();
627 if (lldb_initialized)
629 Mutex::Locker locker (GetDebuggerListMutex ());
630 DebuggerList &debugger_list = GetDebuggerList ();
631 DebuggerList::iterator pos, end = debugger_list.end();
632 for (pos = debugger_list.begin (); pos != end; ++pos)
634 if ((*pos).get() == debugger_sp.get())
636 debugger_list.erase (pos);
644 Debugger::FindDebuggerWithInstanceName (const ConstString &instance_name)
646 DebuggerSP debugger_sp;
647 if (lldb_initialized)
649 Mutex::Locker locker (GetDebuggerListMutex ());
650 DebuggerList &debugger_list = GetDebuggerList();
651 DebuggerList::iterator pos, end = debugger_list.end();
653 for (pos = debugger_list.begin(); pos != end; ++pos)
655 if ((*pos).get()->m_instance_name == instance_name)
666 Debugger::FindTargetWithProcessID (lldb::pid_t pid)
669 if (lldb_initialized)
671 Mutex::Locker locker (GetDebuggerListMutex ());
672 DebuggerList &debugger_list = GetDebuggerList();
673 DebuggerList::iterator pos, end = debugger_list.end();
674 for (pos = debugger_list.begin(); pos != end; ++pos)
676 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID (pid);
685 Debugger::FindTargetWithProcess (Process *process)
688 if (lldb_initialized)
690 Mutex::Locker locker (GetDebuggerListMutex ());
691 DebuggerList &debugger_list = GetDebuggerList();
692 DebuggerList::iterator pos, end = debugger_list.end();
693 for (pos = debugger_list.begin(); pos != end; ++pos)
695 target_sp = (*pos)->GetTargetList().FindTargetWithProcess (process);
703 Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton) :
704 UserID(g_unique_id++),
705 Properties(OptionValuePropertiesSP(new OptionValueProperties())),
706 m_input_file_sp(new StreamFile(stdin, false)),
707 m_output_file_sp(new StreamFile(stdout, false)),
708 m_error_file_sp(new StreamFile(stderr, false)),
710 m_target_list(*this),
712 m_listener("lldb.Debugger"),
713 m_source_manager_ap(),
714 m_source_file_cache(),
715 m_command_interpreter_ap(new CommandInterpreter(*this, eScriptLanguageDefault, false)),
716 m_input_reader_stack(),
719 m_event_handler_thread (),
720 m_io_handler_thread (),
721 m_sync_broadcaster (NULL, "lldb.debugger.sync")
723 char instance_cstr[256];
724 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
725 m_instance_name.SetCString(instance_cstr);
727 m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
728 m_command_interpreter_ap->Initialize ();
729 // Always add our default platform to the platform list
730 PlatformSP default_platform_sp (Platform::GetHostPlatform());
731 assert (default_platform_sp.get());
732 m_platform_list.Append (default_platform_sp, true);
734 m_collection_sp->Initialize (g_properties);
735 m_collection_sp->AppendProperty (ConstString("target"),
736 ConstString("Settings specify to debugging targets."),
738 Target::GetGlobalProperties()->GetValueProperties());
739 m_collection_sp->AppendProperty (ConstString("platform"),
740 ConstString("Platform settings."),
742 Platform::GetGlobalPlatformProperties()->GetValueProperties());
743 if (m_command_interpreter_ap.get())
745 m_collection_sp->AppendProperty (ConstString("interpreter"),
746 ConstString("Settings specify to the debugger's command interpreter."),
748 m_command_interpreter_ap->GetValueProperties());
750 OptionValueSInt64 *term_width = m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64 (NULL, ePropertyTerminalWidth);
751 term_width->SetMinimumValue(10);
752 term_width->SetMaximumValue(1024);
754 // Turn off use-color if this is a dumb terminal.
755 const char *term = getenv ("TERM");
756 if (term && !strcmp (term, "dumb"))
760 Debugger::~Debugger ()
769 StopIOHandlerThread();
770 StopEventHandlerThread();
772 int num_targets = m_target_list.GetNumTargets();
773 for (int i = 0; i < num_targets; i++)
775 TargetSP target_sp (m_target_list.GetTargetAtIndex (i));
778 ProcessSP process_sp (target_sp->GetProcessSP());
780 process_sp->Finalize();
781 target_sp->Destroy();
784 BroadcasterManager::Clear ();
786 // Close the input file _before_ we close the input read communications class
787 // as it does NOT own the input file, our m_input_file does.
788 m_terminal_state.Clear();
790 m_input_file_sp->GetFile().Close ();
792 m_command_interpreter_ap->Clear();
796 Debugger::GetCloseInputOnEOF () const
798 // return m_input_comm.GetCloseOnEOF();
803 Debugger::SetCloseInputOnEOF (bool b)
805 // m_input_comm.SetCloseOnEOF(b);
809 Debugger::GetAsyncExecution ()
811 return !m_command_interpreter_ap->GetSynchronous();
815 Debugger::SetAsyncExecution (bool async_execution)
817 m_command_interpreter_ap->SetSynchronous (!async_execution);
822 Debugger::SetInputFileHandle (FILE *fh, bool tranfer_ownership)
825 m_input_file_sp->GetFile().SetStream (fh, tranfer_ownership);
827 m_input_file_sp.reset (new StreamFile (fh, tranfer_ownership));
829 File &in_file = m_input_file_sp->GetFile();
830 if (in_file.IsValid() == false)
831 in_file.SetStream (stdin, true);
833 // Save away the terminal state if that is relevant, so that we can restore it in RestoreInputState.
834 SaveInputTerminalState ();
838 Debugger::SetOutputFileHandle (FILE *fh, bool tranfer_ownership)
840 if (m_output_file_sp)
841 m_output_file_sp->GetFile().SetStream (fh, tranfer_ownership);
843 m_output_file_sp.reset (new StreamFile (fh, tranfer_ownership));
845 File &out_file = m_output_file_sp->GetFile();
846 if (out_file.IsValid() == false)
847 out_file.SetStream (stdout, false);
849 // do not create the ScriptInterpreter just for setting the output file handle
850 // as the constructor will know how to do the right thing on its own
851 const bool can_create = false;
852 ScriptInterpreter* script_interpreter = GetCommandInterpreter().GetScriptInterpreter(can_create);
853 if (script_interpreter)
854 script_interpreter->ResetOutputFileHandle (fh);
858 Debugger::SetErrorFileHandle (FILE *fh, bool tranfer_ownership)
861 m_error_file_sp->GetFile().SetStream (fh, tranfer_ownership);
863 m_error_file_sp.reset (new StreamFile (fh, tranfer_ownership));
865 File &err_file = m_error_file_sp->GetFile();
866 if (err_file.IsValid() == false)
867 err_file.SetStream (stderr, false);
871 Debugger::SaveInputTerminalState ()
875 File &in_file = m_input_file_sp->GetFile();
876 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
877 m_terminal_state.Save(in_file.GetDescriptor(), true);
882 Debugger::RestoreInputTerminalState ()
884 m_terminal_state.Restore();
888 Debugger::GetSelectedExecutionContext ()
890 ExecutionContext exe_ctx;
891 TargetSP target_sp(GetSelectedTarget());
892 exe_ctx.SetTargetSP (target_sp);
896 ProcessSP process_sp (target_sp->GetProcessSP());
897 exe_ctx.SetProcessSP (process_sp);
898 if (process_sp && process_sp->IsRunning() == false)
900 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
903 exe_ctx.SetThreadSP (thread_sp);
904 exe_ctx.SetFrameSP (thread_sp->GetSelectedFrame());
905 if (exe_ctx.GetFramePtr() == NULL)
906 exe_ctx.SetFrameSP (thread_sp->GetStackFrameAtIndex (0));
914 Debugger::DispatchInputInterrupt ()
916 Mutex::Locker locker (m_input_reader_stack.GetMutex());
917 IOHandlerSP reader_sp (m_input_reader_stack.Top());
919 reader_sp->Interrupt();
923 Debugger::DispatchInputEndOfFile ()
925 Mutex::Locker locker (m_input_reader_stack.GetMutex());
926 IOHandlerSP reader_sp (m_input_reader_stack.Top());
932 Debugger::ClearIOHandlers ()
934 // The bottom input reader should be the main debugger input reader. We do not want to close that one here.
935 Mutex::Locker locker (m_input_reader_stack.GetMutex());
936 while (m_input_reader_stack.GetSize() > 1)
938 IOHandlerSP reader_sp (m_input_reader_stack.Top());
940 PopIOHandler (reader_sp);
945 Debugger::ExecuteIOHandlers()
949 IOHandlerSP reader_sp(m_input_reader_stack.Top());
955 // Remove all input readers that are done from the top of the stack
958 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
959 if (top_reader_sp && top_reader_sp->GetIsDone())
960 PopIOHandler (top_reader_sp);
969 Debugger::IsTopIOHandler (const lldb::IOHandlerSP& reader_sp)
971 return m_input_reader_stack.IsTop (reader_sp);
975 Debugger::CheckTopIOHandlerTypes (IOHandler::Type top_type, IOHandler::Type second_top_type)
977 return m_input_reader_stack.CheckTopIOHandlerTypes (top_type, second_top_type);
981 Debugger::PrintAsync (const char *s, size_t len, bool is_stdout)
983 lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile();
984 m_input_reader_stack.PrintAsync(stream.get(), s, len);
988 Debugger::GetTopIOHandlerControlSequence(char ch)
990 return m_input_reader_stack.GetTopIOHandlerControlSequence (ch);
994 Debugger::GetIOHandlerCommandPrefix()
996 return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
1000 Debugger::GetIOHandlerHelpPrologue()
1002 return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
1006 Debugger::RunIOHandler (const IOHandlerSP& reader_sp)
1008 PushIOHandler (reader_sp);
1010 IOHandlerSP top_reader_sp = reader_sp;
1011 while (top_reader_sp)
1013 top_reader_sp->Run();
1015 if (top_reader_sp.get() == reader_sp.get())
1017 if (PopIOHandler (reader_sp))
1023 top_reader_sp = m_input_reader_stack.Top();
1024 if (top_reader_sp && top_reader_sp->GetIsDone())
1025 PopIOHandler (top_reader_sp);
1033 Debugger::AdoptTopIOHandlerFilesIfInvalid (StreamFileSP &in, StreamFileSP &out, StreamFileSP &err)
1035 // Before an IOHandler runs, it must have in/out/err streams.
1036 // This function is called when one ore more of the streams
1037 // are NULL. We use the top input reader's in/out/err streams,
1038 // or fall back to the debugger file handles, or we fall back
1039 // onto stdin/stdout/stderr as a last resort.
1041 Mutex::Locker locker (m_input_reader_stack.GetMutex());
1042 IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
1043 // If no STDIN has been set, then set it appropriately
1047 in = top_reader_sp->GetInputStreamFile();
1049 in = GetInputFile();
1051 // If there is nothing, use stdin
1053 in = StreamFileSP(new StreamFile(stdin, false));
1055 // If no STDOUT has been set, then set it appropriately
1059 out = top_reader_sp->GetOutputStreamFile();
1061 out = GetOutputFile();
1063 // If there is nothing, use stdout
1065 out = StreamFileSP(new StreamFile(stdout, false));
1067 // If no STDERR has been set, then set it appropriately
1071 err = top_reader_sp->GetErrorStreamFile();
1073 err = GetErrorFile();
1075 // If there is nothing, use stderr
1077 err = StreamFileSP(new StreamFile(stdout, false));
1083 Debugger::PushIOHandler (const IOHandlerSP& reader_sp)
1088 Mutex::Locker locker (m_input_reader_stack.GetMutex());
1090 // Get the current top input reader...
1091 IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
1093 // Don't push the same IO handler twice...
1094 if (reader_sp == top_reader_sp)
1097 // Push our new input reader
1098 m_input_reader_stack.Push (reader_sp);
1099 reader_sp->Activate();
1101 // Interrupt the top input reader to it will exit its Run() function
1102 // and let this new input reader take over
1105 top_reader_sp->Deactivate();
1106 top_reader_sp->Cancel();
1111 Debugger::PopIOHandler (const IOHandlerSP& pop_reader_sp)
1113 if (! pop_reader_sp)
1116 Mutex::Locker locker (m_input_reader_stack.GetMutex());
1118 // The reader on the stop of the stack is done, so let the next
1119 // read on the stack refresh its prompt and if there is one...
1120 if (m_input_reader_stack.IsEmpty())
1123 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1125 if (pop_reader_sp != reader_sp)
1128 reader_sp->Deactivate();
1129 reader_sp->Cancel();
1130 m_input_reader_stack.Pop ();
1132 reader_sp = m_input_reader_stack.Top();
1134 reader_sp->Activate();
1140 Debugger::GetAsyncOutputStream ()
1142 return StreamSP (new StreamAsynchronousIO (*this, true));
1146 Debugger::GetAsyncErrorStream ()
1148 return StreamSP (new StreamAsynchronousIO (*this, false));
1152 Debugger::GetNumDebuggers()
1154 if (lldb_initialized)
1156 Mutex::Locker locker (GetDebuggerListMutex ());
1157 return GetDebuggerList().size();
1163 Debugger::GetDebuggerAtIndex (size_t index)
1165 DebuggerSP debugger_sp;
1167 if (lldb_initialized)
1169 Mutex::Locker locker (GetDebuggerListMutex ());
1170 DebuggerList &debugger_list = GetDebuggerList();
1172 if (index < debugger_list.size())
1173 debugger_sp = debugger_list[index];
1180 Debugger::FindDebuggerWithID (lldb::user_id_t id)
1182 DebuggerSP debugger_sp;
1184 if (lldb_initialized)
1186 Mutex::Locker locker (GetDebuggerListMutex ());
1187 DebuggerList &debugger_list = GetDebuggerList();
1188 DebuggerList::iterator pos, end = debugger_list.end();
1189 for (pos = debugger_list.begin(); pos != end; ++pos)
1191 if ((*pos).get()->GetID() == id)
1203 TestPromptFormats (StackFrame *frame)
1209 const char *prompt_format =
1210 "{addr = '${addr}'\n}"
1211 "{addr-file-or-load = '${addr-file-or-load}'\n}"
1212 "{current-pc-arrow = '${current-pc-arrow}'\n}"
1213 "{process.id = '${process.id}'\n}"
1214 "{process.name = '${process.name}'\n}"
1215 "{process.file.basename = '${process.file.basename}'\n}"
1216 "{process.file.fullpath = '${process.file.fullpath}'\n}"
1217 "{thread.id = '${thread.id}'\n}"
1218 "{thread.index = '${thread.index}'\n}"
1219 "{thread.name = '${thread.name}'\n}"
1220 "{thread.queue = '${thread.queue}'\n}"
1221 "{thread.stop-reason = '${thread.stop-reason}'\n}"
1222 "{target.arch = '${target.arch}'\n}"
1223 "{module.file.basename = '${module.file.basename}'\n}"
1224 "{module.file.fullpath = '${module.file.fullpath}'\n}"
1225 "{file.basename = '${file.basename}'\n}"
1226 "{file.fullpath = '${file.fullpath}'\n}"
1227 "{frame.index = '${frame.index}'\n}"
1228 "{frame.pc = '${frame.pc}'\n}"
1229 "{frame.sp = '${frame.sp}'\n}"
1230 "{frame.fp = '${frame.fp}'\n}"
1231 "{frame.flags = '${frame.flags}'\n}"
1232 "{frame.reg.rdi = '${frame.reg.rdi}'\n}"
1233 "{frame.reg.rip = '${frame.reg.rip}'\n}"
1234 "{frame.reg.rsp = '${frame.reg.rsp}'\n}"
1235 "{frame.reg.rbp = '${frame.reg.rbp}'\n}"
1236 "{frame.reg.rflags = '${frame.reg.rflags}'\n}"
1237 "{frame.reg.xmm0 = '${frame.reg.xmm0}'\n}"
1238 "{frame.reg.carp = '${frame.reg.carp}'\n}"
1239 "{function.id = '${function.id}'\n}"
1240 "{function.changed = '${function.changed}'\n}"
1241 "{function.initial-function = '${function.initial-function}'\n}"
1242 "{function.name = '${function.name}'\n}"
1243 "{function.name-without-args = '${function.name-without-args}'\n}"
1244 "{function.name-with-args = '${function.name-with-args}'\n}"
1245 "{function.addr-offset = '${function.addr-offset}'\n}"
1246 "{function.concrete-only-addr-offset-no-padding = '${function.concrete-only-addr-offset-no-padding}'\n}"
1247 "{function.line-offset = '${function.line-offset}'\n}"
1248 "{function.pc-offset = '${function.pc-offset}'\n}"
1249 "{line.file.basename = '${line.file.basename}'\n}"
1250 "{line.file.fullpath = '${line.file.fullpath}'\n}"
1251 "{line.number = '${line.number}'\n}"
1252 "{line.start-addr = '${line.start-addr}'\n}"
1253 "{line.end-addr = '${line.end-addr}'\n}"
1256 SymbolContext sc (frame->GetSymbolContext(eSymbolContextEverything));
1257 ExecutionContext exe_ctx;
1258 frame->CalculateExecutionContext(exe_ctx);
1259 if (Debugger::FormatPrompt (prompt_format, &sc, &exe_ctx, &sc.line_entry.range.GetBaseAddress(), s))
1261 printf("%s\n", s.GetData());
1265 printf ("what we got: %s\n", s.GetData());
1271 Debugger::FormatDisassemblerAddress (const FormatEntity::Entry *format,
1272 const SymbolContext *sc,
1273 const SymbolContext *prev_sc,
1274 const ExecutionContext *exe_ctx,
1275 const Address *addr,
1278 FormatEntity::Entry format_entry;
1282 if (exe_ctx != NULL && exe_ctx->HasTargetScope())
1283 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1286 FormatEntity::Parse("${addr}: ", format_entry);
1287 format = &format_entry;
1290 bool function_changed = false;
1291 bool initial_function = false;
1292 if (prev_sc && (prev_sc->function || prev_sc->symbol))
1294 if (sc && (sc->function || sc->symbol))
1296 if (prev_sc->symbol && sc->symbol)
1298 if (!sc->symbol->Compare (prev_sc->symbol->GetName(), prev_sc->symbol->GetType()))
1300 function_changed = true;
1303 else if (prev_sc->function && sc->function)
1305 if (prev_sc->function->GetMangled() != sc->function->GetMangled())
1307 function_changed = true;
1312 // The first context on a list of instructions will have a prev_sc that
1313 // has no Function or Symbol -- if SymbolContext had an IsValid() method, it
1314 // would return false. But we do get a prev_sc pointer.
1315 if ((sc && (sc->function || sc->symbol))
1316 && prev_sc && (prev_sc->function == NULL && prev_sc->symbol == NULL))
1318 initial_function = true;
1320 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, NULL, function_changed, initial_function);
1325 Debugger::SetLoggingCallback (lldb::LogOutputCallback log_callback, void *baton)
1327 // For simplicity's sake, I am not going to deal with how to close down any
1328 // open logging streams, I just redirect everything from here on out to the
1330 m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
1334 Debugger::EnableLog (const char *channel, const char **categories, const char *log_file, uint32_t log_options, Stream &error_stream)
1336 StreamSP log_stream_sp;
1337 if (m_log_callback_stream_sp)
1339 log_stream_sp = m_log_callback_stream_sp;
1340 // For now when using the callback mode you always get thread & timestamp.
1341 log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
1343 else if (log_file == NULL || *log_file == '\0')
1345 log_stream_sp = GetOutputFile();
1349 LogStreamMap::iterator pos = m_log_streams.find(log_file);
1350 if (pos != m_log_streams.end())
1351 log_stream_sp = pos->second.lock();
1354 uint32_t options = File::eOpenOptionWrite | File::eOpenOptionCanCreate
1355 | File::eOpenOptionCloseOnExec | File::eOpenOptionAppend;
1356 if (! (log_options & LLDB_LOG_OPTION_APPEND))
1357 options |= File::eOpenOptionTruncate;
1359 log_stream_sp.reset (new StreamFile (log_file, options));
1360 m_log_streams[log_file] = log_stream_sp;
1363 assert (log_stream_sp.get());
1365 if (log_options == 0)
1366 log_options = LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1368 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories, error_stream);
1372 Debugger::GetSourceManager ()
1374 if (m_source_manager_ap.get() == NULL)
1375 m_source_manager_ap.reset (new SourceManager (shared_from_this()));
1376 return *m_source_manager_ap;
1381 // This function handles events that were broadcast by the process.
1383 Debugger::HandleBreakpointEvent (const EventSP &event_sp)
1385 using namespace lldb;
1386 const uint32_t event_type = Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent (event_sp);
1388 // if (event_type & eBreakpointEventTypeAdded
1389 // || event_type & eBreakpointEventTypeRemoved
1390 // || event_type & eBreakpointEventTypeEnabled
1391 // || event_type & eBreakpointEventTypeDisabled
1392 // || event_type & eBreakpointEventTypeCommandChanged
1393 // || event_type & eBreakpointEventTypeConditionChanged
1394 // || event_type & eBreakpointEventTypeIgnoreChanged
1395 // || event_type & eBreakpointEventTypeLocationsResolved)
1397 // // Don't do anything about these events, since the breakpoint commands already echo these actions.
1400 if (event_type & eBreakpointEventTypeLocationsAdded)
1402 uint32_t num_new_locations = Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(event_sp);
1403 if (num_new_locations > 0)
1405 BreakpointSP breakpoint = Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1406 StreamSP output_sp (GetAsyncOutputStream());
1409 output_sp->Printf("%d location%s added to breakpoint %d\n",
1411 num_new_locations == 1 ? "" : "s",
1412 breakpoint->GetID());
1417 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1419 // // These locations just get disabled, not sure it is worth spamming folks about this on the command line.
1421 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1423 // // This might be an interesting thing to note, but I'm going to leave it quiet for now, it just looked noisy.
1428 Debugger::GetProcessSTDOUT (Process *process, Stream *stream)
1430 size_t total_bytes = 0;
1432 stream = GetOutputFile().get();
1436 // The process has stuff waiting for stdout; get it and write it out to the appropriate place.
1437 if (process == NULL)
1439 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1441 process = target_sp->GetProcessSP().get();
1447 char stdio_buffer[1024];
1448 while ((len = process->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
1450 stream->Write(stdio_buffer, len);
1460 Debugger::GetProcessSTDERR (Process *process, Stream *stream)
1462 size_t total_bytes = 0;
1464 stream = GetOutputFile().get();
1468 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
1469 if (process == NULL)
1471 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1473 process = target_sp->GetProcessSP().get();
1479 char stdio_buffer[1024];
1480 while ((len = process->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
1482 stream->Write(stdio_buffer, len);
1492 // This function handles events that were broadcast by the process.
1494 Debugger::HandleProcessEvent (const EventSP &event_sp)
1496 using namespace lldb;
1497 const uint32_t event_type = event_sp->GetType();
1498 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1500 StreamSP output_stream_sp = GetAsyncOutputStream();
1501 StreamSP error_stream_sp = GetAsyncErrorStream();
1502 const bool gui_enabled = IsForwardingEvents();
1506 bool pop_process_io_handler = false;
1507 assert (process_sp);
1509 bool state_is_stopped = false;
1510 const bool got_state_changed = (event_type & Process::eBroadcastBitStateChanged) != 0;
1511 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1512 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1513 if (got_state_changed)
1515 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1516 state_is_stopped = StateIsStoppedState(event_state, false);
1519 // Display running state changes first before any STDIO
1520 if (got_state_changed && !state_is_stopped)
1522 Process::HandleProcessStateChangedEvent (event_sp, output_stream_sp.get(), pop_process_io_handler);
1525 // Now display and STDOUT
1526 if (got_stdout || got_state_changed)
1528 GetProcessSTDOUT (process_sp.get(), output_stream_sp.get());
1531 // Now display and STDERR
1532 if (got_stderr || got_state_changed)
1534 GetProcessSTDERR (process_sp.get(), error_stream_sp.get());
1537 // Now display any stopped state changes after any STDIO
1538 if (got_state_changed && state_is_stopped)
1540 Process::HandleProcessStateChangedEvent (event_sp, output_stream_sp.get(), pop_process_io_handler);
1543 output_stream_sp->Flush();
1544 error_stream_sp->Flush();
1546 if (pop_process_io_handler)
1547 process_sp->PopProcessIOHandler();
1552 Debugger::HandleThreadEvent (const EventSP &event_sp)
1554 // At present the only thread event we handle is the Frame Changed event,
1555 // and all we do for that is just reprint the thread status for that thread.
1556 using namespace lldb;
1557 const uint32_t event_type = event_sp->GetType();
1558 if (event_type == Thread::eBroadcastBitStackChanged ||
1559 event_type == Thread::eBroadcastBitThreadSelected )
1561 ThreadSP thread_sp (Thread::ThreadEventData::GetThreadFromEvent (event_sp.get()));
1564 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1);
1570 Debugger::IsForwardingEvents ()
1572 return (bool)m_forward_listener_sp;
1576 Debugger::EnableForwardEvents (const ListenerSP &listener_sp)
1578 m_forward_listener_sp = listener_sp;
1582 Debugger::CancelForwardEvents (const ListenerSP &listener_sp)
1584 m_forward_listener_sp.reset();
1589 Debugger::DefaultEventHandler()
1591 Listener& listener(GetListener());
1592 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1593 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1594 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1595 BroadcastEventSpec target_event_spec (broadcaster_class_target,
1596 Target::eBroadcastBitBreakpointChanged);
1598 BroadcastEventSpec process_event_spec (broadcaster_class_process,
1599 Process::eBroadcastBitStateChanged |
1600 Process::eBroadcastBitSTDOUT |
1601 Process::eBroadcastBitSTDERR);
1603 BroadcastEventSpec thread_event_spec (broadcaster_class_thread,
1604 Thread::eBroadcastBitStackChanged |
1605 Thread::eBroadcastBitThreadSelected );
1607 listener.StartListeningForEventSpec (*this, target_event_spec);
1608 listener.StartListeningForEventSpec (*this, process_event_spec);
1609 listener.StartListeningForEventSpec (*this, thread_event_spec);
1610 listener.StartListeningForEvents (m_command_interpreter_ap.get(),
1611 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1612 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1613 CommandInterpreter::eBroadcastBitAsynchronousErrorData );
1615 // Let the thread that spawned us know that we have started up and
1616 // that we are now listening to all required events so no events get missed
1617 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
1623 if (listener.WaitForEvent(NULL, event_sp))
1627 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1630 uint32_t event_type = event_sp->GetType();
1631 ConstString broadcaster_class (broadcaster->GetBroadcasterClass());
1632 if (broadcaster_class == broadcaster_class_process)
1634 HandleProcessEvent (event_sp);
1636 else if (broadcaster_class == broadcaster_class_target)
1638 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(event_sp.get()))
1640 HandleBreakpointEvent (event_sp);
1643 else if (broadcaster_class == broadcaster_class_thread)
1645 HandleThreadEvent (event_sp);
1647 else if (broadcaster == m_command_interpreter_ap.get())
1649 if (event_type & CommandInterpreter::eBroadcastBitQuitCommandReceived)
1653 else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousErrorData)
1655 const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
1656 if (data && data[0])
1658 StreamSP error_sp (GetAsyncErrorStream());
1661 error_sp->PutCString(data);
1666 else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousOutputData)
1668 const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
1669 if (data && data[0])
1671 StreamSP output_sp (GetAsyncOutputStream());
1674 output_sp->PutCString(data);
1682 if (m_forward_listener_sp)
1683 m_forward_listener_sp->AddEvent(event_sp);
1689 lldb::thread_result_t
1690 Debugger::EventHandlerThread (lldb::thread_arg_t arg)
1692 ((Debugger *)arg)->DefaultEventHandler();
1697 Debugger::StartEventHandlerThread()
1699 if (!m_event_handler_thread.IsJoinable())
1701 // We must synchronize with the DefaultEventHandler() thread to ensure
1702 // it is up and running and listening to events before we return from
1703 // this function. We do this by listening to events for the
1704 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
1705 Listener listener("lldb.debugger.event-handler");
1706 listener.StartListeningForEvents(&m_sync_broadcaster, eBroadcastBitEventThreadIsListening);
1708 // Use larger 8MB stack for this thread
1709 m_event_handler_thread = ThreadLauncher::LaunchThread("lldb.debugger.event-handler", EventHandlerThread,
1712 g_debugger_event_thread_stack_bytes);
1714 // Make sure DefaultEventHandler() is running and listening to events before we return
1715 // from this function. We are only listening for events of type
1716 // eBroadcastBitEventThreadIsListening so we don't need to check the event, we just need
1717 // to wait an infinite amount of time for it (NULL timeout as the first parameter)
1718 lldb::EventSP event_sp;
1719 listener.WaitForEvent(NULL, event_sp);
1721 return m_event_handler_thread.IsJoinable();
1725 Debugger::StopEventHandlerThread()
1727 if (m_event_handler_thread.IsJoinable())
1729 GetCommandInterpreter().BroadcastEvent(CommandInterpreter::eBroadcastBitQuitCommandReceived);
1730 m_event_handler_thread.Join(nullptr);
1735 lldb::thread_result_t
1736 Debugger::IOHandlerThread (lldb::thread_arg_t arg)
1738 Debugger *debugger = (Debugger *)arg;
1739 debugger->ExecuteIOHandlers();
1740 debugger->StopEventHandlerThread();
1745 Debugger::HasIOHandlerThread()
1747 return m_io_handler_thread.IsJoinable();
1751 Debugger::StartIOHandlerThread()
1753 if (!m_io_handler_thread.IsJoinable())
1754 m_io_handler_thread = ThreadLauncher::LaunchThread ("lldb.debugger.io-handler",
1758 8*1024*1024); // Use larger 8MB stack for this thread
1759 return m_io_handler_thread.IsJoinable();
1763 Debugger::StopIOHandlerThread()
1765 if (m_io_handler_thread.IsJoinable())
1767 if (m_input_file_sp)
1768 m_input_file_sp->GetFile().Close();
1769 m_io_handler_thread.Join(nullptr);
1774 Debugger::JoinIOHandlerThread()
1776 if (HasIOHandlerThread())
1778 thread_result_t result;
1779 m_io_handler_thread.Join(&result);
1780 m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1785 Debugger::GetDummyTarget()
1787 return m_target_list.GetDummyTarget (*this).get();
1791 Debugger::GetSelectedOrDummyTarget(bool prefer_dummy)
1793 Target *target = nullptr;
1796 target = m_target_list.GetSelectedTarget().get();
1801 return GetDummyTarget();
1805 Debugger::RunREPL (LanguageType language, const char *repl_options)
1808 FileSpec repl_executable;
1810 if (language == eLanguageTypeUnknown)
1812 std::set<LanguageType> repl_languages;
1814 Language::GetLanguagesSupportingREPLs(repl_languages);
1816 if (repl_languages.size() == 1)
1818 language = *repl_languages.begin();
1820 else if (repl_languages.size() == 0)
1822 err.SetErrorStringWithFormat("LLDB isn't configured with support support for any REPLs.");
1827 err.SetErrorStringWithFormat("Multiple possible REPL languages. Please specify a language.");
1832 Target *const target = nullptr; // passing in an empty target means the REPL must create one
1834 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
1843 err.SetErrorStringWithFormat("couldn't find a REPL for %s", Language::GetNameForLanguageType(language));
1847 repl_sp->SetCompilerOptions(repl_options);