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 format = "%" PRIu64; 1212 } 1213 } else { 1214 format = entry.printf_format.c_str(); 1215 } 1216 } 1217 s.Printf(format, thread->GetID()); 1218 return true; 1219 } 1220 } 1221 return false; 1222 1223 case Entry::Type::ThreadProtocolID: 1224 if (exe_ctx) { 1225 Thread *thread = exe_ctx->GetThreadPtr(); 1226 if (thread) { 1227 const char *format = "0x%4.4" PRIx64; 1228 if (!entry.printf_format.empty()) 1229 format = entry.printf_format.c_str(); 1230 s.Printf(format, thread->GetProtocolID()); 1231 return true; 1232 } 1233 } 1234 return false; 1235 1236 case Entry::Type::ThreadIndexID: 1237 if (exe_ctx) { 1238 Thread *thread = exe_ctx->GetThreadPtr(); 1239 if (thread) { 1240 const char *format = "%" PRIu32; 1241 if (!entry.printf_format.empty()) 1242 format = entry.printf_format.c_str(); 1243 s.Printf(format, thread->GetIndexID()); 1244 return true; 1245 } 1246 } 1247 return false; 1248 1249 case Entry::Type::ThreadName: 1250 if (exe_ctx) { 1251 Thread *thread = exe_ctx->GetThreadPtr(); 1252 if (thread) { 1253 const char *cstr = thread->GetName(); 1254 if (cstr && cstr[0]) { 1255 s.PutCString(cstr); 1256 return true; 1257 } 1258 } 1259 } 1260 return false; 1261 1262 case Entry::Type::ThreadQueue: 1263 if (exe_ctx) { 1264 Thread *thread = exe_ctx->GetThreadPtr(); 1265 if (thread) { 1266 const char *cstr = thread->GetQueueName(); 1267 if (cstr && cstr[0]) { 1268 s.PutCString(cstr); 1269 return true; 1270 } 1271 } 1272 } 1273 return false; 1274 1275 case Entry::Type::ThreadStopReason: 1276 if (exe_ctx) { 1277 if (Thread *thread = exe_ctx->GetThreadPtr()) { 1278 std::string stop_description = thread->GetStopDescription(); 1279 if (!stop_description.empty()) { 1280 s.PutCString(stop_description); 1281 return true; 1282 } 1283 } 1284 } 1285 return false; 1286 1287 case Entry::Type::ThreadStopReasonRaw: 1288 if (exe_ctx) { 1289 if (Thread *thread = exe_ctx->GetThreadPtr()) { 1290 std::string stop_description = thread->GetStopDescriptionRaw(); 1291 if (!stop_description.empty()) { 1292 s.PutCString(stop_description); 1293 return true; 1294 } 1295 } 1296 } 1297 return false; 1298 1299 case Entry::Type::ThreadReturnValue: 1300 if (exe_ctx) { 1301 Thread *thread = exe_ctx->GetThreadPtr(); 1302 if (thread) { 1303 StopInfoSP stop_info_sp = thread->GetStopInfo(); 1304 if (stop_info_sp && stop_info_sp->IsValid()) { 1305 ValueObjectSP return_valobj_sp = 1306 StopInfo::GetReturnValueObject(stop_info_sp); 1307 if (return_valobj_sp) { 1308 return_valobj_sp->Dump(s); 1309 return true; 1310 } 1311 } 1312 } 1313 } 1314 return false; 1315 1316 case Entry::Type::ThreadCompletedExpression: 1317 if (exe_ctx) { 1318 Thread *thread = exe_ctx->GetThreadPtr(); 1319 if (thread) { 1320 StopInfoSP stop_info_sp = thread->GetStopInfo(); 1321 if (stop_info_sp && stop_info_sp->IsValid()) { 1322 ExpressionVariableSP expression_var_sp = 1323 StopInfo::GetExpressionVariable(stop_info_sp); 1324 if (expression_var_sp && expression_var_sp->GetValueObject()) { 1325 expression_var_sp->GetValueObject()->Dump(s); 1326 return true; 1327 } 1328 } 1329 } 1330 } 1331 return false; 1332 1333 case Entry::Type::ScriptThread: 1334 if (exe_ctx) { 1335 Thread *thread = exe_ctx->GetThreadPtr(); 1336 if (thread) 1337 return RunScriptFormatKeyword(s, sc, exe_ctx, thread, 1338 entry.string.c_str()); 1339 } 1340 return false; 1341 1342 case Entry::Type::ThreadInfo: 1343 if (exe_ctx) { 1344 Thread *thread = exe_ctx->GetThreadPtr(); 1345 if (thread) { 1346 StructuredData::ObjectSP object_sp = thread->GetExtendedInfo(); 1347 if (object_sp && 1348 object_sp->GetType() == eStructuredDataTypeDictionary) { 1349 if (FormatThreadExtendedInfoRecurse(entry, object_sp, sc, exe_ctx, s)) 1350 return true; 1351 } 1352 } 1353 } 1354 return false; 1355 1356 case Entry::Type::TargetArch: 1357 if (exe_ctx) { 1358 Target *target = exe_ctx->GetTargetPtr(); 1359 if (target) { 1360 const ArchSpec &arch = target->GetArchitecture(); 1361 if (arch.IsValid()) { 1362 s.PutCString(arch.GetArchitectureName()); 1363 return true; 1364 } 1365 } 1366 } 1367 return false; 1368 1369 case Entry::Type::ScriptTarget: 1370 if (exe_ctx) { 1371 Target *target = exe_ctx->GetTargetPtr(); 1372 if (target) 1373 return RunScriptFormatKeyword(s, sc, exe_ctx, target, 1374 entry.string.c_str()); 1375 } 1376 return false; 1377 1378 case Entry::Type::ModuleFile: 1379 if (sc) { 1380 Module *module = sc->module_sp.get(); 1381 if (module) { 1382 if (DumpFile(s, module->GetFileSpec(), (FileKind)entry.number)) 1383 return true; 1384 } 1385 } 1386 return false; 1387 1388 case Entry::Type::File: 1389 if (sc) { 1390 CompileUnit *cu = sc->comp_unit; 1391 if (cu) { 1392 if (DumpFile(s, cu->GetPrimaryFile(), (FileKind)entry.number)) 1393 return true; 1394 } 1395 } 1396 return false; 1397 1398 case Entry::Type::Lang: 1399 if (sc) { 1400 CompileUnit *cu = sc->comp_unit; 1401 if (cu) { 1402 const char *lang_name = 1403 Language::GetNameForLanguageType(cu->GetLanguage()); 1404 if (lang_name) { 1405 s.PutCString(lang_name); 1406 return true; 1407 } 1408 } 1409 } 1410 return false; 1411 1412 case Entry::Type::FrameIndex: 1413 if (exe_ctx) { 1414 StackFrame *frame = exe_ctx->GetFramePtr(); 1415 if (frame) { 1416 const char *format = "%" PRIu32; 1417 if (!entry.printf_format.empty()) 1418 format = entry.printf_format.c_str(); 1419 s.Printf(format, frame->GetFrameIndex()); 1420 return true; 1421 } 1422 } 1423 return false; 1424 1425 case Entry::Type::FrameRegisterPC: 1426 if (exe_ctx) { 1427 StackFrame *frame = exe_ctx->GetFramePtr(); 1428 if (frame) { 1429 const Address &pc_addr = frame->GetFrameCodeAddress(); 1430 if (pc_addr.IsValid()) { 1431 if (DumpAddressAndContent(s, sc, exe_ctx, pc_addr, false)) 1432 return true; 1433 } 1434 } 1435 } 1436 return false; 1437 1438 case Entry::Type::FrameRegisterSP: 1439 if (exe_ctx) { 1440 StackFrame *frame = exe_ctx->GetFramePtr(); 1441 if (frame) { 1442 if (DumpRegister(s, frame, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, 1443 (lldb::Format)entry.number)) 1444 return true; 1445 } 1446 } 1447 return false; 1448 1449 case Entry::Type::FrameRegisterFP: 1450 if (exe_ctx) { 1451 StackFrame *frame = exe_ctx->GetFramePtr(); 1452 if (frame) { 1453 if (DumpRegister(s, frame, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FP, 1454 (lldb::Format)entry.number)) 1455 return true; 1456 } 1457 } 1458 return false; 1459 1460 case Entry::Type::FrameRegisterFlags: 1461 if (exe_ctx) { 1462 StackFrame *frame = exe_ctx->GetFramePtr(); 1463 if (frame) { 1464 if (DumpRegister(s, frame, eRegisterKindGeneric, 1465 LLDB_REGNUM_GENERIC_FLAGS, (lldb::Format)entry.number)) 1466 return true; 1467 } 1468 } 1469 return false; 1470 1471 case Entry::Type::FrameNoDebug: 1472 if (exe_ctx) { 1473 StackFrame *frame = exe_ctx->GetFramePtr(); 1474 if (frame) { 1475 return !frame->HasDebugInformation(); 1476 } 1477 } 1478 return true; 1479 1480 case Entry::Type::FrameRegisterByName: 1481 if (exe_ctx) { 1482 StackFrame *frame = exe_ctx->GetFramePtr(); 1483 if (frame) { 1484 if (DumpRegister(s, frame, entry.string.c_str(), 1485 (lldb::Format)entry.number)) 1486 return true; 1487 } 1488 } 1489 return false; 1490 1491 case Entry::Type::FrameIsArtificial: { 1492 if (exe_ctx) 1493 if (StackFrame *frame = exe_ctx->GetFramePtr()) 1494 return frame->IsArtificial(); 1495 return false; 1496 } 1497 1498 case Entry::Type::ScriptFrame: 1499 if (exe_ctx) { 1500 StackFrame *frame = exe_ctx->GetFramePtr(); 1501 if (frame) 1502 return RunScriptFormatKeyword(s, sc, exe_ctx, frame, 1503 entry.string.c_str()); 1504 } 1505 return false; 1506 1507 case Entry::Type::FunctionID: 1508 if (sc) { 1509 if (sc->function) { 1510 s.Printf("function{0x%8.8" PRIx64 "}", sc->function->GetID()); 1511 return true; 1512 } else if (sc->symbol) { 1513 s.Printf("symbol[%u]", sc->symbol->GetID()); 1514 return true; 1515 } 1516 } 1517 return false; 1518 1519 case Entry::Type::FunctionDidChange: 1520 return function_changed; 1521 1522 case Entry::Type::FunctionInitialFunction: 1523 return initial_function; 1524 1525 case Entry::Type::FunctionName: { 1526 Language *language_plugin = nullptr; 1527 bool language_plugin_handled = false; 1528 StreamString ss; 1529 if (sc->function) 1530 language_plugin = Language::FindPlugin(sc->function->GetLanguage()); 1531 else if (sc->symbol) 1532 language_plugin = Language::FindPlugin(sc->symbol->GetLanguage()); 1533 if (language_plugin) { 1534 language_plugin_handled = language_plugin->GetFunctionDisplayName( 1535 sc, exe_ctx, Language::FunctionNameRepresentation::eName, ss); 1536 } 1537 if (language_plugin_handled) { 1538 s << ss.GetString(); 1539 return true; 1540 } else { 1541 const char *name = nullptr; 1542 if (sc->function) 1543 name = sc->function->GetName().AsCString(nullptr); 1544 else if (sc->symbol) 1545 name = sc->symbol->GetName().AsCString(nullptr); 1546 if (name) { 1547 s.PutCString(name); 1548 1549 if (sc->block) { 1550 Block *inline_block = sc->block->GetContainingInlinedBlock(); 1551 if (inline_block) { 1552 const InlineFunctionInfo *inline_info = 1553 sc->block->GetInlinedFunctionInfo(); 1554 if (inline_info) { 1555 s.PutCString(" [inlined] "); 1556 inline_info->GetName().Dump(&s); 1557 } 1558 } 1559 } 1560 return true; 1561 } 1562 } 1563 } 1564 return false; 1565 1566 case Entry::Type::FunctionNameNoArgs: { 1567 Language *language_plugin = nullptr; 1568 bool language_plugin_handled = false; 1569 StreamString ss; 1570 if (sc->function) 1571 language_plugin = Language::FindPlugin(sc->function->GetLanguage()); 1572 else if (sc->symbol) 1573 language_plugin = Language::FindPlugin(sc->symbol->GetLanguage()); 1574 if (language_plugin) { 1575 language_plugin_handled = language_plugin->GetFunctionDisplayName( 1576 sc, exe_ctx, Language::FunctionNameRepresentation::eNameWithNoArgs, 1577 ss); 1578 } 1579 if (language_plugin_handled) { 1580 s << ss.GetString(); 1581 return true; 1582 } else { 1583 ConstString name; 1584 if (sc->function) 1585 name = sc->function->GetNameNoArguments(); 1586 else if (sc->symbol) 1587 name = sc->symbol->GetNameNoArguments(); 1588 if (name) { 1589 s.PutCString(name.GetCString()); 1590 return true; 1591 } 1592 } 1593 } 1594 return false; 1595 1596 case Entry::Type::FunctionNameWithArgs: { 1597 Language *language_plugin = nullptr; 1598 bool language_plugin_handled = false; 1599 StreamString ss; 1600 if (sc->function) 1601 language_plugin = Language::FindPlugin(sc->function->GetLanguage()); 1602 else if (sc->symbol) 1603 language_plugin = Language::FindPlugin(sc->symbol->GetLanguage()); 1604 if (language_plugin) { 1605 language_plugin_handled = language_plugin->GetFunctionDisplayName( 1606 sc, exe_ctx, Language::FunctionNameRepresentation::eNameWithArgs, ss); 1607 } 1608 if (language_plugin_handled) { 1609 s << ss.GetString(); 1610 return true; 1611 } else { 1612 // Print the function name with arguments in it 1613 if (sc->function) { 1614 ExecutionContextScope *exe_scope = 1615 exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr; 1616 const char *cstr = sc->function->GetName().AsCString(nullptr); 1617 if (cstr) { 1618 const InlineFunctionInfo *inline_info = nullptr; 1619 VariableListSP variable_list_sp; 1620 bool get_function_vars = true; 1621 if (sc->block) { 1622 Block *inline_block = sc->block->GetContainingInlinedBlock(); 1623 1624 if (inline_block) { 1625 get_function_vars = false; 1626 inline_info = sc->block->GetInlinedFunctionInfo(); 1627 if (inline_info) 1628 variable_list_sp = inline_block->GetBlockVariableList(true); 1629 } 1630 } 1631 1632 if (get_function_vars) { 1633 variable_list_sp = 1634 sc->function->GetBlock(true).GetBlockVariableList(true); 1635 } 1636 1637 if (inline_info) { 1638 s.PutCString(cstr); 1639 s.PutCString(" [inlined] "); 1640 cstr = inline_info->GetName().GetCString(); 1641 } 1642 1643 VariableList args; 1644 if (variable_list_sp) 1645 variable_list_sp->AppendVariablesWithScope( 1646 eValueTypeVariableArgument, args); 1647 if (args.GetSize() > 0) { 1648 const char *open_paren = strchr(cstr, '('); 1649 const char *close_paren = nullptr; 1650 const char *generic = strchr(cstr, '<'); 1651 // if before the arguments list begins there is a template sign 1652 // then scan to the end of the generic args before you try to find 1653 // the arguments list 1654 if (generic && open_paren && generic < open_paren) { 1655 int generic_depth = 1; 1656 ++generic; 1657 for (; *generic && generic_depth > 0; generic++) { 1658 if (*generic == '<') 1659 generic_depth++; 1660 if (*generic == '>') 1661 generic_depth--; 1662 } 1663 if (*generic) 1664 open_paren = strchr(generic, '('); 1665 else 1666 open_paren = nullptr; 1667 } 1668 if (open_paren) { 1669 if (IsToken(open_paren, "(anonymous namespace)")) { 1670 open_paren = 1671 strchr(open_paren + strlen("(anonymous namespace)"), '('); 1672 if (open_paren) 1673 close_paren = strchr(open_paren, ')'); 1674 } else 1675 close_paren = strchr(open_paren, ')'); 1676 } 1677 1678 if (open_paren) 1679 s.Write(cstr, open_paren - cstr + 1); 1680 else { 1681 s.PutCString(cstr); 1682 s.PutChar('('); 1683 } 1684 const size_t num_args = args.GetSize(); 1685 for (size_t arg_idx = 0; arg_idx < num_args; ++arg_idx) { 1686 std::string buffer; 1687 1688 VariableSP var_sp(args.GetVariableAtIndex(arg_idx)); 1689 ValueObjectSP var_value_sp( 1690 ValueObjectVariable::Create(exe_scope, var_sp)); 1691 StreamString ss; 1692 llvm::StringRef var_representation; 1693 const char *var_name = var_value_sp->GetName().GetCString(); 1694 if (var_value_sp->GetCompilerType().IsValid()) { 1695 if (var_value_sp && exe_scope->CalculateTarget()) 1696 var_value_sp = 1697 var_value_sp->GetQualifiedRepresentationIfAvailable( 1698 exe_scope->CalculateTarget() 1699 ->TargetProperties::GetPreferDynamicValue(), 1700 exe_scope->CalculateTarget() 1701 ->TargetProperties::GetEnableSyntheticValue()); 1702 if (var_value_sp->GetCompilerType().IsAggregateType() && 1703 DataVisualization::ShouldPrintAsOneLiner(*var_value_sp)) { 1704 static StringSummaryFormat format( 1705 TypeSummaryImpl::Flags() 1706 .SetHideItemNames(false) 1707 .SetShowMembersOneLiner(true), 1708 ""); 1709 format.FormatObject(var_value_sp.get(), buffer, 1710 TypeSummaryOptions()); 1711 var_representation = buffer; 1712 } else 1713 var_value_sp->DumpPrintableRepresentation( 1714 ss, 1715 ValueObject::ValueObjectRepresentationStyle:: 1716 eValueObjectRepresentationStyleSummary, 1717 eFormatDefault, 1718 ValueObject::PrintableRepresentationSpecialCases::eAllow, 1719 false); 1720 } 1721 1722 if (!ss.GetString().empty()) 1723 var_representation = ss.GetString(); 1724 if (arg_idx > 0) 1725 s.PutCString(", "); 1726 if (var_value_sp->GetError().Success()) { 1727 if (!var_representation.empty()) 1728 s.Printf("%s=%s", var_name, var_representation.str().c_str()); 1729 else 1730 s.Printf("%s=%s at %s", var_name, 1731 var_value_sp->GetTypeName().GetCString(), 1732 var_value_sp->GetLocationAsCString()); 1733 } else 1734 s.Printf("%s=<unavailable>", var_name); 1735 } 1736 1737 if (close_paren) 1738 s.PutCString(close_paren); 1739 else 1740 s.PutChar(')'); 1741 1742 } else { 1743 s.PutCString(cstr); 1744 } 1745 return true; 1746 } 1747 } else if (sc->symbol) { 1748 const char *cstr = sc->symbol->GetName().AsCString(nullptr); 1749 if (cstr) { 1750 s.PutCString(cstr); 1751 return true; 1752 } 1753 } 1754 } 1755 } 1756 return false; 1757 1758 case Entry::Type::FunctionMangledName: { 1759 const char *name = nullptr; 1760 if (sc->symbol) 1761 name = 1762 sc->symbol->GetMangled().GetName(Mangled::ePreferMangled).AsCString(); 1763 else if (sc->function) 1764 name = sc->function->GetMangled() 1765 .GetName(Mangled::ePreferMangled) 1766 .AsCString(); 1767 1768 if (!name) 1769 return false; 1770 s.PutCString(name); 1771 1772 if (sc->block->GetContainingInlinedBlock()) { 1773 if (const InlineFunctionInfo *inline_info = 1774 sc->block->GetInlinedFunctionInfo()) { 1775 s.PutCString(" [inlined] "); 1776 inline_info->GetName().Dump(&s); 1777 } 1778 } 1779 return true; 1780 } 1781 1782 case Entry::Type::FunctionAddrOffset: 1783 if (addr) { 1784 if (DumpAddressOffsetFromFunction(s, sc, exe_ctx, *addr, false, false, 1785 false)) 1786 return true; 1787 } 1788 return false; 1789 1790 case Entry::Type::FunctionAddrOffsetConcrete: 1791 if (addr) { 1792 if (DumpAddressOffsetFromFunction(s, sc, exe_ctx, *addr, true, true, 1793 true)) 1794 return true; 1795 } 1796 return false; 1797 1798 case Entry::Type::FunctionLineOffset: 1799 return (DumpAddressOffsetFromFunction(s, sc, exe_ctx, 1800 sc->line_entry.range.GetBaseAddress(), 1801 false, false, false)); 1802 1803 case Entry::Type::FunctionPCOffset: 1804 if (exe_ctx) { 1805 StackFrame *frame = exe_ctx->GetFramePtr(); 1806 if (frame) { 1807 if (DumpAddressOffsetFromFunction(s, sc, exe_ctx, 1808 frame->GetFrameCodeAddress(), false, 1809 false, false)) 1810 return true; 1811 } 1812 } 1813 return false; 1814 1815 case Entry::Type::FunctionChanged: 1816 return function_changed; 1817 1818 case Entry::Type::FunctionIsOptimized: { 1819 bool is_optimized = false; 1820 if (sc->function && sc->function->GetIsOptimized()) { 1821 is_optimized = true; 1822 } 1823 return is_optimized; 1824 } 1825 1826 case Entry::Type::FunctionInitial: 1827 return initial_function; 1828 1829 case Entry::Type::LineEntryFile: 1830 if (sc && sc->line_entry.IsValid()) { 1831 Module *module = sc->module_sp.get(); 1832 if (module) { 1833 if (DumpFile(s, sc->line_entry.file, (FileKind)entry.number)) 1834 return true; 1835 } 1836 } 1837 return false; 1838 1839 case Entry::Type::LineEntryLineNumber: 1840 if (sc && sc->line_entry.IsValid()) { 1841 const char *format = "%" PRIu32; 1842 if (!entry.printf_format.empty()) 1843 format = entry.printf_format.c_str(); 1844 s.Printf(format, sc->line_entry.line); 1845 return true; 1846 } 1847 return false; 1848 1849 case Entry::Type::LineEntryColumn: 1850 if (sc && sc->line_entry.IsValid() && sc->line_entry.column) { 1851 const char *format = "%" PRIu32; 1852 if (!entry.printf_format.empty()) 1853 format = entry.printf_format.c_str(); 1854 s.Printf(format, sc->line_entry.column); 1855 return true; 1856 } 1857 return false; 1858 1859 case Entry::Type::LineEntryStartAddress: 1860 case Entry::Type::LineEntryEndAddress: 1861 if (sc && sc->line_entry.range.GetBaseAddress().IsValid()) { 1862 Address addr = sc->line_entry.range.GetBaseAddress(); 1863 1864 if (entry.type == Entry::Type::LineEntryEndAddress) 1865 addr.Slide(sc->line_entry.range.GetByteSize()); 1866 if (DumpAddressAndContent(s, sc, exe_ctx, addr, false)) 1867 return true; 1868 } 1869 return false; 1870 1871 case Entry::Type::CurrentPCArrow: 1872 if (addr && exe_ctx && exe_ctx->GetFramePtr()) { 1873 RegisterContextSP reg_ctx = 1874 exe_ctx->GetFramePtr()->GetRegisterContextSP(); 1875 if (reg_ctx) { 1876 addr_t pc_loadaddr = reg_ctx->GetPC(); 1877 if (pc_loadaddr != LLDB_INVALID_ADDRESS) { 1878 Address pc; 1879 pc.SetLoadAddress(pc_loadaddr, exe_ctx->GetTargetPtr()); 1880 if (pc == *addr) { 1881 s.Printf("-> "); 1882 return true; 1883 } 1884 } 1885 } 1886 s.Printf(" "); 1887 return true; 1888 } 1889 return false; 1890 } 1891 return false; 1892 } 1893 1894 static bool DumpCommaSeparatedChildEntryNames( 1895 Stream &s, const FormatEntity::Entry::Definition *parent) { 1896 if (parent->children) { 1897 const size_t n = parent->num_children; 1898 for (size_t i = 0; i < n; ++i) { 1899 if (i > 0) 1900 s.PutCString(", "); 1901 s.Printf("\"%s\"", parent->children[i].name); 1902 } 1903 return true; 1904 } 1905 return false; 1906 } 1907 1908 static Status ParseEntry(const llvm::StringRef &format_str, 1909 const FormatEntity::Entry::Definition *parent, 1910 FormatEntity::Entry &entry) { 1911 Status error; 1912 1913 const size_t sep_pos = format_str.find_first_of(".[:"); 1914 const char sep_char = 1915 (sep_pos == llvm::StringRef::npos) ? '\0' : format_str[sep_pos]; 1916 llvm::StringRef key = format_str.substr(0, sep_pos); 1917 1918 const size_t n = parent->num_children; 1919 for (size_t i = 0; i < n; ++i) { 1920 const FormatEntity::Entry::Definition *entry_def = parent->children + i; 1921 if (key.equals(entry_def->name) || entry_def->name[0] == '*') { 1922 llvm::StringRef value; 1923 if (sep_char) 1924 value = 1925 format_str.substr(sep_pos + (entry_def->keep_separator ? 0 : 1)); 1926 switch (entry_def->type) { 1927 case FormatEntity::Entry::Type::ParentString: 1928 entry.string = format_str.str(); 1929 return error; // Success 1930 1931 case FormatEntity::Entry::Type::ParentNumber: 1932 entry.number = entry_def->data; 1933 return error; // Success 1934 1935 case FormatEntity::Entry::Type::EscapeCode: 1936 entry.type = entry_def->type; 1937 entry.string = entry_def->string; 1938 return error; // Success 1939 1940 default: 1941 entry.type = entry_def->type; 1942 break; 1943 } 1944 1945 if (value.empty()) { 1946 if (entry_def->type == FormatEntity::Entry::Type::Invalid) { 1947 if (entry_def->children) { 1948 StreamString error_strm; 1949 error_strm.Printf("'%s' can't be specified on its own, you must " 1950 "access one of its children: ", 1951 entry_def->name); 1952 DumpCommaSeparatedChildEntryNames(error_strm, entry_def); 1953 error.SetErrorStringWithFormat("%s", error_strm.GetData()); 1954 } else if (sep_char == ':') { 1955 // Any value whose separator is a with a ':' means this value has a 1956 // string argument that needs to be stored in the entry (like 1957 // "${script.var:}"). In this case the string value is the empty 1958 // string which is ok. 1959 } else { 1960 error.SetErrorStringWithFormat("%s", "invalid entry definitions"); 1961 } 1962 } 1963 } else { 1964 if (entry_def->children) { 1965 error = ParseEntry(value, entry_def, entry); 1966 } else if (sep_char == ':') { 1967 // Any value whose separator is a with a ':' means this value has a 1968 // string argument that needs to be stored in the entry (like 1969 // "${script.var:modulename.function}") 1970 entry.string = value.str(); 1971 } else { 1972 error.SetErrorStringWithFormat( 1973 "'%s' followed by '%s' but it has no children", key.str().c_str(), 1974 value.str().c_str()); 1975 } 1976 } 1977 return error; 1978 } 1979 } 1980 StreamString error_strm; 1981 if (parent->type == FormatEntity::Entry::Type::Root) 1982 error_strm.Printf( 1983 "invalid top level item '%s'. Valid top level items are: ", 1984 key.str().c_str()); 1985 else 1986 error_strm.Printf("invalid member '%s' in '%s'. Valid members are: ", 1987 key.str().c_str(), parent->name); 1988 DumpCommaSeparatedChildEntryNames(error_strm, parent); 1989 error.SetErrorStringWithFormat("%s", error_strm.GetData()); 1990 return error; 1991 } 1992 1993 static const FormatEntity::Entry::Definition * 1994 FindEntry(const llvm::StringRef &format_str, 1995 const FormatEntity::Entry::Definition *parent, 1996 llvm::StringRef &remainder) { 1997 Status error; 1998 1999 std::pair<llvm::StringRef, llvm::StringRef> p = format_str.split('.'); 2000 const size_t n = parent->num_children; 2001 for (size_t i = 0; i < n; ++i) { 2002 const FormatEntity::Entry::Definition *entry_def = parent->children + i; 2003 if (p.first.equals(entry_def->name) || entry_def->name[0] == '*') { 2004 if (p.second.empty()) { 2005 if (format_str.back() == '.') 2006 remainder = format_str.drop_front(format_str.size() - 1); 2007 else 2008 remainder = llvm::StringRef(); // Exact match 2009 return entry_def; 2010 } else { 2011 if (entry_def->children) { 2012 return FindEntry(p.second, entry_def, remainder); 2013 } else { 2014 remainder = p.second; 2015 return entry_def; 2016 } 2017 } 2018 } 2019 } 2020 remainder = format_str; 2021 return parent; 2022 } 2023 2024 Status FormatEntity::ParseInternal(llvm::StringRef &format, Entry &parent_entry, 2025 uint32_t depth) { 2026 Status error; 2027 while (!format.empty() && error.Success()) { 2028 const size_t non_special_chars = format.find_first_of("${}\\"); 2029 2030 if (non_special_chars == llvm::StringRef::npos) { 2031 // No special characters, just string bytes so add them and we are done 2032 parent_entry.AppendText(format); 2033 return error; 2034 } 2035 2036 if (non_special_chars > 0) { 2037 // We have a special character, so add all characters before these as a 2038 // plain string 2039 parent_entry.AppendText(format.substr(0, non_special_chars)); 2040 format = format.drop_front(non_special_chars); 2041 } 2042 2043 switch (format[0]) { 2044 case '\0': 2045 return error; 2046 2047 case '{': { 2048 format = format.drop_front(); // Skip the '{' 2049 Entry scope_entry(Entry::Type::Scope); 2050 error = FormatEntity::ParseInternal(format, scope_entry, depth + 1); 2051 if (error.Fail()) 2052 return error; 2053 parent_entry.AppendEntry(std::move(scope_entry)); 2054 } break; 2055 2056 case '}': 2057 if (depth == 0) 2058 error.SetErrorString("unmatched '}' character"); 2059 else 2060 format = 2061 format 2062 .drop_front(); // Skip the '}' as we are at the end of the scope 2063 return error; 2064 2065 case '\\': { 2066 format = format.drop_front(); // Skip the '\' character 2067 if (format.empty()) { 2068 error.SetErrorString( 2069 "'\\' character was not followed by another character"); 2070 return error; 2071 } 2072 2073 const char desens_char = format[0]; 2074 format = format.drop_front(); // Skip the desensitized char character 2075 switch (desens_char) { 2076 case 'a': 2077 parent_entry.AppendChar('\a'); 2078 break; 2079 case 'b': 2080 parent_entry.AppendChar('\b'); 2081 break; 2082 case 'f': 2083 parent_entry.AppendChar('\f'); 2084 break; 2085 case 'n': 2086 parent_entry.AppendChar('\n'); 2087 break; 2088 case 'r': 2089 parent_entry.AppendChar('\r'); 2090 break; 2091 case 't': 2092 parent_entry.AppendChar('\t'); 2093 break; 2094 case 'v': 2095 parent_entry.AppendChar('\v'); 2096 break; 2097 case '\'': 2098 parent_entry.AppendChar('\''); 2099 break; 2100 case '\\': 2101 parent_entry.AppendChar('\\'); 2102 break; 2103 case '0': 2104 // 1 to 3 octal chars 2105 { 2106 // Make a string that can hold onto the initial zero char, up to 3 2107 // octal digits, and a terminating NULL. 2108 char oct_str[5] = {0, 0, 0, 0, 0}; 2109 2110 int i; 2111 for (i = 0; (format[i] >= '0' && format[i] <= '7') && i < 4; ++i) 2112 oct_str[i] = format[i]; 2113 2114 // We don't want to consume the last octal character since the main 2115 // for loop will do this for us, so we advance p by one less than i 2116 // (even if i is zero) 2117 format = format.drop_front(i); 2118 unsigned long octal_value = ::strtoul(oct_str, nullptr, 8); 2119 if (octal_value <= UINT8_MAX) { 2120 parent_entry.AppendChar((char)octal_value); 2121 } else { 2122 error.SetErrorString("octal number is larger than a single byte"); 2123 return error; 2124 } 2125 } 2126 break; 2127 2128 case 'x': 2129 // hex number in the format 2130 if (isxdigit(format[0])) { 2131 // Make a string that can hold onto two hex chars plus a 2132 // NULL terminator 2133 char hex_str[3] = {0, 0, 0}; 2134 hex_str[0] = format[0]; 2135 2136 format = format.drop_front(); 2137 2138 if (isxdigit(format[0])) { 2139 hex_str[1] = format[0]; 2140 format = format.drop_front(); 2141 } 2142 2143 unsigned long hex_value = strtoul(hex_str, nullptr, 16); 2144 if (hex_value <= UINT8_MAX) { 2145 parent_entry.AppendChar((char)hex_value); 2146 } else { 2147 error.SetErrorString("hex number is larger than a single byte"); 2148 return error; 2149 } 2150 } else { 2151 parent_entry.AppendChar(desens_char); 2152 } 2153 break; 2154 2155 default: 2156 // Just desensitize any other character by just printing what came 2157 // after the '\' 2158 parent_entry.AppendChar(desens_char); 2159 break; 2160 } 2161 } break; 2162 2163 case '$': 2164 if (format.size() == 1) { 2165 // '$' at the end of a format string, just print the '$' 2166 parent_entry.AppendText("$"); 2167 } else { 2168 format = format.drop_front(); // Skip the '$' 2169 2170 if (format[0] == '{') { 2171 format = format.drop_front(); // Skip the '{' 2172 2173 llvm::StringRef variable, variable_format; 2174 error = FormatEntity::ExtractVariableInfo(format, variable, 2175 variable_format); 2176 if (error.Fail()) 2177 return error; 2178 bool verify_is_thread_id = false; 2179 Entry entry; 2180 if (!variable_format.empty()) { 2181 entry.printf_format = variable_format.str(); 2182 2183 // If the format contains a '%' we are going to assume this is a 2184 // printf style format. So if you want to format your thread ID 2185 // using "0x%llx" you can use: ${thread.id%0x%llx} 2186 // 2187 // If there is no '%' in the format, then it is assumed to be a 2188 // LLDB format name, or one of the extended formats specified in 2189 // the switch statement below. 2190 2191 if (entry.printf_format.find('%') == std::string::npos) { 2192 bool clear_printf = false; 2193 2194 if (FormatManager::GetFormatFromCString( 2195 entry.printf_format.c_str(), false, entry.fmt)) { 2196 // We have an LLDB format, so clear the printf format 2197 clear_printf = true; 2198 } else if (entry.printf_format.size() == 1) { 2199 switch (entry.printf_format[0]) { 2200 case '@': // if this is an @ sign, print ObjC description 2201 entry.number = ValueObject:: 2202 eValueObjectRepresentationStyleLanguageSpecific; 2203 clear_printf = true; 2204 break; 2205 case 'V': // if this is a V, print the value using the default 2206 // format 2207 entry.number = 2208 ValueObject::eValueObjectRepresentationStyleValue; 2209 clear_printf = true; 2210 break; 2211 case 'L': // if this is an L, print the location of the value 2212 entry.number = 2213 ValueObject::eValueObjectRepresentationStyleLocation; 2214 clear_printf = true; 2215 break; 2216 case 'S': // if this is an S, print the summary after all 2217 entry.number = 2218 ValueObject::eValueObjectRepresentationStyleSummary; 2219 clear_printf = true; 2220 break; 2221 case '#': // if this is a '#', print the number of children 2222 entry.number = 2223 ValueObject::eValueObjectRepresentationStyleChildrenCount; 2224 clear_printf = true; 2225 break; 2226 case 'T': // if this is a 'T', print the type 2227 entry.number = 2228 ValueObject::eValueObjectRepresentationStyleType; 2229 clear_printf = true; 2230 break; 2231 case 'N': // if this is a 'N', print the name 2232 entry.number = 2233 ValueObject::eValueObjectRepresentationStyleName; 2234 clear_printf = true; 2235 break; 2236 case '>': // if this is a '>', print the expression path 2237 entry.number = ValueObject:: 2238 eValueObjectRepresentationStyleExpressionPath; 2239 clear_printf = true; 2240 break; 2241 default: 2242 error.SetErrorStringWithFormat("invalid format: '%s'", 2243 entry.printf_format.c_str()); 2244 return error; 2245 } 2246 } else if (FormatManager::GetFormatFromCString( 2247 entry.printf_format.c_str(), true, entry.fmt)) { 2248 clear_printf = true; 2249 } else if (entry.printf_format == "tid") { 2250 verify_is_thread_id = true; 2251 } else { 2252 error.SetErrorStringWithFormat("invalid format: '%s'", 2253 entry.printf_format.c_str()); 2254 return error; 2255 } 2256 2257 // Our format string turned out to not be a printf style format 2258 // so lets clear the string 2259 if (clear_printf) 2260 entry.printf_format.clear(); 2261 } 2262 } 2263 2264 // Check for dereferences 2265 if (variable[0] == '*') { 2266 entry.deref = true; 2267 variable = variable.drop_front(); 2268 } 2269 2270 error = ParseEntry(variable, &g_root, entry); 2271 if (error.Fail()) 2272 return error; 2273 2274 if (verify_is_thread_id) { 2275 if (entry.type != Entry::Type::ThreadID && 2276 entry.type != Entry::Type::ThreadProtocolID) { 2277 error.SetErrorString("the 'tid' format can only be used on " 2278 "${thread.id} and ${thread.protocol_id}"); 2279 } 2280 } 2281 2282 switch (entry.type) { 2283 case Entry::Type::Variable: 2284 case Entry::Type::VariableSynthetic: 2285 if (entry.number == 0) { 2286 if (entry.string.empty()) 2287 entry.number = 2288 ValueObject::eValueObjectRepresentationStyleValue; 2289 else 2290 entry.number = 2291 ValueObject::eValueObjectRepresentationStyleSummary; 2292 } 2293 break; 2294 default: 2295 // Make sure someone didn't try to dereference anything but ${var} 2296 // or ${svar} 2297 if (entry.deref) { 2298 error.SetErrorStringWithFormat( 2299 "${%s} can't be dereferenced, only ${var} and ${svar} can.", 2300 variable.str().c_str()); 2301 return error; 2302 } 2303 } 2304 parent_entry.AppendEntry(std::move(entry)); 2305 } 2306 } 2307 break; 2308 } 2309 } 2310 return error; 2311 } 2312 2313 Status FormatEntity::ExtractVariableInfo(llvm::StringRef &format_str, 2314 llvm::StringRef &variable_name, 2315 llvm::StringRef &variable_format) { 2316 Status error; 2317 variable_name = llvm::StringRef(); 2318 variable_format = llvm::StringRef(); 2319 2320 const size_t paren_pos = format_str.find('}'); 2321 if (paren_pos != llvm::StringRef::npos) { 2322 const size_t percent_pos = format_str.find('%'); 2323 if (percent_pos < paren_pos) { 2324 if (percent_pos > 0) { 2325 if (percent_pos > 1) 2326 variable_name = format_str.substr(0, percent_pos); 2327 variable_format = 2328 format_str.substr(percent_pos + 1, paren_pos - (percent_pos + 1)); 2329 } 2330 } else { 2331 variable_name = format_str.substr(0, paren_pos); 2332 } 2333 // Strip off elements and the formatting and the trailing '}' 2334 format_str = format_str.substr(paren_pos + 1); 2335 } else { 2336 error.SetErrorStringWithFormat( 2337 "missing terminating '}' character for '${%s'", 2338 format_str.str().c_str()); 2339 } 2340 return error; 2341 } 2342 2343 bool FormatEntity::FormatFileSpec(const FileSpec &file_spec, Stream &s, 2344 llvm::StringRef variable_name, 2345 llvm::StringRef variable_format) { 2346 if (variable_name.empty() || variable_name.equals(".fullpath")) { 2347 file_spec.Dump(s.AsRawOstream()); 2348 return true; 2349 } else if (variable_name.equals(".basename")) { 2350 s.PutCString(file_spec.GetFilename().GetStringRef()); 2351 return true; 2352 } else if (variable_name.equals(".dirname")) { 2353 s.PutCString(file_spec.GetFilename().GetStringRef()); 2354 return true; 2355 } 2356 return false; 2357 } 2358 2359 static std::string MakeMatch(const llvm::StringRef &prefix, 2360 const char *suffix) { 2361 std::string match(prefix.str()); 2362 match.append(suffix); 2363 return match; 2364 } 2365 2366 static void AddMatches(const FormatEntity::Entry::Definition *def, 2367 const llvm::StringRef &prefix, 2368 const llvm::StringRef &match_prefix, 2369 StringList &matches) { 2370 const size_t n = def->num_children; 2371 if (n > 0) { 2372 for (size_t i = 0; i < n; ++i) { 2373 std::string match = prefix.str(); 2374 if (match_prefix.empty()) 2375 matches.AppendString(MakeMatch(prefix, def->children[i].name)); 2376 else if (strncmp(def->children[i].name, match_prefix.data(), 2377 match_prefix.size()) == 0) 2378 matches.AppendString( 2379 MakeMatch(prefix, def->children[i].name + match_prefix.size())); 2380 } 2381 } 2382 } 2383 2384 void FormatEntity::AutoComplete(CompletionRequest &request) { 2385 llvm::StringRef str = request.GetCursorArgumentPrefix(); 2386 2387 const size_t dollar_pos = str.rfind('$'); 2388 if (dollar_pos == llvm::StringRef::npos) 2389 return; 2390 2391 // Hitting TAB after $ at the end of the string add a "{" 2392 if (dollar_pos == str.size() - 1) { 2393 std::string match = str.str(); 2394 match.append("{"); 2395 request.AddCompletion(match); 2396 return; 2397 } 2398 2399 if (str[dollar_pos + 1] != '{') 2400 return; 2401 2402 const size_t close_pos = str.find('}', dollar_pos + 2); 2403 if (close_pos != llvm::StringRef::npos) 2404 return; 2405 2406 const size_t format_pos = str.find('%', dollar_pos + 2); 2407 if (format_pos != llvm::StringRef::npos) 2408 return; 2409 2410 llvm::StringRef partial_variable(str.substr(dollar_pos + 2)); 2411 if (partial_variable.empty()) { 2412 // Suggest all top level entities as we are just past "${" 2413 StringList new_matches; 2414 AddMatches(&g_root, str, llvm::StringRef(), new_matches); 2415 request.AddCompletions(new_matches); 2416 return; 2417 } 2418 2419 // We have a partially specified variable, find it 2420 llvm::StringRef remainder; 2421 const FormatEntity::Entry::Definition *entry_def = 2422 FindEntry(partial_variable, &g_root, remainder); 2423 if (!entry_def) 2424 return; 2425 2426 const size_t n = entry_def->num_children; 2427 2428 if (remainder.empty()) { 2429 // Exact match 2430 if (n > 0) { 2431 // "${thread.info" <TAB> 2432 request.AddCompletion(MakeMatch(str, ".")); 2433 } else { 2434 // "${thread.id" <TAB> 2435 request.AddCompletion(MakeMatch(str, "}")); 2436 } 2437 } else if (remainder.equals(".")) { 2438 // "${thread." <TAB> 2439 StringList new_matches; 2440 AddMatches(entry_def, str, llvm::StringRef(), new_matches); 2441 request.AddCompletions(new_matches); 2442 } else { 2443 // We have a partial match 2444 // "${thre" <TAB> 2445 StringList new_matches; 2446 AddMatches(entry_def, str, remainder, new_matches); 2447 request.AddCompletions(new_matches); 2448 } 2449 } 2450