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