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