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