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 "clang/AST/DeclCXX.h"
15 #include "clang/AST/Type.h"
16 #include "llvm/ADT/StringRef.h"
18 #include "lldb/lldb-private.h"
19 #include "lldb/Core/FormatEntity.h"
20 #include "lldb/Core/Module.h"
21 #include "lldb/Core/PluginManager.h"
22 #include "lldb/Core/RegisterValue.h"
23 #include "lldb/Core/State.h"
24 #include "lldb/Core/StreamAsynchronousIO.h"
25 #include "lldb/Core/StreamCallback.h"
26 #include "lldb/Core/StreamFile.h"
27 #include "lldb/Core/StreamString.h"
28 #include "lldb/Core/StructuredData.h"
29 #include "lldb/Core/Timer.h"
30 #include "lldb/Core/ValueObject.h"
31 #include "lldb/Core/ValueObjectVariable.h"
32 #include "lldb/DataFormatters/DataVisualization.h"
33 #include "lldb/DataFormatters/FormatManager.h"
34 #include "lldb/DataFormatters/TypeSummary.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/ClangASTContext.h"
44 #include "lldb/Symbol/CompileUnit.h"
45 #include "lldb/Symbol/Function.h"
46 #include "lldb/Symbol/Symbol.h"
47 #include "lldb/Symbol/VariableList.h"
48 #include "lldb/Target/CPPLanguageRuntime.h"
49 #include "lldb/Target/ObjCLanguageRuntime.h"
50 #include "lldb/Target/TargetList.h"
51 #include "lldb/Target/Process.h"
52 #include "lldb/Target/RegisterContext.h"
53 #include "lldb/Target/SectionLoadList.h"
54 #include "lldb/Target/StopInfo.h"
55 #include "lldb/Target/Target.h"
56 #include "lldb/Target/Thread.h"
57 #include "lldb/Utility/AnsiTerminal.h"
59 #include "llvm/Support/DynamicLibrary.h"
62 using namespace lldb_private;
65 static lldb::user_id_t g_unique_id = 1;
66 static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
68 #pragma mark Static Functions
71 GetDebuggerListMutex ()
73 static Mutex g_mutex(Mutex::eMutexTypeRecursive);
77 typedef std::vector<DebuggerSP> DebuggerList;
82 // hide the static debugger list inside a singleton accessor to avoid
83 // global init constructors
84 static DebuggerList g_list;
88 OptionEnumValueElement
89 g_show_disassembly_enum_values[] =
91 { Debugger::eStopDisassemblyTypeNever, "never", "Never show disassembly when displaying a stop context."},
92 { Debugger::eStopDisassemblyTypeNoSource, "no-source", "Show disassembly when there is no source information, or the source file is missing when displaying a stop context."},
93 { Debugger::eStopDisassemblyTypeAlways, "always", "Always show disassembly when displaying a stop context."},
97 OptionEnumValueElement
98 g_language_enumerators[] =
100 { eScriptLanguageNone, "none", "Disable scripting languages."},
101 { eScriptLanguagePython, "python", "Select python as the default scripting language."},
102 { eScriptLanguageDefault, "default", "Select the lldb default as the default scripting language."},
106 #define MODULE_WITH_FUNC "{ ${module.file.basename}{`${function.name-with-args}${function.pc-offset}}}"
107 #define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}"
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}"\
127 // Three parts to this disassembly format specification:
128 // 1. If this is a new function/symbol (no previous symbol/function), print
130 // 2. If this is a symbol context change (different from previous symbol/function), print
133 // address <+offset>:
134 #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}>}: "
136 // gdb's disassembly format can be emulated with
137 // ${current-pc-arrow}${addr-file-or-load}{ <${function.name-without-args}${function.concrete-only-addr-offset-no-padding}>}:
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} }{${addr-file-or-load}}:
143 static PropertyDefinition
146 { "auto-confirm", OptionValue::eTypeBoolean , true, false, NULL, NULL, "If true all confirmation prompts will receive their default reply." },
147 { "disassembly-format", OptionValue::eTypeFormatEntity, true, 0 , DEFAULT_DISASSEMBLY_FORMAT, NULL, "The default disassembly format string to use when disassembling instruction sequences." },
148 { "frame-format", OptionValue::eTypeFormatEntity, true, 0 , DEFAULT_FRAME_FORMAT, NULL, "The default frame format string to use when displaying stack frame information for threads." },
149 { "notify-void", OptionValue::eTypeBoolean , true, false, NULL, NULL, "Notify the user explicitly if an expression returns void (default: false)." },
150 { "prompt", OptionValue::eTypeString , true, OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ", NULL, "The debugger command line prompt displayed for the user." },
151 { "script-lang", OptionValue::eTypeEnum , true, eScriptLanguagePython, NULL, g_language_enumerators, "The script language to be used for evaluating user-written scripts." },
152 { "stop-disassembly-count", OptionValue::eTypeSInt64 , true, 4 , NULL, NULL, "The number of disassembly lines to show when displaying a stopped context." },
153 { "stop-disassembly-display", OptionValue::eTypeEnum , true, Debugger::eStopDisassemblyTypeNoSource, NULL, g_show_disassembly_enum_values, "Control when to display disassembly when displaying a stopped context." },
154 { "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." },
155 { "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." },
156 { "term-width", OptionValue::eTypeSInt64 , true, 80 , NULL, NULL, "The maximum number of columns to use for displaying text." },
157 { "thread-format", OptionValue::eTypeFormatEntity, true, 0 , DEFAULT_THREAD_FORMAT, NULL, "The default thread format string to use when displaying thread information." },
158 { "use-external-editor", OptionValue::eTypeBoolean , true, false, NULL, NULL, "Whether to use an external editor or not." },
159 { "use-color", OptionValue::eTypeBoolean , true, true , NULL, NULL, "Whether to use Ansi color codes or not." },
160 { "auto-one-line-summaries", OptionValue::eTypeBoolean , true, true, NULL, NULL, "If true, LLDB will automatically display small structs in one-liner format (default: true)." },
161 { "escape-non-printables", OptionValue::eTypeBoolean , true, true, NULL, NULL, "If true, LLDB will automatically escape non-printable and escape characters when formatting strings." },
162 { NULL, OptionValue::eTypeInvalid , true, 0 , NULL, NULL, NULL }
167 ePropertyAutoConfirm = 0,
168 ePropertyDisassemblyFormat,
169 ePropertyFrameFormat,
172 ePropertyScriptLanguage,
173 ePropertyStopDisassemblyCount,
174 ePropertyStopDisassemblyDisplay,
175 ePropertyStopLineCountAfter,
176 ePropertyStopLineCountBefore,
177 ePropertyTerminalWidth,
178 ePropertyThreadFormat,
179 ePropertyUseExternalEditor,
181 ePropertyAutoOneLineSummaries,
182 ePropertyEscapeNonPrintables
185 LoadPluginCallbackType Debugger::g_load_plugin_callback = NULL;
188 Debugger::SetPropertyValue (const ExecutionContext *exe_ctx,
189 VarSetOperationType op,
190 const char *property_path,
193 bool is_load_script = strcmp(property_path,"target.load-script-from-symbol-file") == 0;
194 bool is_escape_non_printables = strcmp(property_path, "escape-non-printables") == 0;
196 LoadScriptFromSymFile load_script_old_value;
197 if (is_load_script && exe_ctx->GetTargetSP())
199 target_sp = exe_ctx->GetTargetSP();
200 load_script_old_value = target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
202 Error error (Properties::SetPropertyValue (exe_ctx, op, property_path, value));
205 // FIXME it would be nice to have "on-change" callbacks for properties
206 if (strcmp(property_path, g_properties[ePropertyPrompt].name) == 0)
208 const char *new_prompt = GetPrompt();
209 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
211 new_prompt = str.c_str();
212 GetCommandInterpreter().UpdatePrompt(new_prompt);
213 EventSP prompt_change_event_sp (new Event(CommandInterpreter::eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));
214 GetCommandInterpreter().BroadcastEvent (prompt_change_event_sp);
216 else if (strcmp(property_path, g_properties[ePropertyUseColor].name) == 0)
218 // use-color changed. Ping the prompt so it can reset the ansi terminal codes.
219 SetPrompt (GetPrompt());
221 else if (is_load_script && target_sp && load_script_old_value == eLoadScriptFromSymFileWarn)
223 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() == eLoadScriptFromSymFileTrue)
225 std::list<Error> errors;
226 StreamString feedback_stream;
227 if (!target_sp->LoadScriptingResources(errors,&feedback_stream))
229 StreamFileSP stream_sp (GetErrorFile());
232 for (auto error : errors)
234 stream_sp->Printf("%s\n",error.AsCString());
236 if (feedback_stream.GetSize())
237 stream_sp->Printf("%s",feedback_stream.GetData());
242 else if (is_escape_non_printables)
244 DataVisualization::ForceUpdate();
251 Debugger::GetAutoConfirm () const
253 const uint32_t idx = ePropertyAutoConfirm;
254 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
257 const FormatEntity::Entry *
258 Debugger::GetDisassemblyFormat() const
260 const uint32_t idx = ePropertyDisassemblyFormat;
261 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(NULL, idx);
264 const FormatEntity::Entry *
265 Debugger::GetFrameFormat() const
267 const uint32_t idx = ePropertyFrameFormat;
268 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(NULL, idx);
272 Debugger::GetNotifyVoid () const
274 const uint32_t idx = ePropertyNotiftVoid;
275 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
279 Debugger::GetPrompt() const
281 const uint32_t idx = ePropertyPrompt;
282 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
286 Debugger::SetPrompt(const char *p)
288 const uint32_t idx = ePropertyPrompt;
289 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
290 const char *new_prompt = GetPrompt();
291 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
293 new_prompt = str.c_str();
294 GetCommandInterpreter().UpdatePrompt(new_prompt);
297 const FormatEntity::Entry *
298 Debugger::GetThreadFormat() const
300 const uint32_t idx = ePropertyThreadFormat;
301 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(NULL, idx);
305 Debugger::GetScriptLanguage() const
307 const uint32_t idx = ePropertyScriptLanguage;
308 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
312 Debugger::SetScriptLanguage (lldb::ScriptLanguage script_lang)
314 const uint32_t idx = ePropertyScriptLanguage;
315 return m_collection_sp->SetPropertyAtIndexAsEnumeration (NULL, idx, script_lang);
319 Debugger::GetTerminalWidth () const
321 const uint32_t idx = ePropertyTerminalWidth;
322 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
326 Debugger::SetTerminalWidth (uint32_t term_width)
328 const uint32_t idx = ePropertyTerminalWidth;
329 return m_collection_sp->SetPropertyAtIndexAsSInt64 (NULL, idx, term_width);
333 Debugger::GetUseExternalEditor () const
335 const uint32_t idx = ePropertyUseExternalEditor;
336 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
340 Debugger::SetUseExternalEditor (bool b)
342 const uint32_t idx = ePropertyUseExternalEditor;
343 return m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
347 Debugger::GetUseColor () const
349 const uint32_t idx = ePropertyUseColor;
350 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
354 Debugger::SetUseColor (bool b)
356 const uint32_t idx = ePropertyUseColor;
357 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
358 SetPrompt (GetPrompt());
363 Debugger::GetStopSourceLineCount (bool before) const
365 const uint32_t idx = before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
366 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
369 Debugger::StopDisassemblyType
370 Debugger::GetStopDisassemblyDisplay () const
372 const uint32_t idx = ePropertyStopDisassemblyDisplay;
373 return (Debugger::StopDisassemblyType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
377 Debugger::GetDisassemblyLineCount () const
379 const uint32_t idx = ePropertyStopDisassemblyCount;
380 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
384 Debugger::GetAutoOneLineSummaries () const
386 const uint32_t idx = ePropertyAutoOneLineSummaries;
387 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
391 Debugger::GetEscapeNonPrintables () const
393 const uint32_t idx = ePropertyEscapeNonPrintables;
394 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
397 #pragma mark Debugger
399 //const DebuggerPropertiesSP &
400 //Debugger::GetSettings() const
402 // return m_properties_sp;
406 static bool lldb_initialized = false;
408 Debugger::Initialize(LoadPluginCallbackType load_plugin_callback)
410 assert(!lldb_initialized && "Debugger::Initialize called more than once!");
412 lldb_initialized = true;
413 g_load_plugin_callback = load_plugin_callback;
417 Debugger::Terminate ()
419 assert(lldb_initialized && "Debugger::Terminate called without a matching Debugger::Initialize!");
421 // Clear our master list of debugger objects
422 Mutex::Locker locker (GetDebuggerListMutex ());
423 GetDebuggerList().clear();
427 Debugger::SettingsInitialize ()
429 Target::SettingsInitialize ();
433 Debugger::SettingsTerminate ()
435 Target::SettingsTerminate ();
439 Debugger::LoadPlugin (const FileSpec& spec, Error& error)
441 if (g_load_plugin_callback)
443 llvm::sys::DynamicLibrary dynlib = g_load_plugin_callback (shared_from_this(), spec, error);
444 if (dynlib.isValid())
446 m_loaded_plugins.push_back(dynlib);
452 // The g_load_plugin_callback is registered in SBDebugger::Initialize()
453 // and if the public API layer isn't available (code is linking against
454 // all of the internal LLDB static libraries), then we can't load plugins
455 error.SetErrorString("Public API layer is not available");
460 static FileSpec::EnumerateDirectoryResult
464 FileSpec::FileType file_type,
465 const FileSpec &file_spec
470 static ConstString g_dylibext("dylib");
471 static ConstString g_solibext("so");
474 return FileSpec::eEnumerateDirectoryResultQuit;
476 Debugger *debugger = (Debugger*)baton;
478 // If we have a regular file, a symbolic link or unknown file type, try
479 // and process the file. We must handle unknown as sometimes the directory
480 // enumeration might be enumerating a file system that doesn't have correct
481 // file type information.
482 if (file_type == FileSpec::eFileTypeRegular ||
483 file_type == FileSpec::eFileTypeSymbolicLink ||
484 file_type == FileSpec::eFileTypeUnknown )
486 FileSpec plugin_file_spec (file_spec);
487 plugin_file_spec.ResolvePath ();
489 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
490 plugin_file_spec.GetFileNameExtension() != g_solibext)
492 return FileSpec::eEnumerateDirectoryResultNext;
495 Error plugin_load_error;
496 debugger->LoadPlugin (plugin_file_spec, plugin_load_error);
498 return FileSpec::eEnumerateDirectoryResultNext;
501 else if (file_type == FileSpec::eFileTypeUnknown ||
502 file_type == FileSpec::eFileTypeDirectory ||
503 file_type == FileSpec::eFileTypeSymbolicLink )
505 // Try and recurse into anything that a directory or symbolic link.
506 // We must also do this for unknown as sometimes the directory enumeration
507 // might be enumerating a file system that doesn't have correct file type
509 return FileSpec::eEnumerateDirectoryResultEnter;
512 return FileSpec::eEnumerateDirectoryResultNext;
516 Debugger::InstanceInitialize ()
519 const bool find_directories = true;
520 const bool find_files = true;
521 const bool find_other = true;
522 char dir_path[PATH_MAX];
523 if (HostInfo::GetLLDBPath(ePathTypeLLDBSystemPlugins, dir_spec))
525 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
527 FileSpec::EnumerateDirectory (dir_path,
536 if (HostInfo::GetLLDBPath(ePathTypeLLDBUserPlugins, dir_spec))
538 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
540 FileSpec::EnumerateDirectory (dir_path,
549 PluginManager::DebuggerInitialize (*this);
553 Debugger::CreateInstance (lldb::LogOutputCallback log_callback, void *baton)
555 DebuggerSP debugger_sp (new Debugger(log_callback, baton));
556 if (lldb_initialized)
558 Mutex::Locker locker (GetDebuggerListMutex ());
559 GetDebuggerList().push_back(debugger_sp);
561 debugger_sp->InstanceInitialize ();
566 Debugger::Destroy (DebuggerSP &debugger_sp)
568 if (debugger_sp.get() == NULL)
571 debugger_sp->Clear();
573 if (lldb_initialized)
575 Mutex::Locker locker (GetDebuggerListMutex ());
576 DebuggerList &debugger_list = GetDebuggerList ();
577 DebuggerList::iterator pos, end = debugger_list.end();
578 for (pos = debugger_list.begin (); pos != end; ++pos)
580 if ((*pos).get() == debugger_sp.get())
582 debugger_list.erase (pos);
590 Debugger::FindDebuggerWithInstanceName (const ConstString &instance_name)
592 DebuggerSP debugger_sp;
593 if (lldb_initialized)
595 Mutex::Locker locker (GetDebuggerListMutex ());
596 DebuggerList &debugger_list = GetDebuggerList();
597 DebuggerList::iterator pos, end = debugger_list.end();
599 for (pos = debugger_list.begin(); pos != end; ++pos)
601 if ((*pos).get()->m_instance_name == instance_name)
612 Debugger::FindTargetWithProcessID (lldb::pid_t pid)
615 if (lldb_initialized)
617 Mutex::Locker locker (GetDebuggerListMutex ());
618 DebuggerList &debugger_list = GetDebuggerList();
619 DebuggerList::iterator pos, end = debugger_list.end();
620 for (pos = debugger_list.begin(); pos != end; ++pos)
622 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID (pid);
631 Debugger::FindTargetWithProcess (Process *process)
634 if (lldb_initialized)
636 Mutex::Locker locker (GetDebuggerListMutex ());
637 DebuggerList &debugger_list = GetDebuggerList();
638 DebuggerList::iterator pos, end = debugger_list.end();
639 for (pos = debugger_list.begin(); pos != end; ++pos)
641 target_sp = (*pos)->GetTargetList().FindTargetWithProcess (process);
649 Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton) :
650 UserID(g_unique_id++),
651 Properties(OptionValuePropertiesSP(new OptionValueProperties())),
652 m_input_file_sp(new StreamFile(stdin, false)),
653 m_output_file_sp(new StreamFile(stdout, false)),
654 m_error_file_sp(new StreamFile(stderr, false)),
656 m_target_list(*this),
658 m_listener("lldb.Debugger"),
659 m_source_manager_ap(),
660 m_source_file_cache(),
661 m_command_interpreter_ap(new CommandInterpreter(*this, eScriptLanguageDefault, false)),
662 m_input_reader_stack(),
665 m_event_handler_thread (),
666 m_io_handler_thread (),
667 m_sync_broadcaster (NULL, "lldb.debugger.sync")
669 char instance_cstr[256];
670 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
671 m_instance_name.SetCString(instance_cstr);
673 m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
674 m_command_interpreter_ap->Initialize ();
675 // Always add our default platform to the platform list
676 PlatformSP default_platform_sp (Platform::GetHostPlatform());
677 assert (default_platform_sp.get());
678 m_platform_list.Append (default_platform_sp, true);
680 m_collection_sp->Initialize (g_properties);
681 m_collection_sp->AppendProperty (ConstString("target"),
682 ConstString("Settings specify to debugging targets."),
684 Target::GetGlobalProperties()->GetValueProperties());
685 m_collection_sp->AppendProperty (ConstString("platform"),
686 ConstString("Platform settings."),
688 Platform::GetGlobalPlatformProperties()->GetValueProperties());
689 if (m_command_interpreter_ap.get())
691 m_collection_sp->AppendProperty (ConstString("interpreter"),
692 ConstString("Settings specify to the debugger's command interpreter."),
694 m_command_interpreter_ap->GetValueProperties());
696 OptionValueSInt64 *term_width = m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64 (NULL, ePropertyTerminalWidth);
697 term_width->SetMinimumValue(10);
698 term_width->SetMaximumValue(1024);
700 // Turn off use-color if this is a dumb terminal.
701 const char *term = getenv ("TERM");
702 if (term && !strcmp (term, "dumb"))
706 Debugger::~Debugger ()
715 StopIOHandlerThread();
716 StopEventHandlerThread();
718 int num_targets = m_target_list.GetNumTargets();
719 for (int i = 0; i < num_targets; i++)
721 TargetSP target_sp (m_target_list.GetTargetAtIndex (i));
724 ProcessSP process_sp (target_sp->GetProcessSP());
726 process_sp->Finalize();
727 target_sp->Destroy();
730 BroadcasterManager::Clear ();
732 // Close the input file _before_ we close the input read communications class
733 // as it does NOT own the input file, our m_input_file does.
734 m_terminal_state.Clear();
736 m_input_file_sp->GetFile().Close ();
738 m_command_interpreter_ap->Clear();
742 Debugger::GetCloseInputOnEOF () const
744 // return m_input_comm.GetCloseOnEOF();
749 Debugger::SetCloseInputOnEOF (bool b)
751 // m_input_comm.SetCloseOnEOF(b);
755 Debugger::GetAsyncExecution ()
757 return !m_command_interpreter_ap->GetSynchronous();
761 Debugger::SetAsyncExecution (bool async_execution)
763 m_command_interpreter_ap->SetSynchronous (!async_execution);
768 Debugger::SetInputFileHandle (FILE *fh, bool tranfer_ownership)
771 m_input_file_sp->GetFile().SetStream (fh, tranfer_ownership);
773 m_input_file_sp.reset (new StreamFile (fh, tranfer_ownership));
775 File &in_file = m_input_file_sp->GetFile();
776 if (in_file.IsValid() == false)
777 in_file.SetStream (stdin, true);
779 // Save away the terminal state if that is relevant, so that we can restore it in RestoreInputState.
780 SaveInputTerminalState ();
784 Debugger::SetOutputFileHandle (FILE *fh, bool tranfer_ownership)
786 if (m_output_file_sp)
787 m_output_file_sp->GetFile().SetStream (fh, tranfer_ownership);
789 m_output_file_sp.reset (new StreamFile (fh, tranfer_ownership));
791 File &out_file = m_output_file_sp->GetFile();
792 if (out_file.IsValid() == false)
793 out_file.SetStream (stdout, false);
795 // do not create the ScriptInterpreter just for setting the output file handle
796 // as the constructor will know how to do the right thing on its own
797 const bool can_create = false;
798 ScriptInterpreter* script_interpreter = GetCommandInterpreter().GetScriptInterpreter(can_create);
799 if (script_interpreter)
800 script_interpreter->ResetOutputFileHandle (fh);
804 Debugger::SetErrorFileHandle (FILE *fh, bool tranfer_ownership)
807 m_error_file_sp->GetFile().SetStream (fh, tranfer_ownership);
809 m_error_file_sp.reset (new StreamFile (fh, tranfer_ownership));
811 File &err_file = m_error_file_sp->GetFile();
812 if (err_file.IsValid() == false)
813 err_file.SetStream (stderr, false);
817 Debugger::SaveInputTerminalState ()
821 File &in_file = m_input_file_sp->GetFile();
822 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
823 m_terminal_state.Save(in_file.GetDescriptor(), true);
828 Debugger::RestoreInputTerminalState ()
830 m_terminal_state.Restore();
834 Debugger::GetSelectedExecutionContext ()
836 ExecutionContext exe_ctx;
837 TargetSP target_sp(GetSelectedTarget());
838 exe_ctx.SetTargetSP (target_sp);
842 ProcessSP process_sp (target_sp->GetProcessSP());
843 exe_ctx.SetProcessSP (process_sp);
844 if (process_sp && process_sp->IsRunning() == false)
846 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
849 exe_ctx.SetThreadSP (thread_sp);
850 exe_ctx.SetFrameSP (thread_sp->GetSelectedFrame());
851 if (exe_ctx.GetFramePtr() == NULL)
852 exe_ctx.SetFrameSP (thread_sp->GetStackFrameAtIndex (0));
860 Debugger::DispatchInputInterrupt ()
862 Mutex::Locker locker (m_input_reader_stack.GetMutex());
863 IOHandlerSP reader_sp (m_input_reader_stack.Top());
865 reader_sp->Interrupt();
869 Debugger::DispatchInputEndOfFile ()
871 Mutex::Locker locker (m_input_reader_stack.GetMutex());
872 IOHandlerSP reader_sp (m_input_reader_stack.Top());
878 Debugger::ClearIOHandlers ()
880 // The bottom input reader should be the main debugger input reader. We do not want to close that one here.
881 Mutex::Locker locker (m_input_reader_stack.GetMutex());
882 while (m_input_reader_stack.GetSize() > 1)
884 IOHandlerSP reader_sp (m_input_reader_stack.Top());
886 PopIOHandler (reader_sp);
891 Debugger::ExecuteIOHandlers()
895 IOHandlerSP reader_sp(m_input_reader_stack.Top());
901 // Remove all input readers that are done from the top of the stack
904 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
905 if (top_reader_sp && top_reader_sp->GetIsDone())
906 PopIOHandler (top_reader_sp);
915 Debugger::IsTopIOHandler (const lldb::IOHandlerSP& reader_sp)
917 return m_input_reader_stack.IsTop (reader_sp);
921 Debugger::PrintAsync (const char *s, size_t len, bool is_stdout)
923 lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile();
924 m_input_reader_stack.PrintAsync(stream.get(), s, len);
928 Debugger::GetTopIOHandlerControlSequence(char ch)
930 return m_input_reader_stack.GetTopIOHandlerControlSequence (ch);
934 Debugger::GetIOHandlerCommandPrefix()
936 return m_input_reader_stack.GetTopIOHandlerCommandPrefix();
940 Debugger::GetIOHandlerHelpPrologue()
942 return m_input_reader_stack.GetTopIOHandlerHelpPrologue();
946 Debugger::RunIOHandler (const IOHandlerSP& reader_sp)
948 PushIOHandler (reader_sp);
950 IOHandlerSP top_reader_sp = reader_sp;
951 while (top_reader_sp)
953 top_reader_sp->Run();
955 if (top_reader_sp.get() == reader_sp.get())
957 if (PopIOHandler (reader_sp))
963 top_reader_sp = m_input_reader_stack.Top();
964 if (top_reader_sp && top_reader_sp->GetIsDone())
965 PopIOHandler (top_reader_sp);
973 Debugger::AdoptTopIOHandlerFilesIfInvalid (StreamFileSP &in, StreamFileSP &out, StreamFileSP &err)
975 // Before an IOHandler runs, it must have in/out/err streams.
976 // This function is called when one ore more of the streams
977 // are NULL. We use the top input reader's in/out/err streams,
978 // or fall back to the debugger file handles, or we fall back
979 // onto stdin/stdout/stderr as a last resort.
981 Mutex::Locker locker (m_input_reader_stack.GetMutex());
982 IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
983 // If no STDIN has been set, then set it appropriately
987 in = top_reader_sp->GetInputStreamFile();
991 // If there is nothing, use stdin
993 in = StreamFileSP(new StreamFile(stdin, false));
995 // If no STDOUT has been set, then set it appropriately
999 out = top_reader_sp->GetOutputStreamFile();
1001 out = GetOutputFile();
1003 // If there is nothing, use stdout
1005 out = StreamFileSP(new StreamFile(stdout, false));
1007 // If no STDERR has been set, then set it appropriately
1011 err = top_reader_sp->GetErrorStreamFile();
1013 err = GetErrorFile();
1015 // If there is nothing, use stderr
1017 err = StreamFileSP(new StreamFile(stdout, false));
1023 Debugger::PushIOHandler (const IOHandlerSP& reader_sp)
1028 Mutex::Locker locker (m_input_reader_stack.GetMutex());
1030 // Get the current top input reader...
1031 IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
1033 // Don't push the same IO handler twice...
1034 if (reader_sp == top_reader_sp)
1037 // Push our new input reader
1038 m_input_reader_stack.Push (reader_sp);
1039 reader_sp->Activate();
1041 // Interrupt the top input reader to it will exit its Run() function
1042 // and let this new input reader take over
1045 top_reader_sp->Deactivate();
1046 top_reader_sp->Cancel();
1051 Debugger::PopIOHandler (const IOHandlerSP& pop_reader_sp)
1053 if (! pop_reader_sp)
1056 Mutex::Locker locker (m_input_reader_stack.GetMutex());
1058 // The reader on the stop of the stack is done, so let the next
1059 // read on the stack refresh its prompt and if there is one...
1060 if (m_input_reader_stack.IsEmpty())
1063 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1065 if (pop_reader_sp != reader_sp)
1068 reader_sp->Deactivate();
1069 reader_sp->Cancel();
1070 m_input_reader_stack.Pop ();
1072 reader_sp = m_input_reader_stack.Top();
1074 reader_sp->Activate();
1080 Debugger::GetAsyncOutputStream ()
1082 return StreamSP (new StreamAsynchronousIO (*this, true));
1086 Debugger::GetAsyncErrorStream ()
1088 return StreamSP (new StreamAsynchronousIO (*this, false));
1092 Debugger::GetNumDebuggers()
1094 if (lldb_initialized)
1096 Mutex::Locker locker (GetDebuggerListMutex ());
1097 return GetDebuggerList().size();
1103 Debugger::GetDebuggerAtIndex (size_t index)
1105 DebuggerSP debugger_sp;
1107 if (lldb_initialized)
1109 Mutex::Locker locker (GetDebuggerListMutex ());
1110 DebuggerList &debugger_list = GetDebuggerList();
1112 if (index < debugger_list.size())
1113 debugger_sp = debugger_list[index];
1120 Debugger::FindDebuggerWithID (lldb::user_id_t id)
1122 DebuggerSP debugger_sp;
1124 if (lldb_initialized)
1126 Mutex::Locker locker (GetDebuggerListMutex ());
1127 DebuggerList &debugger_list = GetDebuggerList();
1128 DebuggerList::iterator pos, end = debugger_list.end();
1129 for (pos = debugger_list.begin(); pos != end; ++pos)
1131 if ((*pos).get()->GetID() == id)
1143 TestPromptFormats (StackFrame *frame)
1149 const char *prompt_format =
1150 "{addr = '${addr}'\n}"
1151 "{addr-file-or-load = '${addr-file-or-load}'\n}"
1152 "{current-pc-arrow = '${current-pc-arrow}'\n}"
1153 "{process.id = '${process.id}'\n}"
1154 "{process.name = '${process.name}'\n}"
1155 "{process.file.basename = '${process.file.basename}'\n}"
1156 "{process.file.fullpath = '${process.file.fullpath}'\n}"
1157 "{thread.id = '${thread.id}'\n}"
1158 "{thread.index = '${thread.index}'\n}"
1159 "{thread.name = '${thread.name}'\n}"
1160 "{thread.queue = '${thread.queue}'\n}"
1161 "{thread.stop-reason = '${thread.stop-reason}'\n}"
1162 "{target.arch = '${target.arch}'\n}"
1163 "{module.file.basename = '${module.file.basename}'\n}"
1164 "{module.file.fullpath = '${module.file.fullpath}'\n}"
1165 "{file.basename = '${file.basename}'\n}"
1166 "{file.fullpath = '${file.fullpath}'\n}"
1167 "{frame.index = '${frame.index}'\n}"
1168 "{frame.pc = '${frame.pc}'\n}"
1169 "{frame.sp = '${frame.sp}'\n}"
1170 "{frame.fp = '${frame.fp}'\n}"
1171 "{frame.flags = '${frame.flags}'\n}"
1172 "{frame.reg.rdi = '${frame.reg.rdi}'\n}"
1173 "{frame.reg.rip = '${frame.reg.rip}'\n}"
1174 "{frame.reg.rsp = '${frame.reg.rsp}'\n}"
1175 "{frame.reg.rbp = '${frame.reg.rbp}'\n}"
1176 "{frame.reg.rflags = '${frame.reg.rflags}'\n}"
1177 "{frame.reg.xmm0 = '${frame.reg.xmm0}'\n}"
1178 "{frame.reg.carp = '${frame.reg.carp}'\n}"
1179 "{function.id = '${function.id}'\n}"
1180 "{function.changed = '${function.changed}'\n}"
1181 "{function.initial-function = '${function.initial-function}'\n}"
1182 "{function.name = '${function.name}'\n}"
1183 "{function.name-without-args = '${function.name-without-args}'\n}"
1184 "{function.name-with-args = '${function.name-with-args}'\n}"
1185 "{function.addr-offset = '${function.addr-offset}'\n}"
1186 "{function.concrete-only-addr-offset-no-padding = '${function.concrete-only-addr-offset-no-padding}'\n}"
1187 "{function.line-offset = '${function.line-offset}'\n}"
1188 "{function.pc-offset = '${function.pc-offset}'\n}"
1189 "{line.file.basename = '${line.file.basename}'\n}"
1190 "{line.file.fullpath = '${line.file.fullpath}'\n}"
1191 "{line.number = '${line.number}'\n}"
1192 "{line.start-addr = '${line.start-addr}'\n}"
1193 "{line.end-addr = '${line.end-addr}'\n}"
1196 SymbolContext sc (frame->GetSymbolContext(eSymbolContextEverything));
1197 ExecutionContext exe_ctx;
1198 frame->CalculateExecutionContext(exe_ctx);
1199 if (Debugger::FormatPrompt (prompt_format, &sc, &exe_ctx, &sc.line_entry.range.GetBaseAddress(), s))
1201 printf("%s\n", s.GetData());
1205 printf ("what we got: %s\n", s.GetData());
1211 Debugger::FormatDisassemblerAddress (const FormatEntity::Entry *format,
1212 const SymbolContext *sc,
1213 const SymbolContext *prev_sc,
1214 const ExecutionContext *exe_ctx,
1215 const Address *addr,
1218 FormatEntity::Entry format_entry;
1222 if (exe_ctx != NULL && exe_ctx->HasTargetScope())
1223 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1226 FormatEntity::Parse("${addr}: ", format_entry);
1227 format = &format_entry;
1230 bool function_changed = false;
1231 bool initial_function = false;
1232 if (prev_sc && (prev_sc->function || prev_sc->symbol))
1234 if (sc && (sc->function || sc->symbol))
1236 if (prev_sc->symbol && sc->symbol)
1238 if (!sc->symbol->Compare (prev_sc->symbol->GetName(), prev_sc->symbol->GetType()))
1240 function_changed = true;
1243 else if (prev_sc->function && sc->function)
1245 if (prev_sc->function->GetMangled() != sc->function->GetMangled())
1247 function_changed = true;
1252 // The first context on a list of instructions will have a prev_sc that
1253 // has no Function or Symbol -- if SymbolContext had an IsValid() method, it
1254 // would return false. But we do get a prev_sc pointer.
1255 if ((sc && (sc->function || sc->symbol))
1256 && prev_sc && (prev_sc->function == NULL && prev_sc->symbol == NULL))
1258 initial_function = true;
1260 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, NULL, function_changed, initial_function);
1265 Debugger::SetLoggingCallback (lldb::LogOutputCallback log_callback, void *baton)
1267 // For simplicity's sake, I am not going to deal with how to close down any
1268 // open logging streams, I just redirect everything from here on out to the
1270 m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
1274 Debugger::EnableLog (const char *channel, const char **categories, const char *log_file, uint32_t log_options, Stream &error_stream)
1276 StreamSP log_stream_sp;
1277 if (m_log_callback_stream_sp)
1279 log_stream_sp = m_log_callback_stream_sp;
1280 // For now when using the callback mode you always get thread & timestamp.
1281 log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
1283 else if (log_file == NULL || *log_file == '\0')
1285 log_stream_sp = GetOutputFile();
1289 LogStreamMap::iterator pos = m_log_streams.find(log_file);
1290 if (pos != m_log_streams.end())
1291 log_stream_sp = pos->second.lock();
1294 uint32_t options = File::eOpenOptionWrite | File::eOpenOptionCanCreate
1295 | File::eOpenOptionCloseOnExec | File::eOpenOptionAppend;
1296 if (! (log_options & LLDB_LOG_OPTION_APPEND))
1297 options |= File::eOpenOptionTruncate;
1299 log_stream_sp.reset (new StreamFile (log_file, options));
1300 m_log_streams[log_file] = log_stream_sp;
1303 assert (log_stream_sp.get());
1305 if (log_options == 0)
1306 log_options = LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1308 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories, error_stream);
1312 Debugger::GetSourceManager ()
1314 if (m_source_manager_ap.get() == NULL)
1315 m_source_manager_ap.reset (new SourceManager (shared_from_this()));
1316 return *m_source_manager_ap;
1321 // This function handles events that were broadcast by the process.
1323 Debugger::HandleBreakpointEvent (const EventSP &event_sp)
1325 using namespace lldb;
1326 const uint32_t event_type = Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent (event_sp);
1328 // if (event_type & eBreakpointEventTypeAdded
1329 // || event_type & eBreakpointEventTypeRemoved
1330 // || event_type & eBreakpointEventTypeEnabled
1331 // || event_type & eBreakpointEventTypeDisabled
1332 // || event_type & eBreakpointEventTypeCommandChanged
1333 // || event_type & eBreakpointEventTypeConditionChanged
1334 // || event_type & eBreakpointEventTypeIgnoreChanged
1335 // || event_type & eBreakpointEventTypeLocationsResolved)
1337 // // Don't do anything about these events, since the breakpoint commands already echo these actions.
1340 if (event_type & eBreakpointEventTypeLocationsAdded)
1342 uint32_t num_new_locations = Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(event_sp);
1343 if (num_new_locations > 0)
1345 BreakpointSP breakpoint = Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1346 StreamSP output_sp (GetAsyncOutputStream());
1349 output_sp->Printf("%d location%s added to breakpoint %d\n",
1351 num_new_locations == 1 ? "" : "s",
1352 breakpoint->GetID());
1357 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
1359 // // These locations just get disabled, not sure it is worth spamming folks about this on the command line.
1361 // else if (event_type & eBreakpointEventTypeLocationsResolved)
1363 // // This might be an interesting thing to note, but I'm going to leave it quiet for now, it just looked noisy.
1368 Debugger::GetProcessSTDOUT (Process *process, Stream *stream)
1370 size_t total_bytes = 0;
1372 stream = GetOutputFile().get();
1376 // The process has stuff waiting for stdout; get it and write it out to the appropriate place.
1377 if (process == NULL)
1379 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1381 process = target_sp->GetProcessSP().get();
1387 char stdio_buffer[1024];
1388 while ((len = process->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
1390 stream->Write(stdio_buffer, len);
1400 Debugger::GetProcessSTDERR (Process *process, Stream *stream)
1402 size_t total_bytes = 0;
1404 stream = GetOutputFile().get();
1408 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
1409 if (process == NULL)
1411 TargetSP target_sp = GetTargetList().GetSelectedTarget();
1413 process = target_sp->GetProcessSP().get();
1419 char stdio_buffer[1024];
1420 while ((len = process->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
1422 stream->Write(stdio_buffer, len);
1432 // This function handles events that were broadcast by the process.
1434 Debugger::HandleProcessEvent (const EventSP &event_sp)
1436 using namespace lldb;
1437 const uint32_t event_type = event_sp->GetType();
1438 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1440 StreamSP output_stream_sp = GetAsyncOutputStream();
1441 StreamSP error_stream_sp = GetAsyncErrorStream();
1442 const bool gui_enabled = IsForwardingEvents();
1446 bool pop_process_io_handler = false;
1447 assert (process_sp);
1449 bool state_is_stopped = false;
1450 const bool got_state_changed = (event_type & Process::eBroadcastBitStateChanged) != 0;
1451 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1452 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1453 if (got_state_changed)
1455 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1456 state_is_stopped = StateIsStoppedState(event_state, false);
1459 // Display running state changes first before any STDIO
1460 if (got_state_changed && !state_is_stopped)
1462 Process::HandleProcessStateChangedEvent (event_sp, output_stream_sp.get(), pop_process_io_handler);
1465 // Now display and STDOUT
1466 if (got_stdout || got_state_changed)
1468 GetProcessSTDOUT (process_sp.get(), output_stream_sp.get());
1471 // Now display and STDERR
1472 if (got_stderr || got_state_changed)
1474 GetProcessSTDERR (process_sp.get(), error_stream_sp.get());
1477 // Now display any stopped state changes after any STDIO
1478 if (got_state_changed && state_is_stopped)
1480 Process::HandleProcessStateChangedEvent (event_sp, output_stream_sp.get(), pop_process_io_handler);
1483 output_stream_sp->Flush();
1484 error_stream_sp->Flush();
1486 if (pop_process_io_handler)
1487 process_sp->PopProcessIOHandler();
1492 Debugger::HandleThreadEvent (const EventSP &event_sp)
1494 // At present the only thread event we handle is the Frame Changed event,
1495 // and all we do for that is just reprint the thread status for that thread.
1496 using namespace lldb;
1497 const uint32_t event_type = event_sp->GetType();
1498 if (event_type == Thread::eBroadcastBitStackChanged ||
1499 event_type == Thread::eBroadcastBitThreadSelected )
1501 ThreadSP thread_sp (Thread::ThreadEventData::GetThreadFromEvent (event_sp.get()));
1504 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1);
1510 Debugger::IsForwardingEvents ()
1512 return (bool)m_forward_listener_sp;
1516 Debugger::EnableForwardEvents (const ListenerSP &listener_sp)
1518 m_forward_listener_sp = listener_sp;
1522 Debugger::CancelForwardEvents (const ListenerSP &listener_sp)
1524 m_forward_listener_sp.reset();
1529 Debugger::DefaultEventHandler()
1531 Listener& listener(GetListener());
1532 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1533 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1534 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1535 BroadcastEventSpec target_event_spec (broadcaster_class_target,
1536 Target::eBroadcastBitBreakpointChanged);
1538 BroadcastEventSpec process_event_spec (broadcaster_class_process,
1539 Process::eBroadcastBitStateChanged |
1540 Process::eBroadcastBitSTDOUT |
1541 Process::eBroadcastBitSTDERR);
1543 BroadcastEventSpec thread_event_spec (broadcaster_class_thread,
1544 Thread::eBroadcastBitStackChanged |
1545 Thread::eBroadcastBitThreadSelected );
1547 listener.StartListeningForEventSpec (*this, target_event_spec);
1548 listener.StartListeningForEventSpec (*this, process_event_spec);
1549 listener.StartListeningForEventSpec (*this, thread_event_spec);
1550 listener.StartListeningForEvents (m_command_interpreter_ap.get(),
1551 CommandInterpreter::eBroadcastBitQuitCommandReceived |
1552 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1553 CommandInterpreter::eBroadcastBitAsynchronousErrorData );
1555 // Let the thread that spawned us know that we have started up and
1556 // that we are now listening to all required events so no events get missed
1557 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
1563 if (listener.WaitForEvent(NULL, event_sp))
1567 Broadcaster *broadcaster = event_sp->GetBroadcaster();
1570 uint32_t event_type = event_sp->GetType();
1571 ConstString broadcaster_class (broadcaster->GetBroadcasterClass());
1572 if (broadcaster_class == broadcaster_class_process)
1574 HandleProcessEvent (event_sp);
1576 else if (broadcaster_class == broadcaster_class_target)
1578 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(event_sp.get()))
1580 HandleBreakpointEvent (event_sp);
1583 else if (broadcaster_class == broadcaster_class_thread)
1585 HandleThreadEvent (event_sp);
1587 else if (broadcaster == m_command_interpreter_ap.get())
1589 if (event_type & CommandInterpreter::eBroadcastBitQuitCommandReceived)
1593 else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousErrorData)
1595 const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
1596 if (data && data[0])
1598 StreamSP error_sp (GetAsyncErrorStream());
1601 error_sp->PutCString(data);
1606 else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousOutputData)
1608 const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
1609 if (data && data[0])
1611 StreamSP output_sp (GetAsyncOutputStream());
1614 output_sp->PutCString(data);
1622 if (m_forward_listener_sp)
1623 m_forward_listener_sp->AddEvent(event_sp);
1629 lldb::thread_result_t
1630 Debugger::EventHandlerThread (lldb::thread_arg_t arg)
1632 ((Debugger *)arg)->DefaultEventHandler();
1637 Debugger::StartEventHandlerThread()
1639 if (!m_event_handler_thread.IsJoinable())
1641 // We must synchronize with the DefaultEventHandler() thread to ensure
1642 // it is up and running and listening to events before we return from
1643 // this function. We do this by listening to events for the
1644 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
1645 Listener listener("lldb.debugger.event-handler");
1646 listener.StartListeningForEvents(&m_sync_broadcaster, eBroadcastBitEventThreadIsListening);
1648 // Use larger 8MB stack for this thread
1649 m_event_handler_thread = ThreadLauncher::LaunchThread("lldb.debugger.event-handler", EventHandlerThread,
1652 g_debugger_event_thread_stack_bytes);
1654 // Make sure DefaultEventHandler() is running and listening to events before we return
1655 // from this function. We are only listening for events of type
1656 // eBroadcastBitEventThreadIsListening so we don't need to check the event, we just need
1657 // to wait an infinite amount of time for it (NULL timeout as the first parameter)
1658 lldb::EventSP event_sp;
1659 listener.WaitForEvent(NULL, event_sp);
1661 return m_event_handler_thread.IsJoinable();
1665 Debugger::StopEventHandlerThread()
1667 if (m_event_handler_thread.IsJoinable())
1669 GetCommandInterpreter().BroadcastEvent(CommandInterpreter::eBroadcastBitQuitCommandReceived);
1670 m_event_handler_thread.Join(nullptr);
1675 lldb::thread_result_t
1676 Debugger::IOHandlerThread (lldb::thread_arg_t arg)
1678 Debugger *debugger = (Debugger *)arg;
1679 debugger->ExecuteIOHandlers();
1680 debugger->StopEventHandlerThread();
1685 Debugger::StartIOHandlerThread()
1687 if (!m_io_handler_thread.IsJoinable())
1688 m_io_handler_thread = ThreadLauncher::LaunchThread ("lldb.debugger.io-handler",
1692 8*1024*1024); // Use larger 8MB stack for this thread
1693 return m_io_handler_thread.IsJoinable();
1697 Debugger::StopIOHandlerThread()
1699 if (m_io_handler_thread.IsJoinable())
1701 if (m_input_file_sp)
1702 m_input_file_sp->GetFile().Close();
1703 m_io_handler_thread.Join(nullptr);
1708 Debugger::GetDummyTarget()
1710 return m_target_list.GetDummyTarget (*this).get();
1714 Debugger::GetSelectedOrDummyTarget(bool prefer_dummy)
1716 Target *target = nullptr;
1719 target = m_target_list.GetSelectedTarget().get();
1724 return GetDummyTarget();