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 = 761 std::make_shared<CallbackLogHandler>(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_callback_handler_sp = 1295 std::make_shared<CallbackLogHandler>(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 1415 std::shared_ptr<LogHandler> log_handler_sp; 1416 if (m_callback_handler_sp) { 1417 log_handler_sp = m_callback_handler_sp; 1418 // For now when using the callback mode you always get thread & timestamp. 1419 log_options |= 1420 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME; 1421 } else if (log_file.empty()) { 1422 log_handler_sp = std::make_shared<StreamLogHandler>( 1423 GetOutputFile().GetDescriptor(), !should_close); 1424 } else { 1425 auto pos = m_stream_handlers.find(log_file); 1426 if (pos != m_stream_handlers.end()) 1427 log_handler_sp = pos->second.lock(); 1428 if (!log_handler_sp) { 1429 File::OpenOptions flags = 1430 File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate; 1431 if (log_options & LLDB_LOG_OPTION_APPEND) 1432 flags |= File::eOpenOptionAppend; 1433 else 1434 flags |= File::eOpenOptionTruncate; 1435 llvm::Expected<FileUP> file = FileSystem::Instance().Open( 1436 FileSpec(log_file), flags, lldb::eFilePermissionsFileDefault, false); 1437 if (!file) { 1438 error_stream << "Unable to open log file '" << log_file 1439 << "': " << llvm::toString(file.takeError()) << "\n"; 1440 return false; 1441 } 1442 1443 log_handler_sp = std::make_shared<StreamLogHandler>( 1444 (*file)->GetDescriptor(), should_close); 1445 m_stream_handlers[log_file] = log_handler_sp; 1446 } 1447 } 1448 assert(log_handler_sp); 1449 1450 if (log_options == 0) 1451 log_options = 1452 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE; 1453 1454 return Log::EnableLogChannel(log_handler_sp, log_options, channel, categories, 1455 error_stream); 1456 } 1457 1458 ScriptInterpreter * 1459 Debugger::GetScriptInterpreter(bool can_create, 1460 llvm::Optional<lldb::ScriptLanguage> language) { 1461 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex); 1462 lldb::ScriptLanguage script_language = 1463 language ? *language : GetScriptLanguage(); 1464 1465 if (!m_script_interpreters[script_language]) { 1466 if (!can_create) 1467 return nullptr; 1468 m_script_interpreters[script_language] = 1469 PluginManager::GetScriptInterpreterForLanguage(script_language, *this); 1470 } 1471 1472 return m_script_interpreters[script_language].get(); 1473 } 1474 1475 SourceManager &Debugger::GetSourceManager() { 1476 if (!m_source_manager_up) 1477 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this()); 1478 return *m_source_manager_up; 1479 } 1480 1481 // This function handles events that were broadcast by the process. 1482 void Debugger::HandleBreakpointEvent(const EventSP &event_sp) { 1483 using namespace lldb; 1484 const uint32_t event_type = 1485 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent( 1486 event_sp); 1487 1488 // if (event_type & eBreakpointEventTypeAdded 1489 // || event_type & eBreakpointEventTypeRemoved 1490 // || event_type & eBreakpointEventTypeEnabled 1491 // || event_type & eBreakpointEventTypeDisabled 1492 // || event_type & eBreakpointEventTypeCommandChanged 1493 // || event_type & eBreakpointEventTypeConditionChanged 1494 // || event_type & eBreakpointEventTypeIgnoreChanged 1495 // || event_type & eBreakpointEventTypeLocationsResolved) 1496 // { 1497 // // Don't do anything about these events, since the breakpoint 1498 // commands already echo these actions. 1499 // } 1500 // 1501 if (event_type & eBreakpointEventTypeLocationsAdded) { 1502 uint32_t num_new_locations = 1503 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent( 1504 event_sp); 1505 if (num_new_locations > 0) { 1506 BreakpointSP breakpoint = 1507 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp); 1508 StreamSP output_sp(GetAsyncOutputStream()); 1509 if (output_sp) { 1510 output_sp->Printf("%d location%s added to breakpoint %d\n", 1511 num_new_locations, num_new_locations == 1 ? "" : "s", 1512 breakpoint->GetID()); 1513 output_sp->Flush(); 1514 } 1515 } 1516 } 1517 // else if (event_type & eBreakpointEventTypeLocationsRemoved) 1518 // { 1519 // // These locations just get disabled, not sure it is worth spamming 1520 // folks about this on the command line. 1521 // } 1522 // else if (event_type & eBreakpointEventTypeLocationsResolved) 1523 // { 1524 // // This might be an interesting thing to note, but I'm going to 1525 // leave it quiet for now, it just looked noisy. 1526 // } 1527 } 1528 1529 void Debugger::FlushProcessOutput(Process &process, bool flush_stdout, 1530 bool flush_stderr) { 1531 const auto &flush = [&](Stream &stream, 1532 size_t (Process::*get)(char *, size_t, Status &)) { 1533 Status error; 1534 size_t len; 1535 char buffer[1024]; 1536 while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0) 1537 stream.Write(buffer, len); 1538 stream.Flush(); 1539 }; 1540 1541 std::lock_guard<std::mutex> guard(m_output_flush_mutex); 1542 if (flush_stdout) 1543 flush(*GetAsyncOutputStream(), &Process::GetSTDOUT); 1544 if (flush_stderr) 1545 flush(*GetAsyncErrorStream(), &Process::GetSTDERR); 1546 } 1547 1548 // This function handles events that were broadcast by the process. 1549 void Debugger::HandleProcessEvent(const EventSP &event_sp) { 1550 using namespace lldb; 1551 const uint32_t event_type = event_sp->GetType(); 1552 ProcessSP process_sp = 1553 (event_type == Process::eBroadcastBitStructuredData) 1554 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get()) 1555 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get()); 1556 1557 StreamSP output_stream_sp = GetAsyncOutputStream(); 1558 StreamSP error_stream_sp = GetAsyncErrorStream(); 1559 const bool gui_enabled = IsForwardingEvents(); 1560 1561 if (!gui_enabled) { 1562 bool pop_process_io_handler = false; 1563 assert(process_sp); 1564 1565 bool state_is_stopped = false; 1566 const bool got_state_changed = 1567 (event_type & Process::eBroadcastBitStateChanged) != 0; 1568 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0; 1569 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0; 1570 const bool got_structured_data = 1571 (event_type & Process::eBroadcastBitStructuredData) != 0; 1572 1573 if (got_state_changed) { 1574 StateType event_state = 1575 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 1576 state_is_stopped = StateIsStoppedState(event_state, false); 1577 } 1578 1579 // Display running state changes first before any STDIO 1580 if (got_state_changed && !state_is_stopped) { 1581 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(), 1582 pop_process_io_handler); 1583 } 1584 1585 // Now display STDOUT and STDERR 1586 FlushProcessOutput(*process_sp, got_stdout || got_state_changed, 1587 got_stderr || got_state_changed); 1588 1589 // Give structured data events an opportunity to display. 1590 if (got_structured_data) { 1591 StructuredDataPluginSP plugin_sp = 1592 EventDataStructuredData::GetPluginFromEvent(event_sp.get()); 1593 if (plugin_sp) { 1594 auto structured_data_sp = 1595 EventDataStructuredData::GetObjectFromEvent(event_sp.get()); 1596 if (output_stream_sp) { 1597 StreamString content_stream; 1598 Status error = 1599 plugin_sp->GetDescription(structured_data_sp, content_stream); 1600 if (error.Success()) { 1601 if (!content_stream.GetString().empty()) { 1602 // Add newline. 1603 content_stream.PutChar('\n'); 1604 content_stream.Flush(); 1605 1606 // Print it. 1607 output_stream_sp->PutCString(content_stream.GetString()); 1608 } 1609 } else { 1610 error_stream_sp->Format("Failed to print structured " 1611 "data with plugin {0}: {1}", 1612 plugin_sp->GetPluginName(), error); 1613 } 1614 } 1615 } 1616 } 1617 1618 // Now display any stopped state changes after any STDIO 1619 if (got_state_changed && state_is_stopped) { 1620 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(), 1621 pop_process_io_handler); 1622 } 1623 1624 output_stream_sp->Flush(); 1625 error_stream_sp->Flush(); 1626 1627 if (pop_process_io_handler) 1628 process_sp->PopProcessIOHandler(); 1629 } 1630 } 1631 1632 void Debugger::HandleThreadEvent(const EventSP &event_sp) { 1633 // At present the only thread event we handle is the Frame Changed event, and 1634 // all we do for that is just reprint the thread status for that thread. 1635 using namespace lldb; 1636 const uint32_t event_type = event_sp->GetType(); 1637 const bool stop_format = true; 1638 if (event_type == Thread::eBroadcastBitStackChanged || 1639 event_type == Thread::eBroadcastBitThreadSelected) { 1640 ThreadSP thread_sp( 1641 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get())); 1642 if (thread_sp) { 1643 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format); 1644 } 1645 } 1646 } 1647 1648 bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; } 1649 1650 void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) { 1651 m_forward_listener_sp = listener_sp; 1652 } 1653 1654 void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) { 1655 m_forward_listener_sp.reset(); 1656 } 1657 1658 lldb::thread_result_t Debugger::DefaultEventHandler() { 1659 ListenerSP listener_sp(GetListener()); 1660 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass()); 1661 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass()); 1662 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass()); 1663 BroadcastEventSpec target_event_spec(broadcaster_class_target, 1664 Target::eBroadcastBitBreakpointChanged); 1665 1666 BroadcastEventSpec process_event_spec( 1667 broadcaster_class_process, 1668 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT | 1669 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData); 1670 1671 BroadcastEventSpec thread_event_spec(broadcaster_class_thread, 1672 Thread::eBroadcastBitStackChanged | 1673 Thread::eBroadcastBitThreadSelected); 1674 1675 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp, 1676 target_event_spec); 1677 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp, 1678 process_event_spec); 1679 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp, 1680 thread_event_spec); 1681 listener_sp->StartListeningForEvents( 1682 m_command_interpreter_up.get(), 1683 CommandInterpreter::eBroadcastBitQuitCommandReceived | 1684 CommandInterpreter::eBroadcastBitAsynchronousOutputData | 1685 CommandInterpreter::eBroadcastBitAsynchronousErrorData); 1686 1687 listener_sp->StartListeningForEvents( 1688 &m_broadcaster, 1689 eBroadcastBitProgress | eBroadcastBitWarning | eBroadcastBitError); 1690 1691 // Let the thread that spawned us know that we have started up and that we 1692 // are now listening to all required events so no events get missed 1693 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening); 1694 1695 bool done = false; 1696 while (!done) { 1697 EventSP event_sp; 1698 if (listener_sp->GetEvent(event_sp, llvm::None)) { 1699 if (event_sp) { 1700 Broadcaster *broadcaster = event_sp->GetBroadcaster(); 1701 if (broadcaster) { 1702 uint32_t event_type = event_sp->GetType(); 1703 ConstString broadcaster_class(broadcaster->GetBroadcasterClass()); 1704 if (broadcaster_class == broadcaster_class_process) { 1705 HandleProcessEvent(event_sp); 1706 } else if (broadcaster_class == broadcaster_class_target) { 1707 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent( 1708 event_sp.get())) { 1709 HandleBreakpointEvent(event_sp); 1710 } 1711 } else if (broadcaster_class == broadcaster_class_thread) { 1712 HandleThreadEvent(event_sp); 1713 } else if (broadcaster == m_command_interpreter_up.get()) { 1714 if (event_type & 1715 CommandInterpreter::eBroadcastBitQuitCommandReceived) { 1716 done = true; 1717 } else if (event_type & 1718 CommandInterpreter::eBroadcastBitAsynchronousErrorData) { 1719 const char *data = static_cast<const char *>( 1720 EventDataBytes::GetBytesFromEvent(event_sp.get())); 1721 if (data && data[0]) { 1722 StreamSP error_sp(GetAsyncErrorStream()); 1723 if (error_sp) { 1724 error_sp->PutCString(data); 1725 error_sp->Flush(); 1726 } 1727 } 1728 } else if (event_type & CommandInterpreter:: 1729 eBroadcastBitAsynchronousOutputData) { 1730 const char *data = static_cast<const char *>( 1731 EventDataBytes::GetBytesFromEvent(event_sp.get())); 1732 if (data && data[0]) { 1733 StreamSP output_sp(GetAsyncOutputStream()); 1734 if (output_sp) { 1735 output_sp->PutCString(data); 1736 output_sp->Flush(); 1737 } 1738 } 1739 } 1740 } else if (broadcaster == &m_broadcaster) { 1741 if (event_type & Debugger::eBroadcastBitProgress) 1742 HandleProgressEvent(event_sp); 1743 else if (event_type & Debugger::eBroadcastBitWarning) 1744 HandleDiagnosticEvent(event_sp); 1745 else if (event_type & Debugger::eBroadcastBitError) 1746 HandleDiagnosticEvent(event_sp); 1747 } 1748 } 1749 1750 if (m_forward_listener_sp) 1751 m_forward_listener_sp->AddEvent(event_sp); 1752 } 1753 } 1754 } 1755 return {}; 1756 } 1757 1758 bool Debugger::StartEventHandlerThread() { 1759 if (!m_event_handler_thread.IsJoinable()) { 1760 // We must synchronize with the DefaultEventHandler() thread to ensure it 1761 // is up and running and listening to events before we return from this 1762 // function. We do this by listening to events for the 1763 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster 1764 ConstString full_name("lldb.debugger.event-handler"); 1765 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString())); 1766 listener_sp->StartListeningForEvents(&m_sync_broadcaster, 1767 eBroadcastBitEventThreadIsListening); 1768 1769 llvm::StringRef thread_name = 1770 full_name.GetLength() < llvm::get_max_thread_name_length() 1771 ? full_name.GetStringRef() 1772 : "dbg.evt-handler"; 1773 1774 // Use larger 8MB stack for this thread 1775 llvm::Expected<HostThread> event_handler_thread = 1776 ThreadLauncher::LaunchThread( 1777 thread_name, [this] { return DefaultEventHandler(); }, 1778 g_debugger_event_thread_stack_bytes); 1779 1780 if (event_handler_thread) { 1781 m_event_handler_thread = *event_handler_thread; 1782 } else { 1783 LLDB_LOG(GetLog(LLDBLog::Host), "failed to launch host thread: {}", 1784 llvm::toString(event_handler_thread.takeError())); 1785 } 1786 1787 // Make sure DefaultEventHandler() is running and listening to events 1788 // before we return from this function. We are only listening for events of 1789 // type eBroadcastBitEventThreadIsListening so we don't need to check the 1790 // event, we just need to wait an infinite amount of time for it (nullptr 1791 // timeout as the first parameter) 1792 lldb::EventSP event_sp; 1793 listener_sp->GetEvent(event_sp, llvm::None); 1794 } 1795 return m_event_handler_thread.IsJoinable(); 1796 } 1797 1798 void Debugger::StopEventHandlerThread() { 1799 if (m_event_handler_thread.IsJoinable()) { 1800 GetCommandInterpreter().BroadcastEvent( 1801 CommandInterpreter::eBroadcastBitQuitCommandReceived); 1802 m_event_handler_thread.Join(nullptr); 1803 } 1804 } 1805 1806 lldb::thread_result_t Debugger::IOHandlerThread() { 1807 RunIOHandlers(); 1808 StopEventHandlerThread(); 1809 return {}; 1810 } 1811 1812 void Debugger::HandleProgressEvent(const lldb::EventSP &event_sp) { 1813 auto *data = ProgressEventData::GetEventDataFromEvent(event_sp.get()); 1814 if (!data) 1815 return; 1816 1817 // Do some bookkeeping for the current event, regardless of whether we're 1818 // going to show the progress. 1819 const uint64_t id = data->GetID(); 1820 if (m_current_event_id) { 1821 if (id != *m_current_event_id) 1822 return; 1823 if (data->GetCompleted()) 1824 m_current_event_id.reset(); 1825 } else { 1826 m_current_event_id = id; 1827 } 1828 1829 // Decide whether we actually are going to show the progress. This decision 1830 // can change between iterations so check it inside the loop. 1831 if (!GetShowProgress()) 1832 return; 1833 1834 // Determine whether the current output file is an interactive terminal with 1835 // color support. We assume that if we support ANSI escape codes we support 1836 // vt100 escape codes. 1837 File &file = GetOutputFile(); 1838 if (!file.GetIsInteractive() || !file.GetIsTerminalWithColors()) 1839 return; 1840 1841 StreamSP output = GetAsyncOutputStream(); 1842 1843 // Print over previous line, if any. 1844 output->Printf("\r"); 1845 1846 if (data->GetCompleted()) { 1847 // Clear the current line. 1848 output->Printf("\x1B[2K"); 1849 output->Flush(); 1850 return; 1851 } 1852 1853 // Trim the progress message if it exceeds the window's width and print it. 1854 std::string message = data->GetMessage(); 1855 if (data->IsFinite()) 1856 message = llvm::formatv("[{0}/{1}] {2}", data->GetCompleted(), 1857 data->GetTotal(), message) 1858 .str(); 1859 1860 // Trim the progress message if it exceeds the window's width and print it. 1861 const uint32_t term_width = GetTerminalWidth(); 1862 const uint32_t ellipsis = 3; 1863 if (message.size() + ellipsis >= term_width) 1864 message = message.substr(0, term_width - ellipsis); 1865 1866 const bool use_color = GetUseColor(); 1867 llvm::StringRef ansi_prefix = GetShowProgressAnsiPrefix(); 1868 if (!ansi_prefix.empty()) 1869 output->Printf( 1870 "%s", ansi::FormatAnsiTerminalCodes(ansi_prefix, use_color).c_str()); 1871 1872 output->Printf("%s...", message.c_str()); 1873 1874 llvm::StringRef ansi_suffix = GetShowProgressAnsiSuffix(); 1875 if (!ansi_suffix.empty()) 1876 output->Printf( 1877 "%s", ansi::FormatAnsiTerminalCodes(ansi_suffix, use_color).c_str()); 1878 1879 // Clear until the end of the line. 1880 output->Printf("\x1B[K\r"); 1881 1882 // Flush the output. 1883 output->Flush(); 1884 } 1885 1886 void Debugger::HandleDiagnosticEvent(const lldb::EventSP &event_sp) { 1887 auto *data = DiagnosticEventData::GetEventDataFromEvent(event_sp.get()); 1888 if (!data) 1889 return; 1890 1891 StreamSP stream = GetAsyncErrorStream(); 1892 data->Dump(stream.get()); 1893 } 1894 1895 bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); } 1896 1897 bool Debugger::StartIOHandlerThread() { 1898 if (!m_io_handler_thread.IsJoinable()) { 1899 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread( 1900 "lldb.debugger.io-handler", [this] { return IOHandlerThread(); }, 1901 8 * 1024 * 1024); // Use larger 8MB stack for this thread 1902 if (io_handler_thread) { 1903 m_io_handler_thread = *io_handler_thread; 1904 } else { 1905 LLDB_LOG(GetLog(LLDBLog::Host), "failed to launch host thread: {}", 1906 llvm::toString(io_handler_thread.takeError())); 1907 } 1908 } 1909 return m_io_handler_thread.IsJoinable(); 1910 } 1911 1912 void Debugger::StopIOHandlerThread() { 1913 if (m_io_handler_thread.IsJoinable()) { 1914 GetInputFile().Close(); 1915 m_io_handler_thread.Join(nullptr); 1916 } 1917 } 1918 1919 void Debugger::JoinIOHandlerThread() { 1920 if (HasIOHandlerThread()) { 1921 thread_result_t result; 1922 m_io_handler_thread.Join(&result); 1923 m_io_handler_thread = LLDB_INVALID_HOST_THREAD; 1924 } 1925 } 1926 1927 Target &Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) { 1928 if (!prefer_dummy) { 1929 if (TargetSP target = m_target_list.GetSelectedTarget()) 1930 return *target; 1931 } 1932 return GetDummyTarget(); 1933 } 1934 1935 Status Debugger::RunREPL(LanguageType language, const char *repl_options) { 1936 Status err; 1937 FileSpec repl_executable; 1938 1939 if (language == eLanguageTypeUnknown) 1940 language = GetREPLLanguage(); 1941 1942 if (language == eLanguageTypeUnknown) { 1943 LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs(); 1944 1945 if (auto single_lang = repl_languages.GetSingularLanguage()) { 1946 language = *single_lang; 1947 } else if (repl_languages.Empty()) { 1948 err.SetErrorString( 1949 "LLDB isn't configured with REPL support for any languages."); 1950 return err; 1951 } else { 1952 err.SetErrorString( 1953 "Multiple possible REPL languages. Please specify a language."); 1954 return err; 1955 } 1956 } 1957 1958 Target *const target = 1959 nullptr; // passing in an empty target means the REPL must create one 1960 1961 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options)); 1962 1963 if (!err.Success()) { 1964 return err; 1965 } 1966 1967 if (!repl_sp) { 1968 err.SetErrorStringWithFormat("couldn't find a REPL for %s", 1969 Language::GetNameForLanguageType(language)); 1970 return err; 1971 } 1972 1973 repl_sp->SetCompilerOptions(repl_options); 1974 repl_sp->RunLoop(); 1975 1976 return err; 1977 } 1978 1979 llvm::ThreadPool &Debugger::GetThreadPool() { 1980 // NOTE: intentional leak to avoid issues with C++ destructor chain 1981 static llvm::ThreadPool *g_thread_pool = nullptr; 1982 static llvm::once_flag g_once_flag; 1983 llvm::call_once(g_once_flag, []() { 1984 g_thread_pool = new llvm::ThreadPool(llvm::optimal_concurrency()); 1985 }); 1986 return *g_thread_pool; 1987 } 1988