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