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