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/lldb-python.h"
12 #include "lldb/Core/Debugger.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/Type.h"
18 #include "llvm/ADT/StringRef.h"
20 #include "lldb/lldb-private.h"
21 #include "lldb/Core/Module.h"
22 #include "lldb/Core/PluginManager.h"
23 #include "lldb/Core/RegisterValue.h"
24 #include "lldb/Core/State.h"
25 #include "lldb/Core/StreamAsynchronousIO.h"
26 #include "lldb/Core/StreamCallback.h"
27 #include "lldb/Core/StreamFile.h"
28 #include "lldb/Core/StreamString.h"
29 #include "lldb/Core/StructuredData.h"
30 #include "lldb/Core/Timer.h"
31 #include "lldb/Core/ValueObject.h"
32 #include "lldb/Core/ValueObjectVariable.h"
33 #include "lldb/DataFormatters/DataVisualization.h"
34 #include "lldb/DataFormatters/FormatManager.h"
35 #include "lldb/DataFormatters/TypeSummary.h"
36 #include "lldb/Host/ConnectionFileDescriptor.h"
37 #include "lldb/Host/HostInfo.h"
38 #include "lldb/Host/Terminal.h"
39 #include "lldb/Host/ThreadLauncher.h"
40 #include "lldb/Interpreter/CommandInterpreter.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 uint32_t g_shared_debugger_refcount = 0;
66 static lldb::user_id_t g_unique_id = 1;
67 static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
69 #pragma mark Static Functions
72 GetDebuggerListMutex ()
74 static Mutex g_mutex(Mutex::eMutexTypeRecursive);
78 typedef std::vector<DebuggerSP> DebuggerList;
83 // hide the static debugger list inside a singleton accessor to avoid
84 // global init constructors
85 static DebuggerList g_list;
89 OptionEnumValueElement
90 g_show_disassembly_enum_values[] =
92 { Debugger::eStopDisassemblyTypeNever, "never", "Never show disassembly when displaying a stop context."},
93 { Debugger::eStopDisassemblyTypeNoSource, "no-source", "Show disassembly when there is no source information, or the source file is missing when displaying a stop context."},
94 { Debugger::eStopDisassemblyTypeAlways, "always", "Always show disassembly when displaying a stop context."},
98 OptionEnumValueElement
99 g_language_enumerators[] =
101 { eScriptLanguageNone, "none", "Disable scripting languages."},
102 { eScriptLanguagePython, "python", "Select python as the default scripting language."},
103 { eScriptLanguageDefault, "default", "Select the lldb default as the default scripting language."},
107 #define MODULE_WITH_FUNC "{ ${module.file.basename}{`${function.name-with-args}${function.pc-offset}}}"
108 #define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}"
110 #define DEFAULT_THREAD_FORMAT "thread #${thread.index}: tid = ${thread.id%tid}"\
114 "{, name = '${thread.name}'}"\
115 "{, queue = '${thread.queue}'}"\
116 "{, activity = '${thread.info.activity.name}'}" \
117 "{, ${thread.info.trace_messages} messages}" \
118 "{, stop reason = ${thread.stop-reason}}"\
119 "{\\nReturn value: ${thread.return-value}}"\
120 "{\\nCompleted expression: ${thread.completed-expression}}"\
123 #define DEFAULT_FRAME_FORMAT "frame #${frame.index}: ${frame.pc}"\
128 #define DEFAULT_DISASSEMBLY_FORMAT "${current-pc-arrow}${addr-file-or-load}{ <${function.name-without-args}${function.concrete-only-addr-offset-no-padding}>}: "
130 static PropertyDefinition
133 { "auto-confirm", OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true all confirmation prompts will receive their default reply." },
134 { "disassembly-format", OptionValue::eTypeString , true, 0 , DEFAULT_DISASSEMBLY_FORMAT, NULL, "The default disassembly format string to use when disassembling instruction sequences." },
135 { "frame-format", OptionValue::eTypeString , true, 0 , DEFAULT_FRAME_FORMAT, NULL, "The default frame format string to use when displaying stack frame information for threads." },
136 { "notify-void", OptionValue::eTypeBoolean, true, false, NULL, NULL, "Notify the user explicitly if an expression returns void (default: false)." },
137 { "prompt", OptionValue::eTypeString , true, OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ", NULL, "The debugger command line prompt displayed for the user." },
138 { "script-lang", OptionValue::eTypeEnum , true, eScriptLanguagePython, NULL, g_language_enumerators, "The script language to be used for evaluating user-written scripts." },
139 { "stop-disassembly-count", OptionValue::eTypeSInt64 , true, 4 , NULL, NULL, "The number of disassembly lines to show when displaying a stopped context." },
140 { "stop-disassembly-display", OptionValue::eTypeEnum , true, Debugger::eStopDisassemblyTypeNoSource, NULL, g_show_disassembly_enum_values, "Control when to display disassembly when displaying a stopped context." },
141 { "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." },
142 { "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." },
143 { "term-width", OptionValue::eTypeSInt64 , true, 80 , NULL, NULL, "The maximum number of columns to use for displaying text." },
144 { "thread-format", OptionValue::eTypeString , true, 0 , DEFAULT_THREAD_FORMAT, NULL, "The default thread format string to use when displaying thread information." },
145 { "use-external-editor", OptionValue::eTypeBoolean, true, false, NULL, NULL, "Whether to use an external editor or not." },
146 { "use-color", OptionValue::eTypeBoolean, true, true , NULL, NULL, "Whether to use Ansi color codes or not." },
147 { "auto-one-line-summaries", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, LLDB will automatically display small structs in one-liner format (default: true)." },
148 { "escape-non-printables", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, LLDB will automatically escape non-printable and escape characters when formatting strings." },
150 { NULL, OptionValue::eTypeInvalid, true, 0 , NULL, NULL, NULL }
155 ePropertyAutoConfirm = 0,
156 ePropertyDisassemblyFormat,
157 ePropertyFrameFormat,
160 ePropertyScriptLanguage,
161 ePropertyStopDisassemblyCount,
162 ePropertyStopDisassemblyDisplay,
163 ePropertyStopLineCountAfter,
164 ePropertyStopLineCountBefore,
165 ePropertyTerminalWidth,
166 ePropertyThreadFormat,
167 ePropertyUseExternalEditor,
169 ePropertyAutoOneLineSummaries,
170 ePropertyEscapeNonPrintables
173 Debugger::LoadPluginCallbackType Debugger::g_load_plugin_callback = NULL;
176 Debugger::SetPropertyValue (const ExecutionContext *exe_ctx,
177 VarSetOperationType op,
178 const char *property_path,
181 bool is_load_script = strcmp(property_path,"target.load-script-from-symbol-file") == 0;
182 bool is_escape_non_printables = strcmp(property_path, "escape-non-printables") == 0;
184 LoadScriptFromSymFile load_script_old_value;
185 if (is_load_script && exe_ctx->GetTargetSP())
187 target_sp = exe_ctx->GetTargetSP();
188 load_script_old_value = target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
190 Error error (Properties::SetPropertyValue (exe_ctx, op, property_path, value));
193 // FIXME it would be nice to have "on-change" callbacks for properties
194 if (strcmp(property_path, g_properties[ePropertyPrompt].name) == 0)
196 const char *new_prompt = GetPrompt();
197 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
199 new_prompt = str.c_str();
200 GetCommandInterpreter().UpdatePrompt(new_prompt);
201 EventSP prompt_change_event_sp (new Event(CommandInterpreter::eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));
202 GetCommandInterpreter().BroadcastEvent (prompt_change_event_sp);
204 else if (strcmp(property_path, g_properties[ePropertyUseColor].name) == 0)
206 // use-color changed. Ping the prompt so it can reset the ansi terminal codes.
207 SetPrompt (GetPrompt());
209 else if (is_load_script && target_sp && load_script_old_value == eLoadScriptFromSymFileWarn)
211 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() == eLoadScriptFromSymFileTrue)
213 std::list<Error> errors;
214 StreamString feedback_stream;
215 if (!target_sp->LoadScriptingResources(errors,&feedback_stream))
217 StreamFileSP stream_sp (GetErrorFile());
220 for (auto error : errors)
222 stream_sp->Printf("%s\n",error.AsCString());
224 if (feedback_stream.GetSize())
225 stream_sp->Printf("%s",feedback_stream.GetData());
230 else if (is_escape_non_printables)
232 DataVisualization::ForceUpdate();
239 Debugger::GetAutoConfirm () const
241 const uint32_t idx = ePropertyAutoConfirm;
242 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
246 Debugger::GetDisassemblyFormat() const
248 const uint32_t idx = ePropertyDisassemblyFormat;
249 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
253 Debugger::GetFrameFormat() const
255 const uint32_t idx = ePropertyFrameFormat;
256 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
260 Debugger::GetNotifyVoid () const
262 const uint32_t idx = ePropertyNotiftVoid;
263 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
267 Debugger::GetPrompt() const
269 const uint32_t idx = ePropertyPrompt;
270 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
274 Debugger::SetPrompt(const char *p)
276 const uint32_t idx = ePropertyPrompt;
277 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
278 const char *new_prompt = GetPrompt();
279 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
281 new_prompt = str.c_str();
282 GetCommandInterpreter().UpdatePrompt(new_prompt);
286 Debugger::GetThreadFormat() const
288 const uint32_t idx = ePropertyThreadFormat;
289 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
293 Debugger::GetScriptLanguage() const
295 const uint32_t idx = ePropertyScriptLanguage;
296 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
300 Debugger::SetScriptLanguage (lldb::ScriptLanguage script_lang)
302 const uint32_t idx = ePropertyScriptLanguage;
303 return m_collection_sp->SetPropertyAtIndexAsEnumeration (NULL, idx, script_lang);
307 Debugger::GetTerminalWidth () const
309 const uint32_t idx = ePropertyTerminalWidth;
310 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
314 Debugger::SetTerminalWidth (uint32_t term_width)
316 const uint32_t idx = ePropertyTerminalWidth;
317 return m_collection_sp->SetPropertyAtIndexAsSInt64 (NULL, idx, term_width);
321 Debugger::GetUseExternalEditor () const
323 const uint32_t idx = ePropertyUseExternalEditor;
324 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
328 Debugger::SetUseExternalEditor (bool b)
330 const uint32_t idx = ePropertyUseExternalEditor;
331 return m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
335 Debugger::GetUseColor () const
337 const uint32_t idx = ePropertyUseColor;
338 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
342 Debugger::SetUseColor (bool b)
344 const uint32_t idx = ePropertyUseColor;
345 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
346 SetPrompt (GetPrompt());
351 Debugger::GetStopSourceLineCount (bool before) const
353 const uint32_t idx = before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
354 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
357 Debugger::StopDisassemblyType
358 Debugger::GetStopDisassemblyDisplay () const
360 const uint32_t idx = ePropertyStopDisassemblyDisplay;
361 return (Debugger::StopDisassemblyType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
365 Debugger::GetDisassemblyLineCount () const
367 const uint32_t idx = ePropertyStopDisassemblyCount;
368 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
372 Debugger::GetAutoOneLineSummaries () const
374 const uint32_t idx = ePropertyAutoOneLineSummaries;
375 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
379 Debugger::GetEscapeNonPrintables () const
381 const uint32_t idx = ePropertyEscapeNonPrintables;
382 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
385 #pragma mark Debugger
387 //const DebuggerPropertiesSP &
388 //Debugger::GetSettings() const
390 // return m_properties_sp;
395 Debugger::TestDebuggerRefCount ()
397 return g_shared_debugger_refcount;
401 Debugger::Initialize (LoadPluginCallbackType load_plugin_callback)
403 g_load_plugin_callback = load_plugin_callback;
404 if (g_shared_debugger_refcount++ == 0)
405 lldb_private::Initialize();
409 Debugger::Terminate ()
411 if (g_shared_debugger_refcount > 0)
413 g_shared_debugger_refcount--;
414 if (g_shared_debugger_refcount == 0)
416 lldb_private::WillTerminate();
417 lldb_private::Terminate();
419 // Clear our master list of debugger objects
420 Mutex::Locker locker (GetDebuggerListMutex ());
421 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 (g_shared_debugger_refcount > 0)
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 (g_shared_debugger_refcount > 0)
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 (g_shared_debugger_refcount > 0)
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 (g_shared_debugger_refcount > 0)
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 (g_shared_debugger_refcount > 0)
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 if (m_command_interpreter_ap.get())
687 m_collection_sp->AppendProperty (ConstString("interpreter"),
688 ConstString("Settings specify to the debugger's command interpreter."),
690 m_command_interpreter_ap->GetValueProperties());
692 OptionValueSInt64 *term_width = m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64 (NULL, ePropertyTerminalWidth);
693 term_width->SetMinimumValue(10);
694 term_width->SetMaximumValue(1024);
696 // Turn off use-color if this is a dumb terminal.
697 const char *term = getenv ("TERM");
698 if (term && !strcmp (term, "dumb"))
702 Debugger::~Debugger ()
711 StopIOHandlerThread();
712 StopEventHandlerThread();
714 int num_targets = m_target_list.GetNumTargets();
715 for (int i = 0; i < num_targets; i++)
717 TargetSP target_sp (m_target_list.GetTargetAtIndex (i));
720 ProcessSP process_sp (target_sp->GetProcessSP());
722 process_sp->Finalize();
723 target_sp->Destroy();
726 BroadcasterManager::Clear ();
728 // Close the input file _before_ we close the input read communications class
729 // as it does NOT own the input file, our m_input_file does.
730 m_terminal_state.Clear();
732 m_input_file_sp->GetFile().Close ();
734 m_command_interpreter_ap->Clear();
738 Debugger::GetCloseInputOnEOF () const
740 // return m_input_comm.GetCloseOnEOF();
745 Debugger::SetCloseInputOnEOF (bool b)
747 // m_input_comm.SetCloseOnEOF(b);
751 Debugger::GetAsyncExecution ()
753 return !m_command_interpreter_ap->GetSynchronous();
757 Debugger::SetAsyncExecution (bool async_execution)
759 m_command_interpreter_ap->SetSynchronous (!async_execution);
764 Debugger::SetInputFileHandle (FILE *fh, bool tranfer_ownership)
767 m_input_file_sp->GetFile().SetStream (fh, tranfer_ownership);
769 m_input_file_sp.reset (new StreamFile (fh, tranfer_ownership));
771 File &in_file = m_input_file_sp->GetFile();
772 if (in_file.IsValid() == false)
773 in_file.SetStream (stdin, true);
775 // Save away the terminal state if that is relevant, so that we can restore it in RestoreInputState.
776 SaveInputTerminalState ();
780 Debugger::SetOutputFileHandle (FILE *fh, bool tranfer_ownership)
782 if (m_output_file_sp)
783 m_output_file_sp->GetFile().SetStream (fh, tranfer_ownership);
785 m_output_file_sp.reset (new StreamFile (fh, tranfer_ownership));
787 File &out_file = m_output_file_sp->GetFile();
788 if (out_file.IsValid() == false)
789 out_file.SetStream (stdout, false);
791 // do not create the ScriptInterpreter just for setting the output file handle
792 // as the constructor will know how to do the right thing on its own
793 const bool can_create = false;
794 ScriptInterpreter* script_interpreter = GetCommandInterpreter().GetScriptInterpreter(can_create);
795 if (script_interpreter)
796 script_interpreter->ResetOutputFileHandle (fh);
800 Debugger::SetErrorFileHandle (FILE *fh, bool tranfer_ownership)
803 m_error_file_sp->GetFile().SetStream (fh, tranfer_ownership);
805 m_error_file_sp.reset (new StreamFile (fh, tranfer_ownership));
807 File &err_file = m_error_file_sp->GetFile();
808 if (err_file.IsValid() == false)
809 err_file.SetStream (stderr, false);
813 Debugger::SaveInputTerminalState ()
817 File &in_file = m_input_file_sp->GetFile();
818 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
819 m_terminal_state.Save(in_file.GetDescriptor(), true);
824 Debugger::RestoreInputTerminalState ()
826 m_terminal_state.Restore();
830 Debugger::GetSelectedExecutionContext ()
832 ExecutionContext exe_ctx;
833 TargetSP target_sp(GetSelectedTarget());
834 exe_ctx.SetTargetSP (target_sp);
838 ProcessSP process_sp (target_sp->GetProcessSP());
839 exe_ctx.SetProcessSP (process_sp);
840 if (process_sp && process_sp->IsRunning() == false)
842 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
845 exe_ctx.SetThreadSP (thread_sp);
846 exe_ctx.SetFrameSP (thread_sp->GetSelectedFrame());
847 if (exe_ctx.GetFramePtr() == NULL)
848 exe_ctx.SetFrameSP (thread_sp->GetStackFrameAtIndex (0));
856 Debugger::DispatchInputInterrupt ()
858 Mutex::Locker locker (m_input_reader_stack.GetMutex());
859 IOHandlerSP reader_sp (m_input_reader_stack.Top());
861 reader_sp->Interrupt();
865 Debugger::DispatchInputEndOfFile ()
867 Mutex::Locker locker (m_input_reader_stack.GetMutex());
868 IOHandlerSP reader_sp (m_input_reader_stack.Top());
874 Debugger::ClearIOHandlers ()
876 // The bottom input reader should be the main debugger input reader. We do not want to close that one here.
877 Mutex::Locker locker (m_input_reader_stack.GetMutex());
878 while (m_input_reader_stack.GetSize() > 1)
880 IOHandlerSP reader_sp (m_input_reader_stack.Top());
883 m_input_reader_stack.Pop();
884 reader_sp->SetIsDone(true);
891 Debugger::ExecuteIOHanders()
896 IOHandlerSP reader_sp(m_input_reader_stack.Top());
900 reader_sp->Activate();
902 reader_sp->Deactivate();
904 // Remove all input readers that are done from the top of the stack
907 IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
908 if (top_reader_sp && top_reader_sp->GetIsDone())
909 m_input_reader_stack.Pop();
918 Debugger::IsTopIOHandler (const lldb::IOHandlerSP& reader_sp)
920 return m_input_reader_stack.IsTop (reader_sp);
925 Debugger::GetTopIOHandlerControlSequence(char ch)
927 return m_input_reader_stack.GetTopIOHandlerControlSequence (ch);
931 Debugger::RunIOHandler (const IOHandlerSP& reader_sp)
933 PushIOHandler (reader_sp);
935 IOHandlerSP top_reader_sp = reader_sp;
936 while (top_reader_sp)
938 top_reader_sp->Activate();
939 top_reader_sp->Run();
940 top_reader_sp->Deactivate();
942 if (top_reader_sp.get() == reader_sp.get())
944 if (PopIOHandler (reader_sp))
950 top_reader_sp = m_input_reader_stack.Top();
951 if (top_reader_sp && top_reader_sp->GetIsDone())
952 m_input_reader_stack.Pop();
960 Debugger::AdoptTopIOHandlerFilesIfInvalid (StreamFileSP &in, StreamFileSP &out, StreamFileSP &err)
962 // Before an IOHandler runs, it must have in/out/err streams.
963 // This function is called when one ore more of the streams
964 // are NULL. We use the top input reader's in/out/err streams,
965 // or fall back to the debugger file handles, or we fall back
966 // onto stdin/stdout/stderr as a last resort.
968 Mutex::Locker locker (m_input_reader_stack.GetMutex());
969 IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
970 // If no STDIN has been set, then set it appropriately
974 in = top_reader_sp->GetInputStreamFile();
978 // If there is nothing, use stdin
980 in = StreamFileSP(new StreamFile(stdin, false));
982 // If no STDOUT has been set, then set it appropriately
986 out = top_reader_sp->GetOutputStreamFile();
988 out = GetOutputFile();
990 // If there is nothing, use stdout
992 out = StreamFileSP(new StreamFile(stdout, false));
994 // If no STDERR has been set, then set it appropriately
998 err = top_reader_sp->GetErrorStreamFile();
1000 err = GetErrorFile();
1002 // If there is nothing, use stderr
1004 err = StreamFileSP(new StreamFile(stdout, false));
1010 Debugger::PushIOHandler (const IOHandlerSP& reader_sp)
1015 // Got the current top input reader...
1016 IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
1018 // Don't push the same IO handler twice...
1019 if (reader_sp.get() != top_reader_sp.get())
1021 // Push our new input reader
1022 m_input_reader_stack.Push (reader_sp);
1024 // Interrupt the top input reader to it will exit its Run() function
1025 // and let this new input reader take over
1027 top_reader_sp->Deactivate();
1032 Debugger::PopIOHandler (const IOHandlerSP& pop_reader_sp)
1034 bool result = false;
1036 Mutex::Locker locker (m_input_reader_stack.GetMutex());
1038 // The reader on the stop of the stack is done, so let the next
1039 // read on the stack refresh its prompt and if there is one...
1040 if (!m_input_reader_stack.IsEmpty())
1042 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1044 if (!pop_reader_sp || pop_reader_sp.get() == reader_sp.get())
1046 reader_sp->Deactivate();
1047 reader_sp->Cancel();
1048 m_input_reader_stack.Pop ();
1050 reader_sp = m_input_reader_stack.Top();
1052 reader_sp->Activate();
1061 Debugger::HideTopIOHandler()
1063 Mutex::Locker locker;
1065 if (locker.TryLock(m_input_reader_stack.GetMutex()))
1067 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1076 Debugger::RefreshTopIOHandler()
1078 IOHandlerSP reader_sp(m_input_reader_stack.Top());
1080 reader_sp->Refresh();
1085 Debugger::GetAsyncOutputStream ()
1087 return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
1088 CommandInterpreter::eBroadcastBitAsynchronousOutputData));
1092 Debugger::GetAsyncErrorStream ()
1094 return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
1095 CommandInterpreter::eBroadcastBitAsynchronousErrorData));
1099 Debugger::GetNumDebuggers()
1101 if (g_shared_debugger_refcount > 0)
1103 Mutex::Locker locker (GetDebuggerListMutex ());
1104 return GetDebuggerList().size();
1110 Debugger::GetDebuggerAtIndex (size_t index)
1112 DebuggerSP debugger_sp;
1114 if (g_shared_debugger_refcount > 0)
1116 Mutex::Locker locker (GetDebuggerListMutex ());
1117 DebuggerList &debugger_list = GetDebuggerList();
1119 if (index < debugger_list.size())
1120 debugger_sp = debugger_list[index];
1127 Debugger::FindDebuggerWithID (lldb::user_id_t id)
1129 DebuggerSP debugger_sp;
1131 if (g_shared_debugger_refcount > 0)
1133 Mutex::Locker locker (GetDebuggerListMutex ());
1134 DebuggerList &debugger_list = GetDebuggerList();
1135 DebuggerList::iterator pos, end = debugger_list.end();
1136 for (pos = debugger_list.begin(); pos != end; ++pos)
1138 if ((*pos).get()->GetID() == id)
1150 TestPromptFormats (StackFrame *frame)
1156 const char *prompt_format =
1157 "{addr = '${addr}'\n}"
1158 "{addr-file-or-load = '${addr-file-or-load}'\n}"
1159 "{current-pc-arrow = '${current-pc-arrow}'\n}"
1160 "{process.id = '${process.id}'\n}"
1161 "{process.name = '${process.name}'\n}"
1162 "{process.file.basename = '${process.file.basename}'\n}"
1163 "{process.file.fullpath = '${process.file.fullpath}'\n}"
1164 "{thread.id = '${thread.id}'\n}"
1165 "{thread.index = '${thread.index}'\n}"
1166 "{thread.name = '${thread.name}'\n}"
1167 "{thread.queue = '${thread.queue}'\n}"
1168 "{thread.stop-reason = '${thread.stop-reason}'\n}"
1169 "{target.arch = '${target.arch}'\n}"
1170 "{module.file.basename = '${module.file.basename}'\n}"
1171 "{module.file.fullpath = '${module.file.fullpath}'\n}"
1172 "{file.basename = '${file.basename}'\n}"
1173 "{file.fullpath = '${file.fullpath}'\n}"
1174 "{frame.index = '${frame.index}'\n}"
1175 "{frame.pc = '${frame.pc}'\n}"
1176 "{frame.sp = '${frame.sp}'\n}"
1177 "{frame.fp = '${frame.fp}'\n}"
1178 "{frame.flags = '${frame.flags}'\n}"
1179 "{frame.reg.rdi = '${frame.reg.rdi}'\n}"
1180 "{frame.reg.rip = '${frame.reg.rip}'\n}"
1181 "{frame.reg.rsp = '${frame.reg.rsp}'\n}"
1182 "{frame.reg.rbp = '${frame.reg.rbp}'\n}"
1183 "{frame.reg.rflags = '${frame.reg.rflags}'\n}"
1184 "{frame.reg.xmm0 = '${frame.reg.xmm0}'\n}"
1185 "{frame.reg.carp = '${frame.reg.carp}'\n}"
1186 "{function.id = '${function.id}'\n}"
1187 "{function.changed = '${function.changed}'\n}"
1188 "{function.initial-function = '${function.initial-function}'\n}"
1189 "{function.name = '${function.name}'\n}"
1190 "{function.name-without-args = '${function.name-without-args}'\n}"
1191 "{function.name-with-args = '${function.name-with-args}'\n}"
1192 "{function.addr-offset = '${function.addr-offset}'\n}"
1193 "{function.concrete-only-addr-offset-no-padding = '${function.concrete-only-addr-offset-no-padding}'\n}"
1194 "{function.line-offset = '${function.line-offset}'\n}"
1195 "{function.pc-offset = '${function.pc-offset}'\n}"
1196 "{line.file.basename = '${line.file.basename}'\n}"
1197 "{line.file.fullpath = '${line.file.fullpath}'\n}"
1198 "{line.number = '${line.number}'\n}"
1199 "{line.start-addr = '${line.start-addr}'\n}"
1200 "{line.end-addr = '${line.end-addr}'\n}"
1203 SymbolContext sc (frame->GetSymbolContext(eSymbolContextEverything));
1204 ExecutionContext exe_ctx;
1205 frame->CalculateExecutionContext(exe_ctx);
1206 if (Debugger::FormatPrompt (prompt_format, &sc, &exe_ctx, &sc.line_entry.range.GetBaseAddress(), s))
1208 printf("%s\n", s.GetData());
1212 printf ("what we got: %s\n", s.GetData());
1218 ScanFormatDescriptor (const char* var_name_begin,
1219 const char* var_name_end,
1220 const char** var_name_final,
1221 const char** percent_position,
1222 Format* custom_format,
1223 ValueObject::ValueObjectRepresentationStyle* val_obj_display)
1225 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1226 *percent_position = ::strchr(var_name_begin,'%');
1227 if (!*percent_position || *percent_position > var_name_end)
1230 log->Printf("[ScanFormatDescriptor] no format descriptor in string, skipping");
1231 *var_name_final = var_name_end;
1235 *var_name_final = *percent_position;
1236 std::string format_name(*var_name_final+1, var_name_end-*var_name_final-1);
1238 log->Printf("[ScanFormatDescriptor] parsing %s as a format descriptor", format_name.c_str());
1239 if ( !FormatManager::GetFormatFromCString(format_name.c_str(),
1244 log->Printf("[ScanFormatDescriptor] %s is an unknown format", format_name.c_str());
1246 switch (format_name.front())
1248 case '@': // if this is an @ sign, print ObjC description
1249 *val_obj_display = ValueObject::eValueObjectRepresentationStyleLanguageSpecific;
1251 case 'V': // if this is a V, print the value using the default format
1252 *val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1254 case 'L': // if this is an L, print the location of the value
1255 *val_obj_display = ValueObject::eValueObjectRepresentationStyleLocation;
1257 case 'S': // if this is an S, print the summary after all
1258 *val_obj_display = ValueObject::eValueObjectRepresentationStyleSummary;
1260 case '#': // if this is a '#', print the number of children
1261 *val_obj_display = ValueObject::eValueObjectRepresentationStyleChildrenCount;
1263 case 'T': // if this is a 'T', print the type
1264 *val_obj_display = ValueObject::eValueObjectRepresentationStyleType;
1266 case 'N': // if this is a 'N', print the name
1267 *val_obj_display = ValueObject::eValueObjectRepresentationStyleName;
1269 case '>': // if this is a '>', print the name
1270 *val_obj_display = ValueObject::eValueObjectRepresentationStyleExpressionPath;
1274 log->Printf("ScanFormatDescriptor] %s is an error, leaving the previous value alone", format_name.c_str());
1278 // a good custom format tells us to print the value using it
1282 log->Printf("[ScanFormatDescriptor] will display value for this VO");
1283 *val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1287 log->Printf("[ScanFormatDescriptor] final format description outcome: custom_format = %d, val_obj_display = %d",
1294 ScanBracketedRange (const char* var_name_begin,
1295 const char* var_name_end,
1296 const char* var_name_final,
1297 const char** open_bracket_position,
1298 const char** separator_position,
1299 const char** close_bracket_position,
1300 const char** var_name_final_if_array_range,
1301 int64_t* index_lower,
1302 int64_t* index_higher)
1304 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1305 *open_bracket_position = ::strchr(var_name_begin,'[');
1306 if (*open_bracket_position && *open_bracket_position < var_name_final)
1308 *separator_position = ::strchr(*open_bracket_position,'-'); // might be NULL if this is a simple var[N] bitfield
1309 *close_bracket_position = ::strchr(*open_bracket_position,']');
1310 // as usual, we assume that [] will come before %
1311 //printf("trying to expand a []\n");
1312 *var_name_final_if_array_range = *open_bracket_position;
1313 if (*close_bracket_position - *open_bracket_position == 1)
1316 log->Printf("[ScanBracketedRange] '[]' detected.. going from 0 to end of data");
1319 else if (*separator_position == NULL || *separator_position > var_name_end)
1322 *index_lower = ::strtoul (*open_bracket_position+1, &end, 0);
1323 *index_higher = *index_lower;
1325 log->Printf("[ScanBracketedRange] [%" PRId64 "] detected, high index is same", *index_lower);
1327 else if (*close_bracket_position && *close_bracket_position < var_name_end)
1330 *index_lower = ::strtoul (*open_bracket_position+1, &end, 0);
1331 *index_higher = ::strtoul (*separator_position+1, &end, 0);
1333 log->Printf("[ScanBracketedRange] [%" PRId64 "-%" PRId64 "] detected", *index_lower, *index_higher);
1338 log->Printf("[ScanBracketedRange] expression is erroneous, cannot extract indices out of it");
1341 if (*index_lower > *index_higher && *index_higher > 0)
1344 log->Printf("[ScanBracketedRange] swapping indices");
1345 int64_t temp = *index_lower;
1346 *index_lower = *index_higher;
1347 *index_higher = temp;
1351 log->Printf("[ScanBracketedRange] no bracketed range, skipping entirely");
1355 template <typename T>
1356 static bool RunScriptFormatKeyword(Stream &s, ScriptInterpreter *script_interpreter, T t, const std::string& script_name)
1358 if (script_interpreter)
1361 std::string script_output;
1363 if (script_interpreter->RunScriptFormatKeyword(script_name.c_str(), t, script_output, script_error) && script_error.Success())
1365 s.Printf("%s", script_output.c_str());
1370 s.Printf("<error: %s>",script_error.AsCString());
1376 static ValueObjectSP
1377 ExpandIndexedExpression (ValueObject* valobj,
1382 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1383 const char* ptr_deref_format = "[%d]";
1384 std::string ptr_deref_buffer(10,0);
1385 ::sprintf(&ptr_deref_buffer[0], ptr_deref_format, index);
1387 log->Printf("[ExpandIndexedExpression] name to deref: %s",ptr_deref_buffer.c_str());
1388 const char* first_unparsed;
1389 ValueObject::GetValueForExpressionPathOptions options;
1390 ValueObject::ExpressionPathEndResultType final_value_type;
1391 ValueObject::ExpressionPathScanEndReason reason_to_stop;
1392 ValueObject::ExpressionPathAftermath what_next = (deref_pointer ? ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
1393 ValueObjectSP item = valobj->GetValueForExpressionPath (ptr_deref_buffer.c_str(),
1402 log->Printf("[ExpandIndexedExpression] ERROR: unparsed portion = %s, why stopping = %d,"
1403 " final_value_type %d",
1404 first_unparsed, reason_to_stop, final_value_type);
1409 log->Printf("[ExpandIndexedExpression] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
1410 " final_value_type %d",
1411 first_unparsed, reason_to_stop, final_value_type);
1417 IsToken(const char *var_name_begin, const char *var)
1419 return (::strncmp (var_name_begin, var, strlen(var)) == 0);
1423 IsTokenWithFormat(const char *var_name_begin, const char *var, std::string &format, const char *default_format,
1424 const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
1426 int var_len = strlen(var);
1427 if (::strncmp (var_name_begin, var, var_len) == 0)
1429 var_name_begin += var_len;
1430 if (*var_name_begin == '}')
1432 format = default_format;
1435 else if (*var_name_begin == '%')
1437 // Allow format specifiers: x|X|u with optional width specifiers.
1438 // ${thread.id%x} ; hex
1439 // ${thread.id%X} ; uppercase hex
1440 // ${thread.id%u} ; unsigned decimal
1441 // ${thread.id%8.8X} ; width.precision + specifier
1442 // ${thread.id%tid} ; unsigned on FreeBSD/Linux, otherwise default_format (0x%4.4x for thread.id)
1444 const char *specifier = NULL;
1445 int width_precision_length = 0;
1446 const char *width_precision = ++var_name_begin;
1447 while (isdigit(*var_name_begin) || *var_name_begin == '.')
1449 dot_count += (*var_name_begin == '.');
1453 width_precision_length++;
1456 if (IsToken (var_name_begin, "tid}"))
1458 Target *target = Target::GetTargetFromContexts (exe_ctx_ptr, sc_ptr);
1461 ArchSpec arch (target->GetArchitecture ());
1462 llvm::Triple::OSType ostype = arch.IsValid() ? arch.GetTriple().getOS() : llvm::Triple::UnknownOS;
1463 if ((ostype == llvm::Triple::FreeBSD) || (ostype == llvm::Triple::Linux))
1468 format = default_format;
1472 else if (IsToken (var_name_begin, "x}"))
1474 else if (IsToken (var_name_begin, "X}"))
1476 else if (IsToken (var_name_begin, "u}"))
1482 if (width_precision_length)
1483 format += std::string(width_precision, width_precision_length);
1484 format += specifier;
1492 // Find information for the "thread.info.*" specifiers in a format string
1494 FormatThreadExtendedInfoRecurse
1496 const char *var_name_begin,
1497 StructuredData::ObjectSP thread_info_dictionary,
1498 const SymbolContext *sc,
1499 const ExecutionContext *exe_ctx,
1503 bool var_success = false;
1504 std::string token_format;
1506 llvm::StringRef var_name(var_name_begin);
1507 size_t percent_idx = var_name.find('%');
1508 size_t close_curly_idx = var_name.find('}');
1509 llvm::StringRef path = var_name;
1510 llvm::StringRef formatter = var_name;
1512 // 'path' will be the dot separated list of objects to transverse up until we hit
1513 // a close curly brace, a percent sign, or an end of string.
1514 if (percent_idx != llvm::StringRef::npos || close_curly_idx != llvm::StringRef::npos)
1516 if (percent_idx != llvm::StringRef::npos && close_curly_idx != llvm::StringRef::npos)
1518 if (percent_idx < close_curly_idx)
1520 path = var_name.slice(0, percent_idx);
1521 formatter = var_name.substr (percent_idx);
1525 path = var_name.slice(0, close_curly_idx);
1526 formatter = var_name.substr (close_curly_idx);
1529 else if (percent_idx != llvm::StringRef::npos)
1531 path = var_name.slice(0, percent_idx);
1532 formatter = var_name.substr (percent_idx);
1534 else if (close_curly_idx != llvm::StringRef::npos)
1536 path = var_name.slice(0, close_curly_idx);
1537 formatter = var_name.substr (close_curly_idx);
1541 StructuredData::ObjectSP value = thread_info_dictionary->GetObjectForDotSeparatedPath (path);
1545 if (value->GetType() == StructuredData::Type::eTypeInteger)
1547 if (IsTokenWithFormat (formatter.str().c_str(), "", token_format, "0x%4.4" PRIx64, exe_ctx, sc))
1549 s.Printf(token_format.c_str(), value->GetAsInteger()->GetValue());
1553 else if (value->GetType() == StructuredData::Type::eTypeFloat)
1555 s.Printf ("%f", value->GetAsFloat()->GetValue());
1558 else if (value->GetType() == StructuredData::Type::eTypeString)
1560 s.Printf("%s", value->GetAsString()->GetValue().c_str());
1563 else if (value->GetType() == StructuredData::Type::eTypeArray)
1565 if (value->GetAsArray()->GetSize() > 0)
1567 s.Printf ("%zu", value->GetAsArray()->GetSize());
1571 else if (value->GetType() == StructuredData::Type::eTypeDictionary)
1573 s.Printf ("%zu", value->GetAsDictionary()->GetKeys()->GetAsArray()->GetSize());
1586 const SymbolContext *sc,
1587 const ExecutionContext *exe_ctx,
1588 const Address *addr,
1591 ValueObject* valobj,
1592 bool function_changed,
1593 bool initial_function
1596 ValueObject* realvalobj = NULL; // makes it super-easy to parse pointers
1597 bool success = true;
1599 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1601 for (p = format; *p != '\0'; ++p)
1605 valobj = realvalobj;
1608 size_t non_special_chars = ::strcspn (p, "${}\\");
1609 if (non_special_chars > 0)
1612 s.Write (p, non_special_chars);
1613 p += non_special_chars;
1622 // Start a new scope that must have everything it needs if it is to
1623 // to make it into the final output stream "s". If you want to make
1624 // a format that only prints out the function or symbol name if there
1625 // is one in the symbol context you can use:
1626 // "{function =${function.name}}"
1627 // The first '{' starts a new scope that end with the matching '}' at
1628 // the end of the string. The contents "function =${function.name}"
1629 // will then be evaluated and only be output if there is a function
1630 // or symbol with a valid name.
1631 StreamString sub_strm;
1633 ++p; // Skip the '{'
1635 if (FormatPromptRecurse (p, sc, exe_ctx, addr, sub_strm, &p, valobj, function_changed, initial_function))
1637 // The stream had all it needed
1638 s.Write(sub_strm.GetData(), sub_strm.GetSize());
1648 // End of a enclosing scope
1653 // We have a prompt variable to print
1658 const char *var_name_begin = p;
1659 const char *var_name_end = ::strchr (p, '}');
1661 if (var_name_end && var_name_begin < var_name_end)
1663 // if we have already failed to parse, skip this variable
1666 const char *cstr = NULL;
1667 std::string token_format;
1668 Address format_addr;
1670 // normally "addr" means print a raw address but
1671 // "file-addr-or-load-addr" means print a module + file addr if there's no load addr
1672 bool print_file_addr_or_load_addr = false;
1673 bool addr_offset_concrete_func_only = false;
1674 bool addr_offset_print_with_no_padding = false;
1675 bool calculate_format_addr_function_offset = false;
1676 // Set reg_kind and reg_num to invalid values
1677 RegisterKind reg_kind = kNumRegisterKinds;
1678 uint32_t reg_num = LLDB_INVALID_REGNUM;
1679 FileSpec format_file_spec;
1680 const RegisterInfo *reg_info = NULL;
1681 RegisterContext *reg_ctx = NULL;
1682 bool do_deref_pointer = false;
1683 ValueObject::ExpressionPathScanEndReason reason_to_stop = ValueObject::eExpressionPathScanEndReasonEndOfString;
1684 ValueObject::ExpressionPathEndResultType final_value_type = ValueObject::eExpressionPathEndResultTypePlain;
1686 // Each variable must set success to true below...
1687 bool var_success = false;
1688 switch (var_name_begin[0])
1698 log->Printf("[Debugger::FormatPrompt] initial string: %s",var_name_begin);
1700 // check for *var and *svar
1701 if (*var_name_begin == '*')
1703 do_deref_pointer = true;
1706 log->Printf("[Debugger::FormatPrompt] found a deref, new string is: %s",var_name_begin);
1709 if (*var_name_begin == 's')
1711 if (!valobj->IsSynthetic())
1712 valobj = valobj->GetSyntheticValue().get();
1717 log->Printf("[Debugger::FormatPrompt] found a synthetic, new string is: %s",var_name_begin);
1720 // should be a 'v' by now
1721 if (*var_name_begin != 'v')
1725 log->Printf("[Debugger::FormatPrompt] string I am working with: %s",var_name_begin);
1727 ValueObject::ExpressionPathAftermath what_next = (do_deref_pointer ?
1728 ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
1729 ValueObject::GetValueForExpressionPathOptions options;
1730 options.DontCheckDotVsArrowSyntax().DoAllowBitfieldSyntax().DoAllowFragileIVar().DoAllowSyntheticChildren();
1731 ValueObject::ValueObjectRepresentationStyle val_obj_display = ValueObject::eValueObjectRepresentationStyleSummary;
1732 ValueObject* target = NULL;
1733 Format custom_format = eFormatInvalid;
1734 const char* var_name_final = NULL;
1735 const char* var_name_final_if_array_range = NULL;
1736 const char* close_bracket_position = NULL;
1737 int64_t index_lower = -1;
1738 int64_t index_higher = -1;
1739 bool is_array_range = false;
1740 const char* first_unparsed;
1741 bool was_plain_var = false;
1742 bool was_var_format = false;
1743 bool was_var_indexed = false;
1746 // simplest case ${var}, just print valobj's value
1747 if (IsToken (var_name_begin, "var}"))
1749 was_plain_var = true;
1751 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1753 else if (IsToken (var_name_begin, "var.script:"))
1755 var_name_begin += ::strlen("var.script:");
1756 std::string script_name(var_name_begin,var_name_end);
1757 ScriptInterpreter* script_interpreter = valobj->GetTargetSP()->GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
1758 if (RunScriptFormatKeyword (s, script_interpreter, valobj, script_name))
1762 else if (IsToken (var_name_begin,"var%"))
1764 was_var_format = true;
1765 // this is a variable with some custom format applied to it
1766 const char* percent_position;
1768 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1769 ScanFormatDescriptor (var_name_begin,
1776 // this is ${var.something} or multiple .something nested
1777 else if (IsToken (var_name_begin, "var"))
1779 if (IsToken (var_name_begin, "var["))
1780 was_var_indexed = true;
1781 const char* percent_position;
1782 ScanFormatDescriptor (var_name_begin,
1789 const char* open_bracket_position;
1790 const char* separator_position;
1791 ScanBracketedRange (var_name_begin,
1794 &open_bracket_position,
1795 &separator_position,
1796 &close_bracket_position,
1797 &var_name_final_if_array_range,
1803 std::string expr_path(var_name_final-var_name_begin-1,0);
1804 memcpy(&expr_path[0], var_name_begin+3,var_name_final-var_name_begin-3);
1807 log->Printf("[Debugger::FormatPrompt] symbol to expand: %s",expr_path.c_str());
1809 target = valobj->GetValueForExpressionPath(expr_path.c_str(),
1819 log->Printf("[Debugger::FormatPrompt] ERROR: unparsed portion = %s, why stopping = %d,"
1820 " final_value_type %d",
1821 first_unparsed, reason_to_stop, final_value_type);
1827 log->Printf("[Debugger::FormatPrompt] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
1828 " final_value_type %d",
1829 first_unparsed, reason_to_stop, final_value_type);
1830 target = target->GetQualifiedRepresentationIfAvailable(target->GetDynamicValueType(), true).get();
1836 is_array_range = (final_value_type == ValueObject::eExpressionPathEndResultTypeBoundedRange ||
1837 final_value_type == ValueObject::eExpressionPathEndResultTypeUnboundedRange);
1839 do_deref_pointer = (what_next == ValueObject::eExpressionPathAftermathDereference);
1841 if (do_deref_pointer && !is_array_range)
1843 // I have not deref-ed yet, let's do it
1844 // this happens when we are not going through GetValueForVariableExpressionPath
1845 // to get to the target ValueObject
1847 target = target->Dereference(error).get();
1851 log->Printf("[Debugger::FormatPrompt] ERROR: %s\n", error.AsCString("unknown")); \
1854 do_deref_pointer = false;
1860 log->Printf("[Debugger::FormatPrompt] could not calculate target for prompt expression");
1864 // we do not want to use the summary for a bitfield of type T:n
1865 // if we were originally dealing with just a T - that would get
1866 // us into an endless recursion
1867 if (target->IsBitfield() && was_var_indexed)
1869 // TODO: check for a (T:n)-specific summary - we should still obey that
1870 StreamString bitfield_name;
1871 bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(), target->GetBitfieldBitSize());
1872 lldb::TypeNameSpecifierImplSP type_sp(new TypeNameSpecifierImpl(bitfield_name.GetData(),false));
1873 if (!DataVisualization::GetSummaryForType(type_sp))
1874 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1877 // TODO use flags for these
1878 const uint32_t type_info_flags = target->GetClangType().GetTypeInfo(NULL);
1879 bool is_array = (type_info_flags & eTypeIsArray) != 0;
1880 bool is_pointer = (type_info_flags & eTypeIsPointer) != 0;
1881 bool is_aggregate = target->GetClangType().IsAggregateType();
1883 if ((is_array || is_pointer) && (!is_array_range) && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue) // this should be wrong, but there are some exceptions
1885 StreamString str_temp;
1887 log->Printf("[Debugger::FormatPrompt] I am into array || pointer && !range");
1889 if (target->HasSpecialPrintableRepresentation(val_obj_display, custom_format))
1891 // try to use the special cases
1892 var_success = target->DumpPrintableRepresentation(str_temp,
1896 log->Printf("[Debugger::FormatPrompt] special cases did%s match", var_success ? "" : "n't");
1898 // should not happen
1900 s << str_temp.GetData();
1906 if (was_plain_var) // if ${var}
1908 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
1910 else if (is_pointer) // if pointer, value is the address stored
1912 target->DumpPrintableRepresentation (s,
1915 ValueObject::ePrintableRepresentationSpecialCasesDisable);
1922 // if directly trying to print ${var}, and this is an aggregate, display a nice
1923 // type @ location message
1924 if (is_aggregate && was_plain_var)
1926 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
1931 // if directly trying to print ${var%V}, and this is an aggregate, do not let the user do it
1932 if (is_aggregate && ((was_var_format && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue)))
1934 s << "<invalid use of aggregate type>";
1939 if (!is_array_range)
1942 log->Printf("[Debugger::FormatPrompt] dumping ordinary printable output");
1943 var_success = target->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1948 log->Printf("[Debugger::FormatPrompt] checking if I can handle as array");
1949 if (!is_array && !is_pointer)
1952 log->Printf("[Debugger::FormatPrompt] handle as array");
1953 const char* special_directions = NULL;
1954 StreamString special_directions_writer;
1955 if (close_bracket_position && (var_name_end-close_bracket_position > 1))
1957 ConstString additional_data;
1958 additional_data.SetCStringWithLength(close_bracket_position+1, var_name_end-close_bracket_position-1);
1959 special_directions_writer.Printf("${%svar%s}",
1960 do_deref_pointer ? "*" : "",
1961 additional_data.GetCString());
1962 special_directions = special_directions_writer.GetData();
1965 // let us display items index_lower thru index_higher of this array
1969 if (index_higher < 0)
1970 index_higher = valobj->GetNumChildren() - 1;
1972 uint32_t max_num_children = target->GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();
1974 for (;index_lower<=index_higher;index_lower++)
1976 ValueObject* item = ExpandIndexedExpression (target,
1978 exe_ctx->GetFramePtr(),
1984 log->Printf("[Debugger::FormatPrompt] ERROR in getting child item at index %" PRId64, index_lower);
1989 log->Printf("[Debugger::FormatPrompt] special_directions for child item: %s",special_directions);
1992 if (!special_directions)
1993 var_success &= item->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1995 var_success &= FormatPromptRecurse(special_directions, sc, exe_ctx, addr, s, NULL, item, function_changed, initial_function);
1997 if (--max_num_children == 0)
1999 s.PutCString(", ...");
2003 if (index_lower < index_higher)
2011 if (IsToken (var_name_begin, "addr-file-or-load}"))
2013 print_file_addr_or_load_addr = true;
2015 if (IsToken (var_name_begin, "addr}")
2016 || IsToken (var_name_begin, "addr-file-or-load}"))
2018 if (addr && addr->IsValid())
2021 format_addr = *addr;
2027 if (IsToken (var_name_begin, "process."))
2031 Process *process = exe_ctx->GetProcessPtr();
2034 var_name_begin += ::strlen ("process.");
2035 if (IsTokenWithFormat (var_name_begin, "id", token_format, "%" PRIu64, exe_ctx, sc))
2037 s.Printf(token_format.c_str(), process->GetID());
2040 else if ((IsToken (var_name_begin, "name}")) ||
2041 (IsToken (var_name_begin, "file.basename}")) ||
2042 (IsToken (var_name_begin, "file.fullpath}")))
2044 Module *exe_module = process->GetTarget().GetExecutableModulePointer();
2047 if (var_name_begin[0] == 'n' || var_name_begin[5] == 'f')
2049 format_file_spec.GetFilename() = exe_module->GetFileSpec().GetFilename();
2050 var_success = (bool)format_file_spec;
2054 format_file_spec = exe_module->GetFileSpec();
2055 var_success = (bool)format_file_spec;
2059 else if (IsToken (var_name_begin, "script:"))
2061 var_name_begin += ::strlen("script:");
2062 std::string script_name(var_name_begin,var_name_end);
2063 ScriptInterpreter* script_interpreter = process->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
2064 if (RunScriptFormatKeyword (s, script_interpreter, process, script_name))
2073 if (IsToken (var_name_begin, "thread."))
2077 Thread *thread = exe_ctx->GetThreadPtr();
2080 var_name_begin += ::strlen ("thread.");
2081 if (IsTokenWithFormat (var_name_begin, "id", token_format, "0x%4.4" PRIx64, exe_ctx, sc))
2083 s.Printf(token_format.c_str(), thread->GetID());
2086 else if (IsTokenWithFormat (var_name_begin, "protocol_id", token_format, "0x%4.4" PRIx64, exe_ctx, sc))
2088 s.Printf(token_format.c_str(), thread->GetProtocolID());
2091 else if (IsTokenWithFormat (var_name_begin, "index", token_format, "%" PRIu64, exe_ctx, sc))
2093 s.Printf(token_format.c_str(), (uint64_t)thread->GetIndexID());
2096 else if (IsToken (var_name_begin, "name}"))
2098 cstr = thread->GetName();
2099 var_success = cstr && cstr[0];
2103 else if (IsToken (var_name_begin, "queue}"))
2105 cstr = thread->GetQueueName();
2106 var_success = cstr && cstr[0];
2110 else if (IsToken (var_name_begin, "stop-reason}"))
2112 StopInfoSP stop_info_sp = thread->GetStopInfo ();
2113 if (stop_info_sp && stop_info_sp->IsValid())
2115 cstr = stop_info_sp->GetDescription();
2116 if (cstr && cstr[0])
2123 else if (IsToken (var_name_begin, "return-value}"))
2125 StopInfoSP stop_info_sp = thread->GetStopInfo ();
2126 if (stop_info_sp && stop_info_sp->IsValid())
2128 ValueObjectSP return_valobj_sp = StopInfo::GetReturnValueObject (stop_info_sp);
2129 if (return_valobj_sp)
2131 return_valobj_sp->Dump(s);
2136 else if (IsToken (var_name_begin, "completed-expression}"))
2138 StopInfoSP stop_info_sp = thread->GetStopInfo ();
2139 if (stop_info_sp && stop_info_sp->IsValid())
2141 ClangExpressionVariableSP expression_var_sp = StopInfo::GetExpressionVariable (stop_info_sp);
2142 if (expression_var_sp && expression_var_sp->GetValueObject())
2144 expression_var_sp->GetValueObject()->Dump(s);
2149 else if (IsToken (var_name_begin, "script:"))
2151 var_name_begin += ::strlen("script:");
2152 std::string script_name(var_name_begin,var_name_end);
2153 ScriptInterpreter* script_interpreter = thread->GetProcess()->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
2154 if (RunScriptFormatKeyword (s, script_interpreter, thread, script_name))
2157 else if (IsToken (var_name_begin, "info."))
2159 var_name_begin += ::strlen("info.");
2160 StructuredData::ObjectSP object_sp = thread->GetExtendedInfo();
2161 if (object_sp && object_sp->GetType() == StructuredData::Type::eTypeDictionary)
2163 var_success = FormatThreadExtendedInfoRecurse (var_name_begin, object_sp, sc, exe_ctx, s);
2169 else if (IsToken (var_name_begin, "target."))
2171 // TODO: hookup properties
2172 // if (!target_properties_sp)
2174 // Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2176 // target_properties_sp = target->GetProperties();
2179 // if (target_properties_sp)
2181 // var_name_begin += ::strlen ("target.");
2182 // const char *end_property = strchr(var_name_begin, '}');
2183 // if (end_property)
2185 // ConstString property_name(var_name_begin, end_property - var_name_begin);
2186 // std::string property_value (target_properties_sp->GetPropertyValue(property_name));
2187 // if (!property_value.empty())
2189 // s.PutCString (property_value.c_str());
2190 // var_success = true;
2194 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2197 var_name_begin += ::strlen ("target.");
2198 if (IsToken (var_name_begin, "arch}"))
2200 ArchSpec arch (target->GetArchitecture ());
2203 s.PutCString (arch.GetArchitectureName());
2207 else if (IsToken (var_name_begin, "script:"))
2209 var_name_begin += ::strlen("script:");
2210 std::string script_name(var_name_begin,var_name_end);
2211 ScriptInterpreter* script_interpreter = target->GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
2212 if (RunScriptFormatKeyword (s, script_interpreter, target, script_name))
2220 if (IsToken (var_name_begin, "module."))
2222 if (sc && sc->module_sp.get())
2224 Module *module = sc->module_sp.get();
2225 var_name_begin += ::strlen ("module.");
2227 if (IsToken (var_name_begin, "file."))
2229 if (module->GetFileSpec())
2231 var_name_begin += ::strlen ("file.");
2233 if (IsToken (var_name_begin, "basename}"))
2235 format_file_spec.GetFilename() = module->GetFileSpec().GetFilename();
2236 var_success = (bool)format_file_spec;
2238 else if (IsToken (var_name_begin, "fullpath}"))
2240 format_file_spec = module->GetFileSpec();
2241 var_success = (bool)format_file_spec;
2251 if (IsToken (var_name_begin, "file."))
2253 if (sc && sc->comp_unit != NULL)
2255 var_name_begin += ::strlen ("file.");
2257 if (IsToken (var_name_begin, "basename}"))
2259 format_file_spec.GetFilename() = sc->comp_unit->GetFilename();
2260 var_success = (bool)format_file_spec;
2262 else if (IsToken (var_name_begin, "fullpath}"))
2264 format_file_spec = *sc->comp_unit;
2265 var_success = (bool)format_file_spec;
2269 else if (IsToken (var_name_begin, "frame."))
2273 StackFrame *frame = exe_ctx->GetFramePtr();
2276 var_name_begin += ::strlen ("frame.");
2277 if (IsToken (var_name_begin, "index}"))
2279 s.Printf("%u", frame->GetFrameIndex());
2282 else if (IsToken (var_name_begin, "pc}"))
2284 reg_kind = eRegisterKindGeneric;
2285 reg_num = LLDB_REGNUM_GENERIC_PC;
2288 else if (IsToken (var_name_begin, "sp}"))
2290 reg_kind = eRegisterKindGeneric;
2291 reg_num = LLDB_REGNUM_GENERIC_SP;
2294 else if (IsToken (var_name_begin, "fp}"))
2296 reg_kind = eRegisterKindGeneric;
2297 reg_num = LLDB_REGNUM_GENERIC_FP;
2300 else if (IsToken (var_name_begin, "flags}"))
2302 reg_kind = eRegisterKindGeneric;
2303 reg_num = LLDB_REGNUM_GENERIC_FLAGS;
2306 else if (IsToken (var_name_begin, "reg."))
2308 reg_ctx = frame->GetRegisterContext().get();
2311 var_name_begin += ::strlen ("reg.");
2312 if (var_name_begin < var_name_end)
2314 std::string reg_name (var_name_begin, var_name_end);
2315 reg_info = reg_ctx->GetRegisterInfoByName (reg_name.c_str());
2321 else if (IsToken (var_name_begin, "script:"))
2323 var_name_begin += ::strlen("script:");
2324 std::string script_name(var_name_begin,var_name_end);
2325 ScriptInterpreter* script_interpreter = frame->GetThread()->GetProcess()->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
2326 if (RunScriptFormatKeyword (s, script_interpreter, frame, script_name))
2332 else if (IsToken (var_name_begin, "function."))
2334 if (sc && (sc->function != NULL || sc->symbol != NULL))
2336 var_name_begin += ::strlen ("function.");
2337 if (IsToken (var_name_begin, "id}"))
2340 s.Printf("function{0x%8.8" PRIx64 "}", sc->function->GetID());
2342 s.Printf("symbol[%u]", sc->symbol->GetID());
2346 if (IsToken (var_name_begin, "changed}") && function_changed)
2350 if (IsToken (var_name_begin, "initial-function}") && initial_function)
2354 else if (IsToken (var_name_begin, "name}"))
2357 cstr = sc->function->GetName().AsCString (NULL);
2358 else if (sc->symbol)
2359 cstr = sc->symbol->GetName().AsCString (NULL);
2366 Block *inline_block = sc->block->GetContainingInlinedBlock ();
2369 const InlineFunctionInfo *inline_info = sc->block->GetInlinedFunctionInfo();
2372 s.PutCString(" [inlined] ");
2373 inline_info->GetName().Dump(&s);
2380 else if (IsToken (var_name_begin, "name-without-args}"))
2384 name = sc->function->GetMangled().GetName (Mangled::ePreferDemangledWithoutArguments);
2385 else if (sc->symbol)
2386 name = sc->symbol->GetMangled().GetName (Mangled::ePreferDemangledWithoutArguments);
2389 s.PutCString(name.GetCString());
2393 else if (IsToken (var_name_begin, "name-with-args}"))
2395 // Print the function name with arguments in it
2400 ExecutionContextScope *exe_scope = exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL;
2401 cstr = sc->function->GetName().AsCString (NULL);
2404 const InlineFunctionInfo *inline_info = NULL;
2405 VariableListSP variable_list_sp;
2406 bool get_function_vars = true;
2409 Block *inline_block = sc->block->GetContainingInlinedBlock ();
2413 get_function_vars = false;
2414 inline_info = sc->block->GetInlinedFunctionInfo();
2416 variable_list_sp = inline_block->GetBlockVariableList (true);
2420 if (get_function_vars)
2422 variable_list_sp = sc->function->GetBlock(true).GetBlockVariableList (true);
2427 s.PutCString (cstr);
2428 s.PutCString (" [inlined] ");
2429 cstr = inline_info->GetName().GetCString();
2433 if (variable_list_sp)
2434 variable_list_sp->AppendVariablesWithScope(eValueTypeVariableArgument, args);
2435 if (args.GetSize() > 0)
2437 const char *open_paren = strchr (cstr, '(');
2438 const char *close_paren = nullptr;
2439 const char *generic = strchr(cstr, '<');
2440 // if before the arguments list begins there is a template sign
2441 // then scan to the end of the generic args before you try to find
2442 // the arguments list
2443 if (generic && open_paren && generic < open_paren)
2445 int generic_depth = 1;
2448 *generic && generic_depth > 0;
2451 if (*generic == '<')
2453 if (*generic == '>')
2457 open_paren = strchr(generic, '(');
2459 open_paren = nullptr;
2463 if (IsToken (open_paren, "(anonymous namespace)"))
2465 open_paren = strchr (open_paren + strlen("(anonymous namespace)"), '(');
2467 close_paren = strchr (open_paren, ')');
2470 close_paren = strchr (open_paren, ')');
2474 s.Write(cstr, open_paren - cstr + 1);
2477 s.PutCString (cstr);
2480 const size_t num_args = args.GetSize();
2481 for (size_t arg_idx = 0; arg_idx < num_args; ++arg_idx)
2485 VariableSP var_sp (args.GetVariableAtIndex (arg_idx));
2486 ValueObjectSP var_value_sp (ValueObjectVariable::Create (exe_scope, var_sp));
2487 const char *var_representation = nullptr;
2488 const char *var_name = var_value_sp->GetName().GetCString();
2489 if (var_value_sp->GetClangType().IsAggregateType() &&
2490 DataVisualization::ShouldPrintAsOneLiner(*var_value_sp.get()))
2492 static StringSummaryFormat format(TypeSummaryImpl::Flags()
2493 .SetHideItemNames(false)
2494 .SetShowMembersOneLiner(true),
2496 format.FormatObject(var_value_sp.get(), buffer, TypeSummaryOptions());
2497 var_representation = buffer.c_str();
2500 var_representation = var_value_sp->GetValueAsCString();
2502 s.PutCString (", ");
2503 if (var_value_sp->GetError().Success())
2505 if (var_representation)
2506 s.Printf ("%s=%s", var_name, var_representation);
2508 s.Printf ("%s=%s at %s", var_name, var_value_sp->GetTypeName().GetCString(), var_value_sp->GetLocationAsCString());
2511 s.Printf ("%s=<unavailable>", var_name);
2515 s.PutCString (close_paren);
2526 else if (sc->symbol)
2528 cstr = sc->symbol->GetName().AsCString (NULL);
2536 else if (IsToken (var_name_begin, "addr-offset}")
2537 || IsToken (var_name_begin, "concrete-only-addr-offset-no-padding}"))
2539 if (IsToken (var_name_begin, "concrete-only-addr-offset-no-padding}"))
2541 addr_offset_print_with_no_padding = true;
2542 addr_offset_concrete_func_only = true;
2544 var_success = addr != NULL;
2547 format_addr = *addr;
2548 calculate_format_addr_function_offset = true;
2551 else if (IsToken (var_name_begin, "line-offset}"))
2553 var_success = sc->line_entry.range.GetBaseAddress().IsValid();
2556 format_addr = sc->line_entry.range.GetBaseAddress();
2557 calculate_format_addr_function_offset = true;
2560 else if (IsToken (var_name_begin, "pc-offset}"))
2562 StackFrame *frame = exe_ctx->GetFramePtr();
2563 var_success = frame != NULL;
2566 format_addr = frame->GetFrameCodeAddress();
2567 calculate_format_addr_function_offset = true;
2575 if (IsToken (var_name_begin, "line."))
2577 if (sc && sc->line_entry.IsValid())
2579 var_name_begin += ::strlen ("line.");
2580 if (IsToken (var_name_begin, "file."))
2582 var_name_begin += ::strlen ("file.");
2584 if (IsToken (var_name_begin, "basename}"))
2586 format_file_spec.GetFilename() = sc->line_entry.file.GetFilename();
2587 var_success = (bool)format_file_spec;
2589 else if (IsToken (var_name_begin, "fullpath}"))
2591 format_file_spec = sc->line_entry.file;
2592 var_success = (bool)format_file_spec;
2595 else if (IsTokenWithFormat (var_name_begin, "number", token_format, "%" PRIu64, exe_ctx, sc))
2598 s.Printf(token_format.c_str(), (uint64_t)sc->line_entry.line);
2600 else if ((IsToken (var_name_begin, "start-addr}")) ||
2601 (IsToken (var_name_begin, "end-addr}")))
2603 var_success = sc && sc->line_entry.range.GetBaseAddress().IsValid();
2606 format_addr = sc->line_entry.range.GetBaseAddress();
2607 if (var_name_begin[0] == 'e')
2608 format_addr.Slide (sc->line_entry.range.GetByteSize());
2615 if (IsToken (var_name_begin, "current-pc-arrow"))
2617 if (addr && exe_ctx && exe_ctx->GetFramePtr())
2619 RegisterContextSP reg_ctx = exe_ctx->GetFramePtr()->GetRegisterContextSP();
2622 addr_t pc_loadaddr = reg_ctx->GetPC();
2623 if (pc_loadaddr != LLDB_INVALID_ADDRESS)
2626 pc.SetLoadAddress (pc_loadaddr, exe_ctx->GetTargetPtr());
2634 if (var_success == false)
2647 // If format addr is valid, then we need to print an address
2648 if (reg_num != LLDB_INVALID_REGNUM)
2650 StackFrame *frame = exe_ctx->GetFramePtr();
2651 // We have a register value to display...
2652 if (reg_num == LLDB_REGNUM_GENERIC_PC && reg_kind == eRegisterKindGeneric)
2654 format_addr = frame->GetFrameCodeAddress();
2658 if (reg_ctx == NULL)
2659 reg_ctx = frame->GetRegisterContext().get();
2663 if (reg_kind != kNumRegisterKinds)
2664 reg_num = reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
2665 reg_info = reg_ctx->GetRegisterInfoAtIndex (reg_num);
2666 var_success = reg_info != NULL;
2671 if (reg_info != NULL)
2673 RegisterValue reg_value;
2674 var_success = reg_ctx->ReadRegister (reg_info, reg_value);
2677 reg_value.Dump(&s, reg_info, false, false, eFormatDefault);
2681 if (format_file_spec)
2683 s << format_file_spec;
2686 // If format addr is valid, then we need to print an address
2687 if (format_addr.IsValid())
2689 var_success = false;
2691 if (calculate_format_addr_function_offset)
2699 func_addr = sc->function->GetAddressRange().GetBaseAddress();
2700 if (sc->block && addr_offset_concrete_func_only == false)
2702 // Check to make sure we aren't in an inline
2703 // function. If we are, use the inline block
2704 // range that contains "format_addr" since
2705 // blocks can be discontiguous.
2706 Block *inline_block = sc->block->GetContainingInlinedBlock ();
2707 AddressRange inline_range;
2708 if (inline_block && inline_block->GetRangeContainingAddress (format_addr, inline_range))
2709 func_addr = inline_range.GetBaseAddress();
2712 else if (sc->symbol && sc->symbol->ValueIsAddress())
2713 func_addr = sc->symbol->GetAddress();
2716 if (func_addr.IsValid())
2718 const char *addr_offset_padding = " ";
2719 if (addr_offset_print_with_no_padding)
2721 addr_offset_padding = "";
2723 if (func_addr.GetSection() == format_addr.GetSection())
2725 addr_t func_file_addr = func_addr.GetFileAddress();
2726 addr_t addr_file_addr = format_addr.GetFileAddress();
2727 if (addr_file_addr > func_file_addr)
2728 s.Printf("%s+%s%" PRIu64, addr_offset_padding, addr_offset_padding, addr_file_addr - func_file_addr);
2729 else if (addr_file_addr < func_file_addr)
2730 s.Printf("%s-%s%" PRIu64, addr_offset_padding, addr_offset_padding, func_file_addr - addr_file_addr);
2735 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2738 addr_t func_load_addr = func_addr.GetLoadAddress (target);
2739 addr_t addr_load_addr = format_addr.GetLoadAddress (target);
2740 if (addr_load_addr > func_load_addr)
2741 s.Printf("%s+%s%" PRIu64, addr_offset_padding, addr_offset_padding, addr_load_addr - func_load_addr);
2742 else if (addr_load_addr < func_load_addr)
2743 s.Printf("%s-%s%" PRIu64, addr_offset_padding, addr_offset_padding, func_load_addr - addr_load_addr);
2751 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2752 addr_t vaddr = LLDB_INVALID_ADDRESS;
2753 if (exe_ctx && !target->GetSectionLoadList().IsEmpty())
2754 vaddr = format_addr.GetLoadAddress (target);
2755 if (vaddr == LLDB_INVALID_ADDRESS)
2756 vaddr = format_addr.GetFileAddress ();
2758 if (vaddr != LLDB_INVALID_ADDRESS)
2761 if (exe_ctx && target)
2763 addr_width = target->GetArchitecture().GetAddressByteSize() * 2;
2765 if (addr_width == 0)
2767 if (print_file_addr_or_load_addr)
2769 format_addr.Dump (&s, exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL, Address::DumpStyleLoadAddress, Address::DumpStyleModuleWithFileAddress, 0);
2773 s.Printf("0x%*.*" PRIx64, addr_width, addr_width, vaddr);
2781 if (var_success == false)
2791 // We got a dollar sign with no '{' after it, it must just be a dollar sign
2795 else if (*p == '\\')
2797 ++p; // skip the slash
2800 case 'a': s.PutChar ('\a'); break;
2801 case 'b': s.PutChar ('\b'); break;
2802 case 'f': s.PutChar ('\f'); break;
2803 case 'n': s.PutChar ('\n'); break;
2804 case 'r': s.PutChar ('\r'); break;
2805 case 't': s.PutChar ('\t'); break;
2806 case 'v': s.PutChar ('\v'); break;
2807 case '\'': s.PutChar ('\''); break;
2808 case '\\': s.PutChar ('\\'); break;
2810 // 1 to 3 octal chars
2812 // Make a string that can hold onto the initial zero char,
2813 // up to 3 octal digits, and a terminating NULL.
2814 char oct_str[5] = { 0, 0, 0, 0, 0 };
2817 for (i=0; (p[i] >= '0' && p[i] <= '7') && i<4; ++i)
2820 // We don't want to consume the last octal character since
2821 // the main for loop will do this for us, so we advance p by
2822 // one less than i (even if i is zero)
2824 unsigned long octal_value = ::strtoul (oct_str, NULL, 8);
2825 if (octal_value <= UINT8_MAX)
2827 s.PutChar((char)octal_value);
2833 // hex number in the format
2836 ++p; // Skip the 'x'
2838 // Make a string that can hold onto two hex chars plus a
2840 char hex_str[3] = { 0,0,0 };
2844 ++p; // Skip the first of the two hex chars
2848 unsigned long hex_value = strtoul (hex_str, NULL, 16);
2849 if (hex_value <= UINT8_MAX)
2850 s.PutChar ((char)hex_value);
2859 // Just desensitize any other character by just printing what
2860 // came after the '\'
2874 Debugger::FormatPrompt
2877 const SymbolContext *sc,
2878 const ExecutionContext *exe_ctx,
2879 const Address *addr,
2884 bool use_color = exe_ctx ? exe_ctx->GetTargetRef().GetDebugger().GetUseColor() : true;
2885 std::string format_str = lldb_utility::ansi::FormatAnsiTerminalCodes (format, use_color);
2886 if (format_str.length())
2887 format = format_str.c_str();
2888 return FormatPromptRecurse (format, sc, exe_ctx, addr, s, NULL, valobj, false, false);
2892 Debugger::FormatDisassemblerAddress (const char *format,
2893 const SymbolContext *sc,
2894 const SymbolContext *prev_sc,
2895 const ExecutionContext *exe_ctx,
2896 const Address *addr,
2899 if (format == NULL && exe_ctx != NULL && exe_ctx->HasTargetScope())
2901 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
2903 bool function_changed = false;
2904 bool initial_function = false;
2905 if (prev_sc && (prev_sc->function || prev_sc->symbol))
2907 if (sc && (sc->function || sc->symbol))
2909 if (prev_sc->symbol && sc->symbol)
2911 if (!sc->symbol->Compare (prev_sc->symbol->GetName(), prev_sc->symbol->GetType()))
2913 function_changed = true;
2916 else if (prev_sc->function && sc->function)
2918 if (prev_sc->function->GetMangled() != sc->function->GetMangled())
2920 function_changed = true;
2925 // The first context on a list of instructions will have a prev_sc that
2926 // has no Function or Symbol -- if SymbolContext had an IsValid() method, it
2927 // would return false. But we do get a prev_sc pointer.
2928 if ((sc && (sc->function || sc->symbol))
2929 && prev_sc && (prev_sc->function == NULL && prev_sc->symbol == NULL))
2931 initial_function = true;
2933 return FormatPromptRecurse (format, sc, exe_ctx, addr, s, NULL, NULL, function_changed, initial_function);
2938 Debugger::SetLoggingCallback (lldb::LogOutputCallback log_callback, void *baton)
2940 // For simplicity's sake, I am not going to deal with how to close down any
2941 // open logging streams, I just redirect everything from here on out to the
2943 m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
2947 Debugger::EnableLog (const char *channel, const char **categories, const char *log_file, uint32_t log_options, Stream &error_stream)
2949 Log::Callbacks log_callbacks;
2951 StreamSP log_stream_sp;
2952 if (m_log_callback_stream_sp)
2954 log_stream_sp = m_log_callback_stream_sp;
2955 // For now when using the callback mode you always get thread & timestamp.
2956 log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
2958 else if (log_file == NULL || *log_file == '\0')
2960 log_stream_sp = GetOutputFile();
2964 LogStreamMap::iterator pos = m_log_streams.find(log_file);
2965 if (pos != m_log_streams.end())
2966 log_stream_sp = pos->second.lock();
2969 log_stream_sp.reset (new StreamFile (log_file));
2970 m_log_streams[log_file] = log_stream_sp;
2973 assert (log_stream_sp.get());
2975 if (log_options == 0)
2976 log_options = LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
2978 if (Log::GetLogChannelCallbacks (ConstString(channel), log_callbacks))
2980 log_callbacks.enable (log_stream_sp, log_options, categories, &error_stream);
2985 LogChannelSP log_channel_sp (LogChannel::FindPlugin (channel));
2988 if (log_channel_sp->Enable (log_stream_sp, log_options, &error_stream, categories))
2994 error_stream.Printf ("Invalid log channel '%s'.\n", channel);
3000 error_stream.Printf ("Invalid log channel '%s'.\n", channel);
3008 Debugger::GetSourceManager ()
3010 if (m_source_manager_ap.get() == NULL)
3011 m_source_manager_ap.reset (new SourceManager (shared_from_this()));
3012 return *m_source_manager_ap;
3017 // This function handles events that were broadcast by the process.
3019 Debugger::HandleBreakpointEvent (const EventSP &event_sp)
3021 using namespace lldb;
3022 const uint32_t event_type = Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent (event_sp);
3024 // if (event_type & eBreakpointEventTypeAdded
3025 // || event_type & eBreakpointEventTypeRemoved
3026 // || event_type & eBreakpointEventTypeEnabled
3027 // || event_type & eBreakpointEventTypeDisabled
3028 // || event_type & eBreakpointEventTypeCommandChanged
3029 // || event_type & eBreakpointEventTypeConditionChanged
3030 // || event_type & eBreakpointEventTypeIgnoreChanged
3031 // || event_type & eBreakpointEventTypeLocationsResolved)
3033 // // Don't do anything about these events, since the breakpoint commands already echo these actions.
3036 if (event_type & eBreakpointEventTypeLocationsAdded)
3038 uint32_t num_new_locations = Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(event_sp);
3039 if (num_new_locations > 0)
3041 BreakpointSP breakpoint = Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
3042 StreamFileSP output_sp (GetOutputFile());
3045 output_sp->Printf("%d location%s added to breakpoint %d\n",
3047 num_new_locations == 1 ? "" : "s",
3048 breakpoint->GetID());
3049 RefreshTopIOHandler();
3053 // else if (event_type & eBreakpointEventTypeLocationsRemoved)
3055 // // These locations just get disabled, not sure it is worth spamming folks about this on the command line.
3057 // else if (event_type & eBreakpointEventTypeLocationsResolved)
3059 // // This might be an interesting thing to note, but I'm going to leave it quiet for now, it just looked noisy.
3064 Debugger::GetProcessSTDOUT (Process *process, Stream *stream)
3066 size_t total_bytes = 0;
3068 stream = GetOutputFile().get();
3072 // The process has stuff waiting for stdout; get it and write it out to the appropriate place.
3073 if (process == NULL)
3075 TargetSP target_sp = GetTargetList().GetSelectedTarget();
3077 process = target_sp->GetProcessSP().get();
3083 char stdio_buffer[1024];
3084 while ((len = process->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
3086 stream->Write(stdio_buffer, len);
3096 Debugger::GetProcessSTDERR (Process *process, Stream *stream)
3098 size_t total_bytes = 0;
3100 stream = GetOutputFile().get();
3104 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
3105 if (process == NULL)
3107 TargetSP target_sp = GetTargetList().GetSelectedTarget();
3109 process = target_sp->GetProcessSP().get();
3115 char stdio_buffer[1024];
3116 while ((len = process->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
3118 stream->Write(stdio_buffer, len);
3128 // This function handles events that were broadcast by the process.
3130 Debugger::HandleProcessEvent (const EventSP &event_sp)
3132 using namespace lldb;
3133 const uint32_t event_type = event_sp->GetType();
3134 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
3136 StreamString output_stream;
3137 StreamString error_stream;
3138 const bool gui_enabled = IsForwardingEvents();
3142 bool pop_process_io_handler = false;
3143 assert (process_sp);
3145 if (event_type & Process::eBroadcastBitSTDOUT || event_type & Process::eBroadcastBitStateChanged)
3147 GetProcessSTDOUT (process_sp.get(), &output_stream);
3150 if (event_type & Process::eBroadcastBitSTDERR || event_type & Process::eBroadcastBitStateChanged)
3152 GetProcessSTDERR (process_sp.get(), &error_stream);
3155 if (event_type & Process::eBroadcastBitStateChanged)
3157 Process::HandleProcessStateChangedEvent (event_sp, &output_stream, pop_process_io_handler);
3160 if (output_stream.GetSize() || error_stream.GetSize())
3162 StreamFileSP error_stream_sp (GetOutputFile());
3163 bool top_io_handler_hid = false;
3165 if (process_sp->ProcessIOHandlerIsActive() == false)
3166 top_io_handler_hid = HideTopIOHandler();
3168 if (output_stream.GetSize())
3170 StreamFileSP output_stream_sp (GetOutputFile());
3171 if (output_stream_sp)
3172 output_stream_sp->Write (output_stream.GetData(), output_stream.GetSize());
3175 if (error_stream.GetSize())
3177 StreamFileSP error_stream_sp (GetErrorFile());
3178 if (error_stream_sp)
3179 error_stream_sp->Write (error_stream.GetData(), error_stream.GetSize());
3182 if (top_io_handler_hid)
3183 RefreshTopIOHandler();
3186 if (pop_process_io_handler)
3187 process_sp->PopProcessIOHandler();
3192 Debugger::HandleThreadEvent (const EventSP &event_sp)
3194 // At present the only thread event we handle is the Frame Changed event,
3195 // and all we do for that is just reprint the thread status for that thread.
3196 using namespace lldb;
3197 const uint32_t event_type = event_sp->GetType();
3198 if (event_type == Thread::eBroadcastBitStackChanged ||
3199 event_type == Thread::eBroadcastBitThreadSelected )
3201 ThreadSP thread_sp (Thread::ThreadEventData::GetThreadFromEvent (event_sp.get()));
3205 StreamFileSP stream_sp (GetOutputFile());
3206 thread_sp->GetStatus(*stream_sp, 0, 1, 1);
3207 RefreshTopIOHandler();
3213 Debugger::IsForwardingEvents ()
3215 return (bool)m_forward_listener_sp;
3219 Debugger::EnableForwardEvents (const ListenerSP &listener_sp)
3221 m_forward_listener_sp = listener_sp;
3225 Debugger::CancelForwardEvents (const ListenerSP &listener_sp)
3227 m_forward_listener_sp.reset();
3232 Debugger::DefaultEventHandler()
3234 Listener& listener(GetListener());
3235 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
3236 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
3237 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
3238 BroadcastEventSpec target_event_spec (broadcaster_class_target,
3239 Target::eBroadcastBitBreakpointChanged);
3241 BroadcastEventSpec process_event_spec (broadcaster_class_process,
3242 Process::eBroadcastBitStateChanged |
3243 Process::eBroadcastBitSTDOUT |
3244 Process::eBroadcastBitSTDERR);
3246 BroadcastEventSpec thread_event_spec (broadcaster_class_thread,
3247 Thread::eBroadcastBitStackChanged |
3248 Thread::eBroadcastBitThreadSelected );
3250 listener.StartListeningForEventSpec (*this, target_event_spec);
3251 listener.StartListeningForEventSpec (*this, process_event_spec);
3252 listener.StartListeningForEventSpec (*this, thread_event_spec);
3253 listener.StartListeningForEvents (m_command_interpreter_ap.get(),
3254 CommandInterpreter::eBroadcastBitQuitCommandReceived |
3255 CommandInterpreter::eBroadcastBitAsynchronousOutputData |
3256 CommandInterpreter::eBroadcastBitAsynchronousErrorData );
3258 // Let the thread that spawned us know that we have started up and
3259 // that we are now listening to all required events so no events get missed
3260 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
3266 if (listener.WaitForEvent(NULL, event_sp))
3270 Broadcaster *broadcaster = event_sp->GetBroadcaster();
3273 uint32_t event_type = event_sp->GetType();
3274 ConstString broadcaster_class (broadcaster->GetBroadcasterClass());
3275 if (broadcaster_class == broadcaster_class_process)
3277 HandleProcessEvent (event_sp);
3279 else if (broadcaster_class == broadcaster_class_target)
3281 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(event_sp.get()))
3283 HandleBreakpointEvent (event_sp);
3286 else if (broadcaster_class == broadcaster_class_thread)
3288 HandleThreadEvent (event_sp);
3290 else if (broadcaster == m_command_interpreter_ap.get())
3292 if (event_type & CommandInterpreter::eBroadcastBitQuitCommandReceived)
3296 else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousErrorData)
3298 const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
3299 if (data && data[0])
3301 StreamFileSP error_sp (GetErrorFile());
3305 error_sp->PutCString(data);
3307 RefreshTopIOHandler();
3311 else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousOutputData)
3313 const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
3314 if (data && data[0])
3316 StreamFileSP output_sp (GetOutputFile());
3320 output_sp->PutCString(data);
3322 RefreshTopIOHandler();
3329 if (m_forward_listener_sp)
3330 m_forward_listener_sp->AddEvent(event_sp);
3336 lldb::thread_result_t
3337 Debugger::EventHandlerThread (lldb::thread_arg_t arg)
3339 ((Debugger *)arg)->DefaultEventHandler();
3344 Debugger::StartEventHandlerThread()
3346 if (!m_event_handler_thread.IsJoinable())
3348 // We must synchronize with the DefaultEventHandler() thread to ensure
3349 // it is up and running and listening to events before we return from
3350 // this function. We do this by listening to events for the
3351 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
3352 Listener listener("lldb.debugger.event-handler");
3353 listener.StartListeningForEvents(&m_sync_broadcaster, eBroadcastBitEventThreadIsListening);
3355 // Use larger 8MB stack for this thread
3356 m_event_handler_thread = ThreadLauncher::LaunchThread("lldb.debugger.event-handler", EventHandlerThread,
3359 g_debugger_event_thread_stack_bytes);
3361 // Make sure DefaultEventHandler() is running and listening to events before we return
3362 // from this function. We are only listening for events of type
3363 // eBroadcastBitEventThreadIsListening so we don't need to check the event, we just need
3364 // to wait an infinite amount of time for it (NULL timeout as the first parameter)
3365 lldb::EventSP event_sp;
3366 listener.WaitForEvent(NULL, event_sp);
3368 return m_event_handler_thread.IsJoinable();
3372 Debugger::StopEventHandlerThread()
3374 if (m_event_handler_thread.IsJoinable())
3376 GetCommandInterpreter().BroadcastEvent(CommandInterpreter::eBroadcastBitQuitCommandReceived);
3377 m_event_handler_thread.Join(nullptr);
3382 lldb::thread_result_t
3383 Debugger::IOHandlerThread (lldb::thread_arg_t arg)
3385 Debugger *debugger = (Debugger *)arg;
3386 debugger->ExecuteIOHanders();
3387 debugger->StopEventHandlerThread();
3392 Debugger::StartIOHandlerThread()
3394 if (!m_io_handler_thread.IsJoinable())
3395 m_io_handler_thread = ThreadLauncher::LaunchThread ("lldb.debugger.io-handler",
3399 8*1024*1024); // Use larger 8MB stack for this thread
3400 return m_io_handler_thread.IsJoinable();
3404 Debugger::StopIOHandlerThread()
3406 if (m_io_handler_thread.IsJoinable())
3408 if (m_input_file_sp)
3409 m_input_file_sp->GetFile().Close();
3410 m_io_handler_thread.Join(nullptr);
3415 Debugger::GetDummyTarget()
3417 return m_target_list.GetDummyTarget (*this).get();
3421 Debugger::GetSelectedOrDummyTarget(bool prefer_dummy)
3423 Target *target = nullptr;
3426 target = m_target_list.GetSelectedTarget().get();
3431 return GetDummyTarget();