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