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