1 //===-- Debugger.cpp ------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "lldb/Core/Debugger.h" 10 11 #include "lldb/Breakpoint/Breakpoint.h" 12 #include "lldb/Core/DebuggerEvents.h" 13 #include "lldb/Core/FormatEntity.h" 14 #include "lldb/Core/Mangled.h" 15 #include "lldb/Core/ModuleList.h" 16 #include "lldb/Core/ModuleSpec.h" 17 #include "lldb/Core/PluginManager.h" 18 #include "lldb/Core/StreamAsynchronousIO.h" 19 #include "lldb/Core/StreamFile.h" 20 #include "lldb/DataFormatters/DataVisualization.h" 21 #include "lldb/Expression/REPL.h" 22 #include "lldb/Host/File.h" 23 #include "lldb/Host/FileSystem.h" 24 #include "lldb/Host/HostInfo.h" 25 #include "lldb/Host/Terminal.h" 26 #include "lldb/Host/ThreadLauncher.h" 27 #include "lldb/Interpreter/CommandInterpreter.h" 28 #include "lldb/Interpreter/CommandReturnObject.h" 29 #include "lldb/Interpreter/OptionValue.h" 30 #include "lldb/Interpreter/OptionValueLanguage.h" 31 #include "lldb/Interpreter/OptionValueProperties.h" 32 #include "lldb/Interpreter/OptionValueSInt64.h" 33 #include "lldb/Interpreter/OptionValueString.h" 34 #include "lldb/Interpreter/Property.h" 35 #include "lldb/Interpreter/ScriptInterpreter.h" 36 #include "lldb/Symbol/Function.h" 37 #include "lldb/Symbol/Symbol.h" 38 #include "lldb/Symbol/SymbolContext.h" 39 #include "lldb/Target/Language.h" 40 #include "lldb/Target/Process.h" 41 #include "lldb/Target/StructuredDataPlugin.h" 42 #include "lldb/Target/Target.h" 43 #include "lldb/Target/TargetList.h" 44 #include "lldb/Target/Thread.h" 45 #include "lldb/Target/ThreadList.h" 46 #include "lldb/Utility/AnsiTerminal.h" 47 #include "lldb/Utility/Event.h" 48 #include "lldb/Utility/LLDBLog.h" 49 #include "lldb/Utility/Listener.h" 50 #include "lldb/Utility/Log.h" 51 #include "lldb/Utility/State.h" 52 #include "lldb/Utility/Stream.h" 53 #include "lldb/Utility/StreamString.h" 54 #include "lldb/lldb-enumerations.h" 55 56 #if defined(_WIN32) 57 #include "lldb/Host/windows/PosixApi.h" 58 #include "lldb/Host/windows/windows.h" 59 #endif 60 61 #include "llvm/ADT/STLExtras.h" 62 #include "llvm/ADT/StringRef.h" 63 #include "llvm/ADT/iterator.h" 64 #include "llvm/Support/DynamicLibrary.h" 65 #include "llvm/Support/FileSystem.h" 66 #include "llvm/Support/Process.h" 67 #include "llvm/Support/ThreadPool.h" 68 #include "llvm/Support/Threading.h" 69 #include "llvm/Support/raw_ostream.h" 70 71 #include <cstdio> 72 #include <cstdlib> 73 #include <cstring> 74 #include <list> 75 #include <memory> 76 #include <mutex> 77 #include <optional> 78 #include <set> 79 #include <string> 80 #include <system_error> 81 82 // Includes for pipe() 83 #if defined(_WIN32) 84 #include <fcntl.h> 85 #include <io.h> 86 #else 87 #include <unistd.h> 88 #endif 89 90 namespace lldb_private { 91 class Address; 92 } 93 94 using namespace lldb; 95 using namespace lldb_private; 96 97 static lldb::user_id_t g_unique_id = 1; 98 static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024; 99 100 #pragma mark Static Functions 101 102 static std::recursive_mutex *g_debugger_list_mutex_ptr = 103 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain 104 static Debugger::DebuggerList *g_debugger_list_ptr = 105 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain 106 static llvm::ThreadPool *g_thread_pool = nullptr; 107 108 static constexpr OptionEnumValueElement g_show_disassembly_enum_values[] = { 109 { 110 Debugger::eStopDisassemblyTypeNever, 111 "never", 112 "Never show disassembly when displaying a stop context.", 113 }, 114 { 115 Debugger::eStopDisassemblyTypeNoDebugInfo, 116 "no-debuginfo", 117 "Show disassembly when there is no debug information.", 118 }, 119 { 120 Debugger::eStopDisassemblyTypeNoSource, 121 "no-source", 122 "Show disassembly when there is no source information, or the source " 123 "file " 124 "is missing when displaying a stop context.", 125 }, 126 { 127 Debugger::eStopDisassemblyTypeAlways, 128 "always", 129 "Always show disassembly when displaying a stop context.", 130 }, 131 }; 132 133 static constexpr OptionEnumValueElement g_language_enumerators[] = { 134 { 135 eScriptLanguageNone, 136 "none", 137 "Disable scripting languages.", 138 }, 139 { 140 eScriptLanguagePython, 141 "python", 142 "Select python as the default scripting language.", 143 }, 144 { 145 eScriptLanguageDefault, 146 "default", 147 "Select the lldb default as the default scripting language.", 148 }, 149 }; 150 151 static constexpr OptionEnumValueElement g_dwim_print_verbosities[] = { 152 {eDWIMPrintVerbosityNone, "none", 153 "Use no verbosity when running dwim-print."}, 154 {eDWIMPrintVerbosityExpression, "expression", 155 "Use partial verbosity when running dwim-print - display a message when " 156 "`expression` evaluation is used."}, 157 {eDWIMPrintVerbosityFull, "full", 158 "Use full verbosity when running dwim-print."}, 159 }; 160 161 static constexpr OptionEnumValueElement s_stop_show_column_values[] = { 162 { 163 eStopShowColumnAnsiOrCaret, 164 "ansi-or-caret", 165 "Highlight the stop column with ANSI terminal codes when color/ANSI " 166 "mode is enabled; otherwise, fall back to using a text-only caret (^) " 167 "as if \"caret-only\" mode was selected.", 168 }, 169 { 170 eStopShowColumnAnsi, 171 "ansi", 172 "Highlight the stop column with ANSI terminal codes when running LLDB " 173 "with color/ANSI enabled.", 174 }, 175 { 176 eStopShowColumnCaret, 177 "caret", 178 "Highlight the stop column with a caret character (^) underneath the " 179 "stop column. This method introduces a new line in source listings " 180 "that display thread stop locations.", 181 }, 182 { 183 eStopShowColumnNone, 184 "none", 185 "Do not highlight the stop column.", 186 }, 187 }; 188 189 #define LLDB_PROPERTIES_debugger 190 #include "CoreProperties.inc" 191 192 enum { 193 #define LLDB_PROPERTIES_debugger 194 #include "CorePropertiesEnum.inc" 195 }; 196 197 LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr; 198 199 Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx, 200 VarSetOperationType op, 201 llvm::StringRef property_path, 202 llvm::StringRef value) { 203 bool is_load_script = 204 (property_path == "target.load-script-from-symbol-file"); 205 // These properties might change how we visualize data. 206 bool invalidate_data_vis = (property_path == "escape-non-printables"); 207 invalidate_data_vis |= 208 (property_path == "target.max-zero-padding-in-float-format"); 209 if (invalidate_data_vis) { 210 DataVisualization::ForceUpdate(); 211 } 212 213 TargetSP target_sp; 214 LoadScriptFromSymFile load_script_old_value = eLoadScriptFromSymFileFalse; 215 if (is_load_script && exe_ctx && exe_ctx->GetTargetSP()) { 216 target_sp = exe_ctx->GetTargetSP(); 217 load_script_old_value = 218 target_sp->TargetProperties::GetLoadScriptFromSymbolFile(); 219 } 220 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value)); 221 if (error.Success()) { 222 // FIXME it would be nice to have "on-change" callbacks for properties 223 if (property_path == g_debugger_properties[ePropertyPrompt].name) { 224 llvm::StringRef new_prompt = GetPrompt(); 225 std::string str = lldb_private::ansi::FormatAnsiTerminalCodes( 226 new_prompt, GetUseColor()); 227 if (str.length()) 228 new_prompt = str; 229 GetCommandInterpreter().UpdatePrompt(new_prompt); 230 auto bytes = std::make_unique<EventDataBytes>(new_prompt); 231 auto prompt_change_event_sp = std::make_shared<Event>( 232 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release()); 233 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp); 234 } else if (property_path == g_debugger_properties[ePropertyUseColor].name) { 235 // use-color changed. Ping the prompt so it can reset the ansi terminal 236 // codes. 237 SetPrompt(GetPrompt()); 238 } else if (property_path == 239 g_debugger_properties[ePropertyUseSourceCache].name) { 240 // use-source-cache changed. Wipe out the cache contents if it was 241 // disabled. 242 if (!GetUseSourceCache()) { 243 m_source_file_cache.Clear(); 244 } 245 } else if (is_load_script && target_sp && 246 load_script_old_value == eLoadScriptFromSymFileWarn) { 247 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() == 248 eLoadScriptFromSymFileTrue) { 249 std::list<Status> errors; 250 StreamString feedback_stream; 251 if (!target_sp->LoadScriptingResources(errors, feedback_stream)) { 252 Stream &s = GetErrorStream(); 253 for (auto error : errors) { 254 s.Printf("%s\n", error.AsCString()); 255 } 256 if (feedback_stream.GetSize()) 257 s.PutCString(feedback_stream.GetString()); 258 } 259 } 260 } 261 } 262 return error; 263 } 264 265 bool Debugger::GetAutoConfirm() const { 266 constexpr uint32_t idx = ePropertyAutoConfirm; 267 return GetPropertyAtIndexAs<bool>( 268 idx, g_debugger_properties[idx].default_uint_value != 0); 269 } 270 271 const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const { 272 constexpr uint32_t idx = ePropertyDisassemblyFormat; 273 return GetPropertyAtIndexAs<const FormatEntity::Entry *>(idx); 274 } 275 276 const FormatEntity::Entry *Debugger::GetFrameFormat() const { 277 constexpr uint32_t idx = ePropertyFrameFormat; 278 return GetPropertyAtIndexAs<const FormatEntity::Entry *>(idx); 279 } 280 281 const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const { 282 constexpr uint32_t idx = ePropertyFrameFormatUnique; 283 return GetPropertyAtIndexAs<const FormatEntity::Entry *>(idx); 284 } 285 286 uint64_t Debugger::GetStopDisassemblyMaxSize() const { 287 constexpr uint32_t idx = ePropertyStopDisassemblyMaxSize; 288 return GetPropertyAtIndexAs<uint64_t>( 289 idx, g_debugger_properties[idx].default_uint_value); 290 } 291 292 bool Debugger::GetNotifyVoid() const { 293 constexpr uint32_t idx = ePropertyNotiftVoid; 294 return GetPropertyAtIndexAs<uint64_t>( 295 idx, g_debugger_properties[idx].default_uint_value != 0); 296 } 297 298 llvm::StringRef Debugger::GetPrompt() const { 299 constexpr uint32_t idx = ePropertyPrompt; 300 return GetPropertyAtIndexAs<llvm::StringRef>( 301 idx, g_debugger_properties[idx].default_cstr_value); 302 } 303 304 void Debugger::SetPrompt(llvm::StringRef p) { 305 constexpr uint32_t idx = ePropertyPrompt; 306 SetPropertyAtIndex(idx, p); 307 llvm::StringRef new_prompt = GetPrompt(); 308 std::string str = 309 lldb_private::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor()); 310 if (str.length()) 311 new_prompt = str; 312 GetCommandInterpreter().UpdatePrompt(new_prompt); 313 } 314 315 const FormatEntity::Entry *Debugger::GetThreadFormat() const { 316 constexpr uint32_t idx = ePropertyThreadFormat; 317 return GetPropertyAtIndexAs<const FormatEntity::Entry *>(idx); 318 } 319 320 const FormatEntity::Entry *Debugger::GetThreadStopFormat() const { 321 constexpr uint32_t idx = ePropertyThreadStopFormat; 322 return GetPropertyAtIndexAs<const FormatEntity::Entry *>(idx); 323 } 324 325 lldb::ScriptLanguage Debugger::GetScriptLanguage() const { 326 const uint32_t idx = ePropertyScriptLanguage; 327 return GetPropertyAtIndexAs<lldb::ScriptLanguage>( 328 idx, static_cast<lldb::ScriptLanguage>( 329 g_debugger_properties[idx].default_uint_value)); 330 } 331 332 bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) { 333 const uint32_t idx = ePropertyScriptLanguage; 334 return SetPropertyAtIndex(idx, script_lang); 335 } 336 337 lldb::LanguageType Debugger::GetREPLLanguage() const { 338 const uint32_t idx = ePropertyREPLLanguage; 339 return GetPropertyAtIndexAs<LanguageType>(idx, {}); 340 } 341 342 bool Debugger::SetREPLLanguage(lldb::LanguageType repl_lang) { 343 const uint32_t idx = ePropertyREPLLanguage; 344 return SetPropertyAtIndex(idx, repl_lang); 345 } 346 347 uint64_t Debugger::GetTerminalWidth() const { 348 const uint32_t idx = ePropertyTerminalWidth; 349 return GetPropertyAtIndexAs<int64_t>( 350 idx, g_debugger_properties[idx].default_uint_value); 351 } 352 353 bool Debugger::SetTerminalWidth(uint64_t term_width) { 354 if (auto handler_sp = m_io_handler_stack.Top()) 355 handler_sp->TerminalSizeChanged(); 356 357 const uint32_t idx = ePropertyTerminalWidth; 358 return SetPropertyAtIndex(idx, term_width); 359 } 360 361 bool Debugger::GetUseExternalEditor() const { 362 const uint32_t idx = ePropertyUseExternalEditor; 363 return GetPropertyAtIndexAs<bool>( 364 idx, g_debugger_properties[idx].default_uint_value != 0); 365 } 366 367 bool Debugger::SetUseExternalEditor(bool b) { 368 const uint32_t idx = ePropertyUseExternalEditor; 369 return SetPropertyAtIndex(idx, b); 370 } 371 372 llvm::StringRef Debugger::GetExternalEditor() const { 373 const uint32_t idx = ePropertyExternalEditor; 374 return GetPropertyAtIndexAs<llvm::StringRef>( 375 idx, g_debugger_properties[idx].default_cstr_value); 376 } 377 378 bool Debugger::SetExternalEditor(llvm::StringRef editor) { 379 const uint32_t idx = ePropertyExternalEditor; 380 return SetPropertyAtIndex(idx, editor); 381 } 382 383 bool Debugger::GetUseColor() const { 384 const uint32_t idx = ePropertyUseColor; 385 return GetPropertyAtIndexAs<bool>( 386 idx, g_debugger_properties[idx].default_uint_value != 0); 387 } 388 389 bool Debugger::SetUseColor(bool b) { 390 const uint32_t idx = ePropertyUseColor; 391 bool ret = SetPropertyAtIndex(idx, b); 392 SetPrompt(GetPrompt()); 393 return ret; 394 } 395 396 bool Debugger::GetShowProgress() const { 397 const uint32_t idx = ePropertyShowProgress; 398 return GetPropertyAtIndexAs<bool>( 399 idx, g_debugger_properties[idx].default_uint_value != 0); 400 } 401 402 bool Debugger::SetShowProgress(bool show_progress) { 403 const uint32_t idx = ePropertyShowProgress; 404 return SetPropertyAtIndex(idx, show_progress); 405 } 406 407 llvm::StringRef Debugger::GetShowProgressAnsiPrefix() const { 408 const uint32_t idx = ePropertyShowProgressAnsiPrefix; 409 return GetPropertyAtIndexAs<llvm::StringRef>( 410 idx, g_debugger_properties[idx].default_cstr_value); 411 } 412 413 llvm::StringRef Debugger::GetShowProgressAnsiSuffix() const { 414 const uint32_t idx = ePropertyShowProgressAnsiSuffix; 415 return GetPropertyAtIndexAs<llvm::StringRef>( 416 idx, g_debugger_properties[idx].default_cstr_value); 417 } 418 419 bool Debugger::GetUseAutosuggestion() const { 420 const uint32_t idx = ePropertyShowAutosuggestion; 421 return GetPropertyAtIndexAs<bool>( 422 idx, g_debugger_properties[idx].default_uint_value != 0); 423 } 424 425 llvm::StringRef Debugger::GetAutosuggestionAnsiPrefix() const { 426 const uint32_t idx = ePropertyShowAutosuggestionAnsiPrefix; 427 return GetPropertyAtIndexAs<llvm::StringRef>( 428 idx, g_debugger_properties[idx].default_cstr_value); 429 } 430 431 llvm::StringRef Debugger::GetAutosuggestionAnsiSuffix() const { 432 const uint32_t idx = ePropertyShowAutosuggestionAnsiSuffix; 433 return GetPropertyAtIndexAs<llvm::StringRef>( 434 idx, g_debugger_properties[idx].default_cstr_value); 435 } 436 437 bool Debugger::GetUseSourceCache() const { 438 const uint32_t idx = ePropertyUseSourceCache; 439 return GetPropertyAtIndexAs<bool>( 440 idx, g_debugger_properties[idx].default_uint_value != 0); 441 } 442 443 bool Debugger::SetUseSourceCache(bool b) { 444 const uint32_t idx = ePropertyUseSourceCache; 445 bool ret = SetPropertyAtIndex(idx, b); 446 if (!ret) { 447 m_source_file_cache.Clear(); 448 } 449 return ret; 450 } 451 bool Debugger::GetHighlightSource() const { 452 const uint32_t idx = ePropertyHighlightSource; 453 return GetPropertyAtIndexAs<bool>( 454 idx, g_debugger_properties[idx].default_uint_value != 0); 455 } 456 457 StopShowColumn Debugger::GetStopShowColumn() const { 458 const uint32_t idx = ePropertyStopShowColumn; 459 return GetPropertyAtIndexAs<lldb::StopShowColumn>( 460 idx, static_cast<lldb::StopShowColumn>( 461 g_debugger_properties[idx].default_uint_value)); 462 } 463 464 llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const { 465 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix; 466 return GetPropertyAtIndexAs<llvm::StringRef>( 467 idx, g_debugger_properties[idx].default_cstr_value); 468 } 469 470 llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const { 471 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix; 472 return GetPropertyAtIndexAs<llvm::StringRef>( 473 idx, g_debugger_properties[idx].default_cstr_value); 474 } 475 476 llvm::StringRef Debugger::GetStopShowLineMarkerAnsiPrefix() const { 477 const uint32_t idx = ePropertyStopShowLineMarkerAnsiPrefix; 478 return GetPropertyAtIndexAs<llvm::StringRef>( 479 idx, g_debugger_properties[idx].default_cstr_value); 480 } 481 482 llvm::StringRef Debugger::GetStopShowLineMarkerAnsiSuffix() const { 483 const uint32_t idx = ePropertyStopShowLineMarkerAnsiSuffix; 484 return GetPropertyAtIndexAs<llvm::StringRef>( 485 idx, g_debugger_properties[idx].default_cstr_value); 486 } 487 488 uint64_t Debugger::GetStopSourceLineCount(bool before) const { 489 const uint32_t idx = 490 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter; 491 return GetPropertyAtIndexAs<uint64_t>( 492 idx, g_debugger_properties[idx].default_uint_value); 493 } 494 495 Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const { 496 const uint32_t idx = ePropertyStopDisassemblyDisplay; 497 return GetPropertyAtIndexAs<Debugger::StopDisassemblyType>( 498 idx, static_cast<Debugger::StopDisassemblyType>( 499 g_debugger_properties[idx].default_uint_value)); 500 } 501 502 uint64_t Debugger::GetDisassemblyLineCount() const { 503 const uint32_t idx = ePropertyStopDisassemblyCount; 504 return GetPropertyAtIndexAs<uint64_t>( 505 idx, g_debugger_properties[idx].default_uint_value); 506 } 507 508 bool Debugger::GetAutoOneLineSummaries() const { 509 const uint32_t idx = ePropertyAutoOneLineSummaries; 510 return GetPropertyAtIndexAs<bool>( 511 idx, g_debugger_properties[idx].default_uint_value != 0); 512 } 513 514 bool Debugger::GetEscapeNonPrintables() const { 515 const uint32_t idx = ePropertyEscapeNonPrintables; 516 return GetPropertyAtIndexAs<bool>( 517 idx, g_debugger_properties[idx].default_uint_value != 0); 518 } 519 520 bool Debugger::GetAutoIndent() const { 521 const uint32_t idx = ePropertyAutoIndent; 522 return GetPropertyAtIndexAs<bool>( 523 idx, g_debugger_properties[idx].default_uint_value != 0); 524 } 525 526 bool Debugger::SetAutoIndent(bool b) { 527 const uint32_t idx = ePropertyAutoIndent; 528 return SetPropertyAtIndex(idx, b); 529 } 530 531 bool Debugger::GetPrintDecls() const { 532 const uint32_t idx = ePropertyPrintDecls; 533 return GetPropertyAtIndexAs<bool>( 534 idx, g_debugger_properties[idx].default_uint_value != 0); 535 } 536 537 bool Debugger::SetPrintDecls(bool b) { 538 const uint32_t idx = ePropertyPrintDecls; 539 return SetPropertyAtIndex(idx, b); 540 } 541 542 uint64_t Debugger::GetTabSize() const { 543 const uint32_t idx = ePropertyTabSize; 544 return GetPropertyAtIndexAs<uint64_t>( 545 idx, g_debugger_properties[idx].default_uint_value); 546 } 547 548 bool Debugger::SetTabSize(uint64_t tab_size) { 549 const uint32_t idx = ePropertyTabSize; 550 return SetPropertyAtIndex(idx, tab_size); 551 } 552 553 lldb::DWIMPrintVerbosity Debugger::GetDWIMPrintVerbosity() const { 554 const uint32_t idx = ePropertyDWIMPrintVerbosity; 555 return GetPropertyAtIndexAs<lldb::DWIMPrintVerbosity>( 556 idx, static_cast<lldb::DWIMPrintVerbosity>( 557 g_debugger_properties[idx].default_uint_value)); 558 } 559 560 #pragma mark Debugger 561 562 // const DebuggerPropertiesSP & 563 // Debugger::GetSettings() const 564 //{ 565 // return m_properties_sp; 566 //} 567 // 568 569 void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) { 570 assert(g_debugger_list_ptr == nullptr && 571 "Debugger::Initialize called more than once!"); 572 g_debugger_list_mutex_ptr = new std::recursive_mutex(); 573 g_debugger_list_ptr = new DebuggerList(); 574 g_thread_pool = new llvm::ThreadPool(llvm::optimal_concurrency()); 575 g_load_plugin_callback = load_plugin_callback; 576 } 577 578 void Debugger::Terminate() { 579 assert(g_debugger_list_ptr && 580 "Debugger::Terminate called without a matching Debugger::Initialize!"); 581 582 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 583 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 584 for (const auto &debugger : *g_debugger_list_ptr) 585 debugger->HandleDestroyCallback(); 586 } 587 588 if (g_thread_pool) { 589 // The destructor will wait for all the threads to complete. 590 delete g_thread_pool; 591 } 592 593 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 594 // Clear our global list of debugger objects 595 { 596 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 597 for (const auto &debugger : *g_debugger_list_ptr) 598 debugger->Clear(); 599 g_debugger_list_ptr->clear(); 600 } 601 } 602 } 603 604 void Debugger::SettingsInitialize() { Target::SettingsInitialize(); } 605 606 void Debugger::SettingsTerminate() { Target::SettingsTerminate(); } 607 608 bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) { 609 if (g_load_plugin_callback) { 610 llvm::sys::DynamicLibrary dynlib = 611 g_load_plugin_callback(shared_from_this(), spec, error); 612 if (dynlib.isValid()) { 613 m_loaded_plugins.push_back(dynlib); 614 return true; 615 } 616 } else { 617 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and 618 // if the public API layer isn't available (code is linking against all of 619 // the internal LLDB static libraries), then we can't load plugins 620 error.SetErrorString("Public API layer is not available"); 621 } 622 return false; 623 } 624 625 static FileSystem::EnumerateDirectoryResult 626 LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft, 627 llvm::StringRef path) { 628 Status error; 629 630 static constexpr llvm::StringLiteral g_dylibext(".dylib"); 631 static constexpr llvm::StringLiteral g_solibext(".so"); 632 633 if (!baton) 634 return FileSystem::eEnumerateDirectoryResultQuit; 635 636 Debugger *debugger = (Debugger *)baton; 637 638 namespace fs = llvm::sys::fs; 639 // If we have a regular file, a symbolic link or unknown file type, try and 640 // process the file. We must handle unknown as sometimes the directory 641 // enumeration might be enumerating a file system that doesn't have correct 642 // file type information. 643 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file || 644 ft == fs::file_type::type_unknown) { 645 FileSpec plugin_file_spec(path); 646 FileSystem::Instance().Resolve(plugin_file_spec); 647 648 if (plugin_file_spec.GetFileNameExtension() != g_dylibext && 649 plugin_file_spec.GetFileNameExtension() != g_solibext) { 650 return FileSystem::eEnumerateDirectoryResultNext; 651 } 652 653 Status plugin_load_error; 654 debugger->LoadPlugin(plugin_file_spec, plugin_load_error); 655 656 return FileSystem::eEnumerateDirectoryResultNext; 657 } else if (ft == fs::file_type::directory_file || 658 ft == fs::file_type::symlink_file || 659 ft == fs::file_type::type_unknown) { 660 // Try and recurse into anything that a directory or symbolic link. We must 661 // also do this for unknown as sometimes the directory enumeration might be 662 // enumerating a file system that doesn't have correct file type 663 // information. 664 return FileSystem::eEnumerateDirectoryResultEnter; 665 } 666 667 return FileSystem::eEnumerateDirectoryResultNext; 668 } 669 670 void Debugger::InstanceInitialize() { 671 const bool find_directories = true; 672 const bool find_files = true; 673 const bool find_other = true; 674 char dir_path[PATH_MAX]; 675 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) { 676 if (FileSystem::Instance().Exists(dir_spec) && 677 dir_spec.GetPath(dir_path, sizeof(dir_path))) { 678 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories, 679 find_files, find_other, 680 LoadPluginCallback, this); 681 } 682 } 683 684 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) { 685 if (FileSystem::Instance().Exists(dir_spec) && 686 dir_spec.GetPath(dir_path, sizeof(dir_path))) { 687 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories, 688 find_files, find_other, 689 LoadPluginCallback, this); 690 } 691 } 692 693 PluginManager::DebuggerInitialize(*this); 694 } 695 696 DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback, 697 void *baton) { 698 DebuggerSP debugger_sp(new Debugger(log_callback, baton)); 699 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 700 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 701 g_debugger_list_ptr->push_back(debugger_sp); 702 } 703 debugger_sp->InstanceInitialize(); 704 return debugger_sp; 705 } 706 707 void Debugger::HandleDestroyCallback() { 708 if (m_destroy_callback) { 709 m_destroy_callback(GetID(), m_destroy_callback_baton); 710 m_destroy_callback = nullptr; 711 } 712 } 713 714 void Debugger::Destroy(DebuggerSP &debugger_sp) { 715 if (!debugger_sp) 716 return; 717 718 debugger_sp->HandleDestroyCallback(); 719 CommandInterpreter &cmd_interpreter = debugger_sp->GetCommandInterpreter(); 720 721 if (cmd_interpreter.GetSaveSessionOnQuit()) { 722 CommandReturnObject result(debugger_sp->GetUseColor()); 723 cmd_interpreter.SaveTranscript(result); 724 if (result.Succeeded()) 725 (*debugger_sp->GetAsyncOutputStream()) << result.GetOutputData() << '\n'; 726 else 727 (*debugger_sp->GetAsyncErrorStream()) << result.GetErrorData() << '\n'; 728 } 729 730 debugger_sp->Clear(); 731 732 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 733 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 734 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 735 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) { 736 if ((*pos).get() == debugger_sp.get()) { 737 g_debugger_list_ptr->erase(pos); 738 return; 739 } 740 } 741 } 742 } 743 744 DebuggerSP 745 Debugger::FindDebuggerWithInstanceName(llvm::StringRef instance_name) { 746 if (!g_debugger_list_ptr || !g_debugger_list_mutex_ptr) 747 return DebuggerSP(); 748 749 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 750 for (const DebuggerSP &debugger_sp : *g_debugger_list_ptr) { 751 if (!debugger_sp) 752 continue; 753 754 if (llvm::StringRef(debugger_sp->GetInstanceName()) == instance_name) 755 return debugger_sp; 756 } 757 return DebuggerSP(); 758 } 759 760 TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) { 761 TargetSP target_sp; 762 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 763 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 764 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 765 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) { 766 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid); 767 if (target_sp) 768 break; 769 } 770 } 771 return target_sp; 772 } 773 774 TargetSP Debugger::FindTargetWithProcess(Process *process) { 775 TargetSP target_sp; 776 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 777 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 778 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 779 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) { 780 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process); 781 if (target_sp) 782 break; 783 } 784 } 785 return target_sp; 786 } 787 788 ConstString Debugger::GetStaticBroadcasterClass() { 789 static ConstString class_name("lldb.debugger"); 790 return class_name; 791 } 792 793 Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton) 794 : UserID(g_unique_id++), 795 Properties(std::make_shared<OptionValueProperties>()), 796 m_input_file_sp(std::make_shared<NativeFile>(stdin, false)), 797 m_output_stream_sp(std::make_shared<StreamFile>(stdout, false)), 798 m_error_stream_sp(std::make_shared<StreamFile>(stderr, false)), 799 m_input_recorder(nullptr), 800 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()), 801 m_terminal_state(), m_target_list(*this), m_platform_list(), 802 m_listener_sp(Listener::MakeListener("lldb.Debugger")), 803 m_source_manager_up(), m_source_file_cache(), 804 m_command_interpreter_up( 805 std::make_unique<CommandInterpreter>(*this, false)), 806 m_io_handler_stack(), 807 m_instance_name(llvm::formatv("debugger_{0}", GetID()).str()), 808 m_loaded_plugins(), m_event_handler_thread(), m_io_handler_thread(), 809 m_sync_broadcaster(nullptr, "lldb.debugger.sync"), 810 m_broadcaster(m_broadcaster_manager_sp, 811 GetStaticBroadcasterClass().AsCString()), 812 m_forward_listener_sp(), m_clear_once() { 813 // Initialize the debugger properties as early as possible as other parts of 814 // LLDB will start querying them during construction. 815 m_collection_sp->Initialize(g_debugger_properties); 816 m_collection_sp->AppendProperty( 817 "target", "Settings specify to debugging targets.", true, 818 Target::GetGlobalProperties().GetValueProperties()); 819 m_collection_sp->AppendProperty( 820 "platform", "Platform settings.", true, 821 Platform::GetGlobalPlatformProperties().GetValueProperties()); 822 m_collection_sp->AppendProperty( 823 "symbols", "Symbol lookup and cache settings.", true, 824 ModuleList::GetGlobalModuleListProperties().GetValueProperties()); 825 if (m_command_interpreter_up) { 826 m_collection_sp->AppendProperty( 827 "interpreter", 828 "Settings specify to the debugger's command interpreter.", true, 829 m_command_interpreter_up->GetValueProperties()); 830 } 831 if (log_callback) 832 m_callback_handler_sp = 833 std::make_shared<CallbackLogHandler>(log_callback, baton); 834 m_command_interpreter_up->Initialize(); 835 // Always add our default platform to the platform list 836 PlatformSP default_platform_sp(Platform::GetHostPlatform()); 837 assert(default_platform_sp); 838 m_platform_list.Append(default_platform_sp, true); 839 840 // Create the dummy target. 841 { 842 ArchSpec arch(Target::GetDefaultArchitecture()); 843 if (!arch.IsValid()) 844 arch = HostInfo::GetArchitecture(); 845 assert(arch.IsValid() && "No valid default or host archspec"); 846 const bool is_dummy_target = true; 847 m_dummy_target_sp.reset( 848 new Target(*this, arch, default_platform_sp, is_dummy_target)); 849 } 850 assert(m_dummy_target_sp.get() && "Couldn't construct dummy target?"); 851 852 OptionValueSInt64 *term_width = 853 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64( 854 ePropertyTerminalWidth); 855 term_width->SetMinimumValue(10); 856 term_width->SetMaximumValue(1024); 857 858 // Turn off use-color if this is a dumb terminal. 859 const char *term = getenv("TERM"); 860 if (term && !strcmp(term, "dumb")) 861 SetUseColor(false); 862 // Turn off use-color if we don't write to a terminal with color support. 863 if (!GetOutputFile().GetIsTerminalWithColors()) 864 SetUseColor(false); 865 866 if (Diagnostics::Enabled()) { 867 m_diagnostics_callback_id = Diagnostics::Instance().AddCallback( 868 [this](const FileSpec &dir) -> llvm::Error { 869 for (auto &entry : m_stream_handlers) { 870 llvm::StringRef log_path = entry.first(); 871 llvm::StringRef file_name = llvm::sys::path::filename(log_path); 872 FileSpec destination = dir.CopyByAppendingPathComponent(file_name); 873 std::error_code ec = 874 llvm::sys::fs::copy_file(log_path, destination.GetPath()); 875 if (ec) 876 return llvm::errorCodeToError(ec); 877 } 878 return llvm::Error::success(); 879 }); 880 } 881 882 #if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING) 883 // Enabling use of ANSI color codes because LLDB is using them to highlight 884 // text. 885 llvm::sys::Process::UseANSIEscapeCodes(true); 886 #endif 887 } 888 889 Debugger::~Debugger() { Clear(); } 890 891 void Debugger::Clear() { 892 // Make sure we call this function only once. With the C++ global destructor 893 // chain having a list of debuggers and with code that can be running on 894 // other threads, we need to ensure this doesn't happen multiple times. 895 // 896 // The following functions call Debugger::Clear(): 897 // Debugger::~Debugger(); 898 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp); 899 // static void Debugger::Terminate(); 900 llvm::call_once(m_clear_once, [this]() { 901 ClearIOHandlers(); 902 StopIOHandlerThread(); 903 StopEventHandlerThread(); 904 m_listener_sp->Clear(); 905 for (TargetSP target_sp : m_target_list.Targets()) { 906 if (target_sp) { 907 if (ProcessSP process_sp = target_sp->GetProcessSP()) 908 process_sp->Finalize(); 909 target_sp->Destroy(); 910 } 911 } 912 m_broadcaster_manager_sp->Clear(); 913 914 // Close the input file _before_ we close the input read communications 915 // class as it does NOT own the input file, our m_input_file does. 916 m_terminal_state.Clear(); 917 GetInputFile().Close(); 918 919 m_command_interpreter_up->Clear(); 920 921 if (Diagnostics::Enabled()) 922 Diagnostics::Instance().RemoveCallback(m_diagnostics_callback_id); 923 }); 924 } 925 926 bool Debugger::GetCloseInputOnEOF() const { 927 // return m_input_comm.GetCloseOnEOF(); 928 return false; 929 } 930 931 void Debugger::SetCloseInputOnEOF(bool b) { 932 // m_input_comm.SetCloseOnEOF(b); 933 } 934 935 bool Debugger::GetAsyncExecution() { 936 return !m_command_interpreter_up->GetSynchronous(); 937 } 938 939 void Debugger::SetAsyncExecution(bool async_execution) { 940 m_command_interpreter_up->SetSynchronous(!async_execution); 941 } 942 943 repro::DataRecorder *Debugger::GetInputRecorder() { return m_input_recorder; } 944 945 static inline int OpenPipe(int fds[2], std::size_t size) { 946 #ifdef _WIN32 947 return _pipe(fds, size, O_BINARY); 948 #else 949 (void)size; 950 return pipe(fds); 951 #endif 952 } 953 954 Status Debugger::SetInputString(const char *data) { 955 Status result; 956 enum PIPES { READ, WRITE }; // Indexes for the read and write fds 957 int fds[2] = {-1, -1}; 958 959 if (data == nullptr) { 960 result.SetErrorString("String data is null"); 961 return result; 962 } 963 964 size_t size = strlen(data); 965 if (size == 0) { 966 result.SetErrorString("String data is empty"); 967 return result; 968 } 969 970 if (OpenPipe(fds, size) != 0) { 971 result.SetErrorString( 972 "can't create pipe file descriptors for LLDB commands"); 973 return result; 974 } 975 976 int r = write(fds[WRITE], data, size); 977 (void)r; 978 // Close the write end of the pipe, so that the command interpreter will exit 979 // when it consumes all the data. 980 llvm::sys::Process::SafelyCloseFileDescriptor(fds[WRITE]); 981 982 // Open the read file descriptor as a FILE * that we can return as an input 983 // handle. 984 FILE *commands_file = fdopen(fds[READ], "rb"); 985 if (commands_file == nullptr) { 986 result.SetErrorStringWithFormat("fdopen(%i, \"rb\") failed (errno = %i) " 987 "when trying to open LLDB commands pipe", 988 fds[READ], errno); 989 llvm::sys::Process::SafelyCloseFileDescriptor(fds[READ]); 990 return result; 991 } 992 993 SetInputFile((FileSP)std::make_shared<NativeFile>(commands_file, true)); 994 return result; 995 } 996 997 void Debugger::SetInputFile(FileSP file_sp) { 998 assert(file_sp && file_sp->IsValid()); 999 m_input_file_sp = std::move(file_sp); 1000 // Save away the terminal state if that is relevant, so that we can restore 1001 // it in RestoreInputState. 1002 SaveInputTerminalState(); 1003 } 1004 1005 void Debugger::SetOutputFile(FileSP file_sp) { 1006 assert(file_sp && file_sp->IsValid()); 1007 m_output_stream_sp = std::make_shared<StreamFile>(file_sp); 1008 } 1009 1010 void Debugger::SetErrorFile(FileSP file_sp) { 1011 assert(file_sp && file_sp->IsValid()); 1012 m_error_stream_sp = std::make_shared<StreamFile>(file_sp); 1013 } 1014 1015 void Debugger::SaveInputTerminalState() { 1016 int fd = GetInputFile().GetDescriptor(); 1017 if (fd != File::kInvalidDescriptor) 1018 m_terminal_state.Save(fd, true); 1019 } 1020 1021 void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); } 1022 1023 ExecutionContext Debugger::GetSelectedExecutionContext() { 1024 bool adopt_selected = true; 1025 ExecutionContextRef exe_ctx_ref(GetSelectedTarget().get(), adopt_selected); 1026 return ExecutionContext(exe_ctx_ref); 1027 } 1028 1029 void Debugger::DispatchInputInterrupt() { 1030 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 1031 IOHandlerSP reader_sp(m_io_handler_stack.Top()); 1032 if (reader_sp) 1033 reader_sp->Interrupt(); 1034 } 1035 1036 void Debugger::DispatchInputEndOfFile() { 1037 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 1038 IOHandlerSP reader_sp(m_io_handler_stack.Top()); 1039 if (reader_sp) 1040 reader_sp->GotEOF(); 1041 } 1042 1043 void Debugger::ClearIOHandlers() { 1044 // The bottom input reader should be the main debugger input reader. We do 1045 // not want to close that one here. 1046 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 1047 while (m_io_handler_stack.GetSize() > 1) { 1048 IOHandlerSP reader_sp(m_io_handler_stack.Top()); 1049 if (reader_sp) 1050 PopIOHandler(reader_sp); 1051 } 1052 } 1053 1054 void Debugger::RunIOHandlers() { 1055 IOHandlerSP reader_sp = m_io_handler_stack.Top(); 1056 while (true) { 1057 if (!reader_sp) 1058 break; 1059 1060 reader_sp->Run(); 1061 { 1062 std::lock_guard<std::recursive_mutex> guard( 1063 m_io_handler_synchronous_mutex); 1064 1065 // Remove all input readers that are done from the top of the stack 1066 while (true) { 1067 IOHandlerSP top_reader_sp = m_io_handler_stack.Top(); 1068 if (top_reader_sp && top_reader_sp->GetIsDone()) 1069 PopIOHandler(top_reader_sp); 1070 else 1071 break; 1072 } 1073 reader_sp = m_io_handler_stack.Top(); 1074 } 1075 } 1076 ClearIOHandlers(); 1077 } 1078 1079 void Debugger::RunIOHandlerSync(const IOHandlerSP &reader_sp) { 1080 std::lock_guard<std::recursive_mutex> guard(m_io_handler_synchronous_mutex); 1081 1082 PushIOHandler(reader_sp); 1083 IOHandlerSP top_reader_sp = reader_sp; 1084 1085 while (top_reader_sp) { 1086 if (!top_reader_sp) 1087 break; 1088 1089 top_reader_sp->Run(); 1090 1091 // Don't unwind past the starting point. 1092 if (top_reader_sp.get() == reader_sp.get()) { 1093 if (PopIOHandler(reader_sp)) 1094 break; 1095 } 1096 1097 // If we pushed new IO handlers, pop them if they're done or restart the 1098 // loop to run them if they're not. 1099 while (true) { 1100 top_reader_sp = m_io_handler_stack.Top(); 1101 if (top_reader_sp && top_reader_sp->GetIsDone()) { 1102 PopIOHandler(top_reader_sp); 1103 // Don't unwind past the starting point. 1104 if (top_reader_sp.get() == reader_sp.get()) 1105 return; 1106 } else { 1107 break; 1108 } 1109 } 1110 } 1111 } 1112 1113 bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) { 1114 return m_io_handler_stack.IsTop(reader_sp); 1115 } 1116 1117 bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type, 1118 IOHandler::Type second_top_type) { 1119 return m_io_handler_stack.CheckTopIOHandlerTypes(top_type, second_top_type); 1120 } 1121 1122 void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) { 1123 bool printed = m_io_handler_stack.PrintAsync(s, len, is_stdout); 1124 if (!printed) { 1125 lldb::StreamFileSP stream = 1126 is_stdout ? m_output_stream_sp : m_error_stream_sp; 1127 stream->Write(s, len); 1128 } 1129 } 1130 1131 llvm::StringRef Debugger::GetTopIOHandlerControlSequence(char ch) { 1132 return m_io_handler_stack.GetTopIOHandlerControlSequence(ch); 1133 } 1134 1135 const char *Debugger::GetIOHandlerCommandPrefix() { 1136 return m_io_handler_stack.GetTopIOHandlerCommandPrefix(); 1137 } 1138 1139 const char *Debugger::GetIOHandlerHelpPrologue() { 1140 return m_io_handler_stack.GetTopIOHandlerHelpPrologue(); 1141 } 1142 1143 bool Debugger::RemoveIOHandler(const IOHandlerSP &reader_sp) { 1144 return PopIOHandler(reader_sp); 1145 } 1146 1147 void Debugger::RunIOHandlerAsync(const IOHandlerSP &reader_sp, 1148 bool cancel_top_handler) { 1149 PushIOHandler(reader_sp, cancel_top_handler); 1150 } 1151 1152 void Debugger::AdoptTopIOHandlerFilesIfInvalid(FileSP &in, StreamFileSP &out, 1153 StreamFileSP &err) { 1154 // Before an IOHandler runs, it must have in/out/err streams. This function 1155 // is called when one ore more of the streams are nullptr. We use the top 1156 // input reader's in/out/err streams, or fall back to the debugger file 1157 // handles, or we fall back onto stdin/stdout/stderr as a last resort. 1158 1159 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 1160 IOHandlerSP top_reader_sp(m_io_handler_stack.Top()); 1161 // If no STDIN has been set, then set it appropriately 1162 if (!in || !in->IsValid()) { 1163 if (top_reader_sp) 1164 in = top_reader_sp->GetInputFileSP(); 1165 else 1166 in = GetInputFileSP(); 1167 // If there is nothing, use stdin 1168 if (!in) 1169 in = std::make_shared<NativeFile>(stdin, false); 1170 } 1171 // If no STDOUT has been set, then set it appropriately 1172 if (!out || !out->GetFile().IsValid()) { 1173 if (top_reader_sp) 1174 out = top_reader_sp->GetOutputStreamFileSP(); 1175 else 1176 out = GetOutputStreamSP(); 1177 // If there is nothing, use stdout 1178 if (!out) 1179 out = std::make_shared<StreamFile>(stdout, false); 1180 } 1181 // If no STDERR has been set, then set it appropriately 1182 if (!err || !err->GetFile().IsValid()) { 1183 if (top_reader_sp) 1184 err = top_reader_sp->GetErrorStreamFileSP(); 1185 else 1186 err = GetErrorStreamSP(); 1187 // If there is nothing, use stderr 1188 if (!err) 1189 err = std::make_shared<StreamFile>(stderr, false); 1190 } 1191 } 1192 1193 void Debugger::PushIOHandler(const IOHandlerSP &reader_sp, 1194 bool cancel_top_handler) { 1195 if (!reader_sp) 1196 return; 1197 1198 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 1199 1200 // Get the current top input reader... 1201 IOHandlerSP top_reader_sp(m_io_handler_stack.Top()); 1202 1203 // Don't push the same IO handler twice... 1204 if (reader_sp == top_reader_sp) 1205 return; 1206 1207 // Push our new input reader 1208 m_io_handler_stack.Push(reader_sp); 1209 reader_sp->Activate(); 1210 1211 // Interrupt the top input reader to it will exit its Run() function and let 1212 // this new input reader take over 1213 if (top_reader_sp) { 1214 top_reader_sp->Deactivate(); 1215 if (cancel_top_handler) 1216 top_reader_sp->Cancel(); 1217 } 1218 } 1219 1220 bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) { 1221 if (!pop_reader_sp) 1222 return false; 1223 1224 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 1225 1226 // The reader on the stop of the stack is done, so let the next read on the 1227 // stack refresh its prompt and if there is one... 1228 if (m_io_handler_stack.IsEmpty()) 1229 return false; 1230 1231 IOHandlerSP reader_sp(m_io_handler_stack.Top()); 1232 1233 if (pop_reader_sp != reader_sp) 1234 return false; 1235 1236 reader_sp->Deactivate(); 1237 reader_sp->Cancel(); 1238 m_io_handler_stack.Pop(); 1239 1240 reader_sp = m_io_handler_stack.Top(); 1241 if (reader_sp) 1242 reader_sp->Activate(); 1243 1244 return true; 1245 } 1246 1247 StreamSP Debugger::GetAsyncOutputStream() { 1248 return std::make_shared<StreamAsynchronousIO>(*this, true, GetUseColor()); 1249 } 1250 1251 StreamSP Debugger::GetAsyncErrorStream() { 1252 return std::make_shared<StreamAsynchronousIO>(*this, false, GetUseColor()); 1253 } 1254 1255 void Debugger::RequestInterrupt() { 1256 std::lock_guard<std::mutex> guard(m_interrupt_mutex); 1257 m_interrupt_requested++; 1258 } 1259 1260 void Debugger::CancelInterruptRequest() { 1261 std::lock_guard<std::mutex> guard(m_interrupt_mutex); 1262 if (m_interrupt_requested > 0) 1263 m_interrupt_requested--; 1264 } 1265 1266 bool Debugger::InterruptRequested() { 1267 // This is the one we should call internally. This will return true either 1268 // if there's a debugger interrupt and we aren't on the IOHandler thread, 1269 // or if we are on the IOHandler thread and there's a CommandInterpreter 1270 // interrupt. 1271 if (!IsIOHandlerThreadCurrentThread()) { 1272 std::lock_guard<std::mutex> guard(m_interrupt_mutex); 1273 return m_interrupt_requested != 0; 1274 } 1275 return GetCommandInterpreter().WasInterrupted(); 1276 } 1277 1278 Debugger::InterruptionReport::InterruptionReport(std::string function_name, 1279 const llvm::formatv_object_base &payload) : 1280 m_function_name(std::move(function_name)), 1281 m_interrupt_time(std::chrono::system_clock::now()), 1282 m_thread_id(llvm::get_threadid()) { 1283 llvm::raw_string_ostream desc(m_description); 1284 desc << payload << "\n"; 1285 } 1286 1287 void Debugger::ReportInterruption(const InterruptionReport &report) { 1288 // For now, just log the description: 1289 Log *log = GetLog(LLDBLog::Host); 1290 LLDB_LOG(log, "Interruption: {0}", report.m_description); 1291 } 1292 1293 Debugger::DebuggerList Debugger::DebuggersRequestingInterruption() { 1294 DebuggerList result; 1295 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1296 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1297 for (auto debugger_sp : *g_debugger_list_ptr) { 1298 if (debugger_sp->InterruptRequested()) 1299 result.push_back(debugger_sp); 1300 } 1301 } 1302 return result; 1303 } 1304 1305 size_t Debugger::GetNumDebuggers() { 1306 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1307 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1308 return g_debugger_list_ptr->size(); 1309 } 1310 return 0; 1311 } 1312 1313 lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) { 1314 DebuggerSP debugger_sp; 1315 1316 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1317 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1318 if (index < g_debugger_list_ptr->size()) 1319 debugger_sp = g_debugger_list_ptr->at(index); 1320 } 1321 1322 return debugger_sp; 1323 } 1324 1325 DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) { 1326 DebuggerSP debugger_sp; 1327 1328 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1329 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1330 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 1331 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) { 1332 if ((*pos)->GetID() == id) { 1333 debugger_sp = *pos; 1334 break; 1335 } 1336 } 1337 } 1338 return debugger_sp; 1339 } 1340 1341 bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format, 1342 const SymbolContext *sc, 1343 const SymbolContext *prev_sc, 1344 const ExecutionContext *exe_ctx, 1345 const Address *addr, Stream &s) { 1346 FormatEntity::Entry format_entry; 1347 1348 if (format == nullptr) { 1349 if (exe_ctx != nullptr && exe_ctx->HasTargetScope()) 1350 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat(); 1351 if (format == nullptr) { 1352 FormatEntity::Parse("${addr}: ", format_entry); 1353 format = &format_entry; 1354 } 1355 } 1356 bool function_changed = false; 1357 bool initial_function = false; 1358 if (prev_sc && (prev_sc->function || prev_sc->symbol)) { 1359 if (sc && (sc->function || sc->symbol)) { 1360 if (prev_sc->symbol && sc->symbol) { 1361 if (!sc->symbol->Compare(prev_sc->symbol->GetName(), 1362 prev_sc->symbol->GetType())) { 1363 function_changed = true; 1364 } 1365 } else if (prev_sc->function && sc->function) { 1366 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) { 1367 function_changed = true; 1368 } 1369 } 1370 } 1371 } 1372 // The first context on a list of instructions will have a prev_sc that has 1373 // no Function or Symbol -- if SymbolContext had an IsValid() method, it 1374 // would return false. But we do get a prev_sc pointer. 1375 if ((sc && (sc->function || sc->symbol)) && prev_sc && 1376 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) { 1377 initial_function = true; 1378 } 1379 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr, 1380 function_changed, initial_function); 1381 } 1382 1383 void Debugger::AssertCallback(llvm::StringRef message, 1384 llvm::StringRef backtrace, 1385 llvm::StringRef prompt) { 1386 Debugger::ReportError( 1387 llvm::formatv("{0}\n{1}{2}", message, backtrace, prompt).str()); 1388 } 1389 1390 void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback, 1391 void *baton) { 1392 // For simplicity's sake, I am not going to deal with how to close down any 1393 // open logging streams, I just redirect everything from here on out to the 1394 // callback. 1395 m_callback_handler_sp = 1396 std::make_shared<CallbackLogHandler>(log_callback, baton); 1397 } 1398 1399 void Debugger::SetDestroyCallback( 1400 lldb_private::DebuggerDestroyCallback destroy_callback, void *baton) { 1401 m_destroy_callback = destroy_callback; 1402 m_destroy_callback_baton = baton; 1403 } 1404 1405 static void PrivateReportProgress(Debugger &debugger, uint64_t progress_id, 1406 std::string title, std::string details, 1407 uint64_t completed, uint64_t total, 1408 bool is_debugger_specific) { 1409 // Only deliver progress events if we have any progress listeners. 1410 const uint32_t event_type = Debugger::eBroadcastBitProgress; 1411 if (!debugger.GetBroadcaster().EventTypeHasListeners(event_type)) 1412 return; 1413 EventSP event_sp(new Event( 1414 event_type, 1415 new ProgressEventData(progress_id, std::move(title), std::move(details), 1416 completed, total, is_debugger_specific))); 1417 debugger.GetBroadcaster().BroadcastEvent(event_sp); 1418 } 1419 1420 void Debugger::ReportProgress(uint64_t progress_id, std::string title, 1421 std::string details, uint64_t completed, 1422 uint64_t total, 1423 std::optional<lldb::user_id_t> debugger_id) { 1424 // Check if this progress is for a specific debugger. 1425 if (debugger_id) { 1426 // It is debugger specific, grab it and deliver the event if the debugger 1427 // still exists. 1428 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id); 1429 if (debugger_sp) 1430 PrivateReportProgress(*debugger_sp, progress_id, std::move(title), 1431 std::move(details), completed, total, 1432 /*is_debugger_specific*/ true); 1433 return; 1434 } 1435 // The progress event is not debugger specific, iterate over all debuggers 1436 // and deliver a progress event to each one. 1437 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1438 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1439 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 1440 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) 1441 PrivateReportProgress(*(*pos), progress_id, title, details, completed, 1442 total, /*is_debugger_specific*/ false); 1443 } 1444 } 1445 1446 static void PrivateReportDiagnostic(Debugger &debugger, 1447 DiagnosticEventData::Type type, 1448 std::string message, 1449 bool debugger_specific) { 1450 uint32_t event_type = 0; 1451 switch (type) { 1452 case DiagnosticEventData::Type::Info: 1453 assert(false && "DiagnosticEventData::Type::Info should not be broadcast"); 1454 return; 1455 case DiagnosticEventData::Type::Warning: 1456 event_type = Debugger::eBroadcastBitWarning; 1457 break; 1458 case DiagnosticEventData::Type::Error: 1459 event_type = Debugger::eBroadcastBitError; 1460 break; 1461 } 1462 1463 Broadcaster &broadcaster = debugger.GetBroadcaster(); 1464 if (!broadcaster.EventTypeHasListeners(event_type)) { 1465 // Diagnostics are too important to drop. If nobody is listening, print the 1466 // diagnostic directly to the debugger's error stream. 1467 DiagnosticEventData event_data(type, std::move(message), debugger_specific); 1468 StreamSP stream = debugger.GetAsyncErrorStream(); 1469 event_data.Dump(stream.get()); 1470 return; 1471 } 1472 EventSP event_sp = std::make_shared<Event>( 1473 event_type, 1474 new DiagnosticEventData(type, std::move(message), debugger_specific)); 1475 broadcaster.BroadcastEvent(event_sp); 1476 } 1477 1478 void Debugger::ReportDiagnosticImpl(DiagnosticEventData::Type type, 1479 std::string message, 1480 std::optional<lldb::user_id_t> debugger_id, 1481 std::once_flag *once) { 1482 auto ReportDiagnosticLambda = [&]() { 1483 // The diagnostic subsystem is optional but we still want to broadcast 1484 // events when it's disabled. 1485 if (Diagnostics::Enabled()) 1486 Diagnostics::Instance().Report(message); 1487 1488 // We don't broadcast info events. 1489 if (type == DiagnosticEventData::Type::Info) 1490 return; 1491 1492 // Check if this diagnostic is for a specific debugger. 1493 if (debugger_id) { 1494 // It is debugger specific, grab it and deliver the event if the debugger 1495 // still exists. 1496 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id); 1497 if (debugger_sp) 1498 PrivateReportDiagnostic(*debugger_sp, type, std::move(message), true); 1499 return; 1500 } 1501 // The diagnostic event is not debugger specific, iterate over all debuggers 1502 // and deliver a diagnostic event to each one. 1503 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1504 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1505 for (const auto &debugger : *g_debugger_list_ptr) 1506 PrivateReportDiagnostic(*debugger, type, message, false); 1507 } 1508 }; 1509 1510 if (once) 1511 std::call_once(*once, ReportDiagnosticLambda); 1512 else 1513 ReportDiagnosticLambda(); 1514 } 1515 1516 void Debugger::ReportWarning(std::string message, 1517 std::optional<lldb::user_id_t> debugger_id, 1518 std::once_flag *once) { 1519 ReportDiagnosticImpl(DiagnosticEventData::Type::Warning, std::move(message), 1520 debugger_id, once); 1521 } 1522 1523 void Debugger::ReportError(std::string message, 1524 std::optional<lldb::user_id_t> debugger_id, 1525 std::once_flag *once) { 1526 ReportDiagnosticImpl(DiagnosticEventData::Type::Error, std::move(message), 1527 debugger_id, once); 1528 } 1529 1530 void Debugger::ReportInfo(std::string message, 1531 std::optional<lldb::user_id_t> debugger_id, 1532 std::once_flag *once) { 1533 ReportDiagnosticImpl(DiagnosticEventData::Type::Info, std::move(message), 1534 debugger_id, once); 1535 } 1536 1537 void Debugger::ReportSymbolChange(const ModuleSpec &module_spec) { 1538 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1539 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1540 for (DebuggerSP debugger_sp : *g_debugger_list_ptr) { 1541 EventSP event_sp = std::make_shared<Event>( 1542 Debugger::eBroadcastSymbolChange, 1543 new SymbolChangeEventData(debugger_sp, module_spec)); 1544 debugger_sp->GetBroadcaster().BroadcastEvent(event_sp); 1545 } 1546 } 1547 } 1548 1549 static std::shared_ptr<LogHandler> 1550 CreateLogHandler(LogHandlerKind log_handler_kind, int fd, bool should_close, 1551 size_t buffer_size) { 1552 switch (log_handler_kind) { 1553 case eLogHandlerStream: 1554 return std::make_shared<StreamLogHandler>(fd, should_close, buffer_size); 1555 case eLogHandlerCircular: 1556 return std::make_shared<RotatingLogHandler>(buffer_size); 1557 case eLogHandlerSystem: 1558 return std::make_shared<SystemLogHandler>(); 1559 case eLogHandlerCallback: 1560 return {}; 1561 } 1562 return {}; 1563 } 1564 1565 bool Debugger::EnableLog(llvm::StringRef channel, 1566 llvm::ArrayRef<const char *> categories, 1567 llvm::StringRef log_file, uint32_t log_options, 1568 size_t buffer_size, LogHandlerKind log_handler_kind, 1569 llvm::raw_ostream &error_stream) { 1570 1571 std::shared_ptr<LogHandler> log_handler_sp; 1572 if (m_callback_handler_sp) { 1573 log_handler_sp = m_callback_handler_sp; 1574 // For now when using the callback mode you always get thread & timestamp. 1575 log_options |= 1576 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME; 1577 } else if (log_file.empty()) { 1578 log_handler_sp = 1579 CreateLogHandler(log_handler_kind, GetOutputFile().GetDescriptor(), 1580 /*should_close=*/false, buffer_size); 1581 } else { 1582 auto pos = m_stream_handlers.find(log_file); 1583 if (pos != m_stream_handlers.end()) 1584 log_handler_sp = pos->second.lock(); 1585 if (!log_handler_sp) { 1586 File::OpenOptions flags = 1587 File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate; 1588 if (log_options & LLDB_LOG_OPTION_APPEND) 1589 flags |= File::eOpenOptionAppend; 1590 else 1591 flags |= File::eOpenOptionTruncate; 1592 llvm::Expected<FileUP> file = FileSystem::Instance().Open( 1593 FileSpec(log_file), flags, lldb::eFilePermissionsFileDefault, false); 1594 if (!file) { 1595 error_stream << "Unable to open log file '" << log_file 1596 << "': " << llvm::toString(file.takeError()) << "\n"; 1597 return false; 1598 } 1599 1600 log_handler_sp = 1601 CreateLogHandler(log_handler_kind, (*file)->GetDescriptor(), 1602 /*should_close=*/true, buffer_size); 1603 m_stream_handlers[log_file] = log_handler_sp; 1604 } 1605 } 1606 assert(log_handler_sp); 1607 1608 if (log_options == 0) 1609 log_options = LLDB_LOG_OPTION_PREPEND_THREAD_NAME; 1610 1611 return Log::EnableLogChannel(log_handler_sp, log_options, channel, categories, 1612 error_stream); 1613 } 1614 1615 ScriptInterpreter * 1616 Debugger::GetScriptInterpreter(bool can_create, 1617 std::optional<lldb::ScriptLanguage> language) { 1618 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex); 1619 lldb::ScriptLanguage script_language = 1620 language ? *language : GetScriptLanguage(); 1621 1622 if (!m_script_interpreters[script_language]) { 1623 if (!can_create) 1624 return nullptr; 1625 m_script_interpreters[script_language] = 1626 PluginManager::GetScriptInterpreterForLanguage(script_language, *this); 1627 } 1628 1629 return m_script_interpreters[script_language].get(); 1630 } 1631 1632 SourceManager &Debugger::GetSourceManager() { 1633 if (!m_source_manager_up) 1634 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this()); 1635 return *m_source_manager_up; 1636 } 1637 1638 // This function handles events that were broadcast by the process. 1639 void Debugger::HandleBreakpointEvent(const EventSP &event_sp) { 1640 using namespace lldb; 1641 const uint32_t event_type = 1642 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent( 1643 event_sp); 1644 1645 // if (event_type & eBreakpointEventTypeAdded 1646 // || event_type & eBreakpointEventTypeRemoved 1647 // || event_type & eBreakpointEventTypeEnabled 1648 // || event_type & eBreakpointEventTypeDisabled 1649 // || event_type & eBreakpointEventTypeCommandChanged 1650 // || event_type & eBreakpointEventTypeConditionChanged 1651 // || event_type & eBreakpointEventTypeIgnoreChanged 1652 // || event_type & eBreakpointEventTypeLocationsResolved) 1653 // { 1654 // // Don't do anything about these events, since the breakpoint 1655 // commands already echo these actions. 1656 // } 1657 // 1658 if (event_type & eBreakpointEventTypeLocationsAdded) { 1659 uint32_t num_new_locations = 1660 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent( 1661 event_sp); 1662 if (num_new_locations > 0) { 1663 BreakpointSP breakpoint = 1664 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp); 1665 StreamSP output_sp(GetAsyncOutputStream()); 1666 if (output_sp) { 1667 output_sp->Printf("%d location%s added to breakpoint %d\n", 1668 num_new_locations, num_new_locations == 1 ? "" : "s", 1669 breakpoint->GetID()); 1670 output_sp->Flush(); 1671 } 1672 } 1673 } 1674 // else if (event_type & eBreakpointEventTypeLocationsRemoved) 1675 // { 1676 // // These locations just get disabled, not sure it is worth spamming 1677 // folks about this on the command line. 1678 // } 1679 // else if (event_type & eBreakpointEventTypeLocationsResolved) 1680 // { 1681 // // This might be an interesting thing to note, but I'm going to 1682 // leave it quiet for now, it just looked noisy. 1683 // } 1684 } 1685 1686 void Debugger::FlushProcessOutput(Process &process, bool flush_stdout, 1687 bool flush_stderr) { 1688 const auto &flush = [&](Stream &stream, 1689 size_t (Process::*get)(char *, size_t, Status &)) { 1690 Status error; 1691 size_t len; 1692 char buffer[1024]; 1693 while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0) 1694 stream.Write(buffer, len); 1695 stream.Flush(); 1696 }; 1697 1698 std::lock_guard<std::mutex> guard(m_output_flush_mutex); 1699 if (flush_stdout) 1700 flush(*GetAsyncOutputStream(), &Process::GetSTDOUT); 1701 if (flush_stderr) 1702 flush(*GetAsyncErrorStream(), &Process::GetSTDERR); 1703 } 1704 1705 // This function handles events that were broadcast by the process. 1706 void Debugger::HandleProcessEvent(const EventSP &event_sp) { 1707 using namespace lldb; 1708 const uint32_t event_type = event_sp->GetType(); 1709 ProcessSP process_sp = 1710 (event_type == Process::eBroadcastBitStructuredData) 1711 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get()) 1712 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get()); 1713 1714 StreamSP output_stream_sp = GetAsyncOutputStream(); 1715 StreamSP error_stream_sp = GetAsyncErrorStream(); 1716 const bool gui_enabled = IsForwardingEvents(); 1717 1718 if (!gui_enabled) { 1719 bool pop_process_io_handler = false; 1720 assert(process_sp); 1721 1722 bool state_is_stopped = false; 1723 const bool got_state_changed = 1724 (event_type & Process::eBroadcastBitStateChanged) != 0; 1725 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0; 1726 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0; 1727 const bool got_structured_data = 1728 (event_type & Process::eBroadcastBitStructuredData) != 0; 1729 1730 if (got_state_changed) { 1731 StateType event_state = 1732 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 1733 state_is_stopped = StateIsStoppedState(event_state, false); 1734 } 1735 1736 // Display running state changes first before any STDIO 1737 if (got_state_changed && !state_is_stopped) { 1738 // This is a public stop which we are going to announce to the user, so 1739 // we should force the most relevant frame selection here. 1740 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(), 1741 SelectMostRelevantFrame, 1742 pop_process_io_handler); 1743 } 1744 1745 // Now display STDOUT and STDERR 1746 FlushProcessOutput(*process_sp, got_stdout || got_state_changed, 1747 got_stderr || got_state_changed); 1748 1749 // Give structured data events an opportunity to display. 1750 if (got_structured_data) { 1751 StructuredDataPluginSP plugin_sp = 1752 EventDataStructuredData::GetPluginFromEvent(event_sp.get()); 1753 if (plugin_sp) { 1754 auto structured_data_sp = 1755 EventDataStructuredData::GetObjectFromEvent(event_sp.get()); 1756 if (output_stream_sp) { 1757 StreamString content_stream; 1758 Status error = 1759 plugin_sp->GetDescription(structured_data_sp, content_stream); 1760 if (error.Success()) { 1761 if (!content_stream.GetString().empty()) { 1762 // Add newline. 1763 content_stream.PutChar('\n'); 1764 content_stream.Flush(); 1765 1766 // Print it. 1767 output_stream_sp->PutCString(content_stream.GetString()); 1768 } 1769 } else { 1770 error_stream_sp->Format("Failed to print structured " 1771 "data with plugin {0}: {1}", 1772 plugin_sp->GetPluginName(), error); 1773 } 1774 } 1775 } 1776 } 1777 1778 // Now display any stopped state changes after any STDIO 1779 if (got_state_changed && state_is_stopped) { 1780 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(), 1781 SelectMostRelevantFrame, 1782 pop_process_io_handler); 1783 } 1784 1785 output_stream_sp->Flush(); 1786 error_stream_sp->Flush(); 1787 1788 if (pop_process_io_handler) 1789 process_sp->PopProcessIOHandler(); 1790 } 1791 } 1792 1793 void Debugger::HandleThreadEvent(const EventSP &event_sp) { 1794 // At present the only thread event we handle is the Frame Changed event, and 1795 // all we do for that is just reprint the thread status for that thread. 1796 using namespace lldb; 1797 const uint32_t event_type = event_sp->GetType(); 1798 const bool stop_format = true; 1799 if (event_type == Thread::eBroadcastBitStackChanged || 1800 event_type == Thread::eBroadcastBitThreadSelected) { 1801 ThreadSP thread_sp( 1802 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get())); 1803 if (thread_sp) { 1804 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format); 1805 } 1806 } 1807 } 1808 1809 bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; } 1810 1811 void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) { 1812 m_forward_listener_sp = listener_sp; 1813 } 1814 1815 void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) { 1816 m_forward_listener_sp.reset(); 1817 } 1818 1819 lldb::thread_result_t Debugger::DefaultEventHandler() { 1820 ListenerSP listener_sp(GetListener()); 1821 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass()); 1822 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass()); 1823 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass()); 1824 BroadcastEventSpec target_event_spec(broadcaster_class_target, 1825 Target::eBroadcastBitBreakpointChanged); 1826 1827 BroadcastEventSpec process_event_spec( 1828 broadcaster_class_process, 1829 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT | 1830 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData); 1831 1832 BroadcastEventSpec thread_event_spec(broadcaster_class_thread, 1833 Thread::eBroadcastBitStackChanged | 1834 Thread::eBroadcastBitThreadSelected); 1835 1836 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp, 1837 target_event_spec); 1838 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp, 1839 process_event_spec); 1840 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp, 1841 thread_event_spec); 1842 listener_sp->StartListeningForEvents( 1843 m_command_interpreter_up.get(), 1844 CommandInterpreter::eBroadcastBitQuitCommandReceived | 1845 CommandInterpreter::eBroadcastBitAsynchronousOutputData | 1846 CommandInterpreter::eBroadcastBitAsynchronousErrorData); 1847 1848 listener_sp->StartListeningForEvents( 1849 &m_broadcaster, eBroadcastBitProgress | eBroadcastBitWarning | 1850 eBroadcastBitError | eBroadcastSymbolChange); 1851 1852 // Let the thread that spawned us know that we have started up and that we 1853 // are now listening to all required events so no events get missed 1854 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening); 1855 1856 bool done = false; 1857 while (!done) { 1858 EventSP event_sp; 1859 if (listener_sp->GetEvent(event_sp, std::nullopt)) { 1860 if (event_sp) { 1861 Broadcaster *broadcaster = event_sp->GetBroadcaster(); 1862 if (broadcaster) { 1863 uint32_t event_type = event_sp->GetType(); 1864 ConstString broadcaster_class(broadcaster->GetBroadcasterClass()); 1865 if (broadcaster_class == broadcaster_class_process) { 1866 HandleProcessEvent(event_sp); 1867 } else if (broadcaster_class == broadcaster_class_target) { 1868 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent( 1869 event_sp.get())) { 1870 HandleBreakpointEvent(event_sp); 1871 } 1872 } else if (broadcaster_class == broadcaster_class_thread) { 1873 HandleThreadEvent(event_sp); 1874 } else if (broadcaster == m_command_interpreter_up.get()) { 1875 if (event_type & 1876 CommandInterpreter::eBroadcastBitQuitCommandReceived) { 1877 done = true; 1878 } else if (event_type & 1879 CommandInterpreter::eBroadcastBitAsynchronousErrorData) { 1880 const char *data = static_cast<const char *>( 1881 EventDataBytes::GetBytesFromEvent(event_sp.get())); 1882 if (data && data[0]) { 1883 StreamSP error_sp(GetAsyncErrorStream()); 1884 if (error_sp) { 1885 error_sp->PutCString(data); 1886 error_sp->Flush(); 1887 } 1888 } 1889 } else if (event_type & CommandInterpreter:: 1890 eBroadcastBitAsynchronousOutputData) { 1891 const char *data = static_cast<const char *>( 1892 EventDataBytes::GetBytesFromEvent(event_sp.get())); 1893 if (data && data[0]) { 1894 StreamSP output_sp(GetAsyncOutputStream()); 1895 if (output_sp) { 1896 output_sp->PutCString(data); 1897 output_sp->Flush(); 1898 } 1899 } 1900 } 1901 } else if (broadcaster == &m_broadcaster) { 1902 if (event_type & Debugger::eBroadcastBitProgress) 1903 HandleProgressEvent(event_sp); 1904 else if (event_type & Debugger::eBroadcastBitWarning) 1905 HandleDiagnosticEvent(event_sp); 1906 else if (event_type & Debugger::eBroadcastBitError) 1907 HandleDiagnosticEvent(event_sp); 1908 } 1909 } 1910 1911 if (m_forward_listener_sp) 1912 m_forward_listener_sp->AddEvent(event_sp); 1913 } 1914 } 1915 } 1916 return {}; 1917 } 1918 1919 bool Debugger::StartEventHandlerThread() { 1920 if (!m_event_handler_thread.IsJoinable()) { 1921 // We must synchronize with the DefaultEventHandler() thread to ensure it 1922 // is up and running and listening to events before we return from this 1923 // function. We do this by listening to events for the 1924 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster 1925 ConstString full_name("lldb.debugger.event-handler"); 1926 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString())); 1927 listener_sp->StartListeningForEvents(&m_sync_broadcaster, 1928 eBroadcastBitEventThreadIsListening); 1929 1930 llvm::StringRef thread_name = 1931 full_name.GetLength() < llvm::get_max_thread_name_length() 1932 ? full_name.GetStringRef() 1933 : "dbg.evt-handler"; 1934 1935 // Use larger 8MB stack for this thread 1936 llvm::Expected<HostThread> event_handler_thread = 1937 ThreadLauncher::LaunchThread( 1938 thread_name, [this] { return DefaultEventHandler(); }, 1939 g_debugger_event_thread_stack_bytes); 1940 1941 if (event_handler_thread) { 1942 m_event_handler_thread = *event_handler_thread; 1943 } else { 1944 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), event_handler_thread.takeError(), 1945 "failed to launch host thread: {0}"); 1946 } 1947 1948 // Make sure DefaultEventHandler() is running and listening to events 1949 // before we return from this function. We are only listening for events of 1950 // type eBroadcastBitEventThreadIsListening so we don't need to check the 1951 // event, we just need to wait an infinite amount of time for it (nullptr 1952 // timeout as the first parameter) 1953 lldb::EventSP event_sp; 1954 listener_sp->GetEvent(event_sp, std::nullopt); 1955 } 1956 return m_event_handler_thread.IsJoinable(); 1957 } 1958 1959 void Debugger::StopEventHandlerThread() { 1960 if (m_event_handler_thread.IsJoinable()) { 1961 GetCommandInterpreter().BroadcastEvent( 1962 CommandInterpreter::eBroadcastBitQuitCommandReceived); 1963 m_event_handler_thread.Join(nullptr); 1964 } 1965 } 1966 1967 lldb::thread_result_t Debugger::IOHandlerThread() { 1968 RunIOHandlers(); 1969 StopEventHandlerThread(); 1970 return {}; 1971 } 1972 1973 void Debugger::HandleProgressEvent(const lldb::EventSP &event_sp) { 1974 auto *data = ProgressEventData::GetEventDataFromEvent(event_sp.get()); 1975 if (!data) 1976 return; 1977 1978 // Do some bookkeeping for the current event, regardless of whether we're 1979 // going to show the progress. 1980 const uint64_t id = data->GetID(); 1981 if (m_current_event_id) { 1982 Log *log = GetLog(LLDBLog::Events); 1983 if (log && log->GetVerbose()) { 1984 StreamString log_stream; 1985 log_stream.AsRawOstream() 1986 << static_cast<void *>(this) << " Debugger(" << GetID() 1987 << ")::HandleProgressEvent( m_current_event_id = " 1988 << *m_current_event_id << ", data = { "; 1989 data->Dump(&log_stream); 1990 log_stream << " } )"; 1991 log->PutString(log_stream.GetString()); 1992 } 1993 if (id != *m_current_event_id) 1994 return; 1995 if (data->GetCompleted() == data->GetTotal()) 1996 m_current_event_id.reset(); 1997 } else { 1998 m_current_event_id = id; 1999 } 2000 2001 // Decide whether we actually are going to show the progress. This decision 2002 // can change between iterations so check it inside the loop. 2003 if (!GetShowProgress()) 2004 return; 2005 2006 // Determine whether the current output file is an interactive terminal with 2007 // color support. We assume that if we support ANSI escape codes we support 2008 // vt100 escape codes. 2009 File &file = GetOutputFile(); 2010 if (!file.GetIsInteractive() || !file.GetIsTerminalWithColors()) 2011 return; 2012 2013 StreamSP output = GetAsyncOutputStream(); 2014 2015 // Print over previous line, if any. 2016 output->Printf("\r"); 2017 2018 if (data->GetCompleted() == data->GetTotal()) { 2019 // Clear the current line. 2020 output->Printf("\x1B[2K"); 2021 output->Flush(); 2022 return; 2023 } 2024 2025 // Trim the progress message if it exceeds the window's width and print it. 2026 std::string message = data->GetMessage(); 2027 if (data->IsFinite()) 2028 message = llvm::formatv("[{0}/{1}] {2}", data->GetCompleted(), 2029 data->GetTotal(), message) 2030 .str(); 2031 2032 // Trim the progress message if it exceeds the window's width and print it. 2033 const uint32_t term_width = GetTerminalWidth(); 2034 const uint32_t ellipsis = 3; 2035 if (message.size() + ellipsis >= term_width) 2036 message = message.substr(0, term_width - ellipsis); 2037 2038 const bool use_color = GetUseColor(); 2039 llvm::StringRef ansi_prefix = GetShowProgressAnsiPrefix(); 2040 if (!ansi_prefix.empty()) 2041 output->Printf( 2042 "%s", ansi::FormatAnsiTerminalCodes(ansi_prefix, use_color).c_str()); 2043 2044 output->Printf("%s...", message.c_str()); 2045 2046 llvm::StringRef ansi_suffix = GetShowProgressAnsiSuffix(); 2047 if (!ansi_suffix.empty()) 2048 output->Printf( 2049 "%s", ansi::FormatAnsiTerminalCodes(ansi_suffix, use_color).c_str()); 2050 2051 // Clear until the end of the line. 2052 output->Printf("\x1B[K\r"); 2053 2054 // Flush the output. 2055 output->Flush(); 2056 } 2057 2058 void Debugger::HandleDiagnosticEvent(const lldb::EventSP &event_sp) { 2059 auto *data = DiagnosticEventData::GetEventDataFromEvent(event_sp.get()); 2060 if (!data) 2061 return; 2062 2063 StreamSP stream = GetAsyncErrorStream(); 2064 data->Dump(stream.get()); 2065 } 2066 2067 bool Debugger::HasIOHandlerThread() const { 2068 return m_io_handler_thread.IsJoinable(); 2069 } 2070 2071 HostThread Debugger::SetIOHandlerThread(HostThread &new_thread) { 2072 HostThread old_host = m_io_handler_thread; 2073 m_io_handler_thread = new_thread; 2074 return old_host; 2075 } 2076 2077 bool Debugger::StartIOHandlerThread() { 2078 if (!m_io_handler_thread.IsJoinable()) { 2079 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread( 2080 "lldb.debugger.io-handler", [this] { return IOHandlerThread(); }, 2081 8 * 1024 * 1024); // Use larger 8MB stack for this thread 2082 if (io_handler_thread) { 2083 m_io_handler_thread = *io_handler_thread; 2084 } else { 2085 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), io_handler_thread.takeError(), 2086 "failed to launch host thread: {0}"); 2087 } 2088 } 2089 return m_io_handler_thread.IsJoinable(); 2090 } 2091 2092 void Debugger::StopIOHandlerThread() { 2093 if (m_io_handler_thread.IsJoinable()) { 2094 GetInputFile().Close(); 2095 m_io_handler_thread.Join(nullptr); 2096 } 2097 } 2098 2099 void Debugger::JoinIOHandlerThread() { 2100 if (HasIOHandlerThread()) { 2101 thread_result_t result; 2102 m_io_handler_thread.Join(&result); 2103 m_io_handler_thread = LLDB_INVALID_HOST_THREAD; 2104 } 2105 } 2106 2107 bool Debugger::IsIOHandlerThreadCurrentThread() const { 2108 if (!HasIOHandlerThread()) 2109 return false; 2110 return m_io_handler_thread.EqualsThread(Host::GetCurrentThread()); 2111 } 2112 2113 Target &Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) { 2114 if (!prefer_dummy) { 2115 if (TargetSP target = m_target_list.GetSelectedTarget()) 2116 return *target; 2117 } 2118 return GetDummyTarget(); 2119 } 2120 2121 Status Debugger::RunREPL(LanguageType language, const char *repl_options) { 2122 Status err; 2123 FileSpec repl_executable; 2124 2125 if (language == eLanguageTypeUnknown) 2126 language = GetREPLLanguage(); 2127 2128 if (language == eLanguageTypeUnknown) { 2129 LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs(); 2130 2131 if (auto single_lang = repl_languages.GetSingularLanguage()) { 2132 language = *single_lang; 2133 } else if (repl_languages.Empty()) { 2134 err.SetErrorString( 2135 "LLDB isn't configured with REPL support for any languages."); 2136 return err; 2137 } else { 2138 err.SetErrorString( 2139 "Multiple possible REPL languages. Please specify a language."); 2140 return err; 2141 } 2142 } 2143 2144 Target *const target = 2145 nullptr; // passing in an empty target means the REPL must create one 2146 2147 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options)); 2148 2149 if (!err.Success()) { 2150 return err; 2151 } 2152 2153 if (!repl_sp) { 2154 err.SetErrorStringWithFormat("couldn't find a REPL for %s", 2155 Language::GetNameForLanguageType(language)); 2156 return err; 2157 } 2158 2159 repl_sp->SetCompilerOptions(repl_options); 2160 repl_sp->RunLoop(); 2161 2162 return err; 2163 } 2164 2165 llvm::ThreadPool &Debugger::GetThreadPool() { 2166 assert(g_thread_pool && 2167 "Debugger::GetThreadPool called before Debugger::Initialize"); 2168 return *g_thread_pool; 2169 } 2170