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