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"
19 #include "lldb/lldb-private.h"
20 #include "lldb/Core/ConnectionFileDescriptor.h"
21 #include "lldb/Core/InputReader.h"
22 #include "lldb/Core/Module.h"
23 #include "lldb/Core/PluginManager.h"
24 #include "lldb/Core/RegisterValue.h"
25 #include "lldb/Core/State.h"
26 #include "lldb/Core/StreamAsynchronousIO.h"
27 #include "lldb/Core/StreamCallback.h"
28 #include "lldb/Core/StreamString.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/Host/DynamicLibrary.h"
35 #include "lldb/Host/Terminal.h"
36 #include "lldb/Interpreter/CommandInterpreter.h"
37 #include "lldb/Interpreter/OptionValueSInt64.h"
38 #include "lldb/Interpreter/OptionValueString.h"
39 #include "lldb/Symbol/ClangASTContext.h"
40 #include "lldb/Symbol/CompileUnit.h"
41 #include "lldb/Symbol/Function.h"
42 #include "lldb/Symbol/Symbol.h"
43 #include "lldb/Symbol/VariableList.h"
44 #include "lldb/Target/TargetList.h"
45 #include "lldb/Target/Process.h"
46 #include "lldb/Target/RegisterContext.h"
47 #include "lldb/Target/SectionLoadList.h"
48 #include "lldb/Target/StopInfo.h"
49 #include "lldb/Target/Target.h"
50 #include "lldb/Target/Thread.h"
51 #include "lldb/Utility/AnsiTerminal.h"
54 using namespace lldb_private;
57 static uint32_t g_shared_debugger_refcount = 0;
58 static lldb::user_id_t g_unique_id = 1;
60 #pragma mark Static Functions
63 GetDebuggerListMutex ()
65 static Mutex g_mutex(Mutex::eMutexTypeRecursive);
69 typedef std::vector<DebuggerSP> DebuggerList;
74 // hide the static debugger list inside a singleton accessor to avoid
75 // global init contructors
76 static DebuggerList g_list;
80 OptionEnumValueElement
81 g_show_disassembly_enum_values[] =
83 { Debugger::eStopDisassemblyTypeNever, "never", "Never show disassembly when displaying a stop context."},
84 { Debugger::eStopDisassemblyTypeNoSource, "no-source", "Show disassembly when there is no source information, or the source file is missing when displaying a stop context."},
85 { Debugger::eStopDisassemblyTypeAlways, "always", "Always show disassembly when displaying a stop context."},
89 OptionEnumValueElement
90 g_language_enumerators[] =
92 { eScriptLanguageNone, "none", "Disable scripting languages."},
93 { eScriptLanguagePython, "python", "Select python as the default scripting language."},
94 { eScriptLanguageDefault, "default", "Select the lldb default as the default scripting language."},
98 #define MODULE_WITH_FUNC "{ ${module.file.basename}{`${function.name-with-args}${function.pc-offset}}}"
99 #define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}"
101 #define DEFAULT_THREAD_FORMAT "thread #${thread.index}: tid = ${thread.id%tid}"\
105 "{, name = '${thread.name}'}"\
106 "{, queue = '${thread.queue}'}"\
107 "{, stop reason = ${thread.stop-reason}}"\
108 "{\\nReturn value: ${thread.return-value}}"\
111 #define DEFAULT_FRAME_FORMAT "frame #${frame.index}: ${frame.pc}"\
118 static PropertyDefinition
121 { "auto-confirm", OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true all confirmation prompts will receive their default reply." },
122 { "frame-format", OptionValue::eTypeString , true, 0 , DEFAULT_FRAME_FORMAT, NULL, "The default frame format string to use when displaying stack frame information for threads." },
123 { "notify-void", OptionValue::eTypeBoolean, true, false, NULL, NULL, "Notify the user explicitly if an expression returns void (default: false)." },
124 { "prompt", OptionValue::eTypeString , true, OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ", NULL, "The debugger command line prompt displayed for the user." },
125 { "script-lang", OptionValue::eTypeEnum , true, eScriptLanguagePython, NULL, g_language_enumerators, "The script language to be used for evaluating user-written scripts." },
126 { "stop-disassembly-count", OptionValue::eTypeSInt64 , true, 4 , NULL, NULL, "The number of disassembly lines to show when displaying a stopped context." },
127 { "stop-disassembly-display", OptionValue::eTypeEnum , true, Debugger::eStopDisassemblyTypeNoSource, NULL, g_show_disassembly_enum_values, "Control when to display disassembly when displaying a stopped context." },
128 { "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." },
129 { "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." },
130 { "term-width", OptionValue::eTypeSInt64 , true, 80 , NULL, NULL, "The maximum number of columns to use for displaying text." },
131 { "thread-format", OptionValue::eTypeString , true, 0 , DEFAULT_THREAD_FORMAT, NULL, "The default thread format string to use when displaying thread information." },
132 { "use-external-editor", OptionValue::eTypeBoolean, true, false, NULL, NULL, "Whether to use an external editor or not." },
133 { "use-color", OptionValue::eTypeBoolean, true, true , NULL, NULL, "Whether to use Ansi color codes or not." },
134 { "auto-one-line-summaries", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, LLDB will automatically display small structs in one-liner format (default: true)." },
136 { NULL, OptionValue::eTypeInvalid, true, 0 , NULL, NULL, NULL }
141 ePropertyAutoConfirm = 0,
142 ePropertyFrameFormat,
145 ePropertyScriptLanguage,
146 ePropertyStopDisassemblyCount,
147 ePropertyStopDisassemblyDisplay,
148 ePropertyStopLineCountAfter,
149 ePropertyStopLineCountBefore,
150 ePropertyTerminalWidth,
151 ePropertyThreadFormat,
152 ePropertyUseExternalEditor,
154 ePropertyAutoOneLineSummaries
157 Debugger::LoadPluginCallbackType Debugger::g_load_plugin_callback = NULL;
160 Debugger::SetPropertyValue (const ExecutionContext *exe_ctx,
161 VarSetOperationType op,
162 const char *property_path,
165 bool is_load_script = strcmp(property_path,"target.load-script-from-symbol-file") == 0;
167 LoadScriptFromSymFile load_script_old_value;
168 if (is_load_script && exe_ctx->GetTargetSP())
170 target_sp = exe_ctx->GetTargetSP();
171 load_script_old_value = target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
173 Error error (Properties::SetPropertyValue (exe_ctx, op, property_path, value));
176 // FIXME it would be nice to have "on-change" callbacks for properties
177 if (strcmp(property_path, g_properties[ePropertyPrompt].name) == 0)
179 const char *new_prompt = GetPrompt();
180 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
182 new_prompt = str.c_str();
183 EventSP prompt_change_event_sp (new Event(CommandInterpreter::eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));
184 GetCommandInterpreter().BroadcastEvent (prompt_change_event_sp);
186 else if (strcmp(property_path, g_properties[ePropertyUseColor].name) == 0)
188 // use-color changed. Ping the prompt so it can reset the ansi terminal codes.
189 SetPrompt (GetPrompt());
191 else if (is_load_script && target_sp && load_script_old_value == eLoadScriptFromSymFileWarn)
193 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() == eLoadScriptFromSymFileTrue)
195 std::list<Error> errors;
196 StreamString feedback_stream;
197 if (!target_sp->LoadScriptingResources(errors,&feedback_stream))
199 for (auto error : errors)
201 GetErrorStream().Printf("%s\n",error.AsCString());
203 if (feedback_stream.GetSize())
204 GetErrorStream().Printf("%s",feedback_stream.GetData());
213 Debugger::GetAutoConfirm () const
215 const uint32_t idx = ePropertyAutoConfirm;
216 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
220 Debugger::GetFrameFormat() const
222 const uint32_t idx = ePropertyFrameFormat;
223 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
227 Debugger::GetNotifyVoid () const
229 const uint32_t idx = ePropertyNotiftVoid;
230 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
234 Debugger::GetPrompt() const
236 const uint32_t idx = ePropertyPrompt;
237 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
241 Debugger::SetPrompt(const char *p)
243 const uint32_t idx = ePropertyPrompt;
244 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
245 const char *new_prompt = GetPrompt();
246 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
248 new_prompt = str.c_str();
249 EventSP prompt_change_event_sp (new Event(CommandInterpreter::eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));;
250 GetCommandInterpreter().BroadcastEvent (prompt_change_event_sp);
254 Debugger::GetThreadFormat() const
256 const uint32_t idx = ePropertyThreadFormat;
257 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
261 Debugger::GetScriptLanguage() const
263 const uint32_t idx = ePropertyScriptLanguage;
264 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
268 Debugger::SetScriptLanguage (lldb::ScriptLanguage script_lang)
270 const uint32_t idx = ePropertyScriptLanguage;
271 return m_collection_sp->SetPropertyAtIndexAsEnumeration (NULL, idx, script_lang);
275 Debugger::GetTerminalWidth () const
277 const uint32_t idx = ePropertyTerminalWidth;
278 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
282 Debugger::SetTerminalWidth (uint32_t term_width)
284 const uint32_t idx = ePropertyTerminalWidth;
285 return m_collection_sp->SetPropertyAtIndexAsSInt64 (NULL, idx, term_width);
289 Debugger::GetUseExternalEditor () const
291 const uint32_t idx = ePropertyUseExternalEditor;
292 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
296 Debugger::SetUseExternalEditor (bool b)
298 const uint32_t idx = ePropertyUseExternalEditor;
299 return m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
303 Debugger::GetUseColor () const
305 const uint32_t idx = ePropertyUseColor;
306 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
310 Debugger::SetUseColor (bool b)
312 const uint32_t idx = ePropertyUseColor;
313 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
314 SetPrompt (GetPrompt());
319 Debugger::GetStopSourceLineCount (bool before) const
321 const uint32_t idx = before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
322 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
325 Debugger::StopDisassemblyType
326 Debugger::GetStopDisassemblyDisplay () const
328 const uint32_t idx = ePropertyStopDisassemblyDisplay;
329 return (Debugger::StopDisassemblyType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
333 Debugger::GetDisassemblyLineCount () const
335 const uint32_t idx = ePropertyStopDisassemblyCount;
336 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
340 Debugger::GetAutoOneLineSummaries () const
342 const uint32_t idx = ePropertyAutoOneLineSummaries;
343 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
347 #pragma mark Debugger
349 //const DebuggerPropertiesSP &
350 //Debugger::GetSettings() const
352 // return m_properties_sp;
357 Debugger::TestDebuggerRefCount ()
359 return g_shared_debugger_refcount;
363 Debugger::Initialize (LoadPluginCallbackType load_plugin_callback)
365 g_load_plugin_callback = load_plugin_callback;
366 if (g_shared_debugger_refcount++ == 0)
367 lldb_private::Initialize();
371 Debugger::Terminate ()
373 if (g_shared_debugger_refcount > 0)
375 g_shared_debugger_refcount--;
376 if (g_shared_debugger_refcount == 0)
378 lldb_private::WillTerminate();
379 lldb_private::Terminate();
381 // Clear our master list of debugger objects
382 Mutex::Locker locker (GetDebuggerListMutex ());
383 GetDebuggerList().clear();
389 Debugger::SettingsInitialize ()
391 Target::SettingsInitialize ();
395 Debugger::SettingsTerminate ()
397 Target::SettingsTerminate ();
401 Debugger::LoadPlugin (const FileSpec& spec, Error& error)
403 if (g_load_plugin_callback)
405 lldb::DynamicLibrarySP dynlib_sp = g_load_plugin_callback (shared_from_this(), spec, error);
408 m_loaded_plugins.push_back(dynlib_sp);
414 // The g_load_plugin_callback is registered in SBDebugger::Initialize()
415 // and if the public API layer isn't available (code is linking against
416 // all of the internal LLDB static libraries), then we can't load plugins
417 error.SetErrorString("Public API layer is not available");
422 static FileSpec::EnumerateDirectoryResult
426 FileSpec::FileType file_type,
427 const FileSpec &file_spec
432 static ConstString g_dylibext("dylib");
433 static ConstString g_solibext("so");
436 return FileSpec::eEnumerateDirectoryResultQuit;
438 Debugger *debugger = (Debugger*)baton;
440 // If we have a regular file, a symbolic link or unknown file type, try
441 // and process the file. We must handle unknown as sometimes the directory
442 // enumeration might be enumerating a file system that doesn't have correct
443 // file type information.
444 if (file_type == FileSpec::eFileTypeRegular ||
445 file_type == FileSpec::eFileTypeSymbolicLink ||
446 file_type == FileSpec::eFileTypeUnknown )
448 FileSpec plugin_file_spec (file_spec);
449 plugin_file_spec.ResolvePath ();
451 if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
452 plugin_file_spec.GetFileNameExtension() != g_solibext)
454 return FileSpec::eEnumerateDirectoryResultNext;
457 Error plugin_load_error;
458 debugger->LoadPlugin (plugin_file_spec, plugin_load_error);
460 return FileSpec::eEnumerateDirectoryResultNext;
463 else if (file_type == FileSpec::eFileTypeUnknown ||
464 file_type == FileSpec::eFileTypeDirectory ||
465 file_type == FileSpec::eFileTypeSymbolicLink )
467 // Try and recurse into anything that a directory or symbolic link.
468 // We must also do this for unknown as sometimes the directory enumeration
469 // might be enurating a file system that doesn't have correct file type
471 return FileSpec::eEnumerateDirectoryResultEnter;
474 return FileSpec::eEnumerateDirectoryResultNext;
478 Debugger::InstanceInitialize ()
481 const bool find_directories = true;
482 const bool find_files = true;
483 const bool find_other = true;
484 char dir_path[PATH_MAX];
485 if (Host::GetLLDBPath (ePathTypeLLDBSystemPlugins, dir_spec))
487 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
489 FileSpec::EnumerateDirectory (dir_path,
498 if (Host::GetLLDBPath (ePathTypeLLDBUserPlugins, dir_spec))
500 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
502 FileSpec::EnumerateDirectory (dir_path,
511 PluginManager::DebuggerInitialize (*this);
515 Debugger::CreateInstance (lldb::LogOutputCallback log_callback, void *baton)
517 DebuggerSP debugger_sp (new Debugger(log_callback, baton));
518 if (g_shared_debugger_refcount > 0)
520 Mutex::Locker locker (GetDebuggerListMutex ());
521 GetDebuggerList().push_back(debugger_sp);
523 debugger_sp->InstanceInitialize ();
528 Debugger::Destroy (DebuggerSP &debugger_sp)
530 if (debugger_sp.get() == NULL)
533 debugger_sp->Clear();
535 if (g_shared_debugger_refcount > 0)
537 Mutex::Locker locker (GetDebuggerListMutex ());
538 DebuggerList &debugger_list = GetDebuggerList ();
539 DebuggerList::iterator pos, end = debugger_list.end();
540 for (pos = debugger_list.begin (); pos != end; ++pos)
542 if ((*pos).get() == debugger_sp.get())
544 debugger_list.erase (pos);
552 Debugger::FindDebuggerWithInstanceName (const ConstString &instance_name)
554 DebuggerSP debugger_sp;
555 if (g_shared_debugger_refcount > 0)
557 Mutex::Locker locker (GetDebuggerListMutex ());
558 DebuggerList &debugger_list = GetDebuggerList();
559 DebuggerList::iterator pos, end = debugger_list.end();
561 for (pos = debugger_list.begin(); pos != end; ++pos)
563 if ((*pos).get()->m_instance_name == instance_name)
574 Debugger::FindTargetWithProcessID (lldb::pid_t pid)
577 if (g_shared_debugger_refcount > 0)
579 Mutex::Locker locker (GetDebuggerListMutex ());
580 DebuggerList &debugger_list = GetDebuggerList();
581 DebuggerList::iterator pos, end = debugger_list.end();
582 for (pos = debugger_list.begin(); pos != end; ++pos)
584 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID (pid);
593 Debugger::FindTargetWithProcess (Process *process)
596 if (g_shared_debugger_refcount > 0)
598 Mutex::Locker locker (GetDebuggerListMutex ());
599 DebuggerList &debugger_list = GetDebuggerList();
600 DebuggerList::iterator pos, end = debugger_list.end();
601 for (pos = debugger_list.begin(); pos != end; ++pos)
603 target_sp = (*pos)->GetTargetList().FindTargetWithProcess (process);
611 Debugger::Debugger (lldb::LogOutputCallback log_callback, void *baton) :
612 UserID (g_unique_id++),
613 Properties(OptionValuePropertiesSP(new OptionValueProperties())),
614 m_input_comm("debugger.input"),
619 m_target_list (*this),
621 m_listener ("lldb.Debugger"),
622 m_source_manager_ap(),
623 m_source_file_cache(),
624 m_command_interpreter_ap (new CommandInterpreter (*this, eScriptLanguageDefault, false)),
625 m_input_reader_stack (),
626 m_input_reader_data (),
629 char instance_cstr[256];
630 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
631 m_instance_name.SetCString(instance_cstr);
633 m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
634 m_command_interpreter_ap->Initialize ();
635 // Always add our default platform to the platform list
636 PlatformSP default_platform_sp (Platform::GetDefaultPlatform());
637 assert (default_platform_sp.get());
638 m_platform_list.Append (default_platform_sp, true);
640 m_collection_sp->Initialize (g_properties);
641 m_collection_sp->AppendProperty (ConstString("target"),
642 ConstString("Settings specify to debugging targets."),
644 Target::GetGlobalProperties()->GetValueProperties());
645 if (m_command_interpreter_ap.get())
647 m_collection_sp->AppendProperty (ConstString("interpreter"),
648 ConstString("Settings specify to the debugger's command interpreter."),
650 m_command_interpreter_ap->GetValueProperties());
652 OptionValueSInt64 *term_width = m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64 (NULL, ePropertyTerminalWidth);
653 term_width->SetMinimumValue(10);
654 term_width->SetMaximumValue(1024);
656 // Turn off use-color if this is a dumb terminal.
657 const char *term = getenv ("TERM");
658 if (term && !strcmp (term, "dumb"))
662 Debugger::~Debugger ()
670 CleanUpInputReaders();
672 int num_targets = m_target_list.GetNumTargets();
673 for (int i = 0; i < num_targets; i++)
675 TargetSP target_sp (m_target_list.GetTargetAtIndex (i));
678 ProcessSP process_sp (target_sp->GetProcessSP());
680 process_sp->Finalize();
681 target_sp->Destroy();
684 BroadcasterManager::Clear ();
686 // Close the input file _before_ we close the input read communications class
687 // as it does NOT own the input file, our m_input_file does.
688 m_terminal_state.Clear();
689 GetInputFile().Close ();
690 // Now that we have closed m_input_file, we can now tell our input communication
691 // class to close down. Its read thread should quickly exit after we close
692 // the input file handle above.
693 m_input_comm.Clear ();
697 Debugger::GetCloseInputOnEOF () const
699 return m_input_comm.GetCloseOnEOF();
703 Debugger::SetCloseInputOnEOF (bool b)
705 m_input_comm.SetCloseOnEOF(b);
709 Debugger::GetAsyncExecution ()
711 return !m_command_interpreter_ap->GetSynchronous();
715 Debugger::SetAsyncExecution (bool async_execution)
717 m_command_interpreter_ap->SetSynchronous (!async_execution);
722 Debugger::SetInputFileHandle (FILE *fh, bool tranfer_ownership)
724 File &in_file = GetInputFile();
725 in_file.SetStream (fh, tranfer_ownership);
726 if (in_file.IsValid() == false)
727 in_file.SetStream (stdin, true);
729 // Disconnect from any old connection if we had one
730 m_input_comm.Disconnect ();
731 // Pass false as the second argument to ConnectionFileDescriptor below because
732 // our "in_file" above will already take ownership if requested and we don't
733 // want to objects trying to own and close a file descriptor.
734 m_input_comm.SetConnection (new ConnectionFileDescriptor (in_file.GetDescriptor(), false));
735 m_input_comm.SetReadThreadBytesReceivedCallback (Debugger::DispatchInputCallback, this);
737 // Save away the terminal state if that is relevant, so that we can restore it in RestoreInputState.
738 SaveInputTerminalState ();
741 if (m_input_comm.StartReadThread (&error) == false)
743 File &err_file = GetErrorFile();
745 err_file.Printf ("error: failed to main input read thread: %s", error.AsCString() ? error.AsCString() : "unkown error");
751 Debugger::SetOutputFileHandle (FILE *fh, bool tranfer_ownership)
753 File &out_file = GetOutputFile();
754 out_file.SetStream (fh, tranfer_ownership);
755 if (out_file.IsValid() == false)
756 out_file.SetStream (stdout, false);
758 // do not create the ScriptInterpreter just for setting the output file handle
759 // as the constructor will know how to do the right thing on its own
760 const bool can_create = false;
761 ScriptInterpreter* script_interpreter = GetCommandInterpreter().GetScriptInterpreter(can_create);
762 if (script_interpreter)
763 script_interpreter->ResetOutputFileHandle (fh);
767 Debugger::SetErrorFileHandle (FILE *fh, bool tranfer_ownership)
769 File &err_file = GetErrorFile();
770 err_file.SetStream (fh, tranfer_ownership);
771 if (err_file.IsValid() == false)
772 err_file.SetStream (stderr, false);
776 Debugger::SaveInputTerminalState ()
778 File &in_file = GetInputFile();
779 if (in_file.GetDescriptor() != File::kInvalidDescriptor)
780 m_terminal_state.Save(in_file.GetDescriptor(), true);
784 Debugger::RestoreInputTerminalState ()
786 m_terminal_state.Restore();
790 Debugger::GetSelectedExecutionContext ()
792 ExecutionContext exe_ctx;
793 TargetSP target_sp(GetSelectedTarget());
794 exe_ctx.SetTargetSP (target_sp);
798 ProcessSP process_sp (target_sp->GetProcessSP());
799 exe_ctx.SetProcessSP (process_sp);
800 if (process_sp && process_sp->IsRunning() == false)
802 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
805 exe_ctx.SetThreadSP (thread_sp);
806 exe_ctx.SetFrameSP (thread_sp->GetSelectedFrame());
807 if (exe_ctx.GetFramePtr() == NULL)
808 exe_ctx.SetFrameSP (thread_sp->GetStackFrameAtIndex (0));
816 Debugger::GetCurrentInputReader ()
818 InputReaderSP reader_sp;
820 if (!m_input_reader_stack.IsEmpty())
822 // Clear any finished readers from the stack
823 while (CheckIfTopInputReaderIsDone()) ;
825 if (!m_input_reader_stack.IsEmpty())
826 reader_sp = m_input_reader_stack.Top();
833 Debugger::DispatchInputCallback (void *baton, const void *bytes, size_t bytes_len)
836 ((Debugger *)baton)->DispatchInput ((char *)bytes, bytes_len);
838 ((Debugger *)baton)->DispatchInputEndOfFile ();
843 Debugger::DispatchInput (const char *bytes, size_t bytes_len)
845 if (bytes == NULL || bytes_len == 0)
848 WriteToDefaultReader (bytes, bytes_len);
852 Debugger::DispatchInputInterrupt ()
854 m_input_reader_data.clear();
856 InputReaderSP reader_sp (GetCurrentInputReader ());
859 reader_sp->Notify (eInputReaderInterrupt);
861 // If notifying the reader of the interrupt finished the reader, we should pop it off the stack.
862 while (CheckIfTopInputReaderIsDone ()) ;
867 Debugger::DispatchInputEndOfFile ()
869 m_input_reader_data.clear();
871 InputReaderSP reader_sp (GetCurrentInputReader ());
874 reader_sp->Notify (eInputReaderEndOfFile);
876 // If notifying the reader of the end-of-file finished the reader, we should pop it off the stack.
877 while (CheckIfTopInputReaderIsDone ()) ;
882 Debugger::CleanUpInputReaders ()
884 m_input_reader_data.clear();
886 // The bottom input reader should be the main debugger input reader. We do not want to close that one here.
887 while (m_input_reader_stack.GetSize() > 1)
889 InputReaderSP reader_sp (GetCurrentInputReader ());
892 reader_sp->Notify (eInputReaderEndOfFile);
893 reader_sp->SetIsDone (true);
899 Debugger::NotifyTopInputReader (InputReaderAction notification)
901 InputReaderSP reader_sp (GetCurrentInputReader());
904 reader_sp->Notify (notification);
906 // Flush out any input readers that are done.
907 while (CheckIfTopInputReaderIsDone ())
913 Debugger::InputReaderIsTopReader (const InputReaderSP& reader_sp)
915 InputReaderSP top_reader_sp (GetCurrentInputReader());
917 return (reader_sp.get() == top_reader_sp.get());
922 Debugger::WriteToDefaultReader (const char *bytes, size_t bytes_len)
924 if (bytes && bytes_len)
925 m_input_reader_data.append (bytes, bytes_len);
927 if (m_input_reader_data.empty())
930 while (!m_input_reader_stack.IsEmpty() && !m_input_reader_data.empty())
932 // Get the input reader from the top of the stack
933 InputReaderSP reader_sp (GetCurrentInputReader ());
937 size_t bytes_handled = reader_sp->HandleRawBytes (m_input_reader_data.c_str(),
938 m_input_reader_data.size());
941 m_input_reader_data.erase (0, bytes_handled);
945 // No bytes were handled, we might not have reached our
946 // granularity, just return and wait for more data
951 // Flush out any input readers that are done.
952 while (CheckIfTopInputReaderIsDone ())
958 Debugger::PushInputReader (const InputReaderSP& reader_sp)
963 // Deactivate the old top reader
964 InputReaderSP top_reader_sp (GetCurrentInputReader ());
967 top_reader_sp->Notify (eInputReaderDeactivate);
969 m_input_reader_stack.Push (reader_sp);
970 reader_sp->Notify (eInputReaderActivate);
971 ActivateInputReader (reader_sp);
975 Debugger::PopInputReader (const InputReaderSP& pop_reader_sp)
979 // The reader on the stop of the stack is done, so let the next
980 // read on the stack referesh its prompt and if there is one...
981 if (!m_input_reader_stack.IsEmpty())
983 // Cannot call GetCurrentInputReader here, as that would cause an infinite loop.
984 InputReaderSP reader_sp(m_input_reader_stack.Top());
986 if (!pop_reader_sp || pop_reader_sp.get() == reader_sp.get())
988 m_input_reader_stack.Pop ();
989 reader_sp->Notify (eInputReaderDeactivate);
990 reader_sp->Notify (eInputReaderDone);
993 if (!m_input_reader_stack.IsEmpty())
995 reader_sp = m_input_reader_stack.Top();
998 ActivateInputReader (reader_sp);
999 reader_sp->Notify (eInputReaderReactivate);
1008 Debugger::CheckIfTopInputReaderIsDone ()
1010 bool result = false;
1011 if (!m_input_reader_stack.IsEmpty())
1013 // Cannot call GetCurrentInputReader here, as that would cause an infinite loop.
1014 InputReaderSP reader_sp(m_input_reader_stack.Top());
1016 if (reader_sp && reader_sp->IsDone())
1019 PopInputReader (reader_sp);
1026 Debugger::ActivateInputReader (const InputReaderSP &reader_sp)
1028 int input_fd = m_input_file.GetFile().GetDescriptor();
1032 Terminal tty(input_fd);
1034 tty.SetEcho(reader_sp->GetEcho());
1036 switch (reader_sp->GetGranularity())
1038 case eInputReaderGranularityByte:
1039 case eInputReaderGranularityWord:
1040 tty.SetCanonical (false);
1043 case eInputReaderGranularityLine:
1044 case eInputReaderGranularityAll:
1045 tty.SetCanonical (true);
1055 Debugger::GetAsyncOutputStream ()
1057 return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
1058 CommandInterpreter::eBroadcastBitAsynchronousOutputData));
1062 Debugger::GetAsyncErrorStream ()
1064 return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
1065 CommandInterpreter::eBroadcastBitAsynchronousErrorData));
1069 Debugger::GetNumDebuggers()
1071 if (g_shared_debugger_refcount > 0)
1073 Mutex::Locker locker (GetDebuggerListMutex ());
1074 return GetDebuggerList().size();
1080 Debugger::GetDebuggerAtIndex (size_t index)
1082 DebuggerSP debugger_sp;
1084 if (g_shared_debugger_refcount > 0)
1086 Mutex::Locker locker (GetDebuggerListMutex ());
1087 DebuggerList &debugger_list = GetDebuggerList();
1089 if (index < debugger_list.size())
1090 debugger_sp = debugger_list[index];
1097 Debugger::FindDebuggerWithID (lldb::user_id_t id)
1099 DebuggerSP debugger_sp;
1101 if (g_shared_debugger_refcount > 0)
1103 Mutex::Locker locker (GetDebuggerListMutex ());
1104 DebuggerList &debugger_list = GetDebuggerList();
1105 DebuggerList::iterator pos, end = debugger_list.end();
1106 for (pos = debugger_list.begin(); pos != end; ++pos)
1108 if ((*pos).get()->GetID() == id)
1119 TestPromptFormats (StackFrame *frame)
1125 const char *prompt_format =
1126 "{addr = '${addr}'\n}"
1127 "{process.id = '${process.id}'\n}"
1128 "{process.name = '${process.name}'\n}"
1129 "{process.file.basename = '${process.file.basename}'\n}"
1130 "{process.file.fullpath = '${process.file.fullpath}'\n}"
1131 "{thread.id = '${thread.id}'\n}"
1132 "{thread.index = '${thread.index}'\n}"
1133 "{thread.name = '${thread.name}'\n}"
1134 "{thread.queue = '${thread.queue}'\n}"
1135 "{thread.stop-reason = '${thread.stop-reason}'\n}"
1136 "{target.arch = '${target.arch}'\n}"
1137 "{module.file.basename = '${module.file.basename}'\n}"
1138 "{module.file.fullpath = '${module.file.fullpath}'\n}"
1139 "{file.basename = '${file.basename}'\n}"
1140 "{file.fullpath = '${file.fullpath}'\n}"
1141 "{frame.index = '${frame.index}'\n}"
1142 "{frame.pc = '${frame.pc}'\n}"
1143 "{frame.sp = '${frame.sp}'\n}"
1144 "{frame.fp = '${frame.fp}'\n}"
1145 "{frame.flags = '${frame.flags}'\n}"
1146 "{frame.reg.rdi = '${frame.reg.rdi}'\n}"
1147 "{frame.reg.rip = '${frame.reg.rip}'\n}"
1148 "{frame.reg.rsp = '${frame.reg.rsp}'\n}"
1149 "{frame.reg.rbp = '${frame.reg.rbp}'\n}"
1150 "{frame.reg.rflags = '${frame.reg.rflags}'\n}"
1151 "{frame.reg.xmm0 = '${frame.reg.xmm0}'\n}"
1152 "{frame.reg.carp = '${frame.reg.carp}'\n}"
1153 "{function.id = '${function.id}'\n}"
1154 "{function.name = '${function.name}'\n}"
1155 "{function.name-with-args = '${function.name-with-args}'\n}"
1156 "{function.addr-offset = '${function.addr-offset}'\n}"
1157 "{function.line-offset = '${function.line-offset}'\n}"
1158 "{function.pc-offset = '${function.pc-offset}'\n}"
1159 "{line.file.basename = '${line.file.basename}'\n}"
1160 "{line.file.fullpath = '${line.file.fullpath}'\n}"
1161 "{line.number = '${line.number}'\n}"
1162 "{line.start-addr = '${line.start-addr}'\n}"
1163 "{line.end-addr = '${line.end-addr}'\n}"
1166 SymbolContext sc (frame->GetSymbolContext(eSymbolContextEverything));
1167 ExecutionContext exe_ctx;
1168 frame->CalculateExecutionContext(exe_ctx);
1169 if (Debugger::FormatPrompt (prompt_format, &sc, &exe_ctx, &sc.line_entry.range.GetBaseAddress(), s))
1171 printf("%s\n", s.GetData());
1175 printf ("what we got: %s\n", s.GetData());
1180 ScanFormatDescriptor (const char* var_name_begin,
1181 const char* var_name_end,
1182 const char** var_name_final,
1183 const char** percent_position,
1184 Format* custom_format,
1185 ValueObject::ValueObjectRepresentationStyle* val_obj_display)
1187 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1188 *percent_position = ::strchr(var_name_begin,'%');
1189 if (!*percent_position || *percent_position > var_name_end)
1192 log->Printf("[ScanFormatDescriptor] no format descriptor in string, skipping");
1193 *var_name_final = var_name_end;
1197 *var_name_final = *percent_position;
1198 std::string format_name(*var_name_final+1, var_name_end-*var_name_final-1);
1200 log->Printf("[ScanFormatDescriptor] parsing %s as a format descriptor", format_name.c_str());
1201 if ( !FormatManager::GetFormatFromCString(format_name.c_str(),
1206 log->Printf("[ScanFormatDescriptor] %s is an unknown format", format_name.c_str());
1208 switch (format_name.front())
1210 case '@': // if this is an @ sign, print ObjC description
1211 *val_obj_display = ValueObject::eValueObjectRepresentationStyleLanguageSpecific;
1213 case 'V': // if this is a V, print the value using the default format
1214 *val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1216 case 'L': // if this is an L, print the location of the value
1217 *val_obj_display = ValueObject::eValueObjectRepresentationStyleLocation;
1219 case 'S': // if this is an S, print the summary after all
1220 *val_obj_display = ValueObject::eValueObjectRepresentationStyleSummary;
1222 case '#': // if this is a '#', print the number of children
1223 *val_obj_display = ValueObject::eValueObjectRepresentationStyleChildrenCount;
1225 case 'T': // if this is a 'T', print the type
1226 *val_obj_display = ValueObject::eValueObjectRepresentationStyleType;
1228 case 'N': // if this is a 'N', print the name
1229 *val_obj_display = ValueObject::eValueObjectRepresentationStyleName;
1231 case '>': // if this is a '>', print the name
1232 *val_obj_display = ValueObject::eValueObjectRepresentationStyleExpressionPath;
1236 log->Printf("ScanFormatDescriptor] %s is an error, leaving the previous value alone", format_name.c_str());
1240 // a good custom format tells us to print the value using it
1244 log->Printf("[ScanFormatDescriptor] will display value for this VO");
1245 *val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1249 log->Printf("[ScanFormatDescriptor] final format description outcome: custom_format = %d, val_obj_display = %d",
1256 ScanBracketedRange (const char* var_name_begin,
1257 const char* var_name_end,
1258 const char* var_name_final,
1259 const char** open_bracket_position,
1260 const char** separator_position,
1261 const char** close_bracket_position,
1262 const char** var_name_final_if_array_range,
1263 int64_t* index_lower,
1264 int64_t* index_higher)
1266 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1267 *open_bracket_position = ::strchr(var_name_begin,'[');
1268 if (*open_bracket_position && *open_bracket_position < var_name_final)
1270 *separator_position = ::strchr(*open_bracket_position,'-'); // might be NULL if this is a simple var[N] bitfield
1271 *close_bracket_position = ::strchr(*open_bracket_position,']');
1272 // as usual, we assume that [] will come before %
1273 //printf("trying to expand a []\n");
1274 *var_name_final_if_array_range = *open_bracket_position;
1275 if (*close_bracket_position - *open_bracket_position == 1)
1278 log->Printf("[ScanBracketedRange] '[]' detected.. going from 0 to end of data");
1281 else if (*separator_position == NULL || *separator_position > var_name_end)
1284 *index_lower = ::strtoul (*open_bracket_position+1, &end, 0);
1285 *index_higher = *index_lower;
1287 log->Printf("[ScanBracketedRange] [%" PRId64 "] detected, high index is same", *index_lower);
1289 else if (*close_bracket_position && *close_bracket_position < var_name_end)
1292 *index_lower = ::strtoul (*open_bracket_position+1, &end, 0);
1293 *index_higher = ::strtoul (*separator_position+1, &end, 0);
1295 log->Printf("[ScanBracketedRange] [%" PRId64 "-%" PRId64 "] detected", *index_lower, *index_higher);
1300 log->Printf("[ScanBracketedRange] expression is erroneous, cannot extract indices out of it");
1303 if (*index_lower > *index_higher && *index_higher > 0)
1306 log->Printf("[ScanBracketedRange] swapping indices");
1307 int64_t temp = *index_lower;
1308 *index_lower = *index_higher;
1309 *index_higher = temp;
1313 log->Printf("[ScanBracketedRange] no bracketed range, skipping entirely");
1317 template <typename T>
1318 static bool RunScriptFormatKeyword(Stream &s, ScriptInterpreter *script_interpreter, T t, const std::string& script_name)
1320 if (script_interpreter)
1323 std::string script_output;
1325 if (script_interpreter->RunScriptFormatKeyword(script_name.c_str(), t, script_output, script_error) && script_error.Success())
1327 s.Printf("%s", script_output.c_str());
1332 s.Printf("<error: %s>",script_error.AsCString());
1338 static ValueObjectSP
1339 ExpandIndexedExpression (ValueObject* valobj,
1344 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1345 const char* ptr_deref_format = "[%d]";
1346 std::string ptr_deref_buffer(10,0);
1347 ::sprintf(&ptr_deref_buffer[0], ptr_deref_format, index);
1349 log->Printf("[ExpandIndexedExpression] name to deref: %s",ptr_deref_buffer.c_str());
1350 const char* first_unparsed;
1351 ValueObject::GetValueForExpressionPathOptions options;
1352 ValueObject::ExpressionPathEndResultType final_value_type;
1353 ValueObject::ExpressionPathScanEndReason reason_to_stop;
1354 ValueObject::ExpressionPathAftermath what_next = (deref_pointer ? ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
1355 ValueObjectSP item = valobj->GetValueForExpressionPath (ptr_deref_buffer.c_str(),
1364 log->Printf("[ExpandIndexedExpression] ERROR: unparsed portion = %s, why stopping = %d,"
1365 " final_value_type %d",
1366 first_unparsed, reason_to_stop, final_value_type);
1371 log->Printf("[ExpandIndexedExpression] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
1372 " final_value_type %d",
1373 first_unparsed, reason_to_stop, final_value_type);
1379 IsToken(const char *var_name_begin, const char *var)
1381 return (::strncmp (var_name_begin, var, strlen(var)) == 0);
1385 IsTokenWithFormat(const char *var_name_begin, const char *var, std::string &format, const char *default_format,
1386 const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
1388 int var_len = strlen(var);
1389 if (::strncmp (var_name_begin, var, var_len) == 0)
1391 var_name_begin += var_len;
1392 if (*var_name_begin == '}')
1394 format = default_format;
1397 else if (*var_name_begin == '%')
1399 // Allow format specifiers: x|X|u with optional width specifiers.
1400 // ${thread.id%x} ; hex
1401 // ${thread.id%X} ; uppercase hex
1402 // ${thread.id%u} ; unsigned decimal
1403 // ${thread.id%8.8X} ; width.precision + specifier
1404 // ${thread.id%tid} ; unsigned on FreeBSD/Linux, otherwise default_format (0x%4.4x for thread.id)
1406 const char *specifier = NULL;
1407 int width_precision_length = 0;
1408 const char *width_precision = ++var_name_begin;
1409 while (isdigit(*var_name_begin) || *var_name_begin == '.')
1411 dot_count += (*var_name_begin == '.');
1415 width_precision_length++;
1418 if (IsToken (var_name_begin, "tid}"))
1420 Target *target = Target::GetTargetFromContexts (exe_ctx_ptr, sc_ptr);
1423 ArchSpec arch (target->GetArchitecture ());
1424 llvm::Triple::OSType ostype = arch.IsValid() ? arch.GetTriple().getOS() : llvm::Triple::UnknownOS;
1425 if ((ostype == llvm::Triple::FreeBSD) || (ostype == llvm::Triple::Linux))
1430 format = default_format;
1434 else if (IsToken (var_name_begin, "x}"))
1436 else if (IsToken (var_name_begin, "X}"))
1438 else if (IsToken (var_name_begin, "u}"))
1444 if (width_precision_length)
1445 format += std::string(width_precision, width_precision_length);
1446 format += specifier;
1458 const SymbolContext *sc,
1459 const ExecutionContext *exe_ctx,
1460 const Address *addr,
1466 ValueObject* realvalobj = NULL; // makes it super-easy to parse pointers
1467 bool success = true;
1469 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1471 for (p = format; *p != '\0'; ++p)
1475 valobj = realvalobj;
1478 size_t non_special_chars = ::strcspn (p, "${}\\");
1479 if (non_special_chars > 0)
1482 s.Write (p, non_special_chars);
1483 p += non_special_chars;
1492 // Start a new scope that must have everything it needs if it is to
1493 // to make it into the final output stream "s". If you want to make
1494 // a format that only prints out the function or symbol name if there
1495 // is one in the symbol context you can use:
1496 // "{function =${function.name}}"
1497 // The first '{' starts a new scope that end with the matching '}' at
1498 // the end of the string. The contents "function =${function.name}"
1499 // will then be evaluated and only be output if there is a function
1500 // or symbol with a valid name.
1501 StreamString sub_strm;
1503 ++p; // Skip the '{'
1505 if (FormatPromptRecurse (p, sc, exe_ctx, addr, sub_strm, &p, valobj))
1507 // The stream had all it needed
1508 s.Write(sub_strm.GetData(), sub_strm.GetSize());
1518 // End of a enclosing scope
1523 // We have a prompt variable to print
1528 const char *var_name_begin = p;
1529 const char *var_name_end = ::strchr (p, '}');
1531 if (var_name_end && var_name_begin < var_name_end)
1533 // if we have already failed to parse, skip this variable
1536 const char *cstr = NULL;
1537 std::string token_format;
1538 Address format_addr;
1539 bool calculate_format_addr_function_offset = false;
1540 // Set reg_kind and reg_num to invalid values
1541 RegisterKind reg_kind = kNumRegisterKinds;
1542 uint32_t reg_num = LLDB_INVALID_REGNUM;
1543 FileSpec format_file_spec;
1544 const RegisterInfo *reg_info = NULL;
1545 RegisterContext *reg_ctx = NULL;
1546 bool do_deref_pointer = false;
1547 ValueObject::ExpressionPathScanEndReason reason_to_stop = ValueObject::eExpressionPathScanEndReasonEndOfString;
1548 ValueObject::ExpressionPathEndResultType final_value_type = ValueObject::eExpressionPathEndResultTypePlain;
1550 // Each variable must set success to true below...
1551 bool var_success = false;
1552 switch (var_name_begin[0])
1562 log->Printf("[Debugger::FormatPrompt] initial string: %s",var_name_begin);
1564 // check for *var and *svar
1565 if (*var_name_begin == '*')
1567 do_deref_pointer = true;
1570 log->Printf("[Debugger::FormatPrompt] found a deref, new string is: %s",var_name_begin);
1573 if (*var_name_begin == 's')
1575 if (!valobj->IsSynthetic())
1576 valobj = valobj->GetSyntheticValue().get();
1581 log->Printf("[Debugger::FormatPrompt] found a synthetic, new string is: %s",var_name_begin);
1584 // should be a 'v' by now
1585 if (*var_name_begin != 'v')
1589 log->Printf("[Debugger::FormatPrompt] string I am working with: %s",var_name_begin);
1591 ValueObject::ExpressionPathAftermath what_next = (do_deref_pointer ?
1592 ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
1593 ValueObject::GetValueForExpressionPathOptions options;
1594 options.DontCheckDotVsArrowSyntax().DoAllowBitfieldSyntax().DoAllowFragileIVar().DoAllowSyntheticChildren();
1595 ValueObject::ValueObjectRepresentationStyle val_obj_display = ValueObject::eValueObjectRepresentationStyleSummary;
1596 ValueObject* target = NULL;
1597 Format custom_format = eFormatInvalid;
1598 const char* var_name_final = NULL;
1599 const char* var_name_final_if_array_range = NULL;
1600 const char* close_bracket_position = NULL;
1601 int64_t index_lower = -1;
1602 int64_t index_higher = -1;
1603 bool is_array_range = false;
1604 const char* first_unparsed;
1605 bool was_plain_var = false;
1606 bool was_var_format = false;
1607 bool was_var_indexed = false;
1610 // simplest case ${var}, just print valobj's value
1611 if (IsToken (var_name_begin, "var}"))
1613 was_plain_var = true;
1615 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1617 else if (IsToken (var_name_begin,"var%"))
1619 was_var_format = true;
1620 // this is a variable with some custom format applied to it
1621 const char* percent_position;
1623 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1624 ScanFormatDescriptor (var_name_begin,
1631 // this is ${var.something} or multiple .something nested
1632 else if (IsToken (var_name_begin, "var"))
1634 if (IsToken (var_name_begin, "var["))
1635 was_var_indexed = true;
1636 const char* percent_position;
1637 ScanFormatDescriptor (var_name_begin,
1644 const char* open_bracket_position;
1645 const char* separator_position;
1646 ScanBracketedRange (var_name_begin,
1649 &open_bracket_position,
1650 &separator_position,
1651 &close_bracket_position,
1652 &var_name_final_if_array_range,
1658 std::string expr_path(var_name_final-var_name_begin-1,0);
1659 memcpy(&expr_path[0], var_name_begin+3,var_name_final-var_name_begin-3);
1662 log->Printf("[Debugger::FormatPrompt] symbol to expand: %s",expr_path.c_str());
1664 target = valobj->GetValueForExpressionPath(expr_path.c_str(),
1674 log->Printf("[Debugger::FormatPrompt] ERROR: unparsed portion = %s, why stopping = %d,"
1675 " final_value_type %d",
1676 first_unparsed, reason_to_stop, final_value_type);
1682 log->Printf("[Debugger::FormatPrompt] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
1683 " final_value_type %d",
1684 first_unparsed, reason_to_stop, final_value_type);
1690 is_array_range = (final_value_type == ValueObject::eExpressionPathEndResultTypeBoundedRange ||
1691 final_value_type == ValueObject::eExpressionPathEndResultTypeUnboundedRange);
1693 do_deref_pointer = (what_next == ValueObject::eExpressionPathAftermathDereference);
1695 if (do_deref_pointer && !is_array_range)
1697 // I have not deref-ed yet, let's do it
1698 // this happens when we are not going through GetValueForVariableExpressionPath
1699 // to get to the target ValueObject
1701 target = target->Dereference(error).get();
1705 log->Printf("[Debugger::FormatPrompt] ERROR: %s\n", error.AsCString("unknown")); \
1708 do_deref_pointer = false;
1711 // we do not want to use the summary for a bitfield of type T:n
1712 // if we were originally dealing with just a T - that would get
1713 // us into an endless recursion
1714 if (target->IsBitfield() && was_var_indexed)
1716 // TODO: check for a (T:n)-specific summary - we should still obey that
1717 StreamString bitfield_name;
1718 bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(), target->GetBitfieldBitSize());
1719 lldb::TypeNameSpecifierImplSP type_sp(new TypeNameSpecifierImpl(bitfield_name.GetData(),false));
1720 if (!DataVisualization::GetSummaryForType(type_sp))
1721 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1724 // TODO use flags for these
1725 const uint32_t type_info_flags = target->GetClangType().GetTypeInfo(NULL);
1726 bool is_array = (type_info_flags & ClangASTType::eTypeIsArray) != 0;
1727 bool is_pointer = (type_info_flags & ClangASTType::eTypeIsPointer) != 0;
1728 bool is_aggregate = target->GetClangType().IsAggregateType();
1730 if ((is_array || is_pointer) && (!is_array_range) && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue) // this should be wrong, but there are some exceptions
1732 StreamString str_temp;
1734 log->Printf("[Debugger::FormatPrompt] I am into array || pointer && !range");
1736 if (target->HasSpecialPrintableRepresentation(val_obj_display, custom_format))
1738 // try to use the special cases
1739 var_success = target->DumpPrintableRepresentation(str_temp,
1743 log->Printf("[Debugger::FormatPrompt] special cases did%s match", var_success ? "" : "n't");
1745 // should not happen
1747 s << str_temp.GetData();
1753 if (was_plain_var) // if ${var}
1755 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
1757 else if (is_pointer) // if pointer, value is the address stored
1759 target->DumpPrintableRepresentation (s,
1762 ValueObject::ePrintableRepresentationSpecialCasesDisable);
1769 // if directly trying to print ${var}, and this is an aggregate, display a nice
1770 // type @ location message
1771 if (is_aggregate && was_plain_var)
1773 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
1778 // if directly trying to print ${var%V}, and this is an aggregate, do not let the user do it
1779 if (is_aggregate && ((was_var_format && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue)))
1781 s << "<invalid use of aggregate type>";
1786 if (!is_array_range)
1789 log->Printf("[Debugger::FormatPrompt] dumping ordinary printable output");
1790 var_success = target->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1795 log->Printf("[Debugger::FormatPrompt] checking if I can handle as array");
1796 if (!is_array && !is_pointer)
1799 log->Printf("[Debugger::FormatPrompt] handle as array");
1800 const char* special_directions = NULL;
1801 StreamString special_directions_writer;
1802 if (close_bracket_position && (var_name_end-close_bracket_position > 1))
1804 ConstString additional_data;
1805 additional_data.SetCStringWithLength(close_bracket_position+1, var_name_end-close_bracket_position-1);
1806 special_directions_writer.Printf("${%svar%s}",
1807 do_deref_pointer ? "*" : "",
1808 additional_data.GetCString());
1809 special_directions = special_directions_writer.GetData();
1812 // let us display items index_lower thru index_higher of this array
1816 if (index_higher < 0)
1817 index_higher = valobj->GetNumChildren() - 1;
1819 uint32_t max_num_children = target->GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();
1821 for (;index_lower<=index_higher;index_lower++)
1823 ValueObject* item = ExpandIndexedExpression (target,
1825 exe_ctx->GetFramePtr(),
1831 log->Printf("[Debugger::FormatPrompt] ERROR in getting child item at index %" PRId64, index_lower);
1836 log->Printf("[Debugger::FormatPrompt] special_directions for child item: %s",special_directions);
1839 if (!special_directions)
1840 var_success &= item->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1842 var_success &= FormatPromptRecurse(special_directions, sc, exe_ctx, addr, s, NULL, item);
1844 if (--max_num_children == 0)
1846 s.PutCString(", ...");
1850 if (index_lower < index_higher)
1858 if (IsToken (var_name_begin, "addr}"))
1860 if (addr && addr->IsValid())
1863 format_addr = *addr;
1869 if (IsToken (var_name_begin, "process."))
1873 Process *process = exe_ctx->GetProcessPtr();
1876 var_name_begin += ::strlen ("process.");
1877 if (IsTokenWithFormat (var_name_begin, "id", token_format, "%" PRIu64, exe_ctx, sc))
1879 s.Printf(token_format.c_str(), process->GetID());
1882 else if ((IsToken (var_name_begin, "name}")) ||
1883 (IsToken (var_name_begin, "file.basename}")) ||
1884 (IsToken (var_name_begin, "file.fullpath}")))
1886 Module *exe_module = process->GetTarget().GetExecutableModulePointer();
1889 if (var_name_begin[0] == 'n' || var_name_begin[5] == 'f')
1891 format_file_spec.GetFilename() = exe_module->GetFileSpec().GetFilename();
1892 var_success = (bool)format_file_spec;
1896 format_file_spec = exe_module->GetFileSpec();
1897 var_success = (bool)format_file_spec;
1901 else if (IsToken (var_name_begin, "script:"))
1903 var_name_begin += ::strlen("script:");
1904 std::string script_name(var_name_begin,var_name_end);
1905 ScriptInterpreter* script_interpreter = process->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
1906 if (RunScriptFormatKeyword (s, script_interpreter, process, script_name))
1915 if (IsToken (var_name_begin, "thread."))
1919 Thread *thread = exe_ctx->GetThreadPtr();
1922 var_name_begin += ::strlen ("thread.");
1923 if (IsTokenWithFormat (var_name_begin, "id", token_format, "0x%4.4" PRIx64, exe_ctx, sc))
1925 s.Printf(token_format.c_str(), thread->GetID());
1928 else if (IsTokenWithFormat (var_name_begin, "protocol_id", token_format, "0x%4.4" PRIx64, exe_ctx, sc))
1930 s.Printf(token_format.c_str(), thread->GetProtocolID());
1933 else if (IsTokenWithFormat (var_name_begin, "index", token_format, "%" PRIu64, exe_ctx, sc))
1935 s.Printf(token_format.c_str(), (uint64_t)thread->GetIndexID());
1938 else if (IsToken (var_name_begin, "name}"))
1940 cstr = thread->GetName();
1941 var_success = cstr && cstr[0];
1945 else if (IsToken (var_name_begin, "queue}"))
1947 cstr = thread->GetQueueName();
1948 var_success = cstr && cstr[0];
1952 else if (IsToken (var_name_begin, "stop-reason}"))
1954 StopInfoSP stop_info_sp = thread->GetStopInfo ();
1955 if (stop_info_sp && stop_info_sp->IsValid())
1957 cstr = stop_info_sp->GetDescription();
1958 if (cstr && cstr[0])
1965 else if (IsToken (var_name_begin, "return-value}"))
1967 StopInfoSP stop_info_sp = thread->GetStopInfo ();
1968 if (stop_info_sp && stop_info_sp->IsValid())
1970 ValueObjectSP return_valobj_sp = StopInfo::GetReturnValueObject (stop_info_sp);
1971 if (return_valobj_sp)
1973 return_valobj_sp->Dump(s);
1978 else if (IsToken (var_name_begin, "script:"))
1980 var_name_begin += ::strlen("script:");
1981 std::string script_name(var_name_begin,var_name_end);
1982 ScriptInterpreter* script_interpreter = thread->GetProcess()->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
1983 if (RunScriptFormatKeyword (s, script_interpreter, thread, script_name))
1989 else if (IsToken (var_name_begin, "target."))
1991 // TODO: hookup properties
1992 // if (!target_properties_sp)
1994 // Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
1996 // target_properties_sp = target->GetProperties();
1999 // if (target_properties_sp)
2001 // var_name_begin += ::strlen ("target.");
2002 // const char *end_property = strchr(var_name_begin, '}');
2003 // if (end_property)
2005 // ConstString property_name(var_name_begin, end_property - var_name_begin);
2006 // std::string property_value (target_properties_sp->GetPropertyValue(property_name));
2007 // if (!property_value.empty())
2009 // s.PutCString (property_value.c_str());
2010 // var_success = true;
2014 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2017 var_name_begin += ::strlen ("target.");
2018 if (IsToken (var_name_begin, "arch}"))
2020 ArchSpec arch (target->GetArchitecture ());
2023 s.PutCString (arch.GetArchitectureName());
2027 else if (IsToken (var_name_begin, "script:"))
2029 var_name_begin += ::strlen("script:");
2030 std::string script_name(var_name_begin,var_name_end);
2031 ScriptInterpreter* script_interpreter = target->GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
2032 if (RunScriptFormatKeyword (s, script_interpreter, target, script_name))
2041 if (IsToken (var_name_begin, "module."))
2043 if (sc && sc->module_sp.get())
2045 Module *module = sc->module_sp.get();
2046 var_name_begin += ::strlen ("module.");
2048 if (IsToken (var_name_begin, "file."))
2050 if (module->GetFileSpec())
2052 var_name_begin += ::strlen ("file.");
2054 if (IsToken (var_name_begin, "basename}"))
2056 format_file_spec.GetFilename() = module->GetFileSpec().GetFilename();
2057 var_success = (bool)format_file_spec;
2059 else if (IsToken (var_name_begin, "fullpath}"))
2061 format_file_spec = module->GetFileSpec();
2062 var_success = (bool)format_file_spec;
2072 if (IsToken (var_name_begin, "file."))
2074 if (sc && sc->comp_unit != NULL)
2076 var_name_begin += ::strlen ("file.");
2078 if (IsToken (var_name_begin, "basename}"))
2080 format_file_spec.GetFilename() = sc->comp_unit->GetFilename();
2081 var_success = (bool)format_file_spec;
2083 else if (IsToken (var_name_begin, "fullpath}"))
2085 format_file_spec = *sc->comp_unit;
2086 var_success = (bool)format_file_spec;
2090 else if (IsToken (var_name_begin, "frame."))
2094 StackFrame *frame = exe_ctx->GetFramePtr();
2097 var_name_begin += ::strlen ("frame.");
2098 if (IsToken (var_name_begin, "index}"))
2100 s.Printf("%u", frame->GetFrameIndex());
2103 else if (IsToken (var_name_begin, "pc}"))
2105 reg_kind = eRegisterKindGeneric;
2106 reg_num = LLDB_REGNUM_GENERIC_PC;
2109 else if (IsToken (var_name_begin, "sp}"))
2111 reg_kind = eRegisterKindGeneric;
2112 reg_num = LLDB_REGNUM_GENERIC_SP;
2115 else if (IsToken (var_name_begin, "fp}"))
2117 reg_kind = eRegisterKindGeneric;
2118 reg_num = LLDB_REGNUM_GENERIC_FP;
2121 else if (IsToken (var_name_begin, "flags}"))
2123 reg_kind = eRegisterKindGeneric;
2124 reg_num = LLDB_REGNUM_GENERIC_FLAGS;
2127 else if (IsToken (var_name_begin, "reg."))
2129 reg_ctx = frame->GetRegisterContext().get();
2132 var_name_begin += ::strlen ("reg.");
2133 if (var_name_begin < var_name_end)
2135 std::string reg_name (var_name_begin, var_name_end);
2136 reg_info = reg_ctx->GetRegisterInfoByName (reg_name.c_str());
2142 else if (IsToken (var_name_begin, "script:"))
2144 var_name_begin += ::strlen("script:");
2145 std::string script_name(var_name_begin,var_name_end);
2146 ScriptInterpreter* script_interpreter = frame->GetThread()->GetProcess()->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
2147 if (RunScriptFormatKeyword (s, script_interpreter, frame, script_name))
2153 else if (IsToken (var_name_begin, "function."))
2155 if (sc && (sc->function != NULL || sc->symbol != NULL))
2157 var_name_begin += ::strlen ("function.");
2158 if (IsToken (var_name_begin, "id}"))
2161 s.Printf("function{0x%8.8" PRIx64 "}", sc->function->GetID());
2163 s.Printf("symbol[%u]", sc->symbol->GetID());
2167 else if (IsToken (var_name_begin, "name}"))
2170 cstr = sc->function->GetName().AsCString (NULL);
2171 else if (sc->symbol)
2172 cstr = sc->symbol->GetName().AsCString (NULL);
2179 Block *inline_block = sc->block->GetContainingInlinedBlock ();
2182 const InlineFunctionInfo *inline_info = sc->block->GetInlinedFunctionInfo();
2185 s.PutCString(" [inlined] ");
2186 inline_info->GetName().Dump(&s);
2193 else if (IsToken (var_name_begin, "name-with-args}"))
2195 // Print the function name with arguments in it
2200 ExecutionContextScope *exe_scope = exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL;
2201 cstr = sc->function->GetName().AsCString (NULL);
2204 const InlineFunctionInfo *inline_info = NULL;
2205 VariableListSP variable_list_sp;
2206 bool get_function_vars = true;
2209 Block *inline_block = sc->block->GetContainingInlinedBlock ();
2213 get_function_vars = false;
2214 inline_info = sc->block->GetInlinedFunctionInfo();
2216 variable_list_sp = inline_block->GetBlockVariableList (true);
2220 if (get_function_vars)
2222 variable_list_sp = sc->function->GetBlock(true).GetBlockVariableList (true);
2227 s.PutCString (cstr);
2228 s.PutCString (" [inlined] ");
2229 cstr = inline_info->GetName().GetCString();
2233 if (variable_list_sp)
2234 variable_list_sp->AppendVariablesWithScope(eValueTypeVariableArgument, args);
2235 if (args.GetSize() > 0)
2237 const char *open_paren = strchr (cstr, '(');
2238 const char *close_paren = NULL;
2241 if (IsToken (open_paren, "(anonymous namespace)"))
2243 open_paren = strchr (open_paren + strlen("(anonymous namespace)"), '(');
2245 close_paren = strchr (open_paren, ')');
2248 close_paren = strchr (open_paren, ')');
2252 s.Write(cstr, open_paren - cstr + 1);
2255 s.PutCString (cstr);
2258 const size_t num_args = args.GetSize();
2259 for (size_t arg_idx = 0; arg_idx < num_args; ++arg_idx)
2261 VariableSP var_sp (args.GetVariableAtIndex (arg_idx));
2262 ValueObjectSP var_value_sp (ValueObjectVariable::Create (exe_scope, var_sp));
2263 const char *var_name = var_value_sp->GetName().GetCString();
2264 const char *var_value = var_value_sp->GetValueAsCString();
2266 s.PutCString (", ");
2267 if (var_value_sp->GetError().Success())
2270 s.Printf ("%s=%s", var_name, var_value);
2272 s.Printf ("%s=%s at %s", var_name, var_value_sp->GetTypeName().GetCString(), var_value_sp->GetLocationAsCString());
2275 s.Printf ("%s=<unavailable>", var_name);
2279 s.PutCString (close_paren);
2290 else if (sc->symbol)
2292 cstr = sc->symbol->GetName().AsCString (NULL);
2300 else if (IsToken (var_name_begin, "addr-offset}"))
2302 var_success = addr != NULL;
2305 format_addr = *addr;
2306 calculate_format_addr_function_offset = true;
2309 else if (IsToken (var_name_begin, "line-offset}"))
2311 var_success = sc->line_entry.range.GetBaseAddress().IsValid();
2314 format_addr = sc->line_entry.range.GetBaseAddress();
2315 calculate_format_addr_function_offset = true;
2318 else if (IsToken (var_name_begin, "pc-offset}"))
2320 StackFrame *frame = exe_ctx->GetFramePtr();
2321 var_success = frame != NULL;
2324 format_addr = frame->GetFrameCodeAddress();
2325 calculate_format_addr_function_offset = true;
2333 if (IsToken (var_name_begin, "line."))
2335 if (sc && sc->line_entry.IsValid())
2337 var_name_begin += ::strlen ("line.");
2338 if (IsToken (var_name_begin, "file."))
2340 var_name_begin += ::strlen ("file.");
2342 if (IsToken (var_name_begin, "basename}"))
2344 format_file_spec.GetFilename() = sc->line_entry.file.GetFilename();
2345 var_success = (bool)format_file_spec;
2347 else if (IsToken (var_name_begin, "fullpath}"))
2349 format_file_spec = sc->line_entry.file;
2350 var_success = (bool)format_file_spec;
2353 else if (IsTokenWithFormat (var_name_begin, "number", token_format, "%" PRIu64, exe_ctx, sc))
2356 s.Printf(token_format.c_str(), (uint64_t)sc->line_entry.line);
2358 else if ((IsToken (var_name_begin, "start-addr}")) ||
2359 (IsToken (var_name_begin, "end-addr}")))
2361 var_success = sc && sc->line_entry.range.GetBaseAddress().IsValid();
2364 format_addr = sc->line_entry.range.GetBaseAddress();
2365 if (var_name_begin[0] == 'e')
2366 format_addr.Slide (sc->line_entry.range.GetByteSize());
2376 // If format addr is valid, then we need to print an address
2377 if (reg_num != LLDB_INVALID_REGNUM)
2379 StackFrame *frame = exe_ctx->GetFramePtr();
2380 // We have a register value to display...
2381 if (reg_num == LLDB_REGNUM_GENERIC_PC && reg_kind == eRegisterKindGeneric)
2383 format_addr = frame->GetFrameCodeAddress();
2387 if (reg_ctx == NULL)
2388 reg_ctx = frame->GetRegisterContext().get();
2392 if (reg_kind != kNumRegisterKinds)
2393 reg_num = reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
2394 reg_info = reg_ctx->GetRegisterInfoAtIndex (reg_num);
2395 var_success = reg_info != NULL;
2400 if (reg_info != NULL)
2402 RegisterValue reg_value;
2403 var_success = reg_ctx->ReadRegister (reg_info, reg_value);
2406 reg_value.Dump(&s, reg_info, false, false, eFormatDefault);
2410 if (format_file_spec)
2412 s << format_file_spec;
2415 // If format addr is valid, then we need to print an address
2416 if (format_addr.IsValid())
2418 var_success = false;
2420 if (calculate_format_addr_function_offset)
2428 func_addr = sc->function->GetAddressRange().GetBaseAddress();
2431 // Check to make sure we aren't in an inline
2432 // function. If we are, use the inline block
2433 // range that contains "format_addr" since
2434 // blocks can be discontiguous.
2435 Block *inline_block = sc->block->GetContainingInlinedBlock ();
2436 AddressRange inline_range;
2437 if (inline_block && inline_block->GetRangeContainingAddress (format_addr, inline_range))
2438 func_addr = inline_range.GetBaseAddress();
2441 else if (sc->symbol && sc->symbol->ValueIsAddress())
2442 func_addr = sc->symbol->GetAddress();
2445 if (func_addr.IsValid())
2447 if (func_addr.GetSection() == format_addr.GetSection())
2449 addr_t func_file_addr = func_addr.GetFileAddress();
2450 addr_t addr_file_addr = format_addr.GetFileAddress();
2451 if (addr_file_addr > func_file_addr)
2452 s.Printf(" + %" PRIu64, addr_file_addr - func_file_addr);
2453 else if (addr_file_addr < func_file_addr)
2454 s.Printf(" - %" PRIu64, func_file_addr - addr_file_addr);
2459 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2462 addr_t func_load_addr = func_addr.GetLoadAddress (target);
2463 addr_t addr_load_addr = format_addr.GetLoadAddress (target);
2464 if (addr_load_addr > func_load_addr)
2465 s.Printf(" + %" PRIu64, addr_load_addr - func_load_addr);
2466 else if (addr_load_addr < func_load_addr)
2467 s.Printf(" - %" PRIu64, func_load_addr - addr_load_addr);
2475 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2476 addr_t vaddr = LLDB_INVALID_ADDRESS;
2477 if (exe_ctx && !target->GetSectionLoadList().IsEmpty())
2478 vaddr = format_addr.GetLoadAddress (target);
2479 if (vaddr == LLDB_INVALID_ADDRESS)
2480 vaddr = format_addr.GetFileAddress ();
2482 if (vaddr != LLDB_INVALID_ADDRESS)
2484 int addr_width = target->GetArchitecture().GetAddressByteSize() * 2;
2485 if (addr_width == 0)
2487 s.Printf("0x%*.*" PRIx64, addr_width, addr_width, vaddr);
2494 if (var_success == false)
2504 // We got a dollar sign with no '{' after it, it must just be a dollar sign
2508 else if (*p == '\\')
2510 ++p; // skip the slash
2513 case 'a': s.PutChar ('\a'); break;
2514 case 'b': s.PutChar ('\b'); break;
2515 case 'f': s.PutChar ('\f'); break;
2516 case 'n': s.PutChar ('\n'); break;
2517 case 'r': s.PutChar ('\r'); break;
2518 case 't': s.PutChar ('\t'); break;
2519 case 'v': s.PutChar ('\v'); break;
2520 case '\'': s.PutChar ('\''); break;
2521 case '\\': s.PutChar ('\\'); break;
2523 // 1 to 3 octal chars
2525 // Make a string that can hold onto the initial zero char,
2526 // up to 3 octal digits, and a terminating NULL.
2527 char oct_str[5] = { 0, 0, 0, 0, 0 };
2530 for (i=0; (p[i] >= '0' && p[i] <= '7') && i<4; ++i)
2533 // We don't want to consume the last octal character since
2534 // the main for loop will do this for us, so we advance p by
2535 // one less than i (even if i is zero)
2537 unsigned long octal_value = ::strtoul (oct_str, NULL, 8);
2538 if (octal_value <= UINT8_MAX)
2540 s.PutChar((char)octal_value);
2546 // hex number in the format
2549 ++p; // Skip the 'x'
2551 // Make a string that can hold onto two hex chars plus a
2553 char hex_str[3] = { 0,0,0 };
2557 ++p; // Skip the first of the two hex chars
2561 unsigned long hex_value = strtoul (hex_str, NULL, 16);
2562 if (hex_value <= UINT8_MAX)
2563 s.PutChar ((char)hex_value);
2572 // Just desensitize any other character by just printing what
2573 // came after the '\'
2587 Debugger::FormatPrompt
2590 const SymbolContext *sc,
2591 const ExecutionContext *exe_ctx,
2592 const Address *addr,
2597 bool use_color = exe_ctx ? exe_ctx->GetTargetRef().GetDebugger().GetUseColor() : true;
2598 std::string format_str = lldb_utility::ansi::FormatAnsiTerminalCodes (format, use_color);
2599 if (format_str.length())
2600 format = format_str.c_str();
2601 return FormatPromptRecurse (format, sc, exe_ctx, addr, s, NULL, valobj);
2605 Debugger::SetLoggingCallback (lldb::LogOutputCallback log_callback, void *baton)
2607 // For simplicity's sake, I am not going to deal with how to close down any
2608 // open logging streams, I just redirect everything from here on out to the
2610 m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
2614 Debugger::EnableLog (const char *channel, const char **categories, const char *log_file, uint32_t log_options, Stream &error_stream)
2616 Log::Callbacks log_callbacks;
2618 StreamSP log_stream_sp;
2619 if (m_log_callback_stream_sp)
2621 log_stream_sp = m_log_callback_stream_sp;
2622 // For now when using the callback mode you always get thread & timestamp.
2623 log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
2625 else if (log_file == NULL || *log_file == '\0')
2627 log_stream_sp.reset(new StreamFile(GetOutputFile().GetDescriptor(), false));
2631 LogStreamMap::iterator pos = m_log_streams.find(log_file);
2632 if (pos != m_log_streams.end())
2633 log_stream_sp = pos->second.lock();
2636 log_stream_sp.reset (new StreamFile (log_file));
2637 m_log_streams[log_file] = log_stream_sp;
2640 assert (log_stream_sp.get());
2642 if (log_options == 0)
2643 log_options = LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
2645 if (Log::GetLogChannelCallbacks (ConstString(channel), log_callbacks))
2647 log_callbacks.enable (log_stream_sp, log_options, categories, &error_stream);
2652 LogChannelSP log_channel_sp (LogChannel::FindPlugin (channel));
2655 if (log_channel_sp->Enable (log_stream_sp, log_options, &error_stream, categories))
2661 error_stream.Printf ("Invalid log channel '%s'.\n", channel);
2667 error_stream.Printf ("Invalid log channel '%s'.\n", channel);
2675 Debugger::GetSourceManager ()
2677 if (m_source_manager_ap.get() == NULL)
2678 m_source_manager_ap.reset (new SourceManager (shared_from_this()));
2679 return *m_source_manager_ap;