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