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/Core/Debugger.h"
13 
14 #include <map>
15 
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/Type.h"
18 #include "llvm/ADT/StringRef.h"
19 
20 #include "lldb/lldb-private.h"
21 #include "lldb/Core/Module.h"
22 #include "lldb/Core/PluginManager.h"
23 #include "lldb/Core/RegisterValue.h"
24 #include "lldb/Core/State.h"
25 #include "lldb/Core/StreamAsynchronousIO.h"
26 #include "lldb/Core/StreamCallback.h"
27 #include "lldb/Core/StreamFile.h"
28 #include "lldb/Core/StreamString.h"
29 #include "lldb/Core/StructuredData.h"
30 #include "lldb/Core/Timer.h"
31 #include "lldb/Core/ValueObject.h"
32 #include "lldb/Core/ValueObjectVariable.h"
33 #include "lldb/DataFormatters/DataVisualization.h"
34 #include "lldb/DataFormatters/FormatManager.h"
35 #include "lldb/DataFormatters/TypeSummary.h"
36 #include "lldb/Host/ConnectionFileDescriptor.h"
37 #include "lldb/Host/HostInfo.h"
38 #include "lldb/Host/Terminal.h"
39 #include "lldb/Host/ThreadLauncher.h"
40 #include "lldb/Interpreter/CommandInterpreter.h"
41 #include "lldb/Interpreter/OptionValueSInt64.h"
42 #include "lldb/Interpreter/OptionValueString.h"
43 #include "lldb/Symbol/ClangASTContext.h"
44 #include "lldb/Symbol/CompileUnit.h"
45 #include "lldb/Symbol/Function.h"
46 #include "lldb/Symbol/Symbol.h"
47 #include "lldb/Symbol/VariableList.h"
48 #include "lldb/Target/CPPLanguageRuntime.h"
49 #include "lldb/Target/ObjCLanguageRuntime.h"
50 #include "lldb/Target/TargetList.h"
51 #include "lldb/Target/Process.h"
52 #include "lldb/Target/RegisterContext.h"
53 #include "lldb/Target/SectionLoadList.h"
54 #include "lldb/Target/StopInfo.h"
55 #include "lldb/Target/Target.h"
56 #include "lldb/Target/Thread.h"
57 #include "lldb/Utility/AnsiTerminal.h"
58 
59 #include "llvm/Support/DynamicLibrary.h"
60 
61 using namespace lldb;
62 using namespace lldb_private;
63 
64 
65 static uint32_t g_shared_debugger_refcount = 0;
66 static lldb::user_id_t g_unique_id = 1;
67 static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
68 
69 #pragma mark Static Functions
70 
71 static Mutex &
72 GetDebuggerListMutex ()
73 {
74     static Mutex g_mutex(Mutex::eMutexTypeRecursive);
75     return g_mutex;
76 }
77 
78 typedef std::vector<DebuggerSP> DebuggerList;
79 
80 static DebuggerList &
81 GetDebuggerList()
82 {
83     // hide the static debugger list inside a singleton accessor to avoid
84     // global init constructors
85     static DebuggerList g_list;
86     return g_list;
87 }
88 
89 OptionEnumValueElement
90 g_show_disassembly_enum_values[] =
91 {
92     { Debugger::eStopDisassemblyTypeNever,    "never",     "Never show disassembly when displaying a stop context."},
93     { Debugger::eStopDisassemblyTypeNoSource, "no-source", "Show disassembly when there is no source information, or the source file is missing when displaying a stop context."},
94     { Debugger::eStopDisassemblyTypeAlways,   "always",    "Always show disassembly when displaying a stop context."},
95     { 0, NULL, NULL }
96 };
97 
98 OptionEnumValueElement
99 g_language_enumerators[] =
100 {
101     { eScriptLanguageNone,      "none",     "Disable scripting languages."},
102     { eScriptLanguagePython,    "python",   "Select python as the default scripting language."},
103     { eScriptLanguageDefault,   "default",  "Select the lldb default as the default scripting language."},
104     { 0, NULL, NULL }
105 };
106 
107 #define MODULE_WITH_FUNC "{ ${module.file.basename}{`${function.name-with-args}${function.pc-offset}}}"
108 #define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}"
109 
110 #define DEFAULT_THREAD_FORMAT "thread #${thread.index}: tid = ${thread.id%tid}"\
111     "{, ${frame.pc}}"\
112     MODULE_WITH_FUNC\
113     FILE_AND_LINE\
114     "{, name = '${thread.name}'}"\
115     "{, queue = '${thread.queue}'}"\
116     "{, activity = '${thread.info.activity.name}'}" \
117     "{, ${thread.info.trace_messages} messages}" \
118     "{, stop reason = ${thread.stop-reason}}"\
119     "{\\nReturn value: ${thread.return-value}}"\
120     "{\\nCompleted expression: ${thread.completed-expression}}"\
121     "\\n"
122 
123 #define DEFAULT_FRAME_FORMAT "frame #${frame.index}: ${frame.pc}"\
124     MODULE_WITH_FUNC\
125     FILE_AND_LINE\
126     "\\n"
127 
128 #define DEFAULT_DISASSEMBLY_FORMAT "${addr-file-or-load}{ <${function.name-without-args}${function.concrete-only-addr-offset-no-padding}>}: "
129 
130 static PropertyDefinition
131 g_properties[] =
132 {
133 {   "auto-confirm",             OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true all confirmation prompts will receive their default reply." },
134 {   "disassembly-format",       OptionValue::eTypeString , true, 0    , DEFAULT_DISASSEMBLY_FORMAT, NULL, "The default disassembly format string to use when disassembling instruction sequences." },
135 {   "frame-format",             OptionValue::eTypeString , true, 0    , DEFAULT_FRAME_FORMAT, NULL, "The default frame format string to use when displaying stack frame information for threads." },
136 {   "notify-void",              OptionValue::eTypeBoolean, true, false, NULL, NULL, "Notify the user explicitly if an expression returns void (default: false)." },
137 {   "prompt",                   OptionValue::eTypeString , true, OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ", NULL, "The debugger command line prompt displayed for the user." },
138 {   "script-lang",              OptionValue::eTypeEnum   , true, eScriptLanguagePython, NULL, g_language_enumerators, "The script language to be used for evaluating user-written scripts." },
139 {   "stop-disassembly-count",   OptionValue::eTypeSInt64 , true, 4    , NULL, NULL, "The number of disassembly lines to show when displaying a stopped context." },
140 {   "stop-disassembly-display", OptionValue::eTypeEnum   , true, Debugger::eStopDisassemblyTypeNoSource, NULL, g_show_disassembly_enum_values, "Control when to display disassembly when displaying a stopped context." },
141 {   "stop-line-count-after",    OptionValue::eTypeSInt64 , true, 3    , NULL, NULL, "The number of sources lines to display that come after the current source line when displaying a stopped context." },
142 {   "stop-line-count-before",   OptionValue::eTypeSInt64 , true, 3    , NULL, NULL, "The number of sources lines to display that come before the current source line when displaying a stopped context." },
143 {   "term-width",               OptionValue::eTypeSInt64 , true, 80   , NULL, NULL, "The maximum number of columns to use for displaying text." },
144 {   "thread-format",            OptionValue::eTypeString , true, 0    , DEFAULT_THREAD_FORMAT, NULL, "The default thread format string to use when displaying thread information." },
145 {   "use-external-editor",      OptionValue::eTypeBoolean, true, false, NULL, NULL, "Whether to use an external editor or not." },
146 {   "use-color",                OptionValue::eTypeBoolean, true, true , NULL, NULL, "Whether to use Ansi color codes or not." },
147 {   "auto-one-line-summaries",     OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, LLDB will automatically display small structs in one-liner format (default: true)." },
148 
149     {   NULL,                       OptionValue::eTypeInvalid, true, 0    , NULL, NULL, NULL }
150 };
151 
152 enum
153 {
154     ePropertyAutoConfirm = 0,
155     ePropertyDisassemblyFormat,
156     ePropertyFrameFormat,
157     ePropertyNotiftVoid,
158     ePropertyPrompt,
159     ePropertyScriptLanguage,
160     ePropertyStopDisassemblyCount,
161     ePropertyStopDisassemblyDisplay,
162     ePropertyStopLineCountAfter,
163     ePropertyStopLineCountBefore,
164     ePropertyTerminalWidth,
165     ePropertyThreadFormat,
166     ePropertyUseExternalEditor,
167     ePropertyUseColor,
168     ePropertyAutoOneLineSummaries
169 };
170 
171 Debugger::LoadPluginCallbackType Debugger::g_load_plugin_callback = NULL;
172 
173 Error
174 Debugger::SetPropertyValue (const ExecutionContext *exe_ctx,
175                             VarSetOperationType op,
176                             const char *property_path,
177                             const char *value)
178 {
179     bool is_load_script = strcmp(property_path,"target.load-script-from-symbol-file") == 0;
180     TargetSP target_sp;
181     LoadScriptFromSymFile load_script_old_value;
182     if (is_load_script && exe_ctx->GetTargetSP())
183     {
184         target_sp = exe_ctx->GetTargetSP();
185         load_script_old_value = target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
186     }
187     Error error (Properties::SetPropertyValue (exe_ctx, op, property_path, value));
188     if (error.Success())
189     {
190         // FIXME it would be nice to have "on-change" callbacks for properties
191         if (strcmp(property_path, g_properties[ePropertyPrompt].name) == 0)
192         {
193             const char *new_prompt = GetPrompt();
194             std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
195             if (str.length())
196                 new_prompt = str.c_str();
197             GetCommandInterpreter().UpdatePrompt(new_prompt);
198             EventSP prompt_change_event_sp (new Event(CommandInterpreter::eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));
199             GetCommandInterpreter().BroadcastEvent (prompt_change_event_sp);
200         }
201         else if (strcmp(property_path, g_properties[ePropertyUseColor].name) == 0)
202         {
203 			// use-color changed. Ping the prompt so it can reset the ansi terminal codes.
204             SetPrompt (GetPrompt());
205         }
206         else if (is_load_script && target_sp && load_script_old_value == eLoadScriptFromSymFileWarn)
207         {
208             if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() == eLoadScriptFromSymFileTrue)
209             {
210                 std::list<Error> errors;
211                 StreamString feedback_stream;
212                 if (!target_sp->LoadScriptingResources(errors,&feedback_stream))
213                 {
214                     StreamFileSP stream_sp (GetErrorFile());
215                     if (stream_sp)
216                     {
217                         for (auto error : errors)
218                         {
219                             stream_sp->Printf("%s\n",error.AsCString());
220                         }
221                         if (feedback_stream.GetSize())
222                             stream_sp->Printf("%s",feedback_stream.GetData());
223                     }
224                 }
225             }
226         }
227     }
228     return error;
229 }
230 
231 bool
232 Debugger::GetAutoConfirm () const
233 {
234     const uint32_t idx = ePropertyAutoConfirm;
235     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
236 }
237 
238 const char *
239 Debugger::GetDisassemblyFormat() const
240 {
241     const uint32_t idx = ePropertyDisassemblyFormat;
242     return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
243 }
244 
245 const char *
246 Debugger::GetFrameFormat() const
247 {
248     const uint32_t idx = ePropertyFrameFormat;
249     return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
250 }
251 
252 bool
253 Debugger::GetNotifyVoid () const
254 {
255     const uint32_t idx = ePropertyNotiftVoid;
256     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
257 }
258 
259 const char *
260 Debugger::GetPrompt() const
261 {
262     const uint32_t idx = ePropertyPrompt;
263     return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
264 }
265 
266 void
267 Debugger::SetPrompt(const char *p)
268 {
269     const uint32_t idx = ePropertyPrompt;
270     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
271     const char *new_prompt = GetPrompt();
272     std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor());
273     if (str.length())
274         new_prompt = str.c_str();
275     GetCommandInterpreter().UpdatePrompt(new_prompt);
276 }
277 
278 const char *
279 Debugger::GetThreadFormat() const
280 {
281     const uint32_t idx = ePropertyThreadFormat;
282     return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, g_properties[idx].default_cstr_value);
283 }
284 
285 lldb::ScriptLanguage
286 Debugger::GetScriptLanguage() const
287 {
288     const uint32_t idx = ePropertyScriptLanguage;
289     return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
290 }
291 
292 bool
293 Debugger::SetScriptLanguage (lldb::ScriptLanguage script_lang)
294 {
295     const uint32_t idx = ePropertyScriptLanguage;
296     return m_collection_sp->SetPropertyAtIndexAsEnumeration (NULL, idx, script_lang);
297 }
298 
299 uint32_t
300 Debugger::GetTerminalWidth () const
301 {
302     const uint32_t idx = ePropertyTerminalWidth;
303     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
304 }
305 
306 bool
307 Debugger::SetTerminalWidth (uint32_t term_width)
308 {
309     const uint32_t idx = ePropertyTerminalWidth;
310     return m_collection_sp->SetPropertyAtIndexAsSInt64 (NULL, idx, term_width);
311 }
312 
313 bool
314 Debugger::GetUseExternalEditor () const
315 {
316     const uint32_t idx = ePropertyUseExternalEditor;
317     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
318 }
319 
320 bool
321 Debugger::SetUseExternalEditor (bool b)
322 {
323     const uint32_t idx = ePropertyUseExternalEditor;
324     return m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
325 }
326 
327 bool
328 Debugger::GetUseColor () const
329 {
330     const uint32_t idx = ePropertyUseColor;
331     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
332 }
333 
334 bool
335 Debugger::SetUseColor (bool b)
336 {
337     const uint32_t idx = ePropertyUseColor;
338     bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
339     SetPrompt (GetPrompt());
340     return ret;
341 }
342 
343 uint32_t
344 Debugger::GetStopSourceLineCount (bool before) const
345 {
346     const uint32_t idx = before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter;
347     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
348 }
349 
350 Debugger::StopDisassemblyType
351 Debugger::GetStopDisassemblyDisplay () const
352 {
353     const uint32_t idx = ePropertyStopDisassemblyDisplay;
354     return (Debugger::StopDisassemblyType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
355 }
356 
357 uint32_t
358 Debugger::GetDisassemblyLineCount () const
359 {
360     const uint32_t idx = ePropertyStopDisassemblyCount;
361     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
362 }
363 
364 bool
365 Debugger::GetAutoOneLineSummaries () const
366 {
367     const uint32_t idx = ePropertyAutoOneLineSummaries;
368     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, true);
369 
370 }
371 
372 #pragma mark Debugger
373 
374 //const DebuggerPropertiesSP &
375 //Debugger::GetSettings() const
376 //{
377 //    return m_properties_sp;
378 //}
379 //
380 
381 int
382 Debugger::TestDebuggerRefCount ()
383 {
384     return g_shared_debugger_refcount;
385 }
386 
387 void
388 Debugger::Initialize (LoadPluginCallbackType load_plugin_callback)
389 {
390     g_load_plugin_callback = load_plugin_callback;
391     if (g_shared_debugger_refcount++ == 0)
392         lldb_private::Initialize();
393 }
394 
395 void
396 Debugger::Terminate ()
397 {
398     if (g_shared_debugger_refcount > 0)
399     {
400         g_shared_debugger_refcount--;
401         if (g_shared_debugger_refcount == 0)
402         {
403             lldb_private::WillTerminate();
404             lldb_private::Terminate();
405 
406             // Clear our master list of debugger objects
407             Mutex::Locker locker (GetDebuggerListMutex ());
408             GetDebuggerList().clear();
409         }
410     }
411 }
412 
413 void
414 Debugger::SettingsInitialize ()
415 {
416     Target::SettingsInitialize ();
417 }
418 
419 void
420 Debugger::SettingsTerminate ()
421 {
422     Target::SettingsTerminate ();
423 }
424 
425 bool
426 Debugger::LoadPlugin (const FileSpec& spec, Error& error)
427 {
428     if (g_load_plugin_callback)
429     {
430         llvm::sys::DynamicLibrary dynlib = g_load_plugin_callback (shared_from_this(), spec, error);
431         if (dynlib.isValid())
432         {
433             m_loaded_plugins.push_back(dynlib);
434             return true;
435         }
436     }
437     else
438     {
439         // The g_load_plugin_callback is registered in SBDebugger::Initialize()
440         // and if the public API layer isn't available (code is linking against
441         // all of the internal LLDB static libraries), then we can't load plugins
442         error.SetErrorString("Public API layer is not available");
443     }
444     return false;
445 }
446 
447 static FileSpec::EnumerateDirectoryResult
448 LoadPluginCallback
449 (
450  void *baton,
451  FileSpec::FileType file_type,
452  const FileSpec &file_spec
453  )
454 {
455     Error error;
456 
457     static ConstString g_dylibext("dylib");
458     static ConstString g_solibext("so");
459 
460     if (!baton)
461         return FileSpec::eEnumerateDirectoryResultQuit;
462 
463     Debugger *debugger = (Debugger*)baton;
464 
465     // If we have a regular file, a symbolic link or unknown file type, try
466     // and process the file. We must handle unknown as sometimes the directory
467     // enumeration might be enumerating a file system that doesn't have correct
468     // file type information.
469     if (file_type == FileSpec::eFileTypeRegular         ||
470         file_type == FileSpec::eFileTypeSymbolicLink    ||
471         file_type == FileSpec::eFileTypeUnknown          )
472     {
473         FileSpec plugin_file_spec (file_spec);
474         plugin_file_spec.ResolvePath ();
475 
476         if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
477             plugin_file_spec.GetFileNameExtension() != g_solibext)
478         {
479             return FileSpec::eEnumerateDirectoryResultNext;
480         }
481 
482         Error plugin_load_error;
483         debugger->LoadPlugin (plugin_file_spec, plugin_load_error);
484 
485         return FileSpec::eEnumerateDirectoryResultNext;
486     }
487 
488     else if (file_type == FileSpec::eFileTypeUnknown     ||
489         file_type == FileSpec::eFileTypeDirectory   ||
490         file_type == FileSpec::eFileTypeSymbolicLink )
491     {
492         // Try and recurse into anything that a directory or symbolic link.
493         // We must also do this for unknown as sometimes the directory enumeration
494         // might be enumerating a file system that doesn't have correct file type
495         // information.
496         return FileSpec::eEnumerateDirectoryResultEnter;
497     }
498 
499     return FileSpec::eEnumerateDirectoryResultNext;
500 }
501 
502 void
503 Debugger::InstanceInitialize ()
504 {
505     FileSpec dir_spec;
506     const bool find_directories = true;
507     const bool find_files = true;
508     const bool find_other = true;
509     char dir_path[PATH_MAX];
510     if (HostInfo::GetLLDBPath(ePathTypeLLDBSystemPlugins, dir_spec))
511     {
512         if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
513         {
514             FileSpec::EnumerateDirectory (dir_path,
515                                           find_directories,
516                                           find_files,
517                                           find_other,
518                                           LoadPluginCallback,
519                                           this);
520         }
521     }
522 
523     if (HostInfo::GetLLDBPath(ePathTypeLLDBUserPlugins, dir_spec))
524     {
525         if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path)))
526         {
527             FileSpec::EnumerateDirectory (dir_path,
528                                           find_directories,
529                                           find_files,
530                                           find_other,
531                                           LoadPluginCallback,
532                                           this);
533         }
534     }
535 
536     PluginManager::DebuggerInitialize (*this);
537 }
538 
539 DebuggerSP
540 Debugger::CreateInstance (lldb::LogOutputCallback log_callback, void *baton)
541 {
542     DebuggerSP debugger_sp (new Debugger(log_callback, baton));
543     if (g_shared_debugger_refcount > 0)
544     {
545         Mutex::Locker locker (GetDebuggerListMutex ());
546         GetDebuggerList().push_back(debugger_sp);
547     }
548     debugger_sp->InstanceInitialize ();
549     return debugger_sp;
550 }
551 
552 void
553 Debugger::Destroy (DebuggerSP &debugger_sp)
554 {
555     if (debugger_sp.get() == NULL)
556         return;
557 
558     debugger_sp->Clear();
559 
560     if (g_shared_debugger_refcount > 0)
561     {
562         Mutex::Locker locker (GetDebuggerListMutex ());
563         DebuggerList &debugger_list = GetDebuggerList ();
564         DebuggerList::iterator pos, end = debugger_list.end();
565         for (pos = debugger_list.begin (); pos != end; ++pos)
566         {
567             if ((*pos).get() == debugger_sp.get())
568             {
569                 debugger_list.erase (pos);
570                 return;
571             }
572         }
573     }
574 }
575 
576 DebuggerSP
577 Debugger::FindDebuggerWithInstanceName (const ConstString &instance_name)
578 {
579     DebuggerSP debugger_sp;
580     if (g_shared_debugger_refcount > 0)
581     {
582         Mutex::Locker locker (GetDebuggerListMutex ());
583         DebuggerList &debugger_list = GetDebuggerList();
584         DebuggerList::iterator pos, end = debugger_list.end();
585 
586         for (pos = debugger_list.begin(); pos != end; ++pos)
587         {
588             if ((*pos).get()->m_instance_name == instance_name)
589             {
590                 debugger_sp = *pos;
591                 break;
592             }
593         }
594     }
595     return debugger_sp;
596 }
597 
598 TargetSP
599 Debugger::FindTargetWithProcessID (lldb::pid_t pid)
600 {
601     TargetSP target_sp;
602     if (g_shared_debugger_refcount > 0)
603     {
604         Mutex::Locker locker (GetDebuggerListMutex ());
605         DebuggerList &debugger_list = GetDebuggerList();
606         DebuggerList::iterator pos, end = debugger_list.end();
607         for (pos = debugger_list.begin(); pos != end; ++pos)
608         {
609             target_sp = (*pos)->GetTargetList().FindTargetWithProcessID (pid);
610             if (target_sp)
611                 break;
612         }
613     }
614     return target_sp;
615 }
616 
617 TargetSP
618 Debugger::FindTargetWithProcess (Process *process)
619 {
620     TargetSP target_sp;
621     if (g_shared_debugger_refcount > 0)
622     {
623         Mutex::Locker locker (GetDebuggerListMutex ());
624         DebuggerList &debugger_list = GetDebuggerList();
625         DebuggerList::iterator pos, end = debugger_list.end();
626         for (pos = debugger_list.begin(); pos != end; ++pos)
627         {
628             target_sp = (*pos)->GetTargetList().FindTargetWithProcess (process);
629             if (target_sp)
630                 break;
631         }
632     }
633     return target_sp;
634 }
635 
636 Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton) :
637     UserID(g_unique_id++),
638     Properties(OptionValuePropertiesSP(new OptionValueProperties())),
639     m_input_file_sp(new StreamFile(stdin, false)),
640     m_output_file_sp(new StreamFile(stdout, false)),
641     m_error_file_sp(new StreamFile(stderr, false)),
642     m_terminal_state(),
643     m_target_list(*this),
644     m_platform_list(),
645     m_listener("lldb.Debugger"),
646     m_source_manager_ap(),
647     m_source_file_cache(),
648     m_command_interpreter_ap(new CommandInterpreter(*this, eScriptLanguageDefault, false)),
649     m_input_reader_stack(),
650     m_instance_name(),
651     m_loaded_plugins()
652 {
653     char instance_cstr[256];
654     snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID());
655     m_instance_name.SetCString(instance_cstr);
656     if (log_callback)
657         m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
658     m_command_interpreter_ap->Initialize ();
659     // Always add our default platform to the platform list
660     PlatformSP default_platform_sp (Platform::GetHostPlatform());
661     assert (default_platform_sp.get());
662     m_platform_list.Append (default_platform_sp, true);
663 
664     m_collection_sp->Initialize (g_properties);
665     m_collection_sp->AppendProperty (ConstString("target"),
666                                      ConstString("Settings specify to debugging targets."),
667                                      true,
668                                      Target::GetGlobalProperties()->GetValueProperties());
669     if (m_command_interpreter_ap.get())
670     {
671         m_collection_sp->AppendProperty (ConstString("interpreter"),
672                                          ConstString("Settings specify to the debugger's command interpreter."),
673                                          true,
674                                          m_command_interpreter_ap->GetValueProperties());
675     }
676     OptionValueSInt64 *term_width = m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64 (NULL, ePropertyTerminalWidth);
677     term_width->SetMinimumValue(10);
678     term_width->SetMaximumValue(1024);
679 
680     // Turn off use-color if this is a dumb terminal.
681     const char *term = getenv ("TERM");
682     if (term && !strcmp (term, "dumb"))
683         SetUseColor (false);
684 }
685 
686 Debugger::~Debugger ()
687 {
688     Clear();
689 }
690 
691 void
692 Debugger::Clear()
693 {
694     ClearIOHandlers();
695     StopIOHandlerThread();
696     StopEventHandlerThread();
697     m_listener.Clear();
698     int num_targets = m_target_list.GetNumTargets();
699     for (int i = 0; i < num_targets; i++)
700     {
701         TargetSP target_sp (m_target_list.GetTargetAtIndex (i));
702         if (target_sp)
703         {
704             ProcessSP process_sp (target_sp->GetProcessSP());
705             if (process_sp)
706                 process_sp->Finalize();
707             target_sp->Destroy();
708         }
709     }
710     BroadcasterManager::Clear ();
711 
712     // Close the input file _before_ we close the input read communications class
713     // as it does NOT own the input file, our m_input_file does.
714     m_terminal_state.Clear();
715     if (m_input_file_sp)
716         m_input_file_sp->GetFile().Close ();
717 
718     m_command_interpreter_ap->Clear();
719 }
720 
721 bool
722 Debugger::GetCloseInputOnEOF () const
723 {
724 //    return m_input_comm.GetCloseOnEOF();
725     return false;
726 }
727 
728 void
729 Debugger::SetCloseInputOnEOF (bool b)
730 {
731 //    m_input_comm.SetCloseOnEOF(b);
732 }
733 
734 bool
735 Debugger::GetAsyncExecution ()
736 {
737     return !m_command_interpreter_ap->GetSynchronous();
738 }
739 
740 void
741 Debugger::SetAsyncExecution (bool async_execution)
742 {
743     m_command_interpreter_ap->SetSynchronous (!async_execution);
744 }
745 
746 
747 void
748 Debugger::SetInputFileHandle (FILE *fh, bool tranfer_ownership)
749 {
750     if (m_input_file_sp)
751         m_input_file_sp->GetFile().SetStream (fh, tranfer_ownership);
752     else
753         m_input_file_sp.reset (new StreamFile (fh, tranfer_ownership));
754 
755     File &in_file = m_input_file_sp->GetFile();
756     if (in_file.IsValid() == false)
757         in_file.SetStream (stdin, true);
758 
759     // Save away the terminal state if that is relevant, so that we can restore it in RestoreInputState.
760     SaveInputTerminalState ();
761 }
762 
763 void
764 Debugger::SetOutputFileHandle (FILE *fh, bool tranfer_ownership)
765 {
766     if (m_output_file_sp)
767         m_output_file_sp->GetFile().SetStream (fh, tranfer_ownership);
768     else
769         m_output_file_sp.reset (new StreamFile (fh, tranfer_ownership));
770 
771     File &out_file = m_output_file_sp->GetFile();
772     if (out_file.IsValid() == false)
773         out_file.SetStream (stdout, false);
774 
775     // do not create the ScriptInterpreter just for setting the output file handle
776     // as the constructor will know how to do the right thing on its own
777     const bool can_create = false;
778     ScriptInterpreter* script_interpreter = GetCommandInterpreter().GetScriptInterpreter(can_create);
779     if (script_interpreter)
780         script_interpreter->ResetOutputFileHandle (fh);
781 }
782 
783 void
784 Debugger::SetErrorFileHandle (FILE *fh, bool tranfer_ownership)
785 {
786     if (m_error_file_sp)
787         m_error_file_sp->GetFile().SetStream (fh, tranfer_ownership);
788     else
789         m_error_file_sp.reset (new StreamFile (fh, tranfer_ownership));
790 
791     File &err_file = m_error_file_sp->GetFile();
792     if (err_file.IsValid() == false)
793         err_file.SetStream (stderr, false);
794 }
795 
796 void
797 Debugger::SaveInputTerminalState ()
798 {
799     if (m_input_file_sp)
800     {
801         File &in_file = m_input_file_sp->GetFile();
802         if (in_file.GetDescriptor() != File::kInvalidDescriptor)
803             m_terminal_state.Save(in_file.GetDescriptor(), true);
804     }
805 }
806 
807 void
808 Debugger::RestoreInputTerminalState ()
809 {
810     m_terminal_state.Restore();
811 }
812 
813 ExecutionContext
814 Debugger::GetSelectedExecutionContext ()
815 {
816     ExecutionContext exe_ctx;
817     TargetSP target_sp(GetSelectedTarget());
818     exe_ctx.SetTargetSP (target_sp);
819 
820     if (target_sp)
821     {
822         ProcessSP process_sp (target_sp->GetProcessSP());
823         exe_ctx.SetProcessSP (process_sp);
824         if (process_sp && process_sp->IsRunning() == false)
825         {
826             ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
827             if (thread_sp)
828             {
829                 exe_ctx.SetThreadSP (thread_sp);
830                 exe_ctx.SetFrameSP (thread_sp->GetSelectedFrame());
831                 if (exe_ctx.GetFramePtr() == NULL)
832                     exe_ctx.SetFrameSP (thread_sp->GetStackFrameAtIndex (0));
833             }
834         }
835     }
836     return exe_ctx;
837 }
838 
839 void
840 Debugger::DispatchInputInterrupt ()
841 {
842     Mutex::Locker locker (m_input_reader_stack.GetMutex());
843     IOHandlerSP reader_sp (m_input_reader_stack.Top());
844     if (reader_sp)
845         reader_sp->Interrupt();
846 }
847 
848 void
849 Debugger::DispatchInputEndOfFile ()
850 {
851     Mutex::Locker locker (m_input_reader_stack.GetMutex());
852     IOHandlerSP reader_sp (m_input_reader_stack.Top());
853     if (reader_sp)
854         reader_sp->GotEOF();
855 }
856 
857 void
858 Debugger::ClearIOHandlers ()
859 {
860     // The bottom input reader should be the main debugger input reader.  We do not want to close that one here.
861     Mutex::Locker locker (m_input_reader_stack.GetMutex());
862     while (m_input_reader_stack.GetSize() > 1)
863     {
864         IOHandlerSP reader_sp (m_input_reader_stack.Top());
865         if (reader_sp)
866         {
867             m_input_reader_stack.Pop();
868             reader_sp->SetIsDone(true);
869             reader_sp->Cancel();
870         }
871     }
872 }
873 
874 void
875 Debugger::ExecuteIOHanders()
876 {
877 
878     while (1)
879     {
880         IOHandlerSP reader_sp(m_input_reader_stack.Top());
881         if (!reader_sp)
882             break;
883 
884         reader_sp->Activate();
885         reader_sp->Run();
886         reader_sp->Deactivate();
887 
888         // Remove all input readers that are done from the top of the stack
889         while (1)
890         {
891             IOHandlerSP top_reader_sp = m_input_reader_stack.Top();
892             if (top_reader_sp && top_reader_sp->GetIsDone())
893                 m_input_reader_stack.Pop();
894             else
895                 break;
896         }
897     }
898     ClearIOHandlers();
899 }
900 
901 bool
902 Debugger::IsTopIOHandler (const lldb::IOHandlerSP& reader_sp)
903 {
904     return m_input_reader_stack.IsTop (reader_sp);
905 }
906 
907 
908 ConstString
909 Debugger::GetTopIOHandlerControlSequence(char ch)
910 {
911     return m_input_reader_stack.GetTopIOHandlerControlSequence (ch);
912 }
913 
914 void
915 Debugger::RunIOHandler (const IOHandlerSP& reader_sp)
916 {
917     PushIOHandler (reader_sp);
918 
919     IOHandlerSP top_reader_sp = reader_sp;
920     while (top_reader_sp)
921     {
922         top_reader_sp->Activate();
923         top_reader_sp->Run();
924         top_reader_sp->Deactivate();
925 
926         if (top_reader_sp.get() == reader_sp.get())
927         {
928             if (PopIOHandler (reader_sp))
929                 break;
930         }
931 
932         while (1)
933         {
934             top_reader_sp = m_input_reader_stack.Top();
935             if (top_reader_sp && top_reader_sp->GetIsDone())
936                 m_input_reader_stack.Pop();
937             else
938                 break;
939         }
940     }
941 }
942 
943 void
944 Debugger::AdoptTopIOHandlerFilesIfInvalid (StreamFileSP &in, StreamFileSP &out, StreamFileSP &err)
945 {
946     // Before an IOHandler runs, it must have in/out/err streams.
947     // This function is called when one ore more of the streams
948     // are NULL. We use the top input reader's in/out/err streams,
949     // or fall back to the debugger file handles, or we fall back
950     // onto stdin/stdout/stderr as a last resort.
951 
952     Mutex::Locker locker (m_input_reader_stack.GetMutex());
953     IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
954     // If no STDIN has been set, then set it appropriately
955     if (!in)
956     {
957         if (top_reader_sp)
958             in = top_reader_sp->GetInputStreamFile();
959         else
960             in = GetInputFile();
961 
962         // If there is nothing, use stdin
963         if (!in)
964             in = StreamFileSP(new StreamFile(stdin, false));
965     }
966     // If no STDOUT has been set, then set it appropriately
967     if (!out)
968     {
969         if (top_reader_sp)
970             out = top_reader_sp->GetOutputStreamFile();
971         else
972             out = GetOutputFile();
973 
974         // If there is nothing, use stdout
975         if (!out)
976             out = StreamFileSP(new StreamFile(stdout, false));
977     }
978     // If no STDERR has been set, then set it appropriately
979     if (!err)
980     {
981         if (top_reader_sp)
982             err = top_reader_sp->GetErrorStreamFile();
983         else
984             err = GetErrorFile();
985 
986         // If there is nothing, use stderr
987         if (!err)
988             err = StreamFileSP(new StreamFile(stdout, false));
989 
990     }
991 }
992 
993 void
994 Debugger::PushIOHandler (const IOHandlerSP& reader_sp)
995 {
996     if (!reader_sp)
997         return;
998 
999     // Got the current top input reader...
1000     IOHandlerSP top_reader_sp (m_input_reader_stack.Top());
1001 
1002     // Don't push the same IO handler twice...
1003     if (reader_sp.get() != top_reader_sp.get())
1004     {
1005         // Push our new input reader
1006         m_input_reader_stack.Push (reader_sp);
1007 
1008         // Interrupt the top input reader to it will exit its Run() function
1009         // and let this new input reader take over
1010         if (top_reader_sp)
1011             top_reader_sp->Deactivate();
1012     }
1013 }
1014 
1015 bool
1016 Debugger::PopIOHandler (const IOHandlerSP& pop_reader_sp)
1017 {
1018     bool result = false;
1019 
1020     Mutex::Locker locker (m_input_reader_stack.GetMutex());
1021 
1022     // The reader on the stop of the stack is done, so let the next
1023     // read on the stack refresh its prompt and if there is one...
1024     if (!m_input_reader_stack.IsEmpty())
1025     {
1026         IOHandlerSP reader_sp(m_input_reader_stack.Top());
1027 
1028         if (!pop_reader_sp || pop_reader_sp.get() == reader_sp.get())
1029         {
1030             reader_sp->Deactivate();
1031             reader_sp->Cancel();
1032             m_input_reader_stack.Pop ();
1033 
1034             reader_sp = m_input_reader_stack.Top();
1035             if (reader_sp)
1036                 reader_sp->Activate();
1037 
1038             result = true;
1039         }
1040     }
1041     return result;
1042 }
1043 
1044 bool
1045 Debugger::HideTopIOHandler()
1046 {
1047     Mutex::Locker locker;
1048 
1049     if (locker.TryLock(m_input_reader_stack.GetMutex()))
1050     {
1051         IOHandlerSP reader_sp(m_input_reader_stack.Top());
1052         if (reader_sp)
1053             reader_sp->Hide();
1054         return true;
1055     }
1056     return false;
1057 }
1058 
1059 void
1060 Debugger::RefreshTopIOHandler()
1061 {
1062     IOHandlerSP reader_sp(m_input_reader_stack.Top());
1063     if (reader_sp)
1064         reader_sp->Refresh();
1065 }
1066 
1067 
1068 StreamSP
1069 Debugger::GetAsyncOutputStream ()
1070 {
1071     return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
1072                                                CommandInterpreter::eBroadcastBitAsynchronousOutputData));
1073 }
1074 
1075 StreamSP
1076 Debugger::GetAsyncErrorStream ()
1077 {
1078     return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
1079                                                CommandInterpreter::eBroadcastBitAsynchronousErrorData));
1080 }
1081 
1082 size_t
1083 Debugger::GetNumDebuggers()
1084 {
1085     if (g_shared_debugger_refcount > 0)
1086     {
1087         Mutex::Locker locker (GetDebuggerListMutex ());
1088         return GetDebuggerList().size();
1089     }
1090     return 0;
1091 }
1092 
1093 lldb::DebuggerSP
1094 Debugger::GetDebuggerAtIndex (size_t index)
1095 {
1096     DebuggerSP debugger_sp;
1097 
1098     if (g_shared_debugger_refcount > 0)
1099     {
1100         Mutex::Locker locker (GetDebuggerListMutex ());
1101         DebuggerList &debugger_list = GetDebuggerList();
1102 
1103         if (index < debugger_list.size())
1104             debugger_sp = debugger_list[index];
1105     }
1106 
1107     return debugger_sp;
1108 }
1109 
1110 DebuggerSP
1111 Debugger::FindDebuggerWithID (lldb::user_id_t id)
1112 {
1113     DebuggerSP debugger_sp;
1114 
1115     if (g_shared_debugger_refcount > 0)
1116     {
1117         Mutex::Locker locker (GetDebuggerListMutex ());
1118         DebuggerList &debugger_list = GetDebuggerList();
1119         DebuggerList::iterator pos, end = debugger_list.end();
1120         for (pos = debugger_list.begin(); pos != end; ++pos)
1121         {
1122             if ((*pos).get()->GetID() == id)
1123             {
1124                 debugger_sp = *pos;
1125                 break;
1126             }
1127         }
1128     }
1129     return debugger_sp;
1130 }
1131 
1132 #if 0
1133 static void
1134 TestPromptFormats (StackFrame *frame)
1135 {
1136     if (frame == NULL)
1137         return;
1138 
1139     StreamString s;
1140     const char *prompt_format =
1141     "{addr = '${addr}'\n}"
1142     "{addr-file-or-load = '${addr-file-or-load}'\n}"
1143     "{current-pc-arrow = '${current-pc-arrow}'\n}"
1144     "{process.id = '${process.id}'\n}"
1145     "{process.name = '${process.name}'\n}"
1146     "{process.file.basename = '${process.file.basename}'\n}"
1147     "{process.file.fullpath = '${process.file.fullpath}'\n}"
1148     "{thread.id = '${thread.id}'\n}"
1149     "{thread.index = '${thread.index}'\n}"
1150     "{thread.name = '${thread.name}'\n}"
1151     "{thread.queue = '${thread.queue}'\n}"
1152     "{thread.stop-reason = '${thread.stop-reason}'\n}"
1153     "{target.arch = '${target.arch}'\n}"
1154     "{module.file.basename = '${module.file.basename}'\n}"
1155     "{module.file.fullpath = '${module.file.fullpath}'\n}"
1156     "{file.basename = '${file.basename}'\n}"
1157     "{file.fullpath = '${file.fullpath}'\n}"
1158     "{frame.index = '${frame.index}'\n}"
1159     "{frame.pc = '${frame.pc}'\n}"
1160     "{frame.sp = '${frame.sp}'\n}"
1161     "{frame.fp = '${frame.fp}'\n}"
1162     "{frame.flags = '${frame.flags}'\n}"
1163     "{frame.reg.rdi = '${frame.reg.rdi}'\n}"
1164     "{frame.reg.rip = '${frame.reg.rip}'\n}"
1165     "{frame.reg.rsp = '${frame.reg.rsp}'\n}"
1166     "{frame.reg.rbp = '${frame.reg.rbp}'\n}"
1167     "{frame.reg.rflags = '${frame.reg.rflags}'\n}"
1168     "{frame.reg.xmm0 = '${frame.reg.xmm0}'\n}"
1169     "{frame.reg.carp = '${frame.reg.carp}'\n}"
1170     "{function.id = '${function.id}'\n}"
1171     "{function.changed = '${function.changed}'\n}"
1172     "{function.initial-function = '${function.initial-function}'\n}"
1173     "{function.name = '${function.name}'\n}"
1174     "{function.name-without-args = '${function.name-without-args}'\n}"
1175     "{function.name-with-args = '${function.name-with-args}'\n}"
1176     "{function.addr-offset = '${function.addr-offset}'\n}"
1177     "{function.concrete-only-addr-offset-no-padding = '${function.concrete-only-addr-offset-no-padding}'\n}"
1178     "{function.line-offset = '${function.line-offset}'\n}"
1179     "{function.pc-offset = '${function.pc-offset}'\n}"
1180     "{line.file.basename = '${line.file.basename}'\n}"
1181     "{line.file.fullpath = '${line.file.fullpath}'\n}"
1182     "{line.number = '${line.number}'\n}"
1183     "{line.start-addr = '${line.start-addr}'\n}"
1184     "{line.end-addr = '${line.end-addr}'\n}"
1185 ;
1186 
1187     SymbolContext sc (frame->GetSymbolContext(eSymbolContextEverything));
1188     ExecutionContext exe_ctx;
1189     frame->CalculateExecutionContext(exe_ctx);
1190     if (Debugger::FormatPrompt (prompt_format, &sc, &exe_ctx, &sc.line_entry.range.GetBaseAddress(), s))
1191     {
1192         printf("%s\n", s.GetData());
1193     }
1194     else
1195     {
1196         printf ("what we got: %s\n", s.GetData());
1197     }
1198 }
1199 #endif
1200 
1201 static bool
1202 ScanFormatDescriptor (const char* var_name_begin,
1203                       const char* var_name_end,
1204                       const char** var_name_final,
1205                       const char** percent_position,
1206                       Format* custom_format,
1207                       ValueObject::ValueObjectRepresentationStyle* val_obj_display)
1208 {
1209     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1210     *percent_position = ::strchr(var_name_begin,'%');
1211     if (!*percent_position || *percent_position > var_name_end)
1212     {
1213         if (log)
1214             log->Printf("[ScanFormatDescriptor] no format descriptor in string, skipping");
1215         *var_name_final = var_name_end;
1216     }
1217     else
1218     {
1219         *var_name_final = *percent_position;
1220         std::string format_name(*var_name_final+1, var_name_end-*var_name_final-1);
1221         if (log)
1222             log->Printf("[ScanFormatDescriptor] parsing %s as a format descriptor", format_name.c_str());
1223         if ( !FormatManager::GetFormatFromCString(format_name.c_str(),
1224                                                   true,
1225                                                   *custom_format) )
1226         {
1227             if (log)
1228                 log->Printf("[ScanFormatDescriptor] %s is an unknown format", format_name.c_str());
1229 
1230             switch (format_name.front())
1231             {
1232                 case '@':             // if this is an @ sign, print ObjC description
1233                     *val_obj_display = ValueObject::eValueObjectRepresentationStyleLanguageSpecific;
1234                     break;
1235                 case 'V': // if this is a V, print the value using the default format
1236                     *val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1237                     break;
1238                 case 'L': // if this is an L, print the location of the value
1239                     *val_obj_display = ValueObject::eValueObjectRepresentationStyleLocation;
1240                     break;
1241                 case 'S': // if this is an S, print the summary after all
1242                     *val_obj_display = ValueObject::eValueObjectRepresentationStyleSummary;
1243                     break;
1244                 case '#': // if this is a '#', print the number of children
1245                     *val_obj_display = ValueObject::eValueObjectRepresentationStyleChildrenCount;
1246                     break;
1247                 case 'T': // if this is a 'T', print the type
1248                     *val_obj_display = ValueObject::eValueObjectRepresentationStyleType;
1249                     break;
1250                 case 'N': // if this is a 'N', print the name
1251                     *val_obj_display = ValueObject::eValueObjectRepresentationStyleName;
1252                     break;
1253                 case '>': // if this is a '>', print the name
1254                     *val_obj_display = ValueObject::eValueObjectRepresentationStyleExpressionPath;
1255                     break;
1256                 default:
1257                     if (log)
1258                         log->Printf("ScanFormatDescriptor] %s is an error, leaving the previous value alone", format_name.c_str());
1259                     break;
1260             }
1261         }
1262         // a good custom format tells us to print the value using it
1263         else
1264         {
1265             if (log)
1266                 log->Printf("[ScanFormatDescriptor] will display value for this VO");
1267             *val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1268         }
1269     }
1270     if (log)
1271         log->Printf("[ScanFormatDescriptor] final format description outcome: custom_format = %d, val_obj_display = %d",
1272                     *custom_format,
1273                     *val_obj_display);
1274     return true;
1275 }
1276 
1277 static bool
1278 ScanBracketedRange (const char* var_name_begin,
1279                     const char* var_name_end,
1280                     const char* var_name_final,
1281                     const char** open_bracket_position,
1282                     const char** separator_position,
1283                     const char** close_bracket_position,
1284                     const char** var_name_final_if_array_range,
1285                     int64_t* index_lower,
1286                     int64_t* index_higher)
1287 {
1288     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1289     *open_bracket_position = ::strchr(var_name_begin,'[');
1290     if (*open_bracket_position && *open_bracket_position < var_name_final)
1291     {
1292         *separator_position = ::strchr(*open_bracket_position,'-'); // might be NULL if this is a simple var[N] bitfield
1293         *close_bracket_position = ::strchr(*open_bracket_position,']');
1294         // as usual, we assume that [] will come before %
1295         //printf("trying to expand a []\n");
1296         *var_name_final_if_array_range = *open_bracket_position;
1297         if (*close_bracket_position - *open_bracket_position == 1)
1298         {
1299             if (log)
1300                 log->Printf("[ScanBracketedRange] '[]' detected.. going from 0 to end of data");
1301             *index_lower = 0;
1302         }
1303         else if (*separator_position == NULL || *separator_position > var_name_end)
1304         {
1305             char *end = NULL;
1306             *index_lower = ::strtoul (*open_bracket_position+1, &end, 0);
1307             *index_higher = *index_lower;
1308             if (log)
1309                 log->Printf("[ScanBracketedRange] [%" PRId64 "] detected, high index is same", *index_lower);
1310         }
1311         else if (*close_bracket_position && *close_bracket_position < var_name_end)
1312         {
1313             char *end = NULL;
1314             *index_lower = ::strtoul (*open_bracket_position+1, &end, 0);
1315             *index_higher = ::strtoul (*separator_position+1, &end, 0);
1316             if (log)
1317                 log->Printf("[ScanBracketedRange] [%" PRId64 "-%" PRId64 "] detected", *index_lower, *index_higher);
1318         }
1319         else
1320         {
1321             if (log)
1322                 log->Printf("[ScanBracketedRange] expression is erroneous, cannot extract indices out of it");
1323             return false;
1324         }
1325         if (*index_lower > *index_higher && *index_higher > 0)
1326         {
1327             if (log)
1328                 log->Printf("[ScanBracketedRange] swapping indices");
1329             int64_t temp = *index_lower;
1330             *index_lower = *index_higher;
1331             *index_higher = temp;
1332         }
1333     }
1334     else if (log)
1335             log->Printf("[ScanBracketedRange] no bracketed range, skipping entirely");
1336     return true;
1337 }
1338 
1339 template <typename T>
1340 static bool RunScriptFormatKeyword(Stream &s, ScriptInterpreter *script_interpreter, T t, const std::string& script_name)
1341 {
1342     if (script_interpreter)
1343     {
1344         Error script_error;
1345         std::string script_output;
1346 
1347         if (script_interpreter->RunScriptFormatKeyword(script_name.c_str(), t, script_output, script_error) && script_error.Success())
1348         {
1349             s.Printf("%s", script_output.c_str());
1350             return true;
1351         }
1352         else
1353         {
1354             s.Printf("<error: %s>",script_error.AsCString());
1355         }
1356     }
1357     return false;
1358 }
1359 
1360 static ValueObjectSP
1361 ExpandIndexedExpression (ValueObject* valobj,
1362                          size_t index,
1363                          StackFrame* frame,
1364                          bool deref_pointer)
1365 {
1366     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1367     const char* ptr_deref_format = "[%d]";
1368     std::string ptr_deref_buffer(10,0);
1369     ::sprintf(&ptr_deref_buffer[0], ptr_deref_format, index);
1370     if (log)
1371         log->Printf("[ExpandIndexedExpression] name to deref: %s",ptr_deref_buffer.c_str());
1372     const char* first_unparsed;
1373     ValueObject::GetValueForExpressionPathOptions options;
1374     ValueObject::ExpressionPathEndResultType final_value_type;
1375     ValueObject::ExpressionPathScanEndReason reason_to_stop;
1376     ValueObject::ExpressionPathAftermath what_next = (deref_pointer ? ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
1377     ValueObjectSP item = valobj->GetValueForExpressionPath (ptr_deref_buffer.c_str(),
1378                                                           &first_unparsed,
1379                                                           &reason_to_stop,
1380                                                           &final_value_type,
1381                                                           options,
1382                                                           &what_next);
1383     if (!item)
1384     {
1385         if (log)
1386             log->Printf("[ExpandIndexedExpression] ERROR: unparsed portion = %s, why stopping = %d,"
1387                " final_value_type %d",
1388                first_unparsed, reason_to_stop, final_value_type);
1389     }
1390     else
1391     {
1392         if (log)
1393             log->Printf("[ExpandIndexedExpression] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
1394                " final_value_type %d",
1395                first_unparsed, reason_to_stop, final_value_type);
1396     }
1397     return item;
1398 }
1399 
1400 static inline bool
1401 IsToken(const char *var_name_begin, const char *var)
1402 {
1403     return (::strncmp (var_name_begin, var, strlen(var)) == 0);
1404 }
1405 
1406 static bool
1407 IsTokenWithFormat(const char *var_name_begin, const char *var, std::string &format, const char *default_format,
1408     const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
1409 {
1410     int var_len = strlen(var);
1411     if (::strncmp (var_name_begin, var, var_len) == 0)
1412     {
1413         var_name_begin += var_len;
1414         if (*var_name_begin == '}')
1415         {
1416             format = default_format;
1417             return true;
1418         }
1419         else if (*var_name_begin == '%')
1420         {
1421             // Allow format specifiers: x|X|u with optional width specifiers.
1422             //   ${thread.id%x}    ; hex
1423             //   ${thread.id%X}    ; uppercase hex
1424             //   ${thread.id%u}    ; unsigned decimal
1425             //   ${thread.id%8.8X} ; width.precision + specifier
1426             //   ${thread.id%tid}  ; unsigned on FreeBSD/Linux, otherwise default_format (0x%4.4x for thread.id)
1427             int dot_count = 0;
1428             const char *specifier = NULL;
1429             int width_precision_length = 0;
1430             const char *width_precision = ++var_name_begin;
1431             while (isdigit(*var_name_begin) || *var_name_begin == '.')
1432             {
1433                 dot_count += (*var_name_begin == '.');
1434                 if (dot_count > 1)
1435                     break;
1436                 var_name_begin++;
1437                 width_precision_length++;
1438             }
1439 
1440             if (IsToken (var_name_begin, "tid}"))
1441             {
1442                 Target *target = Target::GetTargetFromContexts (exe_ctx_ptr, sc_ptr);
1443                 if (target)
1444                 {
1445                     ArchSpec arch (target->GetArchitecture ());
1446                     llvm::Triple::OSType ostype = arch.IsValid() ? arch.GetTriple().getOS() : llvm::Triple::UnknownOS;
1447                     if ((ostype == llvm::Triple::FreeBSD) || (ostype == llvm::Triple::Linux))
1448                         specifier = PRIu64;
1449                 }
1450                 if (!specifier)
1451                 {
1452                     format = default_format;
1453                     return true;
1454                 }
1455             }
1456             else if (IsToken (var_name_begin, "x}"))
1457                 specifier = PRIx64;
1458             else if (IsToken (var_name_begin, "X}"))
1459                 specifier = PRIX64;
1460             else if (IsToken (var_name_begin, "u}"))
1461                 specifier = PRIu64;
1462 
1463             if (specifier)
1464             {
1465                 format = "%";
1466                 if (width_precision_length)
1467                     format += std::string(width_precision, width_precision_length);
1468                 format += specifier;
1469                 return true;
1470             }
1471         }
1472     }
1473     return false;
1474 }
1475 
1476 // Find information for the "thread.info.*" specifiers in a format string
1477 static bool
1478 FormatThreadExtendedInfoRecurse
1479 (
1480     const char *var_name_begin,
1481     StructuredData::ObjectSP thread_info_dictionary,
1482     const SymbolContext *sc,
1483     const ExecutionContext *exe_ctx,
1484     Stream &s
1485 )
1486 {
1487     bool var_success = false;
1488     std::string token_format;
1489 
1490     llvm::StringRef var_name(var_name_begin);
1491     size_t percent_idx = var_name.find('%');
1492     size_t close_curly_idx = var_name.find('}');
1493     llvm::StringRef path = var_name;
1494     llvm::StringRef formatter = var_name;
1495 
1496     // 'path' will be the dot separated list of objects to transverse up until we hit
1497     // a close curly brace, a percent sign, or an end of string.
1498     if (percent_idx != llvm::StringRef::npos || close_curly_idx != llvm::StringRef::npos)
1499     {
1500         if (percent_idx != llvm::StringRef::npos && close_curly_idx != llvm::StringRef::npos)
1501         {
1502             if (percent_idx < close_curly_idx)
1503             {
1504                 path = var_name.slice(0, percent_idx);
1505                 formatter = var_name.substr (percent_idx);
1506             }
1507             else
1508             {
1509                 path = var_name.slice(0, close_curly_idx);
1510                 formatter = var_name.substr (close_curly_idx);
1511             }
1512         }
1513         else if (percent_idx != llvm::StringRef::npos)
1514         {
1515             path = var_name.slice(0, percent_idx);
1516             formatter = var_name.substr (percent_idx);
1517         }
1518         else if (close_curly_idx != llvm::StringRef::npos)
1519         {
1520             path = var_name.slice(0, close_curly_idx);
1521             formatter = var_name.substr (close_curly_idx);
1522         }
1523     }
1524 
1525     StructuredData::ObjectSP value = thread_info_dictionary->GetObjectForDotSeparatedPath (path);
1526 
1527     if (value.get())
1528     {
1529         if (value->GetType() == StructuredData::Type::eTypeInteger)
1530         {
1531             if (IsTokenWithFormat (formatter.str().c_str(), "", token_format, "0x%4.4" PRIx64, exe_ctx, sc))
1532             {
1533                 s.Printf(token_format.c_str(), value->GetAsInteger()->GetValue());
1534                 var_success = true;
1535             }
1536         }
1537         else if (value->GetType() == StructuredData::Type::eTypeFloat)
1538         {
1539             s.Printf ("%f", value->GetAsFloat()->GetValue());
1540             var_success = true;
1541         }
1542         else if (value->GetType() == StructuredData::Type::eTypeString)
1543         {
1544             s.Printf("%s", value->GetAsString()->GetValue().c_str());
1545             var_success = true;
1546         }
1547         else if (value->GetType() == StructuredData::Type::eTypeArray)
1548         {
1549             if (value->GetAsArray()->GetSize() > 0)
1550             {
1551                 s.Printf ("%zu", value->GetAsArray()->GetSize());
1552                 var_success = true;
1553             }
1554         }
1555         else if (value->GetType() == StructuredData::Type::eTypeDictionary)
1556         {
1557             s.Printf ("%zu", value->GetAsDictionary()->GetKeys()->GetAsArray()->GetSize());
1558             var_success = true;
1559         }
1560     }
1561 
1562     return var_success;
1563 }
1564 
1565 
1566 static bool
1567 FormatPromptRecurse
1568 (
1569     const char *format,
1570     const SymbolContext *sc,
1571     const ExecutionContext *exe_ctx,
1572     const Address *addr,
1573     Stream &s,
1574     const char **end,
1575     ValueObject* valobj,
1576     bool function_changed,
1577     bool initial_function
1578 )
1579 {
1580     ValueObject* realvalobj = NULL; // makes it super-easy to parse pointers
1581     bool success = true;
1582     const char *p;
1583     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
1584 
1585     for (p = format; *p != '\0'; ++p)
1586     {
1587         if (realvalobj)
1588         {
1589             valobj = realvalobj;
1590             realvalobj = NULL;
1591         }
1592         size_t non_special_chars = ::strcspn (p, "${}\\");
1593         if (non_special_chars > 0)
1594         {
1595             if (success)
1596                 s.Write (p, non_special_chars);
1597             p += non_special_chars;
1598         }
1599 
1600         if (*p == '\0')
1601         {
1602             break;
1603         }
1604         else if (*p == '{')
1605         {
1606             // Start a new scope that must have everything it needs if it is to
1607             // to make it into the final output stream "s". If you want to make
1608             // a format that only prints out the function or symbol name if there
1609             // is one in the symbol context you can use:
1610             //      "{function =${function.name}}"
1611             // The first '{' starts a new scope that end with the matching '}' at
1612             // the end of the string. The contents "function =${function.name}"
1613             // will then be evaluated and only be output if there is a function
1614             // or symbol with a valid name.
1615             StreamString sub_strm;
1616 
1617             ++p;  // Skip the '{'
1618 
1619             if (FormatPromptRecurse (p, sc, exe_ctx, addr, sub_strm, &p, valobj, function_changed, initial_function))
1620             {
1621                 // The stream had all it needed
1622                 s.Write(sub_strm.GetData(), sub_strm.GetSize());
1623             }
1624             if (*p != '}')
1625             {
1626                 success = false;
1627                 break;
1628             }
1629         }
1630         else if (*p == '}')
1631         {
1632             // End of a enclosing scope
1633             break;
1634         }
1635         else if (*p == '$')
1636         {
1637             // We have a prompt variable to print
1638             ++p;
1639             if (*p == '{')
1640             {
1641                 ++p;
1642                 const char *var_name_begin = p;
1643                 const char *var_name_end = ::strchr (p, '}');
1644 
1645                 if (var_name_end && var_name_begin < var_name_end)
1646                 {
1647                     // if we have already failed to parse, skip this variable
1648                     if (success)
1649                     {
1650                         const char *cstr = NULL;
1651                         std::string token_format;
1652                         Address format_addr;
1653 
1654                         // normally "addr" means print a raw address but
1655                         // "file-addr-or-load-addr" means print a module + file addr if there's no load addr
1656                         bool print_file_addr_or_load_addr = false;
1657                         bool addr_offset_concrete_func_only = false;
1658                         bool addr_offset_print_with_no_padding = false;
1659                         bool calculate_format_addr_function_offset = false;
1660                         // Set reg_kind and reg_num to invalid values
1661                         RegisterKind reg_kind = kNumRegisterKinds;
1662                         uint32_t reg_num = LLDB_INVALID_REGNUM;
1663                         FileSpec format_file_spec;
1664                         const RegisterInfo *reg_info = NULL;
1665                         RegisterContext *reg_ctx = NULL;
1666                         bool do_deref_pointer = false;
1667                         ValueObject::ExpressionPathScanEndReason reason_to_stop = ValueObject::eExpressionPathScanEndReasonEndOfString;
1668                         ValueObject::ExpressionPathEndResultType final_value_type = ValueObject::eExpressionPathEndResultTypePlain;
1669 
1670                         // Each variable must set success to true below...
1671                         bool var_success = false;
1672                         switch (var_name_begin[0])
1673                         {
1674                         case '*':
1675                         case 'v':
1676                         case 's':
1677                             {
1678                                 if (!valobj)
1679                                     break;
1680 
1681                                 if (log)
1682                                     log->Printf("[Debugger::FormatPrompt] initial string: %s",var_name_begin);
1683 
1684                                 // check for *var and *svar
1685                                 if (*var_name_begin == '*')
1686                                 {
1687                                     do_deref_pointer = true;
1688                                     var_name_begin++;
1689                                     if (log)
1690                                         log->Printf("[Debugger::FormatPrompt] found a deref, new string is: %s",var_name_begin);
1691                                 }
1692 
1693                                 if (*var_name_begin == 's')
1694                                 {
1695                                     if (!valobj->IsSynthetic())
1696                                         valobj = valobj->GetSyntheticValue().get();
1697                                     if (!valobj)
1698                                         break;
1699                                     var_name_begin++;
1700                                     if (log)
1701                                         log->Printf("[Debugger::FormatPrompt] found a synthetic, new string is: %s",var_name_begin);
1702                                 }
1703 
1704                                 // should be a 'v' by now
1705                                 if (*var_name_begin != 'v')
1706                                     break;
1707 
1708                                 if (log)
1709                                     log->Printf("[Debugger::FormatPrompt] string I am working with: %s",var_name_begin);
1710 
1711                                 ValueObject::ExpressionPathAftermath what_next = (do_deref_pointer ?
1712                                                                                   ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
1713                                 ValueObject::GetValueForExpressionPathOptions options;
1714                                 options.DontCheckDotVsArrowSyntax().DoAllowBitfieldSyntax().DoAllowFragileIVar().DoAllowSyntheticChildren();
1715                                 ValueObject::ValueObjectRepresentationStyle val_obj_display = ValueObject::eValueObjectRepresentationStyleSummary;
1716                                 ValueObject* target = NULL;
1717                                 Format custom_format = eFormatInvalid;
1718                                 const char* var_name_final = NULL;
1719                                 const char* var_name_final_if_array_range = NULL;
1720                                 const char* close_bracket_position = NULL;
1721                                 int64_t index_lower = -1;
1722                                 int64_t index_higher = -1;
1723                                 bool is_array_range = false;
1724                                 const char* first_unparsed;
1725                                 bool was_plain_var = false;
1726                                 bool was_var_format = false;
1727                                 bool was_var_indexed = false;
1728 
1729                                 if (!valobj) break;
1730                                 // simplest case ${var}, just print valobj's value
1731                                 if (IsToken (var_name_begin, "var}"))
1732                                 {
1733                                     was_plain_var = true;
1734                                     target = valobj;
1735                                     val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1736                                 }
1737                                 else if (IsToken (var_name_begin, "var.script:"))
1738                                 {
1739                                     var_name_begin += ::strlen("var.script:");
1740                                     std::string script_name(var_name_begin,var_name_end);
1741                                     ScriptInterpreter* script_interpreter = valobj->GetTargetSP()->GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
1742                                     if (RunScriptFormatKeyword (s, script_interpreter, valobj, script_name))
1743                                         var_success = true;
1744                                     break;
1745                                 }
1746                                 else if (IsToken (var_name_begin,"var%"))
1747                                 {
1748                                     was_var_format = true;
1749                                     // this is a variable with some custom format applied to it
1750                                     const char* percent_position;
1751                                     target = valobj;
1752                                     val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1753                                     ScanFormatDescriptor (var_name_begin,
1754                                                           var_name_end,
1755                                                           &var_name_final,
1756                                                           &percent_position,
1757                                                           &custom_format,
1758                                                           &val_obj_display);
1759                                 }
1760                                     // this is ${var.something} or multiple .something nested
1761                                 else if (IsToken (var_name_begin, "var"))
1762                                 {
1763                                     if (IsToken (var_name_begin, "var["))
1764                                         was_var_indexed = true;
1765                                     const char* percent_position;
1766                                     ScanFormatDescriptor (var_name_begin,
1767                                                           var_name_end,
1768                                                           &var_name_final,
1769                                                           &percent_position,
1770                                                           &custom_format,
1771                                                           &val_obj_display);
1772 
1773                                     const char* open_bracket_position;
1774                                     const char* separator_position;
1775                                     ScanBracketedRange (var_name_begin,
1776                                                         var_name_end,
1777                                                         var_name_final,
1778                                                         &open_bracket_position,
1779                                                         &separator_position,
1780                                                         &close_bracket_position,
1781                                                         &var_name_final_if_array_range,
1782                                                         &index_lower,
1783                                                         &index_higher);
1784 
1785                                     Error error;
1786 
1787                                     std::string expr_path(var_name_final-var_name_begin-1,0);
1788                                     memcpy(&expr_path[0], var_name_begin+3,var_name_final-var_name_begin-3);
1789 
1790                                     if (log)
1791                                         log->Printf("[Debugger::FormatPrompt] symbol to expand: %s",expr_path.c_str());
1792 
1793                                     target = valobj->GetValueForExpressionPath(expr_path.c_str(),
1794                                                                              &first_unparsed,
1795                                                                              &reason_to_stop,
1796                                                                              &final_value_type,
1797                                                                              options,
1798                                                                              &what_next).get();
1799 
1800                                     if (!target)
1801                                     {
1802                                         if (log)
1803                                             log->Printf("[Debugger::FormatPrompt] ERROR: unparsed portion = %s, why stopping = %d,"
1804                                                " final_value_type %d",
1805                                                first_unparsed, reason_to_stop, final_value_type);
1806                                         break;
1807                                     }
1808                                     else
1809                                     {
1810                                         if (log)
1811                                             log->Printf("[Debugger::FormatPrompt] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
1812                                                " final_value_type %d",
1813                                                first_unparsed, reason_to_stop, final_value_type);
1814                                         target = target->GetQualifiedRepresentationIfAvailable(target->GetDynamicValueType(), true).get();
1815                                     }
1816                                 }
1817                                 else
1818                                     break;
1819 
1820                                 is_array_range = (final_value_type == ValueObject::eExpressionPathEndResultTypeBoundedRange ||
1821                                                   final_value_type == ValueObject::eExpressionPathEndResultTypeUnboundedRange);
1822 
1823                                 do_deref_pointer = (what_next == ValueObject::eExpressionPathAftermathDereference);
1824 
1825                                 if (do_deref_pointer && !is_array_range)
1826                                 {
1827                                     // I have not deref-ed yet, let's do it
1828                                     // this happens when we are not going through GetValueForVariableExpressionPath
1829                                     // to get to the target ValueObject
1830                                     Error error;
1831                                     target = target->Dereference(error).get();
1832                                     if (error.Fail())
1833                                     {
1834                                         if (log)
1835                                             log->Printf("[Debugger::FormatPrompt] ERROR: %s\n", error.AsCString("unknown")); \
1836                                         break;
1837                                     }
1838                                     do_deref_pointer = false;
1839                                 }
1840 
1841                                 if (!target)
1842                                 {
1843                                     if (log)
1844                                         log->Printf("[Debugger::FormatPrompt] could not calculate target for prompt expression");
1845                                     break;
1846                                 }
1847 
1848                                 // we do not want to use the summary for a bitfield of type T:n
1849                                 // if we were originally dealing with just a T - that would get
1850                                 // us into an endless recursion
1851                                 if (target->IsBitfield() && was_var_indexed)
1852                                 {
1853                                     // TODO: check for a (T:n)-specific summary - we should still obey that
1854                                     StreamString bitfield_name;
1855                                     bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(), target->GetBitfieldBitSize());
1856                                     lldb::TypeNameSpecifierImplSP type_sp(new TypeNameSpecifierImpl(bitfield_name.GetData(),false));
1857                                     if (!DataVisualization::GetSummaryForType(type_sp))
1858                                         val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
1859                                 }
1860 
1861                                 // TODO use flags for these
1862                                 const uint32_t type_info_flags = target->GetClangType().GetTypeInfo(NULL);
1863                                 bool is_array = (type_info_flags & eTypeIsArray) != 0;
1864                                 bool is_pointer = (type_info_flags & eTypeIsPointer) != 0;
1865                                 bool is_aggregate = target->GetClangType().IsAggregateType();
1866 
1867                                 if ((is_array || is_pointer) && (!is_array_range) && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue) // this should be wrong, but there are some exceptions
1868                                 {
1869                                     StreamString str_temp;
1870                                     if (log)
1871                                         log->Printf("[Debugger::FormatPrompt] I am into array || pointer && !range");
1872 
1873                                     if (target->HasSpecialPrintableRepresentation(val_obj_display, custom_format))
1874                                     {
1875                                         // try to use the special cases
1876                                         var_success = target->DumpPrintableRepresentation(str_temp,
1877                                                                                           val_obj_display,
1878                                                                                           custom_format);
1879                                         if (log)
1880                                             log->Printf("[Debugger::FormatPrompt] special cases did%s match", var_success ? "" : "n't");
1881 
1882                                         // should not happen
1883                                         if (var_success)
1884                                             s << str_temp.GetData();
1885                                         var_success = true;
1886                                         break;
1887                                     }
1888                                     else
1889                                     {
1890                                         if (was_plain_var) // if ${var}
1891                                         {
1892                                             s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
1893                                         }
1894                                         else if (is_pointer) // if pointer, value is the address stored
1895                                         {
1896                                             target->DumpPrintableRepresentation (s,
1897                                                                                  val_obj_display,
1898                                                                                  custom_format,
1899                                                                                  ValueObject::ePrintableRepresentationSpecialCasesDisable);
1900                                         }
1901                                         var_success = true;
1902                                         break;
1903                                     }
1904                                 }
1905 
1906                                 // if directly trying to print ${var}, and this is an aggregate, display a nice
1907                                 // type @ location message
1908                                 if (is_aggregate && was_plain_var)
1909                                 {
1910                                     s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
1911                                     var_success = true;
1912                                     break;
1913                                 }
1914 
1915                                 // if directly trying to print ${var%V}, and this is an aggregate, do not let the user do it
1916                                 if (is_aggregate && ((was_var_format && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue)))
1917                                 {
1918                                     s << "<invalid use of aggregate type>";
1919                                     var_success = true;
1920                                     break;
1921                                 }
1922 
1923                                 if (!is_array_range)
1924                                 {
1925                                     if (log)
1926                                         log->Printf("[Debugger::FormatPrompt] dumping ordinary printable output");
1927                                     var_success = target->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1928                                 }
1929                                 else
1930                                 {
1931                                     if (log)
1932                                         log->Printf("[Debugger::FormatPrompt] checking if I can handle as array");
1933                                     if (!is_array && !is_pointer)
1934                                         break;
1935                                     if (log)
1936                                         log->Printf("[Debugger::FormatPrompt] handle as array");
1937                                     const char* special_directions = NULL;
1938                                     StreamString special_directions_writer;
1939                                     if (close_bracket_position && (var_name_end-close_bracket_position > 1))
1940                                     {
1941                                         ConstString additional_data;
1942                                         additional_data.SetCStringWithLength(close_bracket_position+1, var_name_end-close_bracket_position-1);
1943                                         special_directions_writer.Printf("${%svar%s}",
1944                                                                          do_deref_pointer ? "*" : "",
1945                                                                          additional_data.GetCString());
1946                                         special_directions = special_directions_writer.GetData();
1947                                     }
1948 
1949                                     // let us display items index_lower thru index_higher of this array
1950                                     s.PutChar('[');
1951                                     var_success = true;
1952 
1953                                     if (index_higher < 0)
1954                                         index_higher = valobj->GetNumChildren() - 1;
1955 
1956                                     uint32_t max_num_children = target->GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();
1957 
1958                                     for (;index_lower<=index_higher;index_lower++)
1959                                     {
1960                                         ValueObject* item = ExpandIndexedExpression (target,
1961                                                                                      index_lower,
1962                                                                                      exe_ctx->GetFramePtr(),
1963                                                                                      false).get();
1964 
1965                                         if (!item)
1966                                         {
1967                                             if (log)
1968                                                 log->Printf("[Debugger::FormatPrompt] ERROR in getting child item at index %" PRId64, index_lower);
1969                                         }
1970                                         else
1971                                         {
1972                                             if (log)
1973                                                 log->Printf("[Debugger::FormatPrompt] special_directions for child item: %s",special_directions);
1974                                         }
1975 
1976                                         if (!special_directions)
1977                                             var_success &= item->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1978                                         else
1979                                             var_success &= FormatPromptRecurse(special_directions, sc, exe_ctx, addr, s, NULL, item, function_changed, initial_function);
1980 
1981                                         if (--max_num_children == 0)
1982                                         {
1983                                             s.PutCString(", ...");
1984                                             break;
1985                                         }
1986 
1987                                         if (index_lower < index_higher)
1988                                             s.PutChar(',');
1989                                     }
1990                                     s.PutChar(']');
1991                                 }
1992                             }
1993                             break;
1994                         case 'a':
1995                             if (IsToken (var_name_begin, "addr-file-or-load}"))
1996                             {
1997                                 print_file_addr_or_load_addr = true;
1998                             }
1999                             if (IsToken (var_name_begin, "addr}")
2000                                 || IsToken (var_name_begin, "addr-file-or-load}"))
2001                             {
2002                                 if (addr && addr->IsValid())
2003                                 {
2004                                     var_success = true;
2005                                     format_addr = *addr;
2006                                 }
2007                             }
2008                             break;
2009 
2010                         case 'p':
2011                             if (IsToken (var_name_begin, "process."))
2012                             {
2013                                 if (exe_ctx)
2014                                 {
2015                                     Process *process = exe_ctx->GetProcessPtr();
2016                                     if (process)
2017                                     {
2018                                         var_name_begin += ::strlen ("process.");
2019                                         if (IsTokenWithFormat (var_name_begin, "id", token_format, "%" PRIu64, exe_ctx, sc))
2020                                         {
2021                                             s.Printf(token_format.c_str(), process->GetID());
2022                                             var_success = true;
2023                                         }
2024                                         else if ((IsToken (var_name_begin, "name}")) ||
2025                                                 (IsToken (var_name_begin, "file.basename}")) ||
2026                                                 (IsToken (var_name_begin, "file.fullpath}")))
2027                                         {
2028                                             Module *exe_module = process->GetTarget().GetExecutableModulePointer();
2029                                             if (exe_module)
2030                                             {
2031                                                 if (var_name_begin[0] == 'n' || var_name_begin[5] == 'f')
2032                                                 {
2033                                                     format_file_spec.GetFilename() = exe_module->GetFileSpec().GetFilename();
2034                                                     var_success = (bool)format_file_spec;
2035                                                 }
2036                                                 else
2037                                                 {
2038                                                     format_file_spec = exe_module->GetFileSpec();
2039                                                     var_success = (bool)format_file_spec;
2040                                                 }
2041                                             }
2042                                         }
2043                                         else if (IsToken (var_name_begin, "script:"))
2044                                         {
2045                                             var_name_begin += ::strlen("script:");
2046                                             std::string script_name(var_name_begin,var_name_end);
2047                                             ScriptInterpreter* script_interpreter = process->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
2048                                             if (RunScriptFormatKeyword (s, script_interpreter, process, script_name))
2049                                                 var_success = true;
2050                                         }
2051                                     }
2052                                 }
2053                             }
2054                             break;
2055 
2056                         case 't':
2057                            if (IsToken (var_name_begin, "thread."))
2058                             {
2059                                 if (exe_ctx)
2060                                 {
2061                                     Thread *thread = exe_ctx->GetThreadPtr();
2062                                     if (thread)
2063                                     {
2064                                         var_name_begin += ::strlen ("thread.");
2065                                         if (IsTokenWithFormat (var_name_begin, "id", token_format, "0x%4.4" PRIx64, exe_ctx, sc))
2066                                         {
2067                                             s.Printf(token_format.c_str(), thread->GetID());
2068                                             var_success = true;
2069                                         }
2070                                         else if (IsTokenWithFormat (var_name_begin, "protocol_id", token_format, "0x%4.4" PRIx64, exe_ctx, sc))
2071                                         {
2072                                             s.Printf(token_format.c_str(), thread->GetProtocolID());
2073                                             var_success = true;
2074                                         }
2075                                         else if (IsTokenWithFormat (var_name_begin, "index", token_format, "%" PRIu64, exe_ctx, sc))
2076                                         {
2077                                             s.Printf(token_format.c_str(), (uint64_t)thread->GetIndexID());
2078                                             var_success = true;
2079                                         }
2080                                         else if (IsToken (var_name_begin, "name}"))
2081                                         {
2082                                             cstr = thread->GetName();
2083                                             var_success = cstr && cstr[0];
2084                                             if (var_success)
2085                                                 s.PutCString(cstr);
2086                                         }
2087                                         else if (IsToken (var_name_begin, "queue}"))
2088                                         {
2089                                             cstr = thread->GetQueueName();
2090                                             var_success = cstr && cstr[0];
2091                                             if (var_success)
2092                                                 s.PutCString(cstr);
2093                                         }
2094                                         else if (IsToken (var_name_begin, "stop-reason}"))
2095                                         {
2096                                             StopInfoSP stop_info_sp = thread->GetStopInfo ();
2097                                             if (stop_info_sp && stop_info_sp->IsValid())
2098                                             {
2099                                                 cstr = stop_info_sp->GetDescription();
2100                                                 if (cstr && cstr[0])
2101                                                 {
2102                                                     s.PutCString(cstr);
2103                                                     var_success = true;
2104                                                 }
2105                                             }
2106                                         }
2107                                         else if (IsToken (var_name_begin, "return-value}"))
2108                                         {
2109                                             StopInfoSP stop_info_sp = thread->GetStopInfo ();
2110                                             if (stop_info_sp && stop_info_sp->IsValid())
2111                                             {
2112                                                 ValueObjectSP return_valobj_sp = StopInfo::GetReturnValueObject (stop_info_sp);
2113                                                 if (return_valobj_sp)
2114                                                 {
2115                                                     return_valobj_sp->Dump(s);
2116                                                     var_success = true;
2117                                                 }
2118                                             }
2119                                         }
2120                                         else if (IsToken (var_name_begin, "completed-expression}"))
2121                                         {
2122                                             StopInfoSP stop_info_sp = thread->GetStopInfo ();
2123                                             if (stop_info_sp && stop_info_sp->IsValid())
2124                                             {
2125                                                 ClangExpressionVariableSP expression_var_sp = StopInfo::GetExpressionVariable (stop_info_sp);
2126                                                 if (expression_var_sp && expression_var_sp->GetValueObject())
2127                                                 {
2128                                                     expression_var_sp->GetValueObject()->Dump(s);
2129                                                     var_success = true;
2130                                                 }
2131                                             }
2132                                         }
2133                                         else if (IsToken (var_name_begin, "script:"))
2134                                         {
2135                                             var_name_begin += ::strlen("script:");
2136                                             std::string script_name(var_name_begin,var_name_end);
2137                                             ScriptInterpreter* script_interpreter = thread->GetProcess()->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
2138                                             if (RunScriptFormatKeyword (s, script_interpreter, thread, script_name))
2139                                                 var_success = true;
2140                                         }
2141                                         else if (IsToken (var_name_begin, "info."))
2142                                         {
2143                                             var_name_begin += ::strlen("info.");
2144                                             StructuredData::ObjectSP object_sp = thread->GetExtendedInfo();
2145                                             if (object_sp && object_sp->GetType() == StructuredData::Type::eTypeDictionary)
2146                                             {
2147                                                 var_success = FormatThreadExtendedInfoRecurse (var_name_begin, object_sp, sc, exe_ctx, s);
2148                                             }
2149                                         }
2150                                     }
2151                                 }
2152                             }
2153                             else if (IsToken (var_name_begin, "target."))
2154                             {
2155                                 // TODO: hookup properties
2156 //                                if (!target_properties_sp)
2157 //                                {
2158 //                                    Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2159 //                                    if (target)
2160 //                                        target_properties_sp = target->GetProperties();
2161 //                                }
2162 //
2163 //                                if (target_properties_sp)
2164 //                                {
2165 //                                    var_name_begin += ::strlen ("target.");
2166 //                                    const char *end_property = strchr(var_name_begin, '}');
2167 //                                    if (end_property)
2168 //                                    {
2169 //                                        ConstString property_name(var_name_begin, end_property - var_name_begin);
2170 //                                        std::string property_value (target_properties_sp->GetPropertyValue(property_name));
2171 //                                        if (!property_value.empty())
2172 //                                        {
2173 //                                            s.PutCString (property_value.c_str());
2174 //                                            var_success = true;
2175 //                                        }
2176 //                                    }
2177 //                                }
2178                                 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2179                                 if (target)
2180                                 {
2181                                     var_name_begin += ::strlen ("target.");
2182                                     if (IsToken (var_name_begin, "arch}"))
2183                                     {
2184                                         ArchSpec arch (target->GetArchitecture ());
2185                                         if (arch.IsValid())
2186                                         {
2187                                             s.PutCString (arch.GetArchitectureName());
2188                                             var_success = true;
2189                                         }
2190                                     }
2191                                     else if (IsToken (var_name_begin, "script:"))
2192                                     {
2193                                         var_name_begin += ::strlen("script:");
2194                                         std::string script_name(var_name_begin,var_name_end);
2195                                         ScriptInterpreter* script_interpreter = target->GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
2196                                         if (RunScriptFormatKeyword (s, script_interpreter, target, script_name))
2197                                             var_success = true;
2198                                     }
2199                                 }
2200                             }
2201                             break;
2202 
2203                         case 'm':
2204                            if (IsToken (var_name_begin, "module."))
2205                             {
2206                                 if (sc && sc->module_sp.get())
2207                                 {
2208                                     Module *module = sc->module_sp.get();
2209                                     var_name_begin += ::strlen ("module.");
2210 
2211                                     if (IsToken (var_name_begin, "file."))
2212                                     {
2213                                         if (module->GetFileSpec())
2214                                         {
2215                                             var_name_begin += ::strlen ("file.");
2216 
2217                                             if (IsToken (var_name_begin, "basename}"))
2218                                             {
2219                                                 format_file_spec.GetFilename() = module->GetFileSpec().GetFilename();
2220                                                 var_success = (bool)format_file_spec;
2221                                             }
2222                                             else if (IsToken (var_name_begin, "fullpath}"))
2223                                             {
2224                                                 format_file_spec = module->GetFileSpec();
2225                                                 var_success = (bool)format_file_spec;
2226                                             }
2227                                         }
2228                                     }
2229                                 }
2230                             }
2231                             break;
2232 
2233 
2234                         case 'f':
2235                            if (IsToken (var_name_begin, "file."))
2236                             {
2237                                 if (sc && sc->comp_unit != NULL)
2238                                 {
2239                                     var_name_begin += ::strlen ("file.");
2240 
2241                                     if (IsToken (var_name_begin, "basename}"))
2242                                     {
2243                                         format_file_spec.GetFilename() = sc->comp_unit->GetFilename();
2244                                         var_success = (bool)format_file_spec;
2245                                     }
2246                                     else if (IsToken (var_name_begin, "fullpath}"))
2247                                     {
2248                                         format_file_spec = *sc->comp_unit;
2249                                         var_success = (bool)format_file_spec;
2250                                     }
2251                                 }
2252                             }
2253                            else if (IsToken (var_name_begin, "frame."))
2254                             {
2255                                 if (exe_ctx)
2256                                 {
2257                                     StackFrame *frame = exe_ctx->GetFramePtr();
2258                                     if (frame)
2259                                     {
2260                                         var_name_begin += ::strlen ("frame.");
2261                                         if (IsToken (var_name_begin, "index}"))
2262                                         {
2263                                             s.Printf("%u", frame->GetFrameIndex());
2264                                             var_success = true;
2265                                         }
2266                                         else if (IsToken (var_name_begin, "pc}"))
2267                                         {
2268                                             reg_kind = eRegisterKindGeneric;
2269                                             reg_num = LLDB_REGNUM_GENERIC_PC;
2270                                             var_success = true;
2271                                         }
2272                                         else if (IsToken (var_name_begin, "sp}"))
2273                                         {
2274                                             reg_kind = eRegisterKindGeneric;
2275                                             reg_num = LLDB_REGNUM_GENERIC_SP;
2276                                             var_success = true;
2277                                         }
2278                                         else if (IsToken (var_name_begin, "fp}"))
2279                                         {
2280                                             reg_kind = eRegisterKindGeneric;
2281                                             reg_num = LLDB_REGNUM_GENERIC_FP;
2282                                             var_success = true;
2283                                         }
2284                                         else if (IsToken (var_name_begin, "flags}"))
2285                                         {
2286                                             reg_kind = eRegisterKindGeneric;
2287                                             reg_num = LLDB_REGNUM_GENERIC_FLAGS;
2288                                             var_success = true;
2289                                         }
2290                                         else if (IsToken (var_name_begin, "reg."))
2291                                         {
2292                                             reg_ctx = frame->GetRegisterContext().get();
2293                                             if (reg_ctx)
2294                                             {
2295                                                 var_name_begin += ::strlen ("reg.");
2296                                                 if (var_name_begin < var_name_end)
2297                                                 {
2298                                                     std::string reg_name (var_name_begin, var_name_end);
2299                                                     reg_info = reg_ctx->GetRegisterInfoByName (reg_name.c_str());
2300                                                     if (reg_info)
2301                                                         var_success = true;
2302                                                 }
2303                                             }
2304                                         }
2305                                         else if (IsToken (var_name_begin, "script:"))
2306                                         {
2307                                             var_name_begin += ::strlen("script:");
2308                                             std::string script_name(var_name_begin,var_name_end);
2309                                             ScriptInterpreter* script_interpreter = frame->GetThread()->GetProcess()->GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
2310                                             if (RunScriptFormatKeyword (s, script_interpreter, frame, script_name))
2311                                                 var_success = true;
2312                                         }
2313                                     }
2314                                 }
2315                             }
2316                             else if (IsToken (var_name_begin, "function."))
2317                             {
2318                                 if (sc && (sc->function != NULL || sc->symbol != NULL))
2319                                 {
2320                                     var_name_begin += ::strlen ("function.");
2321                                     if (IsToken (var_name_begin, "id}"))
2322                                     {
2323                                         if (sc->function)
2324                                             s.Printf("function{0x%8.8" PRIx64 "}", sc->function->GetID());
2325                                         else
2326                                             s.Printf("symbol[%u]", sc->symbol->GetID());
2327 
2328                                         var_success = true;
2329                                     }
2330                                     if (IsToken (var_name_begin, "changed}") && function_changed)
2331                                     {
2332                                         var_success = true;
2333                                     }
2334                                     if (IsToken (var_name_begin, "initial-function}") && initial_function)
2335                                     {
2336                                         var_success = true;
2337                                     }
2338                                     else if (IsToken (var_name_begin, "name}"))
2339                                     {
2340                                         if (sc->function)
2341                                             cstr = sc->function->GetName().AsCString (NULL);
2342                                         else if (sc->symbol)
2343                                             cstr = sc->symbol->GetName().AsCString (NULL);
2344                                         if (cstr)
2345                                         {
2346                                             s.PutCString(cstr);
2347 
2348                                             if (sc->block)
2349                                             {
2350                                                 Block *inline_block = sc->block->GetContainingInlinedBlock ();
2351                                                 if (inline_block)
2352                                                 {
2353                                                     const InlineFunctionInfo *inline_info = sc->block->GetInlinedFunctionInfo();
2354                                                     if (inline_info)
2355                                                     {
2356                                                         s.PutCString(" [inlined] ");
2357                                                         inline_info->GetName().Dump(&s);
2358                                                     }
2359                                                 }
2360                                             }
2361                                             var_success = true;
2362                                         }
2363                                     }
2364                                     else if (IsToken (var_name_begin, "name-without-args}"))
2365                                     {
2366                                         ConstString name;
2367                                         if (sc->function)
2368                                             name = sc->function->GetMangled().GetName (Mangled::ePreferDemangledWithoutArguments);
2369                                         else if (sc->symbol)
2370                                             name = sc->symbol->GetMangled().GetName (Mangled::ePreferDemangledWithoutArguments);
2371                                         if (name)
2372                                         {
2373                                             s.PutCString(name.GetCString());
2374                                             var_success = true;
2375                                         }
2376                                     }
2377                                     else if (IsToken (var_name_begin, "name-with-args}"))
2378                                     {
2379                                         // Print the function name with arguments in it
2380 
2381                                         if (sc->function)
2382                                         {
2383                                             var_success = true;
2384                                             ExecutionContextScope *exe_scope = exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL;
2385                                             cstr = sc->function->GetName().AsCString (NULL);
2386                                             if (cstr)
2387                                             {
2388                                                 const InlineFunctionInfo *inline_info = NULL;
2389                                                 VariableListSP variable_list_sp;
2390                                                 bool get_function_vars = true;
2391                                                 if (sc->block)
2392                                                 {
2393                                                     Block *inline_block = sc->block->GetContainingInlinedBlock ();
2394 
2395                                                     if (inline_block)
2396                                                     {
2397                                                         get_function_vars = false;
2398                                                         inline_info = sc->block->GetInlinedFunctionInfo();
2399                                                         if (inline_info)
2400                                                             variable_list_sp = inline_block->GetBlockVariableList (true);
2401                                                     }
2402                                                 }
2403 
2404                                                 if (get_function_vars)
2405                                                 {
2406                                                     variable_list_sp = sc->function->GetBlock(true).GetBlockVariableList (true);
2407                                                 }
2408 
2409                                                 if (inline_info)
2410                                                 {
2411                                                     s.PutCString (cstr);
2412                                                     s.PutCString (" [inlined] ");
2413                                                     cstr = inline_info->GetName().GetCString();
2414                                                 }
2415 
2416                                                 VariableList args;
2417                                                 if (variable_list_sp)
2418                                                     variable_list_sp->AppendVariablesWithScope(eValueTypeVariableArgument, args);
2419                                                 if (args.GetSize() > 0)
2420                                                 {
2421                                                     const char *open_paren = strchr (cstr, '(');
2422                                                     const char *close_paren = nullptr;
2423                                                     const char *generic = strchr(cstr, '<');
2424                                                     // if before the arguments list begins there is a template sign
2425                                                     // then scan to the end of the generic args before you try to find
2426                                                     // the arguments list
2427                                                     if (generic && open_paren && generic < open_paren)
2428                                                     {
2429                                                         int generic_depth = 1;
2430                                                         ++generic;
2431                                                         for (;
2432                                                              *generic && generic_depth > 0;
2433                                                              generic++)
2434                                                         {
2435                                                             if (*generic == '<')
2436                                                                 generic_depth++;
2437                                                             if (*generic == '>')
2438                                                                 generic_depth--;
2439                                                         }
2440                                                         if (*generic)
2441                                                             open_paren = strchr(generic, '(');
2442                                                         else
2443                                                             open_paren = nullptr;
2444                                                     }
2445                                                     if (open_paren)
2446                                                     {
2447                                                         if (IsToken (open_paren, "(anonymous namespace)"))
2448                                                         {
2449                                                             open_paren = strchr (open_paren + strlen("(anonymous namespace)"), '(');
2450                                                             if (open_paren)
2451                                                                 close_paren = strchr (open_paren, ')');
2452                                                         }
2453                                                         else
2454                                                             close_paren = strchr (open_paren, ')');
2455                                                     }
2456 
2457                                                     if (open_paren)
2458                                                         s.Write(cstr, open_paren - cstr + 1);
2459                                                     else
2460                                                     {
2461                                                         s.PutCString (cstr);
2462                                                         s.PutChar ('(');
2463                                                     }
2464                                                     const size_t num_args = args.GetSize();
2465                                                     for (size_t arg_idx = 0; arg_idx < num_args; ++arg_idx)
2466                                                     {
2467                                                         std::string buffer;
2468 
2469                                                         VariableSP var_sp (args.GetVariableAtIndex (arg_idx));
2470                                                         ValueObjectSP var_value_sp (ValueObjectVariable::Create (exe_scope, var_sp));
2471                                                         const char *var_representation = nullptr;
2472                                                         const char *var_name = var_value_sp->GetName().GetCString();
2473                                                         if (var_value_sp->GetClangType().IsAggregateType() &&
2474                                                             DataVisualization::ShouldPrintAsOneLiner(*var_value_sp.get()))
2475                                                         {
2476                                                             static StringSummaryFormat format(TypeSummaryImpl::Flags()
2477                                                                                               .SetHideItemNames(false)
2478                                                                                               .SetShowMembersOneLiner(true),
2479                                                                                               "");
2480                                                             format.FormatObject(var_value_sp.get(), buffer);
2481                                                             var_representation = buffer.c_str();
2482                                                         }
2483                                                         else
2484                                                             var_representation = var_value_sp->GetValueAsCString();
2485                                                         if (arg_idx > 0)
2486                                                             s.PutCString (", ");
2487                                                         if (var_value_sp->GetError().Success())
2488                                                         {
2489                                                             if (var_representation)
2490                                                                 s.Printf ("%s=%s", var_name, var_representation);
2491                                                             else
2492                                                                 s.Printf ("%s=%s at %s", var_name, var_value_sp->GetTypeName().GetCString(), var_value_sp->GetLocationAsCString());
2493                                                         }
2494                                                         else
2495                                                             s.Printf ("%s=<unavailable>", var_name);
2496                                                     }
2497 
2498                                                     if (close_paren)
2499                                                         s.PutCString (close_paren);
2500                                                     else
2501                                                         s.PutChar(')');
2502 
2503                                                 }
2504                                                 else
2505                                                 {
2506                                                     s.PutCString(cstr);
2507                                                 }
2508                                             }
2509                                         }
2510                                         else if (sc->symbol)
2511                                         {
2512                                             cstr = sc->symbol->GetName().AsCString (NULL);
2513                                             if (cstr)
2514                                             {
2515                                                 s.PutCString(cstr);
2516                                                 var_success = true;
2517                                             }
2518                                         }
2519                                     }
2520                                     else if (IsToken (var_name_begin, "addr-offset}")
2521                                             || IsToken (var_name_begin, "concrete-only-addr-offset-no-padding}"))
2522                                     {
2523                                         if (IsToken (var_name_begin, "concrete-only-addr-offset-no-padding}"))
2524                                         {
2525                                             addr_offset_print_with_no_padding = true;
2526                                             addr_offset_concrete_func_only = true;
2527                                         }
2528                                         var_success = addr != NULL;
2529                                         if (var_success)
2530                                         {
2531                                             format_addr = *addr;
2532                                             calculate_format_addr_function_offset = true;
2533                                         }
2534                                     }
2535                                     else if (IsToken (var_name_begin, "line-offset}"))
2536                                     {
2537                                         var_success = sc->line_entry.range.GetBaseAddress().IsValid();
2538                                         if (var_success)
2539                                         {
2540                                             format_addr = sc->line_entry.range.GetBaseAddress();
2541                                             calculate_format_addr_function_offset = true;
2542                                         }
2543                                     }
2544                                     else if (IsToken (var_name_begin, "pc-offset}"))
2545                                     {
2546                                         StackFrame *frame = exe_ctx->GetFramePtr();
2547                                         var_success = frame != NULL;
2548                                         if (var_success)
2549                                         {
2550                                             format_addr = frame->GetFrameCodeAddress();
2551                                             calculate_format_addr_function_offset = true;
2552                                         }
2553                                     }
2554                                 }
2555                             }
2556                             break;
2557 
2558                         case 'l':
2559                             if (IsToken (var_name_begin, "line."))
2560                             {
2561                                 if (sc && sc->line_entry.IsValid())
2562                                 {
2563                                     var_name_begin += ::strlen ("line.");
2564                                     if (IsToken (var_name_begin, "file."))
2565                                     {
2566                                         var_name_begin += ::strlen ("file.");
2567 
2568                                         if (IsToken (var_name_begin, "basename}"))
2569                                         {
2570                                             format_file_spec.GetFilename() = sc->line_entry.file.GetFilename();
2571                                             var_success = (bool)format_file_spec;
2572                                         }
2573                                         else if (IsToken (var_name_begin, "fullpath}"))
2574                                         {
2575                                             format_file_spec = sc->line_entry.file;
2576                                             var_success = (bool)format_file_spec;
2577                                         }
2578                                     }
2579                                     else if (IsTokenWithFormat (var_name_begin, "number", token_format, "%" PRIu64, exe_ctx, sc))
2580                                     {
2581                                         var_success = true;
2582                                         s.Printf(token_format.c_str(), (uint64_t)sc->line_entry.line);
2583                                     }
2584                                     else if ((IsToken (var_name_begin, "start-addr}")) ||
2585                                              (IsToken (var_name_begin, "end-addr}")))
2586                                     {
2587                                         var_success = sc && sc->line_entry.range.GetBaseAddress().IsValid();
2588                                         if (var_success)
2589                                         {
2590                                             format_addr = sc->line_entry.range.GetBaseAddress();
2591                                             if (var_name_begin[0] == 'e')
2592                                                 format_addr.Slide (sc->line_entry.range.GetByteSize());
2593                                         }
2594                                     }
2595                                 }
2596                             }
2597                             break;
2598                         case 'c':
2599                             if (IsToken (var_name_begin, "current-pc-arrow"))
2600                             {
2601                                 if (addr && exe_ctx && exe_ctx->GetFramePtr())
2602                                 {
2603                                     RegisterContextSP reg_ctx = exe_ctx->GetFramePtr()->GetRegisterContextSP();
2604                                     if (reg_ctx.get())
2605                                     {
2606                                         addr_t pc_loadaddr = reg_ctx->GetPC();
2607                                         if (pc_loadaddr != LLDB_INVALID_ADDRESS)
2608                                         {
2609                                             Address pc;
2610                                             pc.SetLoadAddress (pc_loadaddr, exe_ctx->GetTargetPtr());
2611                                             if (pc == *addr)
2612                                             {
2613                                                 s.Printf ("->");
2614                                                 var_success = true;
2615                                             }
2616                                             else
2617                                             {
2618                                                 s.Printf("  ");
2619                                                 var_success = true;
2620                                             }
2621                                         }
2622                                     }
2623                                 }
2624                             }
2625                             break;
2626                         }
2627 
2628                         if (var_success)
2629                         {
2630                             // If format addr is valid, then we need to print an address
2631                             if (reg_num != LLDB_INVALID_REGNUM)
2632                             {
2633                                 StackFrame *frame = exe_ctx->GetFramePtr();
2634                                 // We have a register value to display...
2635                                 if (reg_num == LLDB_REGNUM_GENERIC_PC && reg_kind == eRegisterKindGeneric)
2636                                 {
2637                                     format_addr = frame->GetFrameCodeAddress();
2638                                 }
2639                                 else
2640                                 {
2641                                     if (reg_ctx == NULL)
2642                                         reg_ctx = frame->GetRegisterContext().get();
2643 
2644                                     if (reg_ctx)
2645                                     {
2646                                         if (reg_kind != kNumRegisterKinds)
2647                                             reg_num = reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
2648                                         reg_info = reg_ctx->GetRegisterInfoAtIndex (reg_num);
2649                                         var_success = reg_info != NULL;
2650                                     }
2651                                 }
2652                             }
2653 
2654                             if (reg_info != NULL)
2655                             {
2656                                 RegisterValue reg_value;
2657                                 var_success = reg_ctx->ReadRegister (reg_info, reg_value);
2658                                 if (var_success)
2659                                 {
2660                                     reg_value.Dump(&s, reg_info, false, false, eFormatDefault);
2661                                 }
2662                             }
2663 
2664                             if (format_file_spec)
2665                             {
2666                                 s << format_file_spec;
2667                             }
2668 
2669                             // If format addr is valid, then we need to print an address
2670                             if (format_addr.IsValid())
2671                             {
2672                                 var_success = false;
2673 
2674                                 if (calculate_format_addr_function_offset)
2675                                 {
2676                                     Address func_addr;
2677 
2678                                     if (sc)
2679                                     {
2680                                         if (sc->function)
2681                                         {
2682                                             func_addr = sc->function->GetAddressRange().GetBaseAddress();
2683                                             if (sc->block && addr_offset_concrete_func_only == false)
2684                                             {
2685                                                 // Check to make sure we aren't in an inline
2686                                                 // function. If we are, use the inline block
2687                                                 // range that contains "format_addr" since
2688                                                 // blocks can be discontiguous.
2689                                                 Block *inline_block = sc->block->GetContainingInlinedBlock ();
2690                                                 AddressRange inline_range;
2691                                                 if (inline_block && inline_block->GetRangeContainingAddress (format_addr, inline_range))
2692                                                     func_addr = inline_range.GetBaseAddress();
2693                                             }
2694                                         }
2695                                         else if (sc->symbol && sc->symbol->ValueIsAddress())
2696                                             func_addr = sc->symbol->GetAddress();
2697                                     }
2698 
2699                                     if (func_addr.IsValid())
2700                                     {
2701                                         const char *addr_offset_padding  =  " ";
2702                                         if (addr_offset_print_with_no_padding)
2703                                         {
2704                                             addr_offset_padding = "";
2705                                         }
2706                                         if (func_addr.GetSection() == format_addr.GetSection())
2707                                         {
2708                                             addr_t func_file_addr = func_addr.GetFileAddress();
2709                                             addr_t addr_file_addr = format_addr.GetFileAddress();
2710                                             if (addr_file_addr > func_file_addr)
2711                                                 s.Printf("%s+%s%" PRIu64, addr_offset_padding, addr_offset_padding, addr_file_addr - func_file_addr);
2712                                             else if (addr_file_addr < func_file_addr)
2713                                                 s.Printf("%s-%s%" PRIu64, addr_offset_padding, addr_offset_padding, func_file_addr - addr_file_addr);
2714                                             var_success = true;
2715                                         }
2716                                         else
2717                                         {
2718                                             Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2719                                             if (target)
2720                                             {
2721                                                 addr_t func_load_addr = func_addr.GetLoadAddress (target);
2722                                                 addr_t addr_load_addr = format_addr.GetLoadAddress (target);
2723                                                 if (addr_load_addr > func_load_addr)
2724                                                     s.Printf("%s+%s%" PRIu64, addr_offset_padding, addr_offset_padding, addr_load_addr - func_load_addr);
2725                                                 else if (addr_load_addr < func_load_addr)
2726                                                     s.Printf("%s-%s%" PRIu64, addr_offset_padding, addr_offset_padding, func_load_addr - addr_load_addr);
2727                                                 var_success = true;
2728                                             }
2729                                         }
2730                                     }
2731                                 }
2732                                 else
2733                                 {
2734                                     Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
2735                                     addr_t vaddr = LLDB_INVALID_ADDRESS;
2736                                     if (exe_ctx && !target->GetSectionLoadList().IsEmpty())
2737                                         vaddr = format_addr.GetLoadAddress (target);
2738                                     if (vaddr == LLDB_INVALID_ADDRESS)
2739                                         vaddr = format_addr.GetFileAddress ();
2740 
2741                                     if (vaddr != LLDB_INVALID_ADDRESS)
2742                                     {
2743                                         int addr_width = 0;
2744                                         if (exe_ctx && target)
2745                                         {
2746                                             addr_width = target->GetArchitecture().GetAddressByteSize() * 2;
2747                                         }
2748                                         if (addr_width == 0)
2749                                             addr_width = 16;
2750                                         if (print_file_addr_or_load_addr)
2751                                         {
2752                                             format_addr.Dump (&s, exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL, Address::DumpStyleLoadAddress, Address::DumpStyleModuleWithFileAddress, 0);
2753                                         }
2754                                         else
2755                                         {
2756                                             s.Printf("0x%*.*" PRIx64, addr_width, addr_width, vaddr);
2757                                         }
2758                                         var_success = true;
2759                                     }
2760                                 }
2761                             }
2762                         }
2763 
2764                         if (var_success == false)
2765                             success = false;
2766                     }
2767                     p = var_name_end;
2768                 }
2769                 else
2770                     break;
2771             }
2772             else
2773             {
2774                 // We got a dollar sign with no '{' after it, it must just be a dollar sign
2775                 s.PutChar(*p);
2776             }
2777         }
2778         else if (*p == '\\')
2779         {
2780             ++p; // skip the slash
2781             switch (*p)
2782             {
2783             case 'a': s.PutChar ('\a'); break;
2784             case 'b': s.PutChar ('\b'); break;
2785             case 'f': s.PutChar ('\f'); break;
2786             case 'n': s.PutChar ('\n'); break;
2787             case 'r': s.PutChar ('\r'); break;
2788             case 't': s.PutChar ('\t'); break;
2789             case 'v': s.PutChar ('\v'); break;
2790             case '\'': s.PutChar ('\''); break;
2791             case '\\': s.PutChar ('\\'); break;
2792             case '0':
2793                 // 1 to 3 octal chars
2794                 {
2795                     // Make a string that can hold onto the initial zero char,
2796                     // up to 3 octal digits, and a terminating NULL.
2797                     char oct_str[5] = { 0, 0, 0, 0, 0 };
2798 
2799                     int i;
2800                     for (i=0; (p[i] >= '0' && p[i] <= '7') && i<4; ++i)
2801                         oct_str[i] = p[i];
2802 
2803                     // We don't want to consume the last octal character since
2804                     // the main for loop will do this for us, so we advance p by
2805                     // one less than i (even if i is zero)
2806                     p += i - 1;
2807                     unsigned long octal_value = ::strtoul (oct_str, NULL, 8);
2808                     if (octal_value <= UINT8_MAX)
2809                     {
2810                         s.PutChar((char)octal_value);
2811                     }
2812                 }
2813                 break;
2814 
2815             case 'x':
2816                 // hex number in the format
2817                 if (isxdigit(p[1]))
2818                 {
2819                     ++p;    // Skip the 'x'
2820 
2821                     // Make a string that can hold onto two hex chars plus a
2822                     // NULL terminator
2823                     char hex_str[3] = { 0,0,0 };
2824                     hex_str[0] = *p;
2825                     if (isxdigit(p[1]))
2826                     {
2827                         ++p; // Skip the first of the two hex chars
2828                         hex_str[1] = *p;
2829                     }
2830 
2831                     unsigned long hex_value = strtoul (hex_str, NULL, 16);
2832                     if (hex_value <= UINT8_MAX)
2833                         s.PutChar ((char)hex_value);
2834                 }
2835                 else
2836                 {
2837                     s.PutChar('x');
2838                 }
2839                 break;
2840 
2841             default:
2842                 // Just desensitize any other character by just printing what
2843                 // came after the '\'
2844                 s << *p;
2845                 break;
2846 
2847             }
2848 
2849         }
2850     }
2851     if (end)
2852         *end = p;
2853     return success;
2854 }
2855 
2856 bool
2857 Debugger::FormatPrompt
2858 (
2859     const char *format,
2860     const SymbolContext *sc,
2861     const ExecutionContext *exe_ctx,
2862     const Address *addr,
2863     Stream &s,
2864     ValueObject* valobj
2865 )
2866 {
2867     bool use_color = exe_ctx ? exe_ctx->GetTargetRef().GetDebugger().GetUseColor() : true;
2868     std::string format_str = lldb_utility::ansi::FormatAnsiTerminalCodes (format, use_color);
2869     if (format_str.length())
2870         format = format_str.c_str();
2871     return FormatPromptRecurse (format, sc, exe_ctx, addr, s, NULL, valobj, false, false);
2872 }
2873 
2874 bool
2875 Debugger::FormatDisassemblerAddress (const char *format,
2876                                      const SymbolContext *sc,
2877                                      const SymbolContext *prev_sc,
2878                                      const ExecutionContext *exe_ctx,
2879                                      const Address *addr,
2880                                      Stream &s)
2881 {
2882     if (format == NULL && exe_ctx != NULL && exe_ctx->HasTargetScope())
2883     {
2884         format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
2885     }
2886     bool function_changed = false;
2887     bool initial_function = false;
2888     if (prev_sc && (prev_sc->function || prev_sc->symbol))
2889     {
2890         if (sc && (sc->function || sc->symbol))
2891         {
2892             if (prev_sc->symbol && sc->symbol)
2893             {
2894                 if (!sc->symbol->Compare (prev_sc->symbol->GetName(), prev_sc->symbol->GetType()))
2895                 {
2896                     function_changed = true;
2897                 }
2898             }
2899             else if (prev_sc->function && sc->function)
2900             {
2901                 if (prev_sc->function->GetMangled() != sc->function->GetMangled())
2902                 {
2903                     function_changed = true;
2904                 }
2905             }
2906         }
2907     }
2908     // The first context on a list of instructions will have a prev_sc that
2909     // has no Function or Symbol -- if SymbolContext had an IsValid() method, it
2910     // would return false.  But we do get a prev_sc pointer.
2911     if ((sc && (sc->function || sc->symbol))
2912         && prev_sc && (prev_sc->function == NULL && prev_sc->symbol == NULL))
2913     {
2914         initial_function = true;
2915     }
2916     return FormatPromptRecurse (format, sc, exe_ctx, addr, s, NULL, NULL, function_changed, initial_function);
2917 }
2918 
2919 
2920 void
2921 Debugger::SetLoggingCallback (lldb::LogOutputCallback log_callback, void *baton)
2922 {
2923     // For simplicity's sake, I am not going to deal with how to close down any
2924     // open logging streams, I just redirect everything from here on out to the
2925     // callback.
2926     m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton));
2927 }
2928 
2929 bool
2930 Debugger::EnableLog (const char *channel, const char **categories, const char *log_file, uint32_t log_options, Stream &error_stream)
2931 {
2932     Log::Callbacks log_callbacks;
2933 
2934     StreamSP log_stream_sp;
2935     if (m_log_callback_stream_sp)
2936     {
2937         log_stream_sp = m_log_callback_stream_sp;
2938         // For now when using the callback mode you always get thread & timestamp.
2939         log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
2940     }
2941     else if (log_file == NULL || *log_file == '\0')
2942     {
2943         log_stream_sp = GetOutputFile();
2944     }
2945     else
2946     {
2947         LogStreamMap::iterator pos = m_log_streams.find(log_file);
2948         if (pos != m_log_streams.end())
2949             log_stream_sp = pos->second.lock();
2950         if (!log_stream_sp)
2951         {
2952             log_stream_sp.reset (new StreamFile (log_file));
2953             m_log_streams[log_file] = log_stream_sp;
2954         }
2955     }
2956     assert (log_stream_sp.get());
2957 
2958     if (log_options == 0)
2959         log_options = LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
2960 
2961     if (Log::GetLogChannelCallbacks (ConstString(channel), log_callbacks))
2962     {
2963         log_callbacks.enable (log_stream_sp, log_options, categories, &error_stream);
2964         return true;
2965     }
2966     else
2967     {
2968         LogChannelSP log_channel_sp (LogChannel::FindPlugin (channel));
2969         if (log_channel_sp)
2970         {
2971             if (log_channel_sp->Enable (log_stream_sp, log_options, &error_stream, categories))
2972             {
2973                 return true;
2974             }
2975             else
2976             {
2977                 error_stream.Printf ("Invalid log channel '%s'.\n", channel);
2978                 return false;
2979             }
2980         }
2981         else
2982         {
2983             error_stream.Printf ("Invalid log channel '%s'.\n", channel);
2984             return false;
2985         }
2986     }
2987     return false;
2988 }
2989 
2990 SourceManager &
2991 Debugger::GetSourceManager ()
2992 {
2993     if (m_source_manager_ap.get() == NULL)
2994         m_source_manager_ap.reset (new SourceManager (shared_from_this()));
2995     return *m_source_manager_ap;
2996 }
2997 
2998 
2999 
3000 // This function handles events that were broadcast by the process.
3001 void
3002 Debugger::HandleBreakpointEvent (const EventSP &event_sp)
3003 {
3004     using namespace lldb;
3005     const uint32_t event_type = Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent (event_sp);
3006 
3007 //    if (event_type & eBreakpointEventTypeAdded
3008 //        || event_type & eBreakpointEventTypeRemoved
3009 //        || event_type & eBreakpointEventTypeEnabled
3010 //        || event_type & eBreakpointEventTypeDisabled
3011 //        || event_type & eBreakpointEventTypeCommandChanged
3012 //        || event_type & eBreakpointEventTypeConditionChanged
3013 //        || event_type & eBreakpointEventTypeIgnoreChanged
3014 //        || event_type & eBreakpointEventTypeLocationsResolved)
3015 //    {
3016 //        // Don't do anything about these events, since the breakpoint commands already echo these actions.
3017 //    }
3018 //
3019     if (event_type & eBreakpointEventTypeLocationsAdded)
3020     {
3021         uint32_t num_new_locations = Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(event_sp);
3022         if (num_new_locations > 0)
3023         {
3024             BreakpointSP breakpoint = Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
3025             StreamFileSP output_sp (GetOutputFile());
3026             if (output_sp)
3027             {
3028                 output_sp->Printf("%d location%s added to breakpoint %d\n",
3029                                   num_new_locations,
3030                                   num_new_locations == 1 ? "" : "s",
3031                                   breakpoint->GetID());
3032                 RefreshTopIOHandler();
3033             }
3034         }
3035     }
3036 //    else if (event_type & eBreakpointEventTypeLocationsRemoved)
3037 //    {
3038 //        // These locations just get disabled, not sure it is worth spamming folks about this on the command line.
3039 //    }
3040 //    else if (event_type & eBreakpointEventTypeLocationsResolved)
3041 //    {
3042 //        // This might be an interesting thing to note, but I'm going to leave it quiet for now, it just looked noisy.
3043 //    }
3044 }
3045 
3046 size_t
3047 Debugger::GetProcessSTDOUT (Process *process, Stream *stream)
3048 {
3049     size_t total_bytes = 0;
3050     if (stream == NULL)
3051         stream = GetOutputFile().get();
3052 
3053     if (stream)
3054     {
3055         //  The process has stuff waiting for stdout; get it and write it out to the appropriate place.
3056         if (process == NULL)
3057         {
3058             TargetSP target_sp = GetTargetList().GetSelectedTarget();
3059             if (target_sp)
3060                 process = target_sp->GetProcessSP().get();
3061         }
3062         if (process)
3063         {
3064             Error error;
3065             size_t len;
3066             char stdio_buffer[1024];
3067             while ((len = process->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
3068             {
3069                 stream->Write(stdio_buffer, len);
3070                 total_bytes += len;
3071             }
3072         }
3073         stream->Flush();
3074     }
3075     return total_bytes;
3076 }
3077 
3078 size_t
3079 Debugger::GetProcessSTDERR (Process *process, Stream *stream)
3080 {
3081     size_t total_bytes = 0;
3082     if (stream == NULL)
3083         stream = GetOutputFile().get();
3084 
3085     if (stream)
3086     {
3087         //  The process has stuff waiting for stderr; get it and write it out to the appropriate place.
3088         if (process == NULL)
3089         {
3090             TargetSP target_sp = GetTargetList().GetSelectedTarget();
3091             if (target_sp)
3092                 process = target_sp->GetProcessSP().get();
3093         }
3094         if (process)
3095         {
3096             Error error;
3097             size_t len;
3098             char stdio_buffer[1024];
3099             while ((len = process->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
3100             {
3101                 stream->Write(stdio_buffer, len);
3102                 total_bytes += len;
3103             }
3104         }
3105         stream->Flush();
3106     }
3107     return total_bytes;
3108 }
3109 
3110 
3111 // This function handles events that were broadcast by the process.
3112 void
3113 Debugger::HandleProcessEvent (const EventSP &event_sp)
3114 {
3115     using namespace lldb;
3116     const uint32_t event_type = event_sp->GetType();
3117     ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
3118 
3119     StreamString output_stream;
3120     StreamString error_stream;
3121     const bool gui_enabled = IsForwardingEvents();
3122 
3123     if (!gui_enabled)
3124     {
3125         bool pop_process_io_handler = false;
3126         assert (process_sp);
3127 
3128         if (event_type & Process::eBroadcastBitSTDOUT || event_type & Process::eBroadcastBitStateChanged)
3129         {
3130             GetProcessSTDOUT (process_sp.get(), &output_stream);
3131         }
3132 
3133         if (event_type & Process::eBroadcastBitSTDERR || event_type & Process::eBroadcastBitStateChanged)
3134         {
3135             GetProcessSTDERR (process_sp.get(), &error_stream);
3136         }
3137 
3138         if (event_type & Process::eBroadcastBitStateChanged)
3139         {
3140             Process::HandleProcessStateChangedEvent (event_sp, &output_stream, pop_process_io_handler);
3141         }
3142 
3143         if (output_stream.GetSize() || error_stream.GetSize())
3144         {
3145             StreamFileSP error_stream_sp (GetOutputFile());
3146             bool top_io_handler_hid = false;
3147 
3148             if (process_sp->ProcessIOHandlerIsActive() == false)
3149                 top_io_handler_hid = HideTopIOHandler();
3150 
3151             if (output_stream.GetSize())
3152             {
3153                 StreamFileSP output_stream_sp (GetOutputFile());
3154                 if (output_stream_sp)
3155                     output_stream_sp->Write (output_stream.GetData(), output_stream.GetSize());
3156             }
3157 
3158             if (error_stream.GetSize())
3159             {
3160                 StreamFileSP error_stream_sp (GetErrorFile());
3161                 if (error_stream_sp)
3162                     error_stream_sp->Write (error_stream.GetData(), error_stream.GetSize());
3163             }
3164 
3165             if (top_io_handler_hid)
3166                 RefreshTopIOHandler();
3167         }
3168 
3169         if (pop_process_io_handler)
3170             process_sp->PopProcessIOHandler();
3171     }
3172 }
3173 
3174 void
3175 Debugger::HandleThreadEvent (const EventSP &event_sp)
3176 {
3177     // At present the only thread event we handle is the Frame Changed event,
3178     // and all we do for that is just reprint the thread status for that thread.
3179     using namespace lldb;
3180     const uint32_t event_type = event_sp->GetType();
3181     if (event_type == Thread::eBroadcastBitStackChanged   ||
3182         event_type == Thread::eBroadcastBitThreadSelected )
3183     {
3184         ThreadSP thread_sp (Thread::ThreadEventData::GetThreadFromEvent (event_sp.get()));
3185         if (thread_sp)
3186         {
3187             HideTopIOHandler();
3188             StreamFileSP stream_sp (GetOutputFile());
3189             thread_sp->GetStatus(*stream_sp, 0, 1, 1);
3190             RefreshTopIOHandler();
3191         }
3192     }
3193 }
3194 
3195 bool
3196 Debugger::IsForwardingEvents ()
3197 {
3198     return (bool)m_forward_listener_sp;
3199 }
3200 
3201 void
3202 Debugger::EnableForwardEvents (const ListenerSP &listener_sp)
3203 {
3204     m_forward_listener_sp = listener_sp;
3205 }
3206 
3207 void
3208 Debugger::CancelForwardEvents (const ListenerSP &listener_sp)
3209 {
3210     m_forward_listener_sp.reset();
3211 }
3212 
3213 
3214 void
3215 Debugger::DefaultEventHandler()
3216 {
3217     Listener& listener(GetListener());
3218     ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
3219     ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
3220     ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
3221     BroadcastEventSpec target_event_spec (broadcaster_class_target,
3222                                           Target::eBroadcastBitBreakpointChanged);
3223 
3224     BroadcastEventSpec process_event_spec (broadcaster_class_process,
3225                                            Process::eBroadcastBitStateChanged   |
3226                                            Process::eBroadcastBitSTDOUT         |
3227                                            Process::eBroadcastBitSTDERR);
3228 
3229     BroadcastEventSpec thread_event_spec (broadcaster_class_thread,
3230                                           Thread::eBroadcastBitStackChanged     |
3231                                           Thread::eBroadcastBitThreadSelected   );
3232 
3233     listener.StartListeningForEventSpec (*this, target_event_spec);
3234     listener.StartListeningForEventSpec (*this, process_event_spec);
3235     listener.StartListeningForEventSpec (*this, thread_event_spec);
3236     listener.StartListeningForEvents (m_command_interpreter_ap.get(),
3237                                       CommandInterpreter::eBroadcastBitQuitCommandReceived      |
3238                                       CommandInterpreter::eBroadcastBitAsynchronousOutputData   |
3239                                       CommandInterpreter::eBroadcastBitAsynchronousErrorData    );
3240 
3241     bool done = false;
3242     while (!done)
3243     {
3244 //        Mutex::Locker locker;
3245 //        if (locker.TryLock(m_input_reader_stack.GetMutex()))
3246 //        {
3247 //            if (m_input_reader_stack.IsEmpty())
3248 //                break;
3249 //        }
3250 //
3251         EventSP event_sp;
3252         if (listener.WaitForEvent(NULL, event_sp))
3253         {
3254             if (event_sp)
3255             {
3256                 Broadcaster *broadcaster = event_sp->GetBroadcaster();
3257                 if (broadcaster)
3258                 {
3259                     uint32_t event_type = event_sp->GetType();
3260                     ConstString broadcaster_class (broadcaster->GetBroadcasterClass());
3261                     if (broadcaster_class == broadcaster_class_process)
3262                     {
3263                         HandleProcessEvent (event_sp);
3264                     }
3265                     else if (broadcaster_class == broadcaster_class_target)
3266                     {
3267                         if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(event_sp.get()))
3268                         {
3269                             HandleBreakpointEvent (event_sp);
3270                         }
3271                     }
3272                     else if (broadcaster_class == broadcaster_class_thread)
3273                     {
3274                         HandleThreadEvent (event_sp);
3275                     }
3276                     else if (broadcaster == m_command_interpreter_ap.get())
3277                     {
3278                         if (event_type & CommandInterpreter::eBroadcastBitQuitCommandReceived)
3279                         {
3280                             done = true;
3281                         }
3282                         else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousErrorData)
3283                         {
3284                             const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
3285                             if (data && data[0])
3286                             {
3287                                 StreamFileSP error_sp (GetErrorFile());
3288                                 if (error_sp)
3289                                 {
3290                                     HideTopIOHandler();
3291                                     error_sp->PutCString(data);
3292                                     error_sp->Flush();
3293                                     RefreshTopIOHandler();
3294                                 }
3295                             }
3296                         }
3297                         else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousOutputData)
3298                         {
3299                             const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get()));
3300                             if (data && data[0])
3301                             {
3302                                 StreamFileSP output_sp (GetOutputFile());
3303                                 if (output_sp)
3304                                 {
3305                                     HideTopIOHandler();
3306                                     output_sp->PutCString(data);
3307                                     output_sp->Flush();
3308                                     RefreshTopIOHandler();
3309                                 }
3310                             }
3311                         }
3312                     }
3313                 }
3314 
3315                 if (m_forward_listener_sp)
3316                     m_forward_listener_sp->AddEvent(event_sp);
3317             }
3318         }
3319     }
3320 }
3321 
3322 lldb::thread_result_t
3323 Debugger::EventHandlerThread (lldb::thread_arg_t arg)
3324 {
3325     ((Debugger *)arg)->DefaultEventHandler();
3326     return NULL;
3327 }
3328 
3329 bool
3330 Debugger::StartEventHandlerThread()
3331 {
3332     if (!m_event_handler_thread.IsJoinable())
3333     {
3334         // Use larger 8MB stack for this thread
3335         m_event_handler_thread = ThreadLauncher::LaunchThread("lldb.debugger.event-handler", EventHandlerThread, this, NULL,
3336                                                               g_debugger_event_thread_stack_bytes);
3337     }
3338     return m_event_handler_thread.IsJoinable();
3339 }
3340 
3341 void
3342 Debugger::StopEventHandlerThread()
3343 {
3344     if (m_event_handler_thread.IsJoinable())
3345     {
3346         GetCommandInterpreter().BroadcastEvent(CommandInterpreter::eBroadcastBitQuitCommandReceived);
3347         m_event_handler_thread.Join(nullptr);
3348     }
3349 }
3350 
3351 
3352 lldb::thread_result_t
3353 Debugger::IOHandlerThread (lldb::thread_arg_t arg)
3354 {
3355     Debugger *debugger = (Debugger *)arg;
3356     debugger->ExecuteIOHanders();
3357     debugger->StopEventHandlerThread();
3358     return NULL;
3359 }
3360 
3361 bool
3362 Debugger::StartIOHandlerThread()
3363 {
3364     if (!m_io_handler_thread.IsJoinable())
3365         m_io_handler_thread = ThreadLauncher::LaunchThread ("lldb.debugger.io-handler",
3366                                                             IOHandlerThread,
3367                                                             this,
3368                                                             NULL,
3369                                                             8*1024*1024); // Use larger 8MB stack for this thread
3370     return m_io_handler_thread.IsJoinable();
3371 }
3372 
3373 void
3374 Debugger::StopIOHandlerThread()
3375 {
3376     if (m_io_handler_thread.IsJoinable())
3377     {
3378         if (m_input_file_sp)
3379             m_input_file_sp->GetFile().Close();
3380         m_io_handler_thread.Join(nullptr);
3381     }
3382 }
3383 
3384 
3385