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