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