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