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