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