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