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/FormatManager.h"
20 #include "lldb/Core/InputReader.h"
21 #include "lldb/Core/RegisterValue.h"
22 #include "lldb/Core/State.h"
23 #include "lldb/Core/StreamAsynchronousIO.h"
24 #include "lldb/Core/StreamString.h"
25 #include "lldb/Core/Timer.h"
26 #include "lldb/Core/ValueObject.h"
27 #include "lldb/Host/Terminal.h"
28 #include "lldb/Interpreter/CommandInterpreter.h"
29 #include "lldb/Target/TargetList.h"
30 #include "lldb/Target/Process.h"
31 #include "lldb/Target/RegisterContext.h"
32 #include "lldb/Target/StopInfo.h"
33 #include "lldb/Target/Thread.h"
34 
35 
36 using namespace lldb;
37 using namespace lldb_private;
38 
39 
40 static uint32_t g_shared_debugger_refcount = 0;
41 static lldb::user_id_t g_unique_id = 1;
42 
43 #pragma mark Static Functions
44 
45 static Mutex &
46 GetDebuggerListMutex ()
47 {
48     static Mutex g_mutex(Mutex::eMutexTypeRecursive);
49     return g_mutex;
50 }
51 
52 typedef std::vector<DebuggerSP> DebuggerList;
53 
54 static DebuggerList &
55 GetDebuggerList()
56 {
57     // hide the static debugger list inside a singleton accessor to avoid
58     // global init contructors
59     static DebuggerList g_list;
60     return g_list;
61 }
62 
63 
64 #pragma mark Debugger
65 
66 UserSettingsControllerSP &
67 Debugger::GetSettingsController ()
68 {
69     static UserSettingsControllerSP g_settings_controller;
70     return g_settings_controller;
71 }
72 
73 int
74 Debugger::TestDebuggerRefCount ()
75 {
76     return g_shared_debugger_refcount;
77 }
78 
79 void
80 Debugger::Initialize ()
81 {
82     if (g_shared_debugger_refcount == 0)
83     {
84         lldb_private::Initialize();
85     }
86     g_shared_debugger_refcount++;
87 
88 }
89 
90 void
91 Debugger::Terminate ()
92 {
93     if (g_shared_debugger_refcount > 0)
94     {
95         g_shared_debugger_refcount--;
96         if (g_shared_debugger_refcount == 0)
97         {
98             lldb_private::WillTerminate();
99             lldb_private::Terminate();
100 
101             // Clear our master list of debugger objects
102             Mutex::Locker locker (GetDebuggerListMutex ());
103             GetDebuggerList().clear();
104         }
105     }
106 }
107 
108 void
109 Debugger::SettingsInitialize ()
110 {
111     static bool g_initialized = false;
112 
113     if (!g_initialized)
114     {
115         g_initialized = true;
116         UserSettingsControllerSP &usc = GetSettingsController();
117         usc.reset (new SettingsController);
118         UserSettingsController::InitializeSettingsController (usc,
119                                                               SettingsController::global_settings_table,
120                                                               SettingsController::instance_settings_table);
121         // Now call SettingsInitialize for each settings 'child' of Debugger
122         Target::SettingsInitialize ();
123     }
124 }
125 
126 void
127 Debugger::SettingsTerminate ()
128 {
129 
130     // Must call SettingsTerminate() for each settings 'child' of Debugger, before terminating the Debugger's
131     // Settings.
132 
133     Target::SettingsTerminate ();
134 
135     // Now terminate the Debugger Settings.
136 
137     UserSettingsControllerSP &usc = GetSettingsController();
138     UserSettingsController::FinalizeSettingsController (usc);
139     usc.reset();
140 }
141 
142 DebuggerSP
143 Debugger::CreateInstance ()
144 {
145     DebuggerSP debugger_sp (new Debugger);
146     // Scope for locker
147     {
148         Mutex::Locker locker (GetDebuggerListMutex ());
149         GetDebuggerList().push_back(debugger_sp);
150     }
151     return debugger_sp;
152 }
153 
154 void
155 Debugger::Destroy (lldb::DebuggerSP &debugger_sp)
156 {
157     if (debugger_sp.get() == NULL)
158         return;
159 
160     Mutex::Locker locker (GetDebuggerListMutex ());
161     DebuggerList &debugger_list = GetDebuggerList ();
162     DebuggerList::iterator pos, end = debugger_list.end();
163     for (pos = debugger_list.begin (); pos != end; ++pos)
164     {
165         if ((*pos).get() == debugger_sp.get())
166         {
167             debugger_list.erase (pos);
168             return;
169         }
170     }
171 
172 }
173 
174 lldb::DebuggerSP
175 Debugger::GetSP ()
176 {
177     lldb::DebuggerSP debugger_sp;
178 
179     Mutex::Locker locker (GetDebuggerListMutex ());
180     DebuggerList &debugger_list = GetDebuggerList();
181     DebuggerList::iterator pos, end = debugger_list.end();
182     for (pos = debugger_list.begin(); pos != end; ++pos)
183     {
184         if ((*pos).get() == this)
185         {
186             debugger_sp = *pos;
187             break;
188         }
189     }
190     return debugger_sp;
191 }
192 
193 lldb::DebuggerSP
194 Debugger::FindDebuggerWithInstanceName (const ConstString &instance_name)
195 {
196     lldb::DebuggerSP debugger_sp;
197 
198     Mutex::Locker locker (GetDebuggerListMutex ());
199     DebuggerList &debugger_list = GetDebuggerList();
200     DebuggerList::iterator pos, end = debugger_list.end();
201 
202     for (pos = debugger_list.begin(); pos != end; ++pos)
203     {
204         if ((*pos).get()->m_instance_name == instance_name)
205         {
206             debugger_sp = *pos;
207             break;
208         }
209     }
210     return debugger_sp;
211 }
212 
213 TargetSP
214 Debugger::FindTargetWithProcessID (lldb::pid_t pid)
215 {
216     lldb::TargetSP target_sp;
217     Mutex::Locker locker (GetDebuggerListMutex ());
218     DebuggerList &debugger_list = GetDebuggerList();
219     DebuggerList::iterator pos, end = debugger_list.end();
220     for (pos = debugger_list.begin(); pos != end; ++pos)
221     {
222         target_sp = (*pos)->GetTargetList().FindTargetWithProcessID (pid);
223         if (target_sp)
224             break;
225     }
226     return target_sp;
227 }
228 
229 
230 Debugger::Debugger () :
231     UserID (g_unique_id++),
232     DebuggerInstanceSettings (*GetSettingsController()),
233     m_input_comm("debugger.input"),
234     m_input_file (),
235     m_output_file (),
236     m_error_file (),
237     m_target_list (),
238     m_platform_list (),
239     m_listener ("lldb.Debugger"),
240     m_source_manager (),
241     m_command_interpreter_ap (new CommandInterpreter (*this, eScriptLanguageDefault, false)),
242     m_input_reader_stack (),
243     m_input_reader_data ()
244 {
245     m_command_interpreter_ap->Initialize ();
246     // Always add our default platform to the platform list
247     PlatformSP default_platform_sp (Platform::GetDefaultPlatform());
248     assert (default_platform_sp.get());
249     m_platform_list.Append (default_platform_sp, true);
250 }
251 
252 Debugger::~Debugger ()
253 {
254     CleanUpInputReaders();
255     int num_targets = m_target_list.GetNumTargets();
256     for (int i = 0; i < num_targets; i++)
257     {
258         ProcessSP process_sp (m_target_list.GetTargetAtIndex (i)->GetProcessSP());
259         if (process_sp)
260             process_sp->Destroy();
261     }
262     DisconnectInput();
263 }
264 
265 
266 bool
267 Debugger::GetCloseInputOnEOF () const
268 {
269     return m_input_comm.GetCloseOnEOF();
270 }
271 
272 void
273 Debugger::SetCloseInputOnEOF (bool b)
274 {
275     m_input_comm.SetCloseOnEOF(b);
276 }
277 
278 bool
279 Debugger::GetAsyncExecution ()
280 {
281     return !m_command_interpreter_ap->GetSynchronous();
282 }
283 
284 void
285 Debugger::SetAsyncExecution (bool async_execution)
286 {
287     m_command_interpreter_ap->SetSynchronous (!async_execution);
288 }
289 
290 
291 void
292 Debugger::SetInputFileHandle (FILE *fh, bool tranfer_ownership)
293 {
294     File &in_file = GetInputFile();
295     in_file.SetStream (fh, tranfer_ownership);
296     if (in_file.IsValid() == false)
297         in_file.SetStream (stdin, true);
298 
299     // Disconnect from any old connection if we had one
300     m_input_comm.Disconnect ();
301     m_input_comm.SetConnection (new ConnectionFileDescriptor (in_file.GetDescriptor(), true));
302     m_input_comm.SetReadThreadBytesReceivedCallback (Debugger::DispatchInputCallback, this);
303 
304     Error error;
305     if (m_input_comm.StartReadThread (&error) == false)
306     {
307         File &err_file = GetErrorFile();
308 
309         err_file.Printf ("error: failed to main input read thread: %s", error.AsCString() ? error.AsCString() : "unkown error");
310         exit(1);
311     }
312 }
313 
314 void
315 Debugger::SetOutputFileHandle (FILE *fh, bool tranfer_ownership)
316 {
317     File &out_file = GetOutputFile();
318     out_file.SetStream (fh, tranfer_ownership);
319     if (out_file.IsValid() == false)
320         out_file.SetStream (stdout, false);
321 
322     GetCommandInterpreter().GetScriptInterpreter()->ResetOutputFileHandle (fh);
323 }
324 
325 void
326 Debugger::SetErrorFileHandle (FILE *fh, bool tranfer_ownership)
327 {
328     File &err_file = GetErrorFile();
329     err_file.SetStream (fh, tranfer_ownership);
330     if (err_file.IsValid() == false)
331         err_file.SetStream (stderr, false);
332 }
333 
334 ExecutionContext
335 Debugger::GetSelectedExecutionContext ()
336 {
337     ExecutionContext exe_ctx;
338     exe_ctx.Clear();
339 
340     lldb::TargetSP target_sp = GetSelectedTarget();
341     exe_ctx.target = target_sp.get();
342 
343     if (target_sp)
344     {
345         exe_ctx.process = target_sp->GetProcessSP().get();
346         if (exe_ctx.process && exe_ctx.process->IsRunning() == false)
347         {
348             exe_ctx.thread = exe_ctx.process->GetThreadList().GetSelectedThread().get();
349             if (exe_ctx.thread == NULL)
350                 exe_ctx.thread = exe_ctx.process->GetThreadList().GetThreadAtIndex(0).get();
351             if (exe_ctx.thread)
352             {
353                 exe_ctx.frame = exe_ctx.thread->GetSelectedFrame().get();
354                 if (exe_ctx.frame == NULL)
355                     exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex (0).get();
356             }
357         }
358     }
359     return exe_ctx;
360 
361 }
362 
363 InputReaderSP
364 Debugger::GetCurrentInputReader ()
365 {
366     InputReaderSP reader_sp;
367 
368     if (!m_input_reader_stack.IsEmpty())
369     {
370         // Clear any finished readers from the stack
371         while (CheckIfTopInputReaderIsDone()) ;
372 
373         if (!m_input_reader_stack.IsEmpty())
374             reader_sp = m_input_reader_stack.Top();
375     }
376 
377     return reader_sp;
378 }
379 
380 void
381 Debugger::DispatchInputCallback (void *baton, const void *bytes, size_t bytes_len)
382 {
383     if (bytes_len > 0)
384         ((Debugger *)baton)->DispatchInput ((char *)bytes, bytes_len);
385     else
386         ((Debugger *)baton)->DispatchInputEndOfFile ();
387 }
388 
389 
390 void
391 Debugger::DispatchInput (const char *bytes, size_t bytes_len)
392 {
393     if (bytes == NULL || bytes_len == 0)
394         return;
395 
396     WriteToDefaultReader (bytes, bytes_len);
397 }
398 
399 void
400 Debugger::DispatchInputInterrupt ()
401 {
402     m_input_reader_data.clear();
403 
404     InputReaderSP reader_sp (GetCurrentInputReader ());
405     if (reader_sp)
406     {
407         reader_sp->Notify (eInputReaderInterrupt);
408 
409         // If notifying the reader of the interrupt finished the reader, we should pop it off the stack.
410         while (CheckIfTopInputReaderIsDone ()) ;
411     }
412 }
413 
414 void
415 Debugger::DispatchInputEndOfFile ()
416 {
417     m_input_reader_data.clear();
418 
419     InputReaderSP reader_sp (GetCurrentInputReader ());
420     if (reader_sp)
421     {
422         reader_sp->Notify (eInputReaderEndOfFile);
423 
424         // If notifying the reader of the end-of-file finished the reader, we should pop it off the stack.
425         while (CheckIfTopInputReaderIsDone ()) ;
426     }
427 }
428 
429 void
430 Debugger::CleanUpInputReaders ()
431 {
432     m_input_reader_data.clear();
433 
434     // The bottom input reader should be the main debugger input reader.  We do not want to close that one here.
435     while (m_input_reader_stack.GetSize() > 1)
436     {
437         InputReaderSP reader_sp (GetCurrentInputReader ());
438         if (reader_sp)
439         {
440             reader_sp->Notify (eInputReaderEndOfFile);
441             reader_sp->SetIsDone (true);
442         }
443     }
444 }
445 
446 void
447 Debugger::NotifyTopInputReader (InputReaderAction notification)
448 {
449     InputReaderSP reader_sp (GetCurrentInputReader());
450     if (reader_sp)
451 	{
452         reader_sp->Notify (notification);
453 
454         // Flush out any input readers that are done.
455         while (CheckIfTopInputReaderIsDone ())
456             /* Do nothing. */;
457     }
458 }
459 
460 bool
461 Debugger::InputReaderIsTopReader (const lldb::InputReaderSP& reader_sp)
462 {
463     InputReaderSP top_reader_sp (GetCurrentInputReader());
464 
465     return (reader_sp.get() == top_reader_sp.get());
466 }
467 
468 
469 void
470 Debugger::WriteToDefaultReader (const char *bytes, size_t bytes_len)
471 {
472     if (bytes && bytes_len)
473         m_input_reader_data.append (bytes, bytes_len);
474 
475     if (m_input_reader_data.empty())
476         return;
477 
478     while (!m_input_reader_stack.IsEmpty() && !m_input_reader_data.empty())
479     {
480         // Get the input reader from the top of the stack
481         InputReaderSP reader_sp (GetCurrentInputReader ());
482         if (!reader_sp)
483             break;
484 
485         size_t bytes_handled = reader_sp->HandleRawBytes (m_input_reader_data.c_str(),
486                                                           m_input_reader_data.size());
487         if (bytes_handled)
488         {
489             m_input_reader_data.erase (0, bytes_handled);
490         }
491         else
492         {
493             // No bytes were handled, we might not have reached our
494             // granularity, just return and wait for more data
495             break;
496         }
497     }
498 
499     // Flush out any input readers that are done.
500     while (CheckIfTopInputReaderIsDone ())
501         /* Do nothing. */;
502 
503 }
504 
505 void
506 Debugger::PushInputReader (const InputReaderSP& reader_sp)
507 {
508     if (!reader_sp)
509         return;
510 
511     // Deactivate the old top reader
512     InputReaderSP top_reader_sp (GetCurrentInputReader ());
513 
514     if (top_reader_sp)
515         top_reader_sp->Notify (eInputReaderDeactivate);
516 
517     m_input_reader_stack.Push (reader_sp);
518     reader_sp->Notify (eInputReaderActivate);
519     ActivateInputReader (reader_sp);
520 }
521 
522 bool
523 Debugger::PopInputReader (const lldb::InputReaderSP& pop_reader_sp)
524 {
525     bool result = false;
526 
527     // The reader on the stop of the stack is done, so let the next
528     // read on the stack referesh its prompt and if there is one...
529     if (!m_input_reader_stack.IsEmpty())
530     {
531         // Cannot call GetCurrentInputReader here, as that would cause an infinite loop.
532         InputReaderSP reader_sp(m_input_reader_stack.Top());
533 
534         if (!pop_reader_sp || pop_reader_sp.get() == reader_sp.get())
535         {
536             m_input_reader_stack.Pop ();
537             reader_sp->Notify (eInputReaderDeactivate);
538             reader_sp->Notify (eInputReaderDone);
539             result = true;
540 
541             if (!m_input_reader_stack.IsEmpty())
542             {
543                 reader_sp = m_input_reader_stack.Top();
544                 if (reader_sp)
545                 {
546                     ActivateInputReader (reader_sp);
547                     reader_sp->Notify (eInputReaderReactivate);
548                 }
549             }
550         }
551     }
552     return result;
553 }
554 
555 bool
556 Debugger::CheckIfTopInputReaderIsDone ()
557 {
558     bool result = false;
559     if (!m_input_reader_stack.IsEmpty())
560     {
561         // Cannot call GetCurrentInputReader here, as that would cause an infinite loop.
562         InputReaderSP reader_sp(m_input_reader_stack.Top());
563 
564         if (reader_sp && reader_sp->IsDone())
565         {
566             result = true;
567             PopInputReader (reader_sp);
568         }
569     }
570     return result;
571 }
572 
573 void
574 Debugger::ActivateInputReader (const InputReaderSP &reader_sp)
575 {
576     int input_fd = m_input_file.GetFile().GetDescriptor();
577 
578     if (input_fd >= 0)
579     {
580         Terminal tty(input_fd);
581 
582         tty.SetEcho(reader_sp->GetEcho());
583 
584         switch (reader_sp->GetGranularity())
585         {
586         case eInputReaderGranularityByte:
587         case eInputReaderGranularityWord:
588             tty.SetCanonical (false);
589             break;
590 
591         case eInputReaderGranularityLine:
592         case eInputReaderGranularityAll:
593             tty.SetCanonical (true);
594             break;
595 
596         default:
597             break;
598         }
599     }
600 }
601 
602 StreamSP
603 Debugger::GetAsyncOutputStream ()
604 {
605     return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
606                                                CommandInterpreter::eBroadcastBitAsynchronousOutputData));
607 }
608 
609 StreamSP
610 Debugger::GetAsyncErrorStream ()
611 {
612     return StreamSP (new StreamAsynchronousIO (GetCommandInterpreter(),
613                                                CommandInterpreter::eBroadcastBitAsynchronousErrorData));
614 }
615 
616 DebuggerSP
617 Debugger::FindDebuggerWithID (lldb::user_id_t id)
618 {
619     lldb::DebuggerSP debugger_sp;
620 
621     Mutex::Locker locker (GetDebuggerListMutex ());
622     DebuggerList &debugger_list = GetDebuggerList();
623     DebuggerList::iterator pos, end = debugger_list.end();
624     for (pos = debugger_list.begin(); pos != end; ++pos)
625     {
626         if ((*pos).get()->GetID() == id)
627         {
628             debugger_sp = *pos;
629             break;
630         }
631     }
632     return debugger_sp;
633 }
634 
635 static void
636 TestPromptFormats (StackFrame *frame)
637 {
638     if (frame == NULL)
639         return;
640 
641     StreamString s;
642     const char *prompt_format =
643     "{addr = '${addr}'\n}"
644     "{process.id = '${process.id}'\n}"
645     "{process.name = '${process.name}'\n}"
646     "{process.file.basename = '${process.file.basename}'\n}"
647     "{process.file.fullpath = '${process.file.fullpath}'\n}"
648     "{thread.id = '${thread.id}'\n}"
649     "{thread.index = '${thread.index}'\n}"
650     "{thread.name = '${thread.name}'\n}"
651     "{thread.queue = '${thread.queue}'\n}"
652     "{thread.stop-reason = '${thread.stop-reason}'\n}"
653     "{target.arch = '${target.arch}'\n}"
654     "{module.file.basename = '${module.file.basename}'\n}"
655     "{module.file.fullpath = '${module.file.fullpath}'\n}"
656     "{file.basename = '${file.basename}'\n}"
657     "{file.fullpath = '${file.fullpath}'\n}"
658     "{frame.index = '${frame.index}'\n}"
659     "{frame.pc = '${frame.pc}'\n}"
660     "{frame.sp = '${frame.sp}'\n}"
661     "{frame.fp = '${frame.fp}'\n}"
662     "{frame.flags = '${frame.flags}'\n}"
663     "{frame.reg.rdi = '${frame.reg.rdi}'\n}"
664     "{frame.reg.rip = '${frame.reg.rip}'\n}"
665     "{frame.reg.rsp = '${frame.reg.rsp}'\n}"
666     "{frame.reg.rbp = '${frame.reg.rbp}'\n}"
667     "{frame.reg.rflags = '${frame.reg.rflags}'\n}"
668     "{frame.reg.xmm0 = '${frame.reg.xmm0}'\n}"
669     "{frame.reg.carp = '${frame.reg.carp}'\n}"
670     "{function.id = '${function.id}'\n}"
671     "{function.name = '${function.name}'\n}"
672     "{function.addr-offset = '${function.addr-offset}'\n}"
673     "{function.line-offset = '${function.line-offset}'\n}"
674     "{function.pc-offset = '${function.pc-offset}'\n}"
675     "{line.file.basename = '${line.file.basename}'\n}"
676     "{line.file.fullpath = '${line.file.fullpath}'\n}"
677     "{line.number = '${line.number}'\n}"
678     "{line.start-addr = '${line.start-addr}'\n}"
679     "{line.end-addr = '${line.end-addr}'\n}"
680 ;
681 
682     SymbolContext sc (frame->GetSymbolContext(eSymbolContextEverything));
683     ExecutionContext exe_ctx;
684     frame->CalculateExecutionContext(exe_ctx);
685     const char *end = NULL;
686     if (Debugger::FormatPrompt (prompt_format, &sc, &exe_ctx, &sc.line_entry.range.GetBaseAddress(), s, &end))
687     {
688         printf("%s\n", s.GetData());
689     }
690     else
691     {
692         printf ("error: at '%s'\n", end);
693         printf ("what we got: %s\n", s.GetData());
694     }
695 }
696 
697 #define IFERROR_PRINT_IT if (error.Fail()) \
698 { \
699     if (log) \
700         log->Printf("ERROR: %s\n", error.AsCString("unknown")); \
701     break; \
702 }
703 
704 static bool
705 ScanFormatDescriptor(const char* var_name_begin,
706                      const char* var_name_end,
707                      const char** var_name_final,
708                      const char** percent_position,
709                      lldb::Format* custom_format,
710                      ValueObject::ValueObjectRepresentationStyle* val_obj_display)
711 {
712     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
713     *percent_position = ::strchr(var_name_begin,'%');
714     if (!*percent_position || *percent_position > var_name_end)
715     {
716         if (log)
717             log->Printf("no format descriptor in string, skipping");
718         *var_name_final = var_name_end;
719     }
720     else
721     {
722         *var_name_final = *percent_position;
723         char* format_name = new char[var_name_end-*var_name_final]; format_name[var_name_end-*var_name_final-1] = '\0';
724         memcpy(format_name, *var_name_final+1, var_name_end-*var_name_final-1);
725         if (log)
726             log->Printf("parsing %s as a format descriptor", format_name);
727         if ( !FormatManager::GetFormatFromCString(format_name,
728                                                   true,
729                                                   *custom_format) )
730         {
731             if (log)
732                 log->Printf("%s is an unknown format", format_name);
733             // if this is an @ sign, print ObjC description
734             if (*format_name == '@')
735                 *val_obj_display = ValueObject::eDisplayLanguageSpecific;
736             // if this is a V, print the value using the default format
737             else if (*format_name == 'V')
738                 *val_obj_display = ValueObject::eDisplayValue;
739             // if this is an L, print the location of the value
740             else if (*format_name == 'L')
741                 *val_obj_display = ValueObject::eDisplayLocation;
742             // if this is an S, print the summary after all
743             else if (*format_name == 'S')
744                 *val_obj_display = ValueObject::eDisplaySummary;
745             else if (*format_name == '#')
746                 *val_obj_display = ValueObject::eDisplayChildrenCount;
747             else if (log)
748                 log->Printf("%s is an error, leaving the previous value alone", format_name);
749         }
750         // a good custom format tells us to print the value using it
751         else
752         {
753             if (log)
754                 log->Printf("will display value for this VO");
755             *val_obj_display = ValueObject::eDisplayValue;
756         }
757         delete format_name;
758     }
759     if (log)
760         log->Printf("final format description outcome: custom_format = %d, val_obj_display = %d",
761                     *custom_format,
762                     *val_obj_display);
763     return true;
764 }
765 
766 static bool
767 ScanBracketedRange(const char* var_name_begin,
768                    const char* var_name_end,
769                    const char* var_name_final,
770                    const char** open_bracket_position,
771                    const char** separator_position,
772                    const char** close_bracket_position,
773                    const char** var_name_final_if_array_range,
774                    int64_t* index_lower,
775                    int64_t* index_higher)
776 {
777     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
778     *open_bracket_position = ::strchr(var_name_begin,'[');
779     if (*open_bracket_position && *open_bracket_position < var_name_final)
780     {
781         *separator_position = ::strchr(*open_bracket_position,'-'); // might be NULL if this is a simple var[N] bitfield
782         *close_bracket_position = ::strchr(*open_bracket_position,']');
783         // as usual, we assume that [] will come before %
784         //printf("trying to expand a []\n");
785         *var_name_final_if_array_range = *open_bracket_position;
786         if (*close_bracket_position - *open_bracket_position == 1)
787         {
788             if (log)
789                 log->Printf("[] detected.. going from 0 to end of data");
790             *index_lower = 0;
791         }
792         else if (*separator_position == NULL || *separator_position > var_name_end)
793         {
794             char *end = NULL;
795             *index_lower = ::strtoul (*open_bracket_position+1, &end, 0);
796             *index_higher = *index_lower;
797             if (log)
798                 log->Printf("[%d] detected, high index is same", *index_lower);
799         }
800         else if (*close_bracket_position && *close_bracket_position < var_name_end)
801         {
802             char *end = NULL;
803             *index_lower = ::strtoul (*open_bracket_position+1, &end, 0);
804             *index_higher = ::strtoul (*separator_position+1, &end, 0);
805             if (log)
806                 log->Printf("[%d-%d] detected", *index_lower, *index_higher);
807         }
808         else
809         {
810             if (log)
811                 log->Printf("expression is erroneous, cannot extract indices out of it");
812             return false;
813         }
814         if (*index_lower > *index_higher && *index_higher > 0)
815         {
816             if (log)
817                 log->Printf("swapping indices");
818             int temp = *index_lower;
819             *index_lower = *index_higher;
820             *index_higher = temp;
821         }
822     }
823     else if (log)
824             log->Printf("no bracketed range, skipping entirely");
825     return true;
826 }
827 
828 
829 static ValueObjectSP
830 ExpandExpressionPath(ValueObject* vobj,
831                      StackFrame* frame,
832                      bool* do_deref_pointer,
833                      const char* var_name_begin,
834                      const char* var_name_final,
835                      Error& error)
836 {
837     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
838     StreamString sstring;
839     VariableSP var_sp;
840 
841     if (*do_deref_pointer)
842     {
843         if (log)
844             log->Printf("been told to deref_pointer by caller");
845         sstring.PutChar('*');
846     }
847     else if (vobj->IsDereferenceOfParent() && ClangASTContext::IsPointerType(vobj->GetParent()->GetClangType()) && !vobj->IsArrayItemForPointer())
848     {
849         if (log)
850             log->Printf("decided to deref_pointer myself");
851         sstring.PutChar('*');
852         *do_deref_pointer = true;
853     }
854 
855     vobj->GetExpressionPath(sstring, true, ValueObject::eHonorPointers);
856     if (log)
857         log->Printf("expression path to expand in phase 0: %s",sstring.GetData());
858     sstring.PutRawBytes(var_name_begin+3, var_name_final-var_name_begin-3);
859     if (log)
860         log->Printf("expression path to expand in phase 1: %s",sstring.GetData());
861     std::string name = std::string(sstring.GetData());
862     ValueObjectSP target = frame->GetValueForVariableExpressionPath (name.c_str(),
863                                                                      eNoDynamicValues,
864                                                                      0,
865                                                                      var_sp,
866                                                                      error);
867     return target;
868 }
869 
870 static ValueObjectSP
871 ExpandIndexedExpression(ValueObject* vobj,
872                         uint32_t index,
873                         StackFrame* frame,
874                         bool deref_pointer)
875 {
876     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
877     const char* ptr_deref_format = "[%d]";
878     std::auto_ptr<char> ptr_deref_buffer(new char[10]);
879     ::sprintf(ptr_deref_buffer.get(), ptr_deref_format, index);
880     if (log)
881         log->Printf("name to deref: %s",ptr_deref_buffer.get());
882     const char* first_unparsed;
883     ValueObject::GetValueForExpressionPathOptions options;
884     ValueObject::ExpressionPathEndResultType final_value_type;
885     ValueObject::ExpressionPathScanEndReason reason_to_stop;
886     ValueObject::ExpressionPathAftermath what_next = (deref_pointer ? ValueObject::eDereference : ValueObject::eNothing);
887     ValueObjectSP item = vobj->GetValueForExpressionPath (ptr_deref_buffer.get(),
888                                                           &first_unparsed,
889                                                           &reason_to_stop,
890                                                           &final_value_type,
891                                                           options,
892                                                           &what_next);
893     if (!item)
894     {
895         if (log)
896             log->Printf("ERROR: unparsed portion = %s, why stopping = %d,"
897                " final_value_type %d",
898                first_unparsed, reason_to_stop, final_value_type);
899     }
900     else
901     {
902         if (log)
903             log->Printf("ALL RIGHT: unparsed portion = %s, why stopping = %d,"
904                " final_value_type %d",
905                first_unparsed, reason_to_stop, final_value_type);
906     }
907     return item;
908 }
909 
910 bool
911 Debugger::FormatPrompt
912 (
913     const char *format,
914     const SymbolContext *sc,
915     const ExecutionContext *exe_ctx,
916     const Address *addr,
917     Stream &s,
918     const char **end,
919     ValueObject* vobj
920 )
921 {
922     ValueObject* realvobj = NULL; // makes it super-easy to parse pointers
923     bool success = true;
924     const char *p;
925     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
926     for (p = format; *p != '\0'; ++p)
927     {
928         if (realvobj)
929         {
930             vobj = realvobj;
931             realvobj = NULL;
932         }
933         size_t non_special_chars = ::strcspn (p, "${}\\");
934         if (non_special_chars > 0)
935         {
936             if (success)
937                 s.Write (p, non_special_chars);
938             p += non_special_chars;
939         }
940 
941         if (*p == '\0')
942         {
943             break;
944         }
945         else if (*p == '{')
946         {
947             // Start a new scope that must have everything it needs if it is to
948             // to make it into the final output stream "s". If you want to make
949             // a format that only prints out the function or symbol name if there
950             // is one in the symbol context you can use:
951             //      "{function =${function.name}}"
952             // The first '{' starts a new scope that end with the matching '}' at
953             // the end of the string. The contents "function =${function.name}"
954             // will then be evaluated and only be output if there is a function
955             // or symbol with a valid name.
956             StreamString sub_strm;
957 
958             ++p;  // Skip the '{'
959 
960             if (FormatPrompt (p, sc, exe_ctx, addr, sub_strm, &p, vobj))
961             {
962                 // The stream had all it needed
963                 s.Write(sub_strm.GetData(), sub_strm.GetSize());
964             }
965             if (*p != '}')
966             {
967                 success = false;
968                 break;
969             }
970         }
971         else if (*p == '}')
972         {
973             // End of a enclosing scope
974             break;
975         }
976         else if (*p == '$')
977         {
978             // We have a prompt variable to print
979             ++p;
980             if (*p == '{')
981             {
982                 ++p;
983                 const char *var_name_begin = p;
984                 const char *var_name_end = ::strchr (p, '}');
985 
986                 if (var_name_end && var_name_begin < var_name_end)
987                 {
988                     // if we have already failed to parse, skip this variable
989                     if (success)
990                     {
991                         const char *cstr = NULL;
992                         Address format_addr;
993                         bool calculate_format_addr_function_offset = false;
994                         // Set reg_kind and reg_num to invalid values
995                         RegisterKind reg_kind = kNumRegisterKinds;
996                         uint32_t reg_num = LLDB_INVALID_REGNUM;
997                         FileSpec format_file_spec;
998                         const RegisterInfo *reg_info = NULL;
999                         RegisterContext *reg_ctx = NULL;
1000                         bool do_deref_pointer = false;
1001                         ValueObject::ExpressionPathScanEndReason reason_to_stop = ValueObject::eEndOfString;
1002                         ValueObject::ExpressionPathEndResultType final_value_type = ValueObject::ePlain;
1003 
1004                         // Each variable must set success to true below...
1005                         bool var_success = false;
1006                         switch (var_name_begin[0])
1007                         {
1008                         case '*':
1009                         case 'v':
1010                         case 's':
1011                             {
1012                                 if (!vobj)
1013                                     break;
1014 
1015                                 if (log)
1016                                     log->Printf("initial string: %s",var_name_begin);
1017 
1018                                 // check for *var and *svar
1019                                 if (*var_name_begin == '*')
1020                                 {
1021                                     do_deref_pointer = true;
1022                                     var_name_begin++;
1023                                 }
1024 
1025                                 if (log)
1026                                     log->Printf("initial string: %s",var_name_begin);
1027 
1028                                 if (*var_name_begin == 's')
1029                                 {
1030                                     vobj = vobj->GetSyntheticValue(lldb::eUseSyntheticFilter).get();
1031                                     var_name_begin++;
1032                                 }
1033 
1034                                 if (log)
1035                                     log->Printf("initial string: %s",var_name_begin);
1036 
1037                                 // should be a 'v' by now
1038                                 if (*var_name_begin != 'v')
1039                                     break;
1040 
1041                                 if (log)
1042                                     log->Printf("initial string: %s",var_name_begin);
1043 
1044                                 ValueObject::ExpressionPathAftermath what_next = (do_deref_pointer ?
1045                                                                                   ValueObject::eDereference : ValueObject::eNothing);
1046                                 ValueObject::GetValueForExpressionPathOptions options;
1047                                 options.DontCheckDotVsArrowSyntax().DoAllowBitfieldSyntax().DoAllowFragileIVar().DoAllowSyntheticChildren();
1048                                 ValueObject::ValueObjectRepresentationStyle val_obj_display = ValueObject::eDisplaySummary;
1049                                 ValueObject* target = NULL;
1050                                 lldb::Format custom_format = eFormatInvalid;
1051                                 const char* var_name_final = NULL;
1052                                 const char* var_name_final_if_array_range = NULL;
1053                                 const char* close_bracket_position = NULL;
1054                                 int64_t index_lower = -1;
1055                                 int64_t index_higher = -1;
1056                                 bool is_array_range = false;
1057                                 const char* first_unparsed;
1058 
1059                                 if (!vobj) break;
1060                                 // simplest case ${var}, just print vobj's value
1061                                 if (::strncmp (var_name_begin, "var}", strlen("var}")) == 0)
1062                                 {
1063                                     target = vobj;
1064                                     val_obj_display = ValueObject::eDisplayValue;
1065                                 }
1066                                 else if (::strncmp(var_name_begin,"var%",strlen("var%")) == 0)
1067                                 {
1068                                     // this is a variable with some custom format applied to it
1069                                     const char* percent_position;
1070                                     target = vobj;
1071                                     val_obj_display = ValueObject::eDisplayValue;
1072                                     ScanFormatDescriptor (var_name_begin,
1073                                                           var_name_end,
1074                                                           &var_name_final,
1075                                                           &percent_position,
1076                                                           &custom_format,
1077                                                           &val_obj_display);
1078                                 }
1079                                     // this is ${var.something} or multiple .something nested
1080                                 else if (::strncmp (var_name_begin, "var", strlen("var")) == 0)
1081                                 {
1082 
1083                                     const char* percent_position;
1084                                     ScanFormatDescriptor (var_name_begin,
1085                                                           var_name_end,
1086                                                           &var_name_final,
1087                                                           &percent_position,
1088                                                           &custom_format,
1089                                                           &val_obj_display);
1090 
1091                                     const char* open_bracket_position;
1092                                     const char* separator_position;
1093                                     ScanBracketedRange (var_name_begin,
1094                                                         var_name_end,
1095                                                         var_name_final,
1096                                                         &open_bracket_position,
1097                                                         &separator_position,
1098                                                         &close_bracket_position,
1099                                                         &var_name_final_if_array_range,
1100                                                         &index_lower,
1101                                                         &index_higher);
1102 
1103                                     Error error;
1104 
1105                                     std::auto_ptr<char> expr_path(new char[var_name_final-var_name_begin-1]);
1106                                     ::memset(expr_path.get(), 0, var_name_final-var_name_begin-1);
1107                                     memcpy(expr_path.get(), var_name_begin+3,var_name_final-var_name_begin-3);
1108 
1109                                     if (log)
1110                                         log->Printf("symbol to expand: %s",expr_path.get());
1111 
1112                                     target = vobj->GetValueForExpressionPath(expr_path.get(),
1113                                                                              &first_unparsed,
1114                                                                              &reason_to_stop,
1115                                                                              &final_value_type,
1116                                                                              options,
1117                                                                              &what_next).get();
1118 
1119                                     if (!target)
1120                                     {
1121                                         if (log)
1122                                             log->Printf("ERROR: unparsed portion = %s, why stopping = %d,"
1123                                                " final_value_type %d",
1124                                                first_unparsed, reason_to_stop, final_value_type);
1125                                         break;
1126                                     }
1127                                     else
1128                                     {
1129                                         if (log)
1130                                             log->Printf("ALL RIGHT: unparsed portion = %s, why stopping = %d,"
1131                                                " final_value_type %d",
1132                                                first_unparsed, reason_to_stop, final_value_type);
1133                                     }
1134                                 }
1135                                 else
1136                                     break;
1137 
1138                                 is_array_range = (final_value_type == ValueObject::eBoundedRange ||
1139                                                   final_value_type == ValueObject::eUnboundedRange);
1140 
1141                                 do_deref_pointer = (what_next == ValueObject::eDereference);
1142 
1143                                 if (do_deref_pointer && !is_array_range)
1144                                 {
1145                                     // I have not deref-ed yet, let's do it
1146                                     // this happens when we are not going through GetValueForVariableExpressionPath
1147                                     // to get to the target ValueObject
1148                                     Error error;
1149                                     target = target->Dereference(error).get();
1150                                     IFERROR_PRINT_IT
1151                                     do_deref_pointer = false;
1152                                 }
1153 
1154                                 bool is_array = ClangASTContext::IsArrayType(target->GetClangType());
1155                                 bool is_pointer = ClangASTContext::IsPointerType(target->GetClangType());
1156 
1157                                 if ((is_array || is_pointer) && (!is_array_range) && val_obj_display == ValueObject::eDisplayValue) // this should be wrong, but there are some exceptions
1158                                 {
1159                                     if (log)
1160                                         log->Printf("I am into array || pointer && !range");
1161                                     // try to use the special cases
1162                                     var_success = target->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1163                                     if (!var_success)
1164                                         s << "<invalid, please use [] operator>";
1165                                     if (log)
1166                                         log->Printf("special cases did%s match", var_success ? "" : "n't");
1167                                     break;
1168                                 }
1169 
1170                                 if (!is_array_range)
1171                                 {
1172                                     if (log)
1173                                         log->Printf("dumping ordinary printable output");
1174                                     var_success = target->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1175                                 }
1176                                 else
1177                                 {
1178                                     if (log)
1179                                         log->Printf("checking if I can handle as array");
1180                                     if (!is_array && !is_pointer)
1181                                         break;
1182                                     if (log)
1183                                         log->Printf("handle as array");
1184                                     const char* special_directions = NULL;
1185                                     StreamString special_directions_writer;
1186                                     if (close_bracket_position && (var_name_end-close_bracket_position > 1))
1187                                     {
1188                                         ConstString additional_data;
1189                                         additional_data.SetCStringWithLength(close_bracket_position+1, var_name_end-close_bracket_position-1);
1190                                         special_directions_writer.Printf("${%svar%s}",
1191                                                                          do_deref_pointer ? "*" : "",
1192                                                                          additional_data.GetCString());
1193                                         special_directions = special_directions_writer.GetData();
1194                                     }
1195 
1196                                     // let us display items index_lower thru index_higher of this array
1197                                     s.PutChar('[');
1198                                     var_success = true;
1199 
1200                                     if (index_higher < 0)
1201                                         index_higher = vobj->GetNumChildren() - 1;
1202 
1203                                     uint32_t max_num_children = target->GetUpdatePoint().GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();
1204 
1205                                     for (;index_lower<=index_higher;index_lower++)
1206                                     {
1207                                         ValueObject* item = ExpandIndexedExpression(target,
1208                                                                                     index_lower,
1209                                                                                     exe_ctx->frame,
1210                                                                                     false).get();
1211 
1212                                         if (!item)
1213                                         {
1214                                             if (log)
1215                                                 log->Printf("ERROR in getting child item at index %d", index_lower);
1216                                         }
1217                                         else
1218                                         {
1219                                             if (log)
1220                                                 log->Printf("special_directions for child item: %s",special_directions);
1221                                         }
1222 
1223                                         if (!special_directions)
1224                                             var_success &= item->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1225                                         else
1226                                             var_success &= FormatPrompt(special_directions, sc, exe_ctx, addr, s, NULL, item);
1227 
1228                                         if (--max_num_children == 0)
1229                                         {
1230                                             s.PutCString(", ...");
1231                                             break;
1232                                         }
1233 
1234                                         if (index_lower < index_higher)
1235                                             s.PutChar(',');
1236                                     }
1237                                     s.PutChar(']');
1238                                 }
1239                             }
1240                             break;
1241                         case 'a':
1242                             if (::strncmp (var_name_begin, "addr}", strlen("addr}")) == 0)
1243                             {
1244                                 if (addr && addr->IsValid())
1245                                 {
1246                                     var_success = true;
1247                                     format_addr = *addr;
1248                                 }
1249                             }
1250                             break;
1251 
1252                         case 'p':
1253                             if (::strncmp (var_name_begin, "process.", strlen("process.")) == 0)
1254                             {
1255                                 if (exe_ctx && exe_ctx->process != NULL)
1256                                 {
1257                                     var_name_begin += ::strlen ("process.");
1258                                     if (::strncmp (var_name_begin, "id}", strlen("id}")) == 0)
1259                                     {
1260                                         s.Printf("%i", exe_ctx->process->GetID());
1261                                         var_success = true;
1262                                     }
1263                                     else if ((::strncmp (var_name_begin, "name}", strlen("name}")) == 0) ||
1264                                              (::strncmp (var_name_begin, "file.basename}", strlen("file.basename}")) == 0) ||
1265                                              (::strncmp (var_name_begin, "file.fullpath}", strlen("file.fullpath}")) == 0))
1266                                     {
1267                                         Module *exe_module = exe_ctx->process->GetTarget().GetExecutableModulePointer();
1268                                         if (exe_module)
1269                                         {
1270                                             if (var_name_begin[0] == 'n' || var_name_begin[5] == 'f')
1271                                             {
1272                                                 format_file_spec.GetFilename() = exe_module->GetFileSpec().GetFilename();
1273                                                 var_success = format_file_spec;
1274                                             }
1275                                             else
1276                                             {
1277                                                 format_file_spec = exe_module->GetFileSpec();
1278                                                 var_success = format_file_spec;
1279                                             }
1280                                         }
1281                                     }
1282                                 }
1283                             }
1284                             break;
1285 
1286                         case 't':
1287                             if (::strncmp (var_name_begin, "thread.", strlen("thread.")) == 0)
1288                             {
1289                                 if (exe_ctx && exe_ctx->thread)
1290                                 {
1291                                     var_name_begin += ::strlen ("thread.");
1292                                     if (::strncmp (var_name_begin, "id}", strlen("id}")) == 0)
1293                                     {
1294                                         s.Printf("0x%4.4x", exe_ctx->thread->GetID());
1295                                         var_success = true;
1296                                     }
1297                                     else if (::strncmp (var_name_begin, "index}", strlen("index}")) == 0)
1298                                     {
1299                                         s.Printf("%u", exe_ctx->thread->GetIndexID());
1300                                         var_success = true;
1301                                     }
1302                                     else if (::strncmp (var_name_begin, "name}", strlen("name}")) == 0)
1303                                     {
1304                                         cstr = exe_ctx->thread->GetName();
1305                                         var_success = cstr && cstr[0];
1306                                         if (var_success)
1307                                             s.PutCString(cstr);
1308                                     }
1309                                     else if (::strncmp (var_name_begin, "queue}", strlen("queue}")) == 0)
1310                                     {
1311                                         cstr = exe_ctx->thread->GetQueueName();
1312                                         var_success = cstr && cstr[0];
1313                                         if (var_success)
1314                                             s.PutCString(cstr);
1315                                     }
1316                                     else if (::strncmp (var_name_begin, "stop-reason}", strlen("stop-reason}")) == 0)
1317                                     {
1318                                         StopInfoSP stop_info_sp = exe_ctx->thread->GetStopInfo ();
1319                                         if (stop_info_sp)
1320                                         {
1321                                             cstr = stop_info_sp->GetDescription();
1322                                             if (cstr && cstr[0])
1323                                             {
1324                                                 s.PutCString(cstr);
1325                                                 var_success = true;
1326                                             }
1327                                         }
1328                                     }
1329                                 }
1330                             }
1331                             else if (::strncmp (var_name_begin, "target.", strlen("target.")) == 0)
1332                             {
1333                                 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
1334                                 if (target)
1335                                 {
1336                                     var_name_begin += ::strlen ("target.");
1337                                     if (::strncmp (var_name_begin, "arch}", strlen("arch}")) == 0)
1338                                     {
1339                                         ArchSpec arch (target->GetArchitecture ());
1340                                         if (arch.IsValid())
1341                                         {
1342                                             s.PutCString (arch.GetArchitectureName());
1343                                             var_success = true;
1344                                         }
1345                                     }
1346                                 }
1347                             }
1348                             break;
1349 
1350 
1351                         case 'm':
1352                             if (::strncmp (var_name_begin, "module.", strlen("module.")) == 0)
1353                             {
1354                                 if (sc && sc->module_sp.get())
1355                                 {
1356                                     Module *module = sc->module_sp.get();
1357                                     var_name_begin += ::strlen ("module.");
1358 
1359                                     if (::strncmp (var_name_begin, "file.", strlen("file.")) == 0)
1360                                     {
1361                                         if (module->GetFileSpec())
1362                                         {
1363                                             var_name_begin += ::strlen ("file.");
1364 
1365                                             if (::strncmp (var_name_begin, "basename}", strlen("basename}")) == 0)
1366                                             {
1367                                                 format_file_spec.GetFilename() = module->GetFileSpec().GetFilename();
1368                                                 var_success = format_file_spec;
1369                                             }
1370                                             else if (::strncmp (var_name_begin, "fullpath}", strlen("fullpath}")) == 0)
1371                                             {
1372                                                 format_file_spec = module->GetFileSpec();
1373                                                 var_success = format_file_spec;
1374                                             }
1375                                         }
1376                                     }
1377                                 }
1378                             }
1379                             break;
1380 
1381 
1382                         case 'f':
1383                             if (::strncmp (var_name_begin, "file.", strlen("file.")) == 0)
1384                             {
1385                                 if (sc && sc->comp_unit != NULL)
1386                                 {
1387                                     var_name_begin += ::strlen ("file.");
1388 
1389                                     if (::strncmp (var_name_begin, "basename}", strlen("basename}")) == 0)
1390                                     {
1391                                         format_file_spec.GetFilename() = sc->comp_unit->GetFilename();
1392                                         var_success = format_file_spec;
1393                                     }
1394                                     else if (::strncmp (var_name_begin, "fullpath}", strlen("fullpath}")) == 0)
1395                                     {
1396                                         format_file_spec = *sc->comp_unit;
1397                                         var_success = format_file_spec;
1398                                     }
1399                                 }
1400                             }
1401                             else if (::strncmp (var_name_begin, "frame.", strlen("frame.")) == 0)
1402                             {
1403                                 if (exe_ctx && exe_ctx->frame)
1404                                 {
1405                                     var_name_begin += ::strlen ("frame.");
1406                                     if (::strncmp (var_name_begin, "index}", strlen("index}")) == 0)
1407                                     {
1408                                         s.Printf("%u", exe_ctx->frame->GetFrameIndex());
1409                                         var_success = true;
1410                                     }
1411                                     else if (::strncmp (var_name_begin, "pc}", strlen("pc}")) == 0)
1412                                     {
1413                                         reg_kind = eRegisterKindGeneric;
1414                                         reg_num = LLDB_REGNUM_GENERIC_PC;
1415                                         var_success = true;
1416                                     }
1417                                     else if (::strncmp (var_name_begin, "sp}", strlen("sp}")) == 0)
1418                                     {
1419                                         reg_kind = eRegisterKindGeneric;
1420                                         reg_num = LLDB_REGNUM_GENERIC_SP;
1421                                         var_success = true;
1422                                     }
1423                                     else if (::strncmp (var_name_begin, "fp}", strlen("fp}")) == 0)
1424                                     {
1425                                         reg_kind = eRegisterKindGeneric;
1426                                         reg_num = LLDB_REGNUM_GENERIC_FP;
1427                                         var_success = true;
1428                                     }
1429                                     else if (::strncmp (var_name_begin, "flags}", strlen("flags}")) == 0)
1430                                     {
1431                                         reg_kind = eRegisterKindGeneric;
1432                                         reg_num = LLDB_REGNUM_GENERIC_FLAGS;
1433                                         var_success = true;
1434                                     }
1435                                     else if (::strncmp (var_name_begin, "reg.", strlen ("reg.")) == 0)
1436                                     {
1437                                         reg_ctx = exe_ctx->frame->GetRegisterContext().get();
1438                                         if (reg_ctx)
1439                                         {
1440                                             var_name_begin += ::strlen ("reg.");
1441                                             if (var_name_begin < var_name_end)
1442                                             {
1443                                                 std::string reg_name (var_name_begin, var_name_end);
1444                                                 reg_info = reg_ctx->GetRegisterInfoByName (reg_name.c_str());
1445                                                 if (reg_info)
1446                                                     var_success = true;
1447                                             }
1448                                         }
1449                                     }
1450                                 }
1451                             }
1452                             else if (::strncmp (var_name_begin, "function.", strlen("function.")) == 0)
1453                             {
1454                                 if (sc && (sc->function != NULL || sc->symbol != NULL))
1455                                 {
1456                                     var_name_begin += ::strlen ("function.");
1457                                     if (::strncmp (var_name_begin, "id}", strlen("id}")) == 0)
1458                                     {
1459                                         if (sc->function)
1460                                             s.Printf("function{0x%8.8x}", sc->function->GetID());
1461                                         else
1462                                             s.Printf("symbol[%u]", sc->symbol->GetID());
1463 
1464                                         var_success = true;
1465                                     }
1466                                     else if (::strncmp (var_name_begin, "name}", strlen("name}")) == 0)
1467                                     {
1468                                         if (sc->function)
1469                                             cstr = sc->function->GetName().AsCString (NULL);
1470                                         else if (sc->symbol)
1471                                             cstr = sc->symbol->GetName().AsCString (NULL);
1472                                         if (cstr)
1473                                         {
1474                                             s.PutCString(cstr);
1475 
1476                                             if (sc->block)
1477                                             {
1478                                                 Block *inline_block = sc->block->GetContainingInlinedBlock ();
1479                                                 if (inline_block)
1480                                                 {
1481                                                     const InlineFunctionInfo *inline_info = sc->block->GetInlinedFunctionInfo();
1482                                                     if (inline_info)
1483                                                     {
1484                                                         s.PutCString(" [inlined] ");
1485                                                         inline_info->GetName().Dump(&s);
1486                                                     }
1487                                                 }
1488                                             }
1489                                             var_success = true;
1490                                         }
1491                                     }
1492                                     else if (::strncmp (var_name_begin, "addr-offset}", strlen("addr-offset}")) == 0)
1493                                     {
1494                                         var_success = addr != NULL;
1495                                         if (var_success)
1496                                         {
1497                                             format_addr = *addr;
1498                                             calculate_format_addr_function_offset = true;
1499                                         }
1500                                     }
1501                                     else if (::strncmp (var_name_begin, "line-offset}", strlen("line-offset}")) == 0)
1502                                     {
1503                                         var_success = sc->line_entry.range.GetBaseAddress().IsValid();
1504                                         if (var_success)
1505                                         {
1506                                             format_addr = sc->line_entry.range.GetBaseAddress();
1507                                             calculate_format_addr_function_offset = true;
1508                                         }
1509                                     }
1510                                     else if (::strncmp (var_name_begin, "pc-offset}", strlen("pc-offset}")) == 0)
1511                                     {
1512                                         var_success = exe_ctx->frame;
1513                                         if (var_success)
1514                                         {
1515                                             format_addr = exe_ctx->frame->GetFrameCodeAddress();
1516                                             calculate_format_addr_function_offset = true;
1517                                         }
1518                                     }
1519                                 }
1520                             }
1521                             break;
1522 
1523                         case 'l':
1524                             if (::strncmp (var_name_begin, "line.", strlen("line.")) == 0)
1525                             {
1526                                 if (sc && sc->line_entry.IsValid())
1527                                 {
1528                                     var_name_begin += ::strlen ("line.");
1529                                     if (::strncmp (var_name_begin, "file.", strlen("file.")) == 0)
1530                                     {
1531                                         var_name_begin += ::strlen ("file.");
1532 
1533                                         if (::strncmp (var_name_begin, "basename}", strlen("basename}")) == 0)
1534                                         {
1535                                             format_file_spec.GetFilename() = sc->line_entry.file.GetFilename();
1536                                             var_success = format_file_spec;
1537                                         }
1538                                         else if (::strncmp (var_name_begin, "fullpath}", strlen("fullpath}")) == 0)
1539                                         {
1540                                             format_file_spec = sc->line_entry.file;
1541                                             var_success = format_file_spec;
1542                                         }
1543                                     }
1544                                     else if (::strncmp (var_name_begin, "number}", strlen("number}")) == 0)
1545                                     {
1546                                         var_success = true;
1547                                         s.Printf("%u", sc->line_entry.line);
1548                                     }
1549                                     else if ((::strncmp (var_name_begin, "start-addr}", strlen("start-addr}")) == 0) ||
1550                                              (::strncmp (var_name_begin, "end-addr}", strlen("end-addr}")) == 0))
1551                                     {
1552                                         var_success = sc && sc->line_entry.range.GetBaseAddress().IsValid();
1553                                         if (var_success)
1554                                         {
1555                                             format_addr = sc->line_entry.range.GetBaseAddress();
1556                                             if (var_name_begin[0] == 'e')
1557                                                 format_addr.Slide (sc->line_entry.range.GetByteSize());
1558                                         }
1559                                     }
1560                                 }
1561                             }
1562                             break;
1563                         }
1564 
1565                         if (var_success)
1566                         {
1567                             // If format addr is valid, then we need to print an address
1568                             if (reg_num != LLDB_INVALID_REGNUM)
1569                             {
1570                                 // We have a register value to display...
1571                                 if (reg_num == LLDB_REGNUM_GENERIC_PC && reg_kind == eRegisterKindGeneric)
1572                                 {
1573                                     format_addr = exe_ctx->frame->GetFrameCodeAddress();
1574                                 }
1575                                 else
1576                                 {
1577                                     if (reg_ctx == NULL)
1578                                         reg_ctx = exe_ctx->frame->GetRegisterContext().get();
1579 
1580                                     if (reg_ctx)
1581                                     {
1582                                         if (reg_kind != kNumRegisterKinds)
1583                                             reg_num = reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
1584                                         reg_info = reg_ctx->GetRegisterInfoAtIndex (reg_num);
1585                                         var_success = reg_info != NULL;
1586                                     }
1587                                 }
1588                             }
1589 
1590                             if (reg_info != NULL)
1591                             {
1592                                 RegisterValue reg_value;
1593                                 var_success = reg_ctx->ReadRegister (reg_info, reg_value);
1594                                 if (var_success)
1595                                 {
1596                                     reg_value.Dump(&s, reg_info, false, false, eFormatDefault);
1597                                 }
1598                             }
1599 
1600                             if (format_file_spec)
1601                             {
1602                                 s << format_file_spec;
1603                             }
1604 
1605                             // If format addr is valid, then we need to print an address
1606                             if (format_addr.IsValid())
1607                             {
1608                                 var_success = false;
1609 
1610                                 if (calculate_format_addr_function_offset)
1611                                 {
1612                                     Address func_addr;
1613 
1614                                     if (sc)
1615                                     {
1616                                         if (sc->function)
1617                                         {
1618                                             func_addr = sc->function->GetAddressRange().GetBaseAddress();
1619                                             if (sc->block)
1620                                             {
1621                                                 // Check to make sure we aren't in an inline
1622                                                 // function. If we are, use the inline block
1623                                                 // range that contains "format_addr" since
1624                                                 // blocks can be discontiguous.
1625                                                 Block *inline_block = sc->block->GetContainingInlinedBlock ();
1626                                                 AddressRange inline_range;
1627                                                 if (inline_block && inline_block->GetRangeContainingAddress (format_addr, inline_range))
1628                                                     func_addr = inline_range.GetBaseAddress();
1629                                             }
1630                                         }
1631                                         else if (sc->symbol && sc->symbol->GetAddressRangePtr())
1632                                             func_addr = sc->symbol->GetAddressRangePtr()->GetBaseAddress();
1633                                     }
1634 
1635                                     if (func_addr.IsValid())
1636                                     {
1637                                         if (func_addr.GetSection() == format_addr.GetSection())
1638                                         {
1639                                             addr_t func_file_addr = func_addr.GetFileAddress();
1640                                             addr_t addr_file_addr = format_addr.GetFileAddress();
1641                                             if (addr_file_addr > func_file_addr)
1642                                                 s.Printf(" + %llu", addr_file_addr - func_file_addr);
1643                                             else if (addr_file_addr < func_file_addr)
1644                                                 s.Printf(" - %llu", func_file_addr - addr_file_addr);
1645                                             var_success = true;
1646                                         }
1647                                         else
1648                                         {
1649                                             Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
1650                                             if (target)
1651                                             {
1652                                                 addr_t func_load_addr = func_addr.GetLoadAddress (target);
1653                                                 addr_t addr_load_addr = format_addr.GetLoadAddress (target);
1654                                                 if (addr_load_addr > func_load_addr)
1655                                                     s.Printf(" + %llu", addr_load_addr - func_load_addr);
1656                                                 else if (addr_load_addr < func_load_addr)
1657                                                     s.Printf(" - %llu", func_load_addr - addr_load_addr);
1658                                                 var_success = true;
1659                                             }
1660                                         }
1661                                     }
1662                                 }
1663                                 else
1664                                 {
1665                                     Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
1666                                     addr_t vaddr = LLDB_INVALID_ADDRESS;
1667                                     if (exe_ctx && !target->GetSectionLoadList().IsEmpty())
1668                                         vaddr = format_addr.GetLoadAddress (target);
1669                                     if (vaddr == LLDB_INVALID_ADDRESS)
1670                                         vaddr = format_addr.GetFileAddress ();
1671 
1672                                     if (vaddr != LLDB_INVALID_ADDRESS)
1673                                     {
1674                                         int addr_width = target->GetArchitecture().GetAddressByteSize() * 2;
1675                                         if (addr_width == 0)
1676                                             addr_width = 16;
1677                                         s.Printf("0x%*.*llx", addr_width, addr_width, vaddr);
1678                                         var_success = true;
1679                                     }
1680                                 }
1681                             }
1682                         }
1683 
1684                         if (var_success == false)
1685                             success = false;
1686                     }
1687                     p = var_name_end;
1688                 }
1689                 else
1690                     break;
1691             }
1692             else
1693             {
1694                 // We got a dollar sign with no '{' after it, it must just be a dollar sign
1695                 s.PutChar(*p);
1696             }
1697         }
1698         else if (*p == '\\')
1699         {
1700             ++p; // skip the slash
1701             switch (*p)
1702             {
1703             case 'a': s.PutChar ('\a'); break;
1704             case 'b': s.PutChar ('\b'); break;
1705             case 'f': s.PutChar ('\f'); break;
1706             case 'n': s.PutChar ('\n'); break;
1707             case 'r': s.PutChar ('\r'); break;
1708             case 't': s.PutChar ('\t'); break;
1709             case 'v': s.PutChar ('\v'); break;
1710             case '\'': s.PutChar ('\''); break;
1711             case '\\': s.PutChar ('\\'); break;
1712             case '0':
1713                 // 1 to 3 octal chars
1714                 {
1715                     // Make a string that can hold onto the initial zero char,
1716                     // up to 3 octal digits, and a terminating NULL.
1717                     char oct_str[5] = { 0, 0, 0, 0, 0 };
1718 
1719                     int i;
1720                     for (i=0; (p[i] >= '0' && p[i] <= '7') && i<4; ++i)
1721                         oct_str[i] = p[i];
1722 
1723                     // We don't want to consume the last octal character since
1724                     // the main for loop will do this for us, so we advance p by
1725                     // one less than i (even if i is zero)
1726                     p += i - 1;
1727                     unsigned long octal_value = ::strtoul (oct_str, NULL, 8);
1728                     if (octal_value <= UINT8_MAX)
1729                     {
1730                         char octal_char = octal_value;
1731                         s.Write (&octal_char, 1);
1732                     }
1733                 }
1734                 break;
1735 
1736             case 'x':
1737                 // hex number in the format
1738                 if (isxdigit(p[1]))
1739                 {
1740                     ++p;    // Skip the 'x'
1741 
1742                     // Make a string that can hold onto two hex chars plus a
1743                     // NULL terminator
1744                     char hex_str[3] = { 0,0,0 };
1745                     hex_str[0] = *p;
1746                     if (isxdigit(p[1]))
1747                     {
1748                         ++p; // Skip the first of the two hex chars
1749                         hex_str[1] = *p;
1750                     }
1751 
1752                     unsigned long hex_value = strtoul (hex_str, NULL, 16);
1753                     if (hex_value <= UINT8_MAX)
1754                         s.PutChar (hex_value);
1755                 }
1756                 else
1757                 {
1758                     s.PutChar('x');
1759                 }
1760                 break;
1761 
1762             default:
1763                 // Just desensitize any other character by just printing what
1764                 // came after the '\'
1765                 s << *p;
1766                 break;
1767 
1768             }
1769 
1770         }
1771     }
1772     if (end)
1773         *end = p;
1774     return success;
1775 }
1776 
1777 
1778 static FormatManager&
1779 GetFormatManager() {
1780     static FormatManager g_format_manager;
1781     return g_format_manager;
1782 }
1783 
1784 void
1785 Debugger::Formatting::ForceUpdate()
1786 {
1787     GetFormatManager().Changed();
1788 }
1789 
1790 bool
1791 Debugger::Formatting::ValueFormats::Get(ValueObject& vobj, lldb::DynamicValueType use_dynamic, ValueFormat::SharedPointer &entry)
1792 {
1793     return GetFormatManager().Value().Get(vobj,entry, use_dynamic);
1794 }
1795 
1796 void
1797 Debugger::Formatting::ValueFormats::Add(const ConstString &type, const ValueFormat::SharedPointer &entry)
1798 {
1799     GetFormatManager().Value().Add(type.AsCString(),entry);
1800 }
1801 
1802 bool
1803 Debugger::Formatting::ValueFormats::Delete(const ConstString &type)
1804 {
1805     return GetFormatManager().Value().Delete(type.AsCString());
1806 }
1807 
1808 void
1809 Debugger::Formatting::ValueFormats::Clear()
1810 {
1811     GetFormatManager().Value().Clear();
1812 }
1813 
1814 void
1815 Debugger::Formatting::ValueFormats::LoopThrough(ValueFormat::ValueCallback callback, void* callback_baton)
1816 {
1817     GetFormatManager().Value().LoopThrough(callback, callback_baton);
1818 }
1819 
1820 uint32_t
1821 Debugger::Formatting::ValueFormats::GetCurrentRevision()
1822 {
1823     return GetFormatManager().GetCurrentRevision();
1824 }
1825 
1826 uint32_t
1827 Debugger::Formatting::ValueFormats::GetCount()
1828 {
1829     return GetFormatManager().Value().GetCount();
1830 }
1831 
1832 bool
1833 Debugger::Formatting::GetSummaryFormat(ValueObject& vobj,
1834                                        lldb::DynamicValueType use_dynamic,
1835                                        lldb::SummaryFormatSP& entry)
1836 {
1837     return GetFormatManager().Get(vobj, entry, use_dynamic);
1838 }
1839 bool
1840 Debugger::Formatting::GetSyntheticFilter(ValueObject& vobj,
1841                                          lldb::DynamicValueType use_dynamic,
1842                                          lldb::SyntheticChildrenSP& entry)
1843 {
1844     return GetFormatManager().Get(vobj, entry, use_dynamic);
1845 }
1846 
1847 bool
1848 Debugger::Formatting::Categories::Get(const ConstString &category, lldb::FormatCategorySP &entry)
1849 {
1850     entry = GetFormatManager().Category(category.GetCString());
1851     return true;
1852 }
1853 
1854 void
1855 Debugger::Formatting::Categories::Add(const ConstString &category)
1856 {
1857     GetFormatManager().Category(category.GetCString());
1858 }
1859 
1860 bool
1861 Debugger::Formatting::Categories::Delete(const ConstString &category)
1862 {
1863     GetFormatManager().DisableCategory(category.GetCString());
1864     return GetFormatManager().Categories().Delete(category.GetCString());
1865 }
1866 
1867 void
1868 Debugger::Formatting::Categories::Clear()
1869 {
1870     GetFormatManager().Categories().Clear();
1871 }
1872 
1873 void
1874 Debugger::Formatting::Categories::Clear(ConstString &category)
1875 {
1876     GetFormatManager().Category(category.GetCString())->ClearSummaries();
1877 }
1878 
1879 void
1880 Debugger::Formatting::Categories::Enable(ConstString& category)
1881 {
1882     if (GetFormatManager().Category(category.GetCString())->IsEnabled() == false)
1883         GetFormatManager().EnableCategory(category.GetCString());
1884     else
1885     {
1886         GetFormatManager().DisableCategory(category.GetCString());
1887         GetFormatManager().EnableCategory(category.GetCString());
1888     }
1889 }
1890 
1891 void
1892 Debugger::Formatting::Categories::Disable(ConstString& category)
1893 {
1894     if (GetFormatManager().Category(category.GetCString())->IsEnabled() == true)
1895         GetFormatManager().DisableCategory(category.GetCString());
1896 }
1897 
1898 void
1899 Debugger::Formatting::Categories::LoopThrough(FormatManager::CategoryCallback callback, void* callback_baton)
1900 {
1901     GetFormatManager().LoopThroughCategories(callback, callback_baton);
1902 }
1903 
1904 uint32_t
1905 Debugger::Formatting::Categories::GetCurrentRevision()
1906 {
1907     return GetFormatManager().GetCurrentRevision();
1908 }
1909 
1910 uint32_t
1911 Debugger::Formatting::Categories::GetCount()
1912 {
1913     return GetFormatManager().Categories().GetCount();
1914 }
1915 
1916 bool
1917 Debugger::Formatting::NamedSummaryFormats::Get(const ConstString &type, SummaryFormat::SharedPointer &entry)
1918 {
1919     return GetFormatManager().NamedSummary().Get(type.AsCString(),entry);
1920 }
1921 
1922 void
1923 Debugger::Formatting::NamedSummaryFormats::Add(const ConstString &type, const SummaryFormat::SharedPointer &entry)
1924 {
1925     GetFormatManager().NamedSummary().Add(type.AsCString(),entry);
1926 }
1927 
1928 bool
1929 Debugger::Formatting::NamedSummaryFormats::Delete(const ConstString &type)
1930 {
1931     return GetFormatManager().NamedSummary().Delete(type.AsCString());
1932 }
1933 
1934 void
1935 Debugger::Formatting::NamedSummaryFormats::Clear()
1936 {
1937     GetFormatManager().NamedSummary().Clear();
1938 }
1939 
1940 void
1941 Debugger::Formatting::NamedSummaryFormats::LoopThrough(SummaryFormat::SummaryCallback callback, void* callback_baton)
1942 {
1943     GetFormatManager().NamedSummary().LoopThrough(callback, callback_baton);
1944 }
1945 
1946 uint32_t
1947 Debugger::Formatting::NamedSummaryFormats::GetCurrentRevision()
1948 {
1949     return GetFormatManager().GetCurrentRevision();
1950 }
1951 
1952 uint32_t
1953 Debugger::Formatting::NamedSummaryFormats::GetCount()
1954 {
1955     return GetFormatManager().NamedSummary().GetCount();
1956 }
1957 
1958 #pragma mark Debugger::SettingsController
1959 
1960 //--------------------------------------------------
1961 // class Debugger::SettingsController
1962 //--------------------------------------------------
1963 
1964 Debugger::SettingsController::SettingsController () :
1965     UserSettingsController ("", lldb::UserSettingsControllerSP())
1966 {
1967     m_default_settings.reset (new DebuggerInstanceSettings (*this, false,
1968                                                             InstanceSettings::GetDefaultName().AsCString()));
1969 }
1970 
1971 Debugger::SettingsController::~SettingsController ()
1972 {
1973 }
1974 
1975 
1976 lldb::InstanceSettingsSP
1977 Debugger::SettingsController::CreateInstanceSettings (const char *instance_name)
1978 {
1979     DebuggerInstanceSettings *new_settings = new DebuggerInstanceSettings (*GetSettingsController(),
1980                                                                            false, instance_name);
1981     lldb::InstanceSettingsSP new_settings_sp (new_settings);
1982     return new_settings_sp;
1983 }
1984 
1985 #pragma mark DebuggerInstanceSettings
1986 //--------------------------------------------------
1987 //  class DebuggerInstanceSettings
1988 //--------------------------------------------------
1989 
1990 DebuggerInstanceSettings::DebuggerInstanceSettings
1991 (
1992     UserSettingsController &owner,
1993     bool live_instance,
1994     const char *name
1995 ) :
1996     InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
1997     m_term_width (80),
1998     m_prompt (),
1999     m_frame_format (),
2000     m_thread_format (),
2001     m_script_lang (),
2002     m_use_external_editor (false),
2003     m_auto_confirm_on (false)
2004 {
2005     // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2006     // until the vtables for DebuggerInstanceSettings are properly set up, i.e. AFTER all the initializers.
2007     // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
2008     // The same is true of CreateInstanceName().
2009 
2010     if (GetInstanceName() == InstanceSettings::InvalidName())
2011     {
2012         ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2013         m_owner.RegisterInstanceSettings (this);
2014     }
2015 
2016     if (live_instance)
2017     {
2018         const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2019         CopyInstanceSettings (pending_settings, false);
2020     }
2021 }
2022 
2023 DebuggerInstanceSettings::DebuggerInstanceSettings (const DebuggerInstanceSettings &rhs) :
2024     InstanceSettings (*Debugger::GetSettingsController(), CreateInstanceName ().AsCString()),
2025     m_prompt (rhs.m_prompt),
2026     m_frame_format (rhs.m_frame_format),
2027     m_thread_format (rhs.m_thread_format),
2028     m_script_lang (rhs.m_script_lang),
2029     m_use_external_editor (rhs.m_use_external_editor),
2030     m_auto_confirm_on(rhs.m_auto_confirm_on)
2031 {
2032     const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2033     CopyInstanceSettings (pending_settings, false);
2034     m_owner.RemovePendingSettings (m_instance_name);
2035 }
2036 
2037 DebuggerInstanceSettings::~DebuggerInstanceSettings ()
2038 {
2039 }
2040 
2041 DebuggerInstanceSettings&
2042 DebuggerInstanceSettings::operator= (const DebuggerInstanceSettings &rhs)
2043 {
2044     if (this != &rhs)
2045     {
2046         m_term_width = rhs.m_term_width;
2047         m_prompt = rhs.m_prompt;
2048         m_frame_format = rhs.m_frame_format;
2049         m_thread_format = rhs.m_thread_format;
2050         m_script_lang = rhs.m_script_lang;
2051         m_use_external_editor = rhs.m_use_external_editor;
2052         m_auto_confirm_on = rhs.m_auto_confirm_on;
2053     }
2054 
2055     return *this;
2056 }
2057 
2058 bool
2059 DebuggerInstanceSettings::ValidTermWidthValue (const char *value, Error err)
2060 {
2061     bool valid = false;
2062 
2063     // Verify we have a value string.
2064     if (value == NULL || value[0] == '\0')
2065     {
2066         err.SetErrorString ("Missing value. Can't set terminal width without a value.\n");
2067     }
2068     else
2069     {
2070         char *end = NULL;
2071         const uint32_t width = ::strtoul (value, &end, 0);
2072 
2073         if (end && end[0] == '\0')
2074         {
2075             if (width >= 10 && width <= 1024)
2076                 valid = true;
2077             else
2078                 err.SetErrorString ("Invalid term-width value; value must be between 10 and 1024.\n");
2079         }
2080         else
2081             err.SetErrorStringWithFormat ("'%s' is not a valid unsigned integer string.\n", value);
2082     }
2083 
2084     return valid;
2085 }
2086 
2087 
2088 void
2089 DebuggerInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
2090                                                           const char *index_value,
2091                                                           const char *value,
2092                                                           const ConstString &instance_name,
2093                                                           const SettingEntry &entry,
2094                                                           VarSetOperationType op,
2095                                                           Error &err,
2096                                                           bool pending)
2097 {
2098 
2099     if (var_name == TermWidthVarName())
2100     {
2101         if (ValidTermWidthValue (value, err))
2102         {
2103             m_term_width = ::strtoul (value, NULL, 0);
2104         }
2105     }
2106     else if (var_name == PromptVarName())
2107     {
2108         UserSettingsController::UpdateStringVariable (op, m_prompt, value, err);
2109         if (!pending)
2110         {
2111             // 'instance_name' is actually (probably) in the form '[<instance_name>]';  if so, we need to
2112             // strip off the brackets before passing it to BroadcastPromptChange.
2113 
2114             std::string tmp_instance_name (instance_name.AsCString());
2115             if ((tmp_instance_name[0] == '[')
2116                 && (tmp_instance_name[instance_name.GetLength() - 1] == ']'))
2117                 tmp_instance_name = tmp_instance_name.substr (1, instance_name.GetLength() - 2);
2118             ConstString new_name (tmp_instance_name.c_str());
2119 
2120             BroadcastPromptChange (new_name, m_prompt.c_str());
2121         }
2122     }
2123     else if (var_name == GetFrameFormatName())
2124     {
2125         UserSettingsController::UpdateStringVariable (op, m_frame_format, value, err);
2126     }
2127     else if (var_name == GetThreadFormatName())
2128     {
2129         UserSettingsController::UpdateStringVariable (op, m_thread_format, value, err);
2130     }
2131     else if (var_name == ScriptLangVarName())
2132     {
2133         bool success;
2134         m_script_lang = Args::StringToScriptLanguage (value, eScriptLanguageDefault,
2135                                                       &success);
2136     }
2137     else if (var_name == UseExternalEditorVarName ())
2138     {
2139         UserSettingsController::UpdateBooleanVariable (op, m_use_external_editor, value, false, err);
2140     }
2141     else if (var_name == AutoConfirmName ())
2142     {
2143         UserSettingsController::UpdateBooleanVariable (op, m_auto_confirm_on, value, false, err);
2144     }
2145 }
2146 
2147 bool
2148 DebuggerInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
2149                                                     const ConstString &var_name,
2150                                                     StringList &value,
2151                                                     Error *err)
2152 {
2153     if (var_name == PromptVarName())
2154     {
2155         value.AppendString (m_prompt.c_str(), m_prompt.size());
2156 
2157     }
2158     else if (var_name == ScriptLangVarName())
2159     {
2160         value.AppendString (ScriptInterpreter::LanguageToString (m_script_lang).c_str());
2161     }
2162     else if (var_name == TermWidthVarName())
2163     {
2164         StreamString width_str;
2165         width_str.Printf ("%d", m_term_width);
2166         value.AppendString (width_str.GetData());
2167     }
2168     else if (var_name == GetFrameFormatName ())
2169     {
2170         value.AppendString(m_frame_format.c_str(), m_frame_format.size());
2171     }
2172     else if (var_name == GetThreadFormatName ())
2173     {
2174         value.AppendString(m_thread_format.c_str(), m_thread_format.size());
2175     }
2176     else if (var_name == UseExternalEditorVarName())
2177     {
2178         if (m_use_external_editor)
2179             value.AppendString ("true");
2180         else
2181             value.AppendString ("false");
2182     }
2183     else if (var_name == AutoConfirmName())
2184     {
2185         if (m_auto_confirm_on)
2186             value.AppendString ("true");
2187         else
2188             value.AppendString ("false");
2189     }
2190     else
2191     {
2192         if (err)
2193             err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
2194         return false;
2195     }
2196     return true;
2197 }
2198 
2199 void
2200 DebuggerInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
2201                                                 bool pending)
2202 {
2203     if (new_settings.get() == NULL)
2204         return;
2205 
2206     DebuggerInstanceSettings *new_debugger_settings = (DebuggerInstanceSettings *) new_settings.get();
2207 
2208     m_prompt = new_debugger_settings->m_prompt;
2209     if (!pending)
2210     {
2211         // 'instance_name' is actually (probably) in the form '[<instance_name>]';  if so, we need to
2212         // strip off the brackets before passing it to BroadcastPromptChange.
2213 
2214         std::string tmp_instance_name (m_instance_name.AsCString());
2215         if ((tmp_instance_name[0] == '[')
2216             && (tmp_instance_name[m_instance_name.GetLength() - 1] == ']'))
2217             tmp_instance_name = tmp_instance_name.substr (1, m_instance_name.GetLength() - 2);
2218         ConstString new_name (tmp_instance_name.c_str());
2219 
2220         BroadcastPromptChange (new_name, m_prompt.c_str());
2221     }
2222     m_frame_format = new_debugger_settings->m_frame_format;
2223     m_thread_format = new_debugger_settings->m_thread_format;
2224     m_term_width = new_debugger_settings->m_term_width;
2225     m_script_lang = new_debugger_settings->m_script_lang;
2226     m_use_external_editor = new_debugger_settings->m_use_external_editor;
2227     m_auto_confirm_on = new_debugger_settings->m_auto_confirm_on;
2228 }
2229 
2230 
2231 bool
2232 DebuggerInstanceSettings::BroadcastPromptChange (const ConstString &instance_name, const char *new_prompt)
2233 {
2234     std::string tmp_prompt;
2235 
2236     if (new_prompt != NULL)
2237     {
2238         tmp_prompt = new_prompt ;
2239         int len = tmp_prompt.size();
2240         if (len > 1
2241             && (tmp_prompt[0] == '\'' || tmp_prompt[0] == '"')
2242             && (tmp_prompt[len-1] == tmp_prompt[0]))
2243         {
2244             tmp_prompt = tmp_prompt.substr(1,len-2);
2245         }
2246         len = tmp_prompt.size();
2247         if (tmp_prompt[len-1] != ' ')
2248             tmp_prompt.append(" ");
2249     }
2250     EventSP new_event_sp;
2251     new_event_sp.reset (new Event(CommandInterpreter::eBroadcastBitResetPrompt,
2252                                   new EventDataBytes (tmp_prompt.c_str())));
2253 
2254     if (instance_name.GetLength() != 0)
2255     {
2256         // Set prompt for a particular instance.
2257         Debugger *dbg = Debugger::FindDebuggerWithInstanceName (instance_name).get();
2258         if (dbg != NULL)
2259         {
2260             dbg->GetCommandInterpreter().BroadcastEvent (new_event_sp);
2261         }
2262     }
2263 
2264     return true;
2265 }
2266 
2267 const ConstString
2268 DebuggerInstanceSettings::CreateInstanceName ()
2269 {
2270     static int instance_count = 1;
2271     StreamString sstr;
2272 
2273     sstr.Printf ("debugger_%d", instance_count);
2274     ++instance_count;
2275 
2276     const ConstString ret_val (sstr.GetData());
2277 
2278     return ret_val;
2279 }
2280 
2281 const ConstString &
2282 DebuggerInstanceSettings::PromptVarName ()
2283 {
2284     static ConstString prompt_var_name ("prompt");
2285 
2286     return prompt_var_name;
2287 }
2288 
2289 const ConstString &
2290 DebuggerInstanceSettings::GetFrameFormatName ()
2291 {
2292     static ConstString prompt_var_name ("frame-format");
2293 
2294     return prompt_var_name;
2295 }
2296 
2297 const ConstString &
2298 DebuggerInstanceSettings::GetThreadFormatName ()
2299 {
2300     static ConstString prompt_var_name ("thread-format");
2301 
2302     return prompt_var_name;
2303 }
2304 
2305 const ConstString &
2306 DebuggerInstanceSettings::ScriptLangVarName ()
2307 {
2308     static ConstString script_lang_var_name ("script-lang");
2309 
2310     return script_lang_var_name;
2311 }
2312 
2313 const ConstString &
2314 DebuggerInstanceSettings::TermWidthVarName ()
2315 {
2316     static ConstString term_width_var_name ("term-width");
2317 
2318     return term_width_var_name;
2319 }
2320 
2321 const ConstString &
2322 DebuggerInstanceSettings::UseExternalEditorVarName ()
2323 {
2324     static ConstString use_external_editor_var_name ("use-external-editor");
2325 
2326     return use_external_editor_var_name;
2327 }
2328 
2329 const ConstString &
2330 DebuggerInstanceSettings::AutoConfirmName ()
2331 {
2332     static ConstString use_external_editor_var_name ("auto-confirm");
2333 
2334     return use_external_editor_var_name;
2335 }
2336 
2337 //--------------------------------------------------
2338 // SettingsController Variable Tables
2339 //--------------------------------------------------
2340 
2341 
2342 SettingEntry
2343 Debugger::SettingsController::global_settings_table[] =
2344 {
2345   //{ "var-name",    var-type,      "default", enum-table, init'd, hidden, "help-text"},
2346   // The Debugger level global table should always be empty; all Debugger settable variables should be instance
2347   // variables.
2348     {  NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
2349 };
2350 
2351 #define MODULE_WITH_FUNC "{ ${module.file.basename}{`${function.name}${function.pc-offset}}}"
2352 #define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}"
2353 
2354 #define DEFAULT_THREAD_FORMAT "thread #${thread.index}: tid = ${thread.id}"\
2355     "{, ${frame.pc}}"\
2356     MODULE_WITH_FUNC\
2357     FILE_AND_LINE\
2358     "{, stop reason = ${thread.stop-reason}}"\
2359     "\\n"
2360 
2361 //#define DEFAULT_THREAD_FORMAT "thread #${thread.index}: tid = ${thread.id}"\
2362 //    "{, ${frame.pc}}"\
2363 //    MODULE_WITH_FUNC\
2364 //    FILE_AND_LINE\
2365 //    "{, stop reason = ${thread.stop-reason}}"\
2366 //    "{, name = ${thread.name}}"\
2367 //    "{, queue = ${thread.queue}}"\
2368 //    "\\n"
2369 
2370 #define DEFAULT_FRAME_FORMAT "frame #${frame.index}: ${frame.pc}"\
2371     MODULE_WITH_FUNC\
2372     FILE_AND_LINE\
2373     "\\n"
2374 
2375 SettingEntry
2376 Debugger::SettingsController::instance_settings_table[] =
2377 {
2378 //  NAME                    Setting variable type   Default                 Enum  Init'd Hidden Help
2379 //  ======================= ======================= ======================  ====  ====== ====== ======================
2380 {   "frame-format",         eSetVarTypeString,      DEFAULT_FRAME_FORMAT,   NULL, false, false, "The default frame format string to use when displaying thread information." },
2381 {   "prompt",               eSetVarTypeString,      "(lldb) ",              NULL, false, false, "The debugger command line prompt displayed for the user." },
2382 {   "script-lang",          eSetVarTypeString,      "python",               NULL, false, false, "The script language to be used for evaluating user-written scripts." },
2383 {   "term-width",           eSetVarTypeInt,         "80"    ,               NULL, false, false, "The maximum number of columns to use for displaying text." },
2384 {   "thread-format",        eSetVarTypeString,      DEFAULT_THREAD_FORMAT,  NULL, false, false, "The default thread format string to use when displaying thread information." },
2385 {   "use-external-editor",  eSetVarTypeBoolean,        "false",                NULL, false, false, "Whether to use an external editor or not." },
2386 {   "auto-confirm",         eSetVarTypeBoolean,        "false",                NULL, false, false, "If true all confirmation prompts will receive their default reply." },
2387 {   NULL,                   eSetVarTypeNone,        NULL,                   NULL, false, false, NULL }
2388 };
2389