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