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