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