1 //===-- Debugger.cpp --------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/lldb-python.h"
11 
12 #include "lldb/API/SBDebugger.h"
13 
14 #include "lldb/Core/Debugger.h"
15 
16 #include <map>
17 
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/Type.h"
20 
21 #include "lldb/lldb-private.h"
22 #include "lldb/Core/ConnectionFileDescriptor.h"
23 #include "lldb/Core/InputReader.h"
24 #include "lldb/Core/Module.h"
25 #include "lldb/Core/PluginManager.h"
26 #include "lldb/Core/RegisterValue.h"
27 #include "lldb/Core/State.h"
28 #include "lldb/Core/StreamAsynchronousIO.h"
29 #include "lldb/Core/StreamCallback.h"
30 #include "lldb/Core/StreamString.h"
31 #include "lldb/Core/Timer.h"
32 #include "lldb/Core/ValueObject.h"
33 #include "lldb/Core/ValueObjectVariable.h"
34 #include "lldb/DataFormatters/DataVisualization.h"
35 #include "lldb/DataFormatters/FormatManager.h"
36 #include "lldb/Host/DynamicLibrary.h"
37 #include "lldb/Host/Terminal.h"
38 #include "lldb/Interpreter/CommandInterpreter.h"
39 #include "lldb/Interpreter/OptionValueSInt64.h"
40 #include "lldb/Interpreter/OptionValueString.h"
41 #include "lldb/Symbol/ClangASTContext.h"
42 #include "lldb/Symbol/CompileUnit.h"
43 #include "lldb/Symbol/Function.h"
44 #include "lldb/Symbol/Symbol.h"
45 #include "lldb/Symbol/VariableList.h"
46 #include "lldb/Target/TargetList.h"
47 #include "lldb/Target/Process.h"
48 #include "lldb/Target/RegisterContext.h"
49 #include "lldb/Target/StopInfo.h"
50 #include "lldb/Target/Thread.h"
51 #include "lldb/Utility/AnsiTerminal.h"
52 
53 using namespace lldb;
54 using namespace lldb_private;
55 
56 
57 static uint32_t g_shared_debugger_refcount = 0;
58 static lldb::user_id_t g_unique_id = 1;
59 
60 #pragma mark Static Functions
61 
62 static Mutex &
63 GetDebuggerListMutex ()
64 {
65     static Mutex g_mutex(Mutex::eMutexTypeRecursive);
66     return g_mutex;
67 }
68 
69 typedef std::vector<DebuggerSP> DebuggerList;
70 
71 static DebuggerList &
72 GetDebuggerList()
73 {
74     // hide the static debugger list inside a singleton accessor to avoid
75     // global init contructors
76     static DebuggerList g_list;
77     return g_list;
78 }
79 
80 OptionEnumValueElement
81 g_show_disassembly_enum_values[] =
82 {
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."},
86     { 0, NULL, NULL }
87 };
88 
89 OptionEnumValueElement
90 g_language_enumerators[] =
91 {
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."},
95     { 0, NULL, NULL }
96 };
97 
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}}"
100 
101 #define DEFAULT_THREAD_FORMAT "thread #${thread.index}: tid = ${thread.id}"\
102     "{, ${frame.pc}}"\
103     MODULE_WITH_FUNC\
104     FILE_AND_LINE\
105     "{, name = '${thread.name}}"\
106     "{, queue = '${thread.queue}}"\
107     "{, stop reason = ${thread.stop-reason}}"\
108     "{\\nReturn value: ${thread.return-value}}"\
109     "\\n"
110 
111 #define DEFAULT_FRAME_FORMAT "frame #${frame.index}: ${frame.pc}"\
112     MODULE_WITH_FUNC\
113     FILE_AND_LINE\
114     "\\n"
115 
116 
117 
118 static PropertyDefinition
119 g_properties[] =
120 {
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 
134     {   NULL,                       OptionValue::eTypeInvalid, true, 0    , NULL, NULL, NULL }
135 };
136 
137 enum
138 {
139     ePropertyAutoConfirm = 0,
140     ePropertyFrameFormat,
141     ePropertyNotiftVoid,
142     ePropertyPrompt,
143     ePropertyScriptLanguage,
144     ePropertyStopDisassemblyCount,
145     ePropertyStopDisassemblyDisplay,
146     ePropertyStopLineCountAfter,
147     ePropertyStopLineCountBefore,
148     ePropertyTerminalWidth,
149     ePropertyThreadFormat,
150     ePropertyUseExternalEditor
151 };
152 
153 //
154 //const char *
155 //Debugger::GetFrameFormat() const
156 //{
157 //    return m_properties_sp->GetFrameFormat();
158 //}
159 //const char *
160 //Debugger::GetThreadFormat() const
161 //{
162 //    return m_properties_sp->GetThreadFormat();
163 //}
164 //
165 
166 
167 Error
168 Debugger::SetPropertyValue (const ExecutionContext *exe_ctx,
169                             VarSetOperationType op,
170                             const char *property_path,
171                             const char *value)
172 {
173     Error error (Properties::SetPropertyValue (exe_ctx, op, property_path, value));
174     if (error.Success())
175     {
176         if (strcmp(property_path, g_properties[ePropertyPrompt].name) == 0)
177         {
178             const char *new_prompt = GetPrompt();
179             EventSP prompt_change_event_sp (new Event(CommandInterpreter::eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));
180             GetCommandInterpreter().BroadcastEvent (prompt_change_event_sp);
181         }
182     }
183     return error;
184 }
185 
186 bool
187 Debugger::GetAutoConfirm () const
188 {
189     const uint32_t idx = ePropertyAutoConfirm;
190     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
191 }
192 
193 const char *
194 Debugger::GetFrameFormat() const
195 {
196     const uint32_t idx = ePropertyFrameFormat;
197     return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
198 }
199 
200 bool
201 Debugger::GetNotifyVoid () const
202 {
203     const uint32_t idx = ePropertyNotiftVoid;
204     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
205 }
206 
207 const char *
208 Debugger::GetPrompt() const
209 {
210     const uint32_t idx = ePropertyPrompt;
211     return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
212 }
213 
214 void
215 Debugger::SetPrompt(const char *p)
216 {
217     const uint32_t idx = ePropertyPrompt;
218     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
219     const char *new_prompt = GetPrompt();
220     EventSP prompt_change_event_sp (new Event(CommandInterpreter::eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));;
221     GetCommandInterpreter().BroadcastEvent (prompt_change_event_sp);
222 }
223 
224 const char *
225 Debugger::GetThreadFormat() const
226 {
227     const uint32_t idx = ePropertyThreadFormat;
228     return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
229 }
230 
231 lldb::ScriptLanguage
232 Debugger::GetScriptLanguage() const
233 {
234     const uint32_t idx = ePropertyScriptLanguage;
235     return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
236 }
237 
238 bool
239 Debugger::SetScriptLanguage (lldb::ScriptLanguage script_lang)
240 {
241     const uint32_t idx = ePropertyScriptLanguage;
242     return m_collection_sp->SetPropertyAtIndexAsEnumeration (NULL, idx, script_lang);
243 }
244 
245 uint32_t
246 Debugger::GetTerminalWidth () const
247 {
248     const uint32_t idx = ePropertyTerminalWidth;
249     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
250 }
251 
252 bool
253 Debugger::SetTerminalWidth (uint32_t term_width)
254 {
255     const uint32_t idx = ePropertyTerminalWidth;
256     return m_collection_sp->SetPropertyAtIndexAsSInt64 (NULL, idx, term_width);
257 }
258 
259 bool
260 Debugger::GetUseExternalEditor () const
261 {
262     const uint32_t idx = ePropertyUseExternalEditor;
263     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
264 }
265 
266 bool
267 Debugger::SetUseExternalEditor (bool b)
268 {
269     const uint32_t idx = ePropertyUseExternalEditor;
270     return m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
271 }
272 
273 uint32_t
274 Debugger::GetStopSourceLineCount (bool before) const
275 {
276     const uint32_t idx = before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
277     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
278 }
279 
280 Debugger::StopDisassemblyType
281 Debugger::GetStopDisassemblyDisplay () const
282 {
283     const uint32_t idx = ePropertyStopDisassemblyDisplay;
284     return (Debugger::StopDisassemblyType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
285 }
286 
287 uint32_t
288 Debugger::GetDisassemblyLineCount () const
289 {
290     const uint32_t idx = ePropertyStopDisassemblyCount;
291     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
292 }
293 
294 #pragma mark Debugger
295 
296 //const DebuggerPropertiesSP &
297 //Debugger::GetSettings() const
298 //{
299 //    return m_properties_sp;
300 //}
301 //
302 
303 int
304 Debugger::TestDebuggerRefCount ()
305 {
306     return g_shared_debugger_refcount;
307 }
308 
309 void
310 Debugger::Initialize ()
311 {
312     if (g_shared_debugger_refcount++ == 0)
313         lldb_private::Initialize();
314 }
315 
316 void
317 Debugger::Terminate ()
318 {
319     if (g_shared_debugger_refcount > 0)
320     {
321         g_shared_debugger_refcount--;
322         if (g_shared_debugger_refcount == 0)
323         {
324             lldb_private::WillTerminate();
325             lldb_private::Terminate();
326 
327             // Clear our master list of debugger objects
328             Mutex::Locker locker (GetDebuggerListMutex ());
329             GetDebuggerList().clear();
330         }
331     }
332 }
333 
334 void
335 Debugger::SettingsInitialize ()
336 {
337     Target::SettingsInitialize ();
338 }
339 
340 void
341 Debugger::SettingsTerminate ()
342 {
343     Target::SettingsTerminate ();
344 }
345 
346 bool
347 Debugger::LoadPlugin (const FileSpec& spec, Error& error)
348 {
349     lldb::DynamicLibrarySP dynlib_sp(new lldb_private::DynamicLibrary(spec));
350     if (!dynlib_sp || dynlib_sp->IsValid() == false)
351     {
352         if (spec.Exists())
353             error.SetErrorString("this file does not represent a loadable dylib");
354         else
355             error.SetErrorString("no such file");
356         return false;
357     }
358     lldb::DebuggerSP debugger_sp(shared_from_this());
359     lldb::SBDebugger debugger_sb(debugger_sp);
360     // TODO: mangle this differently for your system - on OSX, the first underscore needs to be removed and the second one stays
361     LLDBCommandPluginInit init_func = dynlib_sp->GetSymbol<LLDBCommandPluginInit>("_ZN4lldb16PluginInitializeENS_10SBDebuggerE");
362     if (!init_func)
363     {
364         error.SetErrorString("cannot find the initialization function lldb::PluginInitialize(lldb::SBDebugger)");
365         return false;
366     }
367     if (init_func(debugger_sb))
368     {
369         m_loaded_plugins.push_back(dynlib_sp);
370         return true;
371     }
372     error.SetErrorString("dylib refused to be loaded");
373     return false;
374 }
375 
376 static FileSpec::EnumerateDirectoryResult
377 LoadPluginCallback
378 (
379  void *baton,
380  FileSpec::FileType file_type,
381  const FileSpec &file_spec
382  )
383 {
384     Error error;
385 
386     static ConstString g_dylibext("dylib");
387 
388     if (!baton)
389         return FileSpec::eEnumerateDirectoryResultQuit;
390 
391     Debugger *debugger = (Debugger*)baton;
392 
393     // If we have a regular file, a symbolic link or unknown file type, try
394     // and process the file. We must handle unknown as sometimes the directory
395     // enumeration might be enumerating a file system that doesn't have correct
396     // file type information.
397     if (file_type == FileSpec::eFileTypeRegular         ||
398         file_type == FileSpec::eFileTypeSymbolicLink    ||
399         file_type == FileSpec::eFileTypeUnknown          )
400     {
401         FileSpec plugin_file_spec (file_spec);
402         plugin_file_spec.ResolvePath ();
403 
404         if (plugin_file_spec.GetFileNameExtension() != g_dylibext)
405             return FileSpec::eEnumerateDirectoryResultNext;
406 
407         Error plugin_load_error;
408         debugger->LoadPlugin (plugin_file_spec, plugin_load_error);
409 
410         return FileSpec::eEnumerateDirectoryResultNext;
411     }
412 
413     else if (file_type == FileSpec::eFileTypeUnknown     ||
414         file_type == FileSpec::eFileTypeDirectory   ||
415         file_type == FileSpec::eFileTypeSymbolicLink )
416     {
417         // Try and recurse into anything that a directory or symbolic link.
418         // We must also do this for unknown as sometimes the directory enumeration
419         // might be enurating a file system that doesn't have correct file type
420         // information.
421         return FileSpec::eEnumerateDirectoryResultEnter;
422     }
423 
424     return FileSpec::eEnumerateDirectoryResultNext;
425 }
426 
427 void
428 Debugger::InstanceInitialize ()
429 {
430     FileSpec dir_spec;
431     const bool find_directories = true;
432     const bool find_files = true;
433     const bool find_other = true;
434     char dir_path[PATH_MAX];
435     if (Host::GetLLDBPath (ePathTypeLLDBSystemPlugins, dir_spec))
436     {
437         if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
438         {
439             FileSpec::EnumerateDirectory (dir_path,
440                                           find_directories,
441                                           find_files,
442                                           find_other,
443                                           LoadPluginCallback,
444                                           this);
445         }
446     }
447 
448     if (Host::GetLLDBPath (ePathTypeLLDBUserPlugins, dir_spec))
449     {
450         if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
451         {
452             FileSpec::EnumerateDirectory (dir_path,
453                                           find_directories,
454                                           find_files,
455                                           find_other,
456                                           LoadPluginCallback,
457                                           this);
458         }
459     }
460 
461     PluginManager::DebuggerInitialize (*this);
462 }
463 
464 DebuggerSP
465 Debugger::CreateInstance (lldb::LogOutputCallback log_callback, void *baton)
466 {
467     DebuggerSP debugger_sp (new Debugger(log_callback, baton));
468     if (g_shared_debugger_refcount > 0)
469     {
470         Mutex::Locker locker (GetDebuggerListMutex ());
471         GetDebuggerList().push_back(debugger_sp);
472     }
473     debugger_sp->InstanceInitialize ();
474     return debugger_sp;
475 }
476 
477 void
478 Debugger::Destroy (DebuggerSP &debugger_sp)
479 {
480     if (debugger_sp.get() == NULL)
481         return;
482 
483     debugger_sp->Clear();
484 
485     if (g_shared_debugger_refcount > 0)
486     {
487         Mutex::Locker locker (GetDebuggerListMutex ());
488         DebuggerList &debugger_list = GetDebuggerList ();
489         DebuggerList::iterator pos, end = debugger_list.end();
490         for (pos = debugger_list.begin (); pos != end; ++pos)
491         {
492             if ((*pos).get() == debugger_sp.get())
493             {
494                 debugger_list.erase (pos);
495                 return;
496             }
497         }
498     }
499 }
500 
501 DebuggerSP
502 Debugger::FindDebuggerWithInstanceName (const ConstString &instance_name)
503 {
504     DebuggerSP debugger_sp;
505     if (g_shared_debugger_refcount > 0)
506     {
507         Mutex::Locker locker (GetDebuggerListMutex ());
508         DebuggerList &debugger_list = GetDebuggerList();
509         DebuggerList::iterator pos, end = debugger_list.end();
510 
511         for (pos = debugger_list.begin(); pos != end; ++pos)
512         {
513             if ((*pos).get()->m_instance_name == instance_name)
514             {
515                 debugger_sp = *pos;
516                 break;
517             }
518         }
519     }
520     return debugger_sp;
521 }
522 
523 TargetSP
524 Debugger::FindTargetWithProcessID (lldb::pid_t pid)
525 {
526     TargetSP target_sp;
527     if (g_shared_debugger_refcount > 0)
528     {
529         Mutex::Locker locker (GetDebuggerListMutex ());
530         DebuggerList &debugger_list = GetDebuggerList();
531         DebuggerList::iterator pos, end = debugger_list.end();
532         for (pos = debugger_list.begin(); pos != end; ++pos)
533         {
534             target_sp = (*pos)->GetTargetList().FindTargetWithProcessID (pid);
535             if (target_sp)
536                 break;
537         }
538     }
539     return target_sp;
540 }
541 
542 TargetSP
543 Debugger::FindTargetWithProcess (Process *process)
544 {
545     TargetSP target_sp;
546     if (g_shared_debugger_refcount > 0)
547     {
548         Mutex::Locker locker (GetDebuggerListMutex ());
549         DebuggerList &debugger_list = GetDebuggerList();
550         DebuggerList::iterator pos, end = debugger_list.end();
551         for (pos = debugger_list.begin(); pos != end; ++pos)
552         {
553             target_sp = (*pos)->GetTargetList().FindTargetWithProcess (process);
554             if (target_sp)
555                 break;
556         }
557     }
558     return target_sp;
559 }
560 
561 Debugger::Debugger (lldb::LogOutputCallback log_callback, void *baton) :
562     UserID (g_unique_id++),
563     Properties(OptionValuePropertiesSP(new OptionValueProperties())),
564     m_input_comm("debugger.input"),
565     m_input_file (),
566     m_output_file (),
567     m_error_file (),
568     m_terminal_state (),
569     m_target_list (*this),
570     m_platform_list (),
571     m_listener ("lldb.Debugger"),
572     m_source_manager_ap(),
573     m_source_file_cache(),
574     m_command_interpreter_ap (new CommandInterpreter (*this, eScriptLanguageDefault, false)),
575     m_input_reader_stack (),
576     m_input_reader_data (),
577     m_instance_name()
578 {
579     char instance_cstr[256];
580     snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
581     m_instance_name.SetCString(instance_cstr);
582     if (log_callback)
583         m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
584     m_command_interpreter_ap->Initialize ();
585     // Always add our default platform to the platform list
586     PlatformSP default_platform_sp (Platform::GetDefaultPlatform());
587     assert (default_platform_sp.get());
588     m_platform_list.Append (default_platform_sp, true);
589 
590     m_collection_sp->Initialize (g_properties);
591     m_collection_sp->AppendProperty (ConstString("target"),
592                                      ConstString("Settings specify to debugging targets."),
593                                      true,
594                                      Target::GetGlobalProperties()->GetValueProperties());
595     if (m_command_interpreter_ap.get())
596     {
597         m_collection_sp->AppendProperty (ConstString("interpreter"),
598                                          ConstString("Settings specify to the debugger's command interpreter."),
599                                          true,
600                                          m_command_interpreter_ap->GetValueProperties());
601     }
602     OptionValueSInt64 *term_width = m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64 (NULL, ePropertyTerminalWidth);
603     term_width->SetMinimumValue(10);
604     term_width->SetMaximumValue(1024);
605 }
606 
607 Debugger::~Debugger ()
608 {
609     Clear();
610 }
611 
612 void
613 Debugger::Clear()
614 {
615     CleanUpInputReaders();
616     m_listener.Clear();
617     int num_targets = m_target_list.GetNumTargets();
618     for (int i = 0; i < num_targets; i++)
619     {
620         TargetSP target_sp (m_target_list.GetTargetAtIndex (i));
621         if (target_sp)
622         {
623             ProcessSP process_sp (target_sp->GetProcessSP());
624             if (process_sp)
625                 process_sp->Finalize();
626             target_sp->Destroy();
627         }
628     }
629     BroadcasterManager::Clear ();
630 
631     // Close the input file _before_ we close the input read communications class
632     // as it does NOT own the input file, our m_input_file does.
633     m_terminal_state.Clear();
634     GetInputFile().Close ();
635     // Now that we have closed m_input_file, we can now tell our input communication
636     // class to close down. Its read thread should quickly exit after we close
637     // the input file handle above.
638     m_input_comm.Clear ();
639 }
640 
641 bool
642 Debugger::GetCloseInputOnEOF () const
643 {
644     return m_input_comm.GetCloseOnEOF();
645 }
646 
647 void
648 Debugger::SetCloseInputOnEOF (bool b)
649 {
650     m_input_comm.SetCloseOnEOF(b);
651 }
652 
653 bool
654 Debugger::GetAsyncExecution ()
655 {
656     return !m_command_interpreter_ap->GetSynchronous();
657 }
658 
659 void
660 Debugger::SetAsyncExecution (bool async_execution)
661 {
662     m_command_interpreter_ap->SetSynchronous (!async_execution);
663 }
664 
665 
666 void
667 Debugger::SetInputFileHandle (FILE *fh, bool tranfer_ownership)
668 {
669     File &in_file = GetInputFile();
670     in_file.SetStream (fh, tranfer_ownership);
671     if (in_file.IsValid() == false)
672         in_file.SetStream (stdin, true);
673 
674     // Disconnect from any old connection if we had one
675     m_input_comm.Disconnect ();
676     // Pass false as the second argument to ConnectionFileDescriptor below because
677     // our "in_file" above will already take ownership if requested and we don't
678     // want to objects trying to own and close a file descriptor.
679     m_input_comm.SetConnection (new ConnectionFileDescriptor (in_file.GetDescriptor(), false));
680     m_input_comm.SetReadThreadBytesReceivedCallback (Debugger::DispatchInputCallback, this);
681 
682     // Save away the terminal state if that is relevant, so that we can restore it in RestoreInputState.
683     SaveInputTerminalState ();
684 
685     Error error;
686     if (m_input_comm.StartReadThread (&error) == false)
687     {
688         File &err_file = GetErrorFile();
689 
690         err_file.Printf ("error: failed to main input read thread: %s", error.AsCString() ? error.AsCString() : "unkown error");
691         exit(1);
692     }
693 }
694 
695 void
696 Debugger::SetOutputFileHandle (FILE *fh, bool tranfer_ownership)
697 {
698     File &out_file = GetOutputFile();
699     out_file.SetStream (fh, tranfer_ownership);
700     if (out_file.IsValid() == false)
701         out_file.SetStream (stdout, false);
702 
703     // do not create the ScriptInterpreter just for setting the output file handle
704     // as the constructor will know how to do the right thing on its own
705     const bool can_create = false;
706     ScriptInterpreter* script_interpreter = GetCommandInterpreter().GetScriptInterpreter(can_create);
707     if (script_interpreter)
708         script_interpreter->ResetOutputFileHandle (fh);
709 }
710 
711 void
712 Debugger::SetErrorFileHandle (FILE *fh, bool tranfer_ownership)
713 {
714     File &err_file = GetErrorFile();
715     err_file.SetStream (fh, tranfer_ownership);
716     if (err_file.IsValid() == false)
717         err_file.SetStream (stderr, false);
718 }
719 
720 void
721 Debugger::SaveInputTerminalState ()
722 {
723     File &in_file = GetInputFile();
724     if (in_file.GetDescriptor() != File::kInvalidDescriptor)
725         m_terminal_state.Save(in_file.GetDescriptor(), true);
726 }
727 
728 void
729 Debugger::RestoreInputTerminalState ()
730 {
731     m_terminal_state.Restore();
732 }
733 
734 ExecutionContext
735 Debugger::GetSelectedExecutionContext ()
736 {
737     ExecutionContext exe_ctx;
738     TargetSP target_sp(GetSelectedTarget());
739     exe_ctx.SetTargetSP (target_sp);
740 
741     if (target_sp)
742     {
743         ProcessSP process_sp (target_sp->GetProcessSP());
744         exe_ctx.SetProcessSP (process_sp);
745         if (process_sp && process_sp->IsRunning() == false)
746         {
747             ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
748             if (thread_sp)
749             {
750                 exe_ctx.SetThreadSP (thread_sp);
751                 exe_ctx.SetFrameSP (thread_sp->GetSelectedFrame());
752                 if (exe_ctx.GetFramePtr() == NULL)
753                     exe_ctx.SetFrameSP (thread_sp->GetStackFrameAtIndex (0));
754             }
755         }
756     }
757     return exe_ctx;
758 
759 }
760 
761 InputReaderSP
762 Debugger::GetCurrentInputReader ()
763 {
764     InputReaderSP reader_sp;
765 
766     if (!m_input_reader_stack.IsEmpty())
767     {
768         // Clear any finished readers from the stack
769         while (CheckIfTopInputReaderIsDone()) ;
770 
771         if (!m_input_reader_stack.IsEmpty())
772             reader_sp = m_input_reader_stack.Top();
773     }
774 
775     return reader_sp;
776 }
777 
778 void
779 Debugger::DispatchInputCallback (void *baton, const void *bytes, size_t bytes_len)
780 {
781     if (bytes_len > 0)
782         ((Debugger *)baton)->DispatchInput ((char *)bytes, bytes_len);
783     else
784         ((Debugger *)baton)->DispatchInputEndOfFile ();
785 }
786 
787 
788 void
789 Debugger::DispatchInput (const char *bytes, size_t bytes_len)
790 {
791     if (bytes == NULL || bytes_len == 0)
792         return;
793 
794     WriteToDefaultReader (bytes, bytes_len);
795 }
796 
797 void
798 Debugger::DispatchInputInterrupt ()
799 {
800     m_input_reader_data.clear();
801 
802     InputReaderSP reader_sp (GetCurrentInputReader ());
803     if (reader_sp)
804     {
805         reader_sp->Notify (eInputReaderInterrupt);
806 
807         // If notifying the reader of the interrupt finished the reader, we should pop it off the stack.
808         while (CheckIfTopInputReaderIsDone ()) ;
809     }
810 }
811 
812 void
813 Debugger::DispatchInputEndOfFile ()
814 {
815     m_input_reader_data.clear();
816 
817     InputReaderSP reader_sp (GetCurrentInputReader ());
818     if (reader_sp)
819     {
820         reader_sp->Notify (eInputReaderEndOfFile);
821 
822         // If notifying the reader of the end-of-file finished the reader, we should pop it off the stack.
823         while (CheckIfTopInputReaderIsDone ()) ;
824     }
825 }
826 
827 void
828 Debugger::CleanUpInputReaders ()
829 {
830     m_input_reader_data.clear();
831 
832     // The bottom input reader should be the main debugger input reader.  We do not want to close that one here.
833     while (m_input_reader_stack.GetSize() > 1)
834     {
835         InputReaderSP reader_sp (GetCurrentInputReader ());
836         if (reader_sp)
837         {
838             reader_sp->Notify (eInputReaderEndOfFile);
839             reader_sp->SetIsDone (true);
840         }
841     }
842 }
843 
844 void
845 Debugger::NotifyTopInputReader (InputReaderAction notification)
846 {
847     InputReaderSP reader_sp (GetCurrentInputReader());
848     if (reader_sp)
849 	{
850         reader_sp->Notify (notification);
851 
852         // Flush out any input readers that are done.
853         while (CheckIfTopInputReaderIsDone ())
854             /* Do nothing. */;
855     }
856 }
857 
858 bool
859 Debugger::InputReaderIsTopReader (const InputReaderSP& reader_sp)
860 {
861     InputReaderSP top_reader_sp (GetCurrentInputReader());
862 
863     return (reader_sp.get() == top_reader_sp.get());
864 }
865 
866 
867 void
868 Debugger::WriteToDefaultReader (const char *bytes, size_t bytes_len)
869 {
870     if (bytes && bytes_len)
871         m_input_reader_data.append (bytes, bytes_len);
872 
873     if (m_input_reader_data.empty())
874         return;
875 
876     while (!m_input_reader_stack.IsEmpty() && !m_input_reader_data.empty())
877     {
878         // Get the input reader from the top of the stack
879         InputReaderSP reader_sp (GetCurrentInputReader ());
880         if (!reader_sp)
881             break;
882 
883         size_t bytes_handled = reader_sp->HandleRawBytes (m_input_reader_data.c_str(),
884                                                           m_input_reader_data.size());
885         if (bytes_handled)
886         {
887             m_input_reader_data.erase (0, bytes_handled);
888         }
889         else
890         {
891             // No bytes were handled, we might not have reached our
892             // granularity, just return and wait for more data
893             break;
894         }
895     }
896 
897     // Flush out any input readers that are done.
898     while (CheckIfTopInputReaderIsDone ())
899         /* Do nothing. */;
900 
901 }
902 
903 void
904 Debugger::PushInputReader (const InputReaderSP& reader_sp)
905 {
906     if (!reader_sp)
907         return;
908 
909     // Deactivate the old top reader
910     InputReaderSP top_reader_sp (GetCurrentInputReader ());
911 
912     if (top_reader_sp)
913         top_reader_sp->Notify (eInputReaderDeactivate);
914 
915     m_input_reader_stack.Push (reader_sp);
916     reader_sp->Notify (eInputReaderActivate);
917     ActivateInputReader (reader_sp);
918 }
919 
920 bool
921 Debugger::PopInputReader (const InputReaderSP& pop_reader_sp)
922 {
923     bool result = false;
924 
925     // The reader on the stop of the stack is done, so let the next
926     // read on the stack referesh its prompt and if there is one...
927     if (!m_input_reader_stack.IsEmpty())
928     {
929         // Cannot call GetCurrentInputReader here, as that would cause an infinite loop.
930         InputReaderSP reader_sp(m_input_reader_stack.Top());
931 
932         if (!pop_reader_sp || pop_reader_sp.get() == reader_sp.get())
933         {
934             m_input_reader_stack.Pop ();
935             reader_sp->Notify (eInputReaderDeactivate);
936             reader_sp->Notify (eInputReaderDone);
937             result = true;
938 
939             if (!m_input_reader_stack.IsEmpty())
940             {
941                 reader_sp = m_input_reader_stack.Top();
942                 if (reader_sp)
943                 {
944                     ActivateInputReader (reader_sp);
945                     reader_sp->Notify (eInputReaderReactivate);
946                 }
947             }
948         }
949     }
950     return result;
951 }
952 
953 bool
954 Debugger::CheckIfTopInputReaderIsDone ()
955 {
956     bool result = false;
957     if (!m_input_reader_stack.IsEmpty())
958     {
959         // Cannot call GetCurrentInputReader here, as that would cause an infinite loop.
960         InputReaderSP reader_sp(m_input_reader_stack.Top());
961 
962         if (reader_sp && reader_sp->IsDone())
963         {
964             result = true;
965             PopInputReader (reader_sp);
966         }
967     }
968     return result;
969 }
970 
971 void
972 Debugger::ActivateInputReader (const InputReaderSP &reader_sp)
973 {
974     int input_fd = m_input_file.GetFile().GetDescriptor();
975 
976     if (input_fd >= 0)
977     {
978         Terminal tty(input_fd);
979 
980         tty.SetEcho(reader_sp->GetEcho());
981 
982         switch (reader_sp->GetGranularity())
983         {
984         case eInputReaderGranularityByte:
985         case eInputReaderGranularityWord:
986             tty.SetCanonical (false);
987             break;
988 
989         case eInputReaderGranularityLine:
990         case eInputReaderGranularityAll:
991             tty.SetCanonical (true);
992             break;
993 
994         default:
995             break;
996         }
997     }
998 }
999 
1000 StreamSP
1001 Debugger::GetAsyncOutputStream ()
1002 {
1003     return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
1004                                                CommandInterpreter::eBroadcastBitAsynchronousOutputData));
1005 }
1006 
1007 StreamSP
1008 Debugger::GetAsyncErrorStream ()
1009 {
1010     return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
1011                                                CommandInterpreter::eBroadcastBitAsynchronousErrorData));
1012 }
1013 
1014 size_t
1015 Debugger::GetNumDebuggers()
1016 {
1017     if (g_shared_debugger_refcount > 0)
1018     {
1019         Mutex::Locker locker (GetDebuggerListMutex ());
1020         return GetDebuggerList().size();
1021     }
1022     return 0;
1023 }
1024 
1025 lldb::DebuggerSP
1026 Debugger::GetDebuggerAtIndex (size_t index)
1027 {
1028     DebuggerSP debugger_sp;
1029 
1030     if (g_shared_debugger_refcount > 0)
1031     {
1032         Mutex::Locker locker (GetDebuggerListMutex ());
1033         DebuggerList &debugger_list = GetDebuggerList();
1034 
1035         if (index < debugger_list.size())
1036             debugger_sp = debugger_list[index];
1037     }
1038 
1039     return debugger_sp;
1040 }
1041 
1042 DebuggerSP
1043 Debugger::FindDebuggerWithID (lldb::user_id_t id)
1044 {
1045     DebuggerSP debugger_sp;
1046 
1047     if (g_shared_debugger_refcount > 0)
1048     {
1049         Mutex::Locker locker (GetDebuggerListMutex ());
1050         DebuggerList &debugger_list = GetDebuggerList();
1051         DebuggerList::iterator pos, end = debugger_list.end();
1052         for (pos = debugger_list.begin(); pos != end; ++pos)
1053         {
1054             if ((*pos).get()->GetID() == id)
1055             {
1056                 debugger_sp = *pos;
1057                 break;
1058             }
1059         }
1060     }
1061     return debugger_sp;
1062 }
1063 
1064 static void
1065 TestPromptFormats (StackFrame *frame)
1066 {
1067     if (frame == NULL)
1068         return;
1069 
1070     StreamString s;
1071     const char *prompt_format =
1072     "{addr = '${addr}'\n}"
1073     "{process.id = '${process.id}'\n}"
1074     "{process.name = '${process.name}'\n}"
1075     "{process.file.basename = '${process.file.basename}'\n}"
1076     "{process.file.fullpath = '${process.file.fullpath}'\n}"
1077     "{thread.id = '${thread.id}'\n}"
1078     "{thread.index = '${thread.index}'\n}"
1079     "{thread.name = '${thread.name}'\n}"
1080     "{thread.queue = '${thread.queue}'\n}"
1081     "{thread.stop-reason = '${thread.stop-reason}'\n}"
1082     "{target.arch = '${target.arch}'\n}"
1083     "{module.file.basename = '${module.file.basename}'\n}"
1084     "{module.file.fullpath = '${module.file.fullpath}'\n}"
1085     "{file.basename = '${file.basename}'\n}"
1086     "{file.fullpath = '${file.fullpath}'\n}"
1087     "{frame.index = '${frame.index}'\n}"
1088     "{frame.pc = '${frame.pc}'\n}"
1089     "{frame.sp = '${frame.sp}'\n}"
1090     "{frame.fp = '${frame.fp}'\n}"
1091     "{frame.flags = '${frame.flags}'\n}"
1092     "{frame.reg.rdi = '${frame.reg.rdi}'\n}"
1093     "{frame.reg.rip = '${frame.reg.rip}'\n}"
1094     "{frame.reg.rsp = '${frame.reg.rsp}'\n}"
1095     "{frame.reg.rbp = '${frame.reg.rbp}'\n}"
1096     "{frame.reg.rflags = '${frame.reg.rflags}'\n}"
1097     "{frame.reg.xmm0 = '${frame.reg.xmm0}'\n}"
1098     "{frame.reg.carp = '${frame.reg.carp}'\n}"
1099     "{function.id = '${function.id}'\n}"
1100     "{function.name = '${function.name}'\n}"
1101     "{function.name-with-args = '${function.name-with-args}'\n}"
1102     "{function.addr-offset = '${function.addr-offset}'\n}"
1103     "{function.line-offset = '${function.line-offset}'\n}"
1104     "{function.pc-offset = '${function.pc-offset}'\n}"
1105     "{line.file.basename = '${line.file.basename}'\n}"
1106     "{line.file.fullpath = '${line.file.fullpath}'\n}"
1107     "{line.number = '${line.number}'\n}"
1108     "{line.start-addr = '${line.start-addr}'\n}"
1109     "{line.end-addr = '${line.end-addr}'\n}"
1110 ;
1111 
1112     SymbolContext sc (frame->GetSymbolContext(eSymbolContextEverything));
1113     ExecutionContext exe_ctx;
1114     frame->CalculateExecutionContext(exe_ctx);
1115     const char *end = NULL;
1116     if (Debugger::FormatPrompt (prompt_format, &sc, &exe_ctx, &sc.line_entry.range.GetBaseAddress(), s, &end))
1117     {
1118         printf("%s\n", s.GetData());
1119     }
1120     else
1121     {
1122         printf ("error: at '%s'\n", end);
1123         printf ("what we got: %s\n", s.GetData());
1124     }
1125 }
1126 
1127 static bool
1128 ScanFormatDescriptor (const char* var_name_begin,
1129                       const char* var_name_end,
1130                       const char** var_name_final,
1131                       const char** percent_position,
1132                       Format* custom_format,
1133                       ValueObject::ValueObjectRepresentationStyle* val_obj_display)
1134 {
1135     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1136     *percent_position = ::strchr(var_name_begin,'%');
1137     if (!*percent_position || *percent_position > var_name_end)
1138     {
1139         if (log)
1140             log->Printf("[ScanFormatDescriptor] no format descriptor in string, skipping");
1141         *var_name_final = var_name_end;
1142     }
1143     else
1144     {
1145         *var_name_final = *percent_position;
1146         std::string format_name(*var_name_final+1, var_name_end-*var_name_final-1);
1147         if (log)
1148             log->Printf("ScanFormatDescriptor] parsing %s as a format descriptor", format_name.c_str());
1149         if ( !FormatManager::GetFormatFromCString(format_name.c_str(),
1150                                                   true,
1151                                                   *custom_format) )
1152         {
1153             if (log)
1154                 log->Printf("ScanFormatDescriptor] %s is an unknown format", format_name.c_str());
1155 
1156             switch (format_name.front())
1157             {
1158                 case '@':             // if this is an @ sign, print ObjC description
1159                     *val_obj_display = ValueObject::eValueObjectRepresentationStyleLanguageSpecific;
1160                     break;
1161                 case 'V': // if this is a V, print the value using the default format
1162                     *val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1163                     break;
1164                 case 'L': // if this is an L, print the location of the value
1165                     *val_obj_display = ValueObject::eValueObjectRepresentationStyleLocation;
1166                     break;
1167                 case 'S': // if this is an S, print the summary after all
1168                     *val_obj_display = ValueObject::eValueObjectRepresentationStyleSummary;
1169                     break;
1170                 case '#': // if this is a '#', print the number of children
1171                     *val_obj_display = ValueObject::eValueObjectRepresentationStyleChildrenCount;
1172                     break;
1173                 case 'T': // if this is a 'T', print the type
1174                     *val_obj_display = ValueObject::eValueObjectRepresentationStyleType;
1175                     break;
1176                 default:
1177                     log->Printf("ScanFormatDescriptor] %s is an error, leaving the previous value alone", format_name.c_str());
1178                     break;
1179             }
1180         }
1181         // a good custom format tells us to print the value using it
1182         else
1183         {
1184             if (log)
1185                 log->Printf("ScanFormatDescriptor] will display value for this VO");
1186             *val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1187         }
1188     }
1189     if (log)
1190         log->Printf("ScanFormatDescriptor] final format description outcome: custom_format = %d, val_obj_display = %d",
1191                     *custom_format,
1192                     *val_obj_display);
1193     return true;
1194 }
1195 
1196 static bool
1197 ScanBracketedRange (const char* var_name_begin,
1198                     const char* var_name_end,
1199                     const char* var_name_final,
1200                     const char** open_bracket_position,
1201                     const char** separator_position,
1202                     const char** close_bracket_position,
1203                     const char** var_name_final_if_array_range,
1204                     int64_t* index_lower,
1205                     int64_t* index_higher)
1206 {
1207     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1208     *open_bracket_position = ::strchr(var_name_begin,'[');
1209     if (*open_bracket_position && *open_bracket_position < var_name_final)
1210     {
1211         *separator_position = ::strchr(*open_bracket_position,'-'); // might be NULL if this is a simple var[N] bitfield
1212         *close_bracket_position = ::strchr(*open_bracket_position,']');
1213         // as usual, we assume that [] will come before %
1214         //printf("trying to expand a []\n");
1215         *var_name_final_if_array_range = *open_bracket_position;
1216         if (*close_bracket_position - *open_bracket_position == 1)
1217         {
1218             if (log)
1219                 log->Printf("[ScanBracketedRange] '[]' detected.. going from 0 to end of data");
1220             *index_lower = 0;
1221         }
1222         else if (*separator_position == NULL || *separator_position > var_name_end)
1223         {
1224             char *end = NULL;
1225             *index_lower = ::strtoul (*open_bracket_position+1, &end, 0);
1226             *index_higher = *index_lower;
1227             if (log)
1228                 log->Printf("[ScanBracketedRange] [%" PRId64 "] detected, high index is same", *index_lower);
1229         }
1230         else if (*close_bracket_position && *close_bracket_position < var_name_end)
1231         {
1232             char *end = NULL;
1233             *index_lower = ::strtoul (*open_bracket_position+1, &end, 0);
1234             *index_higher = ::strtoul (*separator_position+1, &end, 0);
1235             if (log)
1236                 log->Printf("[ScanBracketedRange] [%" PRId64 "-%" PRId64 "] detected", *index_lower, *index_higher);
1237         }
1238         else
1239         {
1240             if (log)
1241                 log->Printf("[ScanBracketedRange] expression is erroneous, cannot extract indices out of it");
1242             return false;
1243         }
1244         if (*index_lower > *index_higher && *index_higher > 0)
1245         {
1246             if (log)
1247                 log->Printf("[ScanBracketedRange] swapping indices");
1248             int64_t temp = *index_lower;
1249             *index_lower = *index_higher;
1250             *index_higher = temp;
1251         }
1252     }
1253     else if (log)
1254             log->Printf("[ScanBracketedRange] no bracketed range, skipping entirely");
1255     return true;
1256 }
1257 
1258 static ValueObjectSP
1259 ExpandIndexedExpression (ValueObject* valobj,
1260                          size_t index,
1261                          StackFrame* frame,
1262                          bool deref_pointer)
1263 {
1264     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1265     const char* ptr_deref_format = "[%d]";
1266     std::string ptr_deref_buffer(10,0);
1267     ::sprintf(&ptr_deref_buffer[0], ptr_deref_format, index);
1268     if (log)
1269         log->Printf("[ExpandIndexedExpression] name to deref: %s",ptr_deref_buffer.c_str());
1270     const char* first_unparsed;
1271     ValueObject::GetValueForExpressionPathOptions options;
1272     ValueObject::ExpressionPathEndResultType final_value_type;
1273     ValueObject::ExpressionPathScanEndReason reason_to_stop;
1274     ValueObject::ExpressionPathAftermath what_next = (deref_pointer ? ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
1275     ValueObjectSP item = valobj->GetValueForExpressionPath (ptr_deref_buffer.c_str(),
1276                                                           &first_unparsed,
1277                                                           &reason_to_stop,
1278                                                           &final_value_type,
1279                                                           options,
1280                                                           &what_next);
1281     if (!item)
1282     {
1283         if (log)
1284             log->Printf("[ExpandIndexedExpression] ERROR: unparsed portion = %s, why stopping = %d,"
1285                " final_value_type %d",
1286                first_unparsed, reason_to_stop, final_value_type);
1287     }
1288     else
1289     {
1290         if (log)
1291             log->Printf("[ExpandIndexedExpression] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
1292                " final_value_type %d",
1293                first_unparsed, reason_to_stop, final_value_type);
1294     }
1295     return item;
1296 }
1297 
1298 bool
1299 Debugger::FormatPrompt
1300 (
1301     const char *format,
1302     const SymbolContext *sc,
1303     const ExecutionContext *exe_ctx,
1304     const Address *addr,
1305     Stream &s,
1306     const char **end,
1307     ValueObject* valobj
1308 )
1309 {
1310     ValueObject* realvalobj = NULL; // makes it super-easy to parse pointers
1311     bool success = true;
1312     const char *p;
1313     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1314     for (p = format; *p != '\0'; ++p)
1315     {
1316         if (realvalobj)
1317         {
1318             valobj = realvalobj;
1319             realvalobj = NULL;
1320         }
1321         size_t non_special_chars = ::strcspn (p, "${}\\");
1322         if (non_special_chars > 0)
1323         {
1324             if (success)
1325                 s.Write (p, non_special_chars);
1326             p += non_special_chars;
1327         }
1328 
1329         if (*p == '\0')
1330         {
1331             break;
1332         }
1333         else if (*p == '{')
1334         {
1335             // Start a new scope that must have everything it needs if it is to
1336             // to make it into the final output stream "s". If you want to make
1337             // a format that only prints out the function or symbol name if there
1338             // is one in the symbol context you can use:
1339             //      "{function =${function.name}}"
1340             // The first '{' starts a new scope that end with the matching '}' at
1341             // the end of the string. The contents "function =${function.name}"
1342             // will then be evaluated and only be output if there is a function
1343             // or symbol with a valid name.
1344             StreamString sub_strm;
1345 
1346             ++p;  // Skip the '{'
1347 
1348             if (FormatPrompt (p, sc, exe_ctx, addr, sub_strm, &p, valobj))
1349             {
1350                 // The stream had all it needed
1351                 s.Write(sub_strm.GetData(), sub_strm.GetSize());
1352             }
1353             if (*p != '}')
1354             {
1355                 success = false;
1356                 break;
1357             }
1358         }
1359         else if (*p == '}')
1360         {
1361             // End of a enclosing scope
1362             break;
1363         }
1364         else if (*p == '$')
1365         {
1366             // We have a prompt variable to print
1367             ++p;
1368             if (*p == '{')
1369             {
1370                 ++p;
1371                 const char *var_name_begin = p;
1372                 const char *var_name_end = ::strchr (p, '}');
1373 
1374                 if (var_name_end && var_name_begin < var_name_end)
1375                 {
1376                     // if we have already failed to parse, skip this variable
1377                     if (success)
1378                     {
1379                         const char *cstr = NULL;
1380                         Address format_addr;
1381                         bool calculate_format_addr_function_offset = false;
1382                         // Set reg_kind and reg_num to invalid values
1383                         RegisterKind reg_kind = kNumRegisterKinds;
1384                         uint32_t reg_num = LLDB_INVALID_REGNUM;
1385                         FileSpec format_file_spec;
1386                         const RegisterInfo *reg_info = NULL;
1387                         RegisterContext *reg_ctx = NULL;
1388                         bool do_deref_pointer = false;
1389                         ValueObject::ExpressionPathScanEndReason reason_to_stop = ValueObject::eExpressionPathScanEndReasonEndOfString;
1390                         ValueObject::ExpressionPathEndResultType final_value_type = ValueObject::eExpressionPathEndResultTypePlain;
1391 
1392                         // Each variable must set success to true below...
1393                         bool var_success = false;
1394                         switch (var_name_begin[0])
1395                         {
1396                         case '*':
1397                         case 'v':
1398                         case 's':
1399                             {
1400                                 if (!valobj)
1401                                     break;
1402 
1403                                 if (log)
1404                                     log->Printf("[Debugger::FormatPrompt] initial string: %s",var_name_begin);
1405 
1406                                 // check for *var and *svar
1407                                 if (*var_name_begin == '*')
1408                                 {
1409                                     do_deref_pointer = true;
1410                                     var_name_begin++;
1411                                 }
1412 
1413                                 if (log)
1414                                     log->Printf("[Debugger::FormatPrompt] initial string: %s",var_name_begin);
1415 
1416                                 if (*var_name_begin == 's')
1417                                 {
1418                                     if (!valobj->IsSynthetic())
1419                                         valobj = valobj->GetSyntheticValue().get();
1420                                     if (!valobj)
1421                                         break;
1422                                     var_name_begin++;
1423                                 }
1424 
1425                                 if (log)
1426                                     log->Printf("[Debugger::FormatPrompt] initial string: %s",var_name_begin);
1427 
1428                                 // should be a 'v' by now
1429                                 if (*var_name_begin != 'v')
1430                                     break;
1431 
1432                                 if (log)
1433                                     log->Printf("[Debugger::FormatPrompt] initial string: %s",var_name_begin);
1434 
1435                                 ValueObject::ExpressionPathAftermath what_next = (do_deref_pointer ?
1436                                                                                   ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
1437                                 ValueObject::GetValueForExpressionPathOptions options;
1438                                 options.DontCheckDotVsArrowSyntax().DoAllowBitfieldSyntax().DoAllowFragileIVar().DoAllowSyntheticChildren();
1439                                 ValueObject::ValueObjectRepresentationStyle val_obj_display = ValueObject::eValueObjectRepresentationStyleSummary;
1440                                 ValueObject* target = NULL;
1441                                 Format custom_format = eFormatInvalid;
1442                                 const char* var_name_final = NULL;
1443                                 const char* var_name_final_if_array_range = NULL;
1444                                 const char* close_bracket_position = NULL;
1445                                 int64_t index_lower = -1;
1446                                 int64_t index_higher = -1;
1447                                 bool is_array_range = false;
1448                                 const char* first_unparsed;
1449                                 bool was_plain_var = false;
1450                                 bool was_var_format = false;
1451                                 bool was_var_indexed = false;
1452 
1453                                 if (!valobj) break;
1454                                 // simplest case ${var}, just print valobj's value
1455                                 if (::strncmp (var_name_begin, "var}", strlen("var}")) == 0)
1456                                 {
1457                                     was_plain_var = true;
1458                                     target = valobj;
1459                                     val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1460                                 }
1461                                 else if (::strncmp(var_name_begin,"var%",strlen("var%")) == 0)
1462                                 {
1463                                     was_var_format = true;
1464                                     // this is a variable with some custom format applied to it
1465                                     const char* percent_position;
1466                                     target = valobj;
1467                                     val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1468                                     ScanFormatDescriptor (var_name_begin,
1469                                                           var_name_end,
1470                                                           &var_name_final,
1471                                                           &percent_position,
1472                                                           &custom_format,
1473                                                           &val_obj_display);
1474                                 }
1475                                     // this is ${var.something} or multiple .something nested
1476                                 else if (::strncmp (var_name_begin, "var", strlen("var")) == 0)
1477                                 {
1478                                     if (::strncmp(var_name_begin, "var[", strlen("var[")) == 0)
1479                                         was_var_indexed = true;
1480                                     const char* percent_position;
1481                                     ScanFormatDescriptor (var_name_begin,
1482                                                           var_name_end,
1483                                                           &var_name_final,
1484                                                           &percent_position,
1485                                                           &custom_format,
1486                                                           &val_obj_display);
1487 
1488                                     const char* open_bracket_position;
1489                                     const char* separator_position;
1490                                     ScanBracketedRange (var_name_begin,
1491                                                         var_name_end,
1492                                                         var_name_final,
1493                                                         &open_bracket_position,
1494                                                         &separator_position,
1495                                                         &close_bracket_position,
1496                                                         &var_name_final_if_array_range,
1497                                                         &index_lower,
1498                                                         &index_higher);
1499 
1500                                     Error error;
1501 
1502                                     std::string expr_path(var_name_final-var_name_begin-1,0);
1503                                     memcpy(&expr_path[0], var_name_begin+3,var_name_final-var_name_begin-3);
1504 
1505                                     if (log)
1506                                         log->Printf("[Debugger::FormatPrompt] symbol to expand: %s",expr_path.c_str());
1507 
1508                                     target = valobj->GetValueForExpressionPath(expr_path.c_str(),
1509                                                                              &first_unparsed,
1510                                                                              &reason_to_stop,
1511                                                                              &final_value_type,
1512                                                                              options,
1513                                                                              &what_next).get();
1514 
1515                                     if (!target)
1516                                     {
1517                                         if (log)
1518                                             log->Printf("[Debugger::FormatPrompt] ERROR: unparsed portion = %s, why stopping = %d,"
1519                                                " final_value_type %d",
1520                                                first_unparsed, reason_to_stop, final_value_type);
1521                                         break;
1522                                     }
1523                                     else
1524                                     {
1525                                         if (log)
1526                                             log->Printf("[Debugger::FormatPrompt] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
1527                                                " final_value_type %d",
1528                                                first_unparsed, reason_to_stop, final_value_type);
1529                                     }
1530                                 }
1531                                 else
1532                                     break;
1533 
1534                                 is_array_range = (final_value_type == ValueObject::eExpressionPathEndResultTypeBoundedRange ||
1535                                                   final_value_type == ValueObject::eExpressionPathEndResultTypeUnboundedRange);
1536 
1537                                 do_deref_pointer = (what_next == ValueObject::eExpressionPathAftermathDereference);
1538 
1539                                 if (do_deref_pointer && !is_array_range)
1540                                 {
1541                                     // I have not deref-ed yet, let's do it
1542                                     // this happens when we are not going through GetValueForVariableExpressionPath
1543                                     // to get to the target ValueObject
1544                                     Error error;
1545                                     target = target->Dereference(error).get();
1546                                     if (error.Fail())
1547                                     {
1548                                         if (log)
1549                                             log->Printf("[Debugger::FormatPrompt] ERROR: %s\n", error.AsCString("unknown")); \
1550                                         break;
1551                                     }
1552                                     do_deref_pointer = false;
1553                                 }
1554 
1555                                 // <rdar://problem/11338654>
1556                                 // we do not want to use the summary for a bitfield of type T:n
1557                                 // if we were originally dealing with just a T - that would get
1558                                 // us into an endless recursion
1559                                 if (target->IsBitfield() && was_var_indexed)
1560                                 {
1561                                     // TODO: check for a (T:n)-specific summary - we should still obey that
1562                                     StreamString bitfield_name;
1563                                     bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(), target->GetBitfieldBitSize());
1564                                     lldb::TypeNameSpecifierImplSP type_sp(new TypeNameSpecifierImpl(bitfield_name.GetData(),false));
1565                                     if (!DataVisualization::GetSummaryForType(type_sp))
1566                                         val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1567                                 }
1568 
1569                                 // TODO use flags for these
1570                                 bool is_array = ClangASTContext::IsArrayType(target->GetClangType(), NULL, NULL, NULL);
1571                                 bool is_pointer = ClangASTContext::IsPointerType(target->GetClangType());
1572                                 bool is_aggregate = ClangASTContext::IsAggregateType(target->GetClangType());
1573 
1574                                 if ((is_array || is_pointer) && (!is_array_range) && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue) // this should be wrong, but there are some exceptions
1575                                 {
1576                                     StreamString str_temp;
1577                                     if (log)
1578                                         log->Printf("[Debugger::FormatPrompt] I am into array || pointer && !range");
1579 
1580                                     if (target->HasSpecialPrintableRepresentation(val_obj_display, custom_format))
1581                                     {
1582                                         // try to use the special cases
1583                                         var_success = target->DumpPrintableRepresentation(str_temp,
1584                                                                                           val_obj_display,
1585                                                                                           custom_format);
1586                                         if (log)
1587                                             log->Printf("[Debugger::FormatPrompt] special cases did%s match", var_success ? "" : "n't");
1588 
1589                                         // should not happen
1590                                         if (var_success)
1591                                             s << str_temp.GetData();
1592                                         var_success = true;
1593                                         break;
1594                                     }
1595                                     else
1596                                     {
1597                                         if (was_plain_var) // if ${var}
1598                                         {
1599                                             s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
1600                                         }
1601                                         else if (is_pointer) // if pointer, value is the address stored
1602                                         {
1603                                             target->DumpPrintableRepresentation (s,
1604                                                                                  val_obj_display,
1605                                                                                  custom_format,
1606                                                                                  ValueObject::ePrintableRepresentationSpecialCasesDisable);
1607                                         }
1608                                         var_success = true;
1609                                         break;
1610                                     }
1611                                 }
1612 
1613                                 // if directly trying to print ${var}, and this is an aggregate, display a nice
1614                                 // type @ location message
1615                                 if (is_aggregate && was_plain_var)
1616                                 {
1617                                     s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
1618                                     var_success = true;
1619                                     break;
1620                                 }
1621 
1622                                 // if directly trying to print ${var%V}, and this is an aggregate, do not let the user do it
1623                                 if (is_aggregate && ((was_var_format && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue)))
1624                                 {
1625                                     s << "<invalid use of aggregate type>";
1626                                     var_success = true;
1627                                     break;
1628                                 }
1629 
1630                                 if (!is_array_range)
1631                                 {
1632                                     if (log)
1633                                         log->Printf("[Debugger::FormatPrompt] dumping ordinary printable output");
1634                                     var_success = target->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1635                                 }
1636                                 else
1637                                 {
1638                                     if (log)
1639                                         log->Printf("[Debugger::FormatPrompt] checking if I can handle as array");
1640                                     if (!is_array && !is_pointer)
1641                                         break;
1642                                     if (log)
1643                                         log->Printf("[Debugger::FormatPrompt] handle as array");
1644                                     const char* special_directions = NULL;
1645                                     StreamString special_directions_writer;
1646                                     if (close_bracket_position && (var_name_end-close_bracket_position > 1))
1647                                     {
1648                                         ConstString additional_data;
1649                                         additional_data.SetCStringWithLength(close_bracket_position+1, var_name_end-close_bracket_position-1);
1650                                         special_directions_writer.Printf("${%svar%s}",
1651                                                                          do_deref_pointer ? "*" : "",
1652                                                                          additional_data.GetCString());
1653                                         special_directions = special_directions_writer.GetData();
1654                                     }
1655 
1656                                     // let us display items index_lower thru index_higher of this array
1657                                     s.PutChar('[');
1658                                     var_success = true;
1659 
1660                                     if (index_higher < 0)
1661                                         index_higher = valobj->GetNumChildren() - 1;
1662 
1663                                     uint32_t max_num_children = target->GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();
1664 
1665                                     for (;index_lower<=index_higher;index_lower++)
1666                                     {
1667                                         ValueObject* item = ExpandIndexedExpression (target,
1668                                                                                      index_lower,
1669                                                                                      exe_ctx->GetFramePtr(),
1670                                                                                      false).get();
1671 
1672                                         if (!item)
1673                                         {
1674                                             if (log)
1675                                                 log->Printf("[Debugger::FormatPrompt] ERROR in getting child item at index %" PRId64, index_lower);
1676                                         }
1677                                         else
1678                                         {
1679                                             if (log)
1680                                                 log->Printf("[Debugger::FormatPrompt] special_directions for child item: %s",special_directions);
1681                                         }
1682 
1683                                         if (!special_directions)
1684                                             var_success &= item->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1685                                         else
1686                                             var_success &= FormatPrompt(special_directions, sc, exe_ctx, addr, s, NULL, item);
1687 
1688                                         if (--max_num_children == 0)
1689                                         {
1690                                             s.PutCString(", ...");
1691                                             break;
1692                                         }
1693 
1694                                         if (index_lower < index_higher)
1695                                             s.PutChar(',');
1696                                     }
1697                                     s.PutChar(']');
1698                                 }
1699                             }
1700                             break;
1701                         case 'a':
1702                             if (::strncmp (var_name_begin, "addr}", strlen("addr}")) == 0)
1703                             {
1704                                 if (addr && addr->IsValid())
1705                                 {
1706                                     var_success = true;
1707                                     format_addr = *addr;
1708                                 }
1709                             }
1710                             else if (::strncmp (var_name_begin, "ansi.", strlen("ansi.")) == 0)
1711                             {
1712                                 var_success = true;
1713                                 var_name_begin += strlen("ansi."); // Skip the "ansi."
1714                                 if (::strncmp (var_name_begin, "fg.", strlen("fg.")) == 0)
1715                                 {
1716                                     var_name_begin += strlen("fg."); // Skip the "fg."
1717                                     if (::strncmp (var_name_begin, "black}", strlen("black}")) == 0)
1718                                     {
1719                                         s.Printf ("%s%s%s",
1720                                                   lldb_utility::ansi::k_escape_start,
1721                                                   lldb_utility::ansi::k_fg_black,
1722                                                   lldb_utility::ansi::k_escape_end);
1723                                     }
1724                                     else if (::strncmp (var_name_begin, "red}", strlen("red}")) == 0)
1725                                     {
1726                                         s.Printf ("%s%s%s",
1727                                                   lldb_utility::ansi::k_escape_start,
1728                                                   lldb_utility::ansi::k_fg_red,
1729                                                   lldb_utility::ansi::k_escape_end);
1730                                     }
1731                                     else if (::strncmp (var_name_begin, "green}", strlen("green}")) == 0)
1732                                     {
1733                                         s.Printf ("%s%s%s",
1734                                                   lldb_utility::ansi::k_escape_start,
1735                                                   lldb_utility::ansi::k_fg_green,
1736                                                   lldb_utility::ansi::k_escape_end);
1737                                     }
1738                                     else if (::strncmp (var_name_begin, "yellow}", strlen("yellow}")) == 0)
1739                                     {
1740                                         s.Printf ("%s%s%s",
1741                                                   lldb_utility::ansi::k_escape_start,
1742                                                   lldb_utility::ansi::k_fg_yellow,
1743                                                   lldb_utility::ansi::k_escape_end);
1744                                     }
1745                                     else if (::strncmp (var_name_begin, "blue}", strlen("blue}")) == 0)
1746                                     {
1747                                         s.Printf ("%s%s%s",
1748                                                   lldb_utility::ansi::k_escape_start,
1749                                                   lldb_utility::ansi::k_fg_blue,
1750                                                   lldb_utility::ansi::k_escape_end);
1751                                     }
1752                                     else if (::strncmp (var_name_begin, "purple}", strlen("purple}")) == 0)
1753                                     {
1754                                         s.Printf ("%s%s%s",
1755                                                   lldb_utility::ansi::k_escape_start,
1756                                                   lldb_utility::ansi::k_fg_purple,
1757                                                   lldb_utility::ansi::k_escape_end);
1758                                     }
1759                                     else if (::strncmp (var_name_begin, "cyan}", strlen("cyan}")) == 0)
1760                                     {
1761                                         s.Printf ("%s%s%s",
1762                                                   lldb_utility::ansi::k_escape_start,
1763                                                   lldb_utility::ansi::k_fg_cyan,
1764                                                   lldb_utility::ansi::k_escape_end);
1765                                     }
1766                                     else if (::strncmp (var_name_begin, "white}", strlen("white}")) == 0)
1767                                     {
1768                                         s.Printf ("%s%s%s",
1769                                                   lldb_utility::ansi::k_escape_start,
1770                                                   lldb_utility::ansi::k_fg_white,
1771                                                   lldb_utility::ansi::k_escape_end);
1772                                     }
1773                                     else
1774                                     {
1775                                         var_success = false;
1776                                     }
1777                                 }
1778                                 else if (::strncmp (var_name_begin, "bg.", strlen("bg.")) == 0)
1779                                 {
1780                                     var_name_begin += strlen("bg."); // Skip the "bg."
1781                                     if (::strncmp (var_name_begin, "black}", strlen("black}")) == 0)
1782                                     {
1783                                         s.Printf ("%s%s%s",
1784                                                   lldb_utility::ansi::k_escape_start,
1785                                                   lldb_utility::ansi::k_bg_black,
1786                                                   lldb_utility::ansi::k_escape_end);
1787                                     }
1788                                     else if (::strncmp (var_name_begin, "red}", strlen("red}")) == 0)
1789                                     {
1790                                         s.Printf ("%s%s%s",
1791                                                   lldb_utility::ansi::k_escape_start,
1792                                                   lldb_utility::ansi::k_bg_red,
1793                                                   lldb_utility::ansi::k_escape_end);
1794                                     }
1795                                     else if (::strncmp (var_name_begin, "green}", strlen("green}")) == 0)
1796                                     {
1797                                         s.Printf ("%s%s%s",
1798                                                   lldb_utility::ansi::k_escape_start,
1799                                                   lldb_utility::ansi::k_bg_green,
1800                                                   lldb_utility::ansi::k_escape_end);
1801                                     }
1802                                     else if (::strncmp (var_name_begin, "yellow}", strlen("yellow}")) == 0)
1803                                     {
1804                                         s.Printf ("%s%s%s",
1805                                                   lldb_utility::ansi::k_escape_start,
1806                                                   lldb_utility::ansi::k_bg_yellow,
1807                                                   lldb_utility::ansi::k_escape_end);
1808                                     }
1809                                     else if (::strncmp (var_name_begin, "blue}", strlen("blue}")) == 0)
1810                                     {
1811                                         s.Printf ("%s%s%s",
1812                                                   lldb_utility::ansi::k_escape_start,
1813                                                   lldb_utility::ansi::k_bg_blue,
1814                                                   lldb_utility::ansi::k_escape_end);
1815                                     }
1816                                     else if (::strncmp (var_name_begin, "purple}", strlen("purple}")) == 0)
1817                                     {
1818                                         s.Printf ("%s%s%s",
1819                                                   lldb_utility::ansi::k_escape_start,
1820                                                   lldb_utility::ansi::k_bg_purple,
1821                                                   lldb_utility::ansi::k_escape_end);
1822                                     }
1823                                     else if (::strncmp (var_name_begin, "cyan}", strlen("cyan}")) == 0)
1824                                     {
1825                                         s.Printf ("%s%s%s",
1826                                                   lldb_utility::ansi::k_escape_start,
1827                                                   lldb_utility::ansi::k_bg_cyan,
1828                                                   lldb_utility::ansi::k_escape_end);
1829                                     }
1830                                     else if (::strncmp (var_name_begin, "white}", strlen("white}")) == 0)
1831                                     {
1832                                         s.Printf ("%s%s%s",
1833                                                   lldb_utility::ansi::k_escape_start,
1834                                                   lldb_utility::ansi::k_bg_white,
1835                                                   lldb_utility::ansi::k_escape_end);
1836                                     }
1837                                     else
1838                                     {
1839                                         var_success = false;
1840                                     }
1841                                 }
1842                                 else if (::strncmp (var_name_begin, "normal}", strlen ("normal}")) == 0)
1843                                 {
1844                                     s.Printf ("%s%s%s",
1845                                               lldb_utility::ansi::k_escape_start,
1846                                               lldb_utility::ansi::k_ctrl_normal,
1847                                               lldb_utility::ansi::k_escape_end);
1848                                 }
1849                                 else if (::strncmp (var_name_begin, "bold}", strlen("bold}")) == 0)
1850                                 {
1851                                     s.Printf ("%s%s%s",
1852                                               lldb_utility::ansi::k_escape_start,
1853                                               lldb_utility::ansi::k_ctrl_bold,
1854                                               lldb_utility::ansi::k_escape_end);
1855                                 }
1856                                 else if (::strncmp (var_name_begin, "faint}", strlen("faint}")) == 0)
1857                                 {
1858                                     s.Printf ("%s%s%s",
1859                                               lldb_utility::ansi::k_escape_start,
1860                                               lldb_utility::ansi::k_ctrl_faint,
1861                                               lldb_utility::ansi::k_escape_end);
1862                                 }
1863                                 else if (::strncmp (var_name_begin, "italic}", strlen("italic}")) == 0)
1864                                 {
1865                                     s.Printf ("%s%s%s",
1866                                               lldb_utility::ansi::k_escape_start,
1867                                               lldb_utility::ansi::k_ctrl_italic,
1868                                               lldb_utility::ansi::k_escape_end);
1869                                 }
1870                                 else if (::strncmp (var_name_begin, "underline}", strlen("underline}")) == 0)
1871                                 {
1872                                     s.Printf ("%s%s%s",
1873                                               lldb_utility::ansi::k_escape_start,
1874                                               lldb_utility::ansi::k_ctrl_underline,
1875                                               lldb_utility::ansi::k_escape_end);
1876                                 }
1877                                 else if (::strncmp (var_name_begin, "slow-blink}", strlen("slow-blink}")) == 0)
1878                                 {
1879                                     s.Printf ("%s%s%s",
1880                                               lldb_utility::ansi::k_escape_start,
1881                                               lldb_utility::ansi::k_ctrl_slow_blink,
1882                                               lldb_utility::ansi::k_escape_end);
1883                                 }
1884                                 else if (::strncmp (var_name_begin, "fast-blink}", strlen("fast-blink}")) == 0)
1885                                 {
1886                                     s.Printf ("%s%s%s",
1887                                               lldb_utility::ansi::k_escape_start,
1888                                               lldb_utility::ansi::k_ctrl_fast_blink,
1889                                               lldb_utility::ansi::k_escape_end);
1890                                 }
1891                                 else if (::strncmp (var_name_begin, "negative}", strlen("negative}")) == 0)
1892                                 {
1893                                     s.Printf ("%s%s%s",
1894                                               lldb_utility::ansi::k_escape_start,
1895                                               lldb_utility::ansi::k_ctrl_negative,
1896                                               lldb_utility::ansi::k_escape_end);
1897                                 }
1898                                 else if (::strncmp (var_name_begin, "conceal}", strlen("conceal}")) == 0)
1899                                 {
1900                                     s.Printf ("%s%s%s",
1901                                               lldb_utility::ansi::k_escape_start,
1902                                               lldb_utility::ansi::k_ctrl_conceal,
1903                                               lldb_utility::ansi::k_escape_end);
1904 
1905                                 }
1906                                 else if (::strncmp (var_name_begin, "crossed-out}", strlen("crossed-out}")) == 0)
1907                                 {
1908                                     s.Printf ("%s%s%s",
1909                                               lldb_utility::ansi::k_escape_start,
1910                                               lldb_utility::ansi::k_ctrl_crossed_out,
1911                                               lldb_utility::ansi::k_escape_end);
1912                                 }
1913                                 else
1914                                 {
1915                                     var_success = false;
1916                                 }
1917                             }
1918                             break;
1919 
1920                         case 'p':
1921                             if (::strncmp (var_name_begin, "process.", strlen("process.")) == 0)
1922                             {
1923                                 if (exe_ctx)
1924                                 {
1925                                     Process *process = exe_ctx->GetProcessPtr();
1926                                     if (process)
1927                                     {
1928                                         var_name_begin += ::strlen ("process.");
1929                                         if (::strncmp (var_name_begin, "id}", strlen("id}")) == 0)
1930                                         {
1931                                             s.Printf("%" PRIu64, process->GetID());
1932                                             var_success = true;
1933                                         }
1934                                         else if ((::strncmp (var_name_begin, "name}", strlen("name}")) == 0) ||
1935                                                  (::strncmp (var_name_begin, "file.basename}", strlen("file.basename}")) == 0) ||
1936                                                  (::strncmp (var_name_begin, "file.fullpath}", strlen("file.fullpath}")) == 0))
1937                                         {
1938                                             Module *exe_module = process->GetTarget().GetExecutableModulePointer();
1939                                             if (exe_module)
1940                                             {
1941                                                 if (var_name_begin[0] == 'n' || var_name_begin[5] == 'f')
1942                                                 {
1943                                                     format_file_spec.GetFilename() = exe_module->GetFileSpec().GetFilename();
1944                                                     var_success = format_file_spec;
1945                                                 }
1946                                                 else
1947                                                 {
1948                                                     format_file_spec = exe_module->GetFileSpec();
1949                                                     var_success = format_file_spec;
1950                                                 }
1951                                             }
1952                                         }
1953                                     }
1954                                 }
1955                             }
1956                             break;
1957 
1958                         case 't':
1959                             if (::strncmp (var_name_begin, "thread.", strlen("thread.")) == 0)
1960                             {
1961                                 if (exe_ctx)
1962                                 {
1963                                     Thread *thread = exe_ctx->GetThreadPtr();
1964                                     if (thread)
1965                                     {
1966                                         var_name_begin += ::strlen ("thread.");
1967                                         if (::strncmp (var_name_begin, "id}", strlen("id}")) == 0)
1968                                         {
1969                                             s.Printf("0x%4.4" PRIx64, thread->GetID());
1970                                             var_success = true;
1971                                         }
1972                                         else if (::strncmp (var_name_begin, "protocol_id}", strlen("protocol_id}")) == 0)
1973                                         {
1974                                             s.Printf("0x%4.4" PRIx64, thread->GetProtocolID());
1975                                             var_success = true;
1976                                         }
1977                                         else if (::strncmp (var_name_begin, "index}", strlen("index}")) == 0)
1978                                         {
1979                                             s.Printf("%u", thread->GetIndexID());
1980                                             var_success = true;
1981                                         }
1982                                         else if (::strncmp (var_name_begin, "name}", strlen("name}")) == 0)
1983                                         {
1984                                             cstr = thread->GetName();
1985                                             var_success = cstr && cstr[0];
1986                                             if (var_success)
1987                                                 s.PutCString(cstr);
1988                                         }
1989                                         else if (::strncmp (var_name_begin, "queue}", strlen("queue}")) == 0)
1990                                         {
1991                                             cstr = thread->GetQueueName();
1992                                             var_success = cstr && cstr[0];
1993                                             if (var_success)
1994                                                 s.PutCString(cstr);
1995                                         }
1996                                         else if (::strncmp (var_name_begin, "stop-reason}", strlen("stop-reason}")) == 0)
1997                                         {
1998                                             StopInfoSP stop_info_sp = thread->GetStopInfo ();
1999                                             if (stop_info_sp && stop_info_sp->IsValid())
2000                                             {
2001                                                 cstr = stop_info_sp->GetDescription();
2002                                                 if (cstr && cstr[0])
2003                                                 {
2004                                                     s.PutCString(cstr);
2005                                                     var_success = true;
2006                                                 }
2007                                             }
2008                                         }
2009                                         else if (::strncmp (var_name_begin, "return-value}", strlen("return-value}")) == 0)
2010                                         {
2011                                             StopInfoSP stop_info_sp = thread->GetStopInfo ();
2012                                             if (stop_info_sp && stop_info_sp->IsValid())
2013                                             {
2014                                                 ValueObjectSP return_valobj_sp = StopInfo::GetReturnValueObject (stop_info_sp);
2015                                                 if (return_valobj_sp)
2016                                                 {
2017                                                     ValueObject::DumpValueObject (s, return_valobj_sp.get());
2018                                                     var_success = true;
2019                                                 }
2020                                             }
2021                                         }
2022                                     }
2023                                 }
2024                             }
2025                             else if (::strncmp (var_name_begin, "target.", strlen("target.")) == 0)
2026                             {
2027                                 // TODO: hookup properties
2028 //                                if (!target_properties_sp)
2029 //                                {
2030 //                                    Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2031 //                                    if (target)
2032 //                                        target_properties_sp = target->GetProperties();
2033 //                                }
2034 //
2035 //                                if (target_properties_sp)
2036 //                                {
2037 //                                    var_name_begin += ::strlen ("target.");
2038 //                                    const char *end_property = strchr(var_name_begin, '}');
2039 //                                    if (end_property)
2040 //                                    {
2041 //                                        ConstString property_name(var_name_begin, end_property - var_name_begin);
2042 //                                        std::string property_value (target_properties_sp->GetPropertyValue(property_name));
2043 //                                        if (!property_value.empty())
2044 //                                        {
2045 //                                            s.PutCString (property_value.c_str());
2046 //                                            var_success = true;
2047 //                                        }
2048 //                                    }
2049 //                                }
2050                                 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2051                                 if (target)
2052                                 {
2053                                     var_name_begin += ::strlen ("target.");
2054                                     if (::strncmp (var_name_begin, "arch}", strlen("arch}")) == 0)
2055                                     {
2056                                         ArchSpec arch (target->GetArchitecture ());
2057                                         if (arch.IsValid())
2058                                         {
2059                                             s.PutCString (arch.GetArchitectureName());
2060                                             var_success = true;
2061                                         }
2062                                     }
2063                                 }
2064                             }
2065                             break;
2066 
2067 
2068                         case 'm':
2069                             if (::strncmp (var_name_begin, "module.", strlen("module.")) == 0)
2070                             {
2071                                 if (sc && sc->module_sp.get())
2072                                 {
2073                                     Module *module = sc->module_sp.get();
2074                                     var_name_begin += ::strlen ("module.");
2075 
2076                                     if (::strncmp (var_name_begin, "file.", strlen("file.")) == 0)
2077                                     {
2078                                         if (module->GetFileSpec())
2079                                         {
2080                                             var_name_begin += ::strlen ("file.");
2081 
2082                                             if (::strncmp (var_name_begin, "basename}", strlen("basename}")) == 0)
2083                                             {
2084                                                 format_file_spec.GetFilename() = module->GetFileSpec().GetFilename();
2085                                                 var_success = format_file_spec;
2086                                             }
2087                                             else if (::strncmp (var_name_begin, "fullpath}", strlen("fullpath}")) == 0)
2088                                             {
2089                                                 format_file_spec = module->GetFileSpec();
2090                                                 var_success = format_file_spec;
2091                                             }
2092                                         }
2093                                     }
2094                                 }
2095                             }
2096                             break;
2097 
2098 
2099                         case 'f':
2100                             if (::strncmp (var_name_begin, "file.", strlen("file.")) == 0)
2101                             {
2102                                 if (sc && sc->comp_unit != NULL)
2103                                 {
2104                                     var_name_begin += ::strlen ("file.");
2105 
2106                                     if (::strncmp (var_name_begin, "basename}", strlen("basename}")) == 0)
2107                                     {
2108                                         format_file_spec.GetFilename() = sc->comp_unit->GetFilename();
2109                                         var_success = format_file_spec;
2110                                     }
2111                                     else if (::strncmp (var_name_begin, "fullpath}", strlen("fullpath}")) == 0)
2112                                     {
2113                                         format_file_spec = *sc->comp_unit;
2114                                         var_success = format_file_spec;
2115                                     }
2116                                 }
2117                             }
2118                             else if (::strncmp (var_name_begin, "frame.", strlen("frame.")) == 0)
2119                             {
2120                                 if (exe_ctx)
2121                                 {
2122                                     StackFrame *frame = exe_ctx->GetFramePtr();
2123                                     if (frame)
2124                                     {
2125                                         var_name_begin += ::strlen ("frame.");
2126                                         if (::strncmp (var_name_begin, "index}", strlen("index}")) == 0)
2127                                         {
2128                                             s.Printf("%u", frame->GetFrameIndex());
2129                                             var_success = true;
2130                                         }
2131                                         else if (::strncmp (var_name_begin, "pc}", strlen("pc}")) == 0)
2132                                         {
2133                                             reg_kind = eRegisterKindGeneric;
2134                                             reg_num = LLDB_REGNUM_GENERIC_PC;
2135                                             var_success = true;
2136                                         }
2137                                         else if (::strncmp (var_name_begin, "sp}", strlen("sp}")) == 0)
2138                                         {
2139                                             reg_kind = eRegisterKindGeneric;
2140                                             reg_num = LLDB_REGNUM_GENERIC_SP;
2141                                             var_success = true;
2142                                         }
2143                                         else if (::strncmp (var_name_begin, "fp}", strlen("fp}")) == 0)
2144                                         {
2145                                             reg_kind = eRegisterKindGeneric;
2146                                             reg_num = LLDB_REGNUM_GENERIC_FP;
2147                                             var_success = true;
2148                                         }
2149                                         else if (::strncmp (var_name_begin, "flags}", strlen("flags}")) == 0)
2150                                         {
2151                                             reg_kind = eRegisterKindGeneric;
2152                                             reg_num = LLDB_REGNUM_GENERIC_FLAGS;
2153                                             var_success = true;
2154                                         }
2155                                         else if (::strncmp (var_name_begin, "reg.", strlen ("reg.")) == 0)
2156                                         {
2157                                             reg_ctx = frame->GetRegisterContext().get();
2158                                             if (reg_ctx)
2159                                             {
2160                                                 var_name_begin += ::strlen ("reg.");
2161                                                 if (var_name_begin < var_name_end)
2162                                                 {
2163                                                     std::string reg_name (var_name_begin, var_name_end);
2164                                                     reg_info = reg_ctx->GetRegisterInfoByName (reg_name.c_str());
2165                                                     if (reg_info)
2166                                                         var_success = true;
2167                                                 }
2168                                             }
2169                                         }
2170                                     }
2171                                 }
2172                             }
2173                             else if (::strncmp (var_name_begin, "function.", strlen("function.")) == 0)
2174                             {
2175                                 if (sc && (sc->function != NULL || sc->symbol != NULL))
2176                                 {
2177                                     var_name_begin += ::strlen ("function.");
2178                                     if (::strncmp (var_name_begin, "id}", strlen("id}")) == 0)
2179                                     {
2180                                         if (sc->function)
2181                                             s.Printf("function{0x%8.8" PRIx64 "}", sc->function->GetID());
2182                                         else
2183                                             s.Printf("symbol[%u]", sc->symbol->GetID());
2184 
2185                                         var_success = true;
2186                                     }
2187                                     else if (::strncmp (var_name_begin, "name}", strlen("name}")) == 0)
2188                                     {
2189                                         if (sc->function)
2190                                             cstr = sc->function->GetName().AsCString (NULL);
2191                                         else if (sc->symbol)
2192                                             cstr = sc->symbol->GetName().AsCString (NULL);
2193                                         if (cstr)
2194                                         {
2195                                             s.PutCString(cstr);
2196 
2197                                             if (sc->block)
2198                                             {
2199                                                 Block *inline_block = sc->block->GetContainingInlinedBlock ();
2200                                                 if (inline_block)
2201                                                 {
2202                                                     const InlineFunctionInfo *inline_info = sc->block->GetInlinedFunctionInfo();
2203                                                     if (inline_info)
2204                                                     {
2205                                                         s.PutCString(" [inlined] ");
2206                                                         inline_info->GetName().Dump(&s);
2207                                                     }
2208                                                 }
2209                                             }
2210                                             var_success = true;
2211                                         }
2212                                     }
2213                                     else if (::strncmp (var_name_begin, "name-with-args}", strlen("name-with-args}")) == 0)
2214                                     {
2215                                         // Print the function name with arguments in it
2216 
2217                                         if (sc->function)
2218                                         {
2219                                             var_success = true;
2220                                             ExecutionContextScope *exe_scope = exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL;
2221                                             cstr = sc->function->GetName().AsCString (NULL);
2222                                             if (cstr)
2223                                             {
2224                                                 const InlineFunctionInfo *inline_info = NULL;
2225                                                 VariableListSP variable_list_sp;
2226                                                 bool get_function_vars = true;
2227                                                 if (sc->block)
2228                                                 {
2229                                                     Block *inline_block = sc->block->GetContainingInlinedBlock ();
2230 
2231                                                     if (inline_block)
2232                                                     {
2233                                                         get_function_vars = false;
2234                                                         inline_info = sc->block->GetInlinedFunctionInfo();
2235                                                         if (inline_info)
2236                                                             variable_list_sp = inline_block->GetBlockVariableList (true);
2237                                                     }
2238                                                 }
2239 
2240                                                 if (get_function_vars)
2241                                                 {
2242                                                     variable_list_sp = sc->function->GetBlock(true).GetBlockVariableList (true);
2243                                                 }
2244 
2245                                                 if (inline_info)
2246                                                 {
2247                                                     s.PutCString (cstr);
2248                                                     s.PutCString (" [inlined] ");
2249                                                     cstr = inline_info->GetName().GetCString();
2250                                                 }
2251 
2252                                                 VariableList args;
2253                                                 if (variable_list_sp)
2254                                                     variable_list_sp->AppendVariablesWithScope(eValueTypeVariableArgument, args);
2255                                                 if (args.GetSize() > 0)
2256                                                 {
2257                                                     const char *open_paren = strchr (cstr, '(');
2258                                                     const char *close_paren = NULL;
2259                                                     if (open_paren)
2260                                                     {
2261                                                         if (strncmp(open_paren, "(anonymous namespace)", strlen("(anonymous namespace)")) == 0)
2262                                                         {
2263                                                             open_paren = strchr (open_paren + strlen("(anonymous namespace)"), '(');
2264                                                             if (open_paren)
2265                                                                 close_paren = strchr (open_paren, ')');
2266                                                         }
2267                                                         else
2268                                                             close_paren = strchr (open_paren, ')');
2269                                                     }
2270 
2271                                                     if (open_paren)
2272                                                         s.Write(cstr, open_paren - cstr + 1);
2273                                                     else
2274                                                     {
2275                                                         s.PutCString (cstr);
2276                                                         s.PutChar ('(');
2277                                                     }
2278                                                     const size_t num_args = args.GetSize();
2279                                                     for (size_t arg_idx = 0; arg_idx < num_args; ++arg_idx)
2280                                                     {
2281                                                         VariableSP var_sp (args.GetVariableAtIndex (arg_idx));
2282                                                         ValueObjectSP var_value_sp (ValueObjectVariable::Create (exe_scope, var_sp));
2283                                                         const char *var_name = var_value_sp->GetName().GetCString();
2284                                                         const char *var_value = var_value_sp->GetValueAsCString();
2285                                                         if (arg_idx > 0)
2286                                                             s.PutCString (", ");
2287                                                         if (var_value_sp->GetError().Success())
2288                                                         {
2289                                                             if (var_value)
2290                                                                 s.Printf ("%s=%s", var_name, var_value);
2291                                                             else
2292                                                                 s.Printf ("%s=%s at %s", var_name, var_value_sp->GetTypeName().GetCString(), var_value_sp->GetLocationAsCString());
2293                                                         }
2294                                                         else
2295                                                             s.Printf ("%s=<unavailable>", var_name);
2296                                                     }
2297 
2298                                                     if (close_paren)
2299                                                         s.PutCString (close_paren);
2300                                                     else
2301                                                         s.PutChar(')');
2302 
2303                                                 }
2304                                                 else
2305                                                 {
2306                                                     s.PutCString(cstr);
2307                                                 }
2308                                             }
2309                                         }
2310                                         else if (sc->symbol)
2311                                         {
2312                                             cstr = sc->symbol->GetName().AsCString (NULL);
2313                                             if (cstr)
2314                                             {
2315                                                 s.PutCString(cstr);
2316                                                 var_success = true;
2317                                             }
2318                                         }
2319                                     }
2320                                     else if (::strncmp (var_name_begin, "addr-offset}", strlen("addr-offset}")) == 0)
2321                                     {
2322                                         var_success = addr != NULL;
2323                                         if (var_success)
2324                                         {
2325                                             format_addr = *addr;
2326                                             calculate_format_addr_function_offset = true;
2327                                         }
2328                                     }
2329                                     else if (::strncmp (var_name_begin, "line-offset}", strlen("line-offset}")) == 0)
2330                                     {
2331                                         var_success = sc->line_entry.range.GetBaseAddress().IsValid();
2332                                         if (var_success)
2333                                         {
2334                                             format_addr = sc->line_entry.range.GetBaseAddress();
2335                                             calculate_format_addr_function_offset = true;
2336                                         }
2337                                     }
2338                                     else if (::strncmp (var_name_begin, "pc-offset}", strlen("pc-offset}")) == 0)
2339                                     {
2340                                         StackFrame *frame = exe_ctx->GetFramePtr();
2341                                         var_success = frame != NULL;
2342                                         if (var_success)
2343                                         {
2344                                             format_addr = frame->GetFrameCodeAddress();
2345                                             calculate_format_addr_function_offset = true;
2346                                         }
2347                                     }
2348                                 }
2349                             }
2350                             break;
2351 
2352                         case 'l':
2353                             if (::strncmp (var_name_begin, "line.", strlen("line.")) == 0)
2354                             {
2355                                 if (sc && sc->line_entry.IsValid())
2356                                 {
2357                                     var_name_begin += ::strlen ("line.");
2358                                     if (::strncmp (var_name_begin, "file.", strlen("file.")) == 0)
2359                                     {
2360                                         var_name_begin += ::strlen ("file.");
2361 
2362                                         if (::strncmp (var_name_begin, "basename}", strlen("basename}")) == 0)
2363                                         {
2364                                             format_file_spec.GetFilename() = sc->line_entry.file.GetFilename();
2365                                             var_success = format_file_spec;
2366                                         }
2367                                         else if (::strncmp (var_name_begin, "fullpath}", strlen("fullpath}")) == 0)
2368                                         {
2369                                             format_file_spec = sc->line_entry.file;
2370                                             var_success = format_file_spec;
2371                                         }
2372                                     }
2373                                     else if (::strncmp (var_name_begin, "number}", strlen("number}")) == 0)
2374                                     {
2375                                         var_success = true;
2376                                         s.Printf("%u", sc->line_entry.line);
2377                                     }
2378                                     else if ((::strncmp (var_name_begin, "start-addr}", strlen("start-addr}")) == 0) ||
2379                                              (::strncmp (var_name_begin, "end-addr}", strlen("end-addr}")) == 0))
2380                                     {
2381                                         var_success = sc && sc->line_entry.range.GetBaseAddress().IsValid();
2382                                         if (var_success)
2383                                         {
2384                                             format_addr = sc->line_entry.range.GetBaseAddress();
2385                                             if (var_name_begin[0] == 'e')
2386                                                 format_addr.Slide (sc->line_entry.range.GetByteSize());
2387                                         }
2388                                     }
2389                                 }
2390                             }
2391                             break;
2392                         }
2393 
2394                         if (var_success)
2395                         {
2396                             // If format addr is valid, then we need to print an address
2397                             if (reg_num != LLDB_INVALID_REGNUM)
2398                             {
2399                                 StackFrame *frame = exe_ctx->GetFramePtr();
2400                                 // We have a register value to display...
2401                                 if (reg_num == LLDB_REGNUM_GENERIC_PC && reg_kind == eRegisterKindGeneric)
2402                                 {
2403                                     format_addr = frame->GetFrameCodeAddress();
2404                                 }
2405                                 else
2406                                 {
2407                                     if (reg_ctx == NULL)
2408                                         reg_ctx = frame->GetRegisterContext().get();
2409 
2410                                     if (reg_ctx)
2411                                     {
2412                                         if (reg_kind != kNumRegisterKinds)
2413                                             reg_num = reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
2414                                         reg_info = reg_ctx->GetRegisterInfoAtIndex (reg_num);
2415                                         var_success = reg_info != NULL;
2416                                     }
2417                                 }
2418                             }
2419 
2420                             if (reg_info != NULL)
2421                             {
2422                                 RegisterValue reg_value;
2423                                 var_success = reg_ctx->ReadRegister (reg_info, reg_value);
2424                                 if (var_success)
2425                                 {
2426                                     reg_value.Dump(&s, reg_info, false, false, eFormatDefault);
2427                                 }
2428                             }
2429 
2430                             if (format_file_spec)
2431                             {
2432                                 s << format_file_spec;
2433                             }
2434 
2435                             // If format addr is valid, then we need to print an address
2436                             if (format_addr.IsValid())
2437                             {
2438                                 var_success = false;
2439 
2440                                 if (calculate_format_addr_function_offset)
2441                                 {
2442                                     Address func_addr;
2443 
2444                                     if (sc)
2445                                     {
2446                                         if (sc->function)
2447                                         {
2448                                             func_addr = sc->function->GetAddressRange().GetBaseAddress();
2449                                             if (sc->block)
2450                                             {
2451                                                 // Check to make sure we aren't in an inline
2452                                                 // function. If we are, use the inline block
2453                                                 // range that contains "format_addr" since
2454                                                 // blocks can be discontiguous.
2455                                                 Block *inline_block = sc->block->GetContainingInlinedBlock ();
2456                                                 AddressRange inline_range;
2457                                                 if (inline_block && inline_block->GetRangeContainingAddress (format_addr, inline_range))
2458                                                     func_addr = inline_range.GetBaseAddress();
2459                                             }
2460                                         }
2461                                         else if (sc->symbol && sc->symbol->ValueIsAddress())
2462                                             func_addr = sc->symbol->GetAddress();
2463                                     }
2464 
2465                                     if (func_addr.IsValid())
2466                                     {
2467                                         if (func_addr.GetSection() == format_addr.GetSection())
2468                                         {
2469                                             addr_t func_file_addr = func_addr.GetFileAddress();
2470                                             addr_t addr_file_addr = format_addr.GetFileAddress();
2471                                             if (addr_file_addr > func_file_addr)
2472                                                 s.Printf(" + %" PRIu64, addr_file_addr - func_file_addr);
2473                                             else if (addr_file_addr < func_file_addr)
2474                                                 s.Printf(" - %" PRIu64, func_file_addr - addr_file_addr);
2475                                             var_success = true;
2476                                         }
2477                                         else
2478                                         {
2479                                             Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2480                                             if (target)
2481                                             {
2482                                                 addr_t func_load_addr = func_addr.GetLoadAddress (target);
2483                                                 addr_t addr_load_addr = format_addr.GetLoadAddress (target);
2484                                                 if (addr_load_addr > func_load_addr)
2485                                                     s.Printf(" + %" PRIu64, addr_load_addr - func_load_addr);
2486                                                 else if (addr_load_addr < func_load_addr)
2487                                                     s.Printf(" - %" PRIu64, func_load_addr - addr_load_addr);
2488                                                 var_success = true;
2489                                             }
2490                                         }
2491                                     }
2492                                 }
2493                                 else
2494                                 {
2495                                     Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2496                                     addr_t vaddr = LLDB_INVALID_ADDRESS;
2497                                     if (exe_ctx && !target->GetSectionLoadList().IsEmpty())
2498                                         vaddr = format_addr.GetLoadAddress (target);
2499                                     if (vaddr == LLDB_INVALID_ADDRESS)
2500                                         vaddr = format_addr.GetFileAddress ();
2501 
2502                                     if (vaddr != LLDB_INVALID_ADDRESS)
2503                                     {
2504                                         int addr_width = target->GetArchitecture().GetAddressByteSize() * 2;
2505                                         if (addr_width == 0)
2506                                             addr_width = 16;
2507                                         s.Printf("0x%*.*" PRIx64, addr_width, addr_width, vaddr);
2508                                         var_success = true;
2509                                     }
2510                                 }
2511                             }
2512                         }
2513 
2514                         if (var_success == false)
2515                             success = false;
2516                     }
2517                     p = var_name_end;
2518                 }
2519                 else
2520                     break;
2521             }
2522             else
2523             {
2524                 // We got a dollar sign with no '{' after it, it must just be a dollar sign
2525                 s.PutChar(*p);
2526             }
2527         }
2528         else if (*p == '\\')
2529         {
2530             ++p; // skip the slash
2531             switch (*p)
2532             {
2533             case 'a': s.PutChar ('\a'); break;
2534             case 'b': s.PutChar ('\b'); break;
2535             case 'f': s.PutChar ('\f'); break;
2536             case 'n': s.PutChar ('\n'); break;
2537             case 'r': s.PutChar ('\r'); break;
2538             case 't': s.PutChar ('\t'); break;
2539             case 'v': s.PutChar ('\v'); break;
2540             case '\'': s.PutChar ('\''); break;
2541             case '\\': s.PutChar ('\\'); break;
2542             case '0':
2543                 // 1 to 3 octal chars
2544                 {
2545                     // Make a string that can hold onto the initial zero char,
2546                     // up to 3 octal digits, and a terminating NULL.
2547                     char oct_str[5] = { 0, 0, 0, 0, 0 };
2548 
2549                     int i;
2550                     for (i=0; (p[i] >= '0' && p[i] <= '7') && i<4; ++i)
2551                         oct_str[i] = p[i];
2552 
2553                     // We don't want to consume the last octal character since
2554                     // the main for loop will do this for us, so we advance p by
2555                     // one less than i (even if i is zero)
2556                     p += i - 1;
2557                     unsigned long octal_value = ::strtoul (oct_str, NULL, 8);
2558                     if (octal_value <= UINT8_MAX)
2559                     {
2560                         s.PutChar((char)octal_value);
2561                     }
2562                 }
2563                 break;
2564 
2565             case 'x':
2566                 // hex number in the format
2567                 if (isxdigit(p[1]))
2568                 {
2569                     ++p;    // Skip the 'x'
2570 
2571                     // Make a string that can hold onto two hex chars plus a
2572                     // NULL terminator
2573                     char hex_str[3] = { 0,0,0 };
2574                     hex_str[0] = *p;
2575                     if (isxdigit(p[1]))
2576                     {
2577                         ++p; // Skip the first of the two hex chars
2578                         hex_str[1] = *p;
2579                     }
2580 
2581                     unsigned long hex_value = strtoul (hex_str, NULL, 16);
2582                     if (hex_value <= UINT8_MAX)
2583                         s.PutChar ((char)hex_value);
2584                 }
2585                 else
2586                 {
2587                     s.PutChar('x');
2588                 }
2589                 break;
2590 
2591             default:
2592                 // Just desensitize any other character by just printing what
2593                 // came after the '\'
2594                 s << *p;
2595                 break;
2596 
2597             }
2598 
2599         }
2600     }
2601     if (end)
2602         *end = p;
2603     return success;
2604 }
2605 
2606 void
2607 Debugger::SetLoggingCallback (lldb::LogOutputCallback log_callback, void *baton)
2608 {
2609     // For simplicity's sake, I am not going to deal with how to close down any
2610     // open logging streams, I just redirect everything from here on out to the
2611     // callback.
2612     m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
2613 }
2614 
2615 bool
2616 Debugger::EnableLog (const char *channel, const char **categories, const char *log_file, uint32_t log_options, Stream &error_stream)
2617 {
2618     Log::Callbacks log_callbacks;
2619 
2620     StreamSP log_stream_sp;
2621     if (m_log_callback_stream_sp)
2622     {
2623         log_stream_sp = m_log_callback_stream_sp;
2624         // For now when using the callback mode you always get thread & timestamp.
2625         log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
2626     }
2627     else if (log_file == NULL || *log_file == '\0')
2628     {
2629         log_stream_sp.reset(new StreamFile(GetOutputFile().GetDescriptor(), false));
2630     }
2631     else
2632     {
2633         LogStreamMap::iterator pos = m_log_streams.find(log_file);
2634         if (pos != m_log_streams.end())
2635             log_stream_sp = pos->second.lock();
2636         if (!log_stream_sp)
2637         {
2638             log_stream_sp.reset (new StreamFile (log_file));
2639             m_log_streams[log_file] = log_stream_sp;
2640         }
2641     }
2642     assert (log_stream_sp.get());
2643 
2644     if (log_options == 0)
2645         log_options = LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
2646 
2647     if (Log::GetLogChannelCallbacks (channel, log_callbacks))
2648     {
2649         log_callbacks.enable (log_stream_sp, log_options, categories, &error_stream);
2650         return true;
2651     }
2652     else
2653     {
2654         LogChannelSP log_channel_sp (LogChannel::FindPlugin (channel));
2655         if (log_channel_sp)
2656         {
2657             if (log_channel_sp->Enable (log_stream_sp, log_options, &error_stream, categories))
2658             {
2659                 return true;
2660             }
2661             else
2662             {
2663                 error_stream.Printf ("Invalid log channel '%s'.\n", channel);
2664                 return false;
2665             }
2666         }
2667         else
2668         {
2669             error_stream.Printf ("Invalid log channel '%s'.\n", channel);
2670             return false;
2671         }
2672     }
2673     return false;
2674 }
2675 
2676 SourceManager &
2677 Debugger::GetSourceManager ()
2678 {
2679     if (m_source_manager_ap.get() == NULL)
2680         m_source_manager_ap.reset (new SourceManager (shared_from_this()));
2681     return *m_source_manager_ap;
2682 }
2683 
2684 
2685