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