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