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