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