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