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/FormatEntity.h" 13 #include "lldb/Core/Mangled.h" 14 #include "lldb/Core/ModuleList.h" 15 #include "lldb/Core/PluginManager.h" 16 #include "lldb/Core/StreamAsynchronousIO.h" 17 #include "lldb/Core/StreamFile.h" 18 #include "lldb/DataFormatters/DataVisualization.h" 19 #include "lldb/Expression/REPL.h" 20 #include "lldb/Host/File.h" 21 #include "lldb/Host/FileSystem.h" 22 #include "lldb/Host/HostInfo.h" 23 #include "lldb/Host/Terminal.h" 24 #include "lldb/Host/ThreadLauncher.h" 25 #include "lldb/Interpreter/CommandInterpreter.h" 26 #include "lldb/Interpreter/CommandReturnObject.h" 27 #include "lldb/Interpreter/OptionValue.h" 28 #include "lldb/Interpreter/OptionValueProperties.h" 29 #include "lldb/Interpreter/OptionValueSInt64.h" 30 #include "lldb/Interpreter/OptionValueString.h" 31 #include "lldb/Interpreter/Property.h" 32 #include "lldb/Interpreter/ScriptInterpreter.h" 33 #include "lldb/Symbol/Function.h" 34 #include "lldb/Symbol/Symbol.h" 35 #include "lldb/Symbol/SymbolContext.h" 36 #include "lldb/Target/Language.h" 37 #include "lldb/Target/Process.h" 38 #include "lldb/Target/StructuredDataPlugin.h" 39 #include "lldb/Target/Target.h" 40 #include "lldb/Target/TargetList.h" 41 #include "lldb/Target/Thread.h" 42 #include "lldb/Target/ThreadList.h" 43 #include "lldb/Utility/AnsiTerminal.h" 44 #include "lldb/Utility/Event.h" 45 #include "lldb/Utility/Listener.h" 46 #include "lldb/Utility/Log.h" 47 #include "lldb/Utility/Reproducer.h" 48 #include "lldb/Utility/ReproducerProvider.h" 49 #include "lldb/Utility/State.h" 50 #include "lldb/Utility/Stream.h" 51 #include "lldb/Utility/StreamCallback.h" 52 #include "lldb/Utility/StreamString.h" 53 54 #if defined(_WIN32) 55 #include "lldb/Host/windows/PosixApi.h" 56 #include "lldb/Host/windows/windows.h" 57 #endif 58 59 #include "llvm/ADT/None.h" 60 #include "llvm/ADT/STLExtras.h" 61 #include "llvm/ADT/StringRef.h" 62 #include "llvm/ADT/iterator.h" 63 #include "llvm/Support/DynamicLibrary.h" 64 #include "llvm/Support/FileSystem.h" 65 #include "llvm/Support/Process.h" 66 #include "llvm/Support/Threading.h" 67 #include "llvm/Support/raw_ostream.h" 68 69 #include <cstdio> 70 #include <cstdlib> 71 #include <cstring> 72 #include <list> 73 #include <memory> 74 #include <mutex> 75 #include <set> 76 #include <string> 77 #include <system_error> 78 79 // Includes for pipe() 80 #if defined(_WIN32) 81 #include <fcntl.h> 82 #include <io.h> 83 #else 84 #include <unistd.h> 85 #endif 86 87 namespace lldb_private { 88 class Address; 89 } 90 91 using namespace lldb; 92 using namespace lldb_private; 93 94 static lldb::user_id_t g_unique_id = 1; 95 static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024; 96 97 #pragma mark Static Functions 98 99 typedef std::vector<DebuggerSP> DebuggerList; 100 static std::recursive_mutex *g_debugger_list_mutex_ptr = 101 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain 102 static DebuggerList *g_debugger_list_ptr = 103 nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain 104 105 static constexpr OptionEnumValueElement g_show_disassembly_enum_values[] = { 106 { 107 Debugger::eStopDisassemblyTypeNever, 108 "never", 109 "Never show disassembly when displaying a stop context.", 110 }, 111 { 112 Debugger::eStopDisassemblyTypeNoDebugInfo, 113 "no-debuginfo", 114 "Show disassembly when there is no debug information.", 115 }, 116 { 117 Debugger::eStopDisassemblyTypeNoSource, 118 "no-source", 119 "Show disassembly when there is no source information, or the source " 120 "file " 121 "is missing when displaying a stop context.", 122 }, 123 { 124 Debugger::eStopDisassemblyTypeAlways, 125 "always", 126 "Always show disassembly when displaying a stop context.", 127 }, 128 }; 129 130 static constexpr OptionEnumValueElement g_language_enumerators[] = { 131 { 132 eScriptLanguageNone, 133 "none", 134 "Disable scripting languages.", 135 }, 136 { 137 eScriptLanguagePython, 138 "python", 139 "Select python as the default scripting language.", 140 }, 141 { 142 eScriptLanguageDefault, 143 "default", 144 "Select the lldb default as the default scripting language.", 145 }, 146 }; 147 148 static constexpr OptionEnumValueElement s_stop_show_column_values[] = { 149 { 150 eStopShowColumnAnsiOrCaret, 151 "ansi-or-caret", 152 "Highlight the stop column with ANSI terminal codes when color/ANSI " 153 "mode is enabled; otherwise, fall back to using a text-only caret (^) " 154 "as if \"caret-only\" mode was selected.", 155 }, 156 { 157 eStopShowColumnAnsi, 158 "ansi", 159 "Highlight the stop column with ANSI terminal codes when running LLDB " 160 "with color/ANSI enabled.", 161 }, 162 { 163 eStopShowColumnCaret, 164 "caret", 165 "Highlight the stop column with a caret character (^) underneath the " 166 "stop column. This method introduces a new line in source listings " 167 "that display thread stop locations.", 168 }, 169 { 170 eStopShowColumnNone, 171 "none", 172 "Do not highlight the stop column.", 173 }, 174 }; 175 176 #define LLDB_PROPERTIES_debugger 177 #include "CoreProperties.inc" 178 179 enum { 180 #define LLDB_PROPERTIES_debugger 181 #include "CorePropertiesEnum.inc" 182 }; 183 184 LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr; 185 186 Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx, 187 VarSetOperationType op, 188 llvm::StringRef property_path, 189 llvm::StringRef value) { 190 bool is_load_script = 191 (property_path == "target.load-script-from-symbol-file"); 192 // These properties might change how we visualize data. 193 bool invalidate_data_vis = (property_path == "escape-non-printables"); 194 invalidate_data_vis |= 195 (property_path == "target.max-zero-padding-in-float-format"); 196 if (invalidate_data_vis) { 197 DataVisualization::ForceUpdate(); 198 } 199 200 TargetSP target_sp; 201 LoadScriptFromSymFile load_script_old_value; 202 if (is_load_script && exe_ctx->GetTargetSP()) { 203 target_sp = exe_ctx->GetTargetSP(); 204 load_script_old_value = 205 target_sp->TargetProperties::GetLoadScriptFromSymbolFile(); 206 } 207 Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value)); 208 if (error.Success()) { 209 // FIXME it would be nice to have "on-change" callbacks for properties 210 if (property_path == g_debugger_properties[ePropertyPrompt].name) { 211 llvm::StringRef new_prompt = GetPrompt(); 212 std::string str = lldb_private::ansi::FormatAnsiTerminalCodes( 213 new_prompt, GetUseColor()); 214 if (str.length()) 215 new_prompt = str; 216 GetCommandInterpreter().UpdatePrompt(new_prompt); 217 auto bytes = std::make_unique<EventDataBytes>(new_prompt); 218 auto prompt_change_event_sp = std::make_shared<Event>( 219 CommandInterpreter::eBroadcastBitResetPrompt, bytes.release()); 220 GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp); 221 } else if (property_path == g_debugger_properties[ePropertyUseColor].name) { 222 // use-color changed. Ping the prompt so it can reset the ansi terminal 223 // codes. 224 SetPrompt(GetPrompt()); 225 } else if (property_path == g_debugger_properties[ePropertyUseSourceCache].name) { 226 // use-source-cache changed. Wipe out the cache contents if it was disabled. 227 if (!GetUseSourceCache()) { 228 m_source_file_cache.Clear(); 229 } 230 } else if (is_load_script && target_sp && 231 load_script_old_value == eLoadScriptFromSymFileWarn) { 232 if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() == 233 eLoadScriptFromSymFileTrue) { 234 std::list<Status> errors; 235 StreamString feedback_stream; 236 if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) { 237 Stream &s = GetErrorStream(); 238 for (auto error : errors) { 239 s.Printf("%s\n", error.AsCString()); 240 } 241 if (feedback_stream.GetSize()) 242 s.PutCString(feedback_stream.GetString()); 243 } 244 } 245 } 246 } 247 return error; 248 } 249 250 bool Debugger::GetAutoConfirm() const { 251 const uint32_t idx = ePropertyAutoConfirm; 252 return m_collection_sp->GetPropertyAtIndexAsBoolean( 253 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0); 254 } 255 256 const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const { 257 const uint32_t idx = ePropertyDisassemblyFormat; 258 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx); 259 } 260 261 const FormatEntity::Entry *Debugger::GetFrameFormat() const { 262 const uint32_t idx = ePropertyFrameFormat; 263 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx); 264 } 265 266 const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const { 267 const uint32_t idx = ePropertyFrameFormatUnique; 268 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx); 269 } 270 271 uint32_t Debugger::GetStopDisassemblyMaxSize() const { 272 const uint32_t idx = ePropertyStopDisassemblyMaxSize; 273 return m_collection_sp->GetPropertyAtIndexAsUInt64( 274 nullptr, idx, g_debugger_properties[idx].default_uint_value); 275 } 276 277 bool Debugger::GetNotifyVoid() const { 278 const uint32_t idx = ePropertyNotiftVoid; 279 return m_collection_sp->GetPropertyAtIndexAsBoolean( 280 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0); 281 } 282 283 llvm::StringRef Debugger::GetPrompt() const { 284 const uint32_t idx = ePropertyPrompt; 285 return m_collection_sp->GetPropertyAtIndexAsString( 286 nullptr, idx, g_debugger_properties[idx].default_cstr_value); 287 } 288 289 void Debugger::SetPrompt(llvm::StringRef p) { 290 const uint32_t idx = ePropertyPrompt; 291 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p); 292 llvm::StringRef new_prompt = GetPrompt(); 293 std::string str = 294 lldb_private::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor()); 295 if (str.length()) 296 new_prompt = str; 297 GetCommandInterpreter().UpdatePrompt(new_prompt); 298 } 299 300 llvm::StringRef Debugger::GetReproducerPath() const { 301 auto &r = repro::Reproducer::Instance(); 302 return r.GetReproducerPath().GetCString(); 303 } 304 305 const FormatEntity::Entry *Debugger::GetThreadFormat() const { 306 const uint32_t idx = ePropertyThreadFormat; 307 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx); 308 } 309 310 const FormatEntity::Entry *Debugger::GetThreadStopFormat() const { 311 const uint32_t idx = ePropertyThreadStopFormat; 312 return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx); 313 } 314 315 lldb::ScriptLanguage Debugger::GetScriptLanguage() const { 316 const uint32_t idx = ePropertyScriptLanguage; 317 return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration( 318 nullptr, idx, g_debugger_properties[idx].default_uint_value); 319 } 320 321 bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) { 322 const uint32_t idx = ePropertyScriptLanguage; 323 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, 324 script_lang); 325 } 326 327 uint32_t Debugger::GetTerminalWidth() const { 328 const uint32_t idx = ePropertyTerminalWidth; 329 return m_collection_sp->GetPropertyAtIndexAsSInt64( 330 nullptr, idx, g_debugger_properties[idx].default_uint_value); 331 } 332 333 bool Debugger::SetTerminalWidth(uint32_t term_width) { 334 if (auto handler_sp = m_io_handler_stack.Top()) 335 handler_sp->TerminalSizeChanged(); 336 337 const uint32_t idx = ePropertyTerminalWidth; 338 return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width); 339 } 340 341 bool Debugger::GetUseExternalEditor() const { 342 const uint32_t idx = ePropertyUseExternalEditor; 343 return m_collection_sp->GetPropertyAtIndexAsBoolean( 344 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0); 345 } 346 347 bool Debugger::SetUseExternalEditor(bool b) { 348 const uint32_t idx = ePropertyUseExternalEditor; 349 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 350 } 351 352 bool Debugger::GetUseColor() const { 353 const uint32_t idx = ePropertyUseColor; 354 return m_collection_sp->GetPropertyAtIndexAsBoolean( 355 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0); 356 } 357 358 bool Debugger::SetUseColor(bool b) { 359 const uint32_t idx = ePropertyUseColor; 360 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 361 SetPrompt(GetPrompt()); 362 return ret; 363 } 364 365 bool Debugger::GetUseAutosuggestion() const { 366 const uint32_t idx = ePropertyShowAutosuggestion; 367 return m_collection_sp->GetPropertyAtIndexAsBoolean( 368 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0); 369 } 370 371 bool Debugger::GetUseSourceCache() const { 372 const uint32_t idx = ePropertyUseSourceCache; 373 return m_collection_sp->GetPropertyAtIndexAsBoolean( 374 nullptr, idx, g_debugger_properties[idx].default_uint_value != 0); 375 } 376 377 bool Debugger::SetUseSourceCache(bool b) { 378 const uint32_t idx = ePropertyUseSourceCache; 379 bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 380 if (!ret) { 381 m_source_file_cache.Clear(); 382 } 383 return ret; 384 } 385 bool Debugger::GetHighlightSource() const { 386 const uint32_t idx = ePropertyHighlightSource; 387 return m_collection_sp->GetPropertyAtIndexAsBoolean( 388 nullptr, idx, g_debugger_properties[idx].default_uint_value); 389 } 390 391 StopShowColumn Debugger::GetStopShowColumn() const { 392 const uint32_t idx = ePropertyStopShowColumn; 393 return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration( 394 nullptr, idx, g_debugger_properties[idx].default_uint_value); 395 } 396 397 llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const { 398 const uint32_t idx = ePropertyStopShowColumnAnsiPrefix; 399 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, ""); 400 } 401 402 llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const { 403 const uint32_t idx = ePropertyStopShowColumnAnsiSuffix; 404 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, ""); 405 } 406 407 llvm::StringRef Debugger::GetStopShowLineMarkerAnsiPrefix() const { 408 const uint32_t idx = ePropertyStopShowLineMarkerAnsiPrefix; 409 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, ""); 410 } 411 412 llvm::StringRef Debugger::GetStopShowLineMarkerAnsiSuffix() const { 413 const uint32_t idx = ePropertyStopShowLineMarkerAnsiSuffix; 414 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, ""); 415 } 416 417 uint32_t Debugger::GetStopSourceLineCount(bool before) const { 418 const uint32_t idx = 419 before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter; 420 return m_collection_sp->GetPropertyAtIndexAsSInt64( 421 nullptr, idx, g_debugger_properties[idx].default_uint_value); 422 } 423 424 Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const { 425 const uint32_t idx = ePropertyStopDisassemblyDisplay; 426 return (Debugger::StopDisassemblyType) 427 m_collection_sp->GetPropertyAtIndexAsEnumeration( 428 nullptr, idx, g_debugger_properties[idx].default_uint_value); 429 } 430 431 uint32_t Debugger::GetDisassemblyLineCount() const { 432 const uint32_t idx = ePropertyStopDisassemblyCount; 433 return m_collection_sp->GetPropertyAtIndexAsSInt64( 434 nullptr, idx, g_debugger_properties[idx].default_uint_value); 435 } 436 437 bool Debugger::GetAutoOneLineSummaries() const { 438 const uint32_t idx = ePropertyAutoOneLineSummaries; 439 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true); 440 } 441 442 bool Debugger::GetEscapeNonPrintables() const { 443 const uint32_t idx = ePropertyEscapeNonPrintables; 444 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true); 445 } 446 447 bool Debugger::GetAutoIndent() const { 448 const uint32_t idx = ePropertyAutoIndent; 449 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true); 450 } 451 452 bool Debugger::SetAutoIndent(bool b) { 453 const uint32_t idx = ePropertyAutoIndent; 454 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 455 } 456 457 bool Debugger::GetPrintDecls() const { 458 const uint32_t idx = ePropertyPrintDecls; 459 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true); 460 } 461 462 bool Debugger::SetPrintDecls(bool b) { 463 const uint32_t idx = ePropertyPrintDecls; 464 return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b); 465 } 466 467 uint32_t Debugger::GetTabSize() const { 468 const uint32_t idx = ePropertyTabSize; 469 return m_collection_sp->GetPropertyAtIndexAsUInt64( 470 nullptr, idx, g_debugger_properties[idx].default_uint_value); 471 } 472 473 bool Debugger::SetTabSize(uint32_t tab_size) { 474 const uint32_t idx = ePropertyTabSize; 475 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size); 476 } 477 478 #pragma mark Debugger 479 480 // const DebuggerPropertiesSP & 481 // Debugger::GetSettings() const 482 //{ 483 // return m_properties_sp; 484 //} 485 // 486 487 void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) { 488 assert(g_debugger_list_ptr == nullptr && 489 "Debugger::Initialize called more than once!"); 490 g_debugger_list_mutex_ptr = new std::recursive_mutex(); 491 g_debugger_list_ptr = new DebuggerList(); 492 g_load_plugin_callback = load_plugin_callback; 493 } 494 495 void Debugger::Terminate() { 496 assert(g_debugger_list_ptr && 497 "Debugger::Terminate called without a matching Debugger::Initialize!"); 498 499 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 500 // Clear our global list of debugger objects 501 { 502 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 503 for (const auto &debugger : *g_debugger_list_ptr) 504 debugger->Clear(); 505 g_debugger_list_ptr->clear(); 506 } 507 } 508 } 509 510 void Debugger::SettingsInitialize() { Target::SettingsInitialize(); } 511 512 void Debugger::SettingsTerminate() { Target::SettingsTerminate(); } 513 514 bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) { 515 if (g_load_plugin_callback) { 516 llvm::sys::DynamicLibrary dynlib = 517 g_load_plugin_callback(shared_from_this(), spec, error); 518 if (dynlib.isValid()) { 519 m_loaded_plugins.push_back(dynlib); 520 return true; 521 } 522 } else { 523 // The g_load_plugin_callback is registered in SBDebugger::Initialize() and 524 // if the public API layer isn't available (code is linking against all of 525 // the internal LLDB static libraries), then we can't load plugins 526 error.SetErrorString("Public API layer is not available"); 527 } 528 return false; 529 } 530 531 static FileSystem::EnumerateDirectoryResult 532 LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft, 533 llvm::StringRef path) { 534 Status error; 535 536 static ConstString g_dylibext(".dylib"); 537 static ConstString g_solibext(".so"); 538 539 if (!baton) 540 return FileSystem::eEnumerateDirectoryResultQuit; 541 542 Debugger *debugger = (Debugger *)baton; 543 544 namespace fs = llvm::sys::fs; 545 // If we have a regular file, a symbolic link or unknown file type, try and 546 // process the file. We must handle unknown as sometimes the directory 547 // enumeration might be enumerating a file system that doesn't have correct 548 // file type information. 549 if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file || 550 ft == fs::file_type::type_unknown) { 551 FileSpec plugin_file_spec(path); 552 FileSystem::Instance().Resolve(plugin_file_spec); 553 554 if (plugin_file_spec.GetFileNameExtension() != g_dylibext && 555 plugin_file_spec.GetFileNameExtension() != g_solibext) { 556 return FileSystem::eEnumerateDirectoryResultNext; 557 } 558 559 Status plugin_load_error; 560 debugger->LoadPlugin(plugin_file_spec, plugin_load_error); 561 562 return FileSystem::eEnumerateDirectoryResultNext; 563 } else if (ft == fs::file_type::directory_file || 564 ft == fs::file_type::symlink_file || 565 ft == fs::file_type::type_unknown) { 566 // Try and recurse into anything that a directory or symbolic link. We must 567 // also do this for unknown as sometimes the directory enumeration might be 568 // enumerating a file system that doesn't have correct file type 569 // information. 570 return FileSystem::eEnumerateDirectoryResultEnter; 571 } 572 573 return FileSystem::eEnumerateDirectoryResultNext; 574 } 575 576 void Debugger::InstanceInitialize() { 577 const bool find_directories = true; 578 const bool find_files = true; 579 const bool find_other = true; 580 char dir_path[PATH_MAX]; 581 if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) { 582 if (FileSystem::Instance().Exists(dir_spec) && 583 dir_spec.GetPath(dir_path, sizeof(dir_path))) { 584 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories, 585 find_files, find_other, 586 LoadPluginCallback, this); 587 } 588 } 589 590 if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) { 591 if (FileSystem::Instance().Exists(dir_spec) && 592 dir_spec.GetPath(dir_path, sizeof(dir_path))) { 593 FileSystem::Instance().EnumerateDirectory(dir_path, find_directories, 594 find_files, find_other, 595 LoadPluginCallback, this); 596 } 597 } 598 599 PluginManager::DebuggerInitialize(*this); 600 } 601 602 DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback, 603 void *baton) { 604 DebuggerSP debugger_sp(new Debugger(log_callback, baton)); 605 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 606 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 607 g_debugger_list_ptr->push_back(debugger_sp); 608 } 609 debugger_sp->InstanceInitialize(); 610 return debugger_sp; 611 } 612 613 void Debugger::Destroy(DebuggerSP &debugger_sp) { 614 if (!debugger_sp) 615 return; 616 617 CommandInterpreter &cmd_interpreter = debugger_sp->GetCommandInterpreter(); 618 619 if (cmd_interpreter.GetSaveSessionOnQuit()) { 620 CommandReturnObject result(debugger_sp->GetUseColor()); 621 cmd_interpreter.SaveTranscript(result); 622 if (result.Succeeded()) 623 debugger_sp->GetOutputStream() << result.GetOutputData() << '\n'; 624 else 625 debugger_sp->GetErrorStream() << result.GetErrorData() << '\n'; 626 } 627 628 debugger_sp->Clear(); 629 630 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 631 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 632 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 633 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) { 634 if ((*pos).get() == debugger_sp.get()) { 635 g_debugger_list_ptr->erase(pos); 636 return; 637 } 638 } 639 } 640 } 641 642 DebuggerSP Debugger::FindDebuggerWithInstanceName(ConstString instance_name) { 643 DebuggerSP debugger_sp; 644 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 645 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 646 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 647 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) { 648 if ((*pos)->m_instance_name == instance_name) { 649 debugger_sp = *pos; 650 break; 651 } 652 } 653 } 654 return debugger_sp; 655 } 656 657 TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) { 658 TargetSP target_sp; 659 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 660 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 661 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 662 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) { 663 target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid); 664 if (target_sp) 665 break; 666 } 667 } 668 return target_sp; 669 } 670 671 TargetSP Debugger::FindTargetWithProcess(Process *process) { 672 TargetSP target_sp; 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 target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process); 678 if (target_sp) 679 break; 680 } 681 } 682 return target_sp; 683 } 684 685 ConstString Debugger::GetStaticBroadcasterClass() { 686 static ConstString class_name("lldb.debugger"); 687 return class_name; 688 } 689 690 Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton) 691 : UserID(g_unique_id++), 692 Properties(std::make_shared<OptionValueProperties>()), 693 m_input_file_sp(std::make_shared<NativeFile>(stdin, false)), 694 m_output_stream_sp(std::make_shared<StreamFile>(stdout, false)), 695 m_error_stream_sp(std::make_shared<StreamFile>(stderr, false)), 696 m_input_recorder(nullptr), 697 m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()), 698 m_terminal_state(), m_target_list(*this), m_platform_list(), 699 m_listener_sp(Listener::MakeListener("lldb.Debugger")), 700 m_source_manager_up(), m_source_file_cache(), 701 m_command_interpreter_up( 702 std::make_unique<CommandInterpreter>(*this, false)), 703 m_io_handler_stack(), m_instance_name(), m_loaded_plugins(), 704 m_event_handler_thread(), m_io_handler_thread(), 705 m_sync_broadcaster(nullptr, "lldb.debugger.sync"), 706 m_broadcaster(m_broadcaster_manager_sp, 707 GetStaticBroadcasterClass().AsCString()), 708 m_forward_listener_sp(), m_clear_once() { 709 m_instance_name.SetString(llvm::formatv("debugger_{0}", GetID()).str()); 710 if (log_callback) 711 m_log_callback_stream_sp = 712 std::make_shared<StreamCallback>(log_callback, baton); 713 m_command_interpreter_up->Initialize(); 714 // Always add our default platform to the platform list 715 PlatformSP default_platform_sp(Platform::GetHostPlatform()); 716 assert(default_platform_sp); 717 m_platform_list.Append(default_platform_sp, true); 718 719 // Create the dummy target. 720 { 721 ArchSpec arch(Target::GetDefaultArchitecture()); 722 if (!arch.IsValid()) 723 arch = HostInfo::GetArchitecture(); 724 assert(arch.IsValid() && "No valid default or host archspec"); 725 const bool is_dummy_target = true; 726 m_dummy_target_sp.reset( 727 new Target(*this, arch, default_platform_sp, is_dummy_target)); 728 } 729 assert(m_dummy_target_sp.get() && "Couldn't construct dummy target?"); 730 731 m_collection_sp->Initialize(g_debugger_properties); 732 m_collection_sp->AppendProperty( 733 ConstString("target"), 734 ConstString("Settings specify to debugging targets."), true, 735 Target::GetGlobalProperties().GetValueProperties()); 736 m_collection_sp->AppendProperty( 737 ConstString("platform"), ConstString("Platform settings."), true, 738 Platform::GetGlobalPlatformProperties().GetValueProperties()); 739 m_collection_sp->AppendProperty( 740 ConstString("symbols"), ConstString("Symbol lookup and cache settings."), 741 true, ModuleList::GetGlobalModuleListProperties().GetValueProperties()); 742 if (m_command_interpreter_up) { 743 m_collection_sp->AppendProperty( 744 ConstString("interpreter"), 745 ConstString("Settings specify to the debugger's command interpreter."), 746 true, m_command_interpreter_up->GetValueProperties()); 747 } 748 OptionValueSInt64 *term_width = 749 m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64( 750 nullptr, ePropertyTerminalWidth); 751 term_width->SetMinimumValue(10); 752 term_width->SetMaximumValue(1024); 753 754 // Turn off use-color if this is a dumb terminal. 755 const char *term = getenv("TERM"); 756 if (term && !strcmp(term, "dumb")) 757 SetUseColor(false); 758 // Turn off use-color if we don't write to a terminal with color support. 759 if (!GetOutputFile().GetIsTerminalWithColors()) 760 SetUseColor(false); 761 762 #if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING) 763 // Enabling use of ANSI color codes because LLDB is using them to highlight 764 // text. 765 llvm::sys::Process::UseANSIEscapeCodes(true); 766 #endif 767 } 768 769 Debugger::~Debugger() { Clear(); } 770 771 void Debugger::Clear() { 772 // Make sure we call this function only once. With the C++ global destructor 773 // chain having a list of debuggers and with code that can be running on 774 // other threads, we need to ensure this doesn't happen multiple times. 775 // 776 // The following functions call Debugger::Clear(): 777 // Debugger::~Debugger(); 778 // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp); 779 // static void Debugger::Terminate(); 780 llvm::call_once(m_clear_once, [this]() { 781 ClearIOHandlers(); 782 StopIOHandlerThread(); 783 StopEventHandlerThread(); 784 m_listener_sp->Clear(); 785 for (TargetSP target_sp : m_target_list.Targets()) { 786 if (target_sp) { 787 if (ProcessSP process_sp = target_sp->GetProcessSP()) 788 process_sp->Finalize(); 789 target_sp->Destroy(); 790 } 791 } 792 m_broadcaster_manager_sp->Clear(); 793 794 // Close the input file _before_ we close the input read communications 795 // class as it does NOT own the input file, our m_input_file does. 796 m_terminal_state.Clear(); 797 GetInputFile().Close(); 798 799 m_command_interpreter_up->Clear(); 800 }); 801 } 802 803 bool Debugger::GetCloseInputOnEOF() const { 804 // return m_input_comm.GetCloseOnEOF(); 805 return false; 806 } 807 808 void Debugger::SetCloseInputOnEOF(bool b) { 809 // m_input_comm.SetCloseOnEOF(b); 810 } 811 812 bool Debugger::GetAsyncExecution() { 813 return !m_command_interpreter_up->GetSynchronous(); 814 } 815 816 void Debugger::SetAsyncExecution(bool async_execution) { 817 m_command_interpreter_up->SetSynchronous(!async_execution); 818 } 819 820 repro::DataRecorder *Debugger::GetInputRecorder() { return m_input_recorder; } 821 822 static inline int OpenPipe(int fds[2], std::size_t size) { 823 #ifdef _WIN32 824 return _pipe(fds, size, O_BINARY); 825 #else 826 (void)size; 827 return pipe(fds); 828 #endif 829 } 830 831 Status Debugger::SetInputString(const char *data) { 832 Status result; 833 enum PIPES { READ, WRITE }; // Indexes for the read and write fds 834 int fds[2] = {-1, -1}; 835 836 if (data == nullptr) { 837 result.SetErrorString("String data is null"); 838 return result; 839 } 840 841 size_t size = strlen(data); 842 if (size == 0) { 843 result.SetErrorString("String data is empty"); 844 return result; 845 } 846 847 if (OpenPipe(fds, size) != 0) { 848 result.SetErrorString( 849 "can't create pipe file descriptors for LLDB commands"); 850 return result; 851 } 852 853 write(fds[WRITE], data, size); 854 // Close the write end of the pipe, so that the command interpreter will exit 855 // when it consumes all the data. 856 llvm::sys::Process::SafelyCloseFileDescriptor(fds[WRITE]); 857 858 // Open the read file descriptor as a FILE * that we can return as an input 859 // handle. 860 FILE *commands_file = fdopen(fds[READ], "rb"); 861 if (commands_file == nullptr) { 862 result.SetErrorStringWithFormat("fdopen(%i, \"rb\") failed (errno = %i) " 863 "when trying to open LLDB commands pipe", 864 fds[READ], errno); 865 llvm::sys::Process::SafelyCloseFileDescriptor(fds[READ]); 866 return result; 867 } 868 869 return SetInputFile( 870 (FileSP)std::make_shared<NativeFile>(commands_file, true)); 871 } 872 873 Status Debugger::SetInputFile(FileSP file_sp) { 874 Status error; 875 repro::DataRecorder *recorder = nullptr; 876 if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) 877 recorder = g->GetOrCreate<repro::CommandProvider>().GetNewRecorder(); 878 879 static std::unique_ptr<repro::MultiLoader<repro::CommandProvider>> loader = 880 repro::MultiLoader<repro::CommandProvider>::Create( 881 repro::Reproducer::Instance().GetLoader()); 882 if (loader) { 883 llvm::Optional<std::string> nextfile = loader->GetNextFile(); 884 FILE *fh = nextfile ? FileSystem::Instance().Fopen(nextfile->c_str(), "r") 885 : nullptr; 886 // FIXME Jonas Devlieghere: shouldn't this error be propagated out to the 887 // reproducer somehow if fh is NULL? 888 if (fh) { 889 file_sp = std::make_shared<NativeFile>(fh, true); 890 } 891 } 892 893 if (!file_sp || !file_sp->IsValid()) { 894 error.SetErrorString("invalid file"); 895 return error; 896 } 897 898 SetInputFile(file_sp, recorder); 899 return error; 900 } 901 902 void Debugger::SetInputFile(FileSP file_sp, repro::DataRecorder *recorder) { 903 assert(file_sp && file_sp->IsValid()); 904 m_input_recorder = recorder; 905 m_input_file_sp = std::move(file_sp); 906 // Save away the terminal state if that is relevant, so that we can restore 907 // it in RestoreInputState. 908 SaveInputTerminalState(); 909 } 910 911 void Debugger::SetOutputFile(FileSP file_sp) { 912 assert(file_sp && file_sp->IsValid()); 913 m_output_stream_sp = std::make_shared<StreamFile>(file_sp); 914 } 915 916 void Debugger::SetErrorFile(FileSP file_sp) { 917 assert(file_sp && file_sp->IsValid()); 918 m_error_stream_sp = std::make_shared<StreamFile>(file_sp); 919 } 920 921 void Debugger::SaveInputTerminalState() { 922 int fd = GetInputFile().GetDescriptor(); 923 if (fd != File::kInvalidDescriptor) 924 m_terminal_state.Save(fd, true); 925 } 926 927 void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); } 928 929 ExecutionContext Debugger::GetSelectedExecutionContext() { 930 bool adopt_selected = true; 931 ExecutionContextRef exe_ctx_ref(GetSelectedTarget().get(), adopt_selected); 932 return ExecutionContext(exe_ctx_ref); 933 } 934 935 void Debugger::DispatchInputInterrupt() { 936 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 937 IOHandlerSP reader_sp(m_io_handler_stack.Top()); 938 if (reader_sp) 939 reader_sp->Interrupt(); 940 } 941 942 void Debugger::DispatchInputEndOfFile() { 943 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 944 IOHandlerSP reader_sp(m_io_handler_stack.Top()); 945 if (reader_sp) 946 reader_sp->GotEOF(); 947 } 948 949 void Debugger::ClearIOHandlers() { 950 // The bottom input reader should be the main debugger input reader. We do 951 // not want to close that one here. 952 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 953 while (m_io_handler_stack.GetSize() > 1) { 954 IOHandlerSP reader_sp(m_io_handler_stack.Top()); 955 if (reader_sp) 956 PopIOHandler(reader_sp); 957 } 958 } 959 960 void Debugger::RunIOHandlers() { 961 IOHandlerSP reader_sp = m_io_handler_stack.Top(); 962 while (true) { 963 if (!reader_sp) 964 break; 965 966 reader_sp->Run(); 967 { 968 std::lock_guard<std::recursive_mutex> guard( 969 m_io_handler_synchronous_mutex); 970 971 // Remove all input readers that are done from the top of the stack 972 while (true) { 973 IOHandlerSP top_reader_sp = m_io_handler_stack.Top(); 974 if (top_reader_sp && top_reader_sp->GetIsDone()) 975 PopIOHandler(top_reader_sp); 976 else 977 break; 978 } 979 reader_sp = m_io_handler_stack.Top(); 980 } 981 } 982 ClearIOHandlers(); 983 } 984 985 void Debugger::RunIOHandlerSync(const IOHandlerSP &reader_sp) { 986 std::lock_guard<std::recursive_mutex> guard(m_io_handler_synchronous_mutex); 987 988 PushIOHandler(reader_sp); 989 IOHandlerSP top_reader_sp = reader_sp; 990 991 while (top_reader_sp) { 992 if (!top_reader_sp) 993 break; 994 995 top_reader_sp->Run(); 996 997 // Don't unwind past the starting point. 998 if (top_reader_sp.get() == reader_sp.get()) { 999 if (PopIOHandler(reader_sp)) 1000 break; 1001 } 1002 1003 // If we pushed new IO handlers, pop them if they're done or restart the 1004 // loop to run them if they're not. 1005 while (true) { 1006 top_reader_sp = m_io_handler_stack.Top(); 1007 if (top_reader_sp && top_reader_sp->GetIsDone()) { 1008 PopIOHandler(top_reader_sp); 1009 // Don't unwind past the starting point. 1010 if (top_reader_sp.get() == reader_sp.get()) 1011 return; 1012 } else { 1013 break; 1014 } 1015 } 1016 } 1017 } 1018 1019 bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) { 1020 return m_io_handler_stack.IsTop(reader_sp); 1021 } 1022 1023 bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type, 1024 IOHandler::Type second_top_type) { 1025 return m_io_handler_stack.CheckTopIOHandlerTypes(top_type, second_top_type); 1026 } 1027 1028 void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) { 1029 lldb_private::StreamFile &stream = 1030 is_stdout ? GetOutputStream() : GetErrorStream(); 1031 m_io_handler_stack.PrintAsync(&stream, s, len); 1032 } 1033 1034 ConstString Debugger::GetTopIOHandlerControlSequence(char ch) { 1035 return m_io_handler_stack.GetTopIOHandlerControlSequence(ch); 1036 } 1037 1038 const char *Debugger::GetIOHandlerCommandPrefix() { 1039 return m_io_handler_stack.GetTopIOHandlerCommandPrefix(); 1040 } 1041 1042 const char *Debugger::GetIOHandlerHelpPrologue() { 1043 return m_io_handler_stack.GetTopIOHandlerHelpPrologue(); 1044 } 1045 1046 bool Debugger::RemoveIOHandler(const IOHandlerSP &reader_sp) { 1047 return PopIOHandler(reader_sp); 1048 } 1049 1050 void Debugger::RunIOHandlerAsync(const IOHandlerSP &reader_sp, 1051 bool cancel_top_handler) { 1052 PushIOHandler(reader_sp, cancel_top_handler); 1053 } 1054 1055 void Debugger::AdoptTopIOHandlerFilesIfInvalid(FileSP &in, StreamFileSP &out, 1056 StreamFileSP &err) { 1057 // Before an IOHandler runs, it must have in/out/err streams. This function 1058 // is called when one ore more of the streams are nullptr. We use the top 1059 // input reader's in/out/err streams, or fall back to the debugger file 1060 // handles, or we fall back onto stdin/stdout/stderr as a last resort. 1061 1062 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 1063 IOHandlerSP top_reader_sp(m_io_handler_stack.Top()); 1064 // If no STDIN has been set, then set it appropriately 1065 if (!in || !in->IsValid()) { 1066 if (top_reader_sp) 1067 in = top_reader_sp->GetInputFileSP(); 1068 else 1069 in = GetInputFileSP(); 1070 // If there is nothing, use stdin 1071 if (!in) 1072 in = std::make_shared<NativeFile>(stdin, false); 1073 } 1074 // If no STDOUT has been set, then set it appropriately 1075 if (!out || !out->GetFile().IsValid()) { 1076 if (top_reader_sp) 1077 out = top_reader_sp->GetOutputStreamFileSP(); 1078 else 1079 out = GetOutputStreamSP(); 1080 // If there is nothing, use stdout 1081 if (!out) 1082 out = std::make_shared<StreamFile>(stdout, false); 1083 } 1084 // If no STDERR has been set, then set it appropriately 1085 if (!err || !err->GetFile().IsValid()) { 1086 if (top_reader_sp) 1087 err = top_reader_sp->GetErrorStreamFileSP(); 1088 else 1089 err = GetErrorStreamSP(); 1090 // If there is nothing, use stderr 1091 if (!err) 1092 err = std::make_shared<StreamFile>(stderr, false); 1093 } 1094 } 1095 1096 void Debugger::PushIOHandler(const IOHandlerSP &reader_sp, 1097 bool cancel_top_handler) { 1098 if (!reader_sp) 1099 return; 1100 1101 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 1102 1103 // Get the current top input reader... 1104 IOHandlerSP top_reader_sp(m_io_handler_stack.Top()); 1105 1106 // Don't push the same IO handler twice... 1107 if (reader_sp == top_reader_sp) 1108 return; 1109 1110 // Push our new input reader 1111 m_io_handler_stack.Push(reader_sp); 1112 reader_sp->Activate(); 1113 1114 // Interrupt the top input reader to it will exit its Run() function and let 1115 // this new input reader take over 1116 if (top_reader_sp) { 1117 top_reader_sp->Deactivate(); 1118 if (cancel_top_handler) 1119 top_reader_sp->Cancel(); 1120 } 1121 } 1122 1123 bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) { 1124 if (!pop_reader_sp) 1125 return false; 1126 1127 std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); 1128 1129 // The reader on the stop of the stack is done, so let the next read on the 1130 // stack refresh its prompt and if there is one... 1131 if (m_io_handler_stack.IsEmpty()) 1132 return false; 1133 1134 IOHandlerSP reader_sp(m_io_handler_stack.Top()); 1135 1136 if (pop_reader_sp != reader_sp) 1137 return false; 1138 1139 reader_sp->Deactivate(); 1140 reader_sp->Cancel(); 1141 m_io_handler_stack.Pop(); 1142 1143 reader_sp = m_io_handler_stack.Top(); 1144 if (reader_sp) 1145 reader_sp->Activate(); 1146 1147 return true; 1148 } 1149 1150 StreamSP Debugger::GetAsyncOutputStream() { 1151 return std::make_shared<StreamAsynchronousIO>(*this, true); 1152 } 1153 1154 StreamSP Debugger::GetAsyncErrorStream() { 1155 return std::make_shared<StreamAsynchronousIO>(*this, false); 1156 } 1157 1158 size_t Debugger::GetNumDebuggers() { 1159 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1160 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1161 return g_debugger_list_ptr->size(); 1162 } 1163 return 0; 1164 } 1165 1166 lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) { 1167 DebuggerSP debugger_sp; 1168 1169 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1170 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1171 if (index < g_debugger_list_ptr->size()) 1172 debugger_sp = g_debugger_list_ptr->at(index); 1173 } 1174 1175 return debugger_sp; 1176 } 1177 1178 DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) { 1179 DebuggerSP debugger_sp; 1180 1181 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1182 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1183 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 1184 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) { 1185 if ((*pos)->GetID() == id) { 1186 debugger_sp = *pos; 1187 break; 1188 } 1189 } 1190 } 1191 return debugger_sp; 1192 } 1193 1194 bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format, 1195 const SymbolContext *sc, 1196 const SymbolContext *prev_sc, 1197 const ExecutionContext *exe_ctx, 1198 const Address *addr, Stream &s) { 1199 FormatEntity::Entry format_entry; 1200 1201 if (format == nullptr) { 1202 if (exe_ctx != nullptr && exe_ctx->HasTargetScope()) 1203 format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat(); 1204 if (format == nullptr) { 1205 FormatEntity::Parse("${addr}: ", format_entry); 1206 format = &format_entry; 1207 } 1208 } 1209 bool function_changed = false; 1210 bool initial_function = false; 1211 if (prev_sc && (prev_sc->function || prev_sc->symbol)) { 1212 if (sc && (sc->function || sc->symbol)) { 1213 if (prev_sc->symbol && sc->symbol) { 1214 if (!sc->symbol->Compare(prev_sc->symbol->GetName(), 1215 prev_sc->symbol->GetType())) { 1216 function_changed = true; 1217 } 1218 } else if (prev_sc->function && sc->function) { 1219 if (prev_sc->function->GetMangled() != sc->function->GetMangled()) { 1220 function_changed = true; 1221 } 1222 } 1223 } 1224 } 1225 // The first context on a list of instructions will have a prev_sc that has 1226 // no Function or Symbol -- if SymbolContext had an IsValid() method, it 1227 // would return false. But we do get a prev_sc pointer. 1228 if ((sc && (sc->function || sc->symbol)) && prev_sc && 1229 (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) { 1230 initial_function = true; 1231 } 1232 return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr, 1233 function_changed, initial_function); 1234 } 1235 1236 void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback, 1237 void *baton) { 1238 // For simplicity's sake, I am not going to deal with how to close down any 1239 // open logging streams, I just redirect everything from here on out to the 1240 // callback. 1241 m_log_callback_stream_sp = 1242 std::make_shared<StreamCallback>(log_callback, baton); 1243 } 1244 1245 ConstString Debugger::ProgressEventData::GetFlavorString() { 1246 static ConstString g_flavor("Debugger::ProgressEventData"); 1247 return g_flavor; 1248 } 1249 1250 ConstString Debugger::ProgressEventData::GetFlavor() const { 1251 return Debugger::ProgressEventData::GetFlavorString(); 1252 } 1253 1254 void Debugger::ProgressEventData::Dump(Stream *s) const { 1255 s->Printf(" id = %" PRIu64 ", message = \"%s\"", m_id, m_message.c_str()); 1256 if (m_completed == 0 || m_completed == m_total) 1257 s->Printf(", type = %s", m_completed == 0 ? "start" : "end"); 1258 else 1259 s->PutCString(", type = update"); 1260 // If m_total is UINT64_MAX, there is no progress to report, just "start" 1261 // and "end". If it isn't we will show the completed and total amounts. 1262 if (m_total != UINT64_MAX) 1263 s->Printf(", progress = %" PRIu64 " of %" PRIu64, m_completed, m_total); 1264 } 1265 1266 const Debugger::ProgressEventData * 1267 Debugger::ProgressEventData::GetEventDataFromEvent(const Event *event_ptr) { 1268 if (event_ptr) 1269 if (const EventData *event_data = event_ptr->GetData()) 1270 if (event_data->GetFlavor() == ProgressEventData::GetFlavorString()) 1271 return static_cast<const ProgressEventData *>(event_ptr->GetData()); 1272 return nullptr; 1273 } 1274 1275 static void PrivateReportProgress(Debugger &debugger, uint64_t progress_id, 1276 const std::string &message, 1277 uint64_t completed, uint64_t total, 1278 bool is_debugger_specific) { 1279 // Only deliver progress events if we have any progress listeners. 1280 const uint32_t event_type = Debugger::eBroadcastBitProgress; 1281 if (!debugger.GetBroadcaster().EventTypeHasListeners(event_type)) 1282 return; 1283 EventSP event_sp(new Event(event_type, new Debugger::ProgressEventData( 1284 progress_id, message, completed, 1285 total, is_debugger_specific))); 1286 debugger.GetBroadcaster().BroadcastEvent(event_sp); 1287 } 1288 1289 void Debugger::ReportProgress(uint64_t progress_id, const std::string &message, 1290 uint64_t completed, uint64_t total, 1291 llvm::Optional<lldb::user_id_t> debugger_id) { 1292 // Check if this progress is for a specific debugger. 1293 if (debugger_id.hasValue()) { 1294 // It is debugger specific, grab it and deliver the event if the debugger 1295 // still exists. 1296 DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id); 1297 if (debugger_sp) 1298 PrivateReportProgress(*debugger_sp, progress_id, message, completed, 1299 total, /*is_debugger_specific*/ true); 1300 return; 1301 } 1302 // The progress event is not debugger specific, iterate over all debuggers 1303 // and deliver a progress event to each one. 1304 if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { 1305 std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); 1306 DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); 1307 for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) 1308 PrivateReportProgress(*(*pos), progress_id, message, completed, total, 1309 /*is_debugger_specific*/ false); 1310 } 1311 } 1312 1313 bool Debugger::EnableLog(llvm::StringRef channel, 1314 llvm::ArrayRef<const char *> categories, 1315 llvm::StringRef log_file, uint32_t log_options, 1316 llvm::raw_ostream &error_stream) { 1317 const bool should_close = true; 1318 const bool unbuffered = true; 1319 1320 std::shared_ptr<llvm::raw_ostream> log_stream_sp; 1321 if (m_log_callback_stream_sp) { 1322 log_stream_sp = m_log_callback_stream_sp; 1323 // For now when using the callback mode you always get thread & timestamp. 1324 log_options |= 1325 LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME; 1326 } else if (log_file.empty()) { 1327 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>( 1328 GetOutputFile().GetDescriptor(), !should_close, unbuffered); 1329 } else { 1330 auto pos = m_log_streams.find(log_file); 1331 if (pos != m_log_streams.end()) 1332 log_stream_sp = pos->second.lock(); 1333 if (!log_stream_sp) { 1334 File::OpenOptions flags = 1335 File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate; 1336 if (log_options & LLDB_LOG_OPTION_APPEND) 1337 flags |= File::eOpenOptionAppend; 1338 else 1339 flags |= File::eOpenOptionTruncate; 1340 llvm::Expected<FileUP> file = FileSystem::Instance().Open( 1341 FileSpec(log_file), flags, lldb::eFilePermissionsFileDefault, false); 1342 if (!file) { 1343 error_stream << "Unable to open log file '" << log_file 1344 << "': " << llvm::toString(file.takeError()) << "\n"; 1345 return false; 1346 } 1347 1348 log_stream_sp = std::make_shared<llvm::raw_fd_ostream>( 1349 (*file)->GetDescriptor(), should_close, unbuffered); 1350 m_log_streams[log_file] = log_stream_sp; 1351 } 1352 } 1353 assert(log_stream_sp); 1354 1355 if (log_options == 0) 1356 log_options = 1357 LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE; 1358 1359 return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories, 1360 error_stream); 1361 } 1362 1363 ScriptInterpreter * 1364 Debugger::GetScriptInterpreter(bool can_create, 1365 llvm::Optional<lldb::ScriptLanguage> language) { 1366 std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex); 1367 lldb::ScriptLanguage script_language = 1368 language ? *language : GetScriptLanguage(); 1369 1370 if (!m_script_interpreters[script_language]) { 1371 if (!can_create) 1372 return nullptr; 1373 m_script_interpreters[script_language] = 1374 PluginManager::GetScriptInterpreterForLanguage(script_language, *this); 1375 } 1376 1377 return m_script_interpreters[script_language].get(); 1378 } 1379 1380 SourceManager &Debugger::GetSourceManager() { 1381 if (!m_source_manager_up) 1382 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this()); 1383 return *m_source_manager_up; 1384 } 1385 1386 // This function handles events that were broadcast by the process. 1387 void Debugger::HandleBreakpointEvent(const EventSP &event_sp) { 1388 using namespace lldb; 1389 const uint32_t event_type = 1390 Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent( 1391 event_sp); 1392 1393 // if (event_type & eBreakpointEventTypeAdded 1394 // || event_type & eBreakpointEventTypeRemoved 1395 // || event_type & eBreakpointEventTypeEnabled 1396 // || event_type & eBreakpointEventTypeDisabled 1397 // || event_type & eBreakpointEventTypeCommandChanged 1398 // || event_type & eBreakpointEventTypeConditionChanged 1399 // || event_type & eBreakpointEventTypeIgnoreChanged 1400 // || event_type & eBreakpointEventTypeLocationsResolved) 1401 // { 1402 // // Don't do anything about these events, since the breakpoint 1403 // commands already echo these actions. 1404 // } 1405 // 1406 if (event_type & eBreakpointEventTypeLocationsAdded) { 1407 uint32_t num_new_locations = 1408 Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent( 1409 event_sp); 1410 if (num_new_locations > 0) { 1411 BreakpointSP breakpoint = 1412 Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp); 1413 StreamSP output_sp(GetAsyncOutputStream()); 1414 if (output_sp) { 1415 output_sp->Printf("%d location%s added to breakpoint %d\n", 1416 num_new_locations, num_new_locations == 1 ? "" : "s", 1417 breakpoint->GetID()); 1418 output_sp->Flush(); 1419 } 1420 } 1421 } 1422 // else if (event_type & eBreakpointEventTypeLocationsRemoved) 1423 // { 1424 // // These locations just get disabled, not sure it is worth spamming 1425 // folks about this on the command line. 1426 // } 1427 // else if (event_type & eBreakpointEventTypeLocationsResolved) 1428 // { 1429 // // This might be an interesting thing to note, but I'm going to 1430 // leave it quiet for now, it just looked noisy. 1431 // } 1432 } 1433 1434 void Debugger::FlushProcessOutput(Process &process, bool flush_stdout, 1435 bool flush_stderr) { 1436 const auto &flush = [&](Stream &stream, 1437 size_t (Process::*get)(char *, size_t, Status &)) { 1438 Status error; 1439 size_t len; 1440 char buffer[1024]; 1441 while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0) 1442 stream.Write(buffer, len); 1443 stream.Flush(); 1444 }; 1445 1446 std::lock_guard<std::mutex> guard(m_output_flush_mutex); 1447 if (flush_stdout) 1448 flush(*GetAsyncOutputStream(), &Process::GetSTDOUT); 1449 if (flush_stderr) 1450 flush(*GetAsyncErrorStream(), &Process::GetSTDERR); 1451 } 1452 1453 // This function handles events that were broadcast by the process. 1454 void Debugger::HandleProcessEvent(const EventSP &event_sp) { 1455 using namespace lldb; 1456 const uint32_t event_type = event_sp->GetType(); 1457 ProcessSP process_sp = 1458 (event_type == Process::eBroadcastBitStructuredData) 1459 ? EventDataStructuredData::GetProcessFromEvent(event_sp.get()) 1460 : Process::ProcessEventData::GetProcessFromEvent(event_sp.get()); 1461 1462 StreamSP output_stream_sp = GetAsyncOutputStream(); 1463 StreamSP error_stream_sp = GetAsyncErrorStream(); 1464 const bool gui_enabled = IsForwardingEvents(); 1465 1466 if (!gui_enabled) { 1467 bool pop_process_io_handler = false; 1468 assert(process_sp); 1469 1470 bool state_is_stopped = false; 1471 const bool got_state_changed = 1472 (event_type & Process::eBroadcastBitStateChanged) != 0; 1473 const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0; 1474 const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0; 1475 const bool got_structured_data = 1476 (event_type & Process::eBroadcastBitStructuredData) != 0; 1477 1478 if (got_state_changed) { 1479 StateType event_state = 1480 Process::ProcessEventData::GetStateFromEvent(event_sp.get()); 1481 state_is_stopped = StateIsStoppedState(event_state, false); 1482 } 1483 1484 // Display running state changes first before any STDIO 1485 if (got_state_changed && !state_is_stopped) { 1486 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(), 1487 pop_process_io_handler); 1488 } 1489 1490 // Now display STDOUT and STDERR 1491 FlushProcessOutput(*process_sp, got_stdout || got_state_changed, 1492 got_stderr || got_state_changed); 1493 1494 // Give structured data events an opportunity to display. 1495 if (got_structured_data) { 1496 StructuredDataPluginSP plugin_sp = 1497 EventDataStructuredData::GetPluginFromEvent(event_sp.get()); 1498 if (plugin_sp) { 1499 auto structured_data_sp = 1500 EventDataStructuredData::GetObjectFromEvent(event_sp.get()); 1501 if (output_stream_sp) { 1502 StreamString content_stream; 1503 Status error = 1504 plugin_sp->GetDescription(structured_data_sp, content_stream); 1505 if (error.Success()) { 1506 if (!content_stream.GetString().empty()) { 1507 // Add newline. 1508 content_stream.PutChar('\n'); 1509 content_stream.Flush(); 1510 1511 // Print it. 1512 output_stream_sp->PutCString(content_stream.GetString()); 1513 } 1514 } else { 1515 error_stream_sp->Format("Failed to print structured " 1516 "data with plugin {0}: {1}", 1517 plugin_sp->GetPluginName(), error); 1518 } 1519 } 1520 } 1521 } 1522 1523 // Now display any stopped state changes after any STDIO 1524 if (got_state_changed && state_is_stopped) { 1525 Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(), 1526 pop_process_io_handler); 1527 } 1528 1529 output_stream_sp->Flush(); 1530 error_stream_sp->Flush(); 1531 1532 if (pop_process_io_handler) 1533 process_sp->PopProcessIOHandler(); 1534 } 1535 } 1536 1537 void Debugger::HandleThreadEvent(const EventSP &event_sp) { 1538 // At present the only thread event we handle is the Frame Changed event, and 1539 // all we do for that is just reprint the thread status for that thread. 1540 using namespace lldb; 1541 const uint32_t event_type = event_sp->GetType(); 1542 const bool stop_format = true; 1543 if (event_type == Thread::eBroadcastBitStackChanged || 1544 event_type == Thread::eBroadcastBitThreadSelected) { 1545 ThreadSP thread_sp( 1546 Thread::ThreadEventData::GetThreadFromEvent(event_sp.get())); 1547 if (thread_sp) { 1548 thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format); 1549 } 1550 } 1551 } 1552 1553 bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; } 1554 1555 void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) { 1556 m_forward_listener_sp = listener_sp; 1557 } 1558 1559 void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) { 1560 m_forward_listener_sp.reset(); 1561 } 1562 1563 void Debugger::DefaultEventHandler() { 1564 ListenerSP listener_sp(GetListener()); 1565 ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass()); 1566 ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass()); 1567 ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass()); 1568 BroadcastEventSpec target_event_spec(broadcaster_class_target, 1569 Target::eBroadcastBitBreakpointChanged); 1570 1571 BroadcastEventSpec process_event_spec( 1572 broadcaster_class_process, 1573 Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT | 1574 Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData); 1575 1576 BroadcastEventSpec thread_event_spec(broadcaster_class_thread, 1577 Thread::eBroadcastBitStackChanged | 1578 Thread::eBroadcastBitThreadSelected); 1579 1580 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp, 1581 target_event_spec); 1582 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp, 1583 process_event_spec); 1584 listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp, 1585 thread_event_spec); 1586 listener_sp->StartListeningForEvents( 1587 m_command_interpreter_up.get(), 1588 CommandInterpreter::eBroadcastBitQuitCommandReceived | 1589 CommandInterpreter::eBroadcastBitAsynchronousOutputData | 1590 CommandInterpreter::eBroadcastBitAsynchronousErrorData); 1591 1592 // Let the thread that spawned us know that we have started up and that we 1593 // are now listening to all required events so no events get missed 1594 m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening); 1595 1596 bool done = false; 1597 while (!done) { 1598 EventSP event_sp; 1599 if (listener_sp->GetEvent(event_sp, llvm::None)) { 1600 if (event_sp) { 1601 Broadcaster *broadcaster = event_sp->GetBroadcaster(); 1602 if (broadcaster) { 1603 uint32_t event_type = event_sp->GetType(); 1604 ConstString broadcaster_class(broadcaster->GetBroadcasterClass()); 1605 if (broadcaster_class == broadcaster_class_process) { 1606 HandleProcessEvent(event_sp); 1607 } else if (broadcaster_class == broadcaster_class_target) { 1608 if (Breakpoint::BreakpointEventData::GetEventDataFromEvent( 1609 event_sp.get())) { 1610 HandleBreakpointEvent(event_sp); 1611 } 1612 } else if (broadcaster_class == broadcaster_class_thread) { 1613 HandleThreadEvent(event_sp); 1614 } else if (broadcaster == m_command_interpreter_up.get()) { 1615 if (event_type & 1616 CommandInterpreter::eBroadcastBitQuitCommandReceived) { 1617 done = true; 1618 } else if (event_type & 1619 CommandInterpreter::eBroadcastBitAsynchronousErrorData) { 1620 const char *data = static_cast<const char *>( 1621 EventDataBytes::GetBytesFromEvent(event_sp.get())); 1622 if (data && data[0]) { 1623 StreamSP error_sp(GetAsyncErrorStream()); 1624 if (error_sp) { 1625 error_sp->PutCString(data); 1626 error_sp->Flush(); 1627 } 1628 } 1629 } else if (event_type & CommandInterpreter:: 1630 eBroadcastBitAsynchronousOutputData) { 1631 const char *data = static_cast<const char *>( 1632 EventDataBytes::GetBytesFromEvent(event_sp.get())); 1633 if (data && data[0]) { 1634 StreamSP output_sp(GetAsyncOutputStream()); 1635 if (output_sp) { 1636 output_sp->PutCString(data); 1637 output_sp->Flush(); 1638 } 1639 } 1640 } 1641 } 1642 } 1643 1644 if (m_forward_listener_sp) 1645 m_forward_listener_sp->AddEvent(event_sp); 1646 } 1647 } 1648 } 1649 } 1650 1651 lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) { 1652 ((Debugger *)arg)->DefaultEventHandler(); 1653 return {}; 1654 } 1655 1656 bool Debugger::StartEventHandlerThread() { 1657 if (!m_event_handler_thread.IsJoinable()) { 1658 // We must synchronize with the DefaultEventHandler() thread to ensure it 1659 // is up and running and listening to events before we return from this 1660 // function. We do this by listening to events for the 1661 // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster 1662 ConstString full_name("lldb.debugger.event-handler"); 1663 ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString())); 1664 listener_sp->StartListeningForEvents(&m_sync_broadcaster, 1665 eBroadcastBitEventThreadIsListening); 1666 1667 llvm::StringRef thread_name = 1668 full_name.GetLength() < llvm::get_max_thread_name_length() 1669 ? full_name.GetStringRef() 1670 : "dbg.evt-handler"; 1671 1672 // Use larger 8MB stack for this thread 1673 llvm::Expected<HostThread> event_handler_thread = 1674 ThreadLauncher::LaunchThread(thread_name, EventHandlerThread, this, 1675 g_debugger_event_thread_stack_bytes); 1676 1677 if (event_handler_thread) { 1678 m_event_handler_thread = *event_handler_thread; 1679 } else { 1680 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), 1681 "failed to launch host thread: {}", 1682 llvm::toString(event_handler_thread.takeError())); 1683 } 1684 1685 // Make sure DefaultEventHandler() is running and listening to events 1686 // before we return from this function. We are only listening for events of 1687 // type eBroadcastBitEventThreadIsListening so we don't need to check the 1688 // event, we just need to wait an infinite amount of time for it (nullptr 1689 // timeout as the first parameter) 1690 lldb::EventSP event_sp; 1691 listener_sp->GetEvent(event_sp, llvm::None); 1692 } 1693 return m_event_handler_thread.IsJoinable(); 1694 } 1695 1696 void Debugger::StopEventHandlerThread() { 1697 if (m_event_handler_thread.IsJoinable()) { 1698 GetCommandInterpreter().BroadcastEvent( 1699 CommandInterpreter::eBroadcastBitQuitCommandReceived); 1700 m_event_handler_thread.Join(nullptr); 1701 } 1702 } 1703 1704 lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) { 1705 Debugger *debugger = (Debugger *)arg; 1706 debugger->RunIOHandlers(); 1707 debugger->StopEventHandlerThread(); 1708 return {}; 1709 } 1710 1711 bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); } 1712 1713 bool Debugger::StartIOHandlerThread() { 1714 if (!m_io_handler_thread.IsJoinable()) { 1715 llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread( 1716 "lldb.debugger.io-handler", IOHandlerThread, this, 1717 8 * 1024 * 1024); // Use larger 8MB stack for this thread 1718 if (io_handler_thread) { 1719 m_io_handler_thread = *io_handler_thread; 1720 } else { 1721 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), 1722 "failed to launch host thread: {}", 1723 llvm::toString(io_handler_thread.takeError())); 1724 } 1725 } 1726 return m_io_handler_thread.IsJoinable(); 1727 } 1728 1729 void Debugger::StopIOHandlerThread() { 1730 if (m_io_handler_thread.IsJoinable()) { 1731 GetInputFile().Close(); 1732 m_io_handler_thread.Join(nullptr); 1733 } 1734 } 1735 1736 void Debugger::JoinIOHandlerThread() { 1737 if (HasIOHandlerThread()) { 1738 thread_result_t result; 1739 m_io_handler_thread.Join(&result); 1740 m_io_handler_thread = LLDB_INVALID_HOST_THREAD; 1741 } 1742 } 1743 1744 Target &Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) { 1745 if (!prefer_dummy) { 1746 if (TargetSP target = m_target_list.GetSelectedTarget()) 1747 return *target; 1748 } 1749 return GetDummyTarget(); 1750 } 1751 1752 Status Debugger::RunREPL(LanguageType language, const char *repl_options) { 1753 Status err; 1754 FileSpec repl_executable; 1755 1756 if (language == eLanguageTypeUnknown) { 1757 LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs(); 1758 1759 if (auto single_lang = repl_languages.GetSingularLanguage()) { 1760 language = *single_lang; 1761 } else if (repl_languages.Empty()) { 1762 err.SetErrorStringWithFormat( 1763 "LLDB isn't configured with REPL support for any languages."); 1764 return err; 1765 } else { 1766 err.SetErrorStringWithFormat( 1767 "Multiple possible REPL languages. Please specify a language."); 1768 return err; 1769 } 1770 } 1771 1772 Target *const target = 1773 nullptr; // passing in an empty target means the REPL must create one 1774 1775 REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options)); 1776 1777 if (!err.Success()) { 1778 return err; 1779 } 1780 1781 if (!repl_sp) { 1782 err.SetErrorStringWithFormat("couldn't find a REPL for %s", 1783 Language::GetNameForLanguageType(language)); 1784 return err; 1785 } 1786 1787 repl_sp->SetCompilerOptions(repl_options); 1788 repl_sp->RunLoop(); 1789 1790 return err; 1791 } 1792