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