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