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