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