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