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