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