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