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