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