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