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/SharingPtr.h" 50 #include "lldb/Utility/Stream.h" 51 #include "lldb/Utility/StreamString.h" 52 #include "lldb/Utility/StringList.h" 53 #include "lldb/Utility/StructuredData.h" 54 #include "lldb/lldb-defines.h" 55 #include "lldb/lldb-forward.h" 56 #include "llvm/ADT/STLExtras.h" 57 #include "llvm/ADT/StringRef.h" 58 #include "llvm/ADT/Triple.h" 59 #include "llvm/Support/Compiler.h" 60 61 #include <ctype.h> 62 #include <inttypes.h> 63 #include <memory> 64 #include <stdio.h> 65 #include <stdlib.h> 66 #include <string.h> 67 #include <type_traits> 68 #include <utility> 69 70 namespace lldb_private { 71 class ScriptInterpreter; 72 } 73 namespace lldb_private { 74 struct RegisterInfo; 75 } 76 77 using namespace lldb; 78 using namespace lldb_private; 79 80 enum FileKind { FileError = 0, Basename, Dirname, Fullpath }; 81 82 #define ENTRY(n, t) \ 83 { n, nullptr, FormatEntity::Entry::Type::t, 0, 0, nullptr, false } 84 #define ENTRY_VALUE(n, t, v) \ 85 { n, nullptr, FormatEntity::Entry::Type::t, v, 0, nullptr, false } 86 #define ENTRY_CHILDREN(n, t, c) \ 87 { \ 88 n, nullptr, FormatEntity::Entry::Type::t, 0, \ 89 static_cast<uint32_t>(llvm::array_lengthof(c)), c, false \ 90 } 91 #define ENTRY_CHILDREN_KEEP_SEP(n, t, c) \ 92 { \ 93 n, nullptr, FormatEntity::Entry::Type::t, 0, \ 94 static_cast<uint32_t>(llvm::array_lengthof(c)), c, true \ 95 } 96 #define ENTRY_STRING(n, s) \ 97 { n, s, FormatEntity::Entry::Type::EscapeCode, 0, 0, nullptr, false } 98 static FormatEntity::Entry::Definition g_string_entry[] = { 99 ENTRY("*", ParentString)}; 100 101 static FormatEntity::Entry::Definition g_addr_entries[] = { 102 ENTRY("load", AddressLoad), 103 ENTRY("file", AddressFile), 104 ENTRY("load", AddressLoadOrFile), 105 }; 106 107 static FormatEntity::Entry::Definition g_file_child_entries[] = { 108 ENTRY_VALUE("basename", ParentNumber, FileKind::Basename), 109 ENTRY_VALUE("dirname", ParentNumber, FileKind::Dirname), 110 ENTRY_VALUE("fullpath", ParentNumber, FileKind::Fullpath)}; 111 112 static FormatEntity::Entry::Definition g_frame_child_entries[] = { 113 ENTRY("index", FrameIndex), 114 ENTRY("pc", FrameRegisterPC), 115 ENTRY("fp", FrameRegisterFP), 116 ENTRY("sp", FrameRegisterSP), 117 ENTRY("flags", FrameRegisterFlags), 118 ENTRY("no-debug", FrameNoDebug), 119 ENTRY_CHILDREN("reg", FrameRegisterByName, g_string_entry), 120 ENTRY("is-artificial", FrameIsArtificial), 121 }; 122 123 static FormatEntity::Entry::Definition g_function_child_entries[] = { 124 ENTRY("id", FunctionID), 125 ENTRY("name", FunctionName), 126 ENTRY("name-without-args", FunctionNameNoArgs), 127 ENTRY("name-with-args", FunctionNameWithArgs), 128 ENTRY("mangled-name", FunctionMangledName), 129 ENTRY("addr-offset", FunctionAddrOffset), 130 ENTRY("concrete-only-addr-offset-no-padding", FunctionAddrOffsetConcrete), 131 ENTRY("line-offset", FunctionLineOffset), 132 ENTRY("pc-offset", FunctionPCOffset), 133 ENTRY("initial-function", FunctionInitial), 134 ENTRY("changed", FunctionChanged), 135 ENTRY("is-optimized", FunctionIsOptimized)}; 136 137 static FormatEntity::Entry::Definition g_line_child_entries[] = { 138 ENTRY_CHILDREN("file", LineEntryFile, g_file_child_entries), 139 ENTRY("number", LineEntryLineNumber), 140 ENTRY("column", LineEntryColumn), 141 ENTRY("start-addr", LineEntryStartAddress), 142 ENTRY("end-addr", LineEntryEndAddress), 143 }; 144 145 static FormatEntity::Entry::Definition g_module_child_entries[] = { 146 ENTRY_CHILDREN("file", ModuleFile, g_file_child_entries), 147 }; 148 149 static FormatEntity::Entry::Definition g_process_child_entries[] = { 150 ENTRY("id", ProcessID), 151 ENTRY_VALUE("name", ProcessFile, FileKind::Basename), 152 ENTRY_CHILDREN("file", ProcessFile, g_file_child_entries), 153 }; 154 155 static FormatEntity::Entry::Definition g_svar_child_entries[] = { 156 ENTRY("*", ParentString)}; 157 158 static FormatEntity::Entry::Definition g_var_child_entries[] = { 159 ENTRY("*", ParentString)}; 160 161 static FormatEntity::Entry::Definition g_thread_child_entries[] = { 162 ENTRY("id", ThreadID), 163 ENTRY("protocol_id", ThreadProtocolID), 164 ENTRY("index", ThreadIndexID), 165 ENTRY_CHILDREN("info", ThreadInfo, g_string_entry), 166 ENTRY("queue", ThreadQueue), 167 ENTRY("name", ThreadName), 168 ENTRY("stop-reason", ThreadStopReason), 169 ENTRY("stop-reason-raw", ThreadStopReasonRaw), 170 ENTRY("return-value", ThreadReturnValue), 171 ENTRY("completed-expression", ThreadCompletedExpression), 172 }; 173 174 static FormatEntity::Entry::Definition g_target_child_entries[] = { 175 ENTRY("arch", TargetArch), 176 }; 177 178 #define _TO_STR2(_val) #_val 179 #define _TO_STR(_val) _TO_STR2(_val) 180 181 static FormatEntity::Entry::Definition g_ansi_fg_entries[] = { 182 ENTRY_STRING("black", 183 ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_BLACK) ANSI_ESC_END), 184 ENTRY_STRING("red", ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_RED) ANSI_ESC_END), 185 ENTRY_STRING("green", 186 ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_GREEN) ANSI_ESC_END), 187 ENTRY_STRING("yellow", 188 ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_YELLOW) ANSI_ESC_END), 189 ENTRY_STRING("blue", 190 ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_BLUE) ANSI_ESC_END), 191 ENTRY_STRING("purple", 192 ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_PURPLE) ANSI_ESC_END), 193 ENTRY_STRING("cyan", 194 ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_CYAN) ANSI_ESC_END), 195 ENTRY_STRING("white", 196 ANSI_ESC_START _TO_STR(ANSI_FG_COLOR_WHITE) ANSI_ESC_END), 197 }; 198 199 static FormatEntity::Entry::Definition g_ansi_bg_entries[] = { 200 ENTRY_STRING("black", 201 ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_BLACK) ANSI_ESC_END), 202 ENTRY_STRING("red", ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_RED) ANSI_ESC_END), 203 ENTRY_STRING("green", 204 ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_GREEN) ANSI_ESC_END), 205 ENTRY_STRING("yellow", 206 ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_YELLOW) ANSI_ESC_END), 207 ENTRY_STRING("blue", 208 ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_BLUE) ANSI_ESC_END), 209 ENTRY_STRING("purple", 210 ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_PURPLE) ANSI_ESC_END), 211 ENTRY_STRING("cyan", 212 ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_CYAN) ANSI_ESC_END), 213 ENTRY_STRING("white", 214 ANSI_ESC_START _TO_STR(ANSI_BG_COLOR_WHITE) ANSI_ESC_END), 215 }; 216 217 static FormatEntity::Entry::Definition g_ansi_entries[] = { 218 ENTRY_CHILDREN("fg", Invalid, g_ansi_fg_entries), 219 ENTRY_CHILDREN("bg", Invalid, g_ansi_bg_entries), 220 ENTRY_STRING("normal", 221 ANSI_ESC_START _TO_STR(ANSI_CTRL_NORMAL) ANSI_ESC_END), 222 ENTRY_STRING("bold", ANSI_ESC_START _TO_STR(ANSI_CTRL_BOLD) ANSI_ESC_END), 223 ENTRY_STRING("faint", ANSI_ESC_START _TO_STR(ANSI_CTRL_FAINT) ANSI_ESC_END), 224 ENTRY_STRING("italic", 225 ANSI_ESC_START _TO_STR(ANSI_CTRL_ITALIC) ANSI_ESC_END), 226 ENTRY_STRING("underline", 227 ANSI_ESC_START _TO_STR(ANSI_CTRL_UNDERLINE) ANSI_ESC_END), 228 ENTRY_STRING("slow-blink", 229 ANSI_ESC_START _TO_STR(ANSI_CTRL_SLOW_BLINK) ANSI_ESC_END), 230 ENTRY_STRING("fast-blink", 231 ANSI_ESC_START _TO_STR(ANSI_CTRL_FAST_BLINK) ANSI_ESC_END), 232 ENTRY_STRING("negative", 233 ANSI_ESC_START _TO_STR(ANSI_CTRL_IMAGE_NEGATIVE) ANSI_ESC_END), 234 ENTRY_STRING("conceal", 235 ANSI_ESC_START _TO_STR(ANSI_CTRL_CONCEAL) ANSI_ESC_END), 236 ENTRY_STRING("crossed-out", 237 ANSI_ESC_START _TO_STR(ANSI_CTRL_CROSSED_OUT) ANSI_ESC_END), 238 }; 239 240 static FormatEntity::Entry::Definition g_script_child_entries[] = { 241 ENTRY("frame", ScriptFrame), ENTRY("process", ScriptProcess), 242 ENTRY("target", ScriptTarget), ENTRY("thread", ScriptThread), 243 ENTRY("var", ScriptVariable), ENTRY("svar", ScriptVariableSynthetic), 244 ENTRY("thread", ScriptThread), 245 }; 246 247 static FormatEntity::Entry::Definition g_top_level_entries[] = { 248 ENTRY_CHILDREN("addr", AddressLoadOrFile, g_addr_entries), 249 ENTRY("addr-file-or-load", AddressLoadOrFile), 250 ENTRY_CHILDREN("ansi", Invalid, g_ansi_entries), 251 ENTRY("current-pc-arrow", CurrentPCArrow), 252 ENTRY_CHILDREN("file", File, g_file_child_entries), 253 ENTRY("language", Lang), 254 ENTRY_CHILDREN("frame", Invalid, g_frame_child_entries), 255 ENTRY_CHILDREN("function", Invalid, g_function_child_entries), 256 ENTRY_CHILDREN("line", Invalid, g_line_child_entries), 257 ENTRY_CHILDREN("module", Invalid, g_module_child_entries), 258 ENTRY_CHILDREN("process", Invalid, g_process_child_entries), 259 ENTRY_CHILDREN("script", Invalid, g_script_child_entries), 260 ENTRY_CHILDREN_KEEP_SEP("svar", VariableSynthetic, g_svar_child_entries), 261 ENTRY_CHILDREN("thread", Invalid, g_thread_child_entries), 262 ENTRY_CHILDREN("target", Invalid, g_target_child_entries), 263 ENTRY_CHILDREN_KEEP_SEP("var", Variable, g_var_child_entries), 264 }; 265 266 static FormatEntity::Entry::Definition g_root = 267 ENTRY_CHILDREN("<root>", Root, g_top_level_entries); 268 269 FormatEntity::Entry::Entry(llvm::StringRef s) 270 : string(s.data(), s.size()), printf_format(), children(), 271 definition(nullptr), type(Type::String), fmt(lldb::eFormatDefault), 272 number(0), deref(false) {} 273 274 FormatEntity::Entry::Entry(char ch) 275 : string(1, ch), printf_format(), children(), definition(nullptr), 276 type(Type::String), fmt(lldb::eFormatDefault), number(0), deref(false) {} 277 278 void FormatEntity::Entry::AppendChar(char ch) { 279 if (children.empty() || children.back().type != Entry::Type::String) 280 children.push_back(Entry(ch)); 281 else 282 children.back().string.append(1, ch); 283 } 284 285 void FormatEntity::Entry::AppendText(const llvm::StringRef &s) { 286 if (children.empty() || children.back().type != Entry::Type::String) 287 children.push_back(Entry(s)); 288 else 289 children.back().string.append(s.data(), s.size()); 290 } 291 292 void FormatEntity::Entry::AppendText(const char *cstr) { 293 return AppendText(llvm::StringRef(cstr)); 294 } 295 296 Status FormatEntity::Parse(const llvm::StringRef &format_str, Entry &entry) { 297 entry.Clear(); 298 entry.type = Entry::Type::Root; 299 llvm::StringRef modifiable_format(format_str); 300 return ParseInternal(modifiable_format, entry, 0); 301 } 302 303 #define ENUM_TO_CSTR(eee) \ 304 case FormatEntity::Entry::Type::eee: \ 305 return #eee 306 307 const char *FormatEntity::Entry::TypeToCString(Type t) { 308 switch (t) { 309 ENUM_TO_CSTR(Invalid); 310 ENUM_TO_CSTR(ParentNumber); 311 ENUM_TO_CSTR(ParentString); 312 ENUM_TO_CSTR(EscapeCode); 313 ENUM_TO_CSTR(Root); 314 ENUM_TO_CSTR(String); 315 ENUM_TO_CSTR(Scope); 316 ENUM_TO_CSTR(Variable); 317 ENUM_TO_CSTR(VariableSynthetic); 318 ENUM_TO_CSTR(ScriptVariable); 319 ENUM_TO_CSTR(ScriptVariableSynthetic); 320 ENUM_TO_CSTR(AddressLoad); 321 ENUM_TO_CSTR(AddressFile); 322 ENUM_TO_CSTR(AddressLoadOrFile); 323 ENUM_TO_CSTR(ProcessID); 324 ENUM_TO_CSTR(ProcessFile); 325 ENUM_TO_CSTR(ScriptProcess); 326 ENUM_TO_CSTR(ThreadID); 327 ENUM_TO_CSTR(ThreadProtocolID); 328 ENUM_TO_CSTR(ThreadIndexID); 329 ENUM_TO_CSTR(ThreadName); 330 ENUM_TO_CSTR(ThreadQueue); 331 ENUM_TO_CSTR(ThreadStopReason); 332 ENUM_TO_CSTR(ThreadStopReasonRaw); 333 ENUM_TO_CSTR(ThreadReturnValue); 334 ENUM_TO_CSTR(ThreadCompletedExpression); 335 ENUM_TO_CSTR(ScriptThread); 336 ENUM_TO_CSTR(ThreadInfo); 337 ENUM_TO_CSTR(TargetArch); 338 ENUM_TO_CSTR(ScriptTarget); 339 ENUM_TO_CSTR(ModuleFile); 340 ENUM_TO_CSTR(File); 341 ENUM_TO_CSTR(Lang); 342 ENUM_TO_CSTR(FrameIndex); 343 ENUM_TO_CSTR(FrameNoDebug); 344 ENUM_TO_CSTR(FrameRegisterPC); 345 ENUM_TO_CSTR(FrameRegisterSP); 346 ENUM_TO_CSTR(FrameRegisterFP); 347 ENUM_TO_CSTR(FrameRegisterFlags); 348 ENUM_TO_CSTR(FrameRegisterByName); 349 ENUM_TO_CSTR(FrameIsArtificial); 350 ENUM_TO_CSTR(ScriptFrame); 351 ENUM_TO_CSTR(FunctionID); 352 ENUM_TO_CSTR(FunctionDidChange); 353 ENUM_TO_CSTR(FunctionInitialFunction); 354 ENUM_TO_CSTR(FunctionName); 355 ENUM_TO_CSTR(FunctionNameWithArgs); 356 ENUM_TO_CSTR(FunctionNameNoArgs); 357 ENUM_TO_CSTR(FunctionMangledName); 358 ENUM_TO_CSTR(FunctionAddrOffset); 359 ENUM_TO_CSTR(FunctionAddrOffsetConcrete); 360 ENUM_TO_CSTR(FunctionLineOffset); 361 ENUM_TO_CSTR(FunctionPCOffset); 362 ENUM_TO_CSTR(FunctionInitial); 363 ENUM_TO_CSTR(FunctionChanged); 364 ENUM_TO_CSTR(FunctionIsOptimized); 365 ENUM_TO_CSTR(LineEntryFile); 366 ENUM_TO_CSTR(LineEntryLineNumber); 367 ENUM_TO_CSTR(LineEntryColumn); 368 ENUM_TO_CSTR(LineEntryStartAddress); 369 ENUM_TO_CSTR(LineEntryEndAddress); 370 ENUM_TO_CSTR(CurrentPCArrow); 371 } 372 return "???"; 373 } 374 375 #undef ENUM_TO_CSTR 376 377 void FormatEntity::Entry::Dump(Stream &s, int depth) const { 378 s.Printf("%*.*s%-20s: ", depth * 2, depth * 2, "", TypeToCString(type)); 379 if (fmt != eFormatDefault) 380 s.Printf("lldb-format = %s, ", FormatManager::GetFormatAsCString(fmt)); 381 if (!string.empty()) 382 s.Printf("string = \"%s\"", string.c_str()); 383 if (!printf_format.empty()) 384 s.Printf("printf_format = \"%s\"", printf_format.c_str()); 385 if (number != 0) 386 s.Printf("number = %" PRIu64 " (0x%" PRIx64 "), ", number, number); 387 if (deref) 388 s.Printf("deref = true, "); 389 s.EOL(); 390 for (const auto &child : children) { 391 child.Dump(s, depth + 1); 392 } 393 } 394 395 template <typename T> 396 static bool RunScriptFormatKeyword(Stream &s, const SymbolContext *sc, 397 const ExecutionContext *exe_ctx, T t, 398 const char *script_function_name) { 399 Target *target = Target::GetTargetFromContexts(exe_ctx, sc); 400 401 if (target) { 402 ScriptInterpreter *script_interpreter = 403 target->GetDebugger().GetScriptInterpreter(); 404 if (script_interpreter) { 405 Status error; 406 std::string script_output; 407 408 if (script_interpreter->RunScriptFormatKeyword(script_function_name, t, 409 script_output, error) && 410 error.Success()) { 411 s.Printf("%s", script_output.c_str()); 412 return true; 413 } else { 414 s.Printf("<error: %s>", error.AsCString()); 415 } 416 } 417 } 418 return false; 419 } 420 421 static bool DumpAddressAndContent(Stream &s, const SymbolContext *sc, 422 const ExecutionContext *exe_ctx, 423 const Address &addr, 424 bool print_file_addr_or_load_addr) { 425 Target *target = Target::GetTargetFromContexts(exe_ctx, sc); 426 addr_t vaddr = LLDB_INVALID_ADDRESS; 427 if (exe_ctx && !target->GetSectionLoadList().IsEmpty()) 428 vaddr = addr.GetLoadAddress(target); 429 if (vaddr == LLDB_INVALID_ADDRESS) 430 vaddr = addr.GetFileAddress(); 431 432 if (vaddr != LLDB_INVALID_ADDRESS) { 433 int addr_width = 0; 434 if (exe_ctx && target) { 435 addr_width = target->GetArchitecture().GetAddressByteSize() * 2; 436 } 437 if (addr_width == 0) 438 addr_width = 16; 439 if (print_file_addr_or_load_addr) { 440 ExecutionContextScope *exe_scope = nullptr; 441 if (exe_ctx) 442 exe_scope = exe_ctx->GetBestExecutionContextScope(); 443 addr.Dump(&s, exe_scope, Address::DumpStyleLoadAddress, 444 Address::DumpStyleModuleWithFileAddress, 0); 445 } else { 446 s.Printf("0x%*.*" PRIx64, addr_width, addr_width, vaddr); 447 } 448 return true; 449 } 450 return false; 451 } 452 453 static bool DumpAddressOffsetFromFunction(Stream &s, const SymbolContext *sc, 454 const ExecutionContext *exe_ctx, 455 const Address &format_addr, 456 bool concrete_only, bool no_padding, 457 bool print_zero_offsets) { 458 if (format_addr.IsValid()) { 459 Address func_addr; 460 461 if (sc) { 462 if (sc->function) { 463 func_addr = sc->function->GetAddressRange().GetBaseAddress(); 464 if (sc->block && !concrete_only) { 465 // Check to make sure we aren't in an inline function. If we are, use 466 // the inline block range that contains "format_addr" since blocks 467 // can be discontiguous. 468 Block *inline_block = sc->block->GetContainingInlinedBlock(); 469 AddressRange inline_range; 470 if (inline_block && inline_block->GetRangeContainingAddress( 471 format_addr, inline_range)) 472 func_addr = inline_range.GetBaseAddress(); 473 } 474 } else if (sc->symbol && sc->symbol->ValueIsAddress()) 475 func_addr = sc->symbol->GetAddressRef(); 476 } 477 478 if (func_addr.IsValid()) { 479 const char *addr_offset_padding = no_padding ? "" : " "; 480 481 if (func_addr.GetSection() == format_addr.GetSection()) { 482 addr_t func_file_addr = func_addr.GetFileAddress(); 483 addr_t addr_file_addr = format_addr.GetFileAddress(); 484 if (addr_file_addr > func_file_addr || 485 (addr_file_addr == func_file_addr && print_zero_offsets)) { 486 s.Printf("%s+%s%" PRIu64, addr_offset_padding, addr_offset_padding, 487 addr_file_addr - func_file_addr); 488 } else if (addr_file_addr < func_file_addr) { 489 s.Printf("%s-%s%" PRIu64, addr_offset_padding, addr_offset_padding, 490 func_file_addr - addr_file_addr); 491 } 492 return true; 493 } else { 494 Target *target = Target::GetTargetFromContexts(exe_ctx, sc); 495 if (target) { 496 addr_t func_load_addr = func_addr.GetLoadAddress(target); 497 addr_t addr_load_addr = format_addr.GetLoadAddress(target); 498 if (addr_load_addr > func_load_addr || 499 (addr_load_addr == func_load_addr && print_zero_offsets)) { 500 s.Printf("%s+%s%" PRIu64, addr_offset_padding, addr_offset_padding, 501 addr_load_addr - func_load_addr); 502 } else if (addr_load_addr < func_load_addr) { 503 s.Printf("%s-%s%" PRIu64, addr_offset_padding, addr_offset_padding, 504 func_load_addr - addr_load_addr); 505 } 506 return true; 507 } 508 } 509 } 510 } 511 return false; 512 } 513 514 static bool ScanBracketedRange(llvm::StringRef subpath, 515 size_t &close_bracket_index, 516 const char *&var_name_final_if_array_range, 517 int64_t &index_lower, int64_t &index_higher) { 518 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS)); 519 close_bracket_index = llvm::StringRef::npos; 520 const size_t open_bracket_index = subpath.find('['); 521 if (open_bracket_index == llvm::StringRef::npos) { 522 LLDB_LOGF(log, 523 "[ScanBracketedRange] no bracketed range, skipping entirely"); 524 return false; 525 } 526 527 close_bracket_index = subpath.find(']', open_bracket_index + 1); 528 529 if (close_bracket_index == llvm::StringRef::npos) { 530 LLDB_LOGF(log, 531 "[ScanBracketedRange] no bracketed range, skipping entirely"); 532 return false; 533 } else { 534 var_name_final_if_array_range = subpath.data() + open_bracket_index; 535 536 if (close_bracket_index - open_bracket_index == 1) { 537 LLDB_LOGF( 538 log, 539 "[ScanBracketedRange] '[]' detected.. going from 0 to end of data"); 540 index_lower = 0; 541 } else { 542 const size_t separator_index = subpath.find('-', open_bracket_index + 1); 543 544 if (separator_index == llvm::StringRef::npos) { 545 const char *index_lower_cstr = subpath.data() + open_bracket_index + 1; 546 index_lower = ::strtoul(index_lower_cstr, nullptr, 0); 547 index_higher = index_lower; 548 LLDB_LOGF(log, 549 "[ScanBracketedRange] [%" PRId64 550 "] detected, high index is same", 551 index_lower); 552 } else { 553 const char *index_lower_cstr = subpath.data() + open_bracket_index + 1; 554 const char *index_higher_cstr = subpath.data() + separator_index + 1; 555 index_lower = ::strtoul(index_lower_cstr, nullptr, 0); 556 index_higher = ::strtoul(index_higher_cstr, nullptr, 0); 557 LLDB_LOGF(log, 558 "[ScanBracketedRange] [%" PRId64 "-%" PRId64 "] detected", 559 index_lower, index_higher); 560 } 561 if (index_lower > index_higher && index_higher > 0) { 562 LLDB_LOGF(log, "[ScanBracketedRange] swapping indices"); 563 const int64_t temp = index_lower; 564 index_lower = index_higher; 565 index_higher = temp; 566 } 567 } 568 } 569 return true; 570 } 571 572 static bool DumpFile(Stream &s, const FileSpec &file, FileKind file_kind) { 573 switch (file_kind) { 574 case FileKind::FileError: 575 break; 576 577 case FileKind::Basename: 578 if (file.GetFilename()) { 579 s << file.GetFilename(); 580 return true; 581 } 582 break; 583 584 case FileKind::Dirname: 585 if (file.GetDirectory()) { 586 s << file.GetDirectory(); 587 return true; 588 } 589 break; 590 591 case FileKind::Fullpath: 592 if (file) { 593 s << file; 594 return true; 595 } 596 break; 597 } 598 return false; 599 } 600 601 static bool DumpRegister(Stream &s, StackFrame *frame, RegisterKind reg_kind, 602 uint32_t reg_num, Format format) 603 604 { 605 if (frame) { 606 RegisterContext *reg_ctx = frame->GetRegisterContext().get(); 607 608 if (reg_ctx) { 609 const uint32_t lldb_reg_num = 610 reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num); 611 if (lldb_reg_num != LLDB_INVALID_REGNUM) { 612 const RegisterInfo *reg_info = 613 reg_ctx->GetRegisterInfoAtIndex(lldb_reg_num); 614 if (reg_info) { 615 RegisterValue reg_value; 616 if (reg_ctx->ReadRegister(reg_info, reg_value)) { 617 DumpRegisterValue(reg_value, &s, reg_info, false, false, format); 618 return true; 619 } 620 } 621 } 622 } 623 } 624 return false; 625 } 626 627 static ValueObjectSP ExpandIndexedExpression(ValueObject *valobj, size_t index, 628 StackFrame *frame, 629 bool deref_pointer) { 630 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS)); 631 const char *ptr_deref_format = "[%d]"; 632 std::string ptr_deref_buffer(10, 0); 633 ::sprintf(&ptr_deref_buffer[0], ptr_deref_format, index); 634 LLDB_LOGF(log, "[ExpandIndexedExpression] name to deref: %s", 635 ptr_deref_buffer.c_str()); 636 ValueObject::GetValueForExpressionPathOptions options; 637 ValueObject::ExpressionPathEndResultType final_value_type; 638 ValueObject::ExpressionPathScanEndReason reason_to_stop; 639 ValueObject::ExpressionPathAftermath what_next = 640 (deref_pointer ? ValueObject::eExpressionPathAftermathDereference 641 : ValueObject::eExpressionPathAftermathNothing); 642 ValueObjectSP item = valobj->GetValueForExpressionPath( 643 ptr_deref_buffer.c_str(), &reason_to_stop, &final_value_type, options, 644 &what_next); 645 if (!item) { 646 LLDB_LOGF(log, 647 "[ExpandIndexedExpression] ERROR: why stopping = %d," 648 " final_value_type %d", 649 reason_to_stop, final_value_type); 650 } else { 651 LLDB_LOGF(log, 652 "[ExpandIndexedExpression] ALL RIGHT: why stopping = %d," 653 " final_value_type %d", 654 reason_to_stop, final_value_type); 655 } 656 return item; 657 } 658 659 static char ConvertValueObjectStyleToChar( 660 ValueObject::ValueObjectRepresentationStyle style) { 661 switch (style) { 662 case ValueObject::eValueObjectRepresentationStyleLanguageSpecific: 663 return '@'; 664 case ValueObject::eValueObjectRepresentationStyleValue: 665 return 'V'; 666 case ValueObject::eValueObjectRepresentationStyleLocation: 667 return 'L'; 668 case ValueObject::eValueObjectRepresentationStyleSummary: 669 return 'S'; 670 case ValueObject::eValueObjectRepresentationStyleChildrenCount: 671 return '#'; 672 case ValueObject::eValueObjectRepresentationStyleType: 673 return 'T'; 674 case ValueObject::eValueObjectRepresentationStyleName: 675 return 'N'; 676 case ValueObject::eValueObjectRepresentationStyleExpressionPath: 677 return '>'; 678 } 679 return '\0'; 680 } 681 682 static bool DumpValue(Stream &s, const SymbolContext *sc, 683 const ExecutionContext *exe_ctx, 684 const FormatEntity::Entry &entry, ValueObject *valobj) { 685 if (valobj == nullptr) 686 return false; 687 688 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS)); 689 Format custom_format = eFormatInvalid; 690 ValueObject::ValueObjectRepresentationStyle val_obj_display = 691 entry.string.empty() 692 ? ValueObject::eValueObjectRepresentationStyleValue 693 : ValueObject::eValueObjectRepresentationStyleSummary; 694 695 bool do_deref_pointer = entry.deref; 696 bool is_script = false; 697 switch (entry.type) { 698 case FormatEntity::Entry::Type::ScriptVariable: 699 is_script = true; 700 break; 701 702 case FormatEntity::Entry::Type::Variable: 703 custom_format = entry.fmt; 704 val_obj_display = (ValueObject::ValueObjectRepresentationStyle)entry.number; 705 break; 706 707 case FormatEntity::Entry::Type::ScriptVariableSynthetic: 708 is_script = true; 709 LLVM_FALLTHROUGH; 710 case FormatEntity::Entry::Type::VariableSynthetic: 711 custom_format = entry.fmt; 712 val_obj_display = (ValueObject::ValueObjectRepresentationStyle)entry.number; 713 if (!valobj->IsSynthetic()) { 714 valobj = valobj->GetSyntheticValue().get(); 715 if (valobj == nullptr) 716 return false; 717 } 718 break; 719 720 default: 721 return false; 722 } 723 724 if (valobj == nullptr) 725 return false; 726 727 ValueObject::ExpressionPathAftermath what_next = 728 (do_deref_pointer ? ValueObject::eExpressionPathAftermathDereference 729 : ValueObject::eExpressionPathAftermathNothing); 730 ValueObject::GetValueForExpressionPathOptions options; 731 options.DontCheckDotVsArrowSyntax() 732 .DoAllowBitfieldSyntax() 733 .DoAllowFragileIVar() 734 .SetSyntheticChildrenTraversal( 735 ValueObject::GetValueForExpressionPathOptions:: 736 SyntheticChildrenTraversal::Both); 737 ValueObject *target = nullptr; 738 const char *var_name_final_if_array_range = nullptr; 739 size_t close_bracket_index = llvm::StringRef::npos; 740 int64_t index_lower = -1; 741 int64_t index_higher = -1; 742 bool is_array_range = false; 743 bool was_plain_var = false; 744 bool was_var_format = false; 745 bool was_var_indexed = false; 746 ValueObject::ExpressionPathScanEndReason reason_to_stop = 747 ValueObject::eExpressionPathScanEndReasonEndOfString; 748 ValueObject::ExpressionPathEndResultType final_value_type = 749 ValueObject::eExpressionPathEndResultTypePlain; 750 751 if (is_script) { 752 return RunScriptFormatKeyword(s, sc, exe_ctx, valobj, entry.string.c_str()); 753 } 754 755 llvm::StringRef subpath(entry.string); 756 // simplest case ${var}, just print valobj's value 757 if (entry.string.empty()) { 758 if (entry.printf_format.empty() && entry.fmt == eFormatDefault && 759 entry.number == ValueObject::eValueObjectRepresentationStyleValue) 760 was_plain_var = true; 761 else 762 was_var_format = true; 763 target = valobj; 764 } else // this is ${var.something} or multiple .something nested 765 { 766 if (entry.string[0] == '[') 767 was_var_indexed = true; 768 ScanBracketedRange(subpath, close_bracket_index, 769 var_name_final_if_array_range, index_lower, 770 index_higher); 771 772 Status error; 773 774 const std::string &expr_path = entry.string; 775 776 LLDB_LOGF(log, "[Debugger::FormatPrompt] symbol to expand: %s", 777 expr_path.c_str()); 778 779 target = 780 valobj 781 ->GetValueForExpressionPath(expr_path.c_str(), &reason_to_stop, 782 &final_value_type, options, &what_next) 783 .get(); 784 785 if (!target) { 786 LLDB_LOGF(log, 787 "[Debugger::FormatPrompt] ERROR: why stopping = %d," 788 " final_value_type %d", 789 reason_to_stop, final_value_type); 790 return false; 791 } else { 792 LLDB_LOGF(log, 793 "[Debugger::FormatPrompt] ALL RIGHT: why stopping = %d," 794 " final_value_type %d", 795 reason_to_stop, final_value_type); 796 target = target 797 ->GetQualifiedRepresentationIfAvailable( 798 target->GetDynamicValueType(), true) 799 .get(); 800 } 801 } 802 803 is_array_range = 804 (final_value_type == 805 ValueObject::eExpressionPathEndResultTypeBoundedRange || 806 final_value_type == 807 ValueObject::eExpressionPathEndResultTypeUnboundedRange); 808 809 do_deref_pointer = 810 (what_next == ValueObject::eExpressionPathAftermathDereference); 811 812 if (do_deref_pointer && !is_array_range) { 813 // I have not deref-ed yet, let's do it 814 // this happens when we are not going through 815 // GetValueForVariableExpressionPath to get to the target ValueObject 816 Status error; 817 target = target->Dereference(error).get(); 818 if (error.Fail()) { 819 LLDB_LOGF(log, "[Debugger::FormatPrompt] ERROR: %s\n", 820 error.AsCString("unknown")); 821 return false; 822 } 823 do_deref_pointer = false; 824 } 825 826 if (!target) { 827 LLDB_LOGF(log, "[Debugger::FormatPrompt] could not calculate target for " 828 "prompt expression"); 829 return false; 830 } 831 832 // we do not want to use the summary for a bitfield of type T:n if we were 833 // originally dealing with just a T - that would get us into an endless 834 // recursion 835 if (target->IsBitfield() && was_var_indexed) { 836 // TODO: check for a (T:n)-specific summary - we should still obey that 837 StreamString bitfield_name; 838 bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(), 839 target->GetBitfieldBitSize()); 840 auto type_sp = std::make_shared<TypeNameSpecifierImpl>( 841 bitfield_name.GetString(), false); 842 if (val_obj_display == 843 ValueObject::eValueObjectRepresentationStyleSummary && 844 !DataVisualization::GetSummaryForType(type_sp)) 845 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue; 846 } 847 848 // TODO use flags for these 849 const uint32_t type_info_flags = 850 target->GetCompilerType().GetTypeInfo(nullptr); 851 bool is_array = (type_info_flags & eTypeIsArray) != 0; 852 bool is_pointer = (type_info_flags & eTypeIsPointer) != 0; 853 bool is_aggregate = target->GetCompilerType().IsAggregateType(); 854 855 if ((is_array || is_pointer) && (!is_array_range) && 856 val_obj_display == 857 ValueObject::eValueObjectRepresentationStyleValue) // this should be 858 // wrong, but there 859 // are some 860 // exceptions 861 { 862 StreamString str_temp; 863 LLDB_LOGF(log, 864 "[Debugger::FormatPrompt] I am into array || pointer && !range"); 865 866 if (target->HasSpecialPrintableRepresentation(val_obj_display, 867 custom_format)) { 868 // try to use the special cases 869 bool success = target->DumpPrintableRepresentation( 870 str_temp, val_obj_display, custom_format); 871 LLDB_LOGF(log, "[Debugger::FormatPrompt] special cases did%s match", 872 success ? "" : "n't"); 873 874 // should not happen 875 if (success) 876 s << str_temp.GetString(); 877 return true; 878 } else { 879 if (was_plain_var) // if ${var} 880 { 881 s << target->GetTypeName() << " @ " << target->GetLocationAsCString(); 882 } else if (is_pointer) // if pointer, value is the address stored 883 { 884 target->DumpPrintableRepresentation( 885 s, val_obj_display, custom_format, 886 ValueObject::PrintableRepresentationSpecialCases::eDisable); 887 } 888 return true; 889 } 890 } 891 892 // if directly trying to print ${var}, and this is an aggregate, display a 893 // nice type @ location message 894 if (is_aggregate && was_plain_var) { 895 s << target->GetTypeName() << " @ " << target->GetLocationAsCString(); 896 return true; 897 } 898 899 // if directly trying to print ${var%V}, and this is an aggregate, do not let 900 // the user do it 901 if (is_aggregate && 902 ((was_var_format && 903 val_obj_display == 904 ValueObject::eValueObjectRepresentationStyleValue))) { 905 s << "<invalid use of aggregate type>"; 906 return true; 907 } 908 909 if (!is_array_range) { 910 LLDB_LOGF(log, 911 "[Debugger::FormatPrompt] dumping ordinary printable output"); 912 return target->DumpPrintableRepresentation(s, val_obj_display, 913 custom_format); 914 } else { 915 LLDB_LOGF(log, 916 "[Debugger::FormatPrompt] checking if I can handle as array"); 917 if (!is_array && !is_pointer) 918 return false; 919 LLDB_LOGF(log, "[Debugger::FormatPrompt] handle as array"); 920 StreamString special_directions_stream; 921 llvm::StringRef special_directions; 922 if (close_bracket_index != llvm::StringRef::npos && 923 subpath.size() > close_bracket_index) { 924 ConstString additional_data(subpath.drop_front(close_bracket_index + 1)); 925 special_directions_stream.Printf("${%svar%s", do_deref_pointer ? "*" : "", 926 additional_data.GetCString()); 927 928 if (entry.fmt != eFormatDefault) { 929 const char format_char = 930 FormatManager::GetFormatAsFormatChar(entry.fmt); 931 if (format_char != '\0') 932 special_directions_stream.Printf("%%%c", format_char); 933 else { 934 const char *format_cstr = 935 FormatManager::GetFormatAsCString(entry.fmt); 936 special_directions_stream.Printf("%%%s", format_cstr); 937 } 938 } else if (entry.number != 0) { 939 const char style_char = ConvertValueObjectStyleToChar( 940 (ValueObject::ValueObjectRepresentationStyle)entry.number); 941 if (style_char) 942 special_directions_stream.Printf("%%%c", style_char); 943 } 944 special_directions_stream.PutChar('}'); 945 special_directions = 946 llvm::StringRef(special_directions_stream.GetString()); 947 } 948 949 // let us display items index_lower thru index_higher of this array 950 s.PutChar('['); 951 952 if (index_higher < 0) 953 index_higher = valobj->GetNumChildren() - 1; 954 955 uint32_t max_num_children = 956 target->GetTargetSP()->GetMaximumNumberOfChildrenToDisplay(); 957 958 bool success = true; 959 for (int64_t index = index_lower; index <= index_higher; ++index) { 960 ValueObject *item = 961 ExpandIndexedExpression(target, index, exe_ctx->GetFramePtr(), false) 962 .get(); 963 964 if (!item) { 965 LLDB_LOGF(log, 966 "[Debugger::FormatPrompt] ERROR in getting child item at " 967 "index %" PRId64, 968 index); 969 } else { 970 LLDB_LOGF( 971 log, 972 "[Debugger::FormatPrompt] special_directions for child item: %s", 973 special_directions.data() ? special_directions.data() : ""); 974 } 975 976 if (special_directions.empty()) { 977 success &= item->DumpPrintableRepresentation(s, val_obj_display, 978 custom_format); 979 } else { 980 success &= FormatEntity::FormatStringRef( 981 special_directions, s, sc, exe_ctx, nullptr, item, false, false); 982 } 983 984 if (--max_num_children == 0) { 985 s.PutCString(", ..."); 986 break; 987 } 988 989 if (index < index_higher) 990 s.PutChar(','); 991 } 992 s.PutChar(']'); 993 return success; 994 } 995 } 996 997 static bool DumpRegister(Stream &s, StackFrame *frame, const char *reg_name, 998 Format format) { 999 if (frame) { 1000 RegisterContext *reg_ctx = frame->GetRegisterContext().get(); 1001 1002 if (reg_ctx) { 1003 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name); 1004 if (reg_info) { 1005 RegisterValue reg_value; 1006 if (reg_ctx->ReadRegister(reg_info, reg_value)) { 1007 DumpRegisterValue(reg_value, &s, reg_info, false, false, format); 1008 return true; 1009 } 1010 } 1011 } 1012 } 1013 return false; 1014 } 1015 1016 static bool FormatThreadExtendedInfoRecurse( 1017 const FormatEntity::Entry &entry, 1018 const StructuredData::ObjectSP &thread_info_dictionary, 1019 const SymbolContext *sc, const ExecutionContext *exe_ctx, Stream &s) { 1020 llvm::StringRef path(entry.string); 1021 1022 StructuredData::ObjectSP value = 1023 thread_info_dictionary->GetObjectForDotSeparatedPath(path); 1024 1025 if (value) { 1026 if (value->GetType() == eStructuredDataTypeInteger) { 1027 const char *token_format = "0x%4.4" PRIx64; 1028 if (!entry.printf_format.empty()) 1029 token_format = entry.printf_format.c_str(); 1030 s.Printf(token_format, value->GetAsInteger()->GetValue()); 1031 return true; 1032 } else if (value->GetType() == eStructuredDataTypeFloat) { 1033 s.Printf("%f", value->GetAsFloat()->GetValue()); 1034 return true; 1035 } else if (value->GetType() == eStructuredDataTypeString) { 1036 s.Format("{0}", value->GetAsString()->GetValue()); 1037 return true; 1038 } else if (value->GetType() == eStructuredDataTypeArray) { 1039 if (value->GetAsArray()->GetSize() > 0) { 1040 s.Printf("%zu", value->GetAsArray()->GetSize()); 1041 return true; 1042 } 1043 } else if (value->GetType() == eStructuredDataTypeDictionary) { 1044 s.Printf("%zu", 1045 value->GetAsDictionary()->GetKeys()->GetAsArray()->GetSize()); 1046 return true; 1047 } 1048 } 1049 1050 return false; 1051 } 1052 1053 static inline bool IsToken(const char *var_name_begin, const char *var) { 1054 return (::strncmp(var_name_begin, var, strlen(var)) == 0); 1055 } 1056 1057 bool FormatEntity::FormatStringRef(const llvm::StringRef &format_str, Stream &s, 1058 const SymbolContext *sc, 1059 const ExecutionContext *exe_ctx, 1060 const Address *addr, ValueObject *valobj, 1061 bool function_changed, 1062 bool initial_function) { 1063 if (!format_str.empty()) { 1064 FormatEntity::Entry root; 1065 Status error = FormatEntity::Parse(format_str, root); 1066 if (error.Success()) { 1067 return FormatEntity::Format(root, s, sc, exe_ctx, addr, valobj, 1068 function_changed, initial_function); 1069 } 1070 } 1071 return false; 1072 } 1073 1074 bool FormatEntity::FormatCString(const char *format, Stream &s, 1075 const SymbolContext *sc, 1076 const ExecutionContext *exe_ctx, 1077 const Address *addr, ValueObject *valobj, 1078 bool function_changed, bool initial_function) { 1079 if (format && format[0]) { 1080 FormatEntity::Entry root; 1081 llvm::StringRef format_str(format); 1082 Status error = FormatEntity::Parse(format_str, root); 1083 if (error.Success()) { 1084 return FormatEntity::Format(root, s, sc, exe_ctx, addr, valobj, 1085 function_changed, initial_function); 1086 } 1087 } 1088 return false; 1089 } 1090 1091 bool FormatEntity::Format(const Entry &entry, Stream &s, 1092 const SymbolContext *sc, 1093 const ExecutionContext *exe_ctx, const Address *addr, 1094 ValueObject *valobj, bool function_changed, 1095 bool initial_function) { 1096 switch (entry.type) { 1097 case Entry::Type::Invalid: 1098 case Entry::Type::ParentNumber: // Only used for 1099 // FormatEntity::Entry::Definition encoding 1100 case Entry::Type::ParentString: // Only used for 1101 // FormatEntity::Entry::Definition encoding 1102 return false; 1103 case Entry::Type::EscapeCode: 1104 if (exe_ctx) { 1105 if (Target *target = exe_ctx->GetTargetPtr()) { 1106 Debugger &debugger = target->GetDebugger(); 1107 if (debugger.GetUseColor()) { 1108 s.PutCString(entry.string); 1109 } 1110 } 1111 } 1112 // Always return true, so colors being disabled is transparent. 1113 return true; 1114 1115 case Entry::Type::Root: 1116 for (const auto &child : entry.children) { 1117 if (!Format(child, s, sc, exe_ctx, addr, valobj, function_changed, 1118 initial_function)) { 1119 return false; // If any item of root fails, then the formatting fails 1120 } 1121 } 1122 return true; // Only return true if all items succeeded 1123 1124 case Entry::Type::String: 1125 s.PutCString(entry.string); 1126 return true; 1127 1128 case Entry::Type::Scope: { 1129 StreamString scope_stream; 1130 bool success = false; 1131 for (const auto &child : entry.children) { 1132 success = Format(child, scope_stream, sc, exe_ctx, addr, valobj, 1133 function_changed, initial_function); 1134 if (!success) 1135 break; 1136 } 1137 // Only if all items in a scope succeed, then do we print the output into 1138 // the main stream 1139 if (success) 1140 s.Write(scope_stream.GetString().data(), scope_stream.GetString().size()); 1141 } 1142 return true; // Scopes always successfully print themselves 1143 1144 case Entry::Type::Variable: 1145 case Entry::Type::VariableSynthetic: 1146 case Entry::Type::ScriptVariable: 1147 case Entry::Type::ScriptVariableSynthetic: 1148 return DumpValue(s, sc, exe_ctx, entry, valobj); 1149 1150 case Entry::Type::AddressFile: 1151 case Entry::Type::AddressLoad: 1152 case Entry::Type::AddressLoadOrFile: 1153 return ( 1154 addr != nullptr && addr->IsValid() && 1155 DumpAddressAndContent(s, sc, exe_ctx, *addr, 1156 entry.type == Entry::Type::AddressLoadOrFile)); 1157 1158 case Entry::Type::ProcessID: 1159 if (exe_ctx) { 1160 Process *process = exe_ctx->GetProcessPtr(); 1161 if (process) { 1162 const char *format = "%" PRIu64; 1163 if (!entry.printf_format.empty()) 1164 format = entry.printf_format.c_str(); 1165 s.Printf(format, process->GetID()); 1166 return true; 1167 } 1168 } 1169 return false; 1170 1171 case Entry::Type::ProcessFile: 1172 if (exe_ctx) { 1173 Process *process = exe_ctx->GetProcessPtr(); 1174 if (process) { 1175 Module *exe_module = process->GetTarget().GetExecutableModulePointer(); 1176 if (exe_module) { 1177 if (DumpFile(s, exe_module->GetFileSpec(), (FileKind)entry.number)) 1178 return true; 1179 } 1180 } 1181 } 1182 return false; 1183 1184 case Entry::Type::ScriptProcess: 1185 if (exe_ctx) { 1186 Process *process = exe_ctx->GetProcessPtr(); 1187 if (process) 1188 return RunScriptFormatKeyword(s, sc, exe_ctx, process, 1189 entry.string.c_str()); 1190 } 1191 return false; 1192 1193 case Entry::Type::ThreadID: 1194 if (exe_ctx) { 1195 Thread *thread = exe_ctx->GetThreadPtr(); 1196 if (thread) { 1197 const char *format = "0x%4.4" PRIx64; 1198 if (!entry.printf_format.empty()) { 1199 // Watch for the special "tid" format... 1200 if (entry.printf_format == "tid") { 1201 // TODO(zturner): Rather than hardcoding this to be platform 1202 // specific, it should be controlled by a setting and the default 1203 // value of the setting can be different depending on the platform. 1204 Target &target = thread->GetProcess()->GetTarget(); 1205 ArchSpec arch(target.GetArchitecture()); 1206 llvm::Triple::OSType ostype = arch.IsValid() 1207 ? arch.GetTriple().getOS() 1208 : llvm::Triple::UnknownOS; 1209 if ((ostype == llvm::Triple::FreeBSD) || 1210 (ostype == llvm::Triple::Linux) || 1211 (ostype == llvm::Triple::NetBSD)) { 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 entites 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