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