]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Core/FormatEntity.cpp
Update lldb to upstream trunk r242221.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Core / FormatEntity.cpp
1 //===-- FormatEntity.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 "llvm/ADT/StringRef.h"
11
12 #include "lldb/Core/FormatEntity.h"
13
14 #include "lldb/Core/Address.h"
15 #include "lldb/Core/Debugger.h"
16 #include "lldb/Core/Language.h"
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/Stream.h"
19 #include "lldb/Core/StreamString.h"
20 #include "lldb/Core/ValueObject.h"
21 #include "lldb/Core/ValueObjectVariable.h"
22 #include "lldb/DataFormatters/DataVisualization.h"
23 #include "lldb/DataFormatters/FormatManager.h"
24 #include "lldb/Expression/ClangExpressionVariable.h"
25 #include "lldb/Host/FileSpec.h"
26 #include "lldb/Interpreter/CommandInterpreter.h"
27 #include "lldb/Symbol/Block.h"
28 #include "lldb/Symbol/CompileUnit.h"
29 #include "lldb/Symbol/Function.h"
30 #include "lldb/Symbol/LineEntry.h"
31 #include "lldb/Symbol/Symbol.h"
32 #include "lldb/Symbol/VariableList.h"
33 #include "lldb/Target/ExecutionContext.h"
34 #include "lldb/Target/Process.h"
35 #include "lldb/Target/RegisterContext.h"
36 #include "lldb/Target/SectionLoadList.h"
37 #include "lldb/Target/StackFrame.h"
38 #include "lldb/Target/StopInfo.h"
39 #include "lldb/Target/Target.h"
40 #include "lldb/Target/Thread.h"
41 #include "lldb/Utility/AnsiTerminal.h"
42
43 using namespace lldb;
44 using namespace lldb_private;
45
46
47 enum FileKind
48 {
49     FileError = 0,
50     Basename,
51     Dirname,
52     Fullpath
53 };
54
55 #define ENTRY(n,t,f)            { n, NULL, FormatEntity::Entry::Type::t, FormatEntity::Entry::FormatType::f, 0,0,NULL, false}
56 #define ENTRY_VALUE(n,t,f,v)    { n, NULL, FormatEntity::Entry::Type::t, FormatEntity::Entry::FormatType::f, v,0,NULL, false}
57 #define ENTRY_CHILDREN(n,t,f,c) { n, NULL, FormatEntity::Entry::Type::t, FormatEntity::Entry::FormatType::f, 0,llvm::array_lengthof(c),c, false}
58 #define ENTRY_CHILDREN_KEEP_SEP(n,t,f,c) { n, NULL, FormatEntity::Entry::Type::t, FormatEntity::Entry::FormatType::f, 0,llvm::array_lengthof(c),c, true}
59 #define ENTRY_STRING(n,s)       { n, s, FormatEntity::Entry::Type::InsertString, FormatEntity::Entry::FormatType::None, 0,0, NULL, false}
60 static FormatEntity::Entry::Definition g_string_entry[] =
61 {
62     ENTRY("*", ParentString, None)
63 };
64
65 static FormatEntity::Entry::Definition g_addr_entries[] =
66 {
67     ENTRY ("load", AddressLoad      , UInt64),
68     ENTRY ("file", AddressFile      , UInt64),
69     ENTRY ("load", AddressLoadOrFile, UInt64),
70 };
71
72 static FormatEntity::Entry::Definition g_file_child_entries[] =
73 {
74     ENTRY_VALUE("basename", ParentNumber, CString, FileKind::Basename),
75     ENTRY_VALUE("dirname", ParentNumber, CString, FileKind::Dirname),
76     ENTRY_VALUE("fullpath", ParentNumber, CString, FileKind::Fullpath)
77 };
78
79 static FormatEntity::Entry::Definition g_frame_child_entries[] =
80 {
81     
82     ENTRY ("index", FrameIndex        , UInt32),
83     ENTRY ("pc"   , FrameRegisterPC   , UInt64),
84     ENTRY ("fp"   , FrameRegisterFP   , UInt64),
85     ENTRY ("sp"   , FrameRegisterSP   , UInt64),
86     ENTRY ("flags", FrameRegisterFlags, UInt64),
87     ENTRY_CHILDREN ("reg", FrameRegisterByName, UInt64, g_string_entry),
88 };
89
90 static FormatEntity::Entry::Definition g_function_child_entries[] =
91 {
92     ENTRY ("id"                  , FunctionID             , UInt64),
93     ENTRY ("name"                , FunctionName           , CString),
94     ENTRY ("name-without-args"   , FunctionNameNoArgs     , CString),
95     ENTRY ("name-with-args"      , FunctionNameWithArgs   , CString),
96     ENTRY ("addr-offset"         , FunctionAddrOffset     , UInt64),
97     ENTRY ("concrete-only-addr-offset-no-padding", FunctionAddrOffsetConcrete, UInt64),
98     ENTRY ("line-offset"         , FunctionLineOffset     , UInt64),
99     ENTRY ("pc-offset"           , FunctionPCOffset       , UInt64),
100     ENTRY ("initial-function"    , FunctionInitial        , None),
101     ENTRY ("changed"             , FunctionChanged        , None)
102 };
103
104 static FormatEntity::Entry::Definition g_line_child_entries[] =
105 {
106     ENTRY_CHILDREN("file", LineEntryFile        , None  , g_file_child_entries),
107     ENTRY("number"       , LineEntryLineNumber  , UInt32),
108     ENTRY("start-addr"   , LineEntryStartAddress, UInt64),
109     ENTRY("end-addr"     , LineEntryEndAddress  , UInt64),
110 };
111
112 static FormatEntity::Entry::Definition g_module_child_entries[] =
113 {
114     ENTRY_CHILDREN("file", ModuleFile, None, g_file_child_entries),
115 };
116
117 static FormatEntity::Entry::Definition g_process_child_entries[] =
118 {
119     ENTRY           ( "id"      , ProcessID     , UInt64    ),
120     ENTRY_VALUE     ( "name"    , ProcessFile   , CString   , FileKind::Basename),
121     ENTRY_CHILDREN  ( "file"    , ProcessFile   , None      , g_file_child_entries),
122 };
123
124 static FormatEntity::Entry::Definition g_svar_child_entries[] =
125 {
126     ENTRY           ( "*"       , ParentString  , None)
127 };
128
129 static FormatEntity::Entry::Definition g_var_child_entries[] =
130 {
131     ENTRY           ( "*"       , ParentString  , None)
132 };
133
134 static FormatEntity::Entry::Definition g_thread_child_entries[] =
135 {
136     ENTRY           ( "id"                  , ThreadID                   , UInt64   ),
137     ENTRY           ( "protocol_id"         , ThreadProtocolID           , UInt64   ),
138     ENTRY           ( "index"               , ThreadIndexID              , UInt32   ),
139     ENTRY_CHILDREN  ( "info"                , ThreadInfo                 , None     , g_string_entry),
140     ENTRY           ( "queue"               , ThreadQueue                , CString  ),
141     ENTRY           ( "name"                , ThreadName                 , CString  ),
142     ENTRY           ( "stop-reason"         , ThreadStopReason           , CString  ),
143     ENTRY           ( "return-value"        , ThreadReturnValue          , CString  ),
144     ENTRY           ( "completed-expression", ThreadCompletedExpression  , CString  ),
145 };
146
147 static FormatEntity::Entry::Definition g_target_child_entries[] =
148 {
149     ENTRY           ( "arch"    , TargetArch    , CString   ),
150 };
151
152 #define _TO_STR2(_val) #_val
153 #define _TO_STR(_val) _TO_STR2(_val)
154
155 static FormatEntity::Entry::Definition g_ansi_fg_entries[] =
156 {
157     ENTRY_STRING ("black"   , ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_BLACK)      ANSI_ESC_END),
158     ENTRY_STRING ("red"     , ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_RED)        ANSI_ESC_END),
159     ENTRY_STRING ("green"   , ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_GREEN)      ANSI_ESC_END),
160     ENTRY_STRING ("yellow"  , ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_YELLOW)     ANSI_ESC_END),
161     ENTRY_STRING ("blue"    , ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_BLUE)       ANSI_ESC_END),
162     ENTRY_STRING ("purple"  , ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_PURPLE)     ANSI_ESC_END),
163     ENTRY_STRING ("cyan"    , ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_CYAN)       ANSI_ESC_END),
164     ENTRY_STRING ("white"   , ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_WHITE)      ANSI_ESC_END),
165 };
166
167 static FormatEntity::Entry::Definition g_ansi_bg_entries[] =
168 {
169     ENTRY_STRING ("black"   , ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_BLACK)      ANSI_ESC_END),
170     ENTRY_STRING ("red"     , ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_RED)        ANSI_ESC_END),
171     ENTRY_STRING ("green"   , ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_GREEN)      ANSI_ESC_END),
172     ENTRY_STRING ("yellow"  , ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_YELLOW)     ANSI_ESC_END),
173     ENTRY_STRING ("blue"    , ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_BLUE)       ANSI_ESC_END),
174     ENTRY_STRING ("purple"  , ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_PURPLE)     ANSI_ESC_END),
175     ENTRY_STRING ("cyan"    , ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_CYAN)       ANSI_ESC_END),
176     ENTRY_STRING ("white"   , ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_WHITE)      ANSI_ESC_END),
177 };
178
179 static FormatEntity::Entry::Definition g_ansi_entries[] =
180 {
181     ENTRY_CHILDREN  ( "fg"          , Invalid  , None      , g_ansi_fg_entries),
182     ENTRY_CHILDREN  ( "bg"          , Invalid  , None      , g_ansi_bg_entries),
183     ENTRY_STRING    ( "normal"      , ANSI_ESC_START _TO_STR(ANSI_CTRL_NORMAL)         ANSI_ESC_END),
184     ENTRY_STRING    ( "bold"        , ANSI_ESC_START _TO_STR(ANSI_CTRL_BOLD)           ANSI_ESC_END),
185     ENTRY_STRING    ( "faint"       , ANSI_ESC_START _TO_STR(ANSI_CTRL_FAINT)          ANSI_ESC_END),
186     ENTRY_STRING    ( "italic"      , ANSI_ESC_START _TO_STR(ANSI_CTRL_ITALIC)         ANSI_ESC_END),
187     ENTRY_STRING    ( "underline"   , ANSI_ESC_START _TO_STR(ANSI_CTRL_UNDERLINE)      ANSI_ESC_END),
188     ENTRY_STRING    ( "slow-blink"  , ANSI_ESC_START _TO_STR(ANSI_CTRL_SLOW_BLINK)     ANSI_ESC_END),
189     ENTRY_STRING    ( "fast-blink"  , ANSI_ESC_START _TO_STR(ANSI_CTRL_FAST_BLINK)     ANSI_ESC_END),
190     ENTRY_STRING    ( "negative"    , ANSI_ESC_START _TO_STR(ANSI_CTRL_IMAGE_NEGATIVE) ANSI_ESC_END),
191     ENTRY_STRING    ( "conceal"     , ANSI_ESC_START _TO_STR(ANSI_CTRL_CONCEAL)        ANSI_ESC_END),
192     ENTRY_STRING    ( "crossed-out" , ANSI_ESC_START _TO_STR(ANSI_CTRL_CROSSED_OUT)    ANSI_ESC_END),
193
194 };
195
196 static FormatEntity::Entry::Definition g_script_child_entries[] =
197 {
198     ENTRY  ( "frame"   , ScriptFrame               , None),
199     ENTRY  ( "process" , ScriptProcess             , None),
200     ENTRY  ( "target"  , ScriptTarget              , None),
201     ENTRY  ( "thread"  , ScriptThread              , None),
202     ENTRY  ( "var"     , ScriptVariable            , None),
203     ENTRY  ( "svar"    , ScriptVariableSynthetic   , None),
204     ENTRY  ( "thread"  , ScriptThread              , None),
205 };
206
207 static FormatEntity::Entry::Definition g_top_level_entries[] =
208 {
209     ENTRY_CHILDREN          ("addr"                , AddressLoadOrFile      , UInt64    , g_addr_entries),
210     ENTRY                   ("addr-file-or-load"   , AddressLoadOrFile      , UInt64    ),
211     ENTRY_CHILDREN          ("ansi"                , Invalid                , None      , g_ansi_entries),
212     ENTRY                   ("current-pc-arrow"    , CurrentPCArrow         , CString   ),
213     ENTRY_CHILDREN          ("file"                , File                   , CString   , g_file_child_entries),
214     ENTRY                   ("language"            , Lang                   , CString),
215     ENTRY_CHILDREN          ("frame"               , Invalid                , None      , g_frame_child_entries),
216     ENTRY_CHILDREN          ("function"            , Invalid                , None      , g_function_child_entries),
217     ENTRY_CHILDREN          ("line"                , Invalid                , None      , g_line_child_entries),
218     ENTRY_CHILDREN          ("module"              , Invalid                , None      , g_module_child_entries),
219     ENTRY_CHILDREN          ("process"             , Invalid                , None      , g_process_child_entries),
220     ENTRY_CHILDREN          ("script"              , Invalid                , None      , g_script_child_entries),
221     ENTRY_CHILDREN_KEEP_SEP ("svar"                , VariableSynthetic      , None      , g_svar_child_entries),
222     ENTRY_CHILDREN          ("thread"              , Invalid                , None      , g_thread_child_entries),
223     ENTRY_CHILDREN          ("target"              , Invalid                , None      , g_target_child_entries),
224     ENTRY_CHILDREN_KEEP_SEP ("var"                 , Variable               , None      , g_var_child_entries),
225 };
226
227 static FormatEntity::Entry::Definition g_root = ENTRY_CHILDREN ("<root>", Root, None, g_top_level_entries);
228
229
230 FormatEntity::Entry::Entry (llvm::StringRef s) :
231     string (s.data(), s.size()),
232     printf_format (),
233     children (),
234     definition (NULL),
235     type (Type::String),
236     fmt (lldb::eFormatDefault),
237     number (0),
238     deref (false)
239 {
240 }
241
242 FormatEntity::Entry::Entry (char ch) :
243     string (1, ch),
244     printf_format (),
245     children (),
246     definition (NULL),
247     type (Type::String),
248     fmt (lldb::eFormatDefault),
249     number (0),
250     deref (false)
251 {
252 }
253
254 void
255 FormatEntity::Entry::AppendChar (char ch)
256 {
257     if (children.empty() || children.back().type != Entry::Type::String)
258         children.push_back(Entry(ch));
259     else
260         children.back().string.append(1, ch);
261 }
262
263 void
264 FormatEntity::Entry::AppendText (const llvm::StringRef &s)
265 {
266     if (children.empty() || children.back().type != Entry::Type::String)
267         children.push_back(Entry(s));
268     else
269         children.back().string.append(s.data(), s.size());
270 }
271
272 void
273 FormatEntity::Entry::AppendText (const char *cstr)
274 {
275     return AppendText (llvm::StringRef(cstr));
276 }
277
278
279 Error
280 FormatEntity::Parse (const llvm::StringRef &format_str, Entry &entry)
281 {
282     entry.Clear();
283     entry.type = Entry::Type::Root;
284     llvm::StringRef modifiable_format (format_str);
285     return ParseInternal (modifiable_format, entry, 0);
286 }
287
288 #define ENUM_TO_CSTR(eee) case FormatEntity::Entry::Type::eee: return #eee
289
290 const char *
291 FormatEntity::Entry::TypeToCString (Type t)
292 {
293     switch (t)
294     {
295     ENUM_TO_CSTR(Invalid);
296     ENUM_TO_CSTR(ParentNumber);
297     ENUM_TO_CSTR(ParentString);
298     ENUM_TO_CSTR(InsertString);
299     ENUM_TO_CSTR(Root);
300     ENUM_TO_CSTR(String);
301     ENUM_TO_CSTR(Scope);
302     ENUM_TO_CSTR(Variable);
303     ENUM_TO_CSTR(VariableSynthetic);
304     ENUM_TO_CSTR(ScriptVariable);
305     ENUM_TO_CSTR(ScriptVariableSynthetic);
306     ENUM_TO_CSTR(AddressLoad);
307     ENUM_TO_CSTR(AddressFile);
308     ENUM_TO_CSTR(AddressLoadOrFile);
309     ENUM_TO_CSTR(ProcessID);
310     ENUM_TO_CSTR(ProcessFile);
311     ENUM_TO_CSTR(ScriptProcess);
312     ENUM_TO_CSTR(ThreadID);
313     ENUM_TO_CSTR(ThreadProtocolID);
314     ENUM_TO_CSTR(ThreadIndexID);
315     ENUM_TO_CSTR(ThreadName);
316     ENUM_TO_CSTR(ThreadQueue);
317     ENUM_TO_CSTR(ThreadStopReason);
318     ENUM_TO_CSTR(ThreadReturnValue);
319     ENUM_TO_CSTR(ThreadCompletedExpression);
320     ENUM_TO_CSTR(ScriptThread);
321     ENUM_TO_CSTR(ThreadInfo);
322     ENUM_TO_CSTR(TargetArch);
323     ENUM_TO_CSTR(ScriptTarget);
324     ENUM_TO_CSTR(ModuleFile);
325     ENUM_TO_CSTR(File);
326     ENUM_TO_CSTR(Lang);
327     ENUM_TO_CSTR(FrameIndex);
328     ENUM_TO_CSTR(FrameRegisterPC);
329     ENUM_TO_CSTR(FrameRegisterSP);
330     ENUM_TO_CSTR(FrameRegisterFP);
331     ENUM_TO_CSTR(FrameRegisterFlags);
332     ENUM_TO_CSTR(FrameRegisterByName);
333     ENUM_TO_CSTR(ScriptFrame);
334     ENUM_TO_CSTR(FunctionID);
335     ENUM_TO_CSTR(FunctionDidChange);
336     ENUM_TO_CSTR(FunctionInitialFunction);
337     ENUM_TO_CSTR(FunctionName);
338     ENUM_TO_CSTR(FunctionNameWithArgs);
339     ENUM_TO_CSTR(FunctionNameNoArgs);
340     ENUM_TO_CSTR(FunctionAddrOffset);
341     ENUM_TO_CSTR(FunctionAddrOffsetConcrete);
342     ENUM_TO_CSTR(FunctionLineOffset);
343     ENUM_TO_CSTR(FunctionPCOffset);
344     ENUM_TO_CSTR(FunctionInitial);
345     ENUM_TO_CSTR(FunctionChanged);
346     ENUM_TO_CSTR(LineEntryFile);
347     ENUM_TO_CSTR(LineEntryLineNumber);
348     ENUM_TO_CSTR(LineEntryStartAddress);
349     ENUM_TO_CSTR(LineEntryEndAddress);
350     ENUM_TO_CSTR(CurrentPCArrow);
351     }
352     return "???";
353 }
354
355 #undef ENUM_TO_CSTR
356
357 void
358 FormatEntity::Entry::Dump (Stream &s, int depth) const
359 {
360     s.Printf ("%*.*s%-20s: ", depth * 2, depth * 2, "", TypeToCString(type));
361     if (fmt != eFormatDefault)
362         s.Printf ("lldb-format = %s, ", FormatManager::GetFormatAsCString (fmt));
363     if (!string.empty())
364         s.Printf ("string = \"%s\"", string.c_str());
365     if (!printf_format.empty())
366         s.Printf ("printf_format = \"%s\"", printf_format.c_str());
367     if (number != 0)
368         s.Printf ("number = %" PRIu64 " (0x%" PRIx64 "), ", number, number);
369     if (deref)
370         s.Printf ("deref = true, ");
371     s.EOL();
372     for (const auto &child : children)
373     {
374         child.Dump(s, depth + 1);
375     }
376 }
377
378
379 template <typename T>
380 static bool RunScriptFormatKeyword(Stream &s,
381                                    const SymbolContext *sc,
382                                    const ExecutionContext *exe_ctx,
383                                    T t,
384                                    const char *script_function_name)
385 {
386     Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
387
388     if (target)
389     {
390         ScriptInterpreter *script_interpreter = target->GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
391         if (script_interpreter)
392         {
393             Error error;
394             std::string script_output;
395
396             if (script_interpreter->RunScriptFormatKeyword(script_function_name, t, script_output, error) && error.Success())
397             {
398                 s.Printf("%s", script_output.c_str());
399                 return true;
400             }
401             else
402             {
403                 s.Printf("<error: %s>",error.AsCString());
404             }
405         }
406     }
407     return false;
408 }
409
410 static bool
411 DumpAddress (Stream &s,
412              const SymbolContext *sc,
413              const ExecutionContext *exe_ctx,
414              const Address &addr,
415              bool print_file_addr_or_load_addr)
416 {
417     Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
418     addr_t vaddr = LLDB_INVALID_ADDRESS;
419     if (exe_ctx && !target->GetSectionLoadList().IsEmpty())
420         vaddr = addr.GetLoadAddress (target);
421     if (vaddr == LLDB_INVALID_ADDRESS)
422         vaddr = addr.GetFileAddress ();
423
424     if (vaddr != LLDB_INVALID_ADDRESS)
425     {
426         int addr_width = 0;
427         if (exe_ctx && target)
428         {
429             addr_width = target->GetArchitecture().GetAddressByteSize() * 2;
430         }
431         if (addr_width == 0)
432             addr_width = 16;
433         if (print_file_addr_or_load_addr)
434         {
435             ExecutionContextScope *exe_scope = NULL;
436             if (exe_ctx)
437                 exe_scope = exe_ctx->GetBestExecutionContextScope();
438             addr.Dump (&s, exe_scope, Address::DumpStyleLoadAddress, Address::DumpStyleModuleWithFileAddress, 0);
439         }
440         else
441         {
442             s.Printf("0x%*.*" PRIx64, addr_width, addr_width, vaddr);
443         }
444         return true;
445     }
446     return false;
447 }
448
449 static bool
450 DumpAddressOffsetFromFunction (Stream &s,
451                                const SymbolContext *sc,
452                                const ExecutionContext *exe_ctx,
453                                const Address &format_addr,
454                                bool concrete_only,
455                                bool no_padding,
456                                bool print_zero_offsets)
457 {
458     if (format_addr.IsValid())
459     {
460         Address func_addr;
461         
462         if (sc)
463         {
464             if (sc->function)
465             {
466                 func_addr = sc->function->GetAddressRange().GetBaseAddress();
467                 if (sc->block && !concrete_only)
468                 {
469                     // Check to make sure we aren't in an inline
470                     // function. If we are, use the inline block
471                     // range that contains "format_addr" since
472                     // blocks can be discontiguous.
473                     Block *inline_block = sc->block->GetContainingInlinedBlock ();
474                     AddressRange inline_range;
475                     if (inline_block && inline_block->GetRangeContainingAddress (format_addr, inline_range))
476                         func_addr = inline_range.GetBaseAddress();
477                 }
478             }
479             else if (sc->symbol && sc->symbol->ValueIsAddress())
480                 func_addr = sc->symbol->GetAddressRef();
481         }
482
483         if (func_addr.IsValid())
484         {
485             const char *addr_offset_padding = no_padding ? "" : " ";
486
487             if (func_addr.GetSection() == format_addr.GetSection())
488             {
489                 addr_t func_file_addr = func_addr.GetFileAddress();
490                 addr_t addr_file_addr = format_addr.GetFileAddress();
491                 if (addr_file_addr > func_file_addr
492                     || (addr_file_addr == func_file_addr && print_zero_offsets))
493                 {
494                     s.Printf("%s+%s%" PRIu64, addr_offset_padding, addr_offset_padding, addr_file_addr - func_file_addr);
495                 }
496                 else if (addr_file_addr < func_file_addr)
497                 {
498                     s.Printf("%s-%s%" PRIu64, addr_offset_padding, addr_offset_padding, func_file_addr - addr_file_addr);
499                 }
500                 return true;
501             }
502             else
503             {
504                 Target *target = Target::GetTargetFromContexts (exe_ctx, sc);
505                 if (target)
506                 {
507                     addr_t func_load_addr = func_addr.GetLoadAddress (target);
508                     addr_t addr_load_addr = format_addr.GetLoadAddress (target);
509                     if (addr_load_addr > func_load_addr
510                         || (addr_load_addr == func_load_addr && print_zero_offsets))
511                     {
512                         s.Printf("%s+%s%" PRIu64, addr_offset_padding, addr_offset_padding, addr_load_addr - func_load_addr);
513                     }
514                     else if (addr_load_addr < func_load_addr)
515                     {
516                         s.Printf("%s-%s%" PRIu64, addr_offset_padding, addr_offset_padding, func_load_addr - addr_load_addr);
517                     }
518                     return true;
519                 }
520             }
521         }
522     }
523     return false;
524 }
525
526 static bool
527 ScanBracketedRange (llvm::StringRef subpath,
528                     size_t& close_bracket_index,
529                     const char*& var_name_final_if_array_range,
530                     int64_t& index_lower,
531                     int64_t& index_higher)
532 {
533     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
534     close_bracket_index = llvm::StringRef::npos;
535     const size_t open_bracket_index = subpath.find('[');
536     if (open_bracket_index == llvm::StringRef::npos)
537     {
538         if (log)
539             log->Printf("[ScanBracketedRange] no bracketed range, skipping entirely");
540         return false;
541     }
542
543     close_bracket_index = subpath.find(']', open_bracket_index + 1);
544
545     if (close_bracket_index == llvm::StringRef::npos)
546     {
547         if (log)
548             log->Printf("[ScanBracketedRange] no bracketed range, skipping entirely");
549         return false;
550     }
551     else
552     {
553         var_name_final_if_array_range = subpath.data() + open_bracket_index;
554
555         if (close_bracket_index - open_bracket_index == 1)
556         {
557             if (log)
558                 log->Printf("[ScanBracketedRange] '[]' detected.. going from 0 to end of data");
559             index_lower = 0;
560         }
561         else
562         {
563             const size_t separator_index = subpath.find('-', open_bracket_index + 1);
564
565             if (separator_index == llvm::StringRef::npos)
566             {
567                 const char *index_lower_cstr = subpath.data() + open_bracket_index + 1;
568                 index_lower = ::strtoul (index_lower_cstr, NULL, 0);
569                 index_higher = index_lower;
570                 if (log)
571                     log->Printf("[ScanBracketedRange] [%" PRId64 "] detected, high index is same", index_lower);
572             }
573             else
574             {
575                 const char *index_lower_cstr = subpath.data() + open_bracket_index + 1;
576                 const char *index_higher_cstr = subpath.data() + separator_index + 1;
577                 index_lower = ::strtoul (index_lower_cstr, NULL, 0);
578                 index_higher = ::strtoul (index_higher_cstr, NULL, 0);
579                 if (log)
580                     log->Printf("[ScanBracketedRange] [%" PRId64 "-%" PRId64 "] detected", index_lower, index_higher);
581             }
582             if (index_lower > index_higher && index_higher > 0)
583             {
584                 if (log)
585                     log->Printf("[ScanBracketedRange] swapping indices");
586                 const int64_t temp = index_lower;
587                 index_lower = index_higher;
588                 index_higher = temp;
589             }
590         }
591     }
592     return true;
593 }
594
595 static bool
596 DumpFile (Stream &s, const FileSpec &file, FileKind file_kind)
597 {
598     switch (file_kind)
599     {
600     case FileKind::FileError:
601         break;
602
603     case FileKind::Basename:
604         if (file.GetFilename())
605         {
606             s << file.GetFilename();
607             return true;
608         }
609         break;
610
611     case FileKind::Dirname:
612         if (file.GetDirectory())
613         {
614             s << file.GetDirectory();
615             return true;
616         }
617         break;
618
619     case FileKind::Fullpath:
620         if (file)
621         {
622             s << file;
623             return true;
624         }
625         break;
626     }
627     return false;
628 }
629
630 static bool
631 DumpRegister (Stream &s,
632               StackFrame *frame,
633               RegisterKind reg_kind,
634               uint32_t reg_num,
635               Format format)
636
637 {
638     if (frame)
639     {
640         RegisterContext *reg_ctx = frame->GetRegisterContext().get();
641
642         if (reg_ctx)
643         {
644             const uint32_t lldb_reg_num = reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
645             if (lldb_reg_num != LLDB_INVALID_REGNUM)
646             {
647                 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex (lldb_reg_num);
648                 if (reg_info)
649                 {
650                     RegisterValue reg_value;
651                     if (reg_ctx->ReadRegister (reg_info, reg_value))
652                     {
653                         reg_value.Dump(&s, reg_info, false, false, format);
654                         return true;
655                     }
656                 }
657             }
658         }
659     }
660     return false;
661 }
662
663
664 static ValueObjectSP
665 ExpandIndexedExpression (ValueObject* valobj,
666                          size_t index,
667                          StackFrame* frame,
668                          bool deref_pointer)
669 {
670     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
671     const char* ptr_deref_format = "[%d]";
672     std::string ptr_deref_buffer(10,0);
673     ::sprintf(&ptr_deref_buffer[0], ptr_deref_format, index);
674     if (log)
675         log->Printf("[ExpandIndexedExpression] name to deref: %s",ptr_deref_buffer.c_str());
676     const char* first_unparsed;
677     ValueObject::GetValueForExpressionPathOptions options;
678     ValueObject::ExpressionPathEndResultType final_value_type;
679     ValueObject::ExpressionPathScanEndReason reason_to_stop;
680     ValueObject::ExpressionPathAftermath what_next = (deref_pointer ? ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
681     ValueObjectSP item = valobj->GetValueForExpressionPath (ptr_deref_buffer.c_str(),
682                                                             &first_unparsed,
683                                                             &reason_to_stop,
684                                                             &final_value_type,
685                                                             options,
686                                                             &what_next);
687     if (!item)
688     {
689         if (log)
690             log->Printf("[ExpandIndexedExpression] ERROR: unparsed portion = %s, why stopping = %d,"
691                         " final_value_type %d",
692                         first_unparsed, reason_to_stop, final_value_type);
693     }
694     else
695     {
696         if (log)
697             log->Printf("[ExpandIndexedExpression] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
698                         " final_value_type %d",
699                         first_unparsed, reason_to_stop, final_value_type);
700     }
701     return item;
702 }
703
704 static char
705 ConvertValueObjectStyleToChar(ValueObject::ValueObjectRepresentationStyle style)
706 {
707     switch (style)
708     {
709         case ValueObject::eValueObjectRepresentationStyleLanguageSpecific:  return '@';
710         case ValueObject::eValueObjectRepresentationStyleValue:             return 'V';
711         case ValueObject::eValueObjectRepresentationStyleLocation:          return 'L';
712         case ValueObject::eValueObjectRepresentationStyleSummary:           return 'S';
713         case ValueObject::eValueObjectRepresentationStyleChildrenCount:     return '#';
714         case ValueObject::eValueObjectRepresentationStyleType:              return 'T';
715         case ValueObject::eValueObjectRepresentationStyleName:              return 'N';
716         case ValueObject::eValueObjectRepresentationStyleExpressionPath:    return '>';
717     }
718     return '\0';
719 }
720
721 static bool
722 DumpValue (Stream &s,
723            const SymbolContext *sc,
724            const ExecutionContext *exe_ctx,
725            const FormatEntity::Entry &entry,
726            ValueObject *valobj)
727 {
728     if (valobj == NULL)
729         return false;
730
731     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TYPES));
732     Format custom_format = eFormatInvalid;
733     ValueObject::ValueObjectRepresentationStyle val_obj_display = entry.string.empty() ? ValueObject::eValueObjectRepresentationStyleValue : ValueObject::eValueObjectRepresentationStyleSummary;
734
735     bool do_deref_pointer = entry.deref;
736     bool is_script = false;
737     switch (entry.type)
738     {
739         case FormatEntity::Entry::Type::ScriptVariable:
740             is_script = true;
741             break;
742
743         case FormatEntity::Entry::Type::Variable:
744             custom_format = entry.fmt;
745             val_obj_display = (ValueObject::ValueObjectRepresentationStyle)entry.number;
746             break;
747
748         case FormatEntity::Entry::Type::ScriptVariableSynthetic:
749             is_script = true;
750             // Fall through
751         case FormatEntity::Entry::Type::VariableSynthetic:
752             custom_format = entry.fmt;
753             val_obj_display = (ValueObject::ValueObjectRepresentationStyle)entry.number;
754             if (!valobj->IsSynthetic())
755             {
756                 valobj = valobj->GetSyntheticValue().get();
757                 if (valobj == nullptr)
758                     return false;
759             }
760             break;
761
762         default:
763             return false;
764     }
765
766     if (valobj == NULL)
767         return false;
768
769     ValueObject::ExpressionPathAftermath what_next = (do_deref_pointer ?
770                                                       ValueObject::eExpressionPathAftermathDereference : ValueObject::eExpressionPathAftermathNothing);
771     ValueObject::GetValueForExpressionPathOptions options;
772     options.DontCheckDotVsArrowSyntax().DoAllowBitfieldSyntax().DoAllowFragileIVar().SetSyntheticChildrenTraversal(ValueObject::GetValueForExpressionPathOptions::SyntheticChildrenTraversal::Both);
773     ValueObject* target = NULL;
774     const char* var_name_final_if_array_range = NULL;
775     size_t close_bracket_index = llvm::StringRef::npos;
776     int64_t index_lower = -1;
777     int64_t index_higher = -1;
778     bool is_array_range = false;
779     const char* first_unparsed;
780     bool was_plain_var = false;
781     bool was_var_format = false;
782     bool was_var_indexed = false;
783     ValueObject::ExpressionPathScanEndReason reason_to_stop = ValueObject::eExpressionPathScanEndReasonEndOfString;
784     ValueObject::ExpressionPathEndResultType final_value_type = ValueObject::eExpressionPathEndResultTypePlain;
785
786     if (is_script)
787     {
788         return RunScriptFormatKeyword (s, sc, exe_ctx, valobj, entry.string.c_str());
789     }
790
791     llvm::StringRef subpath (entry.string);
792     // simplest case ${var}, just print valobj's value
793     if (entry.string.empty())
794     {
795         if (entry.printf_format.empty() && entry.fmt == eFormatDefault && entry.number == ValueObject::eValueObjectRepresentationStyleValue)
796             was_plain_var = true;
797         else
798             was_var_format = true;
799         target = valobj;
800     }
801     else    // this is ${var.something} or multiple .something nested
802     {
803         if (entry.string[0] == '[')
804             was_var_indexed = true;
805         ScanBracketedRange (subpath,
806                             close_bracket_index,
807                             var_name_final_if_array_range,
808                             index_lower,
809                             index_higher);
810
811         Error error;
812
813         const std::string &expr_path = entry.string;
814
815         if (log)
816             log->Printf("[Debugger::FormatPrompt] symbol to expand: %s",expr_path.c_str());
817
818         target = valobj->GetValueForExpressionPath(expr_path.c_str(),
819                                                    &first_unparsed,
820                                                    &reason_to_stop,
821                                                    &final_value_type,
822                                                    options,
823                                                    &what_next).get();
824
825         if (!target)
826         {
827             if (log)
828                 log->Printf("[Debugger::FormatPrompt] ERROR: unparsed portion = %s, why stopping = %d,"
829                             " final_value_type %d",
830                             first_unparsed, reason_to_stop, final_value_type);
831             return false;
832         }
833         else
834         {
835             if (log)
836                 log->Printf("[Debugger::FormatPrompt] ALL RIGHT: unparsed portion = %s, why stopping = %d,"
837                             " final_value_type %d",
838                             first_unparsed, reason_to_stop, final_value_type);
839             target = target->GetQualifiedRepresentationIfAvailable(target->GetDynamicValueType(), true).get();
840         }
841     }
842
843
844     is_array_range = (final_value_type == ValueObject::eExpressionPathEndResultTypeBoundedRange ||
845                       final_value_type == ValueObject::eExpressionPathEndResultTypeUnboundedRange);
846
847     do_deref_pointer = (what_next == ValueObject::eExpressionPathAftermathDereference);
848
849     if (do_deref_pointer && !is_array_range)
850     {
851         // I have not deref-ed yet, let's do it
852         // this happens when we are not going through GetValueForVariableExpressionPath
853         // to get to the target ValueObject
854         Error error;
855         target = target->Dereference(error).get();
856         if (error.Fail())
857         {
858             if (log)
859                 log->Printf("[Debugger::FormatPrompt] ERROR: %s\n", error.AsCString("unknown")); \
860             return false;
861         }
862         do_deref_pointer = false;
863     }
864
865     if (!target)
866     {
867         if (log)
868             log->Printf("[Debugger::FormatPrompt] could not calculate target for prompt expression");
869         return false;
870     }
871
872     // we do not want to use the summary for a bitfield of type T:n
873     // if we were originally dealing with just a T - that would get
874     // us into an endless recursion
875     if (target->IsBitfield() && was_var_indexed)
876     {
877         // TODO: check for a (T:n)-specific summary - we should still obey that
878         StreamString bitfield_name;
879         bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(), target->GetBitfieldBitSize());
880         lldb::TypeNameSpecifierImplSP type_sp(new TypeNameSpecifierImpl(bitfield_name.GetData(),false));
881         if (val_obj_display == ValueObject::eValueObjectRepresentationStyleSummary && !DataVisualization::GetSummaryForType(type_sp))
882             val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
883     }
884
885     // TODO use flags for these
886     const uint32_t type_info_flags = target->GetClangType().GetTypeInfo(NULL);
887     bool is_array = (type_info_flags & eTypeIsArray) != 0;
888     bool is_pointer = (type_info_flags & eTypeIsPointer) != 0;
889     bool is_aggregate = target->GetClangType().IsAggregateType();
890
891     if ((is_array || is_pointer) && (!is_array_range) && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue) // this should be wrong, but there are some exceptions
892     {
893         StreamString str_temp;
894         if (log)
895             log->Printf("[Debugger::FormatPrompt] I am into array || pointer && !range");
896
897         if (target->HasSpecialPrintableRepresentation(val_obj_display, custom_format))
898         {
899             // try to use the special cases
900             bool success = target->DumpPrintableRepresentation(str_temp,
901                                                                val_obj_display,
902                                                                custom_format);
903             if (log)
904                 log->Printf("[Debugger::FormatPrompt] special cases did%s match", success ? "" : "n't");
905
906             // should not happen
907             if (success)
908                 s << str_temp.GetData();
909             return true;
910         }
911         else
912         {
913             if (was_plain_var) // if ${var}
914             {
915                 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
916             }
917             else if (is_pointer) // if pointer, value is the address stored
918             {
919                 target->DumpPrintableRepresentation (s,
920                                                      val_obj_display,
921                                                      custom_format,
922                                                      ValueObject::ePrintableRepresentationSpecialCasesDisable);
923             }
924             return true;
925         }
926     }
927
928     // if directly trying to print ${var}, and this is an aggregate, display a nice
929     // type @ location message
930     if (is_aggregate && was_plain_var)
931     {
932         s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
933         return true;
934     }
935
936     // if directly trying to print ${var%V}, and this is an aggregate, do not let the user do it
937     if (is_aggregate && ((was_var_format && val_obj_display == ValueObject::eValueObjectRepresentationStyleValue)))
938     {
939         s << "<invalid use of aggregate type>";
940         return true;
941     }
942
943     if (!is_array_range)
944     {
945         if (log)
946             log->Printf("[Debugger::FormatPrompt] dumping ordinary printable output");
947         return target->DumpPrintableRepresentation(s,val_obj_display, custom_format);
948     }
949     else
950     {
951         if (log)
952             log->Printf("[Debugger::FormatPrompt] checking if I can handle as array");
953         if (!is_array && !is_pointer)
954             return false;
955         if (log)
956             log->Printf("[Debugger::FormatPrompt] handle as array");
957         StreamString special_directions_stream;
958         llvm::StringRef special_directions;
959         if (close_bracket_index != llvm::StringRef::npos && subpath.size() > close_bracket_index)
960         {
961             ConstString additional_data (subpath.drop_front(close_bracket_index+1));
962             special_directions_stream.Printf("${%svar%s",
963                                              do_deref_pointer ? "*" : "",
964                                              additional_data.GetCString());
965
966             if (entry.fmt != eFormatDefault)
967             {
968                 const char format_char = FormatManager::GetFormatAsFormatChar(entry.fmt);
969                 if (format_char != '\0')
970                     special_directions_stream.Printf("%%%c", format_char);
971                 else
972                 {
973                     const char *format_cstr = FormatManager::GetFormatAsCString(entry.fmt);
974                     special_directions_stream.Printf("%%%s", format_cstr);
975                 }
976             }
977             else if (entry.number != 0)
978             {
979                 const char style_char = ConvertValueObjectStyleToChar ((ValueObject::ValueObjectRepresentationStyle)entry.number);
980                 if (style_char)
981                     special_directions_stream.Printf("%%%c", style_char);
982             }
983             special_directions_stream.PutChar('}');
984             special_directions = llvm::StringRef(special_directions_stream.GetString());
985         }
986
987         // let us display items index_lower thru index_higher of this array
988         s.PutChar('[');
989
990         if (index_higher < 0)
991             index_higher = valobj->GetNumChildren() - 1;
992
993         uint32_t max_num_children = target->GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();
994
995         bool success = true;
996         for (int64_t index = index_lower;index<=index_higher; ++index)
997         {
998             ValueObject* item = ExpandIndexedExpression (target,
999                                                          index,
1000                                                          exe_ctx->GetFramePtr(),
1001                                                          false).get();
1002
1003             if (!item)
1004             {
1005                 if (log)
1006                     log->Printf("[Debugger::FormatPrompt] ERROR in getting child item at index %" PRId64, index);
1007             }
1008             else
1009             {
1010                 if (log)
1011                     log->Printf("[Debugger::FormatPrompt] special_directions for child item: %s",special_directions.data() ? special_directions.data() : "");
1012             }
1013
1014             if (special_directions.empty())
1015             {
1016                 success &= item->DumpPrintableRepresentation(s,val_obj_display, custom_format);
1017             }
1018             else
1019             {
1020                 success &= FormatEntity::FormatStringRef(special_directions, s, sc, exe_ctx, NULL, item, false, false);
1021             }
1022
1023             if (--max_num_children == 0)
1024             {
1025                 s.PutCString(", ...");
1026                 break;
1027             }
1028
1029             if (index < index_higher)
1030                 s.PutChar(',');
1031         }
1032         s.PutChar(']');
1033         return success;
1034     }
1035
1036 }
1037
1038 static bool
1039 DumpRegister (Stream &s,
1040               StackFrame *frame,
1041               const char *reg_name,
1042               Format format)
1043
1044 {
1045     if (frame)
1046     {
1047         RegisterContext *reg_ctx = frame->GetRegisterContext().get();
1048
1049         if (reg_ctx)
1050         {
1051             const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name);
1052             if (reg_info)
1053             {
1054                 RegisterValue reg_value;
1055                 if (reg_ctx->ReadRegister (reg_info, reg_value))
1056                 {
1057                     reg_value.Dump(&s, reg_info, false, false, format);
1058                     return true;
1059                 }
1060             }
1061         }
1062     }
1063     return false;
1064 }
1065
1066 static bool
1067 FormatThreadExtendedInfoRecurse(const FormatEntity::Entry &entry,
1068                                 const StructuredData::ObjectSP &thread_info_dictionary,
1069                                 const SymbolContext *sc,
1070                                 const ExecutionContext *exe_ctx,
1071                                 Stream &s)
1072 {
1073     llvm::StringRef path(entry.string);
1074
1075     StructuredData::ObjectSP value = thread_info_dictionary->GetObjectForDotSeparatedPath (path);
1076
1077     if (value.get())
1078     {
1079         if (value->GetType() == StructuredData::Type::eTypeInteger)
1080         {
1081             const char *token_format = "0x%4.4" PRIx64;
1082             if (!entry.printf_format.empty())
1083                 token_format = entry.printf_format.c_str();
1084             s.Printf(token_format, value->GetAsInteger()->GetValue());
1085             return true;
1086         }
1087         else if (value->GetType() == StructuredData::Type::eTypeFloat)
1088         {
1089             s.Printf ("%f", value->GetAsFloat()->GetValue());
1090             return true;
1091         }
1092         else if (value->GetType() == StructuredData::Type::eTypeString)
1093         {
1094             s.Printf("%s", value->GetAsString()->GetValue().c_str());
1095             return true;
1096         }
1097         else if (value->GetType() == StructuredData::Type::eTypeArray)
1098         {
1099             if (value->GetAsArray()->GetSize() > 0)
1100             {
1101                 s.Printf ("%zu", value->GetAsArray()->GetSize());
1102                 return true;
1103             }
1104         }
1105         else if (value->GetType() == StructuredData::Type::eTypeDictionary)
1106         {
1107             s.Printf ("%zu", value->GetAsDictionary()->GetKeys()->GetAsArray()->GetSize());
1108             return true;
1109         }
1110     }
1111
1112     return false;
1113 }
1114
1115
1116 static inline bool
1117 IsToken(const char *var_name_begin, const char *var)
1118 {
1119     return (::strncmp (var_name_begin, var, strlen(var)) == 0);
1120 }
1121
1122 bool
1123 FormatEntity::FormatStringRef (const llvm::StringRef &format_str,
1124                                Stream &s,
1125                                const SymbolContext *sc,
1126                                const ExecutionContext *exe_ctx,
1127                                const Address *addr,
1128                                ValueObject* valobj,
1129                                bool function_changed,
1130                                bool initial_function)
1131 {
1132     if (!format_str.empty())
1133     {
1134         FormatEntity::Entry root;
1135         Error error = FormatEntity::Parse(format_str, root);
1136         if (error.Success())
1137         {
1138             return FormatEntity::Format (root,
1139                                          s,
1140                                          sc,
1141                                          exe_ctx,
1142                                          addr,
1143                                          valobj,
1144                                          function_changed,
1145                                          initial_function);
1146         }
1147     }
1148     return false;
1149
1150 }
1151 bool
1152 FormatEntity::FormatCString (const char *format,
1153                              Stream &s,
1154                              const SymbolContext *sc,
1155                              const ExecutionContext *exe_ctx,
1156                              const Address *addr,
1157                              ValueObject* valobj,
1158                              bool function_changed,
1159                              bool initial_function)
1160 {
1161     if (format && format[0])
1162     {
1163         FormatEntity::Entry root;
1164         llvm::StringRef format_str(format);
1165         Error error = FormatEntity::Parse(format_str, root);
1166         if (error.Success())
1167         {
1168             return FormatEntity::Format (root,
1169                                          s,
1170                                          sc,
1171                                          exe_ctx,
1172                                          addr,
1173                                          valobj,
1174                                          function_changed,
1175                                          initial_function);
1176         }
1177     }
1178     return false;
1179 }
1180
1181 bool
1182 FormatEntity::Format (const Entry &entry,
1183                       Stream &s,
1184                       const SymbolContext *sc,
1185                       const ExecutionContext *exe_ctx,
1186                       const Address *addr,
1187                       ValueObject* valobj,
1188                       bool function_changed,
1189                       bool initial_function)
1190 {
1191     switch (entry.type)
1192     {
1193         case Entry::Type::Invalid:
1194         case Entry::Type::ParentNumber: // Only used for FormatEntity::Entry::Definition encoding
1195         case Entry::Type::ParentString: // Only used for FormatEntity::Entry::Definition encoding
1196         case Entry::Type::InsertString: // Only used for FormatEntity::Entry::Definition encoding
1197             return false;
1198
1199         case Entry::Type::Root:
1200             for (const auto &child : entry.children)
1201             {
1202                 if (Format (child,
1203                             s,
1204                             sc,
1205                             exe_ctx,
1206                             addr,
1207                             valobj,
1208                             function_changed,
1209                             initial_function) == false)
1210                 {
1211                     return false; // If any item of root fails, then the formatting fails
1212                 }
1213             }
1214             return true; // Only return true if all items succeeded
1215
1216         case Entry::Type::String:
1217             s.PutCString(entry.string.c_str());
1218             return true;
1219
1220         case Entry::Type::Scope:
1221             {
1222                 StreamString scope_stream;
1223                 bool success = false;
1224                 for (const auto &child : entry.children)
1225                 {
1226                     success = Format (child, scope_stream, sc, exe_ctx, addr, valobj, function_changed, initial_function);
1227                     if (!success)
1228                         break;
1229                 }
1230                 // Only if all items in a scope succeed, then do we
1231                 // print the output into the main stream
1232                 if (success)
1233                     s.Write(scope_stream.GetString().data(), scope_stream.GetString().size());
1234             }
1235             return true; // Scopes always successfully print themselves
1236
1237         case Entry::Type::Variable:
1238         case Entry::Type::VariableSynthetic:
1239         case Entry::Type::ScriptVariable:
1240         case Entry::Type::ScriptVariableSynthetic:
1241             if (DumpValue(s, sc, exe_ctx, entry, valobj))
1242                 return true;
1243             return false;
1244
1245         case Entry::Type::AddressFile:
1246         case Entry::Type::AddressLoad:
1247         case Entry::Type::AddressLoadOrFile:
1248             if (addr && addr->IsValid() && DumpAddress(s, sc, exe_ctx, *addr, entry.type == Entry::Type::AddressLoadOrFile))
1249                 return true;
1250             return false;
1251
1252         case Entry::Type::ProcessID:
1253             if (exe_ctx)
1254             {
1255                 Process *process = exe_ctx->GetProcessPtr();
1256                 if (process)
1257                 {
1258                     const char *format = "%" PRIu64;
1259                     if (!entry.printf_format.empty())
1260                         format = entry.printf_format.c_str();
1261                     s.Printf(format, process->GetID());
1262                     return true;
1263                 }
1264             }
1265             return false;
1266
1267         case Entry::Type::ProcessFile:
1268             if (exe_ctx)
1269             {
1270                 Process *process = exe_ctx->GetProcessPtr();
1271                 if (process)
1272                 {
1273                     Module *exe_module = process->GetTarget().GetExecutableModulePointer();
1274                     if (exe_module)
1275                     {
1276                         if (DumpFile(s, exe_module->GetFileSpec(), (FileKind)entry.number))
1277                             return true;
1278                     }
1279                 }
1280             }
1281             return false;
1282
1283         case Entry::Type::ScriptProcess:
1284             if (exe_ctx)
1285             {
1286                 Process *process = exe_ctx->GetProcessPtr();
1287                 if (process)
1288                     return RunScriptFormatKeyword (s, sc, exe_ctx, process, entry.string.c_str());
1289             }
1290             return false;
1291
1292
1293         case Entry::Type::ThreadID:
1294             if (exe_ctx)
1295             {
1296                 Thread *thread = exe_ctx->GetThreadPtr();
1297                 if (thread)
1298                 {
1299                     const char *format = "0x%4.4" PRIx64;
1300                     if (!entry.printf_format.empty())
1301                     {
1302                         // Watch for the special "tid" format...
1303                         if (entry.printf_format == "tid")
1304                         {
1305                             Target &target = thread->GetProcess()->GetTarget();
1306                             ArchSpec arch (target.GetArchitecture ());
1307                             llvm::Triple::OSType ostype = arch.IsValid() ? arch.GetTriple().getOS() : llvm::Triple::UnknownOS;
1308                             if ((ostype == llvm::Triple::FreeBSD) || (ostype == llvm::Triple::Linux))
1309                             {
1310                                 format = "%" PRIu64;
1311                             }
1312                         }
1313                         else
1314                         {
1315                             format = entry.printf_format.c_str();
1316                         }
1317                     }
1318                     s.Printf(format, thread->GetID());
1319                     return true;
1320                 }
1321             }
1322             return false;
1323
1324         case Entry::Type::ThreadProtocolID:
1325             if (exe_ctx)
1326             {
1327                 Thread *thread = exe_ctx->GetThreadPtr();
1328                 if (thread)
1329                 {
1330                     const char *format = "0x%4.4" PRIx64;
1331                     if (!entry.printf_format.empty())
1332                         format = entry.printf_format.c_str();
1333                     s.Printf(format, thread->GetProtocolID());
1334                     return true;
1335                 }
1336             }
1337             return false;
1338
1339         case Entry::Type::ThreadIndexID:
1340             if (exe_ctx)
1341             {
1342                 Thread *thread = exe_ctx->GetThreadPtr();
1343                 if (thread)
1344                 {
1345                     const char *format = "%" PRIu32;
1346                     if (!entry.printf_format.empty())
1347                         format = entry.printf_format.c_str();
1348                     s.Printf(format, thread->GetIndexID());
1349                     return true;
1350                 }
1351             }
1352             return false;
1353
1354         case Entry::Type::ThreadName:
1355             if (exe_ctx)
1356             {
1357                 Thread *thread = exe_ctx->GetThreadPtr();
1358                 if (thread)
1359                 {
1360                     const char *cstr = thread->GetName();
1361                     if (cstr && cstr[0])
1362                     {
1363                         s.PutCString(cstr);
1364                         return true;
1365                     }
1366                 }
1367             }
1368             return false;
1369
1370         case Entry::Type::ThreadQueue:
1371             if (exe_ctx)
1372             {
1373                 Thread *thread = exe_ctx->GetThreadPtr();
1374                 if (thread)
1375                 {
1376                     const char *cstr = thread->GetQueueName();
1377                     if (cstr && cstr[0])
1378                     {
1379                         s.PutCString(cstr);
1380                         return true;
1381                     }
1382                 }
1383             }
1384             return false;
1385
1386         case Entry::Type::ThreadStopReason:
1387             if (exe_ctx)
1388             {
1389                 Thread *thread = exe_ctx->GetThreadPtr();
1390                 if (thread)
1391                 {
1392                     StopInfoSP stop_info_sp = thread->GetStopInfo ();
1393                     if (stop_info_sp && stop_info_sp->IsValid())
1394                     {
1395                         const char *cstr = stop_info_sp->GetDescription();
1396                         if (cstr && cstr[0])
1397                         {
1398                             s.PutCString(cstr);
1399                             return true;
1400                         }
1401                     }
1402                 }
1403             }
1404             return false;
1405
1406         case Entry::Type::ThreadReturnValue:
1407             if (exe_ctx)
1408             {
1409                 Thread *thread = exe_ctx->GetThreadPtr();
1410                 if (thread)
1411                 {
1412                     StopInfoSP stop_info_sp = thread->GetStopInfo ();
1413                     if (stop_info_sp && stop_info_sp->IsValid())
1414                     {
1415                         ValueObjectSP return_valobj_sp = StopInfo::GetReturnValueObject (stop_info_sp);
1416                         if (return_valobj_sp)
1417                         {
1418                             return_valobj_sp->Dump(s);
1419                             return true;
1420                         }
1421                     }
1422                 }
1423             }
1424             return false;
1425
1426         case Entry::Type::ThreadCompletedExpression:
1427             if (exe_ctx)
1428             {
1429                 Thread *thread = exe_ctx->GetThreadPtr();
1430                 if (thread)
1431                 {
1432                     StopInfoSP stop_info_sp = thread->GetStopInfo ();
1433                     if (stop_info_sp && stop_info_sp->IsValid())
1434                     {
1435                         ClangExpressionVariableSP expression_var_sp = StopInfo::GetExpressionVariable (stop_info_sp);
1436                         if (expression_var_sp && expression_var_sp->GetValueObject())
1437                         {
1438                             expression_var_sp->GetValueObject()->Dump(s);
1439                             return true;
1440                         }
1441                     }
1442                 }
1443             }
1444             return false;
1445
1446         case Entry::Type::ScriptThread:
1447             if (exe_ctx)
1448             {
1449                 Thread *thread = exe_ctx->GetThreadPtr();
1450                 if (thread)
1451                     return RunScriptFormatKeyword (s, sc, exe_ctx, thread, entry.string.c_str());
1452             }
1453             return false;
1454
1455         case Entry::Type::ThreadInfo:
1456             if (exe_ctx)
1457             {
1458                 Thread *thread = exe_ctx->GetThreadPtr();
1459                 if (thread)
1460                 {
1461                     StructuredData::ObjectSP object_sp = thread->GetExtendedInfo();
1462                     if (object_sp && object_sp->GetType() == StructuredData::Type::eTypeDictionary)
1463                     {
1464                         if (FormatThreadExtendedInfoRecurse (entry, object_sp, sc, exe_ctx, s))
1465                             return true;
1466                     }
1467                 }
1468             }
1469             return false;
1470
1471         case Entry::Type::TargetArch:
1472             if (exe_ctx)
1473             {
1474                 Target *target = exe_ctx->GetTargetPtr();
1475                 if (target)
1476                 {
1477                     const ArchSpec &arch = target->GetArchitecture ();
1478                     if (arch.IsValid())
1479                     {
1480                         s.PutCString (arch.GetArchitectureName());
1481                         return true;
1482                     }
1483                 }
1484             }
1485             return false;
1486
1487         case Entry::Type::ScriptTarget:
1488             if (exe_ctx)
1489             {
1490                 Target *target = exe_ctx->GetTargetPtr();
1491                 if (target)
1492                     return RunScriptFormatKeyword (s, sc, exe_ctx, target, entry.string.c_str());
1493             }
1494             return false;
1495
1496         case Entry::Type::ModuleFile:
1497             if (sc)
1498             {
1499                 Module *module = sc->module_sp.get();
1500                 if (module)
1501                 {
1502                     if (DumpFile(s, module->GetFileSpec(), (FileKind)entry.number))
1503                         return true;
1504                 }
1505             }
1506             return false;
1507
1508         case Entry::Type::File:
1509             if (sc)
1510             {
1511                 CompileUnit *cu = sc->comp_unit;
1512                 if (cu)
1513                 {
1514                     // CompileUnit is a FileSpec
1515                     if (DumpFile(s, *cu, (FileKind)entry.number))
1516                         return true;
1517                 }
1518             }
1519             return false;
1520
1521         case Entry::Type::Lang:
1522             if (sc)
1523             {
1524                 CompileUnit *cu = sc->comp_unit;
1525                 if (cu)
1526                 {
1527                     Language lang(cu->GetLanguage());
1528                     const char *lang_name = lang.AsCString();
1529                     if (lang_name)
1530                     {
1531                         s.PutCString(lang_name);
1532                         return true;
1533                     }
1534                 }
1535             }
1536             return false;
1537
1538         case Entry::Type::FrameIndex:
1539             if (exe_ctx)
1540             {
1541                 StackFrame *frame = exe_ctx->GetFramePtr();
1542                 if (frame)
1543                 {
1544                     const char *format = "%" PRIu32;
1545                     if (!entry.printf_format.empty())
1546                         format = entry.printf_format.c_str();
1547                     s.Printf(format, frame->GetFrameIndex());
1548                     return true;
1549                 }
1550             }
1551             return false;
1552
1553         case Entry::Type::FrameRegisterPC:
1554             if (exe_ctx)
1555             {
1556                 StackFrame *frame = exe_ctx->GetFramePtr();
1557                 if (frame)
1558                 {
1559                     const Address &pc_addr = frame->GetFrameCodeAddress();
1560                     if (pc_addr.IsValid())
1561                     {
1562                         if (DumpAddress(s, sc, exe_ctx, pc_addr, false))
1563                             return true;
1564                     }
1565                 }
1566             }
1567             return false;
1568
1569         case Entry::Type::FrameRegisterSP:
1570             if (exe_ctx)
1571             {
1572                 StackFrame *frame = exe_ctx->GetFramePtr();
1573                 if (frame)
1574                 {
1575                     if (DumpRegister (s, frame, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, (lldb::Format)entry.number))
1576                         return true;
1577                 }
1578             }
1579             return false;
1580
1581         case Entry::Type::FrameRegisterFP:
1582             if (exe_ctx)
1583             {
1584                 StackFrame *frame = exe_ctx->GetFramePtr();
1585                 if (frame)
1586                 {
1587                     if (DumpRegister (s, frame, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FP, (lldb::Format)entry.number))
1588                         return true;
1589                 }
1590             }
1591             return false;
1592
1593         case Entry::Type::FrameRegisterFlags:
1594             if (exe_ctx)
1595             {
1596                 StackFrame *frame = exe_ctx->GetFramePtr();
1597                 if (frame)
1598                 {
1599                     if (DumpRegister (s, frame, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS, (lldb::Format)entry.number))
1600                         return true;
1601                 }
1602             }
1603             return false;
1604
1605
1606         case Entry::Type::FrameRegisterByName:
1607             if (exe_ctx)
1608             {
1609                 StackFrame *frame = exe_ctx->GetFramePtr();
1610                 if (frame)
1611                 {
1612                     if (DumpRegister (s, frame, entry.string.c_str(), (lldb::Format)entry.number))
1613                         return true;
1614                 }
1615             }
1616             return false;
1617
1618         case Entry::Type::ScriptFrame:
1619             if (exe_ctx)
1620             {
1621                 StackFrame *frame = exe_ctx->GetFramePtr();
1622                 if (frame)
1623                     return RunScriptFormatKeyword (s, sc, exe_ctx, frame, entry.string.c_str());
1624             }
1625             return false;
1626
1627         case Entry::Type::FunctionID:
1628             if (sc)
1629             {
1630                 if (sc->function)
1631                 {
1632                     s.Printf("function{0x%8.8" PRIx64 "}", sc->function->GetID());
1633                     return true;
1634                 }
1635                 else if (sc->symbol)
1636                 {
1637                     s.Printf("symbol[%u]", sc->symbol->GetID());
1638                     return true;
1639                 }
1640             }
1641             return false;
1642
1643         case Entry::Type::FunctionDidChange:
1644             return function_changed;
1645
1646         case Entry::Type::FunctionInitialFunction:
1647             return initial_function;
1648
1649         case Entry::Type::FunctionName:
1650             {
1651                 const char *name = NULL;
1652                 if (sc->function)
1653                     name = sc->function->GetName().AsCString (NULL);
1654                 else if (sc->symbol)
1655                     name = sc->symbol->GetName().AsCString (NULL);
1656                 if (name)
1657                 {
1658                     s.PutCString(name);
1659
1660                     if (sc->block)
1661                     {
1662                         Block *inline_block = sc->block->GetContainingInlinedBlock ();
1663                         if (inline_block)
1664                         {
1665                             const InlineFunctionInfo *inline_info = sc->block->GetInlinedFunctionInfo();
1666                             if (inline_info)
1667                             {
1668                                 s.PutCString(" [inlined] ");
1669                                 inline_info->GetName(sc->function->GetLanguage()).Dump(&s);
1670                             }
1671                         }
1672                     }
1673                     return true;
1674                 }
1675             }
1676             return false;
1677
1678         case Entry::Type::FunctionNameNoArgs:
1679             {
1680                 ConstString name;
1681                 if (sc->function)
1682                     name = sc->function->GetNameNoArguments();
1683                 else if (sc->symbol)
1684                     name = sc->symbol->GetNameNoArguments();
1685                 if (name)
1686                 {
1687                     s.PutCString(name.GetCString());
1688                     return true;
1689                 }
1690             }
1691             return false;
1692
1693         case Entry::Type::FunctionNameWithArgs:
1694             {
1695                 // Print the function name with arguments in it
1696                 if (sc->function)
1697                 {
1698                     ExecutionContextScope *exe_scope = exe_ctx ? exe_ctx->GetBestExecutionContextScope() : NULL;
1699                     const char *cstr = sc->function->GetName().AsCString (NULL);
1700                     if (cstr)
1701                     {
1702                         const InlineFunctionInfo *inline_info = NULL;
1703                         VariableListSP variable_list_sp;
1704                         bool get_function_vars = true;
1705                         if (sc->block)
1706                         {
1707                             Block *inline_block = sc->block->GetContainingInlinedBlock ();
1708
1709                             if (inline_block)
1710                             {
1711                                 get_function_vars = false;
1712                                 inline_info = sc->block->GetInlinedFunctionInfo();
1713                                 if (inline_info)
1714                                     variable_list_sp = inline_block->GetBlockVariableList (true);
1715                             }
1716                         }
1717
1718                         if (get_function_vars)
1719                         {
1720                             variable_list_sp = sc->function->GetBlock(true).GetBlockVariableList (true);
1721                         }
1722
1723                         if (inline_info)
1724                         {
1725                             s.PutCString (cstr);
1726                             s.PutCString (" [inlined] ");
1727                             cstr = inline_info->GetName(sc->function->GetLanguage()).GetCString();
1728                         }
1729
1730                         VariableList args;
1731                         if (variable_list_sp)
1732                             variable_list_sp->AppendVariablesWithScope(eValueTypeVariableArgument, args);
1733                         if (args.GetSize() > 0)
1734                         {
1735                             const char *open_paren = strchr (cstr, '(');
1736                             const char *close_paren = nullptr;
1737                             const char *generic = strchr(cstr, '<');
1738                             // if before the arguments list begins there is a template sign
1739                             // then scan to the end of the generic args before you try to find
1740                             // the arguments list
1741                             if (generic && open_paren && generic < open_paren)
1742                             {
1743                                 int generic_depth = 1;
1744                                 ++generic;
1745                                 for (;
1746                                      *generic && generic_depth > 0;
1747                                      generic++)
1748                                 {
1749                                     if (*generic == '<')
1750                                         generic_depth++;
1751                                     if (*generic == '>')
1752                                         generic_depth--;
1753                                 }
1754                                 if (*generic)
1755                                     open_paren = strchr(generic, '(');
1756                                 else
1757                                     open_paren = nullptr;
1758                             }
1759                             if (open_paren)
1760                             {
1761                                 if (IsToken (open_paren, "(anonymous namespace)"))
1762                                 {
1763                                     open_paren = strchr (open_paren + strlen("(anonymous namespace)"), '(');
1764                                     if (open_paren)
1765                                         close_paren = strchr (open_paren, ')');
1766                                 }
1767                                 else
1768                                     close_paren = strchr (open_paren, ')');
1769                             }
1770
1771                             if (open_paren)
1772                                 s.Write(cstr, open_paren - cstr + 1);
1773                             else
1774                             {
1775                                 s.PutCString (cstr);
1776                                 s.PutChar ('(');
1777                             }
1778                             const size_t num_args = args.GetSize();
1779                             for (size_t arg_idx = 0; arg_idx < num_args; ++arg_idx)
1780                             {
1781                                 std::string buffer;
1782
1783                                 VariableSP var_sp (args.GetVariableAtIndex (arg_idx));
1784                                 ValueObjectSP var_value_sp (ValueObjectVariable::Create (exe_scope, var_sp));
1785                                 const char *var_representation = nullptr;
1786                                 const char *var_name = var_value_sp->GetName().GetCString();
1787                                 if (var_value_sp->GetClangType().IsAggregateType() &&
1788                                     DataVisualization::ShouldPrintAsOneLiner(*var_value_sp.get()))
1789                                 {
1790                                     static StringSummaryFormat format(TypeSummaryImpl::Flags()
1791                                                                       .SetHideItemNames(false)
1792                                                                       .SetShowMembersOneLiner(true),
1793                                                                       "");
1794                                     format.FormatObject(var_value_sp.get(), buffer, TypeSummaryOptions());
1795                                     var_representation = buffer.c_str();
1796                                 }
1797                                 else
1798                                     var_representation = var_value_sp->GetValueAsCString();
1799                                 if (arg_idx > 0)
1800                                     s.PutCString (", ");
1801                                 if (var_value_sp->GetError().Success())
1802                                 {
1803                                     if (var_representation)
1804                                         s.Printf ("%s=%s", var_name, var_representation);
1805                                     else
1806                                         s.Printf ("%s=%s at %s", var_name, var_value_sp->GetTypeName().GetCString(), var_value_sp->GetLocationAsCString());
1807                                 }
1808                                 else
1809                                     s.Printf ("%s=<unavailable>", var_name);
1810                             }
1811
1812                             if (close_paren)
1813                                 s.PutCString (close_paren);
1814                             else
1815                                 s.PutChar(')');
1816
1817                         }
1818                         else
1819                         {
1820                             s.PutCString(cstr);
1821                         }
1822                         return true;
1823                     }
1824                 }
1825                 else if (sc->symbol)
1826                 {
1827                     const char *cstr = sc->symbol->GetName().AsCString (NULL);
1828                     if (cstr)
1829                     {
1830                         s.PutCString(cstr);
1831                         return true;
1832                     }
1833                 }
1834             }
1835             return false;
1836
1837         case Entry::Type::FunctionAddrOffset:
1838             if (addr)
1839             {
1840                 if (DumpAddressOffsetFromFunction (s, sc, exe_ctx, *addr, false, false, false))
1841                     return true;
1842             }
1843             return false;
1844
1845         case Entry::Type::FunctionAddrOffsetConcrete:
1846             if (addr)
1847             {
1848                 if (DumpAddressOffsetFromFunction (s, sc, exe_ctx, *addr, true, true, true))
1849                     return true;
1850             }
1851             return false;
1852
1853         case Entry::Type::FunctionLineOffset:
1854             if (DumpAddressOffsetFromFunction (s, sc, exe_ctx, sc->line_entry.range.GetBaseAddress(), false, false, false))
1855                 return true;
1856             return false;
1857
1858         case Entry::Type::FunctionPCOffset:
1859             if (exe_ctx)
1860             {
1861                 StackFrame *frame = exe_ctx->GetFramePtr();
1862                 if (frame)
1863                 {
1864                     if (DumpAddressOffsetFromFunction (s, sc, exe_ctx, frame->GetFrameCodeAddress(), false, false, false))
1865                         return true;
1866                 }
1867             }
1868             return false;
1869
1870         case Entry::Type::FunctionChanged:
1871             return function_changed == true;
1872
1873         case Entry::Type::FunctionInitial:
1874             return initial_function == true;
1875
1876         case Entry::Type::LineEntryFile:
1877             if (sc && sc->line_entry.IsValid())
1878             {
1879                 Module *module = sc->module_sp.get();
1880                 if (module)
1881                 {
1882                     if (DumpFile(s, sc->line_entry.file, (FileKind)entry.number))
1883                         return true;
1884                 }
1885             }
1886             return false;
1887
1888         case Entry::Type::LineEntryLineNumber:
1889             if (sc && sc->line_entry.IsValid())
1890             {
1891                 const char *format = "%" PRIu32;
1892                 if (!entry.printf_format.empty())
1893                     format = entry.printf_format.c_str();
1894                 s.Printf(format, sc->line_entry.line);
1895                 return true;
1896             }
1897             return false;
1898
1899         case Entry::Type::LineEntryStartAddress:
1900         case Entry::Type::LineEntryEndAddress:
1901             if (sc && sc->line_entry.range.GetBaseAddress().IsValid())
1902             {
1903                 Address addr = sc->line_entry.range.GetBaseAddress();
1904
1905                 if (entry.type == Entry::Type::LineEntryEndAddress)
1906                     addr.Slide(sc->line_entry.range.GetByteSize());
1907                 if (DumpAddress(s, sc, exe_ctx, addr, false))
1908                     return true;
1909             }
1910             return false;
1911
1912         case Entry::Type::CurrentPCArrow:
1913             if (addr && exe_ctx && exe_ctx->GetFramePtr())
1914             {
1915                 RegisterContextSP reg_ctx = exe_ctx->GetFramePtr()->GetRegisterContextSP();
1916                 if (reg_ctx.get())
1917                 {
1918                     addr_t pc_loadaddr = reg_ctx->GetPC();
1919                     if (pc_loadaddr != LLDB_INVALID_ADDRESS)
1920                     {
1921                         Address pc;
1922                         pc.SetLoadAddress (pc_loadaddr, exe_ctx->GetTargetPtr());
1923                         if (pc == *addr)
1924                         {
1925                             s.Printf ("-> ");
1926                             return true;
1927                         }
1928                     }
1929                 }
1930                 s.Printf("   ");
1931                 return true;
1932             }
1933             return false;
1934     }
1935     return false;
1936 }
1937
1938 static bool
1939 DumpCommaSeparatedChildEntryNames (Stream &s, const FormatEntity::Entry::Definition *parent)
1940 {
1941     if (parent->children)
1942     {
1943         const size_t n = parent->num_children;
1944         for (size_t i=0; i<n; ++i)
1945         {
1946             if (i > 0)
1947                 s.PutCString(", ");
1948             s.Printf ("\"%s\"", parent->children[i].name);
1949         }
1950         return true;
1951     }
1952     return false;
1953 }
1954
1955
1956 static Error
1957 ParseEntry (const llvm::StringRef &format_str,
1958             const FormatEntity::Entry::Definition *parent,
1959             FormatEntity::Entry &entry)
1960 {
1961     Error error;
1962
1963     const size_t sep_pos = format_str.find_first_of(".[:");
1964     const char sep_char = (sep_pos == llvm::StringRef::npos) ? '\0' : format_str[sep_pos];
1965     llvm::StringRef key = format_str.substr(0, sep_pos);
1966
1967     const size_t n = parent->num_children;
1968     for (size_t i=0; i<n; ++i)
1969     {
1970         const FormatEntity::Entry::Definition *entry_def = parent->children + i;
1971         if (key.equals(entry_def->name) || entry_def->name[0] == '*')
1972         {
1973             llvm::StringRef value;
1974             if (sep_char)
1975                 value = format_str.substr(sep_pos + (entry_def->keep_separator ? 0 : 1));
1976             switch (entry_def->type)
1977             {
1978                 case FormatEntity::Entry::Type::ParentString:
1979                     entry.string = std::move(format_str.str());
1980                     return error; // Success
1981
1982                 case FormatEntity::Entry::Type::ParentNumber:
1983                     entry.number = entry_def->data;
1984                     return error; // Success
1985
1986                 case FormatEntity::Entry::Type::InsertString:
1987                     entry.type = entry_def->type;
1988                     entry.string = entry_def->string;
1989                     return error; // Success
1990
1991                 default:
1992                     entry.type = entry_def->type;
1993                     break;
1994             }
1995
1996             if (value.empty())
1997             {
1998                 if (entry_def->type == FormatEntity::Entry::Type::Invalid)
1999                 {
2000                     if (entry_def->children)
2001                     {
2002                         StreamString error_strm;
2003                         error_strm.Printf("'%s' can't be specified on its own, you must access one of its children: ", entry_def->name);
2004                         DumpCommaSeparatedChildEntryNames (error_strm, entry_def);
2005                         error.SetErrorStringWithFormat("%s", error_strm.GetString().c_str());
2006                     }
2007                     else if (sep_char == ':')
2008                     {
2009                         // Any value whose separator is a with a ':' means this value has a string argument
2010                         // that needs to be stored in the entry (like "${script.var:}").
2011                         // In this case the string value is the empty string which is ok.
2012                     }
2013                     else
2014                     {
2015                         error.SetErrorStringWithFormat("%s", "invalid entry definitions");
2016                     }
2017                 }
2018             }
2019             else
2020             {
2021                 if (entry_def->children)
2022                 {
2023                     error = ParseEntry (value, entry_def, entry);
2024                 }
2025                 else if (sep_char == ':')
2026                 {
2027                     // Any value whose separator is a with a ':' means this value has a string argument
2028                     // that needs to be stored in the entry (like "${script.var:modulename.function}")
2029                     entry.string = std::move(value.str());
2030                 }
2031                 else
2032                 {
2033                     error.SetErrorStringWithFormat("'%s' followed by '%s' but it has no children",
2034                                                    key.str().c_str(),
2035                                                    value.str().c_str());
2036                 }
2037             }
2038             return error;
2039         }
2040     }
2041     StreamString error_strm;
2042     if (parent->type == FormatEntity::Entry::Type::Root)
2043         error_strm.Printf("invalid top level item '%s'. Valid top level items are: ", key.str().c_str());
2044     else
2045         error_strm.Printf("invalid member '%s' in '%s'. Valid members are: ", key.str().c_str(), parent->name);
2046     DumpCommaSeparatedChildEntryNames (error_strm, parent);
2047     error.SetErrorStringWithFormat("%s", error_strm.GetString().c_str());
2048     return error;
2049 }
2050
2051
2052 static const FormatEntity::Entry::Definition *
2053 FindEntry (const llvm::StringRef &format_str, const FormatEntity::Entry::Definition *parent, llvm::StringRef &remainder)
2054 {
2055     Error error;
2056     
2057     std::pair<llvm::StringRef, llvm::StringRef> p = format_str.split('.');
2058     const size_t n = parent->num_children;
2059     for (size_t i=0; i<n; ++i)
2060     {
2061         const FormatEntity::Entry::Definition *entry_def = parent->children + i;
2062         if (p.first.equals(entry_def->name) || entry_def->name[0] == '*')
2063         {
2064             if (p.second.empty())
2065             {
2066                 if (format_str.back() == '.')
2067                     remainder = format_str.drop_front(format_str.size() - 1);
2068                 else
2069                     remainder = llvm::StringRef(); // Exact match
2070                 return entry_def;
2071             }
2072             else
2073             {
2074                 if (entry_def->children)
2075                 {
2076                     return FindEntry (p.second, entry_def, remainder);
2077                 }
2078                 else
2079                 {
2080                     remainder = p.second;
2081                     return entry_def;
2082                 }
2083             }
2084         }
2085     }
2086     remainder = format_str;
2087     return parent;
2088 }
2089
2090 Error
2091 FormatEntity::ParseInternal (llvm::StringRef &format, Entry &parent_entry, uint32_t depth)
2092 {
2093     Error error;
2094     while (!format.empty() && error.Success())
2095     {
2096         const size_t non_special_chars = format.find_first_of("${}\\");
2097
2098         if (non_special_chars == llvm::StringRef::npos)
2099         {
2100             // No special characters, just string bytes so add them and we are done
2101             parent_entry.AppendText(format);
2102             return error;
2103         }
2104
2105         if (non_special_chars > 0)
2106         {
2107             // We have a special character, so add all characters before these as a plain string
2108             parent_entry.AppendText(format.substr(0,non_special_chars));
2109             format = format.drop_front(non_special_chars);
2110         }
2111
2112         switch (format[0])
2113         {
2114             case '\0':
2115                 return error;
2116
2117             case '{':
2118                 {
2119                     format = format.drop_front(); // Skip the '{'
2120                     Entry scope_entry(Entry::Type::Scope);
2121                     error = FormatEntity::ParseInternal (format, scope_entry, depth+1);
2122                     if (error.Fail())
2123                         return error;
2124                     parent_entry.AppendEntry(std::move(scope_entry));
2125                 }
2126                 break;
2127
2128             case '}':
2129                 if (depth == 0)
2130                     error.SetErrorString("unmatched '}' character");
2131                 else
2132                     format = format.drop_front(); // Skip the '}' as we are at the end of the scope
2133                 return error;
2134
2135             case '\\':
2136                 {
2137                     format = format.drop_front(); // Skip the '\' character
2138                     if (format.empty())
2139                     {
2140                         error.SetErrorString("'\\' character was not followed by another character");
2141                         return error;
2142                     }
2143
2144                     const char desens_char = format[0];
2145                     format = format.drop_front(); // Skip the desensitized char character
2146                     switch (desens_char)
2147                     {
2148                         case 'a': parent_entry.AppendChar('\a'); break;
2149                         case 'b': parent_entry.AppendChar('\b'); break;
2150                         case 'f': parent_entry.AppendChar('\f'); break;
2151                         case 'n': parent_entry.AppendChar('\n'); break;
2152                         case 'r': parent_entry.AppendChar('\r'); break;
2153                         case 't': parent_entry.AppendChar('\t'); break;
2154                         case 'v': parent_entry.AppendChar('\v'); break;
2155                         case '\'': parent_entry.AppendChar('\''); break;
2156                         case '\\': parent_entry.AppendChar('\\'); break;
2157                         case '0':
2158                             // 1 to 3 octal chars
2159                         {
2160                             // Make a string that can hold onto the initial zero char,
2161                             // up to 3 octal digits, and a terminating NULL.
2162                             char oct_str[5] = { 0, 0, 0, 0, 0 };
2163
2164                             int i;
2165                             for (i=0; (format[i] >= '0' && format[i] <= '7') && i<4; ++i)
2166                                 oct_str[i] = format[i];
2167
2168                             // We don't want to consume the last octal character since
2169                             // the main for loop will do this for us, so we advance p by
2170                             // one less than i (even if i is zero)
2171                             format = format.drop_front(i);
2172                             unsigned long octal_value = ::strtoul (oct_str, NULL, 8);
2173                             if (octal_value <= UINT8_MAX)
2174                             {
2175                                 parent_entry.AppendChar((char)octal_value);
2176                             }
2177                             else
2178                             {
2179                                 error.SetErrorString("octal number is larger than a single byte");
2180                                 return error;
2181                             }
2182                         }
2183                             break;
2184
2185                         case 'x':
2186                             // hex number in the format
2187                             if (isxdigit(format[0]))
2188                             {
2189                                 // Make a string that can hold onto two hex chars plus a
2190                                 // NULL terminator
2191                                 char hex_str[3] = { 0,0,0 };
2192                                 hex_str[0] = format[0];
2193
2194                                 format = format.drop_front();
2195
2196                                 if (isxdigit(format[0]))
2197                                 {
2198                                     hex_str[1] = format[0];
2199                                     format = format.drop_front();
2200                                 }
2201
2202                                 unsigned long hex_value = strtoul (hex_str, NULL, 16);
2203                                 if (hex_value <= UINT8_MAX)
2204                                 {
2205                                     parent_entry.AppendChar((char)hex_value);
2206                                 }
2207                                 else
2208                                 {
2209                                     error.SetErrorString("hex number is larger than a single byte");
2210                                     return error;
2211                                 }
2212                             }
2213                             else
2214                             {
2215                                 parent_entry.AppendChar(desens_char);
2216                             }
2217                             break;
2218
2219                         default:
2220                             // Just desensitize any other character by just printing what
2221                             // came after the '\'
2222                             parent_entry.AppendChar(desens_char);
2223                             break;
2224                     }
2225                 }
2226                 break;
2227
2228             case '$':
2229                 if (format.size() == 1)
2230                 {
2231                     // '$' at the end of a format string, just print the '$'
2232                     parent_entry.AppendText("$");
2233                 }
2234                 else
2235                 {
2236                     format = format.drop_front(); // Skip the '$'
2237
2238                     if (format[0] == '{')
2239                     {
2240                         format = format.drop_front(); // Skip the '{'
2241
2242                         llvm::StringRef variable, variable_format;
2243                         error = FormatEntity::ExtractVariableInfo (format, variable, variable_format);
2244                         if (error.Fail())
2245                             return error;
2246                         bool verify_is_thread_id = false;
2247                         Entry entry;
2248                         if (!variable_format.empty())
2249                         {
2250                             entry.printf_format = std::move(variable_format.str());
2251                             
2252                             // If the format contains a '%' we are going to assume this is
2253                             // a printf style format. So if you want to format your thread ID
2254                             // using "0x%llx" you can use:
2255                             // ${thread.id%0x%llx}
2256                             //
2257                             // If there is no '%' in the format, then it is assumed to be a
2258                             // LLDB format name, or one of the extended formats specified in
2259                             // the switch statement below.
2260                             
2261                             if (entry.printf_format.find('%') == std::string::npos)
2262                             {
2263                                 bool clear_printf = false;
2264
2265                                 if (FormatManager::GetFormatFromCString(entry.printf_format.c_str(),
2266                                                                         false,
2267                                                                         entry.fmt))
2268                                 {
2269                                     // We have an LLDB format, so clear the printf format
2270                                     clear_printf = true;
2271                                 }
2272                                 else if (entry.printf_format.size() == 1)
2273                                 {
2274                                     switch (entry.printf_format[0])
2275                                     {
2276                                         case '@':             // if this is an @ sign, print ObjC description
2277                                             entry.number = ValueObject::eValueObjectRepresentationStyleLanguageSpecific;
2278                                             clear_printf = true;
2279                                             break;
2280                                         case 'V': // if this is a V, print the value using the default format
2281                                             entry.number = ValueObject::eValueObjectRepresentationStyleValue;
2282                                             clear_printf = true;
2283                                             break;
2284                                         case 'L': // if this is an L, print the location of the value
2285                                             entry.number = ValueObject::eValueObjectRepresentationStyleLocation;
2286                                             clear_printf = true;
2287                                             break;
2288                                         case 'S': // if this is an S, print the summary after all
2289                                             entry.number = ValueObject::eValueObjectRepresentationStyleSummary;
2290                                             clear_printf = true;
2291                                             break;
2292                                         case '#': // if this is a '#', print the number of children
2293                                             entry.number = ValueObject::eValueObjectRepresentationStyleChildrenCount;
2294                                             clear_printf = true;
2295                                             break;
2296                                         case 'T': // if this is a 'T', print the type
2297                                             entry.number = ValueObject::eValueObjectRepresentationStyleType;
2298                                             clear_printf = true;
2299                                             break;
2300                                         case 'N': // if this is a 'N', print the name
2301                                             entry.number = ValueObject::eValueObjectRepresentationStyleName;
2302                                             clear_printf = true;
2303                                             break;
2304                                         case '>': // if this is a '>', print the expression path
2305                                             entry.number = ValueObject::eValueObjectRepresentationStyleExpressionPath;
2306                                             clear_printf = true;
2307                                             break;
2308                                         default:
2309                                             error.SetErrorStringWithFormat("invalid format: '%s'", entry.printf_format.c_str());
2310                                             return error;
2311                                     }
2312                                 }
2313                                 else if (FormatManager::GetFormatFromCString(entry.printf_format.c_str(),
2314                                                                              true,
2315                                                                              entry.fmt))
2316                                 {
2317                                     clear_printf = true;
2318                                 }
2319                                 else if (entry.printf_format == "tid")
2320                                 {
2321                                     verify_is_thread_id = true;
2322                                 }
2323                                 else
2324                                 {
2325                                     error.SetErrorStringWithFormat("invalid format: '%s'", entry.printf_format.c_str());
2326                                     return error;
2327                                 }
2328                                 
2329                                 // Our format string turned out to not be a printf style format
2330                                 // so lets clear the string
2331                                 if (clear_printf)
2332                                     entry.printf_format.clear();
2333                             }
2334                         }
2335
2336                         // Check for dereferences
2337                         if (variable[0] == '*')
2338                         {
2339                             entry.deref = true;
2340                             variable = variable.drop_front();
2341                         }
2342
2343                         error = ParseEntry (variable, &g_root, entry);
2344                         if (error.Fail())
2345                             return error;
2346
2347                         if (verify_is_thread_id)
2348                         {
2349                             if (entry.type != Entry::Type::ThreadID &&
2350                                 entry.type != Entry::Type::ThreadProtocolID)
2351                             {
2352                                 error.SetErrorString("the 'tid' format can only be used on ${thread.id} and ${thread.protocol_id}");
2353                             }
2354                         }
2355
2356                         switch (entry.type)
2357                         {
2358                             case Entry::Type::Variable:
2359                             case Entry::Type::VariableSynthetic:
2360                                 if (entry.number == 0)
2361                                 {
2362                                     if (entry.string.empty())
2363                                         entry.number = ValueObject::eValueObjectRepresentationStyleValue;
2364                                     else
2365                                         entry.number = ValueObject::eValueObjectRepresentationStyleSummary;
2366                                 }
2367                                 break;
2368                             default:
2369                                 // Make sure someone didn't try to dereference anything but ${var} or ${svar}
2370                                 if (entry.deref)
2371                                 {
2372                                     error.SetErrorStringWithFormat("${%s} can't be dereferenced, only ${var} and ${svar} can.", variable.str().c_str());
2373                                     return error;
2374                                 }
2375                         }
2376                         // Check if this entry just wants to insert a constant string
2377                         // value into the parent_entry, if so, insert the string with
2378                         // AppendText, else append the entry to the parent_entry.
2379                         if (entry.type == Entry::Type::InsertString)
2380                             parent_entry.AppendText(entry.string.c_str());
2381                         else
2382                             parent_entry.AppendEntry(std::move(entry));
2383                     }
2384                 }
2385                 break;
2386         }
2387     }
2388     return error;
2389 }
2390
2391
2392 Error
2393 FormatEntity::ExtractVariableInfo (llvm::StringRef &format_str, llvm::StringRef &variable_name, llvm::StringRef &variable_format)
2394 {
2395     Error error;
2396     variable_name = llvm::StringRef();
2397     variable_format = llvm::StringRef();
2398
2399     const size_t paren_pos = format_str.find_first_of('}');
2400     if (paren_pos != llvm::StringRef::npos)
2401     {
2402         const size_t percent_pos = format_str.find_first_of('%');
2403         if (percent_pos < paren_pos)
2404         {
2405             if (percent_pos > 0)
2406             {
2407                 if (percent_pos > 1)
2408                     variable_name = format_str.substr(0, percent_pos);
2409                 variable_format = format_str.substr(percent_pos + 1, paren_pos - (percent_pos + 1));
2410             }
2411         }
2412         else
2413         {
2414             variable_name = format_str.substr(0, paren_pos);
2415         }
2416         // Strip off elements and the formatting and the trailing '}'
2417         format_str = format_str.substr(paren_pos + 1);
2418     }
2419     else
2420     {
2421         error.SetErrorStringWithFormat("missing terminating '}' character for '${%s'", format_str.str().c_str());
2422     }
2423     return error;
2424 }
2425
2426 bool
2427 FormatEntity::FormatFileSpec (const FileSpec &file_spec, Stream &s, llvm::StringRef variable_name, llvm::StringRef variable_format)
2428 {
2429     if (variable_name.empty() || variable_name.equals(".fullpath"))
2430     {
2431         file_spec.Dump(&s);
2432         return true;
2433     }
2434     else if (variable_name.equals(".basename"))
2435     {
2436         s.PutCString(file_spec.GetFilename().AsCString(""));
2437         return true;
2438     }
2439     else if (variable_name.equals(".dirname"))
2440     {
2441         s.PutCString(file_spec.GetFilename().AsCString(""));
2442         return true;
2443     }
2444     return false;
2445 }
2446
2447 static std::string
2448 MakeMatch (const llvm::StringRef &prefix, const char *suffix)
2449 {
2450     std::string match(prefix.str());
2451     match.append(suffix);
2452     return std::move(match);
2453 }
2454
2455 static void
2456 AddMatches (const FormatEntity::Entry::Definition *def,
2457             const llvm::StringRef &prefix,
2458             const llvm::StringRef &match_prefix,
2459             StringList &matches)
2460 {
2461     const size_t n = def->num_children;
2462     if (n > 0)
2463     {
2464         for (size_t i=0; i<n; ++i)
2465         {
2466             std::string match = std::move(prefix.str());
2467             if (match_prefix.empty())
2468                 matches.AppendString(MakeMatch (prefix, def->children[i].name));
2469             else if (strncmp(def->children[i].name, match_prefix.data(), match_prefix.size()) == 0)
2470                 matches.AppendString(MakeMatch (prefix, def->children[i].name + match_prefix.size()));
2471         }
2472     }
2473 }
2474 size_t
2475 FormatEntity::AutoComplete (const char *s,
2476                             int match_start_point,
2477                             int max_return_elements,
2478                             bool &word_complete,
2479                             StringList &matches)
2480 {
2481     word_complete = false;
2482     llvm::StringRef str(s + match_start_point);
2483     matches.Clear();
2484     
2485     const size_t dollar_pos = str.rfind('$');
2486     if (dollar_pos != llvm::StringRef::npos)
2487     {
2488         // Hitting TAB after $ at the end of the string add a "{"
2489         if (dollar_pos == str.size() - 1)
2490         {
2491             std::string match = std::move(str.str());
2492             match.append("{");
2493             matches.AppendString(std::move(match));
2494         }
2495         else if (str[dollar_pos + 1] == '{')
2496         {
2497             const size_t close_pos = str.find('}', dollar_pos + 2);
2498             if (close_pos == llvm::StringRef::npos)
2499             {
2500                 const size_t format_pos = str.find('%', dollar_pos + 2);
2501                 if (format_pos == llvm::StringRef::npos)
2502                 {
2503                     llvm::StringRef partial_variable (str.substr(dollar_pos + 2));
2504                     if (partial_variable.empty())
2505                     {
2506                         // Suggest all top level entites as we are just past "${"
2507                         AddMatches(&g_root, str, llvm::StringRef(), matches);
2508                     }
2509                     else
2510                     {
2511                         // We have a partially specified variable, find it
2512                         llvm::StringRef remainder;
2513                         const FormatEntity::Entry::Definition* entry_def = FindEntry (partial_variable, &g_root, remainder);
2514                         if (entry_def)
2515                         {
2516                             const size_t n = entry_def->num_children;
2517
2518                             if (remainder.empty())
2519                             {
2520                                 // Exact match
2521                                 if (n > 0)
2522                                 {
2523                                     // "${thread.info" <TAB>
2524                                     matches.AppendString(std::move(MakeMatch (str, ".")));
2525                                 }
2526                                 else
2527                                 {
2528                                     // "${thread.id" <TAB>
2529                                     matches.AppendString(std::move(MakeMatch (str, "}")));
2530                                     word_complete = true;
2531                                 }
2532                             }
2533                             else if (remainder.equals("."))
2534                             {
2535                                 // "${thread." <TAB>
2536                                 AddMatches(entry_def, str, llvm::StringRef(), matches);
2537                             }
2538                             else
2539                             {
2540                                 // We have a partial match
2541                                 // "${thre" <TAB>
2542                                 AddMatches(entry_def, str, remainder, matches);
2543                             }
2544                         }
2545                     }
2546                 }
2547             }
2548         }
2549     }
2550     return matches.GetSize();
2551 }