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