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/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->GetOutputStream() << result.GetOutputData() << '\n'; 673 else 674 debugger_sp->GetErrorStream() << 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_log_callback_stream_sp = 761 std::make_shared<StreamCallback>(log_callback, baton); 762 m_command_interpreter_up->Initialize(); 763 // Always add our default platform to the platform list 764 PlatformSP default_platform_sp(Platform::GetHostPlatform()); 765 assert(default_platform_sp); 766 m_platform_list.Append(default_platform_sp, true); 767 768 // Create the dummy target. 769 { 770 ArchSpec arch(Target::GetDefaultArchitecture()); 771 if (!arch.IsValid()) 772 arch = HostInfo::GetArchitecture(); 773 assert(arch.IsValid() && "No valid default or host archspec"); 774 const bool is_dummy_target = true; 775 m_dummy_target_sp.reset( 776 new Target(*this, arch, default_platform_sp, is_dummy_target)); 777 } 778 assert(m_dummy_target_sp.get() && "Couldn't construct dummy target?"); 779 780 m_collection_sp->Initialize(g_debugger_properties); 781 m_collection_sp->AppendProperty( 782 ConstString("target"), 783 ConstString("Settings specify to debugging targets."), true, 784 Target::GetGlobalProperties().GetValueProperties()); 785 m_collection_sp->AppendProperty( 786 ConstString("platform"), ConstString("Platform settings."), true, 787 Platform::GetGlobalPlatformProperties().GetValueProperties()); 788 m_collection_sp->AppendProperty( 789 ConstString("symbols"), ConstString("Symbol lookup and cache settings."), 790 true, ModuleList::GetGlobalModuleListProperties().GetValueProperties()); 791 if (m_command_interpreter_up) { 792 m_collection_sp->AppendProperty( 793 ConstString("interpreter"), 794 ConstString("Settings specify to the debugger's command interpreter."), 795 true, m_command_interpreter_up->GetValueProperties()); 796 } 797 OptionValueSInt64 *term_width = 798 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64( 799 nullptr, ePropertyTerminalWidth); 800 term_width->SetMinimumValue(10); 801 term_width->SetMaximumValue(1024); 802 803 // Turn off use-color if this is a dumb terminal. 804 const char *term = getenv("TERM"); 805 if (term && !strcmp(term, "dumb")) 806 SetUseColor(false); 807 // Turn off use-color if we don't write to a terminal with color support. 808 if (!GetOutputFile().GetIsTerminalWithColors()) 809 SetUseColor(false); 810 811 #if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING) 812 // Enabling use of ANSI color codes because LLDB is using them to highlight 813 // text. 814 llvm::sys::Process::UseANSIEscapeCodes(true); 815 #endif 816 } 817 818 Debugger::~Debugger() { Clear(); } 819 820 void Debugger::Clear() { 821 // Make sure we call this function only once. With the C++ global destructor 822 // chain having a list of debuggers and with code that can be running on 823 // other threads, we need to ensure this doesn't happen multiple times. 824 // 825 // The following functions call Debugger::Clear(): 826 // Debugger::~Debugger(); 827 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp); 828 // static void Debugger::Terminate(); 829 llvm::call_once(m_clear_once, [this]() { 830 ClearIOHandlers(); 831 StopIOHandlerThread(); 832 StopEventHandlerThread(); 833 m_listener_sp->Clear(); 834 for (TargetSP target_sp : m_target_list.Targets()) { 835 if (target_sp) { 836 if (ProcessSP process_sp = target_sp->GetProcessSP()) 837 process_sp->Finalize(); 838 target_sp->Destroy(); 839 } 840 } 841 m_broadcaster_manager_sp->Clear(); 842 843 // Close the input file _before_ we close the input read communications 844 // class as it does NOT own the input file, our m_input_file does. 845 m_terminal_state.Clear(); 846 GetInputFile().Close(); 847 848 m_command_interpreter_up->Clear(); 849 }); 850 } 851 852 bool Debugger::GetCloseInputOnEOF() const { 853 // return m_input_comm.GetCloseOnEOF(); 854 return false; 855 } 856 857 void Debugger::SetCloseInputOnEOF(bool b) { 858 // m_input_comm.SetCloseOnEOF(b); 859 } 860 861 bool Debugger::GetAsyncExecution() { 862 return !m_command_interpreter_up->GetSynchronous(); 863 } 864 865 void Debugger::SetAsyncExecution(bool async_execution) { 866 m_command_interpreter_up->SetSynchronous(!async_execution); 867 } 868 869 repro::DataRecorder *Debugger::GetInputRecorder() { return m_input_recorder; } 870 871 static inline int OpenPipe(int fds[2], std::size_t size) { 872 #ifdef _WIN32 873 return _pipe(fds, size, O_BINARY); 874 #else 875 (void)size; 876 return pipe(fds); 877 #endif 878 } 879 880 Status Debugger::SetInputString(const char *data) { 881 Status result; 882 enum PIPES { READ, WRITE }; // Indexes for the read and write fds 883 int fds[2] = {-1, -1}; 884 885 if (data == nullptr) { 886 result.SetErrorString("String data is null"); 887 return result; 888 } 889 890 size_t size = strlen(data); 891 if (size == 0) { 892 result.SetErrorString("String data is empty"); 893 return result; 894 } 895 896 if (OpenPipe(fds, size) != 0) { 897 result.SetErrorString( 898 "can't create pipe file descriptors for LLDB commands"); 899 return result; 900 } 901 902 int r = write(fds[WRITE], data, size); 903 (void)r; 904 // Close the write end of the pipe, so that the command interpreter will exit 905 // when it consumes all the data. 906 llvm::sys::Process::SafelyCloseFileDescriptor(fds[WRITE]); 907 908 // Open the read file descriptor as a FILE * that we can return as an input 909 // handle. 910 FILE *commands_file = fdopen(fds[READ], "rb"); 911 if (commands_file == nullptr) { 912 result.SetErrorStringWithFormat("fdopen(%i, \"rb\") failed (errno = %i) " 913 "when trying to open LLDB commands pipe", 914 fds[READ], errno); 915 llvm::sys::Process::SafelyCloseFileDescriptor(fds[READ]); 916 return result; 917 } 918 919 return SetInputFile( 920 (FileSP)std::make_shared<NativeFile>(commands_file, true)); 921 } 922 923 Status Debugger::SetInputFile(FileSP file_sp) { 924 Status error; 925 repro::DataRecorder *recorder = nullptr; 926 if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) 927 recorder = g->GetOrCreate<repro::CommandProvider>().GetNewRecorder(); 928 929 static std::unique_ptr<repro::MultiLoader<repro::CommandProvider>> loader = 930 repro::MultiLoader<repro::CommandProvider>::Create( 931 repro::Reproducer::Instance().GetLoader()); 932 if (loader) { 933 llvm::Optional<std::string> nextfile = loader->GetNextFile(); 934 FILE *fh = nextfile ? FileSystem::Instance().Fopen(nextfile->c_str(), "r") 935 : nullptr; 936 // FIXME Jonas Devlieghere: shouldn't this error be propagated out to the 937 // reproducer somehow if fh is NULL? 938 if (fh) { 939 file_sp = std::make_shared<NativeFile>(fh, true); 940 } 941 } 942 943 if (!file_sp || !file_sp->IsValid()) { 944 error.SetErrorString("invalid file"); 945 return error; 946 } 947 948 SetInputFile(file_sp, recorder); 949 return error; 950 } 951 952 void Debugger::SetInputFile(FileSP file_sp, repro::DataRecorder *recorder) { 953 assert(file_sp && file_sp->IsValid()); 954 m_input_recorder = recorder; 955 m_input_file_sp = std::move(file_sp); 956 // Save away the terminal state if that is relevant, so that we can restore 957 // it in RestoreInputState. 958 SaveInputTerminalState(); 959 } 960 961 void Debugger::SetOutputFile(FileSP file_sp) { 962 assert(file_sp && file_sp->IsValid()); 963 m_output_stream_sp = std::make_shared<StreamFile>(file_sp); 964 } 965 966 void Debugger::SetErrorFile(FileSP file_sp) { 967 assert(file_sp && file_sp->IsValid()); 968 m_error_stream_sp = std::make_shared<StreamFile>(file_sp); 969 } 970 971 void Debugger::SaveInputTerminalState() { 972 int fd = GetInputFile().GetDescriptor(); 973 if (fd != File::kInvalidDescriptor) 974 m_terminal_state.Save(fd, true); 975 } 976 977 void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); } 978 979 ExecutionContext Debugger::GetSelectedExecutionContext() { 980 bool adopt_selected = true; 981 ExecutionContextRef exe_ctx_ref(GetSelectedTarget().get(), adopt_selected); 982 return ExecutionContext(exe_ctx_ref); 983 } 984 985 void Debugger::DispatchInputInterrupt() { 986 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 987 IOHandlerSP reader_sp(m_io_handler_stack.Top()); 988 if (reader_sp) 989 reader_sp->Interrupt(); 990 } 991 992 void Debugger::DispatchInputEndOfFile() { 993 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 994 IOHandlerSP reader_sp(m_io_handler_stack.Top()); 995 if (reader_sp) 996 reader_sp->GotEOF(); 997 } 998 999 void Debugger::ClearIOHandlers() { 1000 // The bottom input reader should be the main debugger input reader. We do 1001 // not want to close that one here. 1002 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 1003 while (m_io_handler_stack.GetSize() > 1) { 1004 IOHandlerSP reader_sp(m_io_handler_stack.Top()); 1005 if (reader_sp) 1006 PopIOHandler(reader_sp); 1007 } 1008 } 1009 1010 void Debugger::RunIOHandlers() { 1011 IOHandlerSP reader_sp = m_io_handler_stack.Top(); 1012 while (true) { 1013 if (!reader_sp) 1014 break; 1015 1016 reader_sp->Run(); 1017 { 1018 std::lock_guard<std::recursive_mutex> guard( 1019 m_io_handler_synchronous_mutex); 1020 1021 // Remove all input readers that are done from the top of the stack 1022 while (true) { 1023 IOHandlerSP top_reader_sp = m_io_handler_stack.Top(); 1024 if (top_reader_sp && top_reader_sp->GetIsDone()) 1025 PopIOHandler(top_reader_sp); 1026 else 1027 break; 1028 } 1029 reader_sp = m_io_handler_stack.Top(); 1030 } 1031 } 1032 ClearIOHandlers(); 1033 } 1034 1035 void Debugger::RunIOHandlerSync(const IOHandlerSP &reader_sp) { 1036 std::lock_guard<std::recursive_mutex> guard(m_io_handler_synchronous_mutex); 1037 1038 PushIOHandler(reader_sp); 1039 IOHandlerSP top_reader_sp = reader_sp; 1040 1041 while (top_reader_sp) { 1042 if (!top_reader_sp) 1043 break; 1044 1045 top_reader_sp->Run(); 1046 1047 // Don't unwind past the starting point. 1048 if (top_reader_sp.get() == reader_sp.get()) { 1049 if (PopIOHandler(reader_sp)) 1050 break; 1051 } 1052 1053 // If we pushed new IO handlers, pop them if they're done or restart the 1054 // loop to run them if they're not. 1055 while (true) { 1056 top_reader_sp = m_io_handler_stack.Top(); 1057 if (top_reader_sp && top_reader_sp->GetIsDone()) { 1058 PopIOHandler(top_reader_sp); 1059 // Don't unwind past the starting point. 1060 if (top_reader_sp.get() == reader_sp.get()) 1061 return; 1062 } else { 1063 break; 1064 } 1065 } 1066 } 1067 } 1068 1069 bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) { 1070 return m_io_handler_stack.IsTop(reader_sp); 1071 } 1072 1073 bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type, 1074 IOHandler::Type second_top_type) { 1075 return m_io_handler_stack.CheckTopIOHandlerTypes(top_type, second_top_type); 1076 } 1077 1078 void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) { 1079 bool printed = m_io_handler_stack.PrintAsync(s, len, is_stdout); 1080 if (!printed) { 1081 lldb::StreamFileSP stream = 1082 is_stdout ? m_output_stream_sp : m_error_stream_sp; 1083 stream->Write(s, len); 1084 } 1085 } 1086 1087 ConstString Debugger::GetTopIOHandlerControlSequence(char ch) { 1088 return m_io_handler_stack.GetTopIOHandlerControlSequence(ch); 1089 } 1090 1091 const char *Debugger::GetIOHandlerCommandPrefix() { 1092 return m_io_handler_stack.GetTopIOHandlerCommandPrefix(); 1093 } 1094 1095 const char *Debugger::GetIOHandlerHelpPrologue() { 1096 return m_io_handler_stack.GetTopIOHandlerHelpPrologue(); 1097 } 1098 1099 bool Debugger::RemoveIOHandler(const IOHandlerSP &reader_sp) { 1100 return PopIOHandler(reader_sp); 1101 } 1102 1103 void Debugger::RunIOHandlerAsync(const IOHandlerSP &reader_sp, 1104 bool cancel_top_handler) { 1105 PushIOHandler(reader_sp, cancel_top_handler); 1106 } 1107 1108 void Debugger::AdoptTopIOHandlerFilesIfInvalid(FileSP &in, StreamFileSP &out, 1109 StreamFileSP &err) { 1110 // Before an IOHandler runs, it must have in/out/err streams. This function 1111 // is called when one ore more of the streams are nullptr. We use the top 1112 // input reader's in/out/err streams, or fall back to the debugger file 1113 // handles, or we fall back onto stdin/stdout/stderr as a last resort. 1114 1115 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 1116 IOHandlerSP top_reader_sp(m_io_handler_stack.Top()); 1117 // If no STDIN has been set, then set it appropriately 1118 if (!in || !in->IsValid()) { 1119 if (top_reader_sp) 1120 in = top_reader_sp->GetInputFileSP(); 1121 else 1122 in = GetInputFileSP(); 1123 // If there is nothing, use stdin 1124 if (!in) 1125 in = std::make_shared<NativeFile>(stdin, false); 1126 } 1127 // If no STDOUT has been set, then set it appropriately 1128 if (!out || !out->GetFile().IsValid()) { 1129 if (top_reader_sp) 1130 out = top_reader_sp->GetOutputStreamFileSP(); 1131 else 1132 out = GetOutputStreamSP(); 1133 // If there is nothing, use stdout 1134 if (!out) 1135 out = std::make_shared<StreamFile>(stdout, false); 1136 } 1137 // If no STDERR has been set, then set it appropriately 1138 if (!err || !err->GetFile().IsValid()) { 1139 if (top_reader_sp) 1140 err = top_reader_sp->GetErrorStreamFileSP(); 1141 else 1142 err = GetErrorStreamSP(); 1143 // If there is nothing, use stderr 1144 if (!err) 1145 err = std::make_shared<StreamFile>(stderr, false); 1146 } 1147 } 1148 1149 void Debugger::PushIOHandler(const IOHandlerSP &reader_sp, 1150 bool cancel_top_handler) { 1151 if (!reader_sp) 1152 return; 1153 1154 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 1155 1156 // Get the current top input reader... 1157 IOHandlerSP top_reader_sp(m_io_handler_stack.Top()); 1158 1159 // Don't push the same IO handler twice... 1160 if (reader_sp == top_reader_sp) 1161 return; 1162 1163 // Push our new input reader 1164 m_io_handler_stack.Push(reader_sp); 1165 reader_sp->Activate(); 1166 1167 // Interrupt the top input reader to it will exit its Run() function and let 1168 // this new input reader take over 1169 if (top_reader_sp) { 1170 top_reader_sp->Deactivate(); 1171 if (cancel_top_handler) 1172 top_reader_sp->Cancel(); 1173 } 1174 } 1175 1176 bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) { 1177 if (!pop_reader_sp) 1178 return false; 1179 1180 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 1181 1182 // The reader on the stop of the stack is done, so let the next read on the 1183 // stack refresh its prompt and if there is one... 1184 if (m_io_handler_stack.IsEmpty()) 1185 return false; 1186 1187 IOHandlerSP reader_sp(m_io_handler_stack.Top()); 1188 1189 if (pop_reader_sp != reader_sp) 1190 return false; 1191 1192 reader_sp->Deactivate(); 1193 reader_sp->Cancel(); 1194 m_io_handler_stack.Pop(); 1195 1196 reader_sp = m_io_handler_stack.Top(); 1197 if (reader_sp) 1198 reader_sp->Activate(); 1199 1200 return true; 1201 } 1202 1203 StreamSP Debugger::GetAsyncOutputStream() { 1204 return std::make_shared<StreamAsynchronousIO>(*this, true, GetUseColor()); 1205 } 1206 1207 StreamSP Debugger::GetAsyncErrorStream() { 1208 return std::make_shared<StreamAsynchronousIO>(*this, false, GetUseColor()); 1209 } 1210 1211 size_t Debugger::GetNumDebuggers() { 1212 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1213 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1214 return g_debugger_list_ptr->size(); 1215 } 1216 return 0; 1217 } 1218 1219 lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) { 1220 DebuggerSP debugger_sp; 1221 1222 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1223 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1224 if (index < g_debugger_list_ptr->size()) 1225 debugger_sp = g_debugger_list_ptr->at(index); 1226 } 1227 1228 return debugger_sp; 1229 } 1230 1231 DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) { 1232 DebuggerSP debugger_sp; 1233 1234 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1235 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1236 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 1237 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) { 1238 if ((*pos)->GetID() == id) { 1239 debugger_sp = *pos; 1240 break; 1241 } 1242 } 1243 } 1244 return debugger_sp; 1245 } 1246 1247 bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format, 1248 const SymbolContext *sc, 1249 const SymbolContext *prev_sc, 1250 const ExecutionContext *exe_ctx, 1251 const Address *addr, Stream &s) { 1252 FormatEntity::Entry format_entry; 1253 1254 if (format == nullptr) { 1255 if (exe_ctx != nullptr && exe_ctx->HasTargetScope()) 1256 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat(); 1257 if (format == nullptr) { 1258 FormatEntity::Parse("${addr}: ", format_entry); 1259 format = &format_entry; 1260 } 1261 } 1262 bool function_changed = false; 1263 bool initial_function = false; 1264 if (prev_sc && (prev_sc->function || prev_sc->symbol)) { 1265 if (sc && (sc->function || sc->symbol)) { 1266 if (prev_sc->symbol && sc->symbol) { 1267 if (!sc->symbol->Compare(prev_sc->symbol->GetName(), 1268 prev_sc->symbol->GetType())) { 1269 function_changed = true; 1270 } 1271 } else if (prev_sc->function && sc->function) { 1272 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) { 1273 function_changed = true; 1274 } 1275 } 1276 } 1277 } 1278 // The first context on a list of instructions will have a prev_sc that has 1279 // no Function or Symbol -- if SymbolContext had an IsValid() method, it 1280 // would return false. But we do get a prev_sc pointer. 1281 if ((sc && (sc->function || sc->symbol)) && prev_sc && 1282 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) { 1283 initial_function = true; 1284 } 1285 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr, 1286 function_changed, initial_function); 1287 } 1288 1289 void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback, 1290 void *baton) { 1291 // For simplicity's sake, I am not going to deal with how to close down any 1292 // open logging streams, I just redirect everything from here on out to the 1293 // callback. 1294 m_log_callback_stream_sp = 1295 std::make_shared<StreamCallback>(log_callback, baton); 1296 } 1297 1298 static void PrivateReportProgress(Debugger &debugger, uint64_t progress_id, 1299 const std::string &message, 1300 uint64_t completed, uint64_t total, 1301 bool is_debugger_specific) { 1302 // Only deliver progress events if we have any progress listeners. 1303 const uint32_t event_type = Debugger::eBroadcastBitProgress; 1304 if (!debugger.GetBroadcaster().EventTypeHasListeners(event_type)) 1305 return; 1306 EventSP event_sp(new Event( 1307 event_type, new ProgressEventData(progress_id, message, completed, total, 1308 is_debugger_specific))); 1309 debugger.GetBroadcaster().BroadcastEvent(event_sp); 1310 } 1311 1312 void Debugger::ReportProgress(uint64_t progress_id, const std::string &message, 1313 uint64_t completed, uint64_t total, 1314 llvm::Optional<lldb::user_id_t> debugger_id) { 1315 // Check if this progress is for a specific debugger. 1316 if (debugger_id.hasValue()) { 1317 // It is debugger specific, grab it and deliver the event if the debugger 1318 // still exists. 1319 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id); 1320 if (debugger_sp) 1321 PrivateReportProgress(*debugger_sp, progress_id, message, completed, 1322 total, /*is_debugger_specific*/ true); 1323 return; 1324 } 1325 // The progress event is not debugger specific, iterate over all debuggers 1326 // and deliver a progress event to each one. 1327 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1328 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1329 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 1330 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) 1331 PrivateReportProgress(*(*pos), progress_id, message, completed, total, 1332 /*is_debugger_specific*/ false); 1333 } 1334 } 1335 1336 static void PrivateReportDiagnostic(Debugger &debugger, 1337 DiagnosticEventData::Type type, 1338 std::string message, 1339 bool debugger_specific) { 1340 uint32_t event_type = 0; 1341 switch (type) { 1342 case DiagnosticEventData::Type::Warning: 1343 event_type = Debugger::eBroadcastBitWarning; 1344 break; 1345 case DiagnosticEventData::Type::Error: 1346 event_type = Debugger::eBroadcastBitError; 1347 break; 1348 } 1349 1350 Broadcaster &broadcaster = debugger.GetBroadcaster(); 1351 if (!broadcaster.EventTypeHasListeners(event_type)) { 1352 // Diagnostics are too important to drop. If nobody is listening, print the 1353 // diagnostic directly to the debugger's error stream. 1354 DiagnosticEventData event_data(type, std::move(message), debugger_specific); 1355 StreamSP stream = debugger.GetAsyncErrorStream(); 1356 event_data.Dump(stream.get()); 1357 return; 1358 } 1359 EventSP event_sp = std::make_shared<Event>( 1360 event_type, 1361 new DiagnosticEventData(type, std::move(message), debugger_specific)); 1362 broadcaster.BroadcastEvent(event_sp); 1363 } 1364 1365 void Debugger::ReportDiagnosticImpl(DiagnosticEventData::Type type, 1366 std::string message, 1367 llvm::Optional<lldb::user_id_t> debugger_id, 1368 std::once_flag *once) { 1369 auto ReportDiagnosticLambda = [&]() { 1370 // Check if this progress is for a specific debugger. 1371 if (debugger_id) { 1372 // It is debugger specific, grab it and deliver the event if the debugger 1373 // still exists. 1374 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id); 1375 if (debugger_sp) 1376 PrivateReportDiagnostic(*debugger_sp, type, std::move(message), true); 1377 return; 1378 } 1379 // The progress event is not debugger specific, iterate over all debuggers 1380 // and deliver a progress event to each one. 1381 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1382 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1383 for (const auto &debugger : *g_debugger_list_ptr) 1384 PrivateReportDiagnostic(*debugger, type, message, false); 1385 } 1386 }; 1387 1388 if (once) 1389 std::call_once(*once, ReportDiagnosticLambda); 1390 else 1391 ReportDiagnosticLambda(); 1392 } 1393 1394 void Debugger::ReportWarning(std::string message, 1395 llvm::Optional<lldb::user_id_t> debugger_id, 1396 std::once_flag *once) { 1397 ReportDiagnosticImpl(DiagnosticEventData::Type::Warning, std::move(message), 1398 debugger_id, once); 1399 } 1400 1401 void Debugger::ReportError(std::string message, 1402 llvm::Optional<lldb::user_id_t> debugger_id, 1403 std::once_flag *once) { 1404 1405 ReportDiagnosticImpl(DiagnosticEventData::Type::Error, std::move(message), 1406 debugger_id, once); 1407 } 1408 1409 bool Debugger::EnableLog(llvm::StringRef channel, 1410 llvm::ArrayRef<const char *> categories, 1411 llvm::StringRef log_file, uint32_t log_options, 1412 llvm::raw_ostream &error_stream) { 1413 const bool should_close = true; 1414 const bool unbuffered = true; 1415 1416 std::shared_ptr<llvm::raw_ostream> log_stream_sp; 1417 if (m_log_callback_stream_sp) { 1418 log_stream_sp = m_log_callback_stream_sp; 1419 // For now when using the callback mode you always get thread & timestamp. 1420 log_options |= 1421 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME; 1422 } else if (log_file.empty()) { 1423 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>( 1424 GetOutputFile().GetDescriptor(), !should_close, unbuffered); 1425 } else { 1426 auto pos = m_log_streams.find(log_file); 1427 if (pos != m_log_streams.end()) 1428 log_stream_sp = pos->second.lock(); 1429 if (!log_stream_sp) { 1430 File::OpenOptions flags = 1431 File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate; 1432 if (log_options & LLDB_LOG_OPTION_APPEND) 1433 flags |= File::eOpenOptionAppend; 1434 else 1435 flags |= File::eOpenOptionTruncate; 1436 llvm::Expected<FileUP> file = FileSystem::Instance().Open( 1437 FileSpec(log_file), flags, lldb::eFilePermissionsFileDefault, false); 1438 if (!file) { 1439 error_stream << "Unable to open log file '" << log_file 1440 << "': " << llvm::toString(file.takeError()) << "\n"; 1441 return false; 1442 } 1443 1444 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>( 1445 (*file)->GetDescriptor(), should_close, unbuffered); 1446 m_log_streams[log_file] = log_stream_sp; 1447 } 1448 } 1449 assert(log_stream_sp); 1450 1451 if (log_options == 0) 1452 log_options = 1453 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE; 1454 1455 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories, 1456 error_stream); 1457 } 1458 1459 ScriptInterpreter * 1460 Debugger::GetScriptInterpreter(bool can_create, 1461 llvm::Optional<lldb::ScriptLanguage> language) { 1462 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex); 1463 lldb::ScriptLanguage script_language = 1464 language ? *language : GetScriptLanguage(); 1465 1466 if (!m_script_interpreters[script_language]) { 1467 if (!can_create) 1468 return nullptr; 1469 m_script_interpreters[script_language] = 1470 PluginManager::GetScriptInterpreterForLanguage(script_language, *this); 1471 } 1472 1473 return m_script_interpreters[script_language].get(); 1474 } 1475 1476 SourceManager &Debugger::GetSourceManager() { 1477 if (!m_source_manager_up) 1478 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this()); 1479 return *m_source_manager_up; 1480 } 1481 1482 // This function handles events that were broadcast by the process. 1483 void Debugger::HandleBreakpointEvent(const EventSP &event_sp) { 1484 using namespace lldb; 1485 const uint32_t event_type = 1486 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent( 1487 event_sp); 1488 1489 // if (event_type & eBreakpointEventTypeAdded 1490 // || event_type & eBreakpointEventTypeRemoved 1491 // || event_type & eBreakpointEventTypeEnabled 1492 // || event_type & eBreakpointEventTypeDisabled 1493 // || event_type & eBreakpointEventTypeCommandChanged 1494 // || event_type & eBreakpointEventTypeConditionChanged 1495 // || event_type & eBreakpointEventTypeIgnoreChanged 1496 // || event_type & eBreakpointEventTypeLocationsResolved) 1497 // { 1498 // // Don't do anything about these events, since the breakpoint 1499 // commands already echo these actions. 1500 // } 1501 // 1502 if (event_type & eBreakpointEventTypeLocationsAdded) { 1503 uint32_t num_new_locations = 1504 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent( 1505 event_sp); 1506 if (num_new_locations > 0) { 1507 BreakpointSP breakpoint = 1508 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp); 1509 StreamSP output_sp(GetAsyncOutputStream()); 1510 if (output_sp) { 1511 output_sp->Printf("%d location%s added to breakpoint %d\n", 1512 num_new_locations, num_new_locations == 1 ? "" : "s", 1513 breakpoint->GetID()); 1514 output_sp->Flush(); 1515 } 1516 } 1517 } 1518 // else if (event_type & eBreakpointEventTypeLocationsRemoved) 1519 // { 1520 // // These locations just get disabled, not sure it is worth spamming 1521 // folks about this on the command line. 1522 // } 1523 // else if (event_type & eBreakpointEventTypeLocationsResolved) 1524 // { 1525 // // This might be an interesting thing to note, but I'm going to 1526 // leave it quiet for now, it just looked noisy. 1527 // } 1528 } 1529 1530 void Debugger::FlushProcessOutput(Process &process, bool flush_stdout, 1531 bool flush_stderr) { 1532 const auto &flush = [&](Stream &stream, 1533 size_t (Process::*get)(char *, size_t, Status &)) { 1534 Status error; 1535 size_t len; 1536 char buffer[1024]; 1537 while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0) 1538 stream.Write(buffer, len); 1539 stream.Flush(); 1540 }; 1541 1542 std::lock_guard<std::mutex> guard(m_output_flush_mutex); 1543 if (flush_stdout) 1544 flush(*GetAsyncOutputStream(), &Process::GetSTDOUT); 1545 if (flush_stderr) 1546 flush(*GetAsyncErrorStream(), &Process::GetSTDERR); 1547 } 1548 1549 // This function handles events that were broadcast by the process. 1550 void Debugger::HandleProcessEvent(const EventSP &event_sp) { 1551 using namespace lldb; 1552 const uint32_t event_type = event_sp->GetType(); 1553 ProcessSP process_sp = 1554 (event_type == Process::eBroadcastBitStructuredData) 1555 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get()) 1556 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get()); 1557 1558 StreamSP output_stream_sp = GetAsyncOutputStream(); 1559 StreamSP error_stream_sp = GetAsyncErrorStream(); 1560 const bool gui_enabled = IsForwardingEvents(); 1561 1562 if (!gui_enabled) { 1563 bool pop_process_io_handler = false; 1564 assert(process_sp); 1565 1566 bool state_is_stopped = false; 1567 const bool got_state_changed = 1568 (event_type & Process::eBroadcastBitStateChanged) != 0; 1569 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0; 1570 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0; 1571 const bool got_structured_data = 1572 (event_type & Process::eBroadcastBitStructuredData) != 0; 1573 1574 if (got_state_changed) { 1575 StateType event_state = 1576 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 1577 state_is_stopped = StateIsStoppedState(event_state, false); 1578 } 1579 1580 // Display running state changes first before any STDIO 1581 if (got_state_changed && !state_is_stopped) { 1582 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(), 1583 pop_process_io_handler); 1584 } 1585 1586 // Now display STDOUT and STDERR 1587 FlushProcessOutput(*process_sp, got_stdout || got_state_changed, 1588 got_stderr || got_state_changed); 1589 1590 // Give structured data events an opportunity to display. 1591 if (got_structured_data) { 1592 StructuredDataPluginSP plugin_sp = 1593 EventDataStructuredData::GetPluginFromEvent(event_sp.get()); 1594 if (plugin_sp) { 1595 auto structured_data_sp = 1596 EventDataStructuredData::GetObjectFromEvent(event_sp.get()); 1597 if (output_stream_sp) { 1598 StreamString content_stream; 1599 Status error = 1600 plugin_sp->GetDescription(structured_data_sp, content_stream); 1601 if (error.Success()) { 1602 if (!content_stream.GetString().empty()) { 1603 // Add newline. 1604 content_stream.PutChar('\n'); 1605 content_stream.Flush(); 1606 1607 // Print it. 1608 output_stream_sp->PutCString(content_stream.GetString()); 1609 } 1610 } else { 1611 error_stream_sp->Format("Failed to print structured " 1612 "data with plugin {0}: {1}", 1613 plugin_sp->GetPluginName(), error); 1614 } 1615 } 1616 } 1617 } 1618 1619 // Now display any stopped state changes after any STDIO 1620 if (got_state_changed && state_is_stopped) { 1621 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(), 1622 pop_process_io_handler); 1623 } 1624 1625 output_stream_sp->Flush(); 1626 error_stream_sp->Flush(); 1627 1628 if (pop_process_io_handler) 1629 process_sp->PopProcessIOHandler(); 1630 } 1631 } 1632 1633 void Debugger::HandleThreadEvent(const EventSP &event_sp) { 1634 // At present the only thread event we handle is the Frame Changed event, and 1635 // all we do for that is just reprint the thread status for that thread. 1636 using namespace lldb; 1637 const uint32_t event_type = event_sp->GetType(); 1638 const bool stop_format = true; 1639 if (event_type == Thread::eBroadcastBitStackChanged || 1640 event_type == Thread::eBroadcastBitThreadSelected) { 1641 ThreadSP thread_sp( 1642 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get())); 1643 if (thread_sp) { 1644 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format); 1645 } 1646 } 1647 } 1648 1649 bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; } 1650 1651 void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) { 1652 m_forward_listener_sp = listener_sp; 1653 } 1654 1655 void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) { 1656 m_forward_listener_sp.reset(); 1657 } 1658 1659 lldb::thread_result_t Debugger::DefaultEventHandler() { 1660 ListenerSP listener_sp(GetListener()); 1661 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass()); 1662 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass()); 1663 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass()); 1664 BroadcastEventSpec target_event_spec(broadcaster_class_target, 1665 Target::eBroadcastBitBreakpointChanged); 1666 1667 BroadcastEventSpec process_event_spec( 1668 broadcaster_class_process, 1669 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT | 1670 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData); 1671 1672 BroadcastEventSpec thread_event_spec(broadcaster_class_thread, 1673 Thread::eBroadcastBitStackChanged | 1674 Thread::eBroadcastBitThreadSelected); 1675 1676 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp, 1677 target_event_spec); 1678 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp, 1679 process_event_spec); 1680 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp, 1681 thread_event_spec); 1682 listener_sp->StartListeningForEvents( 1683 m_command_interpreter_up.get(), 1684 CommandInterpreter::eBroadcastBitQuitCommandReceived | 1685 CommandInterpreter::eBroadcastBitAsynchronousOutputData | 1686 CommandInterpreter::eBroadcastBitAsynchronousErrorData); 1687 1688 listener_sp->StartListeningForEvents( 1689 &m_broadcaster, 1690 eBroadcastBitProgress | eBroadcastBitWarning | eBroadcastBitError); 1691 1692 // Let the thread that spawned us know that we have started up and that we 1693 // are now listening to all required events so no events get missed 1694 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening); 1695 1696 bool done = false; 1697 while (!done) { 1698 EventSP event_sp; 1699 if (listener_sp->GetEvent(event_sp, llvm::None)) { 1700 if (event_sp) { 1701 Broadcaster *broadcaster = event_sp->GetBroadcaster(); 1702 if (broadcaster) { 1703 uint32_t event_type = event_sp->GetType(); 1704 ConstString broadcaster_class(broadcaster->GetBroadcasterClass()); 1705 if (broadcaster_class == broadcaster_class_process) { 1706 HandleProcessEvent(event_sp); 1707 } else if (broadcaster_class == broadcaster_class_target) { 1708 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent( 1709 event_sp.get())) { 1710 HandleBreakpointEvent(event_sp); 1711 } 1712 } else if (broadcaster_class == broadcaster_class_thread) { 1713 HandleThreadEvent(event_sp); 1714 } else if (broadcaster == m_command_interpreter_up.get()) { 1715 if (event_type & 1716 CommandInterpreter::eBroadcastBitQuitCommandReceived) { 1717 done = true; 1718 } else if (event_type & 1719 CommandInterpreter::eBroadcastBitAsynchronousErrorData) { 1720 const char *data = static_cast<const char *>( 1721 EventDataBytes::GetBytesFromEvent(event_sp.get())); 1722 if (data && data[0]) { 1723 StreamSP error_sp(GetAsyncErrorStream()); 1724 if (error_sp) { 1725 error_sp->PutCString(data); 1726 error_sp->Flush(); 1727 } 1728 } 1729 } else if (event_type & CommandInterpreter:: 1730 eBroadcastBitAsynchronousOutputData) { 1731 const char *data = static_cast<const char *>( 1732 EventDataBytes::GetBytesFromEvent(event_sp.get())); 1733 if (data && data[0]) { 1734 StreamSP output_sp(GetAsyncOutputStream()); 1735 if (output_sp) { 1736 output_sp->PutCString(data); 1737 output_sp->Flush(); 1738 } 1739 } 1740 } 1741 } else if (broadcaster == &m_broadcaster) { 1742 if (event_type & Debugger::eBroadcastBitProgress) 1743 HandleProgressEvent(event_sp); 1744 else if (event_type & Debugger::eBroadcastBitWarning) 1745 HandleDiagnosticEvent(event_sp); 1746 else if (event_type & Debugger::eBroadcastBitError) 1747 HandleDiagnosticEvent(event_sp); 1748 } 1749 } 1750 1751 if (m_forward_listener_sp) 1752 m_forward_listener_sp->AddEvent(event_sp); 1753 } 1754 } 1755 } 1756 return {}; 1757 } 1758 1759 bool Debugger::StartEventHandlerThread() { 1760 if (!m_event_handler_thread.IsJoinable()) { 1761 // We must synchronize with the DefaultEventHandler() thread to ensure it 1762 // is up and running and listening to events before we return from this 1763 // function. We do this by listening to events for the 1764 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster 1765 ConstString full_name("lldb.debugger.event-handler"); 1766 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString())); 1767 listener_sp->StartListeningForEvents(&m_sync_broadcaster, 1768 eBroadcastBitEventThreadIsListening); 1769 1770 llvm::StringRef thread_name = 1771 full_name.GetLength() < llvm::get_max_thread_name_length() 1772 ? full_name.GetStringRef() 1773 : "dbg.evt-handler"; 1774 1775 // Use larger 8MB stack for this thread 1776 llvm::Expected<HostThread> event_handler_thread = 1777 ThreadLauncher::LaunchThread( 1778 thread_name, [this] { return DefaultEventHandler(); }, 1779 g_debugger_event_thread_stack_bytes); 1780 1781 if (event_handler_thread) { 1782 m_event_handler_thread = *event_handler_thread; 1783 } else { 1784 LLDB_LOG(GetLog(LLDBLog::Host), "failed to launch host thread: {}", 1785 llvm::toString(event_handler_thread.takeError())); 1786 } 1787 1788 // Make sure DefaultEventHandler() is running and listening to events 1789 // before we return from this function. We are only listening for events of 1790 // type eBroadcastBitEventThreadIsListening so we don't need to check the 1791 // event, we just need to wait an infinite amount of time for it (nullptr 1792 // timeout as the first parameter) 1793 lldb::EventSP event_sp; 1794 listener_sp->GetEvent(event_sp, llvm::None); 1795 } 1796 return m_event_handler_thread.IsJoinable(); 1797 } 1798 1799 void Debugger::StopEventHandlerThread() { 1800 if (m_event_handler_thread.IsJoinable()) { 1801 GetCommandInterpreter().BroadcastEvent( 1802 CommandInterpreter::eBroadcastBitQuitCommandReceived); 1803 m_event_handler_thread.Join(nullptr); 1804 } 1805 } 1806 1807 lldb::thread_result_t Debugger::IOHandlerThread() { 1808 RunIOHandlers(); 1809 StopEventHandlerThread(); 1810 return {}; 1811 } 1812 1813 void Debugger::HandleProgressEvent(const lldb::EventSP &event_sp) { 1814 auto *data = ProgressEventData::GetEventDataFromEvent(event_sp.get()); 1815 if (!data) 1816 return; 1817 1818 // Do some bookkeeping for the current event, regardless of whether we're 1819 // going to show the progress. 1820 const uint64_t id = data->GetID(); 1821 if (m_current_event_id) { 1822 if (id != *m_current_event_id) 1823 return; 1824 if (data->GetCompleted()) 1825 m_current_event_id.reset(); 1826 } else { 1827 m_current_event_id = id; 1828 } 1829 1830 // Decide whether we actually are going to show the progress. This decision 1831 // can change between iterations so check it inside the loop. 1832 if (!GetShowProgress()) 1833 return; 1834 1835 // Determine whether the current output file is an interactive terminal with 1836 // color support. We assume that if we support ANSI escape codes we support 1837 // vt100 escape codes. 1838 File &file = GetOutputFile(); 1839 if (!file.GetIsInteractive() || !file.GetIsTerminalWithColors()) 1840 return; 1841 1842 StreamSP output = GetAsyncOutputStream(); 1843 1844 // Print over previous line, if any. 1845 output->Printf("\r"); 1846 1847 if (data->GetCompleted()) { 1848 // Clear the current line. 1849 output->Printf("\x1B[2K"); 1850 output->Flush(); 1851 return; 1852 } 1853 1854 const bool use_color = GetUseColor(); 1855 llvm::StringRef ansi_prefix = GetShowProgressAnsiPrefix(); 1856 if (!ansi_prefix.empty()) 1857 output->Printf( 1858 "%s", ansi::FormatAnsiTerminalCodes(ansi_prefix, use_color).c_str()); 1859 1860 // Print the progress message. 1861 std::string message = data->GetMessage(); 1862 if (data->GetTotal() != UINT64_MAX) { 1863 output->Printf("[%" PRIu64 "/%" PRIu64 "] %s...", data->GetCompleted(), 1864 data->GetTotal(), message.c_str()); 1865 } else { 1866 output->Printf("%s...", message.c_str()); 1867 } 1868 1869 llvm::StringRef ansi_suffix = GetShowProgressAnsiSuffix(); 1870 if (!ansi_suffix.empty()) 1871 output->Printf( 1872 "%s", ansi::FormatAnsiTerminalCodes(ansi_suffix, use_color).c_str()); 1873 1874 // Clear until the end of the line. 1875 output->Printf("\x1B[K\r"); 1876 1877 // Flush the output. 1878 output->Flush(); 1879 } 1880 1881 void Debugger::HandleDiagnosticEvent(const lldb::EventSP &event_sp) { 1882 auto *data = DiagnosticEventData::GetEventDataFromEvent(event_sp.get()); 1883 if (!data) 1884 return; 1885 1886 StreamSP stream = GetAsyncErrorStream(); 1887 data->Dump(stream.get()); 1888 } 1889 1890 bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); } 1891 1892 bool Debugger::StartIOHandlerThread() { 1893 if (!m_io_handler_thread.IsJoinable()) { 1894 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread( 1895 "lldb.debugger.io-handler", [this] { return IOHandlerThread(); }, 1896 8 * 1024 * 1024); // Use larger 8MB stack for this thread 1897 if (io_handler_thread) { 1898 m_io_handler_thread = *io_handler_thread; 1899 } else { 1900 LLDB_LOG(GetLog(LLDBLog::Host), "failed to launch host thread: {}", 1901 llvm::toString(io_handler_thread.takeError())); 1902 } 1903 } 1904 return m_io_handler_thread.IsJoinable(); 1905 } 1906 1907 void Debugger::StopIOHandlerThread() { 1908 if (m_io_handler_thread.IsJoinable()) { 1909 GetInputFile().Close(); 1910 m_io_handler_thread.Join(nullptr); 1911 } 1912 } 1913 1914 void Debugger::JoinIOHandlerThread() { 1915 if (HasIOHandlerThread()) { 1916 thread_result_t result; 1917 m_io_handler_thread.Join(&result); 1918 m_io_handler_thread = LLDB_INVALID_HOST_THREAD; 1919 } 1920 } 1921 1922 Target &Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) { 1923 if (!prefer_dummy) { 1924 if (TargetSP target = m_target_list.GetSelectedTarget()) 1925 return *target; 1926 } 1927 return GetDummyTarget(); 1928 } 1929 1930 Status Debugger::RunREPL(LanguageType language, const char *repl_options) { 1931 Status err; 1932 FileSpec repl_executable; 1933 1934 if (language == eLanguageTypeUnknown) 1935 language = GetREPLLanguage(); 1936 1937 if (language == eLanguageTypeUnknown) { 1938 LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs(); 1939 1940 if (auto single_lang = repl_languages.GetSingularLanguage()) { 1941 language = *single_lang; 1942 } else if (repl_languages.Empty()) { 1943 err.SetErrorString( 1944 "LLDB isn't configured with REPL support for any languages."); 1945 return err; 1946 } else { 1947 err.SetErrorString( 1948 "Multiple possible REPL languages. Please specify a language."); 1949 return err; 1950 } 1951 } 1952 1953 Target *const target = 1954 nullptr; // passing in an empty target means the REPL must create one 1955 1956 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options)); 1957 1958 if (!err.Success()) { 1959 return err; 1960 } 1961 1962 if (!repl_sp) { 1963 err.SetErrorStringWithFormat("couldn't find a REPL for %s", 1964 Language::GetNameForLanguageType(language)); 1965 return err; 1966 } 1967 1968 repl_sp->SetCompilerOptions(repl_options); 1969 repl_sp->RunLoop(); 1970 1971 return err; 1972 } 1973