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