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