1 //===-- Debugger.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/Debugger.h" 11 12 // C Includes 13 // C++ Includes 14 #include <map> 15 #include <mutex> 16 17 // Other libraries and framework includes 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/Support/DynamicLibrary.h" 20 21 // Project includes 22 #include "lldb/lldb-private.h" 23 #include "lldb/Core/FormatEntity.h" 24 #include "lldb/Core/Module.h" 25 #include "lldb/Core/PluginInterface.h" 26 #include "lldb/Core/PluginManager.h" 27 #include "lldb/Core/RegisterValue.h" 28 #include "lldb/Core/State.h" 29 #include "lldb/Core/StreamAsynchronousIO.h" 30 #include "lldb/Core/StreamCallback.h" 31 #include "lldb/Core/StreamFile.h" 32 #include "lldb/Core/StreamString.h" 33 #include "lldb/Core/StructuredData.h" 34 #include "lldb/Core/Timer.h" 35 #include "lldb/Core/ValueObject.h" 36 #include "lldb/Core/ValueObjectVariable.h" 37 #include "lldb/DataFormatters/DataVisualization.h" 38 #include "lldb/DataFormatters/FormatManager.h" 39 #include "lldb/DataFormatters/TypeSummary.h" 40 #include "lldb/Expression/REPL.h" 41 #include "lldb/Host/ConnectionFileDescriptor.h" 42 #include "lldb/Host/HostInfo.h" 43 #include "lldb/Host/Terminal.h" 44 #include "lldb/Host/ThreadLauncher.h" 45 #include "lldb/Interpreter/CommandInterpreter.h" 46 #include "lldb/Interpreter/OptionValueProperties.h" 47 #include "lldb/Interpreter/OptionValueSInt64.h" 48 #include "lldb/Interpreter/OptionValueString.h" 49 #include "lldb/Symbol/CompileUnit.h" 50 #include "lldb/Symbol/Function.h" 51 #include "lldb/Symbol/Symbol.h" 52 #include "lldb/Symbol/VariableList.h" 53 #include "lldb/Target/TargetList.h" 54 #include "lldb/Target/Language.h" 55 #include "lldb/Target/Process.h" 56 #include "lldb/Target/RegisterContext.h" 57 #include "lldb/Target/SectionLoadList.h" 58 #include "lldb/Target/StopInfo.h" 59 #include "lldb/Target/StructuredDataPlugin.h" 60 #include "lldb/Target/Target.h" 61 #include "lldb/Target/Thread.h" 62 #include "lldb/Utility/AnsiTerminal.h" 63 64 using namespace lldb; 65 using namespace lldb_private; 66 67 static lldb::user_id_t g_unique_id = 1; 68 static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024; 69 70 #pragma mark Static Functions 71 72 typedef std::vector<DebuggerSP> DebuggerList; 73 static std::recursive_mutex *g_debugger_list_mutex_ptr = nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain 74 static DebuggerList *g_debugger_list_ptr = nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain 75 76 OptionEnumValueElement 77 g_show_disassembly_enum_values[] = 78 { 79 { Debugger::eStopDisassemblyTypeNever, "never", "Never show disassembly when displaying a stop context."}, 80 { Debugger::eStopDisassemblyTypeNoDebugInfo, "no-debuginfo", "Show disassembly when there is no debug information."}, 81 { Debugger::eStopDisassemblyTypeNoSource, "no-source", "Show disassembly when there is no source information, or the source file is missing when displaying a stop context."}, 82 { Debugger::eStopDisassemblyTypeAlways, "always", "Always show disassembly when displaying a stop context."}, 83 { 0, nullptr, nullptr } 84 }; 85 86 OptionEnumValueElement 87 g_language_enumerators[] = 88 { 89 { eScriptLanguageNone, "none", "Disable scripting languages."}, 90 { eScriptLanguagePython, "python", "Select python as the default scripting language."}, 91 { eScriptLanguageDefault, "default", "Select the lldb default as the default scripting language."}, 92 { 0, nullptr, nullptr } 93 }; 94 95 #define MODULE_WITH_FUNC "{ ${module.file.basename}{`${function.name-with-args}${function.pc-offset}}}" 96 #define FILE_AND_LINE "{ at ${line.file.basename}:${line.number}}" 97 #define IS_OPTIMIZED "{${function.is-optimized} [opt]}" 98 99 #define DEFAULT_THREAD_FORMAT "thread #${thread.index}: tid = ${thread.id%tid}"\ 100 "{, ${frame.pc}}"\ 101 MODULE_WITH_FUNC\ 102 FILE_AND_LINE\ 103 "{, name = '${thread.name}'}"\ 104 "{, queue = '${thread.queue}'}"\ 105 "{, activity = '${thread.info.activity.name}'}" \ 106 "{, ${thread.info.trace_messages} messages}" \ 107 "{, stop reason = ${thread.stop-reason}}"\ 108 "{\\nReturn value: ${thread.return-value}}"\ 109 "{\\nCompleted expression: ${thread.completed-expression}}"\ 110 "\\n" 111 112 #define DEFAULT_FRAME_FORMAT "frame #${frame.index}: ${frame.pc}"\ 113 MODULE_WITH_FUNC\ 114 FILE_AND_LINE\ 115 IS_OPTIMIZED\ 116 "\\n" 117 118 // Three parts to this disassembly format specification: 119 // 1. If this is a new function/symbol (no previous symbol/function), print 120 // dylib`funcname:\n 121 // 2. If this is a symbol context change (different from previous symbol/function), print 122 // dylib`funcname:\n 123 // 3. print 124 // address <+offset>: 125 #define DEFAULT_DISASSEMBLY_FORMAT "{${function.initial-function}{${module.file.basename}`}{${function.name-without-args}}:\n}{${function.changed}\n{${module.file.basename}`}{${function.name-without-args}}:\n}{${current-pc-arrow} }${addr-file-or-load}{ <${function.concrete-only-addr-offset-no-padding}>}: " 126 127 // gdb's disassembly format can be emulated with 128 // ${current-pc-arrow}${addr-file-or-load}{ <${function.name-without-args}${function.concrete-only-addr-offset-no-padding}>}: 129 130 // lldb's original format for disassembly would look like this format string - 131 // {${function.initial-function}{${module.file.basename}`}{${function.name-without-args}}:\n}{${function.changed}\n{${module.file.basename}`}{${function.name-without-args}}:\n}{${current-pc-arrow} }{${addr-file-or-load}}: 132 133 static PropertyDefinition 134 g_properties[] = 135 { 136 { "auto-confirm", OptionValue::eTypeBoolean , true, false, nullptr, nullptr, "If true all confirmation prompts will receive their default reply." }, 137 { "disassembly-format", OptionValue::eTypeFormatEntity, true, 0 , DEFAULT_DISASSEMBLY_FORMAT, nullptr, "The default disassembly format string to use when disassembling instruction sequences." }, 138 { "frame-format", OptionValue::eTypeFormatEntity, true, 0 , DEFAULT_FRAME_FORMAT, nullptr, "The default frame format string to use when displaying stack frame information for threads." }, 139 { "notify-void", OptionValue::eTypeBoolean , true, false, nullptr, nullptr, "Notify the user explicitly if an expression returns void (default: false)." }, 140 { "prompt", OptionValue::eTypeString , true, OptionValueString::eOptionEncodeCharacterEscapeSequences, "(lldb) ", nullptr, "The debugger command line prompt displayed for the user." }, 141 { "script-lang", OptionValue::eTypeEnum , true, eScriptLanguagePython, nullptr, g_language_enumerators, "The script language to be used for evaluating user-written scripts." }, 142 { "stop-disassembly-count", OptionValue::eTypeSInt64 , true, 4 , nullptr, nullptr, "The number of disassembly lines to show when displaying a stopped context." }, 143 { "stop-disassembly-display", OptionValue::eTypeEnum , true, Debugger::eStopDisassemblyTypeNoDebugInfo, nullptr, g_show_disassembly_enum_values, "Control when to display disassembly when displaying a stopped context." }, 144 { "stop-line-count-after", OptionValue::eTypeSInt64 , true, 3 , nullptr, nullptr, "The number of sources lines to display that come after the current source line when displaying a stopped context." }, 145 { "stop-line-count-before", OptionValue::eTypeSInt64 , true, 3 , nullptr, nullptr, "The number of sources lines to display that come before the current source line when displaying a stopped context." }, 146 { "term-width", OptionValue::eTypeSInt64 , true, 80 , nullptr, nullptr, "The maximum number of columns to use for displaying text." }, 147 { "thread-format", OptionValue::eTypeFormatEntity, true, 0 , DEFAULT_THREAD_FORMAT, nullptr, "The default thread format string to use when displaying thread information." }, 148 { "use-external-editor", OptionValue::eTypeBoolean , true, false, nullptr, nullptr, "Whether to use an external editor or not." }, 149 { "use-color", OptionValue::eTypeBoolean , true, true , nullptr, nullptr, "Whether to use Ansi color codes or not." }, 150 { "auto-one-line-summaries", OptionValue::eTypeBoolean , true, true, nullptr, nullptr, "If true, LLDB will automatically display small structs in one-liner format (default: true)." }, 151 { "auto-indent", OptionValue::eTypeBoolean , true, true , nullptr, nullptr, "If true, LLDB will auto indent/outdent code. Currently only supported in the REPL (default: true)." }, 152 { "print-decls", OptionValue::eTypeBoolean , true, true , nullptr, nullptr, "If true, LLDB will print the values of variables declared in an expression. Currently only supported in the REPL (default: true)." }, 153 { "tab-size", OptionValue::eTypeUInt64 , true, 4 , nullptr, nullptr, "The tab size to use when indenting code in multi-line input mode (default: 4)." }, 154 { "escape-non-printables", OptionValue::eTypeBoolean , true, true, nullptr, nullptr, "If true, LLDB will automatically escape non-printable and escape characters when formatting strings." }, 155 { nullptr, OptionValue::eTypeInvalid , true, 0 , nullptr, nullptr, nullptr } 156 }; 157 158 enum 159 { 160 ePropertyAutoConfirm = 0, 161 ePropertyDisassemblyFormat, 162 ePropertyFrameFormat, 163 ePropertyNotiftVoid, 164 ePropertyPrompt, 165 ePropertyScriptLanguage, 166 ePropertyStopDisassemblyCount, 167 ePropertyStopDisassemblyDisplay, 168 ePropertyStopLineCountAfter, 169 ePropertyStopLineCountBefore, 170 ePropertyTerminalWidth, 171 ePropertyThreadFormat, 172 ePropertyUseExternalEditor, 173 ePropertyUseColor, 174 ePropertyAutoOneLineSummaries, 175 ePropertyAutoIndent, 176 ePropertyPrintDecls, 177 ePropertyTabSize, 178 ePropertyEscapeNonPrintables 179 }; 180 181 LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr; 182 183 Error 184 Debugger::SetPropertyValue (const ExecutionContext *exe_ctx, 185 VarSetOperationType op, 186 const char *property_path, 187 const char *value) 188 { 189 bool is_load_script = strcmp(property_path,"target.load-script-from-symbol-file") == 0; 190 bool is_escape_non_printables = strcmp(property_path, "escape-non-printables") == 0; 191 TargetSP target_sp; 192 LoadScriptFromSymFile load_script_old_value; 193 if (is_load_script && exe_ctx->GetTargetSP()) 194 { 195 target_sp = exe_ctx->GetTargetSP(); 196 load_script_old_value = target_sp->TargetProperties::GetLoadScriptFromSymbolFile(); 197 } 198 Error error (Properties::SetPropertyValue (exe_ctx, op, property_path, value)); 199 if (error.Success()) 200 { 201 // FIXME it would be nice to have "on-change" callbacks for properties 202 if (strcmp(property_path, g_properties[ePropertyPrompt].name) == 0) 203 { 204 const char *new_prompt = GetPrompt(); 205 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor()); 206 if (str.length()) 207 new_prompt = str.c_str(); 208 GetCommandInterpreter().UpdatePrompt(new_prompt); 209 EventSP prompt_change_event_sp (new Event(CommandInterpreter::eBroadcastBitResetPrompt, new EventDataBytes (new_prompt))); 210 GetCommandInterpreter().BroadcastEvent (prompt_change_event_sp); 211 } 212 else if (strcmp(property_path, g_properties[ePropertyUseColor].name) == 0) 213 { 214 // use-color changed. Ping the prompt so it can reset the ansi terminal codes. 215 SetPrompt (GetPrompt()); 216 } 217 else if (is_load_script && target_sp && load_script_old_value == eLoadScriptFromSymFileWarn) 218 { 219 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() == eLoadScriptFromSymFileTrue) 220 { 221 std::list<Error> errors; 222 StreamString feedback_stream; 223 if (!target_sp->LoadScriptingResources(errors,&feedback_stream)) 224 { 225 StreamFileSP stream_sp (GetErrorFile()); 226 if (stream_sp) 227 { 228 for (auto error : errors) 229 { 230 stream_sp->Printf("%s\n",error.AsCString()); 231 } 232 if (feedback_stream.GetSize()) 233 stream_sp->Printf("%s",feedback_stream.GetData()); 234 } 235 } 236 } 237 } 238 else if (is_escape_non_printables) 239 { 240 DataVisualization::ForceUpdate(); 241 } 242 } 243 return error; 244 } 245 246 bool 247 Debugger::GetAutoConfirm () const 248 { 249 const uint32_t idx = ePropertyAutoConfirm; 250 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0); 251 } 252 253 const FormatEntity::Entry * 254 Debugger::GetDisassemblyFormat() const 255 { 256 const uint32_t idx = ePropertyDisassemblyFormat; 257 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx); 258 } 259 260 const FormatEntity::Entry * 261 Debugger::GetFrameFormat() const 262 { 263 const uint32_t idx = ePropertyFrameFormat; 264 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx); 265 } 266 267 bool 268 Debugger::GetNotifyVoid () const 269 { 270 const uint32_t idx = ePropertyNotiftVoid; 271 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0); 272 } 273 274 const char * 275 Debugger::GetPrompt() const 276 { 277 const uint32_t idx = ePropertyPrompt; 278 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, g_properties[idx].default_cstr_value); 279 } 280 281 void 282 Debugger::SetPrompt(const char *p) 283 { 284 const uint32_t idx = ePropertyPrompt; 285 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p); 286 const char *new_prompt = GetPrompt(); 287 std::string str = lldb_utility::ansi::FormatAnsiTerminalCodes (new_prompt, GetUseColor()); 288 if (str.length()) 289 new_prompt = str.c_str(); 290 GetCommandInterpreter().UpdatePrompt(new_prompt); 291 } 292 293 const FormatEntity::Entry * 294 Debugger::GetThreadFormat() const 295 { 296 const uint32_t idx = ePropertyThreadFormat; 297 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx); 298 } 299 300 lldb::ScriptLanguage 301 Debugger::GetScriptLanguage() const 302 { 303 const uint32_t idx = ePropertyScriptLanguage; 304 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(nullptr, idx, g_properties[idx].default_uint_value); 305 } 306 307 bool 308 Debugger::SetScriptLanguage (lldb::ScriptLanguage script_lang) 309 { 310 const uint32_t idx = ePropertyScriptLanguage; 311 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, script_lang); 312 } 313 314 uint32_t 315 Debugger::GetTerminalWidth () const 316 { 317 const uint32_t idx = ePropertyTerminalWidth; 318 return m_collection_sp->GetPropertyAtIndexAsSInt64(nullptr, idx, g_properties[idx].default_uint_value); 319 } 320 321 bool 322 Debugger::SetTerminalWidth (uint32_t term_width) 323 { 324 const uint32_t idx = ePropertyTerminalWidth; 325 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width); 326 } 327 328 bool 329 Debugger::GetUseExternalEditor () const 330 { 331 const uint32_t idx = ePropertyUseExternalEditor; 332 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0); 333 } 334 335 bool 336 Debugger::SetUseExternalEditor (bool b) 337 { 338 const uint32_t idx = ePropertyUseExternalEditor; 339 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 340 } 341 342 bool 343 Debugger::GetUseColor () const 344 { 345 const uint32_t idx = ePropertyUseColor; 346 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0); 347 } 348 349 bool 350 Debugger::SetUseColor (bool b) 351 { 352 const uint32_t idx = ePropertyUseColor; 353 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 354 SetPrompt (GetPrompt()); 355 return ret; 356 } 357 358 uint32_t 359 Debugger::GetStopSourceLineCount (bool before) const 360 { 361 const uint32_t idx = before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter; 362 return m_collection_sp->GetPropertyAtIndexAsSInt64(nullptr, idx, g_properties[idx].default_uint_value); 363 } 364 365 Debugger::StopDisassemblyType 366 Debugger::GetStopDisassemblyDisplay () const 367 { 368 const uint32_t idx = ePropertyStopDisassemblyDisplay; 369 return (Debugger::StopDisassemblyType)m_collection_sp->GetPropertyAtIndexAsEnumeration(nullptr, idx, g_properties[idx].default_uint_value); 370 } 371 372 uint32_t 373 Debugger::GetDisassemblyLineCount () const 374 { 375 const uint32_t idx = ePropertyStopDisassemblyCount; 376 return m_collection_sp->GetPropertyAtIndexAsSInt64(nullptr, idx, g_properties[idx].default_uint_value); 377 } 378 379 bool 380 Debugger::GetAutoOneLineSummaries () const 381 { 382 const uint32_t idx = ePropertyAutoOneLineSummaries; 383 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true); 384 } 385 386 bool 387 Debugger::GetEscapeNonPrintables () const 388 { 389 const uint32_t idx = ePropertyEscapeNonPrintables; 390 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true); 391 } 392 393 bool 394 Debugger::GetAutoIndent () const 395 { 396 const uint32_t idx = ePropertyAutoIndent; 397 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true); 398 } 399 400 bool 401 Debugger::SetAutoIndent (bool b) 402 { 403 const uint32_t idx = ePropertyAutoIndent; 404 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 405 } 406 407 bool 408 Debugger::GetPrintDecls () const 409 { 410 const uint32_t idx = ePropertyPrintDecls; 411 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true); 412 } 413 414 bool 415 Debugger::SetPrintDecls (bool b) 416 { 417 const uint32_t idx = ePropertyPrintDecls; 418 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 419 } 420 421 uint32_t 422 Debugger::GetTabSize () const 423 { 424 const uint32_t idx = ePropertyTabSize; 425 return m_collection_sp->GetPropertyAtIndexAsUInt64(nullptr, idx, g_properties[idx].default_uint_value); 426 } 427 428 bool 429 Debugger::SetTabSize (uint32_t tab_size) 430 { 431 const uint32_t idx = ePropertyTabSize; 432 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size); 433 } 434 435 #pragma mark Debugger 436 437 //const DebuggerPropertiesSP & 438 //Debugger::GetSettings() const 439 //{ 440 // return m_properties_sp; 441 //} 442 // 443 444 void 445 Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) 446 { 447 assert(g_debugger_list_ptr == nullptr && "Debugger::Initialize called more than once!"); 448 g_debugger_list_mutex_ptr = new std::recursive_mutex(); 449 g_debugger_list_ptr = new DebuggerList(); 450 g_load_plugin_callback = load_plugin_callback; 451 } 452 453 void 454 Debugger::Terminate () 455 { 456 assert(g_debugger_list_ptr && "Debugger::Terminate called without a matching Debugger::Initialize!"); 457 458 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) 459 { 460 // Clear our master list of debugger objects 461 { 462 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 463 for (const auto& debugger: *g_debugger_list_ptr) 464 debugger->Clear(); 465 g_debugger_list_ptr->clear(); 466 } 467 } 468 } 469 470 void 471 Debugger::SettingsInitialize () 472 { 473 Target::SettingsInitialize (); 474 } 475 476 void 477 Debugger::SettingsTerminate () 478 { 479 Target::SettingsTerminate (); 480 } 481 482 bool 483 Debugger::LoadPlugin (const FileSpec& spec, Error& error) 484 { 485 if (g_load_plugin_callback) 486 { 487 llvm::sys::DynamicLibrary dynlib = g_load_plugin_callback (shared_from_this(), spec, error); 488 if (dynlib.isValid()) 489 { 490 m_loaded_plugins.push_back(dynlib); 491 return true; 492 } 493 } 494 else 495 { 496 // The g_load_plugin_callback is registered in SBDebugger::Initialize() 497 // and if the public API layer isn't available (code is linking against 498 // all of the internal LLDB static libraries), then we can't load plugins 499 error.SetErrorString("Public API layer is not available"); 500 } 501 return false; 502 } 503 504 static FileSpec::EnumerateDirectoryResult 505 LoadPluginCallback(void *baton, 506 FileSpec::FileType file_type, 507 const FileSpec &file_spec) 508 { 509 Error error; 510 511 static ConstString g_dylibext("dylib"); 512 static ConstString g_solibext("so"); 513 514 if (!baton) 515 return FileSpec::eEnumerateDirectoryResultQuit; 516 517 Debugger *debugger = (Debugger*)baton; 518 519 // If we have a regular file, a symbolic link or unknown file type, try 520 // and process the file. We must handle unknown as sometimes the directory 521 // enumeration might be enumerating a file system that doesn't have correct 522 // file type information. 523 if (file_type == FileSpec::eFileTypeRegular || 524 file_type == FileSpec::eFileTypeSymbolicLink || 525 file_type == FileSpec::eFileTypeUnknown ) 526 { 527 FileSpec plugin_file_spec (file_spec); 528 plugin_file_spec.ResolvePath (); 529 530 if (plugin_file_spec.GetFileNameExtension() != g_dylibext && 531 plugin_file_spec.GetFileNameExtension() != g_solibext) 532 { 533 return FileSpec::eEnumerateDirectoryResultNext; 534 } 535 536 Error plugin_load_error; 537 debugger->LoadPlugin (plugin_file_spec, plugin_load_error); 538 539 return FileSpec::eEnumerateDirectoryResultNext; 540 } 541 else if (file_type == FileSpec::eFileTypeUnknown || 542 file_type == FileSpec::eFileTypeDirectory || 543 file_type == FileSpec::eFileTypeSymbolicLink ) 544 { 545 // Try and recurse into anything that a directory or symbolic link. 546 // We must also do this for unknown as sometimes the directory enumeration 547 // might be enumerating a file system that doesn't have correct file type 548 // information. 549 return FileSpec::eEnumerateDirectoryResultEnter; 550 } 551 552 return FileSpec::eEnumerateDirectoryResultNext; 553 } 554 555 void 556 Debugger::InstanceInitialize () 557 { 558 FileSpec dir_spec; 559 const bool find_directories = true; 560 const bool find_files = true; 561 const bool find_other = true; 562 char dir_path[PATH_MAX]; 563 if (HostInfo::GetLLDBPath(ePathTypeLLDBSystemPlugins, dir_spec)) 564 { 565 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path))) 566 { 567 FileSpec::EnumerateDirectory (dir_path, 568 find_directories, 569 find_files, 570 find_other, 571 LoadPluginCallback, 572 this); 573 } 574 } 575 576 if (HostInfo::GetLLDBPath(ePathTypeLLDBUserPlugins, dir_spec)) 577 { 578 if (dir_spec.Exists() && dir_spec.GetPath(dir_path, sizeof(dir_path))) 579 { 580 FileSpec::EnumerateDirectory (dir_path, 581 find_directories, 582 find_files, 583 find_other, 584 LoadPluginCallback, 585 this); 586 } 587 } 588 589 PluginManager::DebuggerInitialize (*this); 590 } 591 592 DebuggerSP 593 Debugger::CreateInstance (lldb::LogOutputCallback log_callback, void *baton) 594 { 595 DebuggerSP debugger_sp (new Debugger(log_callback, baton)); 596 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) 597 { 598 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 599 g_debugger_list_ptr->push_back(debugger_sp); 600 } 601 debugger_sp->InstanceInitialize (); 602 return debugger_sp; 603 } 604 605 void 606 Debugger::Destroy (DebuggerSP &debugger_sp) 607 { 608 if (!debugger_sp) 609 return; 610 611 debugger_sp->Clear(); 612 613 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) 614 { 615 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 616 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 617 for (pos = g_debugger_list_ptr->begin (); pos != end; ++pos) 618 { 619 if ((*pos).get() == debugger_sp.get()) 620 { 621 g_debugger_list_ptr->erase (pos); 622 return; 623 } 624 } 625 } 626 } 627 628 DebuggerSP 629 Debugger::FindDebuggerWithInstanceName (const ConstString &instance_name) 630 { 631 DebuggerSP debugger_sp; 632 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) 633 { 634 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 635 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 636 for (pos = g_debugger_list_ptr->begin (); pos != end; ++pos) 637 { 638 if ((*pos)->m_instance_name == instance_name) 639 { 640 debugger_sp = *pos; 641 break; 642 } 643 } 644 } 645 return debugger_sp; 646 } 647 648 TargetSP 649 Debugger::FindTargetWithProcessID (lldb::pid_t pid) 650 { 651 TargetSP target_sp; 652 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) 653 { 654 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 655 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 656 for (pos = g_debugger_list_ptr->begin (); pos != end; ++pos) 657 { 658 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID (pid); 659 if (target_sp) 660 break; 661 } 662 } 663 return target_sp; 664 } 665 666 TargetSP 667 Debugger::FindTargetWithProcess (Process *process) 668 { 669 TargetSP target_sp; 670 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) 671 { 672 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 673 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 674 for (pos = g_debugger_list_ptr->begin (); pos != end; ++pos) 675 { 676 target_sp = (*pos)->GetTargetList().FindTargetWithProcess (process); 677 if (target_sp) 678 break; 679 } 680 } 681 return target_sp; 682 } 683 684 Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton) : 685 UserID(g_unique_id++), 686 Properties(OptionValuePropertiesSP(new OptionValueProperties())), 687 m_input_file_sp(new StreamFile(stdin, false)), 688 m_output_file_sp(new StreamFile(stdout, false)), 689 m_error_file_sp(new StreamFile(stderr, false)), 690 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()), 691 m_terminal_state(), 692 m_target_list(*this), 693 m_platform_list(), 694 m_listener_sp(Listener::MakeListener("lldb.Debugger")), 695 m_source_manager_ap(), 696 m_source_file_cache(), 697 m_command_interpreter_ap(new CommandInterpreter(*this, eScriptLanguageDefault, false)), 698 m_input_reader_stack(), 699 m_instance_name(), 700 m_loaded_plugins(), 701 m_event_handler_thread(), 702 m_io_handler_thread(), 703 m_sync_broadcaster(nullptr, "lldb.debugger.sync"), 704 m_forward_listener_sp(), 705 m_clear_once() 706 { 707 char instance_cstr[256]; 708 snprintf(instance_cstr, sizeof(instance_cstr), "debugger_%d", (int)GetID()); 709 m_instance_name.SetCString(instance_cstr); 710 if (log_callback) 711 m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton)); 712 m_command_interpreter_ap->Initialize (); 713 // Always add our default platform to the platform list 714 PlatformSP default_platform_sp (Platform::GetHostPlatform()); 715 assert(default_platform_sp); 716 m_platform_list.Append (default_platform_sp, true); 717 718 m_collection_sp->Initialize (g_properties); 719 m_collection_sp->AppendProperty (ConstString("target"), 720 ConstString("Settings specify to debugging targets."), 721 true, 722 Target::GetGlobalProperties()->GetValueProperties()); 723 m_collection_sp->AppendProperty (ConstString("platform"), 724 ConstString("Platform settings."), 725 true, 726 Platform::GetGlobalPlatformProperties()->GetValueProperties()); 727 if (m_command_interpreter_ap) 728 { 729 m_collection_sp->AppendProperty (ConstString("interpreter"), 730 ConstString("Settings specify to the debugger's command interpreter."), 731 true, 732 m_command_interpreter_ap->GetValueProperties()); 733 } 734 OptionValueSInt64 *term_width = m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(nullptr, ePropertyTerminalWidth); 735 term_width->SetMinimumValue(10); 736 term_width->SetMaximumValue(1024); 737 738 // Turn off use-color if this is a dumb terminal. 739 const char *term = getenv ("TERM"); 740 if (term && !strcmp (term, "dumb")) 741 SetUseColor (false); 742 } 743 744 Debugger::~Debugger () 745 { 746 Clear(); 747 } 748 749 void 750 Debugger::Clear() 751 { 752 //---------------------------------------------------------------------- 753 // Make sure we call this function only once. With the C++ global 754 // destructor chain having a list of debuggers and with code that can be 755 // running on other threads, we need to ensure this doesn't happen 756 // multiple times. 757 // 758 // The following functions call Debugger::Clear(): 759 // Debugger::~Debugger(); 760 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp); 761 // static void Debugger::Terminate(); 762 //---------------------------------------------------------------------- 763 std::call_once(m_clear_once, [this]() { 764 ClearIOHandlers(); 765 StopIOHandlerThread(); 766 StopEventHandlerThread(); 767 m_listener_sp->Clear(); 768 int num_targets = m_target_list.GetNumTargets(); 769 for (int i = 0; i < num_targets; i++) 770 { 771 TargetSP target_sp (m_target_list.GetTargetAtIndex (i)); 772 if (target_sp) 773 { 774 ProcessSP process_sp (target_sp->GetProcessSP()); 775 if (process_sp) 776 process_sp->Finalize(); 777 target_sp->Destroy(); 778 } 779 } 780 m_broadcaster_manager_sp->Clear (); 781 782 // Close the input file _before_ we close the input read communications class 783 // as it does NOT own the input file, our m_input_file does. 784 m_terminal_state.Clear(); 785 if (m_input_file_sp) 786 m_input_file_sp->GetFile().Close (); 787 788 m_command_interpreter_ap->Clear(); 789 }); 790 } 791 792 bool 793 Debugger::GetCloseInputOnEOF () const 794 { 795 // return m_input_comm.GetCloseOnEOF(); 796 return false; 797 } 798 799 void 800 Debugger::SetCloseInputOnEOF (bool b) 801 { 802 // m_input_comm.SetCloseOnEOF(b); 803 } 804 805 bool 806 Debugger::GetAsyncExecution () 807 { 808 return !m_command_interpreter_ap->GetSynchronous(); 809 } 810 811 void 812 Debugger::SetAsyncExecution (bool async_execution) 813 { 814 m_command_interpreter_ap->SetSynchronous (!async_execution); 815 } 816 817 void 818 Debugger::SetInputFileHandle (FILE *fh, bool tranfer_ownership) 819 { 820 if (m_input_file_sp) 821 m_input_file_sp->GetFile().SetStream (fh, tranfer_ownership); 822 else 823 m_input_file_sp.reset (new StreamFile (fh, tranfer_ownership)); 824 825 File &in_file = m_input_file_sp->GetFile(); 826 if (!in_file.IsValid()) 827 in_file.SetStream (stdin, true); 828 829 // Save away the terminal state if that is relevant, so that we can restore it in RestoreInputState. 830 SaveInputTerminalState (); 831 } 832 833 void 834 Debugger::SetOutputFileHandle (FILE *fh, bool tranfer_ownership) 835 { 836 if (m_output_file_sp) 837 m_output_file_sp->GetFile().SetStream (fh, tranfer_ownership); 838 else 839 m_output_file_sp.reset (new StreamFile (fh, tranfer_ownership)); 840 841 File &out_file = m_output_file_sp->GetFile(); 842 if (!out_file.IsValid()) 843 out_file.SetStream (stdout, false); 844 845 // do not create the ScriptInterpreter just for setting the output file handle 846 // as the constructor will know how to do the right thing on its own 847 const bool can_create = false; 848 ScriptInterpreter* script_interpreter = GetCommandInterpreter().GetScriptInterpreter(can_create); 849 if (script_interpreter) 850 script_interpreter->ResetOutputFileHandle (fh); 851 } 852 853 void 854 Debugger::SetErrorFileHandle (FILE *fh, bool tranfer_ownership) 855 { 856 if (m_error_file_sp) 857 m_error_file_sp->GetFile().SetStream (fh, tranfer_ownership); 858 else 859 m_error_file_sp.reset (new StreamFile (fh, tranfer_ownership)); 860 861 File &err_file = m_error_file_sp->GetFile(); 862 if (!err_file.IsValid()) 863 err_file.SetStream (stderr, false); 864 } 865 866 void 867 Debugger::SaveInputTerminalState () 868 { 869 if (m_input_file_sp) 870 { 871 File &in_file = m_input_file_sp->GetFile(); 872 if (in_file.GetDescriptor() != File::kInvalidDescriptor) 873 m_terminal_state.Save(in_file.GetDescriptor(), true); 874 } 875 } 876 877 void 878 Debugger::RestoreInputTerminalState () 879 { 880 m_terminal_state.Restore(); 881 } 882 883 ExecutionContext 884 Debugger::GetSelectedExecutionContext () 885 { 886 ExecutionContext exe_ctx; 887 TargetSP target_sp(GetSelectedTarget()); 888 exe_ctx.SetTargetSP (target_sp); 889 890 if (target_sp) 891 { 892 ProcessSP process_sp (target_sp->GetProcessSP()); 893 exe_ctx.SetProcessSP (process_sp); 894 if (process_sp && !process_sp->IsRunning()) 895 { 896 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread()); 897 if (thread_sp) 898 { 899 exe_ctx.SetThreadSP (thread_sp); 900 exe_ctx.SetFrameSP (thread_sp->GetSelectedFrame()); 901 if (exe_ctx.GetFramePtr() == nullptr) 902 exe_ctx.SetFrameSP (thread_sp->GetStackFrameAtIndex (0)); 903 } 904 } 905 } 906 return exe_ctx; 907 } 908 909 void 910 Debugger::DispatchInputInterrupt() 911 { 912 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex()); 913 IOHandlerSP reader_sp(m_input_reader_stack.Top()); 914 if (reader_sp) 915 reader_sp->Interrupt(); 916 } 917 918 void 919 Debugger::DispatchInputEndOfFile() 920 { 921 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex()); 922 IOHandlerSP reader_sp(m_input_reader_stack.Top()); 923 if (reader_sp) 924 reader_sp->GotEOF(); 925 } 926 927 void 928 Debugger::ClearIOHandlers() 929 { 930 // The bottom input reader should be the main debugger input reader. We do not want to close that one here. 931 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex()); 932 while (m_input_reader_stack.GetSize() > 1) 933 { 934 IOHandlerSP reader_sp(m_input_reader_stack.Top()); 935 if (reader_sp) 936 PopIOHandler(reader_sp); 937 } 938 } 939 940 void 941 Debugger::ExecuteIOHandlers() 942 { 943 while (true) 944 { 945 IOHandlerSP reader_sp(m_input_reader_stack.Top()); 946 if (!reader_sp) 947 break; 948 949 reader_sp->Run(); 950 951 // Remove all input readers that are done from the top of the stack 952 while (true) 953 { 954 IOHandlerSP top_reader_sp = m_input_reader_stack.Top(); 955 if (top_reader_sp && top_reader_sp->GetIsDone()) 956 PopIOHandler (top_reader_sp); 957 else 958 break; 959 } 960 } 961 ClearIOHandlers(); 962 } 963 964 bool 965 Debugger::IsTopIOHandler (const lldb::IOHandlerSP& reader_sp) 966 { 967 return m_input_reader_stack.IsTop (reader_sp); 968 } 969 970 bool 971 Debugger::CheckTopIOHandlerTypes (IOHandler::Type top_type, IOHandler::Type second_top_type) 972 { 973 return m_input_reader_stack.CheckTopIOHandlerTypes (top_type, second_top_type); 974 } 975 976 void 977 Debugger::PrintAsync (const char *s, size_t len, bool is_stdout) 978 { 979 lldb::StreamFileSP stream = is_stdout ? GetOutputFile() : GetErrorFile(); 980 m_input_reader_stack.PrintAsync(stream.get(), s, len); 981 } 982 983 ConstString 984 Debugger::GetTopIOHandlerControlSequence(char ch) 985 { 986 return m_input_reader_stack.GetTopIOHandlerControlSequence (ch); 987 } 988 989 const char * 990 Debugger::GetIOHandlerCommandPrefix() 991 { 992 return m_input_reader_stack.GetTopIOHandlerCommandPrefix(); 993 } 994 995 const char * 996 Debugger::GetIOHandlerHelpPrologue() 997 { 998 return m_input_reader_stack.GetTopIOHandlerHelpPrologue(); 999 } 1000 1001 void 1002 Debugger::RunIOHandler (const IOHandlerSP& reader_sp) 1003 { 1004 PushIOHandler (reader_sp); 1005 1006 IOHandlerSP top_reader_sp = reader_sp; 1007 while (top_reader_sp) 1008 { 1009 top_reader_sp->Run(); 1010 1011 if (top_reader_sp.get() == reader_sp.get()) 1012 { 1013 if (PopIOHandler (reader_sp)) 1014 break; 1015 } 1016 1017 while (true) 1018 { 1019 top_reader_sp = m_input_reader_stack.Top(); 1020 if (top_reader_sp && top_reader_sp->GetIsDone()) 1021 PopIOHandler (top_reader_sp); 1022 else 1023 break; 1024 } 1025 } 1026 } 1027 1028 void 1029 Debugger::AdoptTopIOHandlerFilesIfInvalid(StreamFileSP &in, StreamFileSP &out, StreamFileSP &err) 1030 { 1031 // Before an IOHandler runs, it must have in/out/err streams. 1032 // This function is called when one ore more of the streams 1033 // are nullptr. We use the top input reader's in/out/err streams, 1034 // or fall back to the debugger file handles, or we fall back 1035 // onto stdin/stdout/stderr as a last resort. 1036 1037 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex()); 1038 IOHandlerSP top_reader_sp(m_input_reader_stack.Top()); 1039 // If no STDIN has been set, then set it appropriately 1040 if (!in) 1041 { 1042 if (top_reader_sp) 1043 in = top_reader_sp->GetInputStreamFile(); 1044 else 1045 in = GetInputFile(); 1046 1047 // If there is nothing, use stdin 1048 if (!in) 1049 in = StreamFileSP(new StreamFile(stdin, false)); 1050 } 1051 // If no STDOUT has been set, then set it appropriately 1052 if (!out) 1053 { 1054 if (top_reader_sp) 1055 out = top_reader_sp->GetOutputStreamFile(); 1056 else 1057 out = GetOutputFile(); 1058 1059 // If there is nothing, use stdout 1060 if (!out) 1061 out = StreamFileSP(new StreamFile(stdout, false)); 1062 } 1063 // If no STDERR has been set, then set it appropriately 1064 if (!err) 1065 { 1066 if (top_reader_sp) 1067 err = top_reader_sp->GetErrorStreamFile(); 1068 else 1069 err = GetErrorFile(); 1070 1071 // If there is nothing, use stderr 1072 if (!err) 1073 err = StreamFileSP(new StreamFile(stdout, false)); 1074 } 1075 } 1076 1077 void 1078 Debugger::PushIOHandler(const IOHandlerSP &reader_sp) 1079 { 1080 if (!reader_sp) 1081 return; 1082 1083 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex()); 1084 1085 // Get the current top input reader... 1086 IOHandlerSP top_reader_sp(m_input_reader_stack.Top()); 1087 1088 // Don't push the same IO handler twice... 1089 if (reader_sp == top_reader_sp) 1090 return; 1091 1092 // Push our new input reader 1093 m_input_reader_stack.Push(reader_sp); 1094 reader_sp->Activate(); 1095 1096 // Interrupt the top input reader to it will exit its Run() function 1097 // and let this new input reader take over 1098 if (top_reader_sp) 1099 { 1100 top_reader_sp->Deactivate(); 1101 top_reader_sp->Cancel(); 1102 } 1103 } 1104 1105 bool 1106 Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) 1107 { 1108 if (!pop_reader_sp) 1109 return false; 1110 1111 std::lock_guard<std::recursive_mutex> guard(m_input_reader_stack.GetMutex()); 1112 1113 // The reader on the stop of the stack is done, so let the next 1114 // read on the stack refresh its prompt and if there is one... 1115 if (m_input_reader_stack.IsEmpty()) 1116 return false; 1117 1118 IOHandlerSP reader_sp(m_input_reader_stack.Top()); 1119 1120 if (pop_reader_sp != reader_sp) 1121 return false; 1122 1123 reader_sp->Deactivate(); 1124 reader_sp->Cancel(); 1125 m_input_reader_stack.Pop(); 1126 1127 reader_sp = m_input_reader_stack.Top(); 1128 if (reader_sp) 1129 reader_sp->Activate(); 1130 1131 return true; 1132 } 1133 1134 StreamSP 1135 Debugger::GetAsyncOutputStream () 1136 { 1137 return StreamSP (new StreamAsynchronousIO (*this, true)); 1138 } 1139 1140 StreamSP 1141 Debugger::GetAsyncErrorStream () 1142 { 1143 return StreamSP (new StreamAsynchronousIO (*this, false)); 1144 } 1145 1146 size_t 1147 Debugger::GetNumDebuggers() 1148 { 1149 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) 1150 { 1151 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1152 return g_debugger_list_ptr->size(); 1153 } 1154 return 0; 1155 } 1156 1157 lldb::DebuggerSP 1158 Debugger::GetDebuggerAtIndex (size_t index) 1159 { 1160 DebuggerSP debugger_sp; 1161 1162 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) 1163 { 1164 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1165 if (index < g_debugger_list_ptr->size()) 1166 debugger_sp = g_debugger_list_ptr->at(index); 1167 } 1168 1169 return debugger_sp; 1170 } 1171 1172 DebuggerSP 1173 Debugger::FindDebuggerWithID (lldb::user_id_t id) 1174 { 1175 DebuggerSP debugger_sp; 1176 1177 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) 1178 { 1179 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1180 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 1181 for (pos = g_debugger_list_ptr->begin (); pos != end; ++pos) 1182 { 1183 if ((*pos)->GetID() == id) 1184 { 1185 debugger_sp = *pos; 1186 break; 1187 } 1188 } 1189 } 1190 return debugger_sp; 1191 } 1192 1193 #if 0 1194 static void 1195 TestPromptFormats (StackFrame *frame) 1196 { 1197 if (frame == nullptr) 1198 return; 1199 1200 StreamString s; 1201 const char *prompt_format = 1202 "{addr = '${addr}'\n}" 1203 "{addr-file-or-load = '${addr-file-or-load}'\n}" 1204 "{current-pc-arrow = '${current-pc-arrow}'\n}" 1205 "{process.id = '${process.id}'\n}" 1206 "{process.name = '${process.name}'\n}" 1207 "{process.file.basename = '${process.file.basename}'\n}" 1208 "{process.file.fullpath = '${process.file.fullpath}'\n}" 1209 "{thread.id = '${thread.id}'\n}" 1210 "{thread.index = '${thread.index}'\n}" 1211 "{thread.name = '${thread.name}'\n}" 1212 "{thread.queue = '${thread.queue}'\n}" 1213 "{thread.stop-reason = '${thread.stop-reason}'\n}" 1214 "{target.arch = '${target.arch}'\n}" 1215 "{module.file.basename = '${module.file.basename}'\n}" 1216 "{module.file.fullpath = '${module.file.fullpath}'\n}" 1217 "{file.basename = '${file.basename}'\n}" 1218 "{file.fullpath = '${file.fullpath}'\n}" 1219 "{frame.index = '${frame.index}'\n}" 1220 "{frame.pc = '${frame.pc}'\n}" 1221 "{frame.sp = '${frame.sp}'\n}" 1222 "{frame.fp = '${frame.fp}'\n}" 1223 "{frame.flags = '${frame.flags}'\n}" 1224 "{frame.reg.rdi = '${frame.reg.rdi}'\n}" 1225 "{frame.reg.rip = '${frame.reg.rip}'\n}" 1226 "{frame.reg.rsp = '${frame.reg.rsp}'\n}" 1227 "{frame.reg.rbp = '${frame.reg.rbp}'\n}" 1228 "{frame.reg.rflags = '${frame.reg.rflags}'\n}" 1229 "{frame.reg.xmm0 = '${frame.reg.xmm0}'\n}" 1230 "{frame.reg.carp = '${frame.reg.carp}'\n}" 1231 "{function.id = '${function.id}'\n}" 1232 "{function.changed = '${function.changed}'\n}" 1233 "{function.initial-function = '${function.initial-function}'\n}" 1234 "{function.name = '${function.name}'\n}" 1235 "{function.name-without-args = '${function.name-without-args}'\n}" 1236 "{function.name-with-args = '${function.name-with-args}'\n}" 1237 "{function.addr-offset = '${function.addr-offset}'\n}" 1238 "{function.concrete-only-addr-offset-no-padding = '${function.concrete-only-addr-offset-no-padding}'\n}" 1239 "{function.line-offset = '${function.line-offset}'\n}" 1240 "{function.pc-offset = '${function.pc-offset}'\n}" 1241 "{line.file.basename = '${line.file.basename}'\n}" 1242 "{line.file.fullpath = '${line.file.fullpath}'\n}" 1243 "{line.number = '${line.number}'\n}" 1244 "{line.start-addr = '${line.start-addr}'\n}" 1245 "{line.end-addr = '${line.end-addr}'\n}" 1246 ; 1247 1248 SymbolContext sc (frame->GetSymbolContext(eSymbolContextEverything)); 1249 ExecutionContext exe_ctx; 1250 frame->CalculateExecutionContext(exe_ctx); 1251 if (Debugger::FormatPrompt (prompt_format, &sc, &exe_ctx, &sc.line_entry.range.GetBaseAddress(), s)) 1252 { 1253 printf("%s\n", s.GetData()); 1254 } 1255 else 1256 { 1257 printf ("what we got: %s\n", s.GetData()); 1258 } 1259 } 1260 #endif 1261 1262 bool 1263 Debugger::FormatDisassemblerAddress (const FormatEntity::Entry *format, 1264 const SymbolContext *sc, 1265 const SymbolContext *prev_sc, 1266 const ExecutionContext *exe_ctx, 1267 const Address *addr, 1268 Stream &s) 1269 { 1270 FormatEntity::Entry format_entry; 1271 1272 if (format == nullptr) 1273 { 1274 if (exe_ctx != nullptr && exe_ctx->HasTargetScope()) 1275 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat(); 1276 if (format == nullptr) 1277 { 1278 FormatEntity::Parse("${addr}: ", format_entry); 1279 format = &format_entry; 1280 } 1281 } 1282 bool function_changed = false; 1283 bool initial_function = false; 1284 if (prev_sc && (prev_sc->function || prev_sc->symbol)) 1285 { 1286 if (sc && (sc->function || sc->symbol)) 1287 { 1288 if (prev_sc->symbol && sc->symbol) 1289 { 1290 if (!sc->symbol->Compare (prev_sc->symbol->GetName(), prev_sc->symbol->GetType())) 1291 { 1292 function_changed = true; 1293 } 1294 } 1295 else if (prev_sc->function && sc->function) 1296 { 1297 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) 1298 { 1299 function_changed = true; 1300 } 1301 } 1302 } 1303 } 1304 // The first context on a list of instructions will have a prev_sc that 1305 // has no Function or Symbol -- if SymbolContext had an IsValid() method, it 1306 // would return false. But we do get a prev_sc pointer. 1307 if ((sc && (sc->function || sc->symbol)) 1308 && prev_sc && (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) 1309 { 1310 initial_function = true; 1311 } 1312 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr, function_changed, initial_function); 1313 } 1314 1315 void 1316 Debugger::SetLoggingCallback (lldb::LogOutputCallback log_callback, void *baton) 1317 { 1318 // For simplicity's sake, I am not going to deal with how to close down any 1319 // open logging streams, I just redirect everything from here on out to the 1320 // callback. 1321 m_log_callback_stream_sp.reset (new StreamCallback (log_callback, baton)); 1322 } 1323 1324 bool 1325 Debugger::EnableLog (const char *channel, const char **categories, const char *log_file, uint32_t log_options, Stream &error_stream) 1326 { 1327 StreamSP log_stream_sp; 1328 if (m_log_callback_stream_sp) 1329 { 1330 log_stream_sp = m_log_callback_stream_sp; 1331 // For now when using the callback mode you always get thread & timestamp. 1332 log_options |= LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME; 1333 } 1334 else if (log_file == nullptr || *log_file == '\0') 1335 { 1336 log_stream_sp = GetOutputFile(); 1337 } 1338 else 1339 { 1340 LogStreamMap::iterator pos = m_log_streams.find(log_file); 1341 if (pos != m_log_streams.end()) 1342 log_stream_sp = pos->second.lock(); 1343 if (!log_stream_sp) 1344 { 1345 uint32_t options = File::eOpenOptionWrite | File::eOpenOptionCanCreate 1346 | File::eOpenOptionCloseOnExec | File::eOpenOptionAppend; 1347 if (! (log_options & LLDB_LOG_OPTION_APPEND)) 1348 options |= File::eOpenOptionTruncate; 1349 1350 log_stream_sp.reset (new StreamFile (log_file, options)); 1351 m_log_streams[log_file] = log_stream_sp; 1352 } 1353 } 1354 assert(log_stream_sp); 1355 1356 if (log_options == 0) 1357 log_options = LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE; 1358 1359 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories, error_stream); 1360 } 1361 1362 SourceManager & 1363 Debugger::GetSourceManager () 1364 { 1365 if (!m_source_manager_ap) 1366 m_source_manager_ap.reset (new SourceManager (shared_from_this())); 1367 return *m_source_manager_ap; 1368 } 1369 1370 // This function handles events that were broadcast by the process. 1371 void 1372 Debugger::HandleBreakpointEvent (const EventSP &event_sp) 1373 { 1374 using namespace lldb; 1375 const uint32_t event_type = Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent (event_sp); 1376 1377 // if (event_type & eBreakpointEventTypeAdded 1378 // || event_type & eBreakpointEventTypeRemoved 1379 // || event_type & eBreakpointEventTypeEnabled 1380 // || event_type & eBreakpointEventTypeDisabled 1381 // || event_type & eBreakpointEventTypeCommandChanged 1382 // || event_type & eBreakpointEventTypeConditionChanged 1383 // || event_type & eBreakpointEventTypeIgnoreChanged 1384 // || event_type & eBreakpointEventTypeLocationsResolved) 1385 // { 1386 // // Don't do anything about these events, since the breakpoint commands already echo these actions. 1387 // } 1388 // 1389 if (event_type & eBreakpointEventTypeLocationsAdded) 1390 { 1391 uint32_t num_new_locations = Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(event_sp); 1392 if (num_new_locations > 0) 1393 { 1394 BreakpointSP breakpoint = Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp); 1395 StreamSP output_sp (GetAsyncOutputStream()); 1396 if (output_sp) 1397 { 1398 output_sp->Printf("%d location%s added to breakpoint %d\n", 1399 num_new_locations, 1400 num_new_locations == 1 ? "" : "s", 1401 breakpoint->GetID()); 1402 output_sp->Flush(); 1403 } 1404 } 1405 } 1406 // else if (event_type & eBreakpointEventTypeLocationsRemoved) 1407 // { 1408 // // These locations just get disabled, not sure it is worth spamming folks about this on the command line. 1409 // } 1410 // else if (event_type & eBreakpointEventTypeLocationsResolved) 1411 // { 1412 // // This might be an interesting thing to note, but I'm going to leave it quiet for now, it just looked noisy. 1413 // } 1414 } 1415 1416 size_t 1417 Debugger::GetProcessSTDOUT (Process *process, Stream *stream) 1418 { 1419 size_t total_bytes = 0; 1420 if (stream == nullptr) 1421 stream = GetOutputFile().get(); 1422 1423 if (stream) 1424 { 1425 // The process has stuff waiting for stdout; get it and write it out to the appropriate place. 1426 if (process == nullptr) 1427 { 1428 TargetSP target_sp = GetTargetList().GetSelectedTarget(); 1429 if (target_sp) 1430 process = target_sp->GetProcessSP().get(); 1431 } 1432 if (process) 1433 { 1434 Error error; 1435 size_t len; 1436 char stdio_buffer[1024]; 1437 while ((len = process->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0) 1438 { 1439 stream->Write(stdio_buffer, len); 1440 total_bytes += len; 1441 } 1442 } 1443 stream->Flush(); 1444 } 1445 return total_bytes; 1446 } 1447 1448 size_t 1449 Debugger::GetProcessSTDERR (Process *process, Stream *stream) 1450 { 1451 size_t total_bytes = 0; 1452 if (stream == nullptr) 1453 stream = GetOutputFile().get(); 1454 1455 if (stream) 1456 { 1457 // The process has stuff waiting for stderr; get it and write it out to the appropriate place. 1458 if (process == nullptr) 1459 { 1460 TargetSP target_sp = GetTargetList().GetSelectedTarget(); 1461 if (target_sp) 1462 process = target_sp->GetProcessSP().get(); 1463 } 1464 if (process) 1465 { 1466 Error error; 1467 size_t len; 1468 char stdio_buffer[1024]; 1469 while ((len = process->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0) 1470 { 1471 stream->Write(stdio_buffer, len); 1472 total_bytes += len; 1473 } 1474 } 1475 stream->Flush(); 1476 } 1477 return total_bytes; 1478 } 1479 1480 // This function handles events that were broadcast by the process. 1481 void 1482 Debugger::HandleProcessEvent (const EventSP &event_sp) 1483 { 1484 using namespace lldb; 1485 const uint32_t event_type = event_sp->GetType(); 1486 ProcessSP process_sp = (event_type == Process::eBroadcastBitStructuredData) 1487 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get()) 1488 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get()); 1489 1490 StreamSP output_stream_sp = GetAsyncOutputStream(); 1491 StreamSP error_stream_sp = GetAsyncErrorStream(); 1492 const bool gui_enabled = IsForwardingEvents(); 1493 1494 if (!gui_enabled) 1495 { 1496 bool pop_process_io_handler = false; 1497 assert (process_sp); 1498 1499 bool state_is_stopped = false; 1500 const bool got_state_changed = (event_type & Process::eBroadcastBitStateChanged) != 0; 1501 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0; 1502 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0; 1503 const bool got_structured_data = (event_type & 1504 Process::eBroadcastBitStructuredData) != 0; 1505 1506 if (got_state_changed) 1507 { 1508 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get()); 1509 state_is_stopped = StateIsStoppedState(event_state, false); 1510 } 1511 1512 // Display running state changes first before any STDIO 1513 if (got_state_changed && !state_is_stopped) 1514 { 1515 Process::HandleProcessStateChangedEvent (event_sp, output_stream_sp.get(), pop_process_io_handler); 1516 } 1517 1518 // Now display and STDOUT 1519 if (got_stdout || got_state_changed) 1520 { 1521 GetProcessSTDOUT (process_sp.get(), output_stream_sp.get()); 1522 } 1523 1524 // Now display and STDERR 1525 if (got_stderr || got_state_changed) 1526 { 1527 GetProcessSTDERR (process_sp.get(), error_stream_sp.get()); 1528 } 1529 1530 // Give structured data events an opportunity to display. 1531 if (got_structured_data) 1532 { 1533 StructuredDataPluginSP plugin_sp = 1534 EventDataStructuredData::GetPluginFromEvent(event_sp.get()); 1535 if (plugin_sp) 1536 { 1537 auto structured_data_sp = 1538 EventDataStructuredData::GetObjectFromEvent(event_sp.get()); 1539 if (output_stream_sp) 1540 { 1541 StreamString content_stream; 1542 Error error = plugin_sp->GetDescription(structured_data_sp, 1543 content_stream); 1544 if (error.Success()) 1545 { 1546 if (!content_stream.GetString().empty()) 1547 { 1548 // Add newline. 1549 content_stream.PutChar('\n'); 1550 content_stream.Flush(); 1551 1552 // Print it. 1553 output_stream_sp->PutCString(content_stream 1554 .GetString().c_str()); 1555 } 1556 } 1557 else 1558 { 1559 error_stream_sp->Printf("Failed to print structured " 1560 "data with plugin %s: %s", 1561 plugin_sp->GetPluginName() 1562 .AsCString(), 1563 error.AsCString()); 1564 } 1565 } 1566 } 1567 } 1568 1569 // Now display any stopped state changes after any STDIO 1570 if (got_state_changed && state_is_stopped) 1571 { 1572 Process::HandleProcessStateChangedEvent (event_sp, output_stream_sp.get(), pop_process_io_handler); 1573 } 1574 1575 output_stream_sp->Flush(); 1576 error_stream_sp->Flush(); 1577 1578 if (pop_process_io_handler) 1579 process_sp->PopProcessIOHandler(); 1580 } 1581 } 1582 1583 void 1584 Debugger::HandleThreadEvent (const EventSP &event_sp) 1585 { 1586 // At present the only thread event we handle is the Frame Changed event, 1587 // and all we do for that is just reprint the thread status for that thread. 1588 using namespace lldb; 1589 const uint32_t event_type = event_sp->GetType(); 1590 if (event_type == Thread::eBroadcastBitStackChanged || 1591 event_type == Thread::eBroadcastBitThreadSelected ) 1592 { 1593 ThreadSP thread_sp (Thread::ThreadEventData::GetThreadFromEvent (event_sp.get())); 1594 if (thread_sp) 1595 { 1596 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1); 1597 } 1598 } 1599 } 1600 1601 bool 1602 Debugger::IsForwardingEvents () 1603 { 1604 return (bool)m_forward_listener_sp; 1605 } 1606 1607 void 1608 Debugger::EnableForwardEvents (const ListenerSP &listener_sp) 1609 { 1610 m_forward_listener_sp = listener_sp; 1611 } 1612 1613 void 1614 Debugger::CancelForwardEvents (const ListenerSP &listener_sp) 1615 { 1616 m_forward_listener_sp.reset(); 1617 } 1618 1619 1620 void 1621 Debugger::DefaultEventHandler() 1622 { 1623 ListenerSP listener_sp(GetListener()); 1624 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass()); 1625 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass()); 1626 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass()); 1627 BroadcastEventSpec target_event_spec (broadcaster_class_target, 1628 Target::eBroadcastBitBreakpointChanged); 1629 1630 BroadcastEventSpec process_event_spec (broadcaster_class_process, 1631 Process::eBroadcastBitStateChanged | 1632 Process::eBroadcastBitSTDOUT | 1633 Process::eBroadcastBitSTDERR | 1634 Process::eBroadcastBitStructuredData); 1635 1636 BroadcastEventSpec thread_event_spec (broadcaster_class_thread, 1637 Thread::eBroadcastBitStackChanged | 1638 Thread::eBroadcastBitThreadSelected ); 1639 1640 listener_sp->StartListeningForEventSpec (m_broadcaster_manager_sp, target_event_spec); 1641 listener_sp->StartListeningForEventSpec (m_broadcaster_manager_sp, process_event_spec); 1642 listener_sp->StartListeningForEventSpec (m_broadcaster_manager_sp, thread_event_spec); 1643 listener_sp->StartListeningForEvents (m_command_interpreter_ap.get(), 1644 CommandInterpreter::eBroadcastBitQuitCommandReceived | 1645 CommandInterpreter::eBroadcastBitAsynchronousOutputData | 1646 CommandInterpreter::eBroadcastBitAsynchronousErrorData ); 1647 1648 // Let the thread that spawned us know that we have started up and 1649 // that we are now listening to all required events so no events get missed 1650 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening); 1651 1652 bool done = false; 1653 while (!done) 1654 { 1655 EventSP event_sp; 1656 if (listener_sp->WaitForEvent(std::chrono::microseconds(0), event_sp)) 1657 { 1658 if (event_sp) 1659 { 1660 Broadcaster *broadcaster = event_sp->GetBroadcaster(); 1661 if (broadcaster) 1662 { 1663 uint32_t event_type = event_sp->GetType(); 1664 ConstString broadcaster_class (broadcaster->GetBroadcasterClass()); 1665 if (broadcaster_class == broadcaster_class_process) 1666 { 1667 HandleProcessEvent (event_sp); 1668 } 1669 else if (broadcaster_class == broadcaster_class_target) 1670 { 1671 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(event_sp.get())) 1672 { 1673 HandleBreakpointEvent (event_sp); 1674 } 1675 } 1676 else if (broadcaster_class == broadcaster_class_thread) 1677 { 1678 HandleThreadEvent (event_sp); 1679 } 1680 else if (broadcaster == m_command_interpreter_ap.get()) 1681 { 1682 if (event_type & CommandInterpreter::eBroadcastBitQuitCommandReceived) 1683 { 1684 done = true; 1685 } 1686 else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousErrorData) 1687 { 1688 const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get())); 1689 if (data && data[0]) 1690 { 1691 StreamSP error_sp (GetAsyncErrorStream()); 1692 if (error_sp) 1693 { 1694 error_sp->PutCString(data); 1695 error_sp->Flush(); 1696 } 1697 } 1698 } 1699 else if (event_type & CommandInterpreter::eBroadcastBitAsynchronousOutputData) 1700 { 1701 const char *data = reinterpret_cast<const char *>(EventDataBytes::GetBytesFromEvent (event_sp.get())); 1702 if (data && data[0]) 1703 { 1704 StreamSP output_sp (GetAsyncOutputStream()); 1705 if (output_sp) 1706 { 1707 output_sp->PutCString(data); 1708 output_sp->Flush(); 1709 } 1710 } 1711 } 1712 } 1713 } 1714 1715 if (m_forward_listener_sp) 1716 m_forward_listener_sp->AddEvent(event_sp); 1717 } 1718 } 1719 } 1720 } 1721 1722 lldb::thread_result_t 1723 Debugger::EventHandlerThread (lldb::thread_arg_t arg) 1724 { 1725 ((Debugger *)arg)->DefaultEventHandler(); 1726 return NULL; 1727 } 1728 1729 bool 1730 Debugger::StartEventHandlerThread() 1731 { 1732 if (!m_event_handler_thread.IsJoinable()) 1733 { 1734 // We must synchronize with the DefaultEventHandler() thread to ensure 1735 // it is up and running and listening to events before we return from 1736 // this function. We do this by listening to events for the 1737 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster 1738 ListenerSP listener_sp(Listener::MakeListener("lldb.debugger.event-handler")); 1739 listener_sp->StartListeningForEvents(&m_sync_broadcaster, eBroadcastBitEventThreadIsListening); 1740 1741 // Use larger 8MB stack for this thread 1742 m_event_handler_thread = ThreadLauncher::LaunchThread("lldb.debugger.event-handler", 1743 EventHandlerThread, 1744 this, 1745 nullptr, 1746 g_debugger_event_thread_stack_bytes); 1747 1748 // Make sure DefaultEventHandler() is running and listening to events before we return 1749 // from this function. We are only listening for events of type 1750 // eBroadcastBitEventThreadIsListening so we don't need to check the event, we just need 1751 // to wait an infinite amount of time for it (nullptr timeout as the first parameter) 1752 lldb::EventSP event_sp; 1753 listener_sp->WaitForEvent(std::chrono::microseconds(0), event_sp); 1754 } 1755 return m_event_handler_thread.IsJoinable(); 1756 } 1757 1758 void 1759 Debugger::StopEventHandlerThread() 1760 { 1761 if (m_event_handler_thread.IsJoinable()) 1762 { 1763 GetCommandInterpreter().BroadcastEvent(CommandInterpreter::eBroadcastBitQuitCommandReceived); 1764 m_event_handler_thread.Join(nullptr); 1765 } 1766 } 1767 1768 lldb::thread_result_t 1769 Debugger::IOHandlerThread (lldb::thread_arg_t arg) 1770 { 1771 Debugger *debugger = (Debugger *)arg; 1772 debugger->ExecuteIOHandlers(); 1773 debugger->StopEventHandlerThread(); 1774 return NULL; 1775 } 1776 1777 bool 1778 Debugger::HasIOHandlerThread() 1779 { 1780 return m_io_handler_thread.IsJoinable(); 1781 } 1782 1783 bool 1784 Debugger::StartIOHandlerThread() 1785 { 1786 if (!m_io_handler_thread.IsJoinable()) 1787 m_io_handler_thread = ThreadLauncher::LaunchThread("lldb.debugger.io-handler", 1788 IOHandlerThread, 1789 this, 1790 nullptr, 1791 8*1024*1024); // Use larger 8MB stack for this thread 1792 return m_io_handler_thread.IsJoinable(); 1793 } 1794 1795 void 1796 Debugger::StopIOHandlerThread() 1797 { 1798 if (m_io_handler_thread.IsJoinable()) 1799 { 1800 if (m_input_file_sp) 1801 m_input_file_sp->GetFile().Close(); 1802 m_io_handler_thread.Join(nullptr); 1803 } 1804 } 1805 1806 void 1807 Debugger::JoinIOHandlerThread() 1808 { 1809 if (HasIOHandlerThread()) 1810 { 1811 thread_result_t result; 1812 m_io_handler_thread.Join(&result); 1813 m_io_handler_thread = LLDB_INVALID_HOST_THREAD; 1814 } 1815 } 1816 1817 Target * 1818 Debugger::GetDummyTarget() 1819 { 1820 return m_target_list.GetDummyTarget (*this).get(); 1821 } 1822 1823 Target * 1824 Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) 1825 { 1826 Target *target = nullptr; 1827 if (!prefer_dummy) 1828 { 1829 target = m_target_list.GetSelectedTarget().get(); 1830 if (target) 1831 return target; 1832 } 1833 1834 return GetDummyTarget(); 1835 } 1836 1837 Error 1838 Debugger::RunREPL (LanguageType language, const char *repl_options) 1839 { 1840 Error err; 1841 FileSpec repl_executable; 1842 1843 if (language == eLanguageTypeUnknown) 1844 { 1845 std::set<LanguageType> repl_languages; 1846 1847 Language::GetLanguagesSupportingREPLs(repl_languages); 1848 1849 if (repl_languages.size() == 1) 1850 { 1851 language = *repl_languages.begin(); 1852 } 1853 else if (repl_languages.empty()) 1854 { 1855 err.SetErrorStringWithFormat("LLDB isn't configured with REPL support for any languages."); 1856 return err; 1857 } 1858 else 1859 { 1860 err.SetErrorStringWithFormat("Multiple possible REPL languages. Please specify a language."); 1861 return err; 1862 } 1863 } 1864 1865 Target *const target = nullptr; // passing in an empty target means the REPL must create one 1866 1867 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options)); 1868 1869 if (!err.Success()) 1870 { 1871 return err; 1872 } 1873 1874 if (!repl_sp) 1875 { 1876 err.SetErrorStringWithFormat("couldn't find a REPL for %s", Language::GetNameForLanguageType(language)); 1877 return err; 1878 } 1879 1880 repl_sp->SetCompilerOptions(repl_options); 1881 repl_sp->RunLoop(); 1882 1883 return err; 1884 } 1885